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): 合入主干并对齐缓存预览的取消与后台校验

Dash4ba3c93031fe
diff --cc apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
index 9f3a6617ec,569dde5e82..3b751d2b49
--- a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
@@@ -81,31 -215,6 +215,63 @@@ it('opens a preview before downloading
await expect(mocks.handle.mock.calls[0][1]({}, args)).resolves.toMatchObject({ ok: true });
expect(read).not.toHaveBeenCalled();
});
+it.each([1, 2])('serves cached HTML while stat is blocked, then refreshes with mtime %s', async (mtimeMs) => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-swr-test-'));
+ let reply!: (value: any) => void;
+ const metadata = { relPath: 'index.html', type: 'file' as const, size: 3, mtimeMs: 1 };
+ const stat = vi.fn(async () => metadata);
+ const read = vi.fn(async () => path.join(dir, 'old.html'));
+ try {
+ await fs.writeFile(path.join(dir, 'old.html'), 'old');
+ await fs.writeFile(path.join(dir, 'new.html'), 'new');
+ registerHtmlPreviewIpc({ stat, read });
+ const open = mocks.handle.mock.calls[0][1];
+ const first = await open({}, args);
+ expect(await (await readResource(first.url, '/index.html')).text()).toContain('old');
+ stat.mockImplementationOnce(() => new Promise(resolve => { reply = resolve; }));
+ const second = await open({}, args);
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
+ expect(read).toHaveBeenCalledOnce();
+ read.mockResolvedValueOnce(path.join(dir, 'new.html'));
+ reply({ ...metadata, mtimeMs });
+ await vi.waitFor(() => expect(read).toHaveBeenCalledTimes(2));
+ const third = await open({}, args);
+ expect(await (await readResource(third.url, '/index.html')).text()).toContain('new');
+ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
+ } finally { await fs.rm(dir, { recursive: true, force: true }); }
+});
++// #6292 + #6288 integration, unit tier: previous cancellation cases only cover
++// uncached preparation. Cancel a cached preview during a stalled background stat;
++// its transport must abort and a later open must be able to revalidate again.
++it('releases a cancelled cached refresh so the next preview can revalidate', async () => {
++ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-refresh-cancel-'));
++ const metadata = { relPath: 'index.html', type: 'file' as const, size: 3, mtimeMs: 1 };
++ const stat = vi.fn(async (_args, _root, _rel, _signal: AbortSignal) => metadata);
++ const read = vi.fn(async () => path.join(dir, 'old.html'));
++ try {
++ await fs.writeFile(path.join(dir, 'old.html'), 'old');
++ registerHtmlPreviewIpc({ stat, read });
++ const open = mocks.handle.mock.calls[0][1];
++ const cancel = mocks.handle.mock.calls[1][1];
++ const first = await open({}, args);
++ expect(await (await readResource(first.url, '/index.html')).text()).toContain('old');
++ let refreshSignal!: AbortSignal;
++ stat.mockImplementationOnce((_args, _root, _rel, signal) => {
++ refreshSignal = signal;
++ return new Promise(() => {});
++ });
++ const sender = Object.assign(new EventEmitter(), { id: 20 });
++ const second = await open({ sender }, { ...args, requestId: 'cached-preview' });
++ expect(await (await readResource(second.url, '/index.html')).text()).toContain('old');
++ await cancel({ sender }, 'cached-preview');
++ expect(refreshSignal.aborted).toBe(true);
++ const callsBeforeReopen = stat.mock.calls.length;
++ const third = await open({}, args);
++ expect(await (await readResource(third.url, '/index.html')).text()).toContain('old');
++ expect(stat.mock.calls.length).toBeGreaterThan(callsBeforeReopen);
++ expect(read).toHaveBeenCalledTimes(2);
++ } finally { await fs.rm(dir, { recursive: true, force: true }); }
++});
it('passes the captured owner guard through reference-free cache ingestion', async () => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-owner-test-'));
try {
diff --cc apps/desktop/src/main/file-browser/html-preview-ipc.ts
index fa50b7089c,bf59810bd6..8a6e5cae78
--- a/apps/desktop/src/main/file-browser/html-preview-ipc.ts
+++ b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
@@@ -19,13 -19,18 +19,20 @@@ import
} from '../device-link/broadcast-tap.js';
import { getDbClient } from '../localDb/client/current.js';
import { throwIpcError } from '../utils/ipcValidate.js';
+import { isSharedTaskPeer } from '@cindy/device-link';
+ import { isIpcError } from '../../shared/ipc-errors.js';
+ import { previewTransportErrorCode, readPreviewMetadata } from './html-preview-read.js';
const log = createLogger('html-preview');
export const HTML_PREVIEW_CHANNEL = 'maker:html-preview:open';
interface RemoteSource {
- stat(args: HtmlPreviewArgs, root: string, rel: string): Promise<Omit<DirEntry, 'name'>>;
+ stat(
+ args: HtmlPreviewArgs,
+ root: string,
+ rel: string,
+ signal?: AbortSignal,
+ ): Promise<Omit<DirEntry, 'name'>>;
+ /** Validate the source even when size/mtime match; they are not a complete version. */
read(args: HtmlPreviewArgs, root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;
}
@@@ -50,12 -70,10 +77,15 @@@ export function registerHtmlPreviewIpc(
try {
previewLocation(args);
const scope = captureDataOwnerBroadcastScope();
+ const ownerKey = scope.ownerScopeKey;
+ const cacheable = !!ownerKey && !(args.origin.kind === 'device' && isSharedTaskPeer(args.origin.deviceId));
+ if (cacheOwner !== ownerKey) { files.clear(); cacheOwner = ownerKey; }
+ const keyOf = (root: string, rel: string) => JSON.stringify([ownerKey, args.origin, args.workdir, root, rel]);
+ const selected = new Map<string, CachedFile>();
- const isCurrent = () => !shuttingDown && isDataOwnerBroadcastScopeCurrent(scope);
+ const isCurrent = () =>
+ !shuttingDown &&
+ !request.controller.signal.aborted &&
+ isDataOwnerBroadcastScopeCurrent(scope);
const db = getDbClient().drizzle;
// Finished snapshots are a bounded cache, not concurrent preparation slots.
// External browsers cannot report tab closure; evict the oldest snapshot so
@@@ -70,19 -89,13 +101,23 @@@
isCurrent,
// Log status only: paths, signed URLs and page contents are not diagnostics.
onResourceError: (status) => log.warn('Preview resource request failed', { status }),
- stat: async (root, rel) => {
+ stat: async (root, rel, signal) => {
- if (args.origin.kind !== 'local')
+ if (args.origin.kind !== 'local') {
+ const key = keyOf(root, rel);
+ const cached = cacheable ? files.get(key) : undefined;
+ const stat = cached && await fs.stat(cached.path).catch(() => null);
+ if (cached && stat?.isFile() && stat.size === cached.metadata.size) {
+ selected.set(key, cached);
+ return cached.metadata;
+ }
+ selected.delete(key);
+ files.delete(key);
- return remote.stat(args, root, rel);
+ return readPreviewMetadata(
+ (attemptSignal) => remote.stat(args, root, rel, attemptSignal),
+ signal ?? request.controller.signal,
+ isCurrent,
+ );
+ }
const real = await fs.realpath(path.join(root, rel));
if (!isPathAllowedAgainst(real, getSensitiveMediaBlocklist()))
throw new Error('BAD_ARGS');
@@@ -109,21 -115,6 +144,25 @@@
materialize: async (source, dest, expectedSize) => {
// The temporary tree is a view of managed media, not another persistent media store.
await copyPreviewFile(source, dest, expectedSize);
+ // Start after copying: replacing the shared cache cannot invalidate this view.
+ for (const [key, cached] of selected) {
+ if (cached.path !== source || refreshing.has(key)) continue;
+ refreshing.add(key);
+ const [, , , root, rel] = JSON.parse(key) as string[];
+ void (async () => {
+ if (!isCurrent()) return;
- const metadata = await remote.stat(args, root, rel);
++ const metadata = await readPreviewMetadata(
++ (signal) => remote.stat(args, root, rel, signal),
++ request.controller.signal,
++ isCurrent,
++ );
+ if (!isCurrent() || metadata.type !== 'file') return;
+ const entry = { ...metadata, name: cached.metadata.name };
- const file = await remote.read(args, root, entry);
++ const file = await remote.read(args, root, entry, request.controller.signal);
+ if (isCurrent()) files.set(key, { metadata: entry, path: file });
+ })().catch(() => { /* Preserve the usable snapshot while offline. */ })
+ .finally(() => refreshing.delete(key));
+ }
const file = await fs.open(dest, 'r');
const probe = Buffer.alloc(8192);
let mime: string | null;