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(desktop): 补齐变更捕获退出与消息锚点

DavidShenf4337c6bc5b8
diff --git a/apps/desktop/src/main/__tests__/codexFileRestoreExecutor.git-integration.test.ts b/apps/desktop/src/main/__tests__/codexFileRestoreExecutor.git-integration.test.ts
index abf5b99638..0cf55ab68a 100644
--- a/apps/desktop/src/main/__tests__/codexFileRestoreExecutor.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/codexFileRestoreExecutor.git-integration.test.ts
@@ -272,7 +272,8 @@ describe('executeCodexFileRestorePlan', () => {
// 目录被清掉,原文件按基线内容重建。swap 已是文件,子路径 lstat 报 ENOTDIR。
expect(await readFile('swap')).toBe('was a file\n');
await expect(fs.lstat(path.join(repoPath, 'swap/child.txt'))).rejects.toMatchObject({
- code: 'ENOTDIR',
+ // Windows may report ENOENT for a child below a path that is now a file.
+ code: expect.stringMatching(/^(?:ENOENT|ENOTDIR)$/),
});
expect(result?.restoredFiles).toContain('swap');
expect(result?.deletedFiles).toContain('swap/child.txt');
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 6779db9104..d35467d4f1 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -109,7 +109,7 @@ describe('sendToSession ordering', () => {
const policyGuardBlock = extractBetween(
source,
'async function assertLeadCollabProjectEnabled',
- 'type SendToSessionDispatchSession',
+ 'async function sendUserMessageWithAwaitedGitBaseline',
);
expect(policyGuardBlock).toContain(
@@ -132,7 +132,7 @@ describe('sendToSession ordering', () => {
it('uses the same trusted collab scope helper and acknowledges the accepted workspace kind', () => {
const pluginStateBlock = extractBetween(
source,
- 'ipcMain.handle(MAKER_INVOKE.PLUGINS_GET_STATE',
+ 'ipcMain.handle(\n MAKER_INVOKE.PLUGINS_GET_STATE',
'ipcMain.handle(MAKER_INVOKE.PLUGINS_SET_ENABLED',
);
@@ -152,7 +152,7 @@ describe('sendToSession ordering', () => {
const createWorkerReadyBlock = extractBetween(
source,
'sendWorkerReadyMessage: (session) => {',
- ' broadcastSessionCreated,',
+ ' broadcastSessionCreated,',
);
const workerReadyPlaceholderBlock = extractBetween(
source,
@@ -174,7 +174,8 @@ describe('sendToSession ordering', () => {
expect(queuedCreateOptsBlock).toContain('planMode: false,');
expect(orcaInterAgentDispatcherSource).toContain('planMode: false,');
expect(schedulerRunnerSource).toContain('planMode: false,');
- expect(goalControllerSource).toContain("{ origin: { kind: 'goal', goalSessionId: sessionId }, planMode: false },");
+ expect(goalControllerSource).toContain("origin: { kind: 'goal', goalSessionId: sessionId },");
+ expect(goalControllerSource).toContain('planMode: false,');
expect(imTurnRunnerSource).toContain('planMode: false,');
expect(orcaWorkflowSource).toContain('planMode: false,');
});
@@ -315,7 +316,7 @@ describe('sendToSession ordering', () => {
const changeSetBlock = extractBetween(
source,
'async function beginTurnChangeSetAtDispatch',
- 'async function sendUserMessageWithAwaitedGitBaseline',
+ 'export interface RegisterMakerIpcOptions',
);
const helperBlock = extractBetween(
source,
@@ -433,7 +434,7 @@ describe('sendToSession ordering', () => {
it('serializes SET_MODEL behind the send-time agent switch for the same session', () => {
const setModelBlock = extractBetween(
source,
- 'ipcMain.handle(MAKER_INVOKE.SET_MODEL',
+ 'ipcMain.handle(\n MAKER_INVOKE.SET_MODEL',
'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',
);
const directSendSwitchBlock = extractBetween(
@@ -510,7 +511,7 @@ describe('sendToSession ordering', () => {
it('仅 Device Link 归一化 SET_MODEL 的 JSON null 可选占位,本地仍走严格校验', () => {
const setModelBlock = extractBetween(
source,
- 'ipcMain.handle(MAKER_INVOKE.SET_MODEL',
+ 'ipcMain.handle(\n MAKER_INVOKE.SET_MODEL',
'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',
);
expect(setModelBlock).toContain('normalizeDeviceLinkSetModelWireArgs(');
@@ -526,8 +527,8 @@ describe('sendToSession ordering', () => {
it('publishes Agent Island prompt preview from send intent and wires commit rollback', () => {
const makerSendCreateDbMessageBlock = extractBetween(
source,
- 'createDbMessage: async (sessionId, message, opts) => {',
- ' previewUserPrompt: (session, content, options) => {',
+ 'const createUserMessageDurably:',
+ 'const { sendToAgentAccepted: sendToAgentAcceptedUnlocked }',
);
const makerSendPreviewHookBlock = extractBetween(
source,
@@ -535,8 +536,9 @@ describe('sendToSession ordering', () => {
' isSessionRunningError,',
);
- expect(makerSendCreateDbMessageBlock).toContain('const result = await enqueueDurableWrite');
+ expect(makerSendCreateDbMessageBlock).toContain('return await enqueueDurableWrite');
expect(makerSendCreateDbMessageBlock).not.toContain('notifyAgentIslandUserPrompt(');
+ expect(source).toContain('createDbMessage: createUserMessageDurably,');
expect(makerSendPreviewHookBlock).toContain('previewUserPrompt: (session, content, options) => {');
expect(makerSendPreviewHookBlock).toContain(
'const previewed = notifyAgentIslandUserPrompt(session, content, {',
@@ -776,11 +778,14 @@ describe('sendToSession ordering', () => {
});
it('keeps worker idle/archive adapters passing the caller lead session id', () => {
- expect(preloadSource).toContain("idleWorker: (leadSessionId: string, workerId: string, expectedStatus?: 'done'): Promise<unknown> =>");
- expect(preloadSource).toContain("ipcRenderer.invoke('maker:worker:idle', {");
- expect(preloadSource).toContain("ipcRenderer.invoke('maker:worker:acknowledge-done', {");
- expect(preloadSource).toContain("archiveWorker: (leadSessionId: string, workerId: string): Promise<unknown> =>");
- expect(preloadSource).toContain("ipcRenderer.invoke('maker:worker:archive', { leadSessionId, workerId })");
+ const workerAdapterBlock = extractBetween(preloadSource, 'idleWorker: (', 'endTeam:');
+ expect(workerAdapterBlock).toContain('leadSessionId: string,');
+ expect(workerAdapterBlock).toContain('workerId: string,');
+ expect(workerAdapterBlock).toContain("expectedStatus?: 'done',");
+ expect(workerAdapterBlock).toContain("ipcRenderer.invoke('maker:worker:idle', {");
+ expect(workerAdapterBlock).toContain("ipcRenderer.invoke('maker:worker:acknowledge-done', {");
+ expect(workerAdapterBlock).toContain('archiveWorker: (leadSessionId: string, workerId: string)');
+ expect(workerAdapterBlock).toContain("ipcRenderer.invoke('maker:worker:archive', { leadSessionId, workerId })");
// device-link:归档入口(现居 useOrcaWorkerSelection)经 orcaWorkflowsFor 按 lead 来源路由
// (本机直连 / 远程隧道),但仍把 (leadSessionId, workerId) 传给 archiveWorker ——
// 本不变式守的是「带上 caller lead id」;正则容忍链式调用换行。
diff --git a/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts
index 762e1e9570..d6ac5440b2 100644
--- a/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeBranchNamespace.git-integration.test.ts
@@ -20,7 +20,8 @@ function git(cwd: string, ...args: string[]): string {
env: {
...process.env,
GIT_CONFIG_NOSYSTEM: '1',
- GIT_CONFIG_GLOBAL: os.devNull,
+ // Git for Windows does not accept Node's extended `\\.\nul` spelling.
+ GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : os.devNull,
},
}).trim();
}
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 7c255c0d8c..0552eb46d7 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -37,7 +37,10 @@ import {
} from './devStartupStatus';
import { prewarmMacComputerPermissionGuideHelper } from './computer-permission-guide/MacComputerPermissionGuideNativeHost.js';
import { handleOpenChatGPTApp } from './chatgpt-app.js';
-import { waitForTurnChangeSetActions } from './turn-change-set/store.js';
+import {
+ waitForTurnChangeSetActions,
+ waitForTurnChangeSetPersistence,
+} from './turn-change-set/store.js';
const PROCESS_STARTED_AT_MS = Date.now();
// Official Linux binaries total hundreds of MB. Keep one shared deadline for
@@ -101,6 +104,9 @@ async function shutdownMaker(): Promise<void> {
// 注意: getMakerCore 未就绪时抛的是 sync error, await m.shutdown() 也走这里。
console.error('[main] maker.shutdown failed (or not ready):', err);
}
+ // Session shutdown may enqueue the final turn sidecar write. Drain only
+ // after maker.shutdown() has closed every session and emitted those writes.
+ await waitForTurnChangeSetPersistence();
WorktreePool.parkAll();
}
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 9278fdb7ae..ff40336cf2 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -38,6 +38,10 @@ const h = vi.hoisted(() => {
createMessage: vi.fn(async () => {
calls.push('createMessage');
}),
+ beginTurnChangeSetAtDispatch: vi.fn(async (session: { id: string }, anchorClientId: string) => {
+ calls.push(`beginChangeSet:${session.id}:${anchorClientId}`);
+ }),
+ clearPendingTurnChangeSets: vi.fn(),
setSessionProviderIdInDb: vi.fn(async (id: string, providerId: string) => {
calls.push(`providerDb:${id}:${providerId}`);
}),
@@ -96,12 +100,16 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({
tapWindowBroadcast: h.tapWindowBroadcast,
}));
vi.mock('../../maker-ipc/register.js', () => ({
+ beginTurnChangeSetAtDispatch: h.beginTurnChangeSetAtDispatch,
wireSessionToIpc: vi.fn(),
isSessionInTurn: () => false,
installDesktopInteractionListener: h.installDesktopInteractionListener,
noteSilentStopUserSend: vi.fn(),
onSilentStopSettled: vi.fn(() => () => {}),
}));
+vi.mock('../../turn-change-set/store.js', () => ({
+ clearPendingTurnChangeSets: h.clearPendingTurnChangeSets,
+}));
vi.mock('../../maker-host/send-outcome.js', () => ({
toDesktopSessionDispatchOutcome: () => ({ dispatched: true as const }),
}));
@@ -2971,3 +2979,23 @@ describe('watchContinuation: 观察桌面端续跑并回流', () => {
expect(h.eventCbs.has('sess-live')).toBe(false);
});
});
+
+describe('hook turn change-set anchor', () => {
+ it('uses the durable accepted user message client id', async () => {
+ const runner = createMakerHookSessionRunner({ log });
+ const outcome = await runner.run(baseReq({}));
+
+ expect(outcome.status).toBe('ok');
+ const [, message] = h.createMessage.mock.calls[0] as unknown as [
+ string,
+ { clientId: string },
+ ];
+ expect(h.beginTurnChangeSetAtDispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'sess-new' }),
+ message.clientId,
+ );
+ expect(h.calls.indexOf('createMessage')).toBeLessThan(
+ h.calls.indexOf(`beginChangeSet:sess-new:${message.clientId}`),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index a8d39b7dd9..e69b744a7e 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -51,11 +51,13 @@ import { getMaker } from '../maker-host/index.js';
import { resolveLenientRoute } from '../maker-host/model-route-guard.js';
import { resolveLenientSessionRoute } from '../maker-host/model-route-guard-live.js';
import {
+ beginTurnChangeSetAtDispatch,
wireSessionToIpc,
isSessionInTurn,
noteSilentStopUserSend,
onSilentStopSettled,
} from '../maker-ipc/register.js';
+import { clearPendingTurnChangeSets } from '../turn-change-set/store.js';
import {
beginInteractionRoute,
type InteractionHandler,
@@ -951,6 +953,8 @@ export function createMakerHookSessionRunner(deps: {
? { text: req.prompt, images: imageRefs, files: fileRefs }
: req.prompt;
+ const turnChangeAnchorClientId = randomUUID();
+ let turnChangeSetStarted = false;
try {
const pendingHandoff = await agentHandoffPending.peek(session.id);
const outgoingMessage: UserMessage = pendingHandoff
@@ -1002,11 +1006,13 @@ export function createMakerHookSessionRunner(deps: {
// 裸 path 的 image block 会被忽略), 无图为纯文本 string。
noteSilentStopUserSend(session.id);
await createMessage(session.id, {
- clientId: randomUUID(),
+ clientId: turnChangeAnchorClientId,
role: 'user',
content: userMessageContent,
agentMeta: { origin, ...(req.source ? { hookSource: req.source } : {}) },
});
+ await beginTurnChangeSetAtDispatch(session, turnChangeAnchorClientId);
+ turnChangeSetStarted = true;
// 每次被接受的 IM 消息都是一次用户发送: bump userSendAt 让排序
// 时间轴与桌面端 sendMessage 口径一致, sessions:patched 广播顺带把
// 复用/接管会话即时重排序(新建路径已在广播前落过, 这里更新为实际
@@ -1022,12 +1028,14 @@ export function createMakerHookSessionRunner(deps: {
context: `hook:${req.origin.connectionId}`,
});
if (!outcome.dispatched) {
+ if (turnChangeSetStarted) clearPendingTurnChangeSets(session.id);
observer.stop();
finalizeInteractions();
releaseTelegramGroupTurn();
return fail(`send not dispatched: ${outcome.reason}`);
}
} catch (err) {
+ if (turnChangeSetStarted) clearPendingTurnChangeSets(session.id);
observer.stop();
finalizeInteractions();
releaseTelegramGroupTurn();
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 5775176f07..b02a3f7ba6 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -42,6 +42,8 @@ const mocks = vi.hoisted(() => ({
persistUserMessage: vi.fn(),
persistAssistantMessage: vi.fn(),
wireSessionToIpcExternal: vi.fn(),
+ beginTurnChangeSetAtDispatch: vi.fn(async () => undefined),
+ clearPendingTurnChangeSets: vi.fn(),
noteSilentStopUserSend: vi.fn(),
noteSilentStopSessionReset: vi.fn(),
onSilentStopSettled: vi.fn(() => vi.fn()),
@@ -122,6 +124,7 @@ vi.mock('../../binding', () => ({
}));
vi.mock('../../../maker-ipc/register', () => ({
+ beginTurnChangeSetAtDispatch: mocks.beginTurnChangeSetAtDispatch,
wireSessionToIpcExternal: mocks.wireSessionToIpcExternal,
installDesktopInteractionListener: mocks.installDesktopInteractionListener,
takePendingInteractionsForSession: mocks.takePendingInteractionsForSession,
@@ -130,6 +133,10 @@ vi.mock('../../../maker-ipc/register', () => ({
onSilentStopSettled: mocks.onSilentStopSettled,
}));
+vi.mock('../../../turn-change-set/store', () => ({
+ clearPendingTurnChangeSets: mocks.clearPendingTurnChangeSets,
+}));
+
vi.mock('../pendingInteractions', () => ({
registerPending: mocks.registerPending,
registerPendingExternal: mocks.registerPendingExternal,
@@ -547,6 +554,18 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
);
});
+ it('anchors direct IM capture to the durable accepted user message', async () => {
+ mocks.persistUserMessage.mockResolvedValue({ clientId: 'im-anchor-client' });
+ const h = setupSession(async () => ({ accepted: true }));
+
+ await runDefaultTurn();
+
+ expect(mocks.beginTurnChangeSetAtDispatch).toHaveBeenCalledWith(
+ h.session,
+ 'im-anchor-client',
+ );
+ });
+
it('passes persisted null Pi providerId through cold IM session creation', async () => {
// Pi core 将 null 解释为“清除显式来源”;undefined 会反查同名 BYOM provider。
mocks.findActiveSession.mockResolvedValue({
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 77716d6a94..c65cea8a0b 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -86,12 +86,14 @@ import { persistUserMessage } from '../messagePersistence';
import { bindingStore } from '../binding';
import { buildImUserMessage } from './inboundMessage';
import {
+ beginTurnChangeSetAtDispatch,
wireSessionToIpcExternal,
takePendingInteractionsForSession,
noteSilentStopUserSend,
noteSilentStopSessionReset,
onSilentStopSettled,
} from '../../maker-ipc/register';
+import { clearPendingTurnChangeSets } from '../../turn-change-set/store';
import {
beginInteractionRoute,
type InteractionRouteLease,
@@ -812,6 +814,7 @@ export function createTurnRunner(
`enqueued turn for session=${rowId.slice(-8)} queueDepth=${state.queue.length} pendingSends=${state.sendQueue.length}`,
);
let acceptedAt = 0;
+ let turnChangeSetStarted = false;
let releaseAgentSwitchLock = (): void => {};
try {
@@ -904,6 +907,10 @@ export function createTurnRunner(
userMessageId: item.turn.userMessageId,
persisted: persisted !== null,
});
+ if (persisted) {
+ await beginTurnChangeSetAtDispatch(state.makerSession, persisted.clientId);
+ turnChangeSetStarted = true;
+ }
},
});
if (pendingHandoff && sendResult.accepted) {
@@ -914,6 +921,7 @@ export function createTurnRunner(
context: buildSendContext(rowId),
});
if (!outcome.dispatched) {
+ if (turnChangeSetStarted) clearPendingTurnChangeSets(rowId);
await handleSendPreDispatchFailure(state, userId, {
turn: item.turn,
source: outcome.source,
@@ -924,6 +932,7 @@ export function createTurnRunner(
}
return { kind: 'accepted', acceptedAt: acceptedAt || Date.now() };
} catch (err) {
+ if (turnChangeSetStarted) clearPendingTurnChangeSets(rowId);
const normalized = normalizeSendError(err);
if (normalized.reason === 'SESSION_RUNNING') {
releaseTurnInteractionRoute(item.turn, 'session_running_race');
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index ce95a52e0e..910e4e73b7 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4668,6 +4668,31 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
*/
export const wireSessionToIpcExternal = wireSessionToIpc;
+type SendToSessionDispatchSession = {
+ id: string;
+ agentKind: AgentKind;
+ workDir: string;
+ remoteHostId: string | null;
+ send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult>;
+};
+
+/** Starts exact turn capture at the accepted, durable user-message boundary. */
+export async function beginTurnChangeSetAtDispatch(
+ session: SendToSessionDispatchSession,
+ anchorClientId: string,
+): Promise<void> {
+ await waitForTurnChangeSetSeal(session.id);
+ await finalizeTurnChangeSet(session.id, null, 'partial');
+ await waitForTurnChangeSetSeal(session.id);
+ await beginTurnChangeSet({
+ sessionId: session.id,
+ anchorClientId,
+ provider: session.agentKind,
+ cwd: session.workDir,
+ remote: session.remoteHostId !== null,
+ });
+}
+
export interface RegisterMakerIpcOptions {
onAnySessionTurnKeepaliveChange?: (isRunning: boolean) => void;
/** 由 bootstrap 注入,避免 maker-ipc → model-access → maker-host 的循环依赖。 */
@@ -6601,30 +6626,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
- type SendToSessionDispatchSession = {
- id: string;
- agentKind: AgentKind;
- workDir: string;
- remoteHostId: string | null;
- send(message: UserMessage | string, opts?: SessionSendOptions): Promise<SessionSendResult>;
- };
-
- async function beginTurnChangeSetAtDispatch(
- session: SendToSessionDispatchSession,
- anchorClientId: string,
- ): Promise<void> {
- await waitForTurnChangeSetSeal(session.id);
- await finalizeTurnChangeSet(session.id, null, 'partial');
- await waitForTurnChangeSetSeal(session.id);
- await beginTurnChangeSet({
- sessionId: session.id,
- anchorClientId,
- provider: session.agentKind,
- cwd: session.workDir,
- remote: session.remoteHostId !== null,
- });
- }
-
async function sendUserMessageWithAwaitedGitBaseline(
session: SendToSessionDispatchSession,
message: string,
diff --git a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
index 8f7d87f08d..e8bc0d17c0 100644
--- a/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
+++ b/apps/desktop/src/main/turn-change-set/__tests__/store.git-integration.test.ts
@@ -46,6 +46,7 @@ import {
listTurnChangeSets,
noteOpaqueTurnChange,
noteTurnDiffEvent,
+ waitForTurnChangeSetPersistence,
} from '../store';
describe('turn change-set sidecar store', () => {
@@ -121,6 +122,40 @@ describe('turn change-set sidecar store', () => {
});
});
+ it('drains queued sidecar persistence before shutdown returns', async () => {
+ await beginTurnChangeSet({
+ sessionId: 'session-1',
+ anchorClientId: 'user-1',
+ provider: 'codex',
+ cwd: workdir,
+ });
+ noteTurnDiffEvent('session-1', {
+ type: 'turn_diff',
+ source: 'codex',
+ data: {
+ turnId: 'turn-shutdown-drain',
+ cwd: workdir,
+ diff: [
+ 'diff --git a/a.ts b/a.ts',
+ '--- a/a.ts',
+ '+++ b/a.ts',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ '',
+ ].join('\n'),
+ },
+ });
+
+ void finalizeTurnChangeSet('session-1', 'turn-shutdown-drain', 'complete');
+ await waitForTurnChangeSetPersistence();
+
+ const [summary] = await listTurnChangeSets('session-1');
+ expect(summary).toMatchObject({ anchorClientId: 'user-1', state: 'complete' });
+ const [detail] = await getTurnChangeSets('session-1', [summary!.id]);
+ expect(detail?.diffs[0]?.rawPatch).toContain('diff --git a/a.ts b/a.ts');
+ });
+
it('marks a safely composed Codex subset partial when another file conflict was omitted', async () => {
await beginTurnChangeSet({
sessionId: 'session-1',
diff --git a/apps/desktop/src/main/turn-change-set/store.ts b/apps/desktop/src/main/turn-change-set/store.ts
index 3b204b1e13..3a9581dfad 100644
--- a/apps/desktop/src/main/turn-change-set/store.ts
+++ b/apps/desktop/src/main/turn-change-set/store.ts
@@ -660,6 +660,14 @@ export async function waitForTurnChangeSetActions(): Promise<void> {
}
}
+/** Drains queued sidecar persistence before the Desktop process exits. */
+export async function waitForTurnChangeSetPersistence(): Promise<void> {
+ while (sessionWriteChains.size > 0) {
+ await Promise.allSettled([...sessionWriteChains.values()]);
+ }
+ await storageWriteChain.catch(() => undefined);
+}
+
function enqueueStorageWrite(operation: () => Promise<void>): Promise<void> {
const current = storageWriteChain.catch(() => undefined).then(operation);
storageWriteChain = current.catch(() => undefined);