fix(ios): decode imported file URL basenames once (#7263)

Keep file URLs encoded through both Open With entrypoints. In openFile,
reuse the URL basename helper to decode the iOS filename once and use that
same name for the temporary copy. Preserve the original URL for native copying.

This keeps reserved characters and literal percent sequences intact in
originalFilename and prevents URI malformed errors for percent filenames.
Android provider and desktop filename handling are unchanged.

Verified: ten regressions failed before the fix across cold-start intent
parsing, live URL ingress and native file opening. Failures included encoded
# and ? in File.name, literal % throwing URIError, and a second decode changing
the temporary basename. All 180 related tests pass, including import metadata,
PDF title/provenance, conversion and filename checksum cases. TypeScript,
Biome lint, formatting and whitespace checks pass; full suite runs in pre-push.
Not run on iOS: this Linux host has no Xcode, simulator or attached iOS runtime.
Development servers remain stopped after host memory pressure.
Found during review of #7253; tracked in #7257.

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-03 00:09:03 +08:00 • committed by GitHub
parent 0c4b602108
commit ee1a955039
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 90 additions and 4 deletions

View file

@ -180,6 +180,18 @@ describe('parseOpenWithFiles', () => {
expect(result).toEqual(['/path/to/book.epub']);
});
test.each([
'A%23B.epub',
'100%25.epub',
'Report%2520Final.epub',
'%E4%B8%89%E4%BD%93%20book.epub',
])('preserves the raw iOS file URL for %s', async (basename) => {
const url = `file:///path/to/${basename}`;
mockGetCurrent.mockResolvedValue([url]);
const result = await parseOpenWithFiles({ isIOSApp: true } as never);
expect(result).toEqual([url]);
});
test('preserves file:// prefix for iOS', async () => {
const mockAppService = { isIOSApp: true } as MockAppService;
mockGetCurrent.mockResolvedValue(['file:///path/to/book.epub']);

View file

@ -0,0 +1,56 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
const h = vi.hoisted(() => ({
appService: {
isIOSApp: true,
hasWindow: false,
loadSettings: vi.fn(async () => ({ autoImportBooksOnOpen: true })),
},
navigateToLibrary: vi.fn(),
setCheckOpenWithBooks: vi.fn(),
}));
vi.mock('next/navigation', () => ({ useRouter: () => ({}) }));
vi.mock('@tauri-apps/api/window', () => ({
getAllWindows: vi.fn(),
getCurrentWindow: vi.fn(),
}));
vi.mock('@/context/EnvContext', () => ({ useEnv: () => ({ appService: h.appService }) }));
vi.mock('@/services/environment', () => ({ isTauriAppPlatform: () => true }));
vi.mock('@/store/libraryStore', () => ({
useLibraryStore: () => ({ setCheckOpenWithBooks: h.setCheckOpenWithBooks }),
}));
vi.mock('@/utils/nav', () => ({
navigateToLibrary: h.navigateToLibrary,
navigateToReader: vi.fn(),
showLibraryWindow: vi.fn(),
}));
vi.mock('@/utils/md5', () => ({ partialMD5: vi.fn() }));
import { useOpenWithBooks } from '@/hooks/useOpenWithBooks';
import { eventDispatcher } from '@/utils/event';
afterEach(() => {
cleanup();
delete window.OPEN_WITH_FILES;
vi.clearAllMocks();
});
describe('useOpenWithBooks iOS file URL ingress', () => {
test.each([
'A%23B.epub',
'100%25.epub',
'Report%2520Final.epub',
'%E4%B8%89%E4%BD%93%20book.epub',
])('preserves the raw iOS URL for %s', async (basename) => {
const uri = `file:///private/var/Inbox/${basename}`;
renderHook(() => useOpenWithBooks());
act(() => {
eventDispatcher.dispatch('app-incoming-url', { urls: [uri] });
});
await waitFor(() => expect(h.navigateToLibrary).toHaveBeenCalledTimes(1));
expect(window.OPEN_WITH_FILES).toEqual([uri]);
expect(h.setCheckOpenWithBooks).toHaveBeenCalledWith(true);
});
});

View file

@ -123,6 +123,22 @@ describe('NativeAppService.saveFile share gating', () => {
expect(file.name).toBe('Original Manual.pdf');
});
test.each([
['A%23B.epub', 'A#B.epub'],
['100%25.epub', '100%.epub'],
['Report%2520Final.epub', 'Report%20Final.epub'],
['A%3FB.epub', 'A?B.epub'],
['%E4%B8%89%E4%BD%93%20book.epub', '三体 book.epub'],
])('decodes an iOS import basename exactly once: %s', async (encodedName, expected) => {
const service = await loadServiceWithOS('ios');
const uri = `file:///private/var/Inbox/${encodedName}`;
const file = await service.openFile(uri, 'None');
expect(file.name).toBe(expected);
const request = copyURIToPathMock.mock.calls[0]![0] as { uri: string; dst: string };
expect(request.uri).toBe(uri);
expect(request.dst.endsWith(`-${expected}`)).toBe(true);
});
test.each([
['https://example.com/manual.pdf#zoom=1.25', undefined, 'manual.pdf'],
['https://example.com/C%2B%2B.pdf?type=application/pdf', undefined, 'C++.pdf'],

View file

@ -54,7 +54,7 @@ const parseIntentOpenWithFiles = async (appService: AppService | null) => {
.map((url) => {
if (url.startsWith('file://')) {
if (appService?.isIOSApp) {
return decodeURI(url);
return url;
} else {
return decodeURI(url.replace('file://', ''));
}

View file

@ -62,7 +62,7 @@ export function useOpenWithBooks() {
const filePaths: string[] = [];
for (let url of urls) {
if (url.startsWith('file://')) {
url = appService?.isIOSApp ? decodeURI(url) : decodeURI(url.replace('file://', ''));
url = appService?.isIOSApp ? url : decodeURI(url.replace('file://', ''));
}
if (!/^(https?:|data:|blob:|readest:)/i.test(url)) {
filePaths.push(url);

View file

@ -318,7 +318,8 @@ export const nativeFileSystem: FileSystem = {
return await new RemoteFile(path, fname, '', Date.now(), fetcher ?? tauriFetch).open();
}
if (isContentURI(path) || (isFileURI(path) && OS_TYPE === 'ios')) {
const fname = safeDecodePath(await basename(path));
const isIOSFileURI = isFileURI(path) && OS_TYPE === 'ios';
const fname = isIOSFileURI ? getURLFilename(path) : safeDecodePath(await basename(path));
if (path.includes('com.android.externalstorage')) {
// If the URI is from shared internal storage (like /storage/emulated/0),
// we can access it directly using the path — no need to copy.
@ -328,7 +329,8 @@ export const nativeFileSystem: FileSystem = {
// or file:// URIs is security scoped resource in iOS (e.g. from Files app),
// we cannot access the file directly — so we copy it to a temporary cache location.
const prefix = await this.getPrefix('Cache');
const dst = await join(prefix, `${crypto.randomUUID()}-${decodeURIComponent(fname)}`);
const copyName = isIOSFileURI ? fname : decodeURIComponent(fname);
const dst = await join(prefix, `${crypto.randomUUID()}-${copyName}`);
const res = await copyURIToPath({ uri: path, dst });
if (!res.success) {
console.error('Failed to open file:', res);