Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(preview): 不可用的 HTML 缓存回退远端取件

Dashfe12e82c3abc
diff --git a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
index 661a1dbf65..04d5b5a3d6 100644
--- a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
+++ b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
@@ -171,6 +171,60 @@ function previewCache() {
}
describe('persistent HTML preview cache', () => {
+ // Unit regression: old transfer-cache HTML can be invalid UTF-8 even after the
+ // remote document is repaired. Exercise both native preparation entry points.
+ it.each([false, true])('replaces undecodable cached entries and reopens offline (onDemand=%s)', async (demand) => {
+ mocks.demand = demand;
+ const { deps, caps, listDir } = setup();
+ listDir.mockResolvedValue([entry('index.html')]);
+ const { saved } = previewCache();
+ saved.set('index.html', new Uint8Array([0xff]));
+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ expect(saved.get('index.html')).toEqual(bytes);
+ expect([...mocks.contents.values()].some((value) => new TextDecoder().decode(value).endsWith(html))).toBe(true);
+ await preview.close();
+ mocks.remote.mockRejectedValue(new Error('offline'));
+ caps.mockRejectedValue(new Error('offline'));
+ const reopened = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ expect([...mocks.contents.values()].some((value) => new TextDecoder().decode(value).endsWith(html))).toBe(true);
+ await reopened.close();
+ });
+
+ it.each([false, true])('recovers an undecodable cached subpage without blocking the valid entry (onDemand=%s)', async (demand) => {
+ mocks.demand = demand;
+ const { deps } = setup();
+ const { cache, saved } = previewCache();
+ saved.set('index.html', bytes);
+ saved.set('second.html', new Uint8Array([0xff]));
+ cache.manifest.mockResolvedValue([entry('index.html'), entry('second.html')]);
+ const preview = await prepareMobileHtmlPreview('/site/index.html', deps, new AbortController().signal);
+ if (demand) {
+ mocks.listeners.get('resourceRequest')!({ token: '01'.repeat(24), id: 'second', path: 'second.html' });
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith('01'.repeat(24), 'second', expect.any(String), 'text/html', 200));
+ } else {
+ // Legacy servers publish only valid restored files; refresh repairs the next open.
+ expect(mocks.start.mock.calls[0][4].map((item: string[]) => item[0])).toEqual(['index.html']);
+ }
+ await vi.waitFor(() => expect(saved.get('second.html')).toEqual(bytes));
+ await preview.close();
+ });
+
+ it.each([false, true])('does not fetch after cancellation during an invalid cache copy (onDemand=%s)', async (demand) => {
+ mocks.demand = demand;
+ const { deps, caps } = setup();
+ const { cache } = previewCache();
+ const controller = new AbortController();
+ cache.copy.mockImplementation(async (_relative, destination) => {
+ mocks.contents.set(destination.uri, new Uint8Array([0xff]));
+ controller.abort();
+ return 1;
+ });
+ await expect(prepareMobileHtmlPreview('/site/index.html', deps, controller.signal)).rejects.toThrow('PREVIEW_CANCELLED');
+ expect(mocks.remote).not.toHaveBeenCalled();
+ expect(caps).not.toHaveBeenCalled();
+ expect(mocks.contents.size).toBe(0);
+ });
+
// Behavioral timing contract: a cache hit must resolve before an unresolved remote operation.
it.each([false, true])('opens cached content before network checks, including old native mode (onDemand=%s)', async (demand) => {
mocks.demand = demand;
@@ -414,8 +468,7 @@ describe("on-demand mobile HTML previews", () => {
return { url: "data:text/html;base64,", size: bytes.length, inlineBase64: Buffer.from(bytes).toString("base64") };
});
const preparing = prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal, progress);
- await Promise.resolve();
- expect(mocks.remote).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(mocks.remote).toHaveBeenCalledOnce());
expect(mocks.startOnDemand).not.toHaveBeenCalled();
expect(progress).toHaveBeenLastCalledWith(expect.objectContaining({ name: "index.html", loaded: 4, total: bytes.length }));
await vi.advanceTimersByTimeAsync(90_000);
diff --git a/apps/mobile/src/session/mobileHtmlPreview.ts b/apps/mobile/src/session/mobileHtmlPreview.ts
index 09d9f1c96d..420084ac40 100644
--- a/apps/mobile/src/session/mobileHtmlPreview.ts
+++ b/apps/mobile/src/session/mobileHtmlPreview.ts
@@ -268,6 +268,25 @@ async function prepareLegacy(absPath: string, deps: HtmlPreviewDeps, signal: Abo
} catch (error) { await close(); throw error; }
}
+/** Unreadable or undecodable cache copies are misses in both native modes. */
+async function restoreCachedResource(cache: MobileHtmlPreviewCache, relative: string,
+ destination: File, maxBytes?: number) {
+ try {
+ const size = await cache?.copy(relative, destination, maxBytes);
+ if (size != null) {
+ const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ if (mime === 'text/html') {
+ const html = new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes());
+ destination.write(withSnapshotHtmlCsp(html));
+ }
+ return { size, mime };
+ }
+ return null;
+ } catch { /* Old transfer copies may predate HTML validation. Fetch a fresh copy. */ }
+ try { destination.delete(); } catch {}
+ return null;
+}
+
/** Old native binaries can publish only the files restored before starting their server. */
async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: AbortSignal,
cache: NonNullable<MobileHtmlPreviewCache>): Promise<MobileHtmlPreview | null> {
@@ -294,14 +313,13 @@ async function restoreLegacy(absPath: string, deps: HtmlPreviewDeps, signal: Abo
let remaining = HTML_SNAPSHOT_MAX_BYTES;
for (const [index, file] of files.entries()) {
const destination = new File(dir, String(index));
- const size = await cache.copy(file.relPath, destination, remaining);
+ const cached = await restoreCachedResource(cache, file.relPath, destination, remaining);
assertHtmlSnapshotActive(signal);
- if (size === null) {
+ if (!cached) {
if (file.relPath === entry) { await close(); return null; }
continue;
}
- const mime = MIME[file.relPath.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
- if (mime === 'text/html') destination.write(withSnapshotHtmlCsp(new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes())));
+ const { size, mime } = cached;
manifest.push([file.relPath, String(index), mime]);
restored.push({ ...file, size });
remaining -= size;
@@ -337,12 +355,10 @@ async function prepareOnDemand(absPath: string, deps: HtmlPreviewDeps,
const queue = createFileReadQueue();
const loadResource = async (relative: string, filename: string, requestSignal: AbortSignal) => {
const destination = new File(dir, filename);
- const size = await cache?.copy(relative, destination);
+ const cached = await restoreCachedResource(cache, relative, destination);
assertHtmlSnapshotActive(requestSignal);
- if (size != null) {
- const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
- if (mime === 'text/html') destination.write(withSnapshotHtmlCsp(new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes())));
- assertHtmlSnapshotActive(requestSignal);
+ if (cached) {
+ const { size, mime } = cached;
const updatedName = `${filename}-refresh`;
const update = materializeResource(deps, root, relative, dir, updatedName, signal, undefined, cache)
.then(() => {}, () => {}).finally(() => {