Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(projects): 保留独立活跃时间,不因归档或删除任务刷新 (#4617)
Dasha79e1a801b5d
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex fe063d08eb..5dbc03ab1e 100644--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@ -114,7 +114,9 @@ beforeEach(() => {h.captureOwnerScope = false;h.readBindings.mockReset().mockResolvedValue([]);h.requestRecycle.mockReset().mockResolvedValue(undefined);- Object.assign(h.drizzle, { select: () => ({ from: () => ({ where: () => ({ limit: h.readBindings }) }) }) });+ Object.assign(h.drizzle, {+ select: () => ({ from: () => ({ where: () => ({ limit: h.readBindings }) }) }),+ });setSessionRemovalCancelOperations(h.cancelSessionOperations);setSessionRemovalCleanup(h.cleanupRemovedSession);setSessionWorktreeRecycle(h.requestRecycle);@@ -136,30 +138,48 @@ afterEach(async () => {describe('setSessionsStatusInDb', () => {it('returns batch status changes promptly and serializes their cleanup chains', async () => {const ids = ['one', 'two', 'three'];- h.tx.mockResolvedValueOnce(ids.map((sessionId) => ({ sessionId, status: 'archived', workingDir: null })));+ h.tx.mockResolvedValueOnce(+ ids.map((sessionId) => ({ sessionId, status: 'archived', workingDir: null })),+ );let finish!: () => void;- h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );await setSessionsStatusInDb(ids, 'archived');try {await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');- for (const sessionId of ids) expect(h.webContentsSend).toHaveBeenCalledWith(- 'local-db:sessions:patched', { sessionId, patch: { status: 'archived' } },- );- } finally { finish?.(); }+ for (const sessionId of ids)+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:sessions:patched', {+ sessionId,+ patch: { status: 'archived' },+ });+ } finally {+ finish?.();+ }await queueSessionWorktreeRecycle(async () => {});expect(h.recycleWorktreeForRemovedSession.mock.calls.map(([id]) => id)).toEqual(ids);});it('rechecks a queued task restored to active while an earlier cleanup runs', async () => {let finish!: () => void;- h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );const first = recycleSessionWorktreeForStatusChange('one', 'archived');const second = recycleSessionWorktreeForStatusChange('two', 'archived');try {await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());h.isSessionStillRemovable.mockImplementation(async (id) => id !== 'two');- } finally { finish?.(); }+ } finally {+ finish?.();+ }await Promise.all([first, second]);expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');});@@ -167,40 +187,58 @@ describe('setSessionsStatusInDb', () => {it('retains the captured database while cleanup waits in the queue', async () => {let finish!: () => void;const savedDb = h.drizzle;- h.recycleWorktreeForRemovedSession.mockImplementationOnce(() => new Promise<void>((resolve) => { finish = resolve; }));+ h.recycleWorktreeForRemovedSession.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ }),+ );const first = recycleSessionWorktreeForStatusChange('one', 'archived');const second = recycleSessionWorktreeForStatusChange('two', 'archived');try {await vi.waitFor(() => expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledOnce());h.drizzle = {};- finish(); await Promise.all([first, second]);+ finish();+ await Promise.all([first, second]);expect(h.closeSession).toHaveBeenCalledExactlyOnceWith('one');- } finally { finish?.(); h.drizzle = savedDb; }+ } finally {+ finish?.();+ h.drizzle = savedDb;+ }});it('persists shared resource intent before the terminal transaction', async () => {const worktree = path.join(h.userDataPath, 'repo', '.cindy-worktrees', 'one');- h.readBindings.mockResolvedValue([{ workingDir: path.join(worktree, 'src'), worktreePath: null, remoteHostId: null }]);+ h.readBindings.mockResolvedValue([+ { workingDir: path.join(worktree, 'src'), worktreePath: null, remoteHostId: null },+ ]);const order: string[] = [];h.requestRecycle.mockImplementation(async (_id, resources) => {expect(resources).toEqual([worktree]);order.push('request');});- h.tx.mockImplementationOnce(async () => { order.push('status'); return []; });+ h.tx.mockImplementationOnce(async () => {+ order.push('status');+ return [];+ });await setSessionsStatusInDb(['borrower'], 'archived');expect(order).toEqual(['request', 'status']);});it('preserves task status when recovery intent cannot be persisted', async () => {h.requestRecycle.mockRejectedValue(new Error('private internal path'));- await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow('PRECONDITION_FAILED');+ await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow(+ 'PRECONDITION_FAILED',+ );expect(h.tx).not.toHaveBeenCalled();expect(h.tapWindowBroadcast).not.toHaveBeenCalled();});it('does not treat an unreadable reference query as an empty binding', async () => {h.readBindings.mockRejectedValue(new Error('database unavailable'));- await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow('PRECONDITION_FAILED');+ await expect(setSessionsStatusInDb(['owner'], 'archived')).rejects.toThrow(+ 'PRECONDITION_FAILED',+ );expect(h.tx).not.toHaveBeenCalled();});it('runs one sessions.setStatus tx and broadcasts per session after commit', async () => {@@ -277,7 +315,7 @@ describe('setSessionsStatusInDb', () => {});it.each(['desktop', 'plugin'] as const)(- 'touches retained local %s projects when batch archiving and broadcasts the refresh',+ 'preserves retained local %s project activity when batch archiving',async (source) => {h.tx.mockResolvedValueOnce([{@@ -298,15 +336,11 @@ describe('setSessionsStatusInDb', () => {now.mockRestore();}- expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(- '/repo',- 1_786_500_200_000,- process.platform,- expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),);- expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {- path: '/repo',- });},);@@ -350,7 +384,7 @@ describe('setSessionsStatusInDb', () => {);});- it('touches the entry database but suppresses the batch refresh after an owner switch', async () => {+ it('preserves project activity and suppresses the batch refresh after an owner switch', async () => {h.captureOwnerScope = true;h.tx.mockImplementationOnce(async () => {h.isOwnerScopeCurrent.mockReturnValue(false);@@ -369,12 +403,7 @@ describe('setSessionsStatusInDb', () => {await setSessionsStatusInDb(['s1'], 'archived');- expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(- '/repo',- expect.any(Number),- process.platform,- expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),- );+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();expect(h.webContentsSend).not.toHaveBeenCalledWith('local-db:recent-workdirs:changed',expect.anything(),@@ -732,8 +761,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {await recycleSessionWorktreeForStatusChange('owner', 'archived');const options = h.recycleWorktreeForRemovedSession.mock.calls[0]?.[1] as- | { isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined }- | undefined;+ { isSessionRuntimeAlive?: (sessionId: string) => boolean | undefined } | undefined;expect(options?.isSessionRuntimeAlive?.('borrower')).toBe(true);expect(options?.isSessionRuntimeAlive?.('closed')).toBe(false);});diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.tsindex 2eecc6e295..537b04bf05 100644--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts@@ -53,6 +53,9 @@ const h = vi.hoisted(() => {};return {+ upsertRecentWorkdir: vi.fn(async () => true),+ ownerCurrent: true,+ captureOwnerScope: false,tapWindowBroadcast: vi.fn(),webContentsSend: vi.fn(),broadcastSubagentRunsInvalidated: vi.fn(),@@ -84,11 +87,13 @@ vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.vi.mock('../git-context/prRefsStore', () => ({recomputePrRefsForSession: vi.fn(() => Promise.resolve()),}));-vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: vi.fn() }));+vi.mock('../localDb/ipc/recentWorkdirs', () => ({ upsertRecentWorkdir: h.upsertRecentWorkdir }));vi.mock('../device-link/broadcast-tap', () => ({- captureDataOwnerBroadcastScope: vi.fn(() => null),+ captureDataOwnerBroadcastScope: vi.fn(() =>+ h.captureOwnerScope ? { ownerStamp: { dataOwnerId: 'owner-a', generation: 1 } } : null,+ ),getSafeDataOwnerPushStamp: vi.fn(() => undefined),- isDataOwnerBroadcastScopeCurrent: vi.fn(() => true),+ isDataOwnerBroadcastScopeCurrent: vi.fn(() => h.ownerCurrent),tapWindowBroadcast: h.tapWindowBroadcast,}));vi.mock('../localDb/client/current', () => ({ getDbClient: () => ({ drizzle: h.fakeDb }) }));@@ -112,12 +117,89 @@ import {beforeEach(() => {vi.clearAllMocks();+ h.ownerCurrent = true;+ h.captureOwnerScope = false;+ h.upsertRecentWorkdir.mockResolvedValue(true);h.updateSetCalls.length = 0;h.selectResults.length = 0;h.updateErrors.length = 0;});describe('touchUserSendInDb 广播 sessions:patched(device-link 项目归属收敛)', () => {+ it.each([+ ['desktop', '/repo', '/repo'],+ ['plugin', '/plugin-repo', '/plugin-repo'],+ ['desktop', '/repo/.cindy-worktrees/task-a', '/repo'],+ ['desktop', '/repo/.xdt-worktrees/task-a', '/repo'],+ ['desktop', 'D:/repo/.cindy-worktrees/task-a', 'D:/repo'],+ ])('persists %s project activity for %s at send time', async (source, workingDir, projectDir) => {+ const atMs = 1_700_000_000_000;+ h.selectResults.push([+ {+ userSendAt: atMs,+ updatedAt: atMs,+ source,+ workingDir,+ workspaceKind: 'project',+ remoteHostId: null,+ },+ ]);+ await touchUserSendInDb('sess-project', atMs);+ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ projectDir,+ atMs,+ process.platform,+ expect.objectContaining({ drizzle: h.fakeDb }),+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: projectDir,+ });+ });++ it.each([+ { source: 'scheduler', workspaceKind: 'project', remoteHostId: null },+ { source: 'desktop', workspaceKind: 'dialogue', remoteHostId: null },+ { source: 'desktop', workspaceKind: 'project', remoteHostId: 'ssh-host' },+ ])('does not retain unrelated workdirs: %j', async (fields) => {+ const atMs = 1_700_000_000_000;+ h.selectResults.push([+ {+ userSendAt: atMs,+ updatedAt: atMs,+ workingDir: '/repo',+ ...fields,+ },+ ]);+ await touchUserSendInDb('sess-other', atMs);+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ });++ it('suppresses project refresh after an owner switch during persistence', async () => {+ h.captureOwnerScope = true;+ const atMs = 1_700_000_000_000;+ h.selectResults.push([+ {+ userSendAt: atMs,+ updatedAt: atMs,+ workingDir: '/repo',+ source: 'desktop',+ workspaceKind: 'project',+ remoteHostId: null,+ },+ ]);+ h.upsertRecentWorkdir.mockImplementationOnce(async () => {+ h.ownerCurrent = false;+ return true;+ });+ await touchUserSendInDb('sess-project', atMs);+ expect(h.upsertRecentWorkdir).toHaveBeenCalled();+ expect(+ h.webContentsSend.mock.calls.filter(+ ([channel]) => channel === 'local-db:recent-workdirs:changed',+ ),+ ).toHaveLength(0);+ });+it('显式 atMs:UPDATE 落地后广播 ISO userSendAt(本机窗口 + device-link tap)', async () => {const atMs = 1_700_000_000_000;// auto-fill 默认行为(selectResults 为空,makeUpdateChain 自动填充 UPDATE 成功行)。@@ -167,6 +249,7 @@ describe('touchUserSendInDb 广播 sessions:patched(device-link 项目归属收expect(h.updateSetCalls).toHaveLength(1); // UPDATE 调用了,但 WHERE 阻止了写入expect(h.tapWindowBroadcast).not.toHaveBeenCalled();expect(h.webContentsSend).not.toHaveBeenCalled();+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();});it('MAX updatedAt: 广播使用 SELECT 读回的实际 updatedAt,防止 finishedAt 被 firedAt 回退', async () => {diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex ed600fc05b..af3c02db66 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -40,15 +40,21 @@ const h = vi.hoisted(() => ({}>,summarizeSession: vi.fn(async () => undefined),stopAndRemovePiSubagentRuns: vi.fn(async (_root: string) => true),- writePiSubagentDeletedTombstone: vi.fn(async (_agentHome: string, _sessionId: string) => undefined),- clearPiSubagentDeletedTombstone: vi.fn(async (_agentHome: string, _sessionId: string) => undefined),- getMakerIfReady: vi.fn((): {- isSessionAlive: (id: string) => boolean;- closeSession: (id: string) => Promise<void>;- } | null => null),+ writePiSubagentDeletedTombstone: vi.fn(+ async (_agentHome: string, _sessionId: string) => undefined,+ ),+ clearPiSubagentDeletedTombstone: vi.fn(+ async (_agentHome: string, _sessionId: string) => undefined,+ ),+ getMakerIfReady: vi.fn(+ (): {+ isSessionAlive: (id: string) => boolean;+ closeSession: (id: string) => Promise<void>;+ } | null => null,+ ),closeIdleSessionForMove: vi.fn(async (_sessionId: string) => true),- withRehydrateCloseSuppressed: vi.fn(- async (_sessionId: string, task: () => Promise<void>) => task(),+ withRehydrateCloseSuppressed: vi.fn(async (_sessionId: string, task: () => Promise<void>) =>+ task(),),setPinnedSectionCardMode: vi.fn(),upsertRecentWorkdir: vi.fn(@@ -151,6 +157,7 @@ import {setSessionRuntimeCleanup,setSessionWorktreeRecycle,updateSessionInDb,+ touchUserSendInDb,} from '../sessions';import { retireDeletedPiSubagentState } from '../piSubagentDeletion';import { setSessionRouteLockImplementation } from '../../sessionRouteLock';@@ -349,22 +356,27 @@ describe('local-db:sessions:update handler wiring', () => {});it('rejects new SSH writable roots because the picker is not on the remote filesystem', async () => {- await expect(invokeCreate({- id: 'ssh-forged',- agentKind: 'codex',- workingDir: '/remote/repo',- remoteHostId: 'host-1',- writableDirs: ['/remote/outside'],- })).rejects.toThrow(/can only be revoked/i);- expect(h.sqlite!.prepare('SELECT id FROM sessions WHERE id = ?').get('ssh-forged'))- .toBeUndefined();+ await expect(+ invokeCreate({+ id: 'ssh-forged',+ agentKind: 'codex',+ workingDir: '/remote/repo',+ remoteHostId: 'host-1',+ writableDirs: ['/remote/outside'],+ }),+ ).rejects.toThrow(/can only be revoked/i);+ expect(+ h.sqlite!.prepare('SELECT id FROM sessions WHERE id = ?').get('ssh-forged'),+ ).toBeUndefined();});it('rejects renderer-side directory grant writes outside the atomic maker handlers', async () => {- await expect(invokeUpdate('cc-local', { writableDirs: ['/forged'] }))- .rejects.toThrow(/maker:set-\*-dirs/i);- await expect(invokeUpdate('cc-local', { extraDirs: ['/forged-read'] }))- .rejects.toThrow(/maker:set-\*-dirs/i);+ await expect(invokeUpdate('cc-local', { writableDirs: ['/forged'] })).rejects.toThrow(+ /maker:set-\*-dirs/i,+ );+ await expect(invokeUpdate('cc-local', { extraDirs: ['/forged-read'] })).rejects.toThrow(+ /maker:set-\*-dirs/i,+ );});it('recovers cleanup only for deleted parent tasks after restart', async () => {@@ -399,7 +411,10 @@ describe('local-db:sessions:update handler wiring', () => {const userData = h.userDataDir!;const agentHome = path.join(userData, 'pi-agent-home');h.writePiSubagentDeletedTombstone.mockImplementation(- async () => new Promise((resolve) => { setTimeout(resolve, 40); }),+ async () =>+ new Promise((resolve) => {+ setTimeout(resolve, 40);+ }),);h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('pi-local');@@ -484,7 +499,11 @@ describe('local-db:sessions:update handler wiring', () => {// reporting success and its retry timer thrown away.const userData = h.userDataDir!;const runRoot = path.join(- userData, 'pi-agent-home', 'runtime', 'pi-subagent-runs', 'codex-local',+ userData,+ 'pi-agent-home',+ 'runtime',+ 'pi-subagent-runs',+ 'codex-local',);await mkdir(runRoot, { recursive: true });h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');@@ -500,7 +519,9 @@ describe('local-db:sessions:update handler wiring', () => {// the backoff retry re-enters the same body, and a parent that was alive// when one attempt gave up is exactly the case the later ones must recheck.await vi.waitFor(- () => { expect(closeSession.mock.calls.length).toBeGreaterThanOrEqual(2); },+ () => {+ expect(closeSession.mock.calls.length).toBeGreaterThanOrEqual(2);+ },{ timeout: 5_000 },);expect(closeSession).toHaveBeenCalledWith('codex-local');@@ -511,7 +532,9 @@ describe('local-db:sessions:update handler wiring', () => {// The parent finally goes away; the backoff retry re-runs the same gate.alive = false;await vi.waitFor(- () => { expect(h.stopAndRemovePiSubagentRuns).toHaveBeenCalledWith(runRoot); },+ () => {+ expect(h.stopAndRemovePiSubagentRuns).toHaveBeenCalledWith(runRoot);+ },{ timeout: 5_000 },);}, 20_000);@@ -521,7 +544,11 @@ describe('local-db:sessions:update handler wiring', () => {// time, and a launch entering the moment the scan declares the root empty.const userData = h.userDataDir!;const runRoot = path.join(- userData, 'pi-agent-home', 'runtime', 'pi-subagent-runs', 'codex-local',+ userData,+ 'pi-agent-home',+ 'runtime',+ 'pi-subagent-runs',+ 'codex-local',);await mkdir(runRoot, { recursive: true });h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');@@ -548,7 +575,9 @@ describe('local-db:sessions:update handler wiring', () => {});await resumeDeletedPiSubagentCleanup();- await vi.waitFor(() => { expect(h.stopAndRemovePiSubagentRuns).toHaveBeenCalled(); });+ await vi.waitFor(() => {+ expect(h.stopAndRemovePiSubagentRuns).toHaveBeenCalled();+ });// Cleanup reported success, so nothing will look at this task again: the// root has to be genuinely gone, with no orphan inside it.@@ -661,66 +690,44 @@ describe('local-db:sessions:update handler wiring', () => {);});- it('touches a retained local project when the generic writer archives it', async () => {- h.sqlite!- .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'plugin' WHERE id = ?")- .run('codex-local');- h.windows = [- { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },- ];- const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_050_000);-- try {- await invokeUpdate('codex-local', { status: 'archived' });- } finally {- now.mockRestore();- }-- expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(- '/old/dir',- 1_786_500_050_000,- process.platform,- h.client,- );- expect(h.windows[0]?.webContents.send).toHaveBeenCalledWith(- 'local-db:recent-workdirs:changed',- { path: '/old/dir' },+ it.each([+ ['generic', 'archived'],+ ['generic', 'deleted'],+ ['patch-meta', 'archived'],+ ['patch-meta', 'deleted'],+ ] as const)('preserves project activity through %s %s', async (writer, status) => {+ h.sqlite!.prepare(+ "UPDATE sessions SET workspace_kind = 'project', source = 'desktop' WHERE id = ?",+ ).run('codex-local');+ // Exercise the real upsert against this test's isolated SQLite database.+ const real = await vi.importActual<typeof import('../recentWorkdirs')>('../recentWorkdirs');+ h.upsertRecentWorkdir.mockImplementation(async (dir, atMs, platform) =>+ real.upsertRecentWorkdir(dir, atMs, platform),);- });-- it('touches a retained local project when patch-meta archives it', async () => {- h.sqlite!- .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")- .run('codex-local');- h.windows = [- { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },- ];- const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_150_000);+ const sentAt = 1_786_500_050_000;+ await touchUserSendInDb('codex-local', sentAt);+ h.upsertRecentWorkdir.mockClear();- try {- await invokePatchMeta('codex-local', { status: 'archived' });- } finally {- now.mockRestore();- }+ if (writer === 'generic') await invokeUpdate('codex-local', { status });+ else await invokePatchMeta('codex-local', { status });- expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(- '/old/dir',- 1_786_500_150_000,- process.platform,- h.client,- );- expect(h.windows[0]?.webContents.send).toHaveBeenCalledWith(- 'local-db:recent-workdirs:changed',- { path: '/old/dir' },- );+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.sqlite!.prepare('SELECT * FROM recent_workdirs').all()).toEqual([+ { path: '/old/dir', last_used_at: sentAt },+ ]);+ // Even physically removing the last task must leave the project's timestamp intact.+ h.sqlite!.prepare('DELETE FROM sessions WHERE id = ?').run('codex-local');+ expect(h.sqlite!.prepare('SELECT * FROM recent_workdirs').all()).toEqual([+ { path: '/old/dir', last_used_at: sentAt },+ ]);});it.each(['archived', 'deleted'] as const)('does not retain scheduler projects when the generic writer marks them %s',async (status) => {- h.sqlite!- .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'scheduler' WHERE id = ?")- .run('codex-local');+ h.sqlite!.prepare(+ "UPDATE sessions SET workspace_kind = 'project', source = 'scheduler' WHERE id = ?",+ ).run('codex-local');await invokeUpdate('codex-local', { status });@@ -729,20 +736,18 @@ describe('local-db:sessions:update handler wiring', () => {);it('suppresses the recent-project refresh after an owner switch', async () => {- h.sqlite!- .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")- .run('codex-local');+ h.sqlite!.prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?").run(+ 'codex-local',+ );h.captureOwnerScope = true;- h.windows = [- { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } },- ];+ h.windows = [{ isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } }];h.routeLock.mockImplementationOnce(async (_sessionId, task) => {const result = await task();h.ownerCurrent = false;return result;});- await invokeUpdate('codex-local', { status: 'archived' });+ await invokeUpdate('codex-local', { workspaceKind: 'project' });expect(h.upsertRecentWorkdir).toHaveBeenCalledWith('/old/dir',@@ -1029,9 +1034,9 @@ describe('local-db:sessions:update handler wiring', () => {it('rejects moving a local Pi/Codex session whose turn became active', async () => {h.closeIdleSessionForMove.mockResolvedValueOnce(false);- await expect(- invokeUpdate('codex-local', { workingDir: '/new/dir' }),- ).rejects.toThrow('[PRECONDITION_FAILED]');+ await expect(invokeUpdate('codex-local', { workingDir: '/new/dir' })).rejects.toThrow(+ '[PRECONDITION_FAILED]',+ );expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local'),diff --git a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.tsindex 1b0c80f919..770467dd71 100644--- a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts+++ b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts@@ -11,9 +11,9 @@* session 会经 upsertRecentWorkdir 重新入列,已迁移的死路径则一去不返。* recent 只影响项目列表展示,不再充当 device-link remote-workdir-guard* 的放行依据;远程入口始终实时探测目录当前是否可访问。- * - upsert 不暴露 IPC —— 由 main 内部在 session 创建和本地项目归档/删除路径上调用,- * 避免 renderer 私自污染该表。生命周期与 session 解耦:归档 / 删除不会移除目录;- * 两者都会刷新最后活动时间,确保清空会话后的项目仍服从同一活动筛选语义。+ * - upsert 不暴露 IPC —— 由 main 内部在 session 创建、项目归属变更和发送消息时调用,+ * 避免 renderer 私自污染该表。生命周期与 session 解耦:归档 / 删除既不移除目录,+ * 也不刷新最后活动时间;清空会话后仍按项目独立保存的时间筛选。* - upsert 失败仅日志,不抛 —— 这是"用户体验增强"数据,不该挡住 session 创建主流程。*/@@ -136,10 +136,7 @@ async function dirExists(path: string): Promise<boolean> {}}-function recentWorkdirProjectIdentity(- path: string,- localPlatform: NodeJS.Platform,-): string | null {+function recentWorkdirProjectIdentity(path: string, localPlatform: NodeJS.Platform): string | null {const grouped = normalizeWorkingDirForGrouping(path);if (!grouped) return null;return isCaseInsensitiveWindowsPath(grouped, localPlatform) ? grouped.toLowerCase() : grouped;@@ -180,9 +177,7 @@ export function registerRecentWorkdirsIpc(): void {path: r.path,lastUsedAt: new Date(r.lastUsedAt).toISOString(),exists: exists[i],- knownAgentKinds: Array.from(- (identity && knownKindsByPath.get(identity)) ?? [],- ).sort(),+ knownAgentKinds: Array.from((identity && knownKindsByPath.get(identity)) ?? []).sort(),};});});diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 9f94e83524..39601ac572 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -64,7 +64,10 @@ import {DESKTOP_VISIBLE_SESSION_SOURCES,isRetainableProjectSessionSource,} from '../../../shared/sessionSource.js';-import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';+import {+ normalizeWorkingDirForProjectSettings,+ normalizeWorkingDirForStorage,+} from '../../../shared/workingDir.js';import { assertRendererSessionSourceAllowed } from './sessionSourceGuard.js';import type { SessionReference } from '../../../shared/sessionReference.js';import * as broadcastTap from '../../device-link/broadcast-tap.js';@@ -880,7 +883,8 @@ export async function touchUserSendInDb(id: string, atMs?: number): Promise<voidconst ownerScope = captureOwnerScope();const ts =typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now();- const db = getDbClient().drizzle;+ const dbClient = getDbClient();+ const db = dbClient.drizzle;// 原子 guard:单条 UPDATE + WHERE 代替 SELECT→条件判断→UPDATE 三步走。// 旧实现存在 TOCTOU 竞态:两个并发调用(如 scheduler fire + 手动发送)都可能// 通过旧值检查后都执行 UPDATE,后写入的更早时间戳会覆盖已写入的更新值。@@ -904,7 +908,14 @@ export async function touchUserSendInDb(id: string, atMs?: number): Promise<void// 通过 SELECT 拿回实际落库的 updatedAt(已经是 MAX'd 结果)用于广播,// 避免把旧 ts 当作 updatedAt 广播给 renderer。const updated = await db- .select({ userSendAt: sessions.userSendAt, updatedAt: sessions.updatedAt })+ .select({+ userSendAt: sessions.userSendAt,+ updatedAt: sessions.updatedAt,+ workingDir: sessions.workingDir,+ workspaceKind: sessions.workspaceKind,+ remoteHostId: sessions.remoteHostId,+ source: sessions.source,+ }).from(sessions).where(and(eq(sessions.id, id), eq(sessions.userSendAt, ts))).limit(1);@@ -926,6 +937,19 @@ export async function touchUserSendInDb(id: string, atMs?: number): Promise<voidownerScope,);}+ // 项目独立保留真实使用时间;不能等归档/删除时再取清理时间,也不能从剩余任务重算。+ // 复用入口处的 client,避免 await 期间切换账号后把旧项目写入新账号数据库。+ const row = updated[0];+ if (+ row.workspaceKind === 'project' &&+ row.workingDir &&+ !row.remoteHostId &&+ isRetainableProjectSessionSource(row.source)+ ) {+ const projectDir = normalizeWorkingDirForProjectSettings(row.workingDir);+ const touched = await upsertRecentWorkdir(projectDir, ts, process.platform, dbClient);+ if (touched && projectDir) broadcastRecentWorkdirsChanged(projectDir, ownerScope);+ }}/** fork 出来的会话的占位标题前缀("[Fork] …" / "[Fork·已剥离] …")。 */@@ -1874,7 +1898,7 @@ export async function updateSessionInDb(// 否则「在新窗口打开」的副窗口无从得知会话已被移除,仍停留在旧视图(#3175)。const statusChanged = p.status !== undefined;if (- (projectTargetChanged || p.status === 'deleted' || p.status === 'archived') &&+ projectTargetChanged &&row.workspaceKind === 'project' &&row.workingDir &&!row.remoteHostId &&@@ -1998,7 +2022,7 @@ export async function patchSessionMetaInDb(const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。if (patch.title !== undefined) noteUserTitleWritten(sessionId);- const { updated, source } = await withStatusWriteLock(db, sessionId, patch.status, async () => {+ const updated = await withStatusWriteLock(db, sessionId, patch.status, async () => {if (patch.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sessionId);await writeSessionPatch(db, sessionId, setObj, patch.status);const row = await selectSessionWithCount(db, sessionId);@@ -2008,23 +2032,8 @@ export async function patchSessionMetaInDb(row.summary = null;}cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);- return { updated: sessionToCamel(row), source: row.source };+ return sessionToCamel(row);});- if (- (patch.status === 'deleted' || patch.status === 'archived') &&- updated.workspaceKind === 'project' &&- updated.workingDir &&- !updated.remoteHostId &&- isRetainableProjectSessionSource(source)- ) {- const touched = await upsertRecentWorkdir(- updated.workingDir,- Date.now(),- process.platform,- dbClient,- );- if (touched) broadcastRecentWorkdirsChanged(updated.workingDir, ownerScope);- }notifyAgentIslandSessionPatch(updated.id, {status: updated.status,title: updated.title,@@ -2229,23 +2238,6 @@ export async function setSessionsStatusInDb(for (const item of applied) {compactTerminalSessionToolResults(dbClient, item.sessionId, item.status);}- if (status === 'archived') {- const touchedAt = Date.now();- const localProjectDirs = new Set(- applied.flatMap((item) =>- item.workspaceKind === 'project' &&- item.workingDir &&- !item.remoteHostId &&- isRetainableProjectSessionSource(item.source)- ? [item.workingDir]- : [],- ),- );- for (const workingDir of localProjectDirs) {- const touched = await upsertRecentWorkdir(workingDir, touchedAt, process.platform, dbClient);- if (touched) broadcastRecentWorkdirsChanged(workingDir, ownerScope);- }- }if (!isOwnerScopeCurrent(ownerScope))return applied.map((item) => ({sessionId: item.sessionId,diff --git a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts b/apps/desktop/src/renderer/lib/recentWorkdirsStore.tsindex 6c83ac541b..f752ac1057 100644--- a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts+++ b/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts@@ -13,8 +13,8 @@* (main 端 session 创建广播 = 可能新增了 recent_workdirs row)* - 调用方 (hook) 也可以主动调 forceRefresh*- * 普通字段变更 (rename / pin) 不影响 recent_workdirs;归档 / 删除会由 main 刷新- * lastUsedAt,并经 recentWorkdirs.onChanged 触发强制重拉。+ * 普通字段变更 (rename / pin) 与归档 / 删除不影响 recent_workdirs;发送消息会由 main+ * 刷新 lastUsedAt,并经 recentWorkdirs.onChanged 触发强制重拉。*/import {@@ -46,9 +46,8 @@ function notify(): void {async function fetchList(): Promise<RecentWorkdirEntry[]> {// window.electronAPI 在 SSR / 测试 / preload 未就绪场景可能不存在 —— 直接返回空。- const api = (typeof window !== 'undefined'- ? window.electronAPI?.localDb?.recentWorkdirs- : undefined);+ const api =+ typeof window !== 'undefined' ? window.electronAPI?.localDb?.recentWorkdirs : undefined;if (!api) return [];return api.list();}@@ -128,9 +127,8 @@ export const recentWorkdirsStore = {cache = cache.filter((e) => e.path !== path);notify();}- const api = (typeof window !== 'undefined'- ? window.electronAPI?.localDb?.recentWorkdirs- : undefined);+ const api =+ typeof window !== 'undefined' ? window.electronAPI?.localDb?.recentWorkdirs : undefined;if (!api) return;try {await api.remove({ path });@@ -164,7 +162,7 @@ if (typeof window !== 'undefined') {});});}- // 变更广播:显式移除与软删除 activity touch 都会改变持久目录投影;强制重拉+ // 变更广播:显式移除与发送消息 都会改变持久目录投影;强制重拉// 保证本窗口的 lastActivity 过滤立即看到新时间,而不是等下一次 session 创建。const recentApi = window.electronAPI?.localDb?.recentWorkdirs;if (recentApi?.onChanged) {