Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 等直传文件复制完成再释放,修复大于 64KB 的网页预览失败 (#5156)
Lizi2d4507f9c3ad
diff --git a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts b/apps/mobile/src/__tests__/mobileHtmlPreview.test.tsindex fa08a09030..73a9bd7e43 100644--- a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts+++ b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({contents: new Map<string, Uint8Array>(),removed: [] as string[],+ released: [] as string[],remote: vi.fn(),start: vi.fn(),stop: vi.fn(),@@ -33,6 +34,13 @@ vi.mock("@/session/remoteAbsFileFetch", () => ({vi.mock("@/device-link/remoteRetry", () => ({withTransientRemoteRetry: (operation: () => unknown) => operation(),}));+// Releasing a direct-transfer result deletes its staged file, as the real registry does.+vi.mock("@/device-link/peerFileRegistry", () => ({+ releasePeerMedia: (uri: string) => {+ mocks.released.push(uri);+ mocks.contents.delete(uri);+ },+}));vi.mock("expo-file-system", () => {class Directory {uri: string;@@ -55,6 +63,13 @@ vi.mock("expo-file-system", () => {async bytes() {return mocks.contents.get(this.uri);}+ // Asynchronous like expo-file-system's File.copy: the source is read after a tick.+ async copy(target: { uri: string }) {+ await new Promise((done) => setTimeout(done, 0));+ const source = mocks.contents.get(this.uri);+ if (!source) throw new Error("ENOENT");+ mocks.contents.set(target.uri, source);+ }write(text: string | Uint8Array) {mocks.contents.set(this.uri,@@ -100,6 +115,12 @@ function setup() {};return { deps, listDir, caps };}+/** Files above the inline limit arrive as a staged local file owned by the peer registry. */+async function stagedDirectTransfer(_deps: unknown, path: string) {+ const url = "file:///peer/" + path.split("/").pop();+ mocks.contents.set(url, bytes);+ return { url, size: bytes.length };+}beforeEach(() => {vi.resetAllMocks();mocks.demand = false;@@ -108,6 +129,7 @@ beforeEach(() => {mocks.resolveRequest.mockResolvedValue(true);mocks.contents.clear();mocks.removed.length = 0;+ mocks.released.length = 0;mocks.start.mockResolvedValue("http://127.0.0.1:43123/__cindy/token");mocks.stop.mockResolvedValue(undefined);mocks.pause.mockResolvedValue(undefined);@@ -181,6 +203,25 @@ describe("mobile HTML preview preparation", () => {expect(mocks.stop).toHaveBeenCalledTimes(1);expect(mocks.contents.size).toBe(0);});+ it("finishes copying direct-transfer files before releasing their staged source", async () => {+ const { deps } = setup();+ mocks.remote.mockImplementation(stagedDirectTransfer);+ const preview = await prepareMobileHtmlPreview(+ "/site/index.html",+ deps,+ new AbortController().signal,+ );+ expect(mocks.start).toHaveBeenCalledOnce();+ expect(mocks.download).not.toHaveBeenCalled();+ expect(mocks.released).toEqual([+ "file:///peer/index.html",+ "file:///peer/second.html",+ ]);+ expect(mocks.contents.size).toBe(2);+ for (const content of mocks.contents.values())+ expect(new TextDecoder().decode(content)).toContain("Content-Security-Policy");+ await preview.close();+ });it("rejects old peers before enumeration or download", async () => {const { deps, caps, listDir } = setup();caps.mockResolvedValue({ ok: true });@@ -291,6 +332,18 @@ describe("on-demand mobile HTML previews", () => {expect(mocks.contents.size).toBe(0);});+ it("serves a direct-transfer resource only after its copy completes", async () => {+ const { deps } = setup();+ mocks.remote.mockImplementation(stagedDirectTransfer);+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);+ request("a", "index.html");+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "a", "0", "text/html", 200));+ expect(mocks.released).toEqual(["file:///peer/index.html"]);+ expect(mocks.contents.size).toBe(1);+ expect(new TextDecoder().decode([...mocks.contents.values()][0])).toContain("Content-Security-Policy");+ await preview.close();+ });+it("reuses a materialized path instead of fetching cache-busted repeats", async () => {const { deps } = setup();const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.tsindex b5e69a70fe..607975e030 100644--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts@@ -6,6 +6,8 @@ import {const io = vi.hoisted(() => ({size: 5,+ copying: new Set<string>(),+ copied: new Set<string>(),download: vi.fn(),remove: vi.fn(),}));@@ -19,8 +21,17 @@ vi.mock('expo-file-system', () => ({},File: class {uri: string;- constructor(parent: { uri: string }, name: string) { this.uri = `${parent.uri}/${name}`; }- get size() { return io.size; }+ constructor(parent: { uri: string } | string, name?: string) {+ this.uri = typeof parent === 'string' ? parent : `${parent.uri}/${name}`;+ }+ // expo-file-system's File.copy is asynchronous; the destination is empty until it settles.+ async copy(target: { uri: string }) {+ io.copying.add(target.uri);+ await new Promise((done) => setTimeout(done, 0));+ io.copying.delete(target.uri);+ io.copied.add(target.uri);+ }+ get size() { return io.copying.has(this.uri) ? 0 : io.size; }async base64() { return 'aGVsbG8='; }delete() { io.remove(this.uri); }static downloadFileAsync = io.download;@@ -29,6 +40,8 @@ vi.mock('expo-file-system', () => ({beforeEach(() => {io.size = 5;+ io.copying.clear();+ io.copied.clear();io.remove.mockClear();io.download.mockReset().mockImplementation(async (_url, target) => target);});@@ -60,6 +73,13 @@ describe('bounded temporary media downloads', () => {expect(io.remove).toHaveBeenCalledOnce();});+ it('waits for a direct-transfer copy before sizing or reading the file', async () => {+ const read = vi.fn(async (file: { uri: string }) => (io.copied.has(file.uri) ? 'copied' : 'missing'));+ expect(await withDownloadedRemoteMediaFile('file:///peer/staged', 'image/png', 8, read)).toBe('copied');+ expect(read).toHaveBeenCalledOnce();+ expect(io.download).not.toHaveBeenCalled();+ });+it('preserves the existing inline-resource download contract', async () => {expect(await downloadRemoteMediaAsDataUri('https://example.com/image', 'image/png', 8)).toBe('data:image/png;base64,aGVsbG8=');diff --git a/apps/mobile/src/session/mobileHtmlPreview.ts b/apps/mobile/src/session/mobileHtmlPreview.tsindex 703c69de33..b1b646a5a3 100644--- a/apps/mobile/src/session/mobileHtmlPreview.ts+++ b/apps/mobile/src/session/mobileHtmlPreview.ts@@ -108,7 +108,8 @@ export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsFdestination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));if (destination.size !== file.size) throw new Error('PREVIEW_CHANGED');} else if (media.url.startsWith('file://')) {- try { new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }+ // File.copy is async; releasing first deletes the staged direct-transfer source mid-copy.+ try { await new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }if (destination.size !== file.size) throw new Error('PREVIEW_CHANGED');} else {let exceeded = false;@@ -202,7 +203,7 @@ async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {destination.create();destination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));} else if (media.url.startsWith('file://')) {- try { new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }+ try { await new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }} else {let exceeded = false;const download = createDownloadResumable(media.url, destination.uri, {}, (progress) => {diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.tsindex 6f2ebd23b1..b4aa704305 100644--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts@@ -20,7 +20,7 @@ const SHARE_TMP_DIR_NAME = "remote-media-share";async function copyRemoteFile(url: string, target: File): Promise<File> {if (url.startsWith("file://")) {- new File(url).copy(target);+ await new File(url).copy(target);return target;}if (url.startsWith("data:")) {