Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 广播持久化后的会话 status,挡住写读间隙的并发回滚 (#3175 增量) (#3225)
Tsai Yuan4be8eb2a38cc
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex e5fa4cbfc8..6b1deda274 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -40,6 +40,7 @@ const h = vi.hoisted(() => ({closeSession: (id: string) => Promise<void>;} | null => null),setPinnedSectionCardMode: vi.fn(),+ upsertRecentWorkdir: vi.fn(async () => undefined),routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>task(),) as SessionRouteLockMock,@@ -77,7 +78,7 @@ vi.mock('../../../git-context/prRefsStore', () => ({recomputePrRefsForSession: vi.fn(async () => undefined),}));vi.mock('../../../imageCacheStore', () => ({ removeSession: vi.fn(async () => undefined) }));-vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn(async () => undefined) }));+vi.mock('../recentWorkdirs', () => ({ upsertRecentWorkdir: h.upsertRecentWorkdir }));vi.mock('../../../device-link/broadcast-tap.js', () => ({getSafeDataOwnerPushStamp: vi.fn(() => undefined),tapWindowBroadcast: h.tapWindowBroadcast,@@ -100,6 +101,14 @@ vi.mock('../../../maker-host/claude-transcript-relocation.js', () => ({vi.mock('../../../maker-host/index.js', () => ({getMakerIfReady: h.getMakerIfReady,}));+// delete 路径的 removeHookAttachmentDir 会真删 turn change-set;归档路径动态+// import cindy-brain(重副作用模块)。两者都 mock 掉,本文件只断言广播行为。+vi.mock('../../../turn-change-set/store.js', () => ({+ removeTurnChangeSetsForSession: vi.fn(async () => undefined),+}));+vi.mock('../../../cindy-brain/index.js', () => ({+ notifyGhostSessionEvent: vi.fn(),+}));import { registerSessionIpc, resumeDeletedPiSubagentCleanup } from '../sessions';import { retireDeletedPiSubagentState } from '../piSubagentDeletion';@@ -486,6 +495,87 @@ describe('local-db:sessions:update handler wiring', () => {);});+ it('broadcasts local unarchive status patches to every window (#3175)', async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run('codex-local');++ await invokeUpdate('codex-local', { status: 'active' });+ await vi.dynamicImportSettled();++ const persisted = h+ .sqlite!.prepare('SELECT status FROM sessions WHERE id = ?')+ .get('codex-local') as { status: string };+ expect(persisted.status).toBe('active');+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'active' },+ });+ });++ // setStatus 的归档形是 { status, pinnedAt: null }:广播沿用置顶合并逻辑,+ // 归档一并清 pin 与摘要(归档列表不该保留 pin 标记)。+ it('broadcasts local archive status patches with the unpin merge (#3175)', async () => {+ await invokeUpdate('codex-local', { status: 'archived', pinnedAt: null });+ await vi.dynamicImportSettled();++ const persisted = h+ .sqlite!.prepare('SELECT status, pinned_at AS pinnedAt FROM sessions WHERE id = ?')+ .get('codex-local') as { status: string; pinnedAt: number | null };+ expect(persisted.status).toBe('archived');+ expect(persisted.pinnedAt).toBeNull();+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'archived', pinnedAt: null, summary: null },+ });+ });++ // 竞态收敛(review on #3225):写入与查询不在同一串行区间,归档写入后、查询前+ // 另一窗口可能已把行推进到 deleted。广播必须携带持久化后的 updated.status,+ // 否则副窗/控制端镜像会被请求值回滚成旧 UI 状态(已删除任务复活)。+ // routeLock 是测试注入的实现:在锁内写库完成后、handler 继续查询前,模拟+ // 另一窗口的删除落库。+ it('broadcasts the persisted status when a concurrent window deletes between write and read', async () => {+ h.routeLock.mockImplementation(async (_sessionId, task) => {+ await task();+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');+ });++ await invokeUpdate('codex-local', { status: 'archived' });+ await vi.dynamicImportSettled();++ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'codex-local',+ patch: { status: 'deleted' },+ });+ // 不再出现携带请求值的回滚广播+ const statusPatches = h.tapWindowBroadcast.mock.calls+ .filter(([channel]) => channel === 'local-db:sessions:patched')+ .map(([, payload]) => (payload as { patch: { status?: string } }).patch.status);+ expect(statusPatches).toEqual(['deleted']);+ });++ // 竞态收敛(review on #3225 第二轮):读行与广播之间还有 await(摘要清理 /+ // recent-workdir / 转录迁移),期间另一窗口可删除并先广播 deleted;本 handler+ // 恢复后若用旧快照广播 archived,该广播是最后一条,镜像不会自愈——已删任务+ // 持久复活。upsertRecentWorkdir 是已 mock 的依赖:在其 await 期间模拟删除落库,+ // 断言广播前重读了状态。+ it('re-reads status before broadcasting when an await intervenes after the row read', async () => {+ h.upsertRecentWorkdir.mockImplementationOnce(async () => {+ h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('cc-local');+ });++ await invokeUpdate('cc-local', { status: 'archived', workspaceKind: 'project' });+ await vi.dynamicImportSettled();++ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId: 'cc-local',+ patch: expect.objectContaining({ status: 'deleted' }),+ });+ const statusPatches = h.tapWindowBroadcast.mock.calls+ .filter(([channel]) => channel === 'local-db:sessions:patched')+ .map(([, payload]) => (payload as { patch: { status?: string } }).patch.status);+ expect(statusPatches).toEqual(['deleted']);+ });+it('broadcasts pin and unpin patches to device-link subscribers', async () => {const pinnedAt = '2026-08-03T04:08:26.000Z';await invokeUpdate('codex-local', { pinnedAt });diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 66f6c6bdb2..1f030ff116 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1478,14 +1478,6 @@ export function registerSessionIpc(row.summary = null;}const updated = sessionToCamel(row);- const broadcastPatch =- p.pinnedAt === undefined- ? p- : {- ...p,- pinnedAt: updated.pinnedAt,- ...(updated.pinnedAt === null ? { summary: null } : { status: updated.status }),- };const projectTargetChanged = p.workspaceKind !== undefined || p.workingDir !== undefined;const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));const titleChanged = p.title !== undefined;@@ -1500,6 +1492,37 @@ export function registerSessionIpc() {await upsertRecentWorkdir(row.workingDir, Date.now());}+ // status 广播必须用**广播时刻的持久化真值**,不能带请求值 p.status,也不能用+ // 上方读行的快照:写入(withStatusWriteLock)与广播不在同一串行区间,且读行+ // 之后、广播之前还有 await(摘要清理 / recent-workdir / 转录迁移),两个窗口+ // 对同一任务并发操作时,本请求可能在此期间被另一窗口推进到更晚的终态(如+ // 归档写入后被删除)。用过期值广播会把镜像回滚成旧 UI 状态(已删除任务在+ // 副窗/控制端复活),且若本广播是最后一条,镜像不会自愈。+ //+ // 因此含 status 的 patch 在广播前(所有 await 之后)**重读一次**:重读与广播+ // 之间无 await,同进程单事件循环下不可能再插入并发写;即便并发删除的广播+ // 晚于本广播到达,镜像最终也收敛到 deleted。+ let broadcastStatus = updated.status;+ if (p.status !== undefined) {+ const [currentRow] = await db+ .select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, sid))+ .limit(1);+ if (currentRow) broadcastStatus = currentRow.status;+ }+ const broadcastPatch =+ p.pinnedAt === undefined && p.status === undefined+ ? p+ : {+ ...p,+ ...(p.pinnedAt !== undefined ? { pinnedAt: updated.pinnedAt } : {}),+ ...(p.status !== undefined ? { status: broadcastStatus } : {}),+ ...(p.pinnedAt !== undefined && updated.pinnedAt === null ? { summary: null } : {}),+ ...(p.pinnedAt !== undefined && updated.pinnedAt !== null+ ? { status: broadcastStatus }+ : {}),+ };if (projectTargetChanged ||settingsChanged ||diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.tsindex cbb296489c..75db2e48ea 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts@@ -170,9 +170,9 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta// 为什么必须全桶、不能只刷当前桶(codex review):归档时 patchLocal 会 drop// 目标桶(archived,本地没有这条的完整 row)并立刻重拉,而那次重拉发生在// setStatus 写库**之前**,拿回来的是「还没归档」的快照。本机- // local-db:sessions:update 又只在 title / settings / project 变化时才广播- // sessions:patched(status 不在其中),archived 桶再没有别的修正机会 —— 用户- // 切到「已归档」筛选会看不到刚归档的这条,直到某次无关刷新。+ // local-db:sessions:update 对 status 变化也会广播 sessions:patched(#3175,+ // 副窗与控制端靠它收敛),但广播只修单个字段、不触发各桶重拉 ——+ // 已归档桶仍需要这里的 emitRefresh 才能看到刚归档的这条,直到某次无关刷新。// 与 unarchiveSession 末尾的 emitRefresh 同口径。emitRefresh();// 远程会话从侧边栏消失由被控端 sessions:patched{status} 回流(applyPatch 移出分片)驱动,