Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): reconcile reply attachment sources and guarded paths
ylliuuu66594f54dac51a
diff --git a/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts b/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.tsindex 232f069e04..709c08f8d7 100644--- a/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/taskImageDelivery.test.ts@@ -1,5 +1,6 @@import { createHookMediaStore } from '../hookOutbox';import { prepareChatReplyFiles } from '../../maker-ipc/chatServerReplyFiles';+import { mergeChatReplyAttachments } from '../../maker-ipc/chatServerReplyAttachments';import { prepareChatReplyImages } from '../../maker-ipc/chatServerReplyImages';import { createHookRequestLedger, HOOK_TERMINAL_DELIVERY_TTL_MS } from '../../hook-control/requestLedger';import type { TurnEndPayload } from '@cindy/slack-hook-protocol';@@ -128,6 +129,49 @@ describe('task image delivery', () => {expect(images.text).not.toContain(pdf);});+ it.each(['image-first', 'file-first'])('uploads eleven real images once through both reply passes, in source order (%s)', async order => {+ const pdf = path.join(work, 'report.pdf');+ await fs.writeFile(pdf, '%PDF-1.4');+ const targets = Array.from({ length: 11 }, (_, i) => path.join(work, `chart-${i}.png`));+ for (const [i, target] of targets.entries()) await fs.writeFile(target, Buffer.concat([PNG, Buffer.from([i])]));+ const image = (i: number) => ``;+ const file = (i: number) => `[download](<${targets[i]}>)`;+ // The first alias must retain its position relative to a distinct PDF.+ const body = `${order === 'image-first' ? image(0) : file(0)} [report](<${pdf}>) ${order === 'image-first' ? file(0) : image(0)} `+ + targets.slice(1).map((_, index) => `${image(index + 1)} ${file(index + 1)}`).join(' ');+ const files = await prepareChatReplyFiles(body, 's', () => {});+ const images = await prepareChatReplyImages(files.text, 's', () => {});+ const attachments = mergeChatReplyAttachments(images.attachments, files.attachments);+ expect(attachments).toHaveLength(12);+ expect(attachments.map(a => a.category)).toEqual(['image', 'file', ...Array(10).fill('image')]);+ expect(attachments[0]!.sourcePaths).toContain(await fs.realpath(targets[0]!));+ expect(images.text).not.toContain(work);+ expect((await attachments[1]!.readBytes!()).toString()).toBe('%PDF-1.4');+ });++ it('reconciles different local paths imported as the same image at the first file occurrence', async () => {+ const first = path.join(work, 'first.png'), second = path.join(work, 'second.png');+ await fs.writeFile(first, PNG);+ await fs.writeFile(second, PNG);+ const files = await prepareChatReplyFiles(`[download](<${second}>)  `, 's', () => {});+ const images = await prepareChatReplyImages(files.text, 's', () => {});+ const attachments = mergeChatReplyAttachments(images.attachments, files.attachments);+ expect(attachments).toHaveLength(1);+ expect(attachments[0]).toMatchObject({ category: 'image', sourceOffset: 0 });+ expect(attachments[0]!.sourcePaths).toEqual(expect.arrayContaining([await fs.realpath(first), await fs.realpath(second)]));+ });++ it('retains file read safeguards when a rendered image also has a hard-linked download target', async () => {+ const source = path.join(work, 'linked.png');+ await fs.writeFile(source, PNG);+ await fs.link(source, path.join(state.root, 'outside.png'));+ const files = await prepareChatReplyFiles(` [download](<${source}>)`, 's', () => {});+ const images = await prepareChatReplyImages(files.text, 's', () => {});+ const attachments = mergeChatReplyAttachments(images.attachments, files.attachments);+ expect(attachments.map(a => a.category)).toEqual(['image', 'file']);+ await expect(attachments[1]!.readBytes!()).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });+it.each(['before', 'during'].flatMap((order) =>['publish', 'rollback'].map((result) => [order, result]),))('reconciles a reused reference when cleanup runs %s %s', async (order, result) => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 9d467b83a4..d6c020db92 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -753,6 +753,27 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.dispatch).toHaveBeenCalledOnce();});+ it('deduplicates eleven image/file aliases before counting and keeps the first source position on retry', async () => {+ const images = Array.from({ length: 11 }, (_, i) => ({ ...replyImage, id: `image-${i}`, sourceOffset: 100 + i,+ sourcePaths: [`/task/chart-${i}.png`] }));+ const aliases = images.map((image, i) => ({ ...image, id: `file-${i}`, category: 'file', sourceOffset: i }));+ const pdf = { id: 'pdf', name: 'report.pdf', category: 'file', sourceOffset: 50 };+ replyFiles.prepare.mockResolvedValue({ text: 'Report charts', attachments: [...aliases, pdf] });+ replyImages.mockResolvedValue({ text: 'Delivered', attachments: images });+ fixture.upload.mockRejectedValueOnce(Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: 503 })).mockResolvedValue([]);+ await startFileReply();+ const before = fixture.upload.mock.calls.length;+ await service.settleLaneTurn({ ...terminal, resultText: '[download](chart.png) ' });+ await vi.advanceTimersByTimeAsync(16000);+ const uploads = fixture.upload.mock.calls.slice(before);+ expect(uploads).toHaveLength(2);+ for (const call of uploads) {+ expect(call[2].map(a => a.id)).toEqual([...images.map(a => a.id), 'pdf']);+ expect(call[2].map(a => a.sourceOffset)).toEqual([...aliases.map(a => a.sourceOffset), 50]);+ }+ expect(deps.dispatch).toHaveBeenCalledOnce();+ });+it('delivers ten images and a PDF in one completion across an upload retry', async () => {const images = Array.from({ length: 10 }, (_, i) => ({ ...replyImage, id: `image-${i}` }));const pdf = { id: 'pdf', name: 'report.pdf' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.tsindex 60a93a895b..b44d425bf2 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyFiles.test.ts@@ -67,13 +67,13 @@ describe('group reply file delivery', () => {if (mode === 'shared-reference') expect(result.text).not.toContain(`[image]: <${pdf}>`);});- it.each(['file', 'xdt-file'].flatMap(scheme => ['100% done.pdf', 'encoded%20.pdf'].map(name => [scheme, name])))('preserves literal or once-encoded percent paths: %s %s', async (scheme, name) => {+ it.each(['file', 'xdt-file', 'xdt-query'].flatMap(scheme => ['100% done.pdf', 'encoded%20.pdf'].map(name => [scheme, name])))('preserves literal or once-encoded percent paths: %s %s', async (scheme, name) => {const file = path.join(work, name);await fs.writeFile(file, 'percent report');// A direct legacy URL is a URI with forward slashes on every platform.const direct = `${scheme}://${file.startsWith('/') ? '' : '/'}${file.replaceAll('\\', '/')}`;const encoded = pathToFileURL(file).href.replace(/^file:/, `${scheme}:`);- const result = await prepareChatReplyFiles(`[file](<${name.startsWith('100') ? direct : encoded}>)`, 'lane', () => {});+ const result = await prepareChatReplyFiles(`[file](<${scheme === 'xdt-query' ? `xdt-file://local?path=${encodeURIComponent(file)}` : name.startsWith('100') ? direct : encoded}>)`, 'lane', () => {});expect((await result.attachments[0]!.readBytes!()).toString()).toBe('percent report');});@@ -91,6 +91,38 @@ describe('group reply file delivery', () => {await expect(prepareChatReplyFiles(`[report](${href})`, 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');});+ it.each(['final report 中文.pdf', 'encoded%20.pdf', '100% done.pdf'])('decodes sandbox paths once or preserves malformed percents: %s', async name => {+ const file = path.join(work, name);+ await fs.writeFile(file, 'sandbox report');+ const href = `sandbox:/${work.replaceAll('\\', '/')}/${name.startsWith('100') ? name : encodeURIComponent(name)}`;+ const result = await prepareChatReplyFiles(`[report](<${href}>)`, 'lane', () => {});+ expect((await result.attachments[0]!.readBytes!()).toString()).toBe('sandbox report');+ });++ it.each(['reports%2Ffinal.pdf', 'reports%5Cfinal.pdf', '%2e%2e/private.pdf', '%00.pdf'])('refuses encoded sandbox path syntax: %s', async suffix => {+ const href = `sandbox:/${work.replaceAll('\\', '/')}/${suffix}`;+ await expect(prepareChatReplyFiles(`[report](${href})`, 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ });++ it('checks directory case aliases against the real filesystem and task root', async () => {+ const alias = path.join(root, 'TASK');+ let sameDirectory = false;+ try { sameDirectory = (await fs.stat(alias)).ino === (await fs.stat(work)).ino; }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }+ const target = path.join(alias, path.basename(pdf));+ if (sameDirectory) {+ const result = await prepareChatReplyFiles(`[report](<${target}>) [again](<${pdf}>)`, 'lane', () => {});+ expect(result.attachments).toHaveLength(1);+ expect((await result.attachments[0]!.readBytes!()).toString()).toContain('%PDF');+ } else {+ await fs.mkdir(alias);+ try {+ await fs.writeFile(target, 'outside');+ await expect(prepareChatReplyFiles(`[report](<${target}>)`, 'lane', () => {})).rejects.toThrow('ATTACHMENT_UNAVAILABLE');+ } finally { await fs.rm(alias, { recursive: true }); }+ }+ });+it('leaves ordinary relative navigation targets unchanged without file authority', async () => {scope.snapshot = null;const text = '[help](about) [guide][nav]\n\n[nav]: getting-started';diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.tsindex 5f0376a8a8..b1d9c7263e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerReplyImages.test.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import path from 'node:path';-const f = vi.hoisted(() => ({ stat: vi.fn(), canRead: vi.fn(), resolve: vi.fn(), materialize: vi.fn(), db: {} }));-vi.mock('node:fs/promises', () => ({ default: { stat: f.stat } }));+const f = vi.hoisted(() => ({ realpath: vi.fn(), stat: vi.fn(), canRead: vi.fn(), resolve: vi.fn(), materialize: vi.fn(), db: {} }));+vi.mock('node:fs/promises', () => ({ default: { stat: f.stat, realpath: f.realpath } }));vi.mock('../../cindy-media/taskImageDelivery.js', () => ({ materializeTaskImageTextResult: f.materialize }));vi.mock('../../cindy-media/ledger.js', () => ({ sessionCanRead: f.canRead }));vi.mock('../../cindy-media/blobStore.js', async original => ({ ...await original<typeof import('../../cindy-media/blobStore.js')>(), resolveSafe: f.resolve }));@@ -12,7 +12,7 @@ const url = `cindy-media://blobs/${'a'.repeat(64)}.png`;// Markdown collection from settlement. Actual task importer has its own tests.describe('generated reply image attachments', () => {beforeEach(() => {- vi.resetAllMocks(); f.canRead.mockResolvedValue(true);+ vi.resetAllMocks(); f.realpath.mockImplementation(async (source: string) => source); f.canRead.mockResolvedValue(true);f.resolve.mockReturnValue({ absPath: path.resolve('fixture', 'image.png'), mimeType: 'image/png' });f.stat.mockResolvedValue({ isFile: () => true, size: 3 });f.materialize.mockImplementation(async (_session, text) => ({ text, replacements: new Map(), failures: [] }));diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 9c63a8998f..ad372dfe4b 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -19,6 +19,7 @@ import { request as httpsRequest } from 'node:https';import { migrateLocalGroups, type ChatContentBlock } from './chatServerMigration.js';import { chatErrorDiagnostic, chatGroupFailure, missingGroupCode } from './chatServerErrors.js';import { createChatMedia } from './chatServerMedia.js';+import { mergeChatReplyAttachments } from './chatServerReplyAttachments.js';import { prepareChatReplyImages } from './chatServerReplyImages.js';import { chatServerWorkspaces } from './chatServerWorkspaces.js';import { buildPlanStepBrief } from './botGroupDivision.js';@@ -1513,14 +1514,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}, !terminal.resultText.trim() ? terminal.resultMessageClientId : undefined);pending.reply ??= { sourceText: text, ...await prepareChatReplyImages(pending.fileReply.text, run.sessionId, assertCurrent) };contentText = pending.reply.text;- produced.push(...[...pending.reply.attachments, ...pending.fileReply.attachments]- .sort((a, b) => {- const position = (a.sourceOffset ?? Infinity) - (b.sourceOffset ?? Infinity);- // An outer file link starts before its nested preview image;- // removing its delimiters can project both to the same offset.- return position || (a.sourceOffset !== undefined && b.sourceOffset !== undefined- ? Number(a.category === 'image') - Number(b.category === 'image') : 0);- }));+ produced.push(...mergeChatReplyAttachments(pending.reply.attachments, pending.fileReply.attachments));if (produced.length > BOT_GROUP_ATTACHMENTS_MAX) throw new Error('ATTACHMENT_UNAVAILABLE');}const validateUpload = async () => {diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.tsindex 1ab9abb030..72da8c701c 100644--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts@@ -17,6 +17,8 @@ import type { ChatApi, ChatContentBlock } from './chatServerMigration.js';export type ChatUploadAttachment = BotGroupAttachment & {/** Offset in the file-rewritten Markdown, before image materialization. Never sent over the wire. */sourceOffset?: number;+ /** Canonical local image/file sources, used only to reconcile the two reply passes. */+ sourcePaths?: string[];readBytes?: () => Promise<Buffer>;assertCurrent?: () => void;};diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.tsnew file mode 100644index 0000000000..e2e9aeaeaa--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyAttachments.ts@@ -0,0 +1,20 @@+import type { ChatUploadAttachment } from './chatServerMedia.js';++/** A rendered image and its download link share one upload at their first occurrence. */+export function mergeChatReplyAttachments(images: ChatUploadAttachment[], files: ChatUploadAttachment[]): ChatUploadAttachment[] {+ const imageSources = new Map<string, ChatUploadAttachment>();+ const merged = images.map(image => ({ ...image }));+ for (const image of merged) for (const source of image.sourcePaths ?? []) imageSources.set(source, image);+ for (const file of files) {+ const image = file.sourcePaths?.map(source => imageSources.get(source)).find(Boolean);+ if (image) {+ if (file.sourceOffset !== undefined) image.sourceOffset = Math.min(image.sourceOffset ?? Infinity, file.sourceOffset);+ } else merged.push(file);+ }+ return merged.sort((a, b) => {+ const position = (a.sourceOffset ?? Infinity) - (b.sourceOffset ?? Infinity);+ // Removing an outer file link can project it and its nested preview to the same offset.+ return position || (a.sourceOffset !== undefined && b.sourceOffset !== undefined+ ? Number(a.category === 'image') - Number(b.category === 'image') : 0);+ });+}diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.tsindex edbccab59a..45a2eadcbd 100644--- a/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyFiles.ts@@ -99,6 +99,10 @@ function localPath(url: string, workDir: string): string {const match = /^sandbox:\/*(?:([a-z]:[\\/][^\n]*)|(\/[^\n]*))$/i.exec(url);if (!match) throw unavailable();value = match[1] ?? match[2]!;+ if (/%(?:2f|5c)/i.test(value)) throw unavailable();+ const decoded = safeDecodeHrefForLookup(value);+ if (decoded === null) throw unavailable();+ value = decoded;} else if (/^xdt-file:/i.test(url)) {const parsed = new URL(url);// A remote reference must never be interpreted as a path on this machine.@@ -210,15 +214,25 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, assconst source = localPath(link.url, scope.workingDir!);// /tmp can alias /private/tmp; normalize the trusted workdir prefix without following the file.const lexicalRoot = path.resolve(scope.workingDir!);- if (!isPathWithin(lexicalRoot, source) && !isPathWithin(root, source)) throw unavailable();- const canonicalSource = isPathWithin(root, source) ? source : path.resolve(root, path.relative(lexicalRoot, source));+ let canonicalSource: string;+ if (!isPathWithin(lexicalRoot, source) && !isPathWithin(root, source)) {+ // Case aliases depend on the actual volume. Only an existing canonical+ // target within this task can override the lexical precheck.+ if (!isPathWithin(lexicalRoot.toLowerCase(), source.toLowerCase())+ && !isPathWithin(root.toLowerCase(), source.toLowerCase())) throw unavailable();+ canonicalSource = await fs.realpath(source).catch(() => { throw unavailable(); });+ assertCurrent();+ if (!isPathWithin(root, canonicalSource)) throw unavailable();+ } else canonicalSource = isPathWithin(root, source) ? source : path.resolve(root, path.relative(lexicalRoot, source));// Use the actual volume's inode identity (including case-insensitive APFS),// not a platform-wide casing assumption. Never follow the named symlink;// full realpath/descriptor containment is still enforced before reading.let identity = canonicalSource;+ let singleFile = false;try {const stat = await fs.lstat(canonicalSource, { bigint: true });if (stat.isFile() && stat.ino !== 0n) identity = `${stat.dev}:${stat.ino}`;+ singleFile = stat.isFile() && stat.nlink === 1n;} catch (error) {// Preserve deferred missing-file failure and the shared count limit.if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;@@ -227,8 +241,12 @@ export async function prepareChatReplyFiles(text: string, sessionId: string, assif (seen.has(identity)) continue;if (attachments.length >= BOT_GROUP_ATTACHMENTS_MAX) throw unavailable();seen.add(identity);+ // Metadata only: bytes still require the live authority and descriptor checks below.+ const realSource = singleFile ? await fs.realpath(canonicalSource).catch(() => undefined) : undefined;+ assertCurrent();let digest: string | undefined;attachments.push({ id: canonicalSource, sourceOffset: link.outputStart, name: path.basename(source), category: 'file',+ sourcePaths: realSource && isPathWithin(root, realSource) ? [realSource] : [],mimeType: path.extname(source).toLowerCase() === '.pdf' ? 'application/pdf' : 'application/octet-stream',size: 0, path: null, url: null, assertCurrent,readBytes: async () => {diff --git a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.tsindex 42ca79e4fc..3308db782f 100644--- a/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerReplyImages.ts@@ -4,7 +4,7 @@ import { BOT_GROUP_ATTACHMENTS_MAX } from '../../shared/botGroupChat.js';import { parseBlobUrl, resolveSafe } from '../cindy-media/blobStore.js';import { sessionCanRead } from '../cindy-media/ledger.js';import { materializeTaskImageTextResult } from '../cindy-media/taskImageDelivery.js';-import { hasLocalTaskImages, taskImageReferences, rewriteTaskImageReferences } from '../cindy-media/taskImageMarkdown.js';+import { hasLocalTaskImages, localTaskImagePath, taskImageReferences, rewriteTaskImageReferences } from '../cindy-media/taskImageMarkdown.js';import type { ChatUploadAttachment } from './chatServerMedia.js';import { getDbClient } from '../localDb/client/current.js';@@ -12,6 +12,14 @@ import { getDbClient } from '../localDb/client/current.js';export async function prepareChatReplyImages(text: string, sessionId: string, assertCurrent: () => void) {assertCurrent();const originalImages = taskImageReferences(text);+ const localSources = new Map<string, string>();+ for (const ref of originalImages) {+ const local = localTaskImagePath(ref.url);+ if (!local || localSources.has(ref.url)) continue;+ const real = await fs.realpath(local).catch(() => undefined);+ assertCurrent();+ if (real) localSources.set(ref.url, real);+ }let replacements = new Map<string, string>();if (hasLocalTaskImages(text)) {const imported = await materializeTaskImageTextResult(sessionId, text);@@ -21,9 +29,15 @@ export async function prepareChatReplyImages(text: string, sessionId: string, asreplacements = imported.replacements;}const positions = new Map<string, number>();+ const sources = new Map<string, Set<string>>();for (const ref of originalImages) {const url = replacements.get(ref.url) ?? ref.url;if (!positions.has(url)) positions.set(url, ref.start);+ const source = localSources.get(ref.url);+ if (source) {+ if (!sources.has(url)) sources.set(url, new Set());+ sources.get(url)!.add(source);+ }}const attachments: ChatUploadAttachment[] = [];const delivered = new Map<string, string>();@@ -39,6 +53,7 @@ export async function prepareChatReplyImages(text: string, sessionId: string, asassertCurrent();if (!stat.isFile() || stat.size <= 0 || stat.size > 100 * 1024 * 1024) throw new Error('ATTACHMENT_UNAVAILABLE');attachments.push({ id: ref.url, sourceOffset: positions.get(ref.url), name: path.basename(image.absPath), category: 'image',+ sourcePaths: [...sources.get(ref.url) ?? []],mimeType: image.mimeType, size: stat.size, url: ref.url, path: null });delivered.set(ref.url, ref.url);}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsxindex f01d5bc98f..41650a8ee2 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/RewindPreviewDialog.test.tsx@@ -116,6 +116,8 @@ describe('RewindPreviewDialog running-session flow', () => {});it('switches to an exact preview if the turn finishes while the dialog is open', async () => {+ let finishPreview!: (result: { canRewind: boolean; filesChanged: never[]; insertions: number; deletions: number }) => void;+ mocks.rewindPreview.mockReturnValueOnce(new Promise(resolve => { finishPreview = resolve; }));const props = {open: true,sessionId: 'session-1',@@ -130,7 +132,9 @@ describe('RewindPreviewDialog running-session flow', () => {view.rerender(<RewindPreviewDialog {...props} sessionRunning={false} />);await waitFor(() => expect(mocks.rewindPreview).toHaveBeenCalledWith('session-1', 'message-1'));- expect(screen.getByText('chat.rewind.dialog.summaryEmpty')).toBeTruthy();+ expect(screen.getByTestId('spinner')).toBeTruthy();+ finishPreview({ canRewind: true, filesChanged: [], insertions: 0, deletions: 0 });+ expect(await screen.findByText('chat.rewind.dialog.summaryEmpty')).toBeTruthy();});it('upgrades an authoritative running preview race to stop-then-rewind', async () => {