Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): retain archived project activity
zyaoiie3e83d4c095d
diff --git a/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.ts b/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.tsindex 1775e37330..5614abc622 100644--- a/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.ts+++ b/apps/desktop/drizzle/scripts/0090_retain_all_recent_workdirs.ts@@ -1,6 +1,7 @@import type Database from 'better-sqlite3';function canonicalize(raw: string, platform: NodeJS.Platform): string | null {+ void platform;let path = raw.trim().replace(/\\/g, '/');while (path.length > 1 && path.endsWith('/')) {if (/^[A-Za-z]:\/$/.test(path)) break;@@ -45,14 +46,16 @@ function runForPlatform(db: Database.Database, platform: NodeJS.Platform): void(column) => column.name,),);- if (sessionColumns.has('working_dir')) {+ // Missing/unknown provenance must not turn automation workdirs into durable user projects.+ // `source` predates every supported runtime schema, but sparse replay fixtures may omit it.+ if (sessionColumns.has('working_dir') && sessionColumns.has('source')) {const timestampColumns = ['user_send_at', 'updated_at', 'created_at'].filter((column) =>sessionColumns.has(column),);const timestampExpression =timestampColumns.length > 0 ? `COALESCE(${timestampColumns.join(', ')}, 0)` : '0';const predicates = ['working_dir IS NOT NULL', "TRIM(working_dir) != ''"];- if (sessionColumns.has('source')) predicates.push("source = 'desktop'");+ predicates.push("source IN ('desktop', 'plugin')");if (sessionColumns.has('workspace_kind')) predicates.push("workspace_kind = 'project'");if (sessionColumns.has('remote_host_id')) predicates.push('remote_host_id IS NULL');diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex 2501763ee5..38f98b8370 100644--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@ -30,6 +30,8 @@ const h = vi.hoisted(() => ({removeSessionRefs: vi.fn(),recycleWorktreeForRemovedSession: vi.fn(),isOwnerScopeCurrent: vi.fn(),+ upsertRecentWorkdir: vi.fn(async () => true),+ captureOwnerScope: false,drizzle: {},userDataPath: '',agentIslandService: {@@ -55,9 +57,13 @@ vi.mock('../cindy-media/ledger', () => ({}));vi.mock('../localDb/dialogueWorkspace', () => ({ ensureDialogueWorkspaceDir: vi.fn() }));vi.mock('../git-context/prRefsStore', () => ({ recomputePrRefsForSession: vi.fn() }));-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: h.isOwnerScopeCurrent,tapWindowBroadcast: h.tapWindowBroadcast,@@ -95,6 +101,8 @@ beforeEach(() => {h.removeSessionRefs.mockResolvedValue(0);h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);h.isOwnerScopeCurrent.mockReturnValue(true);+ h.upsertRecentWorkdir.mockResolvedValue(true);+ h.captureOwnerScope = false;setSessionRemovalCancelOperations(h.cancelSessionOperations);setSessionRemovalCleanup(h.cleanupRemovedSession);setSessionRouteLockImplementation(h.withSendToSessionLock);@@ -178,6 +186,125 @@ describe('setSessionsStatusInDb', () => {expect(h.closeSession).not.toHaveBeenCalled();expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();+ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ });++ it.each(['desktop', 'plugin'] as const)(+ 'touches retained local %s projects when batch archiving and broadcasts the refresh',+ async (source) => {+ h.tx.mockResolvedValueOnce([+ {+ sessionId: 's1',+ title: 'T1',+ workingDir: '/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source,+ status: 'archived',+ },+ ]);+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_200_000);++ try {+ await setSessionsStatusInDb(['s1'], 'archived');+ } finally {+ now.mockRestore();+ }++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/repo',+ 1_786_500_200_000,+ process.platform,+ expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/repo',+ });+ },+ );++ it('does not retain remote or dialogue workdirs during batch archive', async () => {+ h.tx.mockResolvedValueOnce([+ {+ sessionId: 'remote',+ title: 'Remote',+ workingDir: '/remote/repo',+ workspaceKind: 'project',+ remoteHostId: 'host-a',+ source: 'desktop',+ status: 'archived',+ },+ {+ sessionId: 'dialogue',+ title: 'Dialogue',+ workingDir: '/managed/dialogue',+ workspaceKind: 'dialogue',+ remoteHostId: null,+ source: 'desktop',+ status: 'archived',+ },+ ]);++ await setSessionsStatusInDb(['remote', 'dialogue'], 'archived');++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );+ });++ it('does not retain scheduler projects during batch archive', async () => {+ h.tx.mockResolvedValueOnce([+ {+ sessionId: 'scheduled',+ title: 'Scheduled',+ workingDir: '/scheduled/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source: 'scheduler',+ status: 'archived',+ },+ ]);++ await setSessionsStatusInDb(['scheduled'], 'archived');++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );+ });++ it('touches the entry database but suppresses the batch refresh after an owner switch', async () => {+ h.captureOwnerScope = true;+ h.tx.mockImplementationOnce(async () => {+ h.isOwnerScopeCurrent.mockReturnValue(false);+ return [+ {+ sessionId: 's1',+ title: 'T1',+ workingDir: '/repo',+ workspaceKind: 'project',+ remoteHostId: null,+ source: 'desktop',+ status: 'archived',+ },+ ];+ });++ await setSessionsStatusInDb(['s1'], 'archived');++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/repo',+ expect.any(Number),+ process.platform,+ expect.objectContaining({ tx: h.tx, drizzle: h.drizzle }),+ );+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );});it('acquires overlapping batch route locks once in stable order', async () => {diff --git a/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts b/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.tsindex f36430b301..57e8c1b6bd 100644--- a/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/retainAllRecentWorkdirsMigration.test.ts@@ -35,6 +35,7 @@ function seedSession(input: {id: string;path: string;timestamp: number;+ source?: string;status?: string;remoteHostId?: string | null;}): void {@@ -42,9 +43,10 @@ function seedSession(input: {`INSERT INTO sessions (id, source, workspace_kind, remote_host_id, working_dir, status,user_send_at, updated_at, created_at- ) VALUES (?, 'desktop', 'project', ?, ?, ?, ?, ?, ?)`,+ ) VALUES (?, ?, 'project', ?, ?, ?, ?, ?, ?)`,).run(input.id,+ input.source ?? 'desktop',input.remoteHostId ?? null,input.path,input.status ?? 'active',@@ -78,6 +80,36 @@ describe('0090 retain all recent workdirs migration', () => {expect(recentRows()).toContainEqual({ path: '/workspace/project-0', last_used_at: 1_000 });});+ it('backfills historical local plugin projects without admitting scheduler workdirs', () => {+ seedSession({+ id: 'plugin-archived',+ path: '/workspace/plugin-project',+ timestamp: 2_000,+ source: 'plugin',+ status: 'archived',+ });+ seedSession({+ id: 'scheduler-archived',+ path: '/workspace/scheduler-project',+ timestamp: 3_000,+ source: 'scheduler',+ status: 'archived',+ });+ seedSession({+ id: 'unknown-archived',+ path: '/workspace/unknown-project',+ timestamp: 4_000,+ source: 'future-source',+ status: 'archived',+ });++ migration.run(db);++ expect(recentRows()).toEqual([+ { path: '/workspace/plugin-project', last_used_at: 2_000 },+ ]);+ });+it('normalizes duplicate path spellings and keeps the newest activity time', () => {seedSession({ id: 'old', path: 'D:\\work\\project-a\\', timestamp: 1_000 });seedSession({ id: 'new', path: 'D:/work/project-a', timestamp: 2_000 });@@ -119,7 +151,7 @@ describe('0090 retain all recent workdirs migration', () => {expect(recentRows()).toEqual([{ path: '/workspace/local', last_used_at: 3_000 }]);});- it('replays safely against a sparse legacy sessions table', () => {+ it('fails closed against a sparse legacy sessions table without source provenance', () => {db.exec(`DROP TABLE sessions;CREATE TABLE sessions (@@ -129,11 +161,15 @@ describe('0090 retain all recent workdirs migration', () => {);INSERT INTO sessions (id, working_dir, created_at)VALUES ('legacy', '/workspace/legacy', 4000);+ INSERT INTO recent_workdirs (path, last_used_at)+ VALUES ('/workspace/already-retained', 3000);`);migration.run(db);- expect(recentRows()).toEqual([{ path: '/workspace/legacy', last_used_at: 4_000 }]);+ expect(recentRows()).toEqual([+ { path: '/workspace/already-retained', last_used_at: 3_000 },+ ]);});it('deduplicates legacy Windows drive and UNC casing identities', () => {@@ -153,12 +189,24 @@ describe('0090 retain all recent workdirs migration', () => {'//server/share/project-b',5_000,);+ db.prepare('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)').run(+ 'D:/ÉCOLE/Plugin-Project',+ 5_500,+ );+ seedSession({+ id: 'plugin-windows',+ path: 'd:/école/plugin-project',+ timestamp: 6_000,+ source: 'plugin',+ status: 'archived',+ });migration.runForPlatform(db, 'win32');expect(recentRows()).toEqual([{ path: '//server/share/project-b', last_used_at: 5_000 },{ path: 'D:/Work/Project-A', last_used_at: 3_000 },+ { path: 'd:/école/plugin-project', last_used_at: 6_000 },]);});diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 7dfc1094ef..95741b8c68 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -695,7 +695,7 @@ function sessionsSetStatus(readyDb, args) {'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',);const updateSession = readyDb.prepare(- 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',);return readyDb.transaction(() => {const applied = [];@@ -715,6 +715,8 @@ function sessionsSetStatus(readyDb, args) {title: updated.title,workingDir: updated.workingDir,workspaceKind: updated.workspaceKind,+ remoteHostId: updated.remoteHostId,+ source: updated.source,status,});}diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex de5988fc06..3c6bc52f3b 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -50,6 +50,8 @@ CREATE TABLE sessions (agent_kind TEXT NOT NULL DEFAULT 'cc',orca_role TEXT,workspace_kind TEXT NOT NULL DEFAULT 'project',+ remote_host_id TEXT,+ source TEXT DEFAULT 'desktop',codex_history_has_product_prompt INTEGER,parent_session_id TEXT,forked_at_message_id TEXT,@@ -2131,6 +2133,45 @@ describe('db worker tx handlers', () => {});});+ it.each([+ { label: 'bundled worker', useInlineWorker: false },+ { label: 'inline worker', useInlineWorker: true },+ ])(+ 'returns remote host identity through sessions.setStatus in the $label path',+ async ({ useInlineWorker }) => {+ await withClient(+ async (client) => {+ await seedSession(client, 'local', { workingDir: '/local/repo' });+ await seedSession(client, 'remote', { workingDir: '/remote/repo' });+ await client.exec('UPDATE sessions SET remote_host_id = ? WHERE id = ?', [+ 'host-a',+ 'remote',+ ]);+ await client.exec('UPDATE sessions SET source = ? WHERE id = ?', ['plugin', 'remote']);++ await expect(+ client.tx('sessions.setStatus', {+ sessionIds: ['local', 'remote'],+ status: 'archived',+ }),+ ).resolves.toEqual([+ expect.objectContaining({+ sessionId: 'local',+ remoteHostId: null,+ source: 'desktop',+ }),+ expect.objectContaining({+ sessionId: 'remote',+ remoteHostId: 'host-a',+ source: 'plugin',+ }),+ ]);+ },+ { useInlineWorker },+ );+ },+ );+it.each([{ label: 'bundled worker', useInlineWorker: false },{ label: 'inline worker', useInlineWorker: true },diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex e17b90b595..020083074d 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -344,6 +344,8 @@ export interface SessionsSetStatusResultItem {title: string | null;workingDir: string | null;workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;status: 'active' | 'archived';}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 65dc185d72..99179c044e 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -35,7 +35,13 @@ const h = vi.hoisted(() => ({_atMs?: number,_platform?: NodeJS.Platform,_client?: { drizzle: ReturnType<typeof drizzle> },- ) => true,+ ) => {+ void _path;+ void _atMs;+ void _platform;+ void _client;+ return true;+ },),captureOwnerScope: false,ownerCurrent: true,@@ -225,6 +231,43 @@ describe('local-db:sessions:update handler wiring', () => {});});+ it('touches the retained local project at the archive activity time', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'plugin' WHERE id = ?")+ .run('codex-local');+ 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.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/old/dir',+ });+ });++ it('does not retain scheduler projects when the generic update archives them', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'scheduler' WHERE id = ?")+ .run('codex-local');++ await invokeUpdate('codex-local', { status: 'archived' });++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );+ });+it('touches the retained local project when device-link soft-deletes through patch-meta', async () => {h.sqlite!.prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")@@ -248,57 +291,97 @@ describe('local-db:sessions:update handler wiring', () => {});});- it('touches only the handler-entry database and suppresses broadcast after owner switch', async () => {+ it('touches the retained local project when device-link archives through patch-meta', async () => {h.sqlite!.prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?").run('codex-local');- const oldClient = h.client!;- const nextSqlite = new Database(':memory:');- nextSqlite.exec(`- CREATE TABLE recent_workdirs (- path TEXT PRIMARY KEY NOT NULL,- last_used_at INTEGER NOT NULL- );- `);- const nextClient = { drizzle: drizzle(nextSqlite, { schema: { recentWorkdirs } }) };- h.captureOwnerScope = true;- h.upsertRecentWorkdir.mockImplementation(- async (- _path: string | null | undefined,- atMs?: number,- _platform?: NodeJS.Platform,- client?: typeof oldClient,- ) => {- await client!.drizzle- .insert(recentWorkdirs)- .values({ path: '/old/dir', lastUsedAt: atMs! });- return true;- },- );- h.routeLock.mockImplementation(async (_sessionId, task) => {- const result = await task();- h.client = nextClient as typeof h.client;- h.ownerCurrent = false;- return result;- });+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_786_500_150_000);try {- await invokeUpdate('codex-local', { status: 'deleted' });-- expect(- h.sqlite!.prepare('SELECT path FROM recent_workdirs').all(),- ).toEqual([{ path: '/old/dir' }]);- expect(nextSqlite.prepare('SELECT path FROM recent_workdirs').all()).toEqual([]);- expect(h.webContentsSend).not.toHaveBeenCalledWith(- 'local-db:recent-workdirs:changed',- expect.anything(),- expect.anything(),- );+ await invokePatchMeta('codex-local', { status: 'archived' });} finally {- nextSqlite.close();+ now.mockRestore();}++ expect(h.upsertRecentWorkdir).toHaveBeenCalledWith(+ '/old/dir',+ 1_786_500_150_000,+ process.platform,+ h.client,+ );+ expect(h.webContentsSend).toHaveBeenCalledWith('local-db:recent-workdirs:changed', {+ path: '/old/dir',+ });+ });++ it('does not retain scheduler projects when patch-meta archives them', async () => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project', source = 'scheduler' WHERE id = ?")+ .run('codex-local');++ await invokePatchMeta('codex-local', { status: 'archived' });++ expect(h.upsertRecentWorkdir).not.toHaveBeenCalled();+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ );});+ it.each(['deleted', 'archived'] as const)(+ 'touches only the handler-entry database and suppresses broadcast after owner switch for %s',+ async (status) => {+ h.sqlite!+ .prepare("UPDATE sessions SET workspace_kind = 'project' WHERE id = ?")+ .run('codex-local');+ type CurrentClient = NonNullable<typeof h.client>;+ const nextSqlite = new Database(':memory:');+ nextSqlite.exec(`+ CREATE TABLE recent_workdirs (+ path TEXT PRIMARY KEY NOT NULL,+ last_used_at INTEGER NOT NULL+ );+ `);+ const nextClient = { drizzle: drizzle(nextSqlite, { schema: { recentWorkdirs } }) };+ h.captureOwnerScope = true;+ h.upsertRecentWorkdir.mockImplementation(+ async (+ _path: string | null | undefined,+ atMs?: number,+ _platform?: NodeJS.Platform,+ client?: CurrentClient,+ ) => {+ await client!.drizzle+ .insert(recentWorkdirs)+ .values({ path: '/old/dir', lastUsedAt: atMs! });+ return true;+ },+ );+ h.routeLock.mockImplementation(async (_sessionId, task) => {+ const result = await task();+ h.client = nextClient as typeof h.client;+ h.ownerCurrent = false;+ return result;+ });++ try {+ await invokeUpdate('codex-local', { status });++ expect(h.sqlite!.prepare('SELECT path FROM recent_workdirs').all()).toEqual([+ { path: '/old/dir' },+ ]);+ expect(nextSqlite.prepare('SELECT path FROM recent_workdirs').all()).toEqual([]);+ expect(h.webContentsSend).not.toHaveBeenCalledWith(+ 'local-db:recent-workdirs:changed',+ expect.anything(),+ expect.anything(),+ );+ } finally {+ nextSqlite.close();+ }+ },+ );+it('does not resurrect a deleted task through the generic status writer', async () => {h.sqlite!.prepare("UPDATE sessions SET status = 'deleted' WHERE id = ?").run('codex-local');diff --git a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.tsindex 7858a04cf6..1b0c80f919 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 创建和本地项目软删除路径上调用,+ * - upsert 不暴露 IPC —— 由 main 内部在 session 创建和本地项目归档/删除路径上调用,* 避免 renderer 私自污染该表。生命周期与 session 解耦:归档 / 删除不会移除目录;- * 软删除会刷新最后活动时间,确保清空会话后的项目仍服从同一活动筛选语义。+ * 两者都会刷新最后活动时间,确保清空会话后的项目仍服从同一活动筛选语义。* - upsert 失败仅日志,不抛 —— 这是"用户体验增强"数据,不该挡住 session 创建主流程。*/diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex d860156cc4..b6509c5b78 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -35,7 +35,10 @@ import { removeSessionRefsIfDeleted as removeDeletedSessionMediaRefs } from '../import { removeWechatSessionAttachmentDir } from '../../im/wechat/mediaStaging';import { upsertRecentWorkdir } from './recentWorkdirs';import { createLogger } from '../../logger';-import { DESKTOP_VISIBLE_SESSION_SOURCES } from '../../../shared/sessionSource.js';+import {+ DESKTOP_VISIBLE_SESSION_SOURCES,+ isRetainableProjectSessionSource,+} from '../../../shared/sessionSource.js';import { normalizeWorkingDirForStorage } from '../../../shared/workingDir.js';import type { SessionReference } from '../../../shared/sessionReference.js';import * as broadcastTap from '../../device-link/broadcast-tap.js';@@ -1501,10 +1504,11 @@ export function registerSessionIpc(const settingsChanged = Object.keys(p).some((key) => REMOTE_PERSIST_FIELDS.has(key));const titleChanged = p.title !== undefined;if (- (projectTargetChanged || p.status === 'deleted') &&+ (projectTargetChanged || p.status === 'deleted' || p.status === 'archived') &&row.workspaceKind === 'project' &&row.workingDir &&- !row.remoteHostId+ !row.remoteHostId &&+ isRetainableProjectSessionSource(row.source)) {const touched = await upsertRecentWorkdir(row.workingDir,@@ -1601,17 +1605,18 @@ export async function patchSessionMetaInDb(const setObj = sessionPatchToRow(patch, { bumpUpdatedAt: false });// 控制端远程改名走这条,与本机改名同口径(同样先记号后写库)。if (patch.title !== undefined) noteUserTitleWritten(sessionId);- const updated = await withStatusWriteLock(sessionId, patch.status, async () => {+ const { updated, source } = await withStatusWriteLock(sessionId, patch.status, async () => {await writeSessionPatch(db, sessionId, setObj, patch.status);const row = await selectSessionWithCount(db, sessionId);if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');- return sessionToCamel(row);+ return { updated: sessionToCamel(row), source: row.source };});if (- patch.status === 'deleted' &&+ (patch.status === 'deleted' || patch.status === 'archived') &&updated.workspaceKind === 'project' &&updated.workingDir &&- !updated.remoteHostId+ !updated.remoteHostId &&+ isRetainableProjectSessionSource(source)) {const touched = await upsertRecentWorkdir(updated.workingDir,@@ -1772,6 +1777,28 @@ export async function setSessionsStatusInDb(throw err;}),);+ 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/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex f8e9ac2d34..60b0aca4d9 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -590,6 +590,8 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{title: string | null;workingDir: string | null;workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;status: 'active' | 'archived';}> {const payload = asRecord(args, 'sessions.setStatus args');@@ -604,7 +606,7 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{'SELECT id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, status FROM sessions WHERE id = ? LIMIT 1',);const updateSession = db.prepare(- 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind',+ 'UPDATE sessions SET status = ?, updated_at = ? WHERE id = ? RETURNING id, title, working_dir AS workingDir, workspace_kind AS workspaceKind, remote_host_id AS remoteHostId, source',);const transaction = db.transaction(() => {const applied: Array<{@@ -612,6 +614,8 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{title: string | null;workingDir: string | null;workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;status: 'active' | 'archived';}> = [];const now = Date.now();@@ -626,7 +630,14 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{});}const updated = updateSession.get(status, now, sessionId) as- | { id: string; title: string | null; workingDir: string | null; workspaceKind: string | null }+ | {+ id: string;+ title: string | null;+ workingDir: string | null;+ workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;+ }| undefined;if (!updated) {throw Object.assign(new Error(`Session 不存在: ${sessionId}`), { code: 'NOT_FOUND' });@@ -636,6 +647,8 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{title: updated.title,workingDir: updated.workingDir,workspaceKind: updated.workspaceKind,+ remoteHostId: updated.remoteHostId,+ source: updated.source,status,});}@@ -646,6 +659,8 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{title: string | null;workingDir: string | null;workspaceKind: string | null;+ remoteHostId: string | null;+ source: string | null;status: 'active' | 'archived';}>;}diff --git a/apps/desktop/src/renderer/lib/recentWorkdirsStore.ts b/apps/desktop/src/renderer/lib/recentWorkdirsStore.tsindex de06243f0c..6c83ac541b 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 / archive) 不影响 recent_workdirs;软删除会由 main- * 刷新 lastUsedAt,并经 recentWorkdirs.onChanged 触发强制重拉。+ * 普通字段变更 (rename / pin) 不影响 recent_workdirs;归档 / 删除会由 main 刷新+ * lastUsedAt,并经 recentWorkdirs.onChanged 触发强制重拉。*/import {diff --git a/apps/desktop/src/shared/__tests__/sessionSource.test.ts b/apps/desktop/src/shared/__tests__/sessionSource.test.tsnew file mode 100644index 0000000000..0e8b51e83a--- /dev/null+++ b/apps/desktop/src/shared/__tests__/sessionSource.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { isRetainableProjectSessionSource } from '../sessionSource.js';++describe('isRetainableProjectSessionSource', () => {+ it.each(['desktop', 'plugin'] as const)('accepts the durable %s project source', (source) => {+ expect(isRetainableProjectSessionSource(source)).toBe(true);+ });++ it.each([undefined, null, '', 'scheduler', 'future-source'])(+ 'fails closed for missing or unknown source %j',+ (source) => {+ expect(isRetainableProjectSessionSource(source)).toBe(false);+ },+ );+});diff --git a/apps/desktop/src/shared/sessionSource.ts b/apps/desktop/src/shared/sessionSource.tsindex 5c7300bfa8..b49f4f78ff 100644--- a/apps/desktop/src/shared/sessionSource.ts+++ b/apps/desktop/src/shared/sessionSource.ts@@ -17,6 +17,25 @@ export const SESSION_SOURCES = [export type SessionSource = (typeof SESSION_SOURCES)[number];+/**+ * Only sessions whose project directory was explicitly chosen by the user belong in the+ * durable recent-project registry. Keep historical migration 0090's SQL allowlist aligned.+ */+export const RETAINABLE_PROJECT_SESSION_SOURCES = [+ 'desktop',+ 'plugin',+] as const satisfies readonly SessionSource[];++export type RetainableProjectSessionSource =+ (typeof RETAINABLE_PROJECT_SESSION_SOURCES)[number];++/** Fail closed for legacy/malformed rows whose source is missing or unknown. */+export function isRetainableProjectSessionSource(+ source: unknown,+): source is RetainableProjectSessionSource {+ return source === 'desktop' || source === 'plugin';+}+export function isReviewSessionSource(source: unknown): source is 'review' {return source === 'review';}