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): 修复任务归档卡顿与状态路由冲突 (#3517)

DavidShenXD596d4f927030
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 3df4ff37b9..2a10b3ff4d 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -29,6 +29,7 @@ const h = vi.hoisted(() => ({
cleanupRemovedSession: vi.fn(),
runtimeCleanup: vi.fn(),
removeSessionRefs: vi.fn(),
+ hasRegisteredWorktreeForSession: vi.fn(),
recycleWorktreeForRemovedSession: vi.fn(),
isOwnerScopeCurrent: vi.fn(),
drizzle: {},
@@ -75,6 +76,7 @@ vi.mock('../maker-ipc/register.js', () => ({
}));
vi.mock('../worktree/sessionRemovalRecycle.js', () => ({
isSessionStillRemovable: h.isSessionStillRemovable,
+ hasRegisteredWorktreeForSession: h.hasRegisteredWorktreeForSession,
recycleWorktreeForRemovedSession: h.recycleWorktreeForRemovedSession,
}));
import {
@@ -95,6 +97,7 @@ beforeEach(() => {
h.cancelSessionOperations.mockResolvedValue(undefined);
h.cleanupRemovedSession.mockResolvedValue(undefined);
h.removeSessionRefs.mockResolvedValue(0);
+ h.hasRegisteredWorktreeForSession.mockReturnValue(true);
h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);
h.isOwnerScopeCurrent.mockReturnValue(true);
setSessionRemovalCancelOperations(h.cancelSessionOperations);
@@ -287,8 +290,8 @@ describe('setSessionsStatusInDb', () => {
});
it('broadcasts worktree:changed only after the recycle chain finishes', async () => {
- // renderer 的 WorktreeContext 靠这条推送才能拿到回收后的快照 —— 回收是异步链,
- // 状态 IPC 返回时 store 条目还在,归档动作里那次「顺手 refresh」必然是旧的。
+ // renderer 靠这条推送按 sessionId 查询回收后的真实状态;状态 IPC 返回时
+ // store 条目仍可能存在,不能提前发送。
h.tx.mockResolvedValueOnce([
{
sessionId: 's1',
@@ -329,7 +332,7 @@ describe('setSessionsStatusInDb', () => {
});
it('still broadcasts worktree:changed when the recycle chain fails', async () => {
- // 回收失败/跳过时条目仍在 store 里,重拉拿到「徽标还在」也是真实状态。
+ // 回收失败时条目仍在 store 里,单条查询拿到「徽标还在」也是真实状态。
h.tx.mockResolvedValueOnce([
{
sessionId: 's1',
@@ -350,6 +353,18 @@ describe('setSessionsStatusInDb', () => {
});
});
+ it('does not broadcast worktree:changed for a session without a registered worktree', async () => {
+ h.hasRegisteredWorktreeForSession.mockReturnValue(false);
+
+ await recycleSessionWorktreeForStatusChange('notification', 'archived');
+
+ expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
+ 'notification',
+ expect.objectContaining({ scanOwners: true }),
+ );
+ expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', expect.anything());
+ });
+
it('does not broadcast worktree:changed when restoring to active', async () => {
h.tx.mockResolvedValueOnce([
{
@@ -484,6 +499,9 @@ describe('recycleSessionWorktreeForStatusChange', () => {
if (sessionId === 'shared') await options?.recycleOwner?.('owner');
},
);
+ h.hasRegisteredWorktreeForSession.mockImplementation(
+ (sessionId: string) => sessionId === 'owner',
+ );
await recycleSessionWorktreeForStatusChange('shared', 'archived');
@@ -506,6 +524,12 @@ describe('recycleSessionWorktreeForStatusChange', () => {
recycleOwner: expect.any(Function),
}),
);
+ expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', {
+ sessionId: 'owner',
+ });
+ expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', {
+ sessionId: 'shared',
+ });
});
it('passes current Maker runtime liveness into the low-level live-reference guard', async () => {
@@ -559,7 +583,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.isSessionStillRemovable).not.toHaveBeenCalled();
expect(h.closeSession).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
- expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
+ expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', expect.anything());
});
it('does not remove media or recycle the worktree when Simulator cleanup fails', async () => {
@@ -572,7 +596,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.closeSession).not.toHaveBeenCalled();
expect(h.removeSessionRefs).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
- expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
+ expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', expect.anything());
});
it('does not dynamically import the Simulator Host from the recycle path', () => {
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 24158fe110..3188a7ab6e 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -249,13 +249,11 @@ export function broadcastSessionPatched(
}
/**
- * worktree 回收真正跑完后通知本机所有窗口重拉 worktree 快照。
+ * worktree 回收真正跑完后通知本机所有窗口更新对应 session 的 worktree 缓存。
*
- * 没有这条推送,renderer 只能在归档/删除动作里"顺手"刷一次 worktree map,而回收
- * 是下面 fire-and-forget 的异步链(动态 import → 关子进程 → git worktree remove →
- * 文件系统清理),store 条目被移除的时刻远晚于状态 IPC 返回。renderer 那次刷新会
- * 快照到仍然存在的旧条目,归档列表上的 worktree 徽标就一直陈旧,直到某次无关的
- * 刷新才纠正(codex review P1)。
+ * 回收是下面 fire-and-forget 的异步链(动态 import → 关子进程 → git worktree remove →
+ * 文件系统清理),store 条目被移除的时刻远晚于状态 IPC 返回。这条推送提供回收完成的
+ * 权威时机;payload 保持为单个 sessionId,renderer 不需要重拉全表。
*
* 只广播给本机窗口、不进 device-link tap:控制端(手机/另一台桌面)的远程会话
* worktree 元数据走 device-link 自己的镜像链路,不经本机 WorktreeContext。
@@ -277,8 +275,10 @@ function broadcastWorktreeChanged(sessionId: string): void {
* 反向 import 本文件的 setWorktreePathInDb)。Simulator 清理由启动组合层静态注入,
* 避免在回收临界路径上延迟加载带原生副作用的 Host 模块。
*
- * 回收链结束后(无论成功、跳过还是失败)都广播一次 worktree:changed —— 失败/跳过
- * 时条目仍在 store 里,重拉拿到的就是"徽标还在"这个真实状态,同样是对的。
+ * 只为真正进入低层 worktree 回收的 session 广播。普通通知任务没有 worktree,仍会
+ * 完成 runtime / media / owner 扫描,但不会让 renderer 扫描全部 worktree。共享路径
+ * 扫描若找到另一个终态 owner,则通知 owner 的 sessionId,而不是原任务的 sessionId。
+ * 回收失败时仍广播:renderer 单条查询后会保留仍在 store 中的真实状态。
*/
export async function recycleSessionWorktreeForStatusChange(
sessionId: string,
@@ -286,6 +286,7 @@ export async function recycleSessionWorktreeForStatusChange(
capturedScope?: SessionRecycleScope,
): Promise<void> {
if (status !== 'deleted' && status !== 'archived') return;
+ const affectedWorktreeSessionIds = new Set<string>();
try {
// Callers that already crossed an async status write pass the owner/DB
// captured at operation entry. The fallback is only for direct callers.
@@ -336,6 +337,9 @@ export async function recycleSessionWorktreeForStatusChange(
});
});
if (!ownerIsCurrent()) return;
+ if (recycle.hasRegisteredWorktreeForSession(targetSessionId)) {
+ affectedWorktreeSessionIds.add(targetSessionId);
+ }
await recycle.recycleWorktreeForRemovedSession(targetSessionId, {
scanOwners,
db: mediaDb,
@@ -353,7 +357,9 @@ export async function recycleSessionWorktreeForStatusChange(
err: err instanceof Error ? err.message : String(err),
});
} finally {
- broadcastWorktreeChanged(sessionId);
+ for (const affectedSessionId of affectedWorktreeSessionIds) {
+ broadcastWorktreeChanged(affectedSessionId);
+ }
}
}
diff --git a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
index 96427e8f43..e0802a6d0b 100644
--- a/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
+++ b/apps/desktop/src/main/worktree/sessionRemovalRecycle.ts
@@ -52,6 +52,14 @@ export interface RecycleWorktreeForRemovedSessionOptions {
recycleOwner?: (sessionId: string) => Promise<void>;
}
+/**
+ * 回收通知只关心 store 中实际登记过 worktree 的 session。这个窄查询由状态回收链
+ * 在真正进入低层回收前调用,避免无 worktree 的普通任务也广播 worktree 变化。
+ */
+export function hasRegisteredWorktreeForSession(sessionId: string): boolean {
+ return store.get(sessionId) !== null;
+}
+
export async function recycleWorktreeForRemovedSession(
sessionId: string,
options: RecycleWorktreeForRemovedSessionOptions = {},
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b1ef6c8791..8ee0148c5f 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -4456,11 +4456,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
sessionId: string,
): Promise<{ ok: boolean; snapshotApplied?: boolean; message?: string }> =>
ipcRenderer.invoke('worktree:restore-for-session', sessionId),
- /**
- * 订阅「worktree 回收链已跑完」。payload: { sessionId }。
- * 归档/删除后 main 侧的回收是 fire-and-forget 的异步链,store 条目移除远晚于状态
- * IPC 返回;renderer 只在动作里刷一次会拿到旧快照,徽标就一直陈旧。
- */
+ /** worktree 回收完成后,按实际受影响的 sessionId 增量更新 renderer 缓存。 */
onWorktreeChanged: fanOutWorktreeChanged,
// ── Slack Hook(公司中心 slack-hook-server 接入, 单内置连接) ─────────────
diff --git a/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts b/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts
new file mode 100644
index 0000000000..e95b856d56
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/bulkSessionStatusRouting.test.ts
@@ -0,0 +1,50 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
+ 'utf8',
+);
+
+function handlerSource(startMarker: string, endMarker: string): string {
+ const start = source.indexOf(startMarker);
+ const end = source.indexOf(endMarker, start);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ return source.slice(start, end);
+}
+
+describe('bulk session status routing', () => {
+ it('multi-select delete freezes the resolved target and treats a local collision as local', () => {
+ const handler = handlerSource(
+ 'const handleBulkDelete = useCallback',
+ 'const handleBulkArchive = useCallback',
+ );
+
+ expect(handler).toContain('sessionService.resolveStatusWriteTarget(session.id)');
+ expect(handler).toContain(
+ "sessionService.setStatus(session.id, 'deleted', statusWriteTarget)",
+ );
+ expect(handler).toContain("statusWriteTarget.kind === 'local'");
+ expect(handler).not.toContain('sessionService.patchMeta(');
+ });
+
+ it('multi-select archive freezes the resolved target and converges a local collision locally', () => {
+ const handler = handlerSource(
+ 'const handleBulkArchive = useCallback',
+ 'const handleArchiveAllInProject = useCallback',
+ );
+
+ expect(handler).toContain('sessionService.resolveStatusWriteTarget(session.id)');
+ expect(handler).toContain(
+ "sessionService.setStatus(session.id, 'archived', statusWriteTarget)",
+ );
+ expect(handler).toContain("statusWriteTarget.kind === 'local'");
+ expect(handler).toContain(
+ "patchLocal(session.id, { status: 'archived', pinnedAt: null })",
+ );
+ expect(handler).not.toContain('sessionService.patchMeta(');
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
index 8772877f7c..f3dfaab9ed 100644
--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
@@ -44,15 +44,20 @@ function stubElectron() {
const localMessages = {
estimatedSessionValue: vi.fn().mockResolvedValue({ totalValueUsd: 0, entries: [] }),
};
+ const localSessions = {
+ get: vi.fn().mockRejectedValue(new Error('[NOT_FOUND] Session does not exist')),
+ update: vi.fn(),
+ };
const invoke = vi.fn().mockResolvedValue(undefined);
+ const getState = vi.fn().mockResolvedValue({ disabledControlDeviceIds: [] });
vi.stubGlobal('window', {
electronAPI: {
maker: makerSpies,
- localDb: { orcaWorkflows, messages: localMessages },
- deviceLink: { invoke },
+ localDb: { orcaWorkflows, messages: localMessages, sessions: localSessions },
+ deviceLink: { invoke, getState },
},
});
- return { makerSpies, orcaWorkflows, localMessages, invoke };
+ return { makerSpies, orcaWorkflows, localMessages, localSessions, invoke, getState };
}
const sess = (id: string): Session => ({ id }) as unknown as Session;
@@ -265,6 +270,60 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
]);
});
+ it.each([
+ ['archived', { status: 'archived', pinnedAt: null }],
+ ['deleted', { status: 'deleted' }],
+ ] as const)(
+ 'setStatus routes a disabled remote-id collision to the verified local row for %s',
+ async (status, expectedPatch) => {
+ const { getState, invoke, localSessions } = stubElectron();
+ const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');
+ const { getStickySessionDeviceId } = await import(
+ '@/features/device-link/stickySessionOrigin'
+ );
+ const sessionService = await import('@/lib/sessionService');
+ const localRow = sess('collision');
+
+ remoteProjectsStore.setDeviceSessions('dev-disabled', 'Old desktop', [localRow]);
+ expect(getStickySessionDeviceId('collision')).toBe('dev-disabled');
+ remoteProjectsStore.removeDevice('dev-disabled');
+ getState.mockResolvedValue({ disabledControlDeviceIds: ['dev-disabled'] });
+ localSessions.get.mockResolvedValue(localRow);
+ localSessions.update.mockResolvedValue({ ...localRow, status });
+
+ await sessionService.setStatus('collision', status);
+
+ expect(getState).toHaveBeenCalledOnce();
+ expect(localSessions.get).toHaveBeenCalledWith('collision');
+ expect(localSessions.update).toHaveBeenCalledWith('collision', expectedPatch);
+ expect(invoke).not.toHaveBeenCalled();
+ },
+ );
+
+ it('setStatus keeps a disabled true remote session pinned when no local row exists', async () => {
+ const { getState, invoke, localSessions } = stubElectron();
+ const { remoteProjectsStore } = await import('@/features/device-link/remoteProjectsStore');
+ const { getStickySessionDeviceId } = await import(
+ '@/features/device-link/stickySessionOrigin'
+ );
+ const sessionService = await import('@/lib/sessionService');
+
+ remoteProjectsStore.setDeviceSessions('dev-disabled', 'Old desktop', [sess('remote-only')]);
+ expect(getStickySessionDeviceId('remote-only')).toBe('dev-disabled');
+ remoteProjectsStore.removeDevice('dev-disabled');
+ getState.mockResolvedValue({ disabledControlDeviceIds: ['dev-disabled'] });
+
+ await sessionService.setStatus('remote-only', 'archived');
+
+ expect(getState).toHaveBeenCalledOnce();
+ expect(localSessions.get).toHaveBeenCalledWith('remote-only');
+ expect(localSessions.update).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledWith('dev-disabled', 'local-db:sessions:patch-meta', [
+ 'remote-only',
+ { status: 'archived', pinnedAt: null },
+ ]);
+ });
+
it('本机会话:走本地 maker,不经隧道', async () => {
const { makerSpies, invoke } = stubElectron();
const { makerApiFor } = await import('@/lib/makerTransport');
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
index 620467b94a..5601175894 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreAccountBoundary.test.tsx
@@ -131,21 +131,13 @@ describe('sessionsStore account boundaries', () => {
it('does not let a request started before delete restore the deleted session', async () => {
const staleRequest = deferred<Session[]>();
- const replacementRequest = deferred<Session[]>();
- mocks.list
- .mockImplementationOnce(() => staleRequest.promise)
- .mockImplementationOnce(() => replacementRequest.promise);
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
const staleLoad = sessionsStore.ensureByFilter('all');
act(() => sessionsStore.patchLocal('deleted', { status: 'deleted' }));
- expect(mocks.list).toHaveBeenCalledTimes(2);
- replacementRequest.resolve([session('keep')]);
- await waitFor(() => {
- expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual(['keep']);
- });
-
- staleRequest.resolve([session('deleted'), session('stale')]);
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ staleRequest.resolve([session('deleted'), session('keep')]);
await staleLoad;
expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual(['keep']);
diff --git a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
index a9df746365..5a164dcae8 100644
--- a/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/sessionsStoreStatusBucketMigration.test.tsx
@@ -3,18 +3,17 @@
/**
* sessionsStore 跨桶迁移(patch.status)不变量
* ---------------------------------------------------------------------------
- * 回归的是「点归档后对话过半秒才消失」:早期 patchLocal 对任何桶归属不一致都
- * drop + 重拉,当前可见桶变 null 后 useCCSessions 的 `next !== null` 守卫会跳过
- * setState,列表停在**仍含被归档行**的陈旧快照,直到重拉的 sessions:list(LEFT
- * JOIN messages + GROUP BY 的重查询)回来才更新,把调用方的乐观更新整段抵消。
- *
- * 现在的口径是不对称的:该移出的桶就地移除(本地即可定论,桶保持非 null),
- * 只有该补进却缺 row 的桶才 drop 重拉。下面每条测试都钉这个不对称。
+ * 状态变化必须优先复用已加载桶里的完整 Session 行,同步修正 active / archived /
+ * all。完全找不到行,或 status-only 广播缺少 DB 已更新的 updatedAt 时,才保留即时
+ * 迁移并定向补查目标桶;同桶连续补查只允许一个在途请求和一次尾刷,避免连续归档
+ * 放大成列表查询风暴。
*/
import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DEFAULT_DRAFT_SESSION_TITLE } from '@cindy/maker-shared/session-title';
+
import type { Session } from '@/lib/ccAgent.types';
const mocks = vi.hoisted(() => {
@@ -31,6 +30,7 @@ vi.mock('@/lib/sessionService', () => ({
}));
import { useCCSessions } from '@/hooks/useCCSessions';
+import { emitAutoTitlePreview } from '@/lib/sessionsBus';
import { sessionsStore } from '@/lib/sessionsStore';
import type { ListStatusFilter } from '@/lib/sessionService';
@@ -42,8 +42,18 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
return { promise, resolve };
}
-function session(id: string, status: Session['status'] = 'active'): Session {
- return { id, status } as Session;
+function session(
+ id: string,
+ status: Session['status'] = 'active',
+ updatedAt = '2026-08-27T00:00:00.000Z',
+): Session {
+ return {
+ id,
+ status,
+ title: `title-${id}`,
+ workingDir: `C:\\projects\\${id}`,
+ updatedAt,
+ } as Session;
}
/** 本次 list mock 收到的 filter 参数(sessionService.list(limit, filter))。 */
@@ -62,22 +72,997 @@ describe('sessionsStore status bucket migration', () => {
sessionsStore.reset();
});
- it('archiving removes the row from the active bucket in place, without dropping or refetching it', async () => {
- mocks.list.mockResolvedValueOnce([session('archive-me'), session('keep')]);
+ it('moves a row with an authoritative timestamp into archived and all without querying', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T00:00:00.000Z');
+ const keepActive = session('keep-active', 'active', '2026-08-27T00:30:00.000Z');
+ mocks.list
+ .mockResolvedValueOnce([keepActive, target])
+ .mockResolvedValueOnce([session('already-archived', 'archived')])
+ .mockResolvedValueOnce([keepActive, target]);
await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
mocks.list.mockReset();
- act(() => sessionsStore.patchLocal('archive-me', { status: 'archived', pinnedAt: null }));
+ act(() =>
+ sessionsStore.patchLocal('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T01:00:00.000Z',
+ }),
+ );
+
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep-active']);
+ expect(
+ sessionsStore.getByFilter('archived')?.find(({ id }) => id === 'archive-me'),
+ ).toEqual(
+ expect.objectContaining({
+ id: 'archive-me',
+ status: 'archived',
+ title: 'title-archive-me',
+ workingDir: 'C:\\projects\\archive-me',
+ pinnedAt: null,
+ }),
+ );
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({ id: 'archive-me', status: 'archived', pinnedAt: null }),
+ );
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+ it('backfills archived and all ordering when a status-only archive lacks updatedAt', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T01:00:00.000Z');
+ const previousNewest = session(
+ 'previous-newest',
+ 'archived',
+ '2026-08-27T02:00:00.000Z',
+ );
+ mocks.list
+ .mockResolvedValueOnce([target])
+ .mockResolvedValueOnce([previousNewest])
+ .mockResolvedValueOnce([previousNewest, target]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
+ mocks.list.mockReset();
+
+ const persisted = {
+ ...target,
+ status: 'archived',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ } as Session;
+ mocks.list.mockImplementation((_limit, filter) =>
+ Promise.resolve(filter === 'archived' || filter === 'all' ? [persisted, previousNewest] : []),
+ );
+
+ act(() => sessionsStore.patchLocal('archive-me', { status: 'archived' }));
+
+ expect(requestedFilters()).toEqual(['archived', 'all']);
+ await waitFor(() => {
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'previous-newest',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'previous-newest',
+ ]);
+ });
+ expect(sessionsStore.getByFilter('archived')?.[0]?.updatedAt).toBe(persisted.updatedAt);
+ expect(sessionsStore.getByFilter('all')?.[0]?.updatedAt).toBe(persisted.updatedAt);
+ });
+
+ it('keeps an optimistic archive applied to list requests started before the DB write completes', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T02:00:00.000Z');
+ const keep = session('keep', 'active', '2026-08-27T01:00:00.000Z');
+ const alreadyArchived = session(
+ 'already-archived',
+ 'archived',
+ '2026-08-27T01:30:00.000Z',
+ );
+ mocks.list
+ .mockResolvedValueOnce([target, keep])
+ .mockResolvedValueOnce([alreadyArchived])
+ .mockResolvedValueOnce([target, keep]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(transition).not.toBeNull();
+ mocks.list.mockReset();
+ // 三个请求都在乐观 patch 之后、数据库提交之前启动,返回的仍是旧 DB 快照。
+ mocks.list
+ .mockResolvedValueOnce([target, keep])
+ .mockResolvedValueOnce([alreadyArchived])
+ .mockResolvedValueOnce([target, keep]);
+
+ await Promise.all([
+ sessionsStore.forceRefresh('active'),
+ sessionsStore.forceRefresh('archived'),
+ sessionsStore.forceRefresh('all'),
+ ]);
- // 桶必须仍是数组(非 null)—— null 才是订阅者跳过 setState 的根因。
expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
+ expect(sessionsStore.getByFilter('archived')).toEqual([
+ expect.objectContaining({ id: 'archive-me', status: 'archived' }),
+ expect.objectContaining({ id: 'already-archived' }),
+ ]);
+ expect(sessionsStore.getByFilter('all')?.find(({ id }) => id === 'archive-me')).toEqual(
+ expect.objectContaining({ status: 'archived' }),
+ );
+ });
+
+ it('defers a missing-row backfill until the status write returns the complete row', async () => {
+ mocks.list.mockResolvedValueOnce([]);
+ await sessionsStore.ensureByFilter('archived');
+ mocks.list.mockReset();
+
+ const transition = sessionsStore.beginStatusTransition('not-cached', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+
+ expect(mocks.list).not.toHaveBeenCalled();
+ expect(sessionsStore.getByFilter('archived')).toEqual([]);
+
+ const persisted = session(
+ 'not-cached',
+ 'archived',
+ '2026-08-27T03:00:00.000Z',
+ );
+ expect(sessionsStore.completeStatusTransition(transition!, persisted)).toBe(true);
+ expect(sessionsStore.getByFilter('archived')).toEqual([
+ expect.objectContaining({
+ id: 'not-cached',
+ status: 'archived',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ]);
expect(mocks.list).not.toHaveBeenCalled();
});
- it('drops the archived row from a mounted list synchronously, before any IPC resolves', async () => {
+ it('uses the persisted row to refresh updatedAt and reorder loaded target buckets', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T01:00:00.000Z');
+ const newer = session('newer', 'archived', '2026-08-27T02:00:00.000Z');
+ mocks.list
+ .mockResolvedValueOnce([target])
+ .mockResolvedValueOnce([newer])
+ .mockResolvedValueOnce([newer, target]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'newer',
+ 'archive-me',
+ ]);
+
+ const persisted = {
+ ...target,
+ status: 'archived' as const,
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ };
+ expect(sessionsStore.completeStatusTransition(transition!, persisted)).toBe(true);
+
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'newer',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'newer',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.[0].updatedAt).toBe(
+ '2026-08-27T03:00:00.000Z',
+ );
+ });
+
+ it('replays the persisted row onto a stale list response that finishes after the DB write', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T01:00:00.000Z');
+ const previousNewest = session('previous-newest', 'archived', '2026-08-27T02:00:00.000Z');
+ mocks.list
+ .mockResolvedValueOnce([target])
+ .mockResolvedValueOnce([previousNewest, target]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const staleAllRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleAllRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ staleAllRequest.resolve([previousNewest, target]);
+ await staleRefresh;
+
+ expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'previous-newest',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ );
+ });
+
+ it('replays newer title and spend fields after a complete status override', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ totalCostUsd: 1,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+
+ sessionsStore.patchLocal('archive-me', {
+ title: 'new authoritative title',
+ totalCostUsd: 42,
+ });
+ staleRequest.resolve([target]);
+ await staleRefresh;
+
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ title: 'new authoritative title',
+ totalCostUsd: 42,
+ }),
+ );
+ });
+
+ it('keeps concurrent settings updates when the persisted status row has the same updatedAt', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ model: 'old-model',
+ effort: 'medium',
+ permissionMode: 'ask',
+ fastMode: false,
+ providerId: null,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ sessionsStore.patchLocal('archive-me', {
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ });
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ }),
+ ).toBe(true);
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ }),
+ );
+ });
+
+ it('keeps concurrent settings after optimistic archive removes the last cached row', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ model: 'old-model',
+ effort: 'medium',
+ permissionMode: 'ask',
+ fastMode: false,
+ providerId: null,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('active');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(sessionsStore.findById('archive-me')).toBeNull();
+ sessionsStore.patchLocal('archive-me', {
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ });
+
+ const archivedRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => archivedRequest.promise);
+ const archivedLoad = sessionsStore.ensureByFilter('archived');
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ archivedRequest.resolve([]);
+ await archivedLoad;
+
+ expect(sessionsStore.getByFilter('archived')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ }),
+ );
+ });
+
+ it('keeps concurrent settings when a pending transition started without a cached source row', async () => {
+ mocks.list.mockResolvedValueOnce([]);
+ await sessionsStore.ensureByFilter('archived');
+ const transition = sessionsStore.beginStatusTransition('not-cached', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ sessionsStore.patchLocal('not-cached', {
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ });
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...session('not-cached', 'active', '2026-08-27T01:00:00.000Z'),
+ status: 'archived',
+ pinnedAt: null,
+ model: 'old-model',
+ effort: 'medium',
+ permissionMode: 'ask',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ } as Session),
+ ).toBe(true);
+
+ expect(sessionsStore.getByFilter('archived')?.[0]).toEqual(
+ expect.objectContaining({
+ id: 'not-cached',
+ status: 'archived',
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ }),
+ );
+ });
+
+ it('replays settings fields that arrive after a complete status override', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ model: 'old-model',
+ effort: 'medium',
+ permissionMode: 'ask',
+ fastMode: false,
+ providerId: null,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ sessionsStore.patchLocal('archive-me', {
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ });
+ staleRequest.resolve([target]);
+ await staleRefresh;
+
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ fastMode: true,
+ providerId: 'new-provider',
+ }),
+ );
+ });
+
+ it('keeps later settings fields when a pending status write rolls back', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ model: 'old-model',
+ effort: 'medium',
+ permissionMode: 'ask',
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ sessionsStore.patchLocal('archive-me', {
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ });
+
+ expect(sessionsStore.rollbackStatusTransition(transition!)).toBe(true);
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'active',
+ model: 'new-model',
+ effort: 'high',
+ permissionMode: 'auto',
+ }),
+ );
+ });
+
+ it('applies a newer auto-title preview after a complete status override', async () => {
+ const target = {
+ ...session('archive-me', 'active', '2026-08-27T01:00:00.000Z'),
+ title: DEFAULT_DRAFT_SESSION_TITLE,
+ } as Session;
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
+ const staleRefresh = sessionsStore.forceRefresh('all');
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ emitAutoTitlePreview('archive-me', 'new optimistic title');
+ staleRequest.resolve([target]);
+ await staleRefresh;
+
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({
+ status: 'archived',
+ title: 'new optimistic title',
+ }),
+ );
+ });
+
+ it('keeps the newest 1000 rows when a persisted archive enters a full target bucket', async () => {
+ const archived = Array.from({ length: 1000 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ );
+ const target = session('archive-me', 'active', new Date(500_000).toISOString());
+ mocks.list.mockResolvedValueOnce([target]).mockResolvedValueOnce(archived);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ // 旧 updatedAt 排在 1000 条之外,乐观阶段不能无条件挤掉尾项。
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(
+ archived.map(({ id }) => id),
+ );
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: new Date(3_000_000).toISOString(),
+ }),
+ ).toBe(true);
+ const finalArchived = sessionsStore.getByFilter('archived') ?? [];
+ expect(finalArchived).toHaveLength(1000);
+ expect(finalArchived[0]?.id).toBe('archive-me');
+ expect(finalArchived.some(({ id }) => id === 'archived-999')).toBe(false);
+ });
+
+ it('backfills a full active bucket when a status-only restore lacks updatedAt', async () => {
+ const active = Array.from({ length: 1000 }, (_, index) =>
+ session(`active-${index}`, 'active', new Date(2_000_000 - index * 1_000).toISOString()),
+ );
+ const target = session('restore-me', 'archived', new Date(500_000).toISOString());
+ mocks.list.mockResolvedValueOnce(active).mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ mocks.list.mockReset();
+
+ const persisted = {
+ ...target,
+ status: 'active',
+ updatedAt: new Date(3_000_000).toISOString(),
+ } as Session;
+ mocks.list.mockResolvedValueOnce([persisted, ...active.slice(0, 999)]);
+
+ act(() => sessionsStore.patchLocal('restore-me', { status: 'active' }));
+
+ expect(requestedFilters()).toEqual(['active']);
+ await waitFor(() => expect(sessionsStore.getByFilter('active')?.[0]?.id).toBe('restore-me'));
+ const finalActive = sessionsStore.getByFilter('active') ?? [];
+ expect(finalActive).toHaveLength(1000);
+ expect(finalActive[0]?.updatedAt).toBe(persisted.updatedAt);
+ expect(finalActive.some(({ id }) => id === 'active-999')).toBe(false);
+ });
+
+ it('restores ordering, pin state and an evicted tail row when an archive write fails', async () => {
+ const archived = Array.from({ length: 1000 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ );
+ const target = {
+ ...session('archive-me', 'active', new Date(1_500_500).toISOString()),
+ pinnedAt: '2026-08-27T00:00:00.000Z',
+ };
+ const active = [
+ session('active-newer', 'active', new Date(2_500_000).toISOString()),
+ target,
+ session('active-older', 'active', new Date(500_000).toISOString()),
+ ];
+ mocks.list.mockResolvedValueOnce(active).mockResolvedValueOnce(archived);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(sessionsStore.getByFilter('archived')).toHaveLength(1000);
+ expect(sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archive-me')).toBe(true);
+ expect(
+ sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archived-999'),
+ ).toBe(false);
+
+ expect(sessionsStore.rollbackStatusTransition(transition!)).toBe(true);
+
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(
+ active.map(({ id }) => id),
+ );
+ expect(sessionsStore.getByFilter('active')?.[1]).toEqual(
+ expect.objectContaining({
+ id: 'archive-me',
+ status: 'active',
+ pinnedAt: '2026-08-27T00:00:00.000Z',
+ }),
+ );
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(
+ archived.map(({ id }) => id),
+ );
+ });
+
+ it('restores the 1000th row when a full target bucket loads during a pending archive', async () => {
+ const archived = Array.from({ length: 1000 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ );
+ const target = session('archive-me', 'active', new Date(1_500_500).toISOString());
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('active');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ mocks.list.mockResolvedValueOnce(archived);
+ await sessionsStore.ensureByFilter('archived');
+
+ expect(sessionsStore.getByFilter('archived')).toHaveLength(1000);
+ expect(sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archive-me')).toBe(true);
+ expect(
+ sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archived-999'),
+ ).toBe(false);
+
+ expect(sessionsStore.rollbackStatusTransition(transition!)).toBe(true);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(
+ archived.map(({ id }) => id),
+ );
+ });
+
+ it('backfills the 1001st archived row after restoring from a full bucket', async () => {
+ const target = session('restore-me', 'archived', new Date(2_001_000).toISOString());
+ const archived = [
+ target,
+ ...Array.from({ length: 999 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ ),
+ ];
+ const replacement = session('archived-1000', 'archived', new Date(1_000_000).toISOString());
+ mocks.list.mockResolvedValueOnce(archived).mockResolvedValueOnce([]);
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('active');
+ mocks.list.mockReset();
+ mocks.list.mockResolvedValueOnce([...archived.slice(1), replacement]);
+
+ const transition = sessionsStore.beginStatusTransition('restore-me', { status: 'active' });
+
+ expect(sessionsStore.getByFilter('archived')).toHaveLength(999);
+ expect(mocks.list).not.toHaveBeenCalled();
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'active',
+ updatedAt: new Date(3_000_000).toISOString(),
+ }),
+ ).toBe(true);
+
+ await waitFor(() => expect(sessionsStore.getByFilter('archived')).toHaveLength(1000));
+ expect(requestedFilters()).toEqual(['archived']);
+ expect(sessionsStore.getByFilter('archived')?.at(-1)?.id).toBe('archived-1000');
+ });
+
+ it('backfills only full active and all buckets after deleting a row', async () => {
+ const target = session('delete-me', 'active', new Date(2_001_000).toISOString());
+ const active = [
+ target,
+ ...Array.from({ length: 999 }, (_, index) =>
+ session(
+ `active-${index}`,
+ 'active',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ ),
+ ];
+ const replacement = session('active-1000', 'active', new Date(1_000_000).toISOString());
+ const refilled = [...active.slice(1), replacement];
+ mocks.list.mockResolvedValueOnce(active).mockResolvedValueOnce(active);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('all');
+ mocks.list.mockReset();
+ mocks.list.mockImplementation((_limit, filter) =>
+ Promise.resolve(filter === 'active' || filter === 'all' ? refilled : []),
+ );
+
+ act(() => sessionsStore.patchLocal('delete-me', { status: 'deleted' }));
+
+ await waitFor(() => {
+ expect(sessionsStore.getByFilter('active')).toHaveLength(1000);
+ expect(sessionsStore.getByFilter('all')).toHaveLength(1000);
+ });
+ expect(requestedFilters()).toEqual(['active', 'all']);
+ expect(sessionsStore.getByFilter('active')?.at(-1)?.id).toBe('active-1000');
+ expect(sessionsStore.getByFilter('all')?.at(-1)?.id).toBe('active-1000');
+ });
+
+ it('keeps the full-bucket backfill when the first of two concurrent migrations rolls back', async () => {
+ const first = session('archive-first', 'active', new Date(2_002_000).toISOString());
+ const second = session('archive-second', 'active', new Date(2_001_000).toISOString());
+ const active = [
+ first,
+ second,
+ ...Array.from({ length: 998 }, (_, index) =>
+ session(
+ `active-${index}`,
+ 'active',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ ),
+ ];
+ const replacement = session('active-1000', 'active', new Date(1_000_000).toISOString());
+ mocks.list.mockResolvedValueOnce(active);
+ await sessionsStore.ensureByFilter('active');
+ mocks.list.mockReset();
+ mocks.list.mockResolvedValueOnce([first, ...active.slice(2), replacement]);
+
+ const firstTransition = sessionsStore.beginStatusTransition('archive-first', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const secondTransition = sessionsStore.beginStatusTransition('archive-second', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(sessionsStore.getByFilter('active')).toHaveLength(998);
+
+ expect(sessionsStore.rollbackStatusTransition(firstTransition!)).toBe(true);
+ expect(sessionsStore.getByFilter('active')).toHaveLength(999);
+ expect(mocks.list).not.toHaveBeenCalled();
+ expect(
+ sessionsStore.completeStatusTransition(secondTransition!, {
+ ...second,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: new Date(3_000_000).toISOString(),
+ }),
+ ).toBe(true);
+
+ await waitFor(() => expect(sessionsStore.getByFilter('active')).toHaveLength(1000));
+ expect(requestedFilters()).toEqual(['active']);
+ expect(sessionsStore.getByFilter('active')?.at(-1)?.id).toBe('active-1000');
+ });
+
+ it('waits for all overlapping archive writes before rolling back their shared optimistic state', async () => {
+ const archived = Array.from({ length: 1000 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ );
+ const target = session('archive-me', 'active', new Date(1_500_500).toISOString());
+ mocks.list.mockResolvedValueOnce([target]).mockResolvedValueOnce(archived);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+
+ const first = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const second = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+
+ expect(sessionsStore.rollbackStatusTransition(first!)).toBe(true);
+ expect(sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archive-me')).toBe(true);
+ expect(sessionsStore.rollbackStatusTransition(second!)).toBe(true);
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['archive-me']);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(
+ archived.map(({ id }) => id),
+ );
+ });
+
+ it.each(['active', 'deleted'] as const)(
+ 'keeps a later %s status and restores the full archived bucket before an old archive response returns',
+ async (laterStatus) => {
+ const archived = Array.from({ length: 1000 }, (_, index) =>
+ session(
+ `archived-${index}`,
+ 'archived',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ );
+ const target = session('archive-me', 'active', new Date(1_500_500).toISOString());
+ mocks.list.mockResolvedValueOnce([target]).mockResolvedValueOnce(archived);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ sessionsStore.patchLocal('archive-me', { status: laterStatus });
+
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(
+ archived.map(({ id }) => id),
+ );
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: new Date(3_000_000).toISOString(),
+ }),
+ ).toBe(false);
+ expect(sessionsStore.getByFilter('active')?.some(({ id }) => id === 'archive-me')).toBe(
+ laterStatus === 'active',
+ );
+ expect(sessionsStore.getByFilter('archived')?.some(({ id }) => id === 'archive-me')).toBe(
+ false,
+ );
+ },
+ );
+
+ it('waits for an archive to settle before restoring and rolls a failed restore back to its full row', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T01:00:00.000Z');
+ const previousNewest = session(
+ 'previous-newest',
+ 'archived',
+ '2026-08-27T02:00:00.000Z',
+ );
+ mocks.list
+ .mockResolvedValueOnce([target])
+ .mockResolvedValueOnce([previousNewest])
+ .mockResolvedValueOnce([previousNewest, target]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
+
+ const archive = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ let restoreStarted = false;
+ const restorePromise = sessionsStore
+ .waitForStatusTransition('archive-me')
+ .then((canContinue) => {
+ restoreStarted = true;
+ return canContinue
+ ? sessionsStore.beginStatusTransition('archive-me', { status: 'active' })
+ : null;
+ });
+ await Promise.resolve();
+ expect(restoreStarted).toBe(false);
+
+ expect(
+ sessionsStore.completeStatusTransition(archive!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: '2026-08-27T03:00:00.000Z',
+ }),
+ ).toBe(true);
+ const restore = await restorePromise;
+ expect(restoreStarted).toBe(true);
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['archive-me']);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'previous-newest',
+ ]);
+
+ expect(sessionsStore.rollbackStatusTransition(restore!)).toBe(true);
+ expect(sessionsStore.getByFilter('active')).toEqual([]);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'previous-newest',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.map(({ id, status }) => [id, status])).toEqual([
+ ['archive-me', 'archived'],
+ ['previous-newest', 'archived'],
+ ]);
+ expect(sessionsStore.getByFilter('all')?.[0].updatedAt).toBe(
+ '2026-08-27T03:00:00.000Z',
+ );
+ });
+
+ it('begins queued status actions one at a time so opposite transitions cannot replace each other', async () => {
+ const target = session('archive-me', 'active', '2026-08-27T01:00:00.000Z');
+ mocks.list.mockResolvedValueOnce([target]);
+ await sessionsStore.ensureByFilter('all');
+
+ const initialArchive = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ let laterArchiveStarted = false;
+ const queuedRestore = sessionsStore.beginStatusTransitionWhenReady('archive-me', {
+ status: 'active',
+ });
+ const queuedArchive = sessionsStore
+ .beginStatusTransitionWhenReady('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ })
+ .then((transition) => {
+ laterArchiveStarted = true;
+ return transition;
+ });
+
+ expect(
+ sessionsStore.completeStatusTransition(initialArchive!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ }),
+ ).toBe(true);
+ const restore = await queuedRestore;
+ expect(restore).not.toBeNull();
+ expect(laterArchiveStarted).toBe(false);
+
+ expect(
+ sessionsStore.completeStatusTransition(restore!, {
+ ...target,
+ status: 'active',
+ pinnedAt: null,
+ }),
+ ).toBe(true);
+ const laterArchive = await queuedArchive;
+ expect(laterArchive).not.toBeNull();
+ expect(laterArchiveStarted).toBe(true);
+ expect(
+ sessionsStore.completeStatusTransition(laterArchive!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ }),
+ ).toBe(true);
+ expect(sessionsStore.hasPendingStatusTransition('archive-me')).toBe(false);
+ expect(sessionsStore.getByFilter('all')?.[0].status).toBe('archived');
+ });
+
+ it('stops queued waits and atomic begins when the store resets', async () => {
+ mocks.list.mockResolvedValueOnce([session('archive-me')]);
+ await sessionsStore.ensureByFilter('active');
+ sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ const queued = sessionsStore.waitForStatusTransition('archive-me');
+ const queuedBegin = sessionsStore.beginStatusTransitionWhenReady('archive-me', {
+ status: 'active',
+ });
+
+ sessionsStore.reset();
+
+ await expect(queued).resolves.toBe(false);
+ await expect(queuedBegin).resolves.toBeNull();
+ expect(sessionsStore.getByFilter('active')).toBeNull();
+ });
+
+ it('removes the archived row from a mounted active list synchronously', async () => {
mocks.list.mockResolvedValueOnce([session('archive-me'), session('keep')]);
await sessionsStore.ensureByFilter('active');
- // 归档后若有任何重拉,让它永远悬着:断言必须在没有 IPC 回包的前提下成立。
mocks.list.mockReset();
mocks.list.mockImplementation(() => deferred<Session[]>().promise);
@@ -90,79 +1075,243 @@ describe('sessionsStore status bucket migration', () => {
expect(view.result.current.isLoading).toBe(false);
});
- it('refetches only the bucket that is missing the row after archiving', async () => {
+ it('moves a row with an authoritative timestamp from archived into active without querying', async () => {
mocks.list
- .mockResolvedValueOnce([session('archive-me'), session('keep-active')])
- .mockResolvedValueOnce([session('already-archived', 'archived')]);
+ .mockResolvedValueOnce([session('stay-active')])
+ .mockResolvedValueOnce([session('restore-me', 'archived')])
+ .mockResolvedValueOnce([session('restore-me', 'archived')]);
await sessionsStore.ensureByFilter('active');
await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
mocks.list.mockReset();
- mocks.list.mockResolvedValue([
- session('archive-me', 'archived'),
- session('already-archived', 'archived'),
- ]);
- act(() => sessionsStore.patchLocal('archive-me', { status: 'archived' }));
+ act(() =>
+ sessionsStore.patchLocal('restore-me', {
+ status: 'active',
+ updatedAt: '2026-08-27T01:00:00.000Z',
+ }),
+ );
+
+ expect(sessionsStore.getByFilter('active')?.find(({ id }) => id === 'restore-me')).toEqual(
+ expect.objectContaining({
+ id: 'restore-me',
+ status: 'active',
+ title: 'title-restore-me',
+ }),
+ );
+ expect(sessionsStore.getByFilter('archived')).toEqual([]);
+ expect(sessionsStore.getByFilter('all')?.[0]).toEqual(
+ expect.objectContaining({ id: 'restore-me', status: 'active' }),
+ );
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+ it('removes a deleted row from every loaded bucket without querying', async () => {
+ mocks.list
+ .mockResolvedValueOnce([session('delete-me'), session('keep-active')])
+ .mockResolvedValueOnce([session('delete-me', 'archived'), session('keep-archived', 'archived')])
+ .mockResolvedValueOnce([session('delete-me'), session('keep-all')]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ await sessionsStore.ensureByFilter('all');
+ mocks.list.mockReset();
+
+ act(() => sessionsStore.patchLocal('delete-me', { status: 'deleted' }));
- // active 桶就地移除,不重拉;archived 桶缺这一条 row,只能问 DB。
expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep-active']);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'keep-archived',
+ ]);
+ expect(sessionsStore.getByFilter('all')?.map(({ id }) => id)).toEqual(['keep-all']);
+ expect(mocks.list).not.toHaveBeenCalled();
+ });
+
+ it('keeps loaded snapshots and refetches only a missing target bucket', async () => {
+ mocks.list
+ .mockResolvedValueOnce([session('keep-active')])
+ .mockResolvedValueOnce([session('already-archived', 'archived')]);
+ await sessionsStore.ensureByFilter('active');
+ await sessionsStore.ensureByFilter('archived');
+ mocks.list.mockReset();
+
+ const backfill = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => backfill.promise);
+ act(() => sessionsStore.patchLocal('not-cached', { status: 'archived' }));
+
expect(requestedFilters()).toEqual(['archived']);
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep-active']);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'already-archived',
+ ]);
+
+ backfill.resolve([
+ session('not-cached', 'archived'),
+ session('already-archived', 'archived'),
+ ]);
await waitFor(() => {
expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
- 'archive-me',
+ 'not-cached',
'already-archived',
]);
});
});
- it('keeps the row in the all bucket with the new status', async () => {
- mocks.list.mockResolvedValueOnce([session('archive-me'), session('keep')]);
- await sessionsStore.ensureByFilter('all');
+ it('coalesces consecutive backfills for one bucket into one request plus one trailing refresh', async () => {
+ mocks.list.mockResolvedValueOnce([]);
+ await sessionsStore.ensureByFilter('archived');
mocks.list.mockReset();
- act(() => sessionsStore.patchLocal('archive-me', { status: 'archived' }));
+ const firstBackfill = deferred<Session[]>();
+ const trailingBackfill = deferred<Session[]>();
+ mocks.list
+ .mockImplementationOnce(() => firstBackfill.promise)
+ .mockImplementationOnce(() => trailingBackfill.promise);
- expect(sessionsStore.getByFilter('all')).toEqual([
- expect.objectContaining({ id: 'archive-me', status: 'archived' }),
- expect.objectContaining({ id: 'keep' }),
+ act(() => {
+ sessionsStore.patchLocal('missing-1', { status: 'archived' });
+ sessionsStore.patchLocal('missing-2', { status: 'archived' });
+ sessionsStore.patchLocal('missing-3', { status: 'archived' });
+ });
+ expect(requestedFilters()).toEqual(['archived']);
+
+ firstBackfill.resolve([]);
+ await waitFor(() => expect(requestedFilters()).toEqual(['archived', 'archived']));
+
+ trailingBackfill.resolve([
+ session('missing-1', 'archived'),
+ session('missing-2', 'archived'),
+ session('missing-3', 'archived'),
]);
- expect(mocks.list).not.toHaveBeenCalled();
+ await waitFor(() => {
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'missing-1',
+ 'missing-2',
+ 'missing-3',
+ ]);
+ });
+ expect(mocks.list).toHaveBeenCalledTimes(2);
});
- it('unarchiving removes the row from the archived bucket in place', async () => {
- mocks.list.mockResolvedValueOnce([
- session('restore-me', 'archived'),
- session('stay-archived', 'archived'),
- ]);
- await sessionsStore.ensureByFilter('archived');
- mocks.list.mockReset();
+ it('does not let a list request started before archiving write the row back', async () => {
+ const staleRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleRequest.promise);
- act(() => sessionsStore.patchLocal('restore-me', { status: 'active' }));
+ const staleLoad = sessionsStore.ensureByFilter('active');
+ act(() => sessionsStore.patchLocal('archive-me', { status: 'archived' }));
- expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual(['stay-archived']);
- expect(mocks.list).not.toHaveBeenCalled();
+ expect(requestedFilters()).toEqual(['active']);
+ staleRequest.resolve([session('archive-me'), session('keep')]);
+ await staleLoad;
+
+ expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
+ expect(mocks.list).toHaveBeenCalledTimes(1);
});
- it('does not let a list request started before the archive write the row back', async () => {
+ it('trails a stale full-bucket response only after the pending status write settles', async () => {
+ const target = session('archive-me', 'active', new Date(2_001_000).toISOString());
+ const active = [
+ target,
+ ...Array.from({ length: 999 }, (_, index) =>
+ session(
+ `active-${index}`,
+ 'active',
+ new Date(2_000_000 - index * 1_000).toISOString(),
+ ),
+ ),
+ ];
+ const replacement = session('active-1000', 'active', new Date(1_000_000).toISOString());
const staleRequest = deferred<Session[]>();
- const replacementRequest = deferred<Session[]>();
+ const trailingRequest = deferred<Session[]>();
mocks.list
.mockImplementationOnce(() => staleRequest.promise)
- .mockImplementationOnce(() => replacementRequest.promise);
+ .mockImplementationOnce(() => trailingRequest.promise);
- // 请求在途、桶还没进 cache 时归档:旧响应整桶 cache.set 会把被归档行带回来。
const staleLoad = sessionsStore.ensureByFilter('active');
+ const transition = sessionsStore.beginStatusTransition('archive-me', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ staleRequest.resolve(active);
+ await staleLoad;
+
+ expect(sessionsStore.getByFilter('active')).toHaveLength(999);
+ expect(requestedFilters()).toEqual(['active']);
+
+ expect(
+ sessionsStore.completeStatusTransition(transition!, {
+ ...target,
+ status: 'archived',
+ pinnedAt: null,
+ updatedAt: new Date(3_000_000).toISOString(),
+ }),
+ ).toBe(true);
+ await waitFor(() => expect(requestedFilters()).toEqual(['active', 'active']));
+
+ trailingRequest.resolve([...active.slice(1), replacement]);
+ await waitFor(() => expect(sessionsStore.getByFilter('active')).toHaveLength(1000));
+ expect(sessionsStore.getByFilter('active')?.at(-1)?.id).toBe('active-1000');
+ });
+
+ it('trails a target request when its cached status migration lacks updatedAt', async () => {
+ mocks.list.mockResolvedValueOnce([session('archive-me')]);
+ await sessionsStore.ensureByFilter('active');
+
+ const staleArchivedRequest = deferred<Session[]>();
+ const trailingArchivedRequest = deferred<Session[]>();
+ mocks.list
+ .mockImplementationOnce(() => staleArchivedRequest.promise)
+ .mockImplementationOnce(() => trailingArchivedRequest.promise);
+ const staleLoad = sessionsStore.ensureByFilter('archived');
+
act(() => sessionsStore.patchLocal('archive-me', { status: 'archived' }));
+ staleArchivedRequest.resolve([session('already-archived', 'archived')]);
+ await staleLoad;
+
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'already-archived',
+ 'archive-me',
+ ]);
+ await waitFor(() => expect(requestedFilters()).toEqual(['active', 'archived', 'archived']));
- expect(requestedFilters()).toEqual(['active', 'active']);
- replacementRequest.resolve([session('keep')]);
+ trailingArchivedRequest.resolve([
+ session('archive-me', 'archived', '2026-08-27T03:00:00.000Z'),
+ session('already-archived', 'archived'),
+ ]);
await waitFor(() => {
- expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'already-archived',
+ ]);
});
+ expect(sessionsStore.getByFilter('archived')?.map(({ id }) => id)).toEqual([
+ 'archive-me',
+ 'already-archived',
+ ]);
+ expect(sessionsStore.getByFilter('archived')?.[0]?.updatedAt).toBe(
+ '2026-08-27T03:00:00.000Z',
+ );
+ });
- staleRequest.resolve([session('archive-me'), session('keep')]);
+ it('does not let an older archived response overwrite a later deleted status', async () => {
+ mocks.list.mockResolvedValueOnce([session('archive-me')]);
+ await sessionsStore.ensureByFilter('active');
+
+ const staleArchivedRequest = deferred<Session[]>();
+ mocks.list.mockImplementationOnce(() => staleArchivedRequest.promise);
+ const staleLoad = sessionsStore.ensureByFilter('archived');
+
+ act(() => {
+ sessionsStore.patchLocal('archive-me', {
+ status: 'archived',
+ updatedAt: '2026-08-27T01:00:00.000Z',
+ });
+ sessionsStore.patchLocal('archive-me', { status: 'deleted' });
+ });
+ staleArchivedRequest.resolve([session('archive-me', 'archived')]);
await staleLoad;
- expect(sessionsStore.getByFilter('active')?.map(({ id }) => id)).toEqual(['keep']);
+ expect(sessionsStore.getByFilter('active')).toEqual([]);
+ expect(sessionsStore.getByFilter('archived')).toEqual([]);
+ expect(mocks.list).toHaveBeenCalledTimes(2);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx
index fdfa588d65..52758d1bbd 100644
--- a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx
@@ -1,18 +1,12 @@
// @vitest-environment jsdom
-/**
- * WorktreeContext 必须等 main 的 worktree:changed 推送才能拿到回收后的真实快照。
- *
- * 归档/删除后 main 侧的回收是 fire-and-forget 的异步链(关子进程 → git worktree
- * remove → 文件系统清理),store 条目被移除的时刻远晚于状态 IPC 返回。调用方在
- * 动作里那次「顺手 refresh」几乎必然快照到仍然存在的旧条目,徽标会一直停在回收前
- * 的状态,直到某次无关刷新才纠正(codex review P1)。
- */
+/** WorktreeContext 全量校验只用于启动/聚焦;回收事件按 sessionId 增量更新。 */
import { act, cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WorktreeProvider, useWorktrees } from '@/contexts/WorktreeContext';
+import { emitRefresh } from '@/lib/sessionsBus';
vi.mock('@/lib/logger', () => ({
createLogger: () => ({ warn: vi.fn(), error: vi.fn(), debug: vi.fn(), info: vi.fn() }),
@@ -20,21 +14,37 @@ vi.mock('@/lib/logger', () => ({
const mocks = {
worktreeListAll: vi.fn(),
+ worktreeGetForSession: vi.fn(),
worktreeDetectCwd: vi.fn(),
listeners: new Set<(payload: { sessionId: string }) => void>(),
+ sessionCreatedListeners: new Set<
+ (payload: { sessionId: string }, ownerStamp?: unknown) => void
+ >(),
};
function emitWorktreeChanged(sessionId: string): void {
mocks.listeners.forEach((cb) => cb({ sessionId }));
}
+function emitSessionCreated(sessionId: string, ownerStamp?: unknown): void {
+ mocks.sessionCreatedListeners.forEach((cb) => cb({ sessionId }, ownerStamp));
+}
+
function Probe() {
const metas = useWorktrees();
- return <span data-testid="ids">{Object.keys(metas).sort().join(',')}</span>;
+ return (
+ <span data-testid="ids">
+ {Object.values(metas)
+ .sort((a, b) => a.sessionId.localeCompare(b.sessionId))
+ .map((meta) => `${meta.sessionId}:${meta.path}`)
+ .join(',')}
+ </span>
+ );
}
beforeEach(() => {
mocks.worktreeListAll.mockReset();
+ mocks.worktreeGetForSession.mockReset();
mocks.worktreeDetectCwd.mockReset();
mocks.worktreeDetectCwd.mockResolvedValue({
isInsideWorktree: true,
@@ -42,15 +52,27 @@ beforeEach(() => {
gitInstalled: true,
});
mocks.listeners.clear();
+ mocks.sessionCreatedListeners.clear();
Object.defineProperty(window, 'electronAPI', {
configurable: true,
value: {
worktreeListAll: mocks.worktreeListAll,
+ worktreeGetForSession: mocks.worktreeGetForSession,
worktreeDetectCwd: mocks.worktreeDetectCwd,
onWorktreeChanged: (cb: (payload: { sessionId: string }) => void) => {
mocks.listeners.add(cb);
return () => mocks.listeners.delete(cb);
},
+ localDb: {
+ sessionsPush: {
+ onCreated: (
+ cb: (payload: { sessionId: string }, ownerStamp?: unknown) => void,
+ ) => {
+ mocks.sessionCreatedListeners.add(cb);
+ return () => mocks.sessionCreatedListeners.delete(cb);
+ },
+ },
+ },
},
});
});
@@ -60,8 +82,7 @@ afterEach(() => {
});
describe('WorktreeContext recycle refresh', () => {
- it('re-pulls the snapshot when main reports the recycle finished', async () => {
- // 归档动作那一刻回收还没跑完 —— listAll 仍然带着即将被回收的条目。
+ it('removes only the reported session without reloading the full snapshot', async () => {
mocks.worktreeListAll.mockResolvedValueOnce([
{ sessionId: 'archived-one', path: '/tmp/wt/archived-one' },
{ sessionId: 'other', path: '/tmp/wt/other' },
@@ -72,19 +93,200 @@ describe('WorktreeContext recycle refresh', () => {
</WorktreeProvider>,
);
await waitFor(() => {
- expect(view.getByTestId('ids').textContent).toBe('archived-one,other');
+ expect(view.getByTestId('ids').textContent).toContain('archived-one:/tmp/wt/archived-one');
});
- // 回收链跑完,store 里已经没有那条了。
- mocks.worktreeListAll.mockResolvedValueOnce([{ sessionId: 'other', path: '/tmp/wt/other' }]);
+ mocks.worktreeGetForSession.mockResolvedValueOnce(null);
await act(async () => {
emitWorktreeChanged('archived-one');
});
await waitFor(() => {
- expect(view.getByTestId('ids').textContent).toBe('other');
+ expect(view.getByTestId('ids').textContent).toBe('other:/tmp/wt/other');
+ });
+ expect(mocks.worktreeGetForSession).toHaveBeenCalledWith('archived-one');
+ expect(mocks.worktreeListAll).toHaveBeenCalledTimes(1);
+ expect(mocks.worktreeDetectCwd).toHaveBeenCalledTimes(2);
+ });
+
+ it('validates and updates only the reported worktree', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([
+ { sessionId: 'changed', path: '/tmp/wt/old' },
+ { sessionId: 'other', path: '/tmp/wt/other' },
+ ]);
+ const view = render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeDetectCwd).toHaveBeenCalledTimes(2));
+ mocks.worktreeDetectCwd.mockClear();
+ mocks.worktreeGetForSession.mockResolvedValueOnce({
+ sessionId: 'changed',
+ path: '/tmp/wt/new',
+ });
+
+ act(() => emitWorktreeChanged('changed'));
+
+ await waitFor(() => {
+ expect(view.getByTestId('ids').textContent).toContain('changed:/tmp/wt/new');
+ });
+ expect(mocks.worktreeListAll).toHaveBeenCalledTimes(1);
+ expect(mocks.worktreeDetectCwd).toHaveBeenCalledOnce();
+ expect(mocks.worktreeDetectCwd).toHaveBeenCalledWith({ cwd: '/tmp/wt/new' });
+ });
+
+ it('keeps the newest response when the same session changes twice', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([{ sessionId: 'same', path: '/tmp/wt/start' }]);
+ let resolveFirst!: (value: { sessionId: string; path: string }) => void;
+ mocks.worktreeGetForSession
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFirst = resolve;
+ }),
+ )
+ .mockResolvedValueOnce({ sessionId: 'same', path: '/tmp/wt/newest' });
+ const view = render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(view.getByTestId('ids').textContent).toContain('/tmp/wt/start'));
+
+ act(() => {
+ emitWorktreeChanged('same');
+ emitWorktreeChanged('same');
+ });
+ await waitFor(() => expect(view.getByTestId('ids').textContent).toContain('/tmp/wt/newest'));
+
+ await act(async () => {
+ resolveFirst({ sessionId: 'same', path: '/tmp/wt/stale' });
+ });
+ expect(view.getByTestId('ids').textContent).toBe('same:/tmp/wt/newest');
+ });
+
+ it('applies concurrent events for different sessions independently', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([]);
+ let resolveFirst!: (value: { sessionId: string; path: string }) => void;
+ mocks.worktreeGetForSession.mockImplementation((sessionId: string) => {
+ if (sessionId === 'first') {
+ return new Promise((resolve) => {
+ resolveFirst = resolve;
+ });
+ }
+ return Promise.resolve({ sessionId, path: `/tmp/wt/${sessionId}` });
+ });
+ const view = render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => {
+ emitWorktreeChanged('first');
+ emitWorktreeChanged('second');
+ });
+ await waitFor(() => expect(view.getByTestId('ids').textContent).toContain('second'));
+ await act(async () => {
+ resolveFirst({ sessionId: 'first', path: '/tmp/wt/first' });
+ });
+
+ expect(view.getByTestId('ids').textContent).toBe(
+ 'first:/tmp/wt/first,second:/tmp/wt/second',
+ );
+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();
+ });
+
+ it('does not turn a sessions refresh into a worktree scan', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([]);
+ render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => emitRefresh());
+
+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();
+ });
+
+ it('discovers a worktree created by a local background session without scanning all worktrees', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([]);
+ mocks.worktreeGetForSession.mockResolvedValueOnce({
+ sessionId: 'background',
+ path: '/tmp/wt/background',
+ });
+ const view = render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => emitSessionCreated('background'));
+
+ await waitFor(() => {
+ expect(view.getByTestId('ids').textContent).toBe('background:/tmp/wt/background');
});
- expect(mocks.worktreeListAll).toHaveBeenCalledTimes(2);
+ expect(mocks.worktreeGetForSession).toHaveBeenCalledWith('background');
+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();
+ expect(mocks.worktreeDetectCwd).toHaveBeenCalledOnce();
+ });
+
+ it('does not run Git validation for a local background session without a worktree', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([]);
+ mocks.worktreeGetForSession.mockResolvedValueOnce(null);
+ render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => emitSessionCreated('notification-only'));
+
+ await waitFor(() => {
+ expect(mocks.worktreeGetForSession).toHaveBeenCalledWith('notification-only');
+ });
+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();
+ expect(mocks.worktreeDetectCwd).not.toHaveBeenCalled();
+ });
+
+ it('ignores remote session creation pushes for the local worktree cache', async () => {
+ mocks.worktreeListAll.mockResolvedValueOnce([]);
+ render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => {
+ emitSessionCreated('remote-collision', {
+ dataOwnerId: 'owner',
+ ownerGeneration: 1,
+ });
+ });
+
+ expect(mocks.worktreeGetForSession).not.toHaveBeenCalled();
+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();
+ });
+
+ it('still performs a full validation when the window regains focus', async () => {
+ mocks.worktreeListAll.mockResolvedValue([]);
+ render(
+ <WorktreeProvider>
+ <Probe />
+ </WorktreeProvider>,
+ );
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());
+
+ act(() => window.dispatchEvent(new Event('focus')));
+
+ await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledTimes(2));
});
it('unsubscribes on unmount so a later push cannot refresh a dead tree', async () => {
@@ -98,9 +300,11 @@ describe('WorktreeContext recycle refresh', () => {
view.unmount();
expect(mocks.listeners.size).toBe(0);
+ expect(mocks.sessionCreatedListeners.size).toBe(0);
emitWorktreeChanged('archived-one');
expect(mocks.worktreeListAll).toHaveBeenCalledTimes(1);
+ expect(mocks.worktreeGetForSession).not.toHaveBeenCalled();
});
it('still mounts when the push channel is unavailable', async () => {
@@ -118,7 +322,7 @@ describe('WorktreeContext recycle refresh', () => {
);
await waitFor(() => {
- expect(view.getByTestId('ids').textContent).toBe('only');
+ expect(view.getByTestId('ids').textContent).toBe('only:/tmp/wt/only');
});
});
@@ -140,7 +344,7 @@ describe('WorktreeContext recycle refresh', () => {
);
await waitFor(() => {
- expect(view.getByTestId('ids').textContent).toBe('live');
+ expect(view.getByTestId('ids').textContent).toBe('live:/tmp/wt/live');
});
});
});
diff --git a/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx b/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
index 8378b93097..df1928cae8 100644
--- a/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx
@@ -33,7 +33,7 @@ import { FolderX, RefreshCw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
-import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
+import { useRefreshWorktreeForSession } from '@/contexts/WorktreeContext';
import { addSessionAttention } from '@/lib/sessionAttentionStore';
import { ackErrorAlertHandled } from '@/lib/errorAlertAck';
import { refreshPendingAlerts } from '@/hooks/usePendingAlertAttention';
@@ -66,7 +66,7 @@ export function WorktreeRestoreBanner({
style?: React.CSSProperties;
}) {
const { t } = useTranslation();
- const refreshWorktrees = useRefreshWorktrees();
+ const refreshWorktreeForSession = useRefreshWorktreeForSession();
const [phase, setPhase] = useState<BannerPhase>('hidden');
const [variant, setVariant] = useState<BannerVariant>('missing');
/** 本组件给哪个会话打过红点 —— 清点只清自己打的,不误伤 live error 等其它来源。 */
@@ -152,7 +152,7 @@ export function WorktreeRestoreBanner({
// 恢复成功 = 告警消失,清**发起时那个会话**的红点(过期完成会被忽略)。
clearOwnAttentionFor(target);
}
- void refreshWorktrees();
+ void refreshWorktreeForSession(target);
} else {
toast.error(
t('chat.worktreeRestoreBanner.failed', {
@@ -169,7 +169,7 @@ export function WorktreeRestoreBanner({
);
setPhase('restorable');
}
- }, [clearOwnAttentionFor, refreshWorktrees, sessionId, t]);
+ }, [clearOwnAttentionFor, refreshWorktreeForSession, sessionId, t]);
if (phase === 'hidden') return null;
const restoring = phase === 'restoring';
diff --git a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx b/apps/desktop/src/renderer/contexts/WorktreeContext.tsx
index a25d7ea53b..5d032da919 100644
--- a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx
+++ b/apps/desktop/src/renderer/contexts/WorktreeContext.tsx
@@ -4,9 +4,11 @@
*
* worktree-parallel-sessions 前端方案 M2:
* - mount 时拉一次 listAll
- * - create 成功 / close 完成后由调用方主动 refresh()
- * - 归档/删除的 worktree 回收跑完后,由 main 的 `worktree:changed` 推送触发重拉
- * (回收是异步链,调用方那次主动 refresh 会拿到回收前的旧快照)
+ * - create / restore 成功后由调用方按 sessionId 主动增量更新
+ * - Scheduler / hook 等 main 侧后台创建完成后,复用 sessions:created 按
+ * sessionId 增量发现 worktree
+ * - 归档/删除的 worktree 回收跑完后,由 main 的 `worktree:changed` 推送按
+ * sessionId 增量更新;启动和窗口聚焦时才做全量存活校验
*
* 与项目内 AuthContext / EnvCheckContext 同
* Provider+hooks 范式,不引入新状态库。
@@ -24,7 +26,6 @@ import {
} from 'react';
import type { WorktreeMeta } from '@/lib/worktree.types';
-import { onRefresh as onSessionsRefresh } from '@/lib/sessionsBus';
import { createLogger } from '@/lib/logger';
const log = createLogger('WorktreeContext');
@@ -44,39 +45,82 @@ async function isLiveOfficialPath(cwd: string): Promise<boolean> {
interface WorktreeContextValue {
/** sessionId → meta;非 null 即代表此 session 正绑定一个 worktree。 */
metas: Record<string, WorktreeMeta>;
- /** 重新从 main 拉 listAll 并替换内部缓存。 */
- refresh: () => Promise<void>;
+ /** 从 main 查询并更新单个 session 的 worktree 缓存。 */
+ refreshSession: (sessionId: string) => Promise<void>;
}
const WorktreeContext = createContext<WorktreeContextValue | null>(null);
export function WorktreeProvider({ children }: { children: ReactNode }) {
const [metas, setMetas] = useState<Record<string, WorktreeMeta>>({});
- // 防止并发 refresh 重复落库(mount + 业务侧 refresh 撞车时取最新一次)
- const inflightRef = useRef(0);
+ // 全量刷新彼此只接收最后一次;单条事件另按 sessionId 记代次,避免连续回收时
+ // 一个 session 的迟到响应覆盖另一个 session 的新状态。
+ const fullRefreshGenerationRef = useRef(0);
+ const eventGenerationRef = useRef(0);
+ const sessionEventGenerationsRef = useRef(new Map<string, number>());
const refresh = useCallback(async () => {
- const myTurn = ++inflightRef.current;
+ const myTurn = ++fullRefreshGenerationRef.current;
+ const eventGenerationAtStart = eventGenerationRef.current;
try {
const list = await window.electronAPI.worktreeListAll();
// 中间发生了更新的 refresh,丢弃本次结果
- if (myTurn !== inflightRef.current) return;
+ if (myTurn !== fullRefreshGenerationRef.current) return;
const next: Record<string, WorktreeMeta> = {};
await Promise.all(
(list ?? []).map(async (meta) => {
if (!meta?.sessionId || !meta.path) return;
if (!(await isLiveOfficialPath(meta.path))) return;
- if (myTurn !== inflightRef.current) return;
+ if (myTurn !== fullRefreshGenerationRef.current) return;
next[meta.sessionId] = meta;
}),
);
- if (myTurn !== inflightRef.current) return;
- setMetas(next);
+ if (myTurn !== fullRefreshGenerationRef.current) return;
+ setMetas((current) => {
+ const merged = { ...next };
+ // 全量探测期间若某个 session 收到更晚的权威事件,只保留该 session 当前
+ // 的增量结果;未完成的增量请求随后会再落一次,不能让旧全量快照回写。
+ for (const [sessionId, generation] of sessionEventGenerationsRef.current) {
+ if (generation <= eventGenerationAtStart) continue;
+ if (current[sessionId]) merged[sessionId] = current[sessionId];
+ else delete merged[sessionId];
+ }
+ return merged;
+ });
} catch (err) {
log.warn('refresh failed:', err);
}
}, []);
+ const refreshSession = useCallback(async (sessionId: string) => {
+ const getForSession = window.electronAPI?.worktreeGetForSession;
+ if (!getForSession) return;
+ const generation = ++eventGenerationRef.current;
+ sessionEventGenerationsRef.current.set(sessionId, generation);
+ const fullRefreshGenerationAtStart = fullRefreshGenerationRef.current;
+ const isCurrent = () =>
+ sessionEventGenerationsRef.current.get(sessionId) === generation &&
+ fullRefreshGenerationRef.current === fullRefreshGenerationAtStart;
+ try {
+ const meta = await getForSession(sessionId);
+ if (!isCurrent()) return;
+ const next =
+ meta?.sessionId === sessionId && meta.path && (await isLiveOfficialPath(meta.path))
+ ? meta
+ : null;
+ if (!isCurrent()) return;
+ setMetas((current) => {
+ if (next) return { ...current, [sessionId]: next };
+ if (!current[sessionId]) return current;
+ const updated = { ...current };
+ delete updated[sessionId];
+ return updated;
+ });
+ } catch (err) {
+ log.warn('session refresh failed:', { sessionId, err });
+ }
+ }, []);
+
useEffect(() => {
void refresh();
const onFocus = () => {
@@ -86,28 +130,37 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {
return () => window.removeEventListener('focus', onFocus);
}, [refresh]);
- // 复用 sessionsBus 的 refresh 事件 —— delete / archive 完成后会触发一次,
- // 顺手刷一次 worktree map。
- useEffect(() => {
- return onSessionsRefresh(() => {
- void refresh();
- });
- }, [refresh]);
-
// 权威时机在这条推送上:main 侧的 worktree 回收是 fire-and-forget 的异步链
// (关子进程 → git worktree remove → 文件系统清理),store 条目被移除的时刻
- // 远晚于归档/删除的状态 IPC 返回。上面那次「顺手刷」几乎必然快照到仍然存在的
- // 旧条目,徽标会一直停在回收前的状态,直到某次无关刷新才纠正(codex review P1)。
- // main 在回收链结束后广播 worktree:changed,这里再拉一次拿到真实结果。
+ // 远晚于归档/删除的状态 IPC 返回。main 只为实际涉及 worktree 的 session 广播,
+ // 这里也只查询、校验并更新这一条,不再扫描其它 worktree。
useEffect(() => {
const subscribe = window.electronAPI?.onWorktreeChanged;
if (!subscribe) return;
- return subscribe(() => {
- void refresh();
+ return subscribe(({ sessionId }) => {
+ if (!sessionId) return;
+ void refreshSession(sessionId);
});
- }, [refresh]);
+ }, [refreshSession]);
+
+ // Renderer 主动创建/恢复时调用方会直接 refreshSession;Scheduler、hook-control
+ // 等后台入口只会在 session 建成后广播 sessions:created。这里同样只查该 session,
+ // 没有 worktree 时 getForSession 返回 null,不会进入路径探测,更不会扫描全表。
+ // 本机 emitSessionCreated 不带 ownerStamp;带 stamp 的是 device-link 转发,远端
+ // worktree 元数据不归本机 WorktreeContext,必须忽略以防相同 sessionId 误贴。
+ useEffect(() => {
+ const subscribe = window.electronAPI?.localDb?.sessionsPush?.onCreated;
+ if (!subscribe) return;
+ return subscribe(({ sessionId }, ownerStamp) => {
+ if (ownerStamp !== undefined || !sessionId) return;
+ void refreshSession(sessionId);
+ });
+ }, [refreshSession]);
- const value = useMemo<WorktreeContextValue>(() => ({ metas, refresh }), [metas, refresh]);
+ const value = useMemo<WorktreeContextValue>(
+ () => ({ metas, refreshSession }),
+ [metas, refreshSession],
+ );
return <WorktreeContext.Provider value={value}>{children}</WorktreeContext.Provider>;
}
@@ -132,7 +185,7 @@ export function useWorktreeForSession(sessionId: string | null | undefined): Wor
return metas[sessionId] ?? null;
}
-/** 让调用方在 create / close 后主动触发 Context 刷新。 */
-export function useRefreshWorktrees(): () => Promise<void> {
- return useCtx().refresh;
+/** 让创建/恢复等明确知道 sessionId 的调用方只刷新对应 worktree。 */
+export function useRefreshWorktreeForSession(): (sessionId: string) => Promise<void> {
+ return useCtx().refreshSession;
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 9565dd1853..16f75d6394 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -67,7 +67,6 @@ import { SidebarTopNav } from '@/components/sidebar/SidebarTopNav';
import { SidebarFilterPopover } from './sidebar/SidebarFilterPopover';
import { MainListScopeHeader } from './sidebar/MainListScopeHeader';
import { stripTrailingPathSeparators } from '../../../shared/pathText';
-import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
import {
SessionAttentionUrgencyProvider,
useSessionAttentionUrgencySet,
@@ -825,7 +824,6 @@ function ExpandedView({
setProjectHidden,
initialSnapshot: sidebarSettingsSnapshot,
} = hiddenProjects;
- const refreshWorktrees = useRefreshWorktrees();
const projectPickerOptions = useProjectPickerOptions();
// 自动化任务本身仍在顶部 Automations 入口管理;自动化任务 fire 后创建出的
@@ -852,7 +850,6 @@ function ExpandedView({
const handleScheduleDeleted = useCallback(
async ({ disposition, affectedSessionIds }: DeletedScheduleGeneratedSessionResult) => {
await refreshSessions();
- void refreshWorktrees();
// 重定向判定用 viewedSessionId(files 路由兜底,与其余归档/删除 handler
// 同口径):从面板删 schedule 连带清掉正在浏览的会话时也要跳离文件视图。
if (
@@ -863,7 +860,7 @@ function ExpandedView({
navigate('/cc-agent');
}
},
- [viewedSessionId, navigate, refreshSessions, refreshWorktrees],
+ [viewedSessionId, navigate, refreshSessions],
);
const { requestDeleteSchedule, deleteScheduleDialog } = useDeleteScheduleWithSessions({
onDeleted: handleScheduleDeleted,
@@ -2914,15 +2911,17 @@ function ExpandedView({
for (const session of candidates) {
makerChatStore.closeSessionQuery(session.id);
try {
- // patchMeta 按来源路由:远程会话经隧道写被控端 patch-meta(allowlist 内),本地仍走 update。
- await sessionService.patchMeta(session.id, { status: 'deleted' });
+ // 先固定本次状态写目标:关闭远端控制后,复制库里与 sticky origin 同 ID 的任务
+ // 必须按本地任务删除;真正远端任务仍固定经隧道写被控端。
+ const statusWriteTarget = await sessionService.resolveStatusWriteTarget(session.id);
+ await sessionService.setStatus(session.id, 'deleted', statusWriteTarget);
makerChatStore.purgeSession(session.id);
discardComposerDraft(session.id);
// RSB 布局偏好(fraction / treeWidth / collapsed)走 localStorage 是
// 本机概念,本地 + 远程 session 都要清(被控端的 localStorage 由被控端自己处理)。
cleanupSessionLayoutPrefs(session.id);
// 图片缓存清理是本机概念;远程会话的图在被控端,由被控端自己的删除流程处理。
- if (!session.deviceLinkDeviceId) {
+ if (statusWriteTarget.kind === 'local') {
void window.electronAPI.cleanupSessionImages(session.id).catch((err: unknown) => {
log.warn('[bulk session delete] cleanup images failed', err);
});
@@ -2938,7 +2937,6 @@ function ExpandedView({
candidates.filter((session) => !failedIds.has(session.id)).map((session) => session.id),
);
await refreshSessions();
- void refreshWorktrees();
if (viewedSessionId && succeededIds.has(viewedSessionId)) {
const redirectRoute = await resolveSessionRemovalRedirect(
@@ -2976,7 +2974,6 @@ function ExpandedView({
handleClearSelection,
navigate,
refreshSessions,
- refreshWorktrees,
resolveSessionRemovalRedirect,
selectedSessions,
t,
@@ -3060,10 +3057,12 @@ function ExpandedView({
for (const session of candidates) {
makerChatStore.closeSessionQuery(session.id);
try {
- // patchMeta 按来源路由:远程会话经隧道写被控端;本地仍走 update。
- await sessionService.patchMeta(session.id, { status: 'archived', pinnedAt: null });
+ // 与单条归档共用同一目标判定,避免复制数据库后的 sticky sessionId 冲突
+ // 被误送往已经关闭控制的设备。
+ const statusWriteTarget = await sessionService.resolveStatusWriteTarget(session.id);
+ await sessionService.setStatus(session.id, 'archived', statusWriteTarget);
// 乐观本地 patch 只对本机会话;远程会话由隧道广播 sessions:patched → applyPatch 更新远程分片。
- if (!session.deviceLinkDeviceId) {
+ if (statusWriteTarget.kind === 'local') {
patchLocal(session.id, { status: 'archived', pinnedAt: null });
}
makerChatStore.purgeSession(session.id);
@@ -3079,7 +3078,6 @@ function ExpandedView({
candidates.filter((session) => !failedIds.has(session.id)).map((session) => session.id),
);
await refreshSessions();
- void refreshWorktrees();
if (viewedSessionId && succeededIds.has(viewedSessionId)) {
navigate('/cc-agent');
@@ -3112,7 +3110,6 @@ function ExpandedView({
navigate,
patchLocal,
refreshSessions,
- refreshWorktrees,
runningSessionIds,
selectedSessions,
t,
@@ -3263,7 +3260,6 @@ function ExpandedView({
const succeededIds = new Set(candidates.filter((s) => !failedIds.has(s.id)).map((s) => s.id));
await refreshSessions();
- void refreshWorktrees();
// 当前注视中的 session 被归档了 → 走 /cc-agent 让 CCAgentIndexRedirect
// 做 Orca-aware 的「选下一条 / 空则跳 new」决策(见 runSessionAction 同位置注释)。
@@ -3287,7 +3283,6 @@ function ExpandedView({
runningSessionIds,
confirmDialog,
refreshSessions,
- refreshWorktrees,
viewedSessionId,
navigate,
patchLocal,
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 507e3113c0..2f1911037d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -138,7 +138,7 @@ import {
rewritePiSkillMessageForSend,
} from '@/lib/slashCommands';
import { worktreeCreationStore } from '@/lib/worktreeCreationStore';
-import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
+import { useRefreshWorktreeForSession } from '@/contexts/WorktreeContext';
import { crossAgentConvertService } from '@/lib/crossAgentConvertService';
import {
consumeNewMakerDialogueTargetRequest,
@@ -637,7 +637,7 @@ export function NewMakerDraftRoute() {
const isDraftToolbarNarrow = inputWidthBand <= 1;
const { createSession, error: createSessionError } = useCCSessions();
const vendorAuthGate = useVendorAuthGate();
- const refreshWorktrees = useRefreshWorktrees();
+ const refreshWorktreeForSession = useRefreshWorktreeForSession();
/** createSession 失败 toast:远端路由错误按 code 给可操作文案,其余回退通用文案。 */
const toastCreateSessionFailed = (err?: unknown) => {
@@ -3914,7 +3914,7 @@ export function NewMakerDraftRoute() {
restoreFirstMessageDraft();
return;
}
- await refreshWorktrees();
+ await refreshWorktreeForSession(newSession.id);
// 注意:成功后不立刻 clear worktreeCreationStore —— 移到 sendMessage
// 触发之后再 clear, 让 CCAgentSessionView 里 worktreePreparing 一直
// true 到 sendMessage 已经 push 第一条 user message + isStreaming=true
@@ -4208,7 +4208,7 @@ export function NewMakerDraftRoute() {
navigate,
crossAgentDialog.runMigrationFlow,
attachmentState,
- refreshWorktrees,
+ refreshWorktreeForSession,
t,
],
);
@@ -4696,7 +4696,7 @@ export function NewMakerDraftRoute() {
setProgress: (progress) => worktreeCreationStore.set(newSession.id, progress),
clearProgress: () => worktreeCreationStore.clear(newSession.id),
});
- await refreshWorktrees();
+ await refreshWorktreeForSession(newSession.id);
}
{
const iso = new Date().toISOString();
@@ -4821,7 +4821,7 @@ export function NewMakerDraftRoute() {
localProviders,
localProvidersLoading,
patchCollab,
- refreshWorktrees,
+ refreshWorktreeForSession,
navigate,
t,
],
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
index 896126e827..e58a05bb59 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSessionLifecycleActions.test.tsx
@@ -6,16 +6,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
setStatus: vi.fn(),
+ resolveStatusWriteTarget: vi.fn(),
refreshSessions: vi.fn(),
emitRefresh: vi.fn(),
patchLocal: vi.fn(),
+ beginStatusTransition: vi.fn(),
+ beginStatusTransitionWhenReady: vi.fn(),
+ completeStatusTransition: vi.fn(),
+ rollbackStatusTransition: vi.fn(),
closeSessionQuery: vi.fn(),
purgeSession: vi.fn(),
clearComposerDraft: vi.fn(),
cleanupSessionLayoutPrefs: vi.fn(),
- refreshWorktrees: vi.fn(),
cleanupSessionImages: vi.fn(),
toastError: vi.fn(),
+ logInfo: vi.fn(),
+ logWarn: vi.fn(),
+ logError: vi.fn(),
}));
vi.mock('react-router-dom', () => ({
@@ -32,6 +39,7 @@ vi.mock('@/lib/toast', () => ({
vi.mock('@/lib/sessionService', () => ({
setStatus: mocks.setStatus,
+ resolveStatusWriteTarget: mocks.resolveStatusWriteTarget,
}));
vi.mock('@/lib/makerChatStore', () => ({
@@ -53,6 +61,15 @@ vi.mock('@/lib/sessionsBus', () => ({
emitRefresh: mocks.emitRefresh,
}));
+vi.mock('@/lib/sessionsStore', () => ({
+ sessionsStore: {
+ beginStatusTransition: mocks.beginStatusTransition,
+ beginStatusTransitionWhenReady: mocks.beginStatusTransitionWhenReady,
+ completeStatusTransition: mocks.completeStatusTransition,
+ rollbackStatusTransition: mocks.rollbackStatusTransition,
+ },
+}));
+
vi.mock('@/hooks/useCCSessions', () => ({
useCCSessions: () => ({
refreshSessions: mocks.refreshSessions,
@@ -60,19 +77,37 @@ vi.mock('@/hooks/useCCSessions', () => ({
}),
}));
-vi.mock('@/contexts/WorktreeContext', () => ({
- useRefreshWorktrees: () => mocks.refreshWorktrees,
-}));
-
vi.mock('@/lib/logger', () => ({
- createLogger: () => ({ error: vi.fn(), warn: vi.fn() }),
+ createLogger: () => ({
+ info: mocks.logInfo,
+ warn: mocks.logWarn,
+ error: mocks.logError,
+ }),
}));
import { useSessionLifecycleActions } from '../useSessionLifecycleActions';
beforeEach(() => {
vi.clearAllMocks();
- mocks.setStatus.mockResolvedValue({});
+ mocks.setStatus.mockImplementation(async (id: string, status: string) => ({
+ id,
+ status,
+ title: `title-${id}`,
+ updatedAt: '2026-08-27T00:00:00.000Z',
+ }));
+ mocks.resolveStatusWriteTarget.mockResolvedValue({ kind: 'local' });
+ mocks.beginStatusTransition.mockImplementation((sessionId: string) => ({
+ sessionId,
+ token: 1,
+ }));
+ mocks.beginStatusTransitionWhenReady.mockImplementation(
+ async (sessionId: string, patch: unknown, apply?: (begin: () => unknown) => unknown) => {
+ const begin = () => mocks.beginStatusTransition(sessionId, patch);
+ return apply ? apply(begin) : begin();
+ },
+ );
+ mocks.completeStatusTransition.mockReturnValue(true);
+ mocks.rollbackStatusTransition.mockReturnValue(true);
mocks.refreshSessions.mockResolvedValue([]);
mocks.cleanupSessionImages.mockResolvedValue(undefined);
Object.defineProperty(window, 'electronAPI', {
@@ -95,14 +130,34 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
});
- expect(mocks.patchLocal).toHaveBeenCalledWith('session-1', {
+ expect(mocks.beginStatusTransition).toHaveBeenCalledWith('session-1', {
status: 'archived',
pinnedAt: null,
});
- expect(mocks.patchLocal.mock.invocationCallOrder[0]).toBeLessThan(
+ expect(mocks.beginStatusTransition.mock.invocationCallOrder[0]).toBeLessThan(
mocks.navigate.mock.invocationCallOrder[0],
);
expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/new');
+ expect(mocks.completeStatusTransition).toHaveBeenCalledWith(
+ { sessionId: 'session-1', token: 1 },
+ expect.objectContaining({ id: 'session-1', status: 'archived' }),
+ );
+ expect(mocks.emitRefresh).not.toHaveBeenCalled();
+ expect(mocks.refreshSessions).not.toHaveBeenCalled();
+ expect(mocks.logInfo).toHaveBeenCalledWith(
+ 'archive timing',
+ expect.objectContaining({
+ event: 'renderer.session.archive.timing',
+ outcome: 'success',
+ sessionId: 'session-1',
+ deviceLink: false,
+ preWriteMs: expect.any(Number),
+ writeMs: expect.any(Number),
+ convergeMs: expect.any(Number),
+ cleanupMs: expect.any(Number),
+ totalMs: expect.any(Number),
+ }),
+ );
});
it('navigates first when the archived row stays visible in the all bucket', async () => {
@@ -117,7 +172,7 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
expect(mocks.navigate.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.patchLocal.mock.invocationCallOrder[0],
+ mocks.beginStatusTransition.mock.invocationCallOrder[0],
);
});
@@ -132,7 +187,7 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
});
- expect(mocks.patchLocal).toHaveBeenCalled();
+ expect(mocks.beginStatusTransition).toHaveBeenCalled();
expect(mocks.navigate).not.toHaveBeenCalled();
});
@@ -148,15 +203,119 @@ describe('useSessionLifecycleActions archive optimistic ordering', () => {
});
});
- expect(mocks.patchLocal.mock.calls).toEqual([
- ['session-1', { status: 'archived', pinnedAt: null }],
- ['session-1', { status: 'active' }],
- ]);
- expect(mocks.patchLocal.mock.invocationCallOrder[0]).toBeLessThan(
+ expect(mocks.beginStatusTransition).toHaveBeenCalledWith('session-1', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(mocks.beginStatusTransition.mock.invocationCallOrder[0]).toBeLessThan(
mocks.setStatus.mock.invocationCallOrder[0],
);
+ expect(mocks.rollbackStatusTransition).toHaveBeenCalledWith({
+ sessionId: 'session-1',
+ token: 1,
+ });
expect(mocks.toastError).toHaveBeenCalledWith('ccAgent.sidebar.archiveFailed');
expect(mocks.purgeSession).not.toHaveBeenCalled();
+ expect(mocks.logWarn).toHaveBeenCalledWith(
+ 'archive timing',
+ expect.objectContaining({
+ event: 'renderer.session.archive.timing',
+ outcome: 'failed',
+ sessionId: 'session-1',
+ deviceLink: false,
+ preWriteMs: expect.any(Number),
+ writeMs: expect.any(Number),
+ totalMs: expect.any(Number),
+ }),
+ );
+ });
+
+ it('does not turn consecutive archives into global or current-bucket refreshes', async () => {
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'active' }),
+ );
+
+ await act(async () => {
+ await result.current.runSessionAction('session-1', 'archive', { activeSessionId: null });
+ await result.current.runSessionAction('session-2', 'archive', { activeSessionId: null });
+ await result.current.runSessionAction('session-3', 'archive', { activeSessionId: null });
+ });
+
+ expect(mocks.setStatus).toHaveBeenCalledTimes(3);
+ expect(mocks.beginStatusTransition).toHaveBeenCalledTimes(3);
+ expect(mocks.completeStatusTransition).toHaveBeenCalledTimes(3);
+ expect(mocks.emitRefresh).not.toHaveBeenCalled();
+ expect(mocks.refreshSessions).not.toHaveBeenCalled();
+ });
+
+ it('uses the serialized begin before starting the archive write', async () => {
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'all' }),
+ );
+
+ await act(async () => {
+ await result.current.runSessionAction('session-1', 'archive', {
+ activeSessionId: null,
+ });
+ });
+
+ expect(mocks.beginStatusTransitionWhenReady).toHaveBeenCalledWith(
+ 'session-1',
+ { status: 'archived', pinnedAt: null },
+ expect.any(Function),
+ );
+ expect(mocks.beginStatusTransition.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.setStatus.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('converges a disabled remote-id collision through the local status buckets', async () => {
+ mocks.resolveStatusWriteTarget.mockResolvedValueOnce({ kind: 'local' });
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'active' }),
+ );
+
+ await act(async () => {
+ await result.current.runSessionAction('copied-local-session', 'archive', {
+ activeSessionId: null,
+ });
+ });
+
+ expect(mocks.setStatus).toHaveBeenCalledWith('copied-local-session', 'archived', {
+ kind: 'local',
+ });
+ expect(mocks.beginStatusTransition).toHaveBeenCalledWith('copied-local-session', {
+ status: 'archived',
+ pinnedAt: null,
+ });
+ expect(mocks.completeStatusTransition).toHaveBeenCalledWith(
+ { sessionId: 'copied-local-session', token: 1 },
+ expect.objectContaining({ id: 'copied-local-session', status: 'archived' }),
+ );
+ });
+
+ it('leaves device-link archive convergence to the remote mirror', async () => {
+ mocks.resolveStatusWriteTarget.mockResolvedValueOnce({
+ kind: 'device-link',
+ deviceId: 'device-1',
+ });
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'active' }),
+ );
+
+ await act(async () => {
+ await result.current.runSessionAction('remote-session', 'archive', {
+ activeSessionId: null,
+ });
+ });
+
+ expect(mocks.setStatus).toHaveBeenCalledWith('remote-session', 'archived', {
+ kind: 'device-link',
+ deviceId: 'device-1',
+ });
+ expect(mocks.beginStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.completeStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.patchLocal).not.toHaveBeenCalled();
});
});
@@ -168,16 +327,15 @@ describe('useSessionLifecycleActions delete cache invalidation', () => {
await result.current.runSessionAction('session-1', 'delete', { activeSessionId: null });
});
- expect(mocks.setStatus).toHaveBeenCalledWith('session-1', 'deleted');
- expect(mocks.patchLocal).toHaveBeenCalledWith('session-1', { status: 'deleted' });
+ expect(mocks.setStatus).toHaveBeenCalledWith('session-1', 'deleted', { kind: 'local' });
+ expect(mocks.patchLocal).toHaveBeenCalledWith(
+ 'session-1',
+ expect.objectContaining({ id: 'session-1', status: 'deleted' }),
+ );
expect(mocks.setStatus.mock.invocationCallOrder[0]).toBeLessThan(
mocks.patchLocal.mock.invocationCallOrder[0],
);
- // 兜底重拉走 emitRefresh(强制重拉所有已加载桶),不是只刷当前桶的
- // refreshSessions —— 见 hook 里关于 archived 目标桶的注释。
- expect(mocks.patchLocal.mock.invocationCallOrder[0]).toBeLessThan(
- mocks.emitRefresh.mock.invocationCallOrder[0],
- );
+ expect(mocks.emitRefresh).not.toHaveBeenCalled();
expect(mocks.refreshSessions).not.toHaveBeenCalled();
});
@@ -195,3 +353,100 @@ describe('useSessionLifecycleActions delete cache invalidation', () => {
expect(mocks.toastError).toHaveBeenCalledWith('ccAgent.sidebar.deleteFailed');
});
});
+
+describe('useSessionLifecycleActions unarchive convergence', () => {
+ it('uses the serialized begin before starting the restore write', async () => {
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'archived' }),
+ );
+
+ await act(async () => {
+ await result.current.unarchiveSession('session-1');
+ });
+
+ expect(mocks.beginStatusTransitionWhenReady).toHaveBeenCalledWith('session-1', {
+ status: 'active',
+ });
+ expect(mocks.beginStatusTransition.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.setStatus.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('stops a queued restore when the session store resets', async () => {
+ mocks.beginStatusTransitionWhenReady.mockResolvedValueOnce(null);
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'archived' }),
+ );
+
+ await act(async () => {
+ await result.current.unarchiveSession('session-1');
+ });
+
+ expect(mocks.beginStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.setStatus).not.toHaveBeenCalled();
+ });
+
+ it('uses a serialized local transition and the persisted row without refreshing', async () => {
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'archived' }),
+ );
+
+ await act(async () => {
+ await result.current.unarchiveSession('session-1');
+ });
+
+ expect(mocks.beginStatusTransition).toHaveBeenCalledWith('session-1', {
+ status: 'active',
+ });
+ expect(mocks.beginStatusTransition.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.setStatus.mock.invocationCallOrder[0],
+ );
+ expect(mocks.completeStatusTransition).toHaveBeenCalledWith(
+ { sessionId: 'session-1', token: 1 },
+ expect.objectContaining({ id: 'session-1', status: 'active' }),
+ );
+ expect(mocks.emitRefresh).not.toHaveBeenCalled();
+ expect(mocks.refreshSessions).not.toHaveBeenCalled();
+ });
+
+ it('rolls back every loaded local bucket when the restore write fails', async () => {
+ mocks.setStatus.mockRejectedValueOnce(new Error('write failed'));
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'archived' }),
+ );
+
+ await act(async () => {
+ await result.current.unarchiveSession('session-1');
+ });
+
+ expect(mocks.rollbackStatusTransition).toHaveBeenCalledWith({
+ sessionId: 'session-1',
+ token: 1,
+ });
+ expect(mocks.refreshSessions).not.toHaveBeenCalled();
+ expect(mocks.toastError).toHaveBeenCalledWith('ccAgent.sidebar.unarchiveFailed');
+ });
+
+ it('leaves device-link restore convergence to the remote mirror', async () => {
+ mocks.resolveStatusWriteTarget.mockResolvedValueOnce({
+ kind: 'device-link',
+ deviceId: 'device-1',
+ });
+ const { result } = renderHook(() =>
+ useSessionLifecycleActions({ includeArchived: 'archived' }),
+ );
+
+ await act(async () => {
+ await result.current.unarchiveSession('remote-session');
+ });
+
+ expect(mocks.setStatus).toHaveBeenCalledWith('remote-session', 'active', {
+ kind: 'device-link',
+ deviceId: 'device-1',
+ });
+ expect(mocks.beginStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.completeStatusTransition).not.toHaveBeenCalled();
+ expect(mocks.patchLocal).not.toHaveBeenCalled();
+ expect(mocks.refreshSessions).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
index 75db2e48ea..273efddbce 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSessionLifecycleActions.ts
@@ -30,12 +30,11 @@ import * as sessionService from '@/lib/sessionService';
import { makerChatStore } from '@/lib/makerChatStore';
import { discardDraft as discardComposerDraft } from '@/lib/composerDraftStore';
import { cleanupSessionLayoutPrefs } from '@/lib/sessionLayoutPrefs';
-import { emitRefresh } from '@/lib/sessionsBus';
+import { sessionsStore, type SessionStatusTransitionToken } from '@/lib/sessionsStore';
import { useCCSessions } from '@/hooks/useCCSessions';
-import { useRefreshWorktrees } from '@/contexts/WorktreeContext';
import { createLogger } from '@/lib/logger';
import type { ListStatusFilter } from '@/lib/sessionService';
-import type { SessionStatus } from '@/lib/ccAgent.types';
+import type { Session, SessionStatus } from '@/lib/ccAgent.types';
const log = createLogger('useSessionLifecycleActions');
@@ -56,7 +55,6 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
// 与调用方组件里的 useCCSessions 实例共享同一份 cache。
// includeArchived 跟随调用方的桶(见文件头注释)。
const { refreshSessions, patchLocal } = useCCSessions(options);
- const refreshWorktrees = useRefreshWorktrees();
// 取成 string 再进 deps —— options 是调用方每次渲染新建的字面量对象,直接放进
// runSessionAction 的 deps 会让它每次重建,打穿 sidebar 的行 handler memo
// (行渲染隔离不变量,见 SessionItem.tsx)。
@@ -71,7 +69,11 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
action: 'delete' | 'archive',
{ activeSessionId, deleteRedirectRoute }: RunSessionActionOptions,
) => {
+ const actionStartedAt = performance.now();
const targetStatus: SessionStatus = action === 'delete' ? 'deleted' : 'archived';
+ const statusWriteTarget = await sessionService.resolveStatusWriteTarget(sessionId);
+ const isDeviceLinkSession = statusWriteTarget.kind === 'device-link';
+ let statusTransition: SessionStatusTransitionToken | null = null;
// device-link 远程会话:status 写经隧道(setStatus 内部按来源路由 patch-meta),被控端写库后
// 广播 sessions:patched{status} → 控制端 applyPatch 把它移出分片(纯镜像,无需乐观/重拉)。
@@ -98,7 +100,7 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
//
// Delete 仍走原来的"先 DB 后清理"流程:delete 不可逆,乐观删除如果 DB 失
// 败会让用户看到"行消失又出现"的诡异闪烁,代价比 archive 大。写库成功
- // 后再用 patchLocal 从所有桶移除,并由 emitRefresh 强制重拉所有桶兜底。
+ // 后再用 patchLocal 从所有桶移除。
const archivedRowStaysInList = listFilter === 'all';
const leaveArchivedSession = () => {
if (sessionId === activeSessionId) navigate('/cc-agent/new');
@@ -106,9 +108,23 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
if (archivedRowStaysInList) {
flushSync(leaveArchivedSession);
}
- flushSync(() => {
- patchLocal(sessionId, { status: 'archived', pinnedAt: null });
- });
+ if (!isDeviceLinkSession) {
+ statusTransition = await sessionsStore.beginStatusTransitionWhenReady(
+ sessionId,
+ {
+ status: 'archived',
+ pinnedAt: null,
+ },
+ (begin) => {
+ let transition: SessionStatusTransitionToken | null = null;
+ flushSync(() => {
+ transition = begin();
+ });
+ return transition;
+ },
+ );
+ if (!statusTransition) return;
+ }
if (!archivedRowStaysInList) {
leaveArchivedSession();
}
@@ -118,18 +134,31 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
// query,不影响列表,没有理由挤在用户等着看到行消失的那一段前面。
makerChatStore.closeSessionQuery(sessionId);
+ const statusWriteStartedAt = performance.now();
+ let statusWriteFinishedAt = statusWriteStartedAt;
+ let persisted: Session;
try {
// setStatus 按来源路由(远程走隧道 set-status,本机走原 update);archive 时
// handler 内部一并 unpin —— 归档列表里不该再保留 pin 标记。
- await sessionService.setStatus(sessionId, targetStatus);
+ persisted = await sessionService.setStatus(sessionId, targetStatus, statusWriteTarget);
+ statusWriteFinishedAt = performance.now();
+ if (statusTransition) {
+ sessionsStore.completeStatusTransition(statusTransition, persisted);
+ }
} catch (err) {
log.error('[session action]', err);
- // Archive 乐观更新失败的回滚:把 status 改回 active(pinnedAt 已被乐观
- // 清了,如果回滚不补回原值就会丢 pin。但 oldPinnedAt 在闭包里没捕获,
- // 这里只能补 status —— pin 丢失是已知 trade-off,概率极低(只有 DB
- // 写失败这种边界场景才触发)。
+ if (statusTransition) sessionsStore.rollbackStatusTransition(statusTransition);
if (action === 'archive') {
- patchLocal(sessionId, { status: 'active' });
+ const failedAt = performance.now();
+ log.warn('archive timing', {
+ event: 'renderer.session.archive.timing',
+ outcome: 'failed',
+ sessionId,
+ deviceLink: isDeviceLinkSession,
+ preWriteMs: Math.round(statusWriteStartedAt - actionStartedAt),
+ writeMs: Math.round(failedAt - statusWriteStartedAt),
+ totalMs: Math.round(failedAt - actionStartedAt),
+ });
}
toast.error(
action === 'delete'
@@ -138,12 +167,13 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
);
return;
}
+ const statusConvergedAt = performance.now();
- if (action === 'delete') {
+ if (action === 'delete' && !isDeviceLinkSession) {
// DB 已确认删除成功后再让 sessionsStore 修正所有已加载的筛选桶。
// 仅刷新当前桶会留下陈旧的 active / all 缓存,切换筛选时已删除会话会短暂重现;
// 不在写库前乐观移除,避免失败时出现“先消失、再恢复”的反向闪烁。
- patchLocal(sessionId, { status: 'deleted' });
+ patchLocal(sessionId, persisted);
}
// MEM-1: Free all in-memory state (messages, base64 images, listeners)
@@ -161,26 +191,26 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
// localStorage,删 session 时一起清掉,避免僵尸数据堆积。
cleanupSessionLayoutPrefs(sessionId);
}
+ if (action === 'archive') {
+ const finishedAt = performance.now();
+ log.info('archive timing', {
+ event: 'renderer.session.archive.timing',
+ outcome: 'success',
+ sessionId,
+ deviceLink: isDeviceLinkSession,
+ preWriteMs: Math.round(statusWriteStartedAt - actionStartedAt),
+ writeMs: Math.round(statusWriteFinishedAt - statusWriteStartedAt),
+ convergeMs: Math.round(statusConvergedAt - statusWriteFinishedAt),
+ cleanupMs: Math.round(finishedAt - statusConvergedAt),
+ totalMs: Math.round(finishedAt - actionStartedAt),
+ });
+ }
- // 写库成功后强制重拉**所有已加载桶**。不 await —— 列表视觉已由上面的
- // patchLocal 就地改好,这里只是让缓存跟 DB 对齐;sessions:list 是
- // LEFT JOIN messages + GROUP BY + latest-message 子查询的重查询,await 它
- // 只会把后面的 refreshWorktrees / delete 跳转推迟几百毫秒。
- //
- // 为什么必须全桶、不能只刷当前桶(codex review):归档时 patchLocal 会 drop
- // 目标桶(archived,本地没有这条的完整 row)并立刻重拉,而那次重拉发生在
- // setStatus 写库**之前**,拿回来的是「还没归档」的快照。本机
- // local-db:sessions:update 对 status 变化也会广播 sessions:patched(#3175,
- // 副窗与控制端靠它收敛),但广播只修单个字段、不触发各桶重拉 ——
- // 已归档桶仍需要这里的 emitRefresh 才能看到刚归档的这条,直到某次无关刷新。
- // 与 unarchiveSession 末尾的 emitRefresh 同口径。
- emitRefresh();
+ // sessionsStore 已用任一缓存桶中的完整 row 同步迁移 active / archived / all;
+ // 完全找不到 row 时也只合并补查目标桶。这里不再发全局 refresh,避免连续归档
+ // 把每次状态写放大成所有已加载桶的一轮 fresh 查询。
// 远程会话从侧边栏消失由被控端 sessions:patched{status} 回流(applyPatch 移出分片)驱动,
// 控制端不再主动重拉 / 不再埋「主动移除」标记(掉线 vs 删除的区分见 CCAgentSessionView 优雅退出)。
- // I-2: delete/archive 都要顺手刷一次 worktree map。上面的 emitRefresh 已经会
- // 触发 WorktreeContext(它订阅 sessionsBus.onRefresh),这里再显式刷一次是为了
- // 不依赖那条链;worktree 回收真正跑完后 main 还会广播 worktree:changed。
- void refreshWorktrees();
// Archive 已在前面乐观跳到 /cc-agent/new,这里只处理 delete。调用方有列表
// 上下文时会传入按当前可见顺序解析好的 route;否则回落到 /cc-agent
@@ -189,32 +219,35 @@ export function useSessionLifecycleActions(options?: { includeArchived?: ListSta
navigate(deleteRedirectRoute ?? '/cc-agent');
}
},
- [navigate, refreshWorktrees, patchLocal, listFilter, t],
+ [navigate, patchLocal, listFilter, t],
);
/**
- * unarchive:archive 的反向操作,无副作用直接 patch,不弹确认。
- * 调用方 filter.status === 'archived' 时,unarchive 后 session 不再匹配筛选,
- * 由 refreshSessions 拉到最新列表后自然消失。
+ * unarchive:archive 的反向状态事务,不弹确认。若归档仍在写库,先等它收敛,
+ * 再以完整归档行作为恢复失败时的回滚基线。
*/
const unarchiveSession = useCallback(
async (sessionId: string) => {
- // 乐观更新本地状态,避免 refresh 期间残留 archived 视觉
- patchLocal(sessionId, { status: 'active' });
+ const statusWriteTarget = await sessionService.resolveStatusWriteTarget(sessionId);
+ const isDeviceLinkSession = statusWriteTarget.kind === 'device-link';
+ const statusTransition = isDeviceLinkSession
+ ? null
+ : await sessionsStore.beginStatusTransitionWhenReady(sessionId, { status: 'active' });
+ if (!isDeviceLinkSession && !statusTransition) return;
try {
- await sessionService.setStatus(sessionId, 'active');
+ const persisted = await sessionService.setStatus(sessionId, 'active', statusWriteTarget);
+ if (statusTransition) {
+ sessionsStore.completeStatusTransition(statusTransition, persisted);
+ }
} catch (err) {
log.error('[session unarchive]', err);
+ if (statusTransition) sessionsStore.rollbackStatusTransition(statusTransition);
toast.error(t('ccAgent.sidebar.unarchiveFailed'));
- await refreshSessions();
+ if (!statusTransition && !isDeviceLinkSession) await refreshSessions();
return;
}
- // 兜底:status 跨桶迁移由 sessionsStore.patchLocal 自动 drop+refetch 相关桶,
- // 这里再 emitRefresh 一次,确保即便存在 pre-fix 陈旧 cache,active/archived/all
- // 三桶都会被强制重拉,跟 DB 对齐(unarchive 频次低,代价可接受)。
- emitRefresh();
},
- [patchLocal, refreshSessions, t],
+ [refreshSessions, t],
);
return { runSessionAction, unarchiveSession };
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
index 3788c42aad..3b51ca8422 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sessionWorktreeInfo.ts
@@ -155,8 +155,8 @@ export function useTaskInfoWorktree(
return inflight;
};
void refresh();
- const unsubscribe = window.electronAPI.onWorktreeChanged?.(() => {
- void refresh();
+ const unsubscribe = window.electronAPI.onWorktreeChanged?.(({ sessionId }) => {
+ if (sessionId === session.id) void refresh();
});
const onFocus = () => {
void refresh();
diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.ts
index 44a44e2260..e3772c67f7 100644
--- a/apps/desktop/src/renderer/lib/sessionService.ts
+++ b/apps/desktop/src/renderer/lib/sessionService.ts
@@ -26,6 +26,10 @@ import type { SessionReference } from '../../shared/sessionReference';
*/
export type ListStatusFilter = 'active' | 'archived' | 'all';
+export type SessionStatusWriteTarget =
+ | { kind: 'local' }
+ | { kind: 'device-link'; deviceId: string };
+
function wrap<T>(p: Promise<T>): Promise<T> {
return p.catch((err: unknown) => {
const ipcError = extractIpcError(err);
@@ -185,9 +189,54 @@ export async function patchMeta(
return update(sessionId, patch);
}
+/**
+ * Resolve one status mutation before the caller starts local optimistic convergence.
+ *
+ * A restored/copied database can contain the same session id as a task mirrored from a
+ * device that the user has disabled controlling. Sticky origin deliberately survives
+ * mirror removal, so only prefer the local row when both facts are proven: that exact
+ * device is disabled locally and the current local database contains the id. Any lookup
+ * failure stays pinned to the remote device (fail closed) instead of risking a local write.
+ */
+export async function resolveStatusWriteTarget(
+ sessionId: string,
+): Promise<SessionStatusWriteTarget> {
+ const deviceId = getStickySessionDeviceId(sessionId);
+ if (!deviceId) return { kind: 'local' };
+
+ try {
+ const state = await window.electronAPI.deviceLink.getState();
+ if (!state.disabledControlDeviceIds?.includes(deviceId)) {
+ return { kind: 'device-link', deviceId };
+ }
+ } catch {
+ return { kind: 'device-link', deviceId };
+ }
+
+ try {
+ await get(sessionId);
+ return { kind: 'local' };
+ } catch {
+ return { kind: 'device-link', deviceId };
+ }
+}
+
/** status 切换便捷封装(archive 一并 unpin)。 */
-export async function setStatus(sessionId: string, status: SessionStatus): Promise<Session> {
- return patchMeta(sessionId, status === 'archived' ? { status, pinnedAt: null } : { status });
+export async function setStatus(
+ sessionId: string,
+ status: SessionStatus,
+ target?: SessionStatusWriteTarget,
+): Promise<Session> {
+ const patch = status === 'archived' ? { status, pinnedAt: null } : { status };
+ const resolvedTarget = target ?? (await resolveStatusWriteTarget(sessionId));
+ if (resolvedTarget.kind === 'local') return update(sessionId, patch);
+ return wrap(
+ window.electronAPI.deviceLink.invoke(
+ resolvedTarget.deviceId,
+ 'local-db:sessions:patch-meta',
+ [sessionId, patch],
+ ) as Promise<Session>,
+ );
}
/**
diff --git a/apps/desktop/src/renderer/lib/sessionsStore.ts b/apps/desktop/src/renderer/lib/sessionsStore.ts
index a0ed8d0ec3..7fb7a45699 100644
--- a/apps/desktop/src/renderer/lib/sessionsStore.ts
+++ b/apps/desktop/src/renderer/lib/sessionsStore.ts
@@ -20,9 +20,9 @@
* 写策略:
* - patchLocal(id, patch) 遍历所有桶就地合并字段,保留排序与位置;
* _count 浅合并,避免 { messages: 1 } 把
- * 同级计数清掉。patch.status 会顺带修正桶
- * 归属:该移出的桶就地移除(不 drop,见
- * patchLocal 注释),该补进的桶才重拉。
+ * 同级计数清掉。patch.status 会复用任一桶
+ * 里的完整 row,同步迁移 active / archived /
+ * all;完全找不到 row 时才定向补查目标桶。
* - prependCreated(session) 新建时本地插入:active / all 桶头部插入;
* archived 桶按业务永远不应包含新建项,跳过。
* 保留旧 createSession 的"省一次 IPC"优化。
@@ -110,6 +110,17 @@ function mergeSession(prev: Session, patch: Partial<Session>): Session {
return next;
}
+function mergeSessionPatch(
+ prev: Partial<Session>,
+ patch: Partial<Session>,
+): Partial<Session> {
+ const next = { ...prev, ...patch };
+ if (patch._count) {
+ next._count = { ...prev._count, ...patch._count };
+ }
+ return next;
+}
+
/**
* 自动起名的「即时标题预览」叠加层(sessionId → 预览标题)。
*
@@ -175,6 +186,219 @@ interface SessionTitleOverride {
const sessionTitleOverrides = new Map<string, SessionTitleOverride>();
let sessionTitleRevision = 0;
+interface SessionStatusOverride {
+ /** status 事件版本;rollback 用它区分同向状态是否有更晚的权威写入。 */
+ revision: number;
+ /** 后到的非 status 权威字段版本;只用于挡住更早起飞的列表快照。 */
+ rowRevision: number;
+ patch: Partial<Session>;
+ /** 状态变化前从任一已加载桶捕获的完整行;目标桶缺行时可直接迁移。 */
+ session: Session | null;
+}
+
+/**
+ * 列表请求发起后到达的 status 事件。请求返回时重放这些事件,避免旧快照把已归档、
+ * 已恢复或已删除的行写回旧桶;有完整行时也能把它补进目标桶。
+ */
+const sessionStatusOverrides = new Map<string, SessionStatusOverride>();
+let sessionStatusRevision = 0;
+let sessionStatusRowRevision = 0;
+
+export interface SessionStatusTransitionToken {
+ sessionId: string;
+ token: number;
+}
+
+interface StatusBucketSnapshot {
+ tailBefore: Session | null;
+ evictedByOptimisticInsert: Session | null;
+}
+
+interface PendingStatusTransition {
+ tokens: Set<number>;
+ optimisticStatus: Session['status'];
+ optimisticRevision: number;
+ hasSucceeded: boolean;
+ rollbackPatch: Partial<Session>;
+ sourceSession: Session | null;
+ /** 状态写在途期间后到的非 status 权威字段;成功行落缓存前必须最后重放。 */
+ concurrentAuthoritativePatch: Partial<Session>;
+ titleRevisionAtStart: number;
+ spendRevisionAtStart: number;
+ buckets: Map<ListStatusFilter, StatusBucketSnapshot>;
+ /** 乐观移除前恰好满 1000 条的桶;等状态写收敛后定向补回新的尾项。 */
+ vacatedFullBuckets: Set<ListStatusFilter>;
+}
+
+const pendingStatusTransitions = new Map<string, PendingStatusTransition>();
+const pendingStatusTransitionWaiters = new Map<string, Set<() => void>>();
+let statusTransitionToken = 0;
+let statusTransitionGeneration = 0;
+
+function clearPendingStatusTransition(
+ sessionId: string,
+ pending: PendingStatusTransition,
+): void {
+ if (pendingStatusTransitions.get(sessionId) !== pending) return;
+ pendingStatusTransitions.delete(sessionId);
+ const waiters = pendingStatusTransitionWaiters.get(sessionId);
+ pendingStatusTransitionWaiters.delete(sessionId);
+ waiters?.forEach((resolve) => resolve());
+}
+
+/** 同桶补查已有请求在途时只记一个 dirty 位,请求结束后最多追加一轮 fresh。 */
+const trailingFilterRefreshes = new Set<ListStatusFilter>();
+
+function belongsInFilter(status: Session['status'], filter: ListStatusFilter): boolean {
+ if (status === 'deleted') return false;
+ return filter === 'all' || filter === status;
+}
+
+function updatedAtMs(session: Session): number {
+ const parsed = Date.parse(session.updatedAt);
+ return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;
+}
+
+function statusPatchNeedsTargetBackfill(patch: Partial<Session>): boolean {
+ if (patch.status === undefined || patch.status === 'deleted') return false;
+ return typeof patch.updatedAt !== 'string' || !Number.isFinite(Date.parse(patch.updatedAt));
+}
+
+/** 与 sessions:list 的 updatedAt DESC 保持一致,并保留 1000 条硬上限。 */
+function upsertSessionByUpdatedAt(list: Session[], session: Session): Session[] {
+ const withoutSession = list.filter((item) => item.id !== session.id);
+ const timestamp = updatedAtMs(session);
+ const earlierIndex = withoutSession.findIndex((item) => timestamp > updatedAtMs(item));
+ const insertAt = earlierIndex === -1 ? withoutSession.length : earlierIndex;
+ return [
+ ...withoutSession.slice(0, insertAt),
+ session,
+ ...withoutSession.slice(insertAt),
+ ].slice(0, DEFAULT_LIMIT);
+}
+
+function recordPendingStatusEviction(
+ sessionId: string,
+ filter: ListStatusFilter,
+ before: Session[],
+ after: Session[],
+): void {
+ const pending = pendingStatusTransitions.get(sessionId);
+ const tailBefore = before.length >= DEFAULT_LIMIT ? (before[before.length - 1] ?? null) : null;
+ if (!pending || !tailBefore || after.some((item) => item.id === tailBefore.id)) return;
+ pending.buckets.set(filter, {
+ tailBefore,
+ evictedByOptimisticInsert: tailBefore,
+ });
+}
+
+function restorePendingStatusEvictions(
+ pending: PendingStatusTransition,
+ finalStatus: Session['status'],
+): void {
+ let restoredTail = false;
+ for (const [filter, snapshot] of pending.buckets) {
+ if (belongsInFilter(finalStatus, filter)) continue;
+ const evicted = snapshot.evictedByOptimisticInsert;
+ const list = cache.get(filter);
+ if (!evicted || !list || list.some((item) => item.id === evicted.id)) continue;
+ cache.set(filter, upsertSessionByUpdatedAt(list, evicted));
+ restoredTail = true;
+ }
+ if (restoredTail) notify();
+}
+
+/**
+ * 满桶移除一行会让数据库原第 1001 行进入结果集。pending 期间先记账,避免状态尚未
+ * 落库时反复 fresh;没有 pending 时可立即定向补拉。
+ */
+function recordFullBucketVacancy(
+ sessionId: string,
+ filter: ListStatusFilter,
+ before: Session[],
+ after: Session[],
+ pendingFallback?: PendingStatusTransition,
+): boolean {
+ if (after.length >= before.length) return false;
+ let inheritsFullBucketVacancy = pendingFallback?.vacatedFullBuckets.has(filter) ?? false;
+ if (!inheritsFullBucketVacancy) {
+ for (const candidate of pendingStatusTransitions.values()) {
+ if (!candidate.vacatedFullBuckets.has(filter)) continue;
+ inheritsFullBucketVacancy = true;
+ break;
+ }
+ }
+ if (before.length < DEFAULT_LIMIT && !inheritsFullBucketVacancy) return false;
+ const pending = pendingStatusTransitions.get(sessionId) ?? pendingFallback;
+ if (pending) {
+ pending.vacatedFullBuckets.add(filter);
+ return false;
+ }
+ return true;
+}
+
+function requestPendingStatusVacancyBackfills(
+ pending: PendingStatusTransition,
+ finalStatus: Session['status'],
+): void {
+ for (const filter of pending.vacatedFullBuckets) {
+ if (belongsInFilter(finalStatus, filter)) continue;
+ const list = cache.get(filter);
+ if (list && list.length >= DEFAULT_LIMIT) continue;
+ requestFilterBackfill(filter);
+ }
+}
+
+function applySessionStatusOverrides(
+ list: Session[],
+ filter: ListStatusFilter,
+ afterRevision: number,
+ afterRowRevision: number,
+): Session[] {
+ if (sessionStatusOverrides.size === 0) return list;
+ let next = list;
+ let changed = false;
+ for (const [sessionId, override] of sessionStatusOverrides) {
+ // 乐观状态在写库完成前必须跨过 request-start revision 持续生效;否则归档后、
+ // DB 提交前启动的列表查询会把旧 active 行写回来。
+ if (
+ override.revision <= afterRevision &&
+ override.rowRevision <= afterRowRevision &&
+ !pendingStatusTransitions.has(sessionId)
+ ) {
+ continue;
+ }
+ const status = override.patch.status;
+ if (!status) continue;
+ const idx = next.findIndex((session) => session.id === sessionId);
+ if (!belongsInFilter(status, filter)) {
+ if (idx === -1) continue;
+ const before = next;
+ next = [...before.slice(0, idx), ...before.slice(idx + 1)];
+ if (recordFullBucketVacancy(sessionId, filter, before, next)) {
+ // 当前列表请求仍在 inflight 中,requestFilterBackfill 会把它折叠成一轮尾刷。
+ requestFilterBackfill(filter);
+ }
+ changed = true;
+ continue;
+ }
+ if (idx !== -1) {
+ const before = next;
+ next = upsertSessionByUpdatedAt(before, mergeSession(before[idx], override.patch));
+ recordPendingStatusEviction(sessionId, filter, before, next);
+ changed = true;
+ continue;
+ }
+ if (override.session) {
+ const before = next;
+ next = upsertSessionByUpdatedAt(before, override.session);
+ recordPendingStatusEviction(sessionId, filter, before, next);
+ changed = true;
+ }
+ }
+ return changed ? next : list;
+}
+
/** 仅重放请求启动后到达的标题事件,避免旧事件覆盖未来数据库刷新。 */
function applySessionTitleOverrides(list: Session[], afterRevision: number): Session[] {
if (sessionTitleOverrides.size === 0) return list;
@@ -250,17 +474,27 @@ async function fetchFilter(
// 不一致,必须把 filter 原样透传,由 IPC handler 决定过滤语义。
const spendRevisionAtStart = sessionSpendRevision;
const titleRevisionAtStart = sessionTitleRevision;
+ const statusRevisionAtStart = sessionStatusRevision;
+ const statusRowRevisionAtStart = sessionStatusRowRevision;
const startedAt = performance.now();
const sessions = await sessionService.list(
DEFAULT_LIMIT,
filter,
opts?.fresh ? { fresh: true } : undefined,
);
- // 顺序:先把「请求发起之后到达的权威标题」补回去,再叠乐观预览。反过来的话预览会先
- // 盖在旧标题上、随后又被权威值挤掉,中间多一次跳变。
+ // 顺序:status override 可能携带写库返回的完整旧行,必须先应用;再重放请求期间到达的
+ // 费用与权威标题,最后叠乐观标题预览。否则完整状态行会把这三类更新盖回旧值。
const result = applyAutoTitlePreviews(
applySessionTitleOverrides(
- applySessionSpendOverrides(sessions, spendRevisionAtStart),
+ applySessionSpendOverrides(
+ applySessionStatusOverrides(
+ sessions,
+ filter,
+ statusRevisionAtStart,
+ statusRowRevisionAtStart,
+ ),
+ spendRevisionAtStart,
+ ),
titleRevisionAtStart,
),
);
@@ -279,6 +513,111 @@ async function fetchFilter(
return result;
}
+function runFilterBackfill(filter: ListStatusFilter): void {
+ void sessionsStore.ensureByFilter(filter, { fresh: true }).catch(() => {
+ /* 静默:后续状态广播、主动操作或 refresh 会再次兜底。 */
+ });
+}
+
+/**
+ * 缺少完整 row 时只补查需要包含它的桶。同桶若已有请求在途,不取消、不并发重启,
+ * 只保留一个尾部 fresh;这样连续归档不会把每个状态事件放大成一轮列表查询。
+ */
+function requestFilterBackfill(filter: ListStatusFilter): void {
+ if (inflight.has(filter)) {
+ trailingFilterRefreshes.add(filter);
+ return;
+ }
+ runFilterBackfill(filter);
+}
+
+function runTrailingFilterBackfill(filter: ListStatusFilter): void {
+ if (!trailingFilterRefreshes.delete(filter)) return;
+ runFilterBackfill(filter);
+}
+
+function recordStatusOverride(
+ sessionId: string,
+ patch: Partial<Session>,
+ session: Session | null,
+): void {
+ sessionStatusRevision += 1;
+ sessionStatusOverrides.set(sessionId, {
+ revision: sessionStatusRevision,
+ rowRevision: sessionStatusRowRevision,
+ patch: { ...patch },
+ session: patch.status === 'deleted' ? null : session,
+ });
+}
+
+/**
+ * 状态覆盖可能携带一整行;后到的权威字段必须同时合并进去,否则旧 list 响应重放状态时
+ * 会把 model / effort / permissionMode 等 settings-only 更新盖回旧值。
+ */
+function mergeAuthoritativePatchIntoStatusOverride(
+ sessionId: string,
+ patch: Partial<Session>,
+): void {
+ const pending = pendingStatusTransitions.get(sessionId);
+ if (pending) {
+ pending.concurrentAuthoritativePatch = mergeSessionPatch(
+ pending.concurrentAuthoritativePatch,
+ patch,
+ );
+ if (pending.sourceSession) {
+ pending.sourceSession = mergeSession(pending.sourceSession, patch);
+ }
+ }
+ const override = sessionStatusOverrides.get(sessionId);
+ if (!override) return;
+ if (override.patch.status !== 'deleted') {
+ sessionStatusRowRevision += 1;
+ override.rowRevision = sessionStatusRowRevision;
+ override.patch = mergeSessionPatch(override.patch, patch);
+ if (override.session) {
+ override.session = mergeSession(override.session, patch);
+ }
+ }
+}
+
+function applyAuthoritativeStatusSession(
+ session: Session,
+ pendingForBackfills?: PendingStatusTransition,
+): void {
+ recordStatusOverride(session.id, session, session);
+ if (session.status === 'deleted') {
+ autoTitlePreviews.delete(session.id);
+ sessionTitleOverrides.delete(session.id);
+ sessionSpendOverrides.delete(session.id);
+ }
+ let touched = false;
+ const toBackfill = new Set<ListStatusFilter>();
+ for (const [filter, list] of cache) {
+ if (!belongsInFilter(session.status, filter)) {
+ const next = list.filter((item) => item.id !== session.id);
+ if (next.length === list.length) continue;
+ cache.set(filter, next);
+ if (
+ recordFullBucketVacancy(
+ session.id,
+ filter,
+ list,
+ next,
+ pendingForBackfills,
+ )
+ ) {
+ toBackfill.add(filter);
+ }
+ touched = true;
+ continue;
+ }
+ cache.set(filter, upsertSessionByUpdatedAt(list, session));
+ touched = true;
+ }
+ if (touched) notify();
+ for (const filter of toBackfill) requestFilterBackfill(filter);
+}
+
export const sessionsStore = {
subscribe(fn: (change: StoreChange) => void): () => void {
subs.add(fn);
@@ -324,12 +663,14 @@ export const sessionsStore = {
cache.set(filter, data);
inflight.delete(filter);
notify();
+ runTrailingFilterBackfill(filter);
}
return data;
})
.catch((e) => {
if (inflight.get(filter) === request) {
inflight.delete(filter);
+ runTrailingFilterBackfill(filter);
}
throw e;
});
@@ -343,6 +684,7 @@ export const sessionsStore = {
async forceRefresh(filter: ListStatusFilter): Promise<Session[]> {
cache.delete(filter);
inflight.delete(filter);
+ trailingFilterRefreshes.delete(filter);
await this.ensureByFilter(filter, { fresh: true });
return cache.get(filter) ?? [];
},
@@ -350,7 +692,7 @@ export const sessionsStore = {
/**
* 重拉所有"已加载过"的桶,未加载的桶不动。
* sessionsBus.onRefresh / sessionsPush.onCreated 走这条 ——
- * 列表成员变化(删除 / 归档 / main 端新建)需要让所有活跃订阅者同步刷新。
+ * 无完整 row 的列表成员变化(main 端新建等)需要让所有活跃订阅者同步刷新。
*/
async forceRefreshAll(): Promise<void> {
const filters = Array.from(cache.keys());
@@ -358,6 +700,195 @@ export const sessionsStore = {
await Promise.all(filters.map((f) => this.forceRefresh(f)));
},
+ /**
+ * 开始一次本地乐观状态迁移。pending 期间 status override 对之后启动的列表请求也
+ * 持续生效;写库成功后必须 complete,失败后必须 rollback。
+ */
+ beginStatusTransition(
+ id: string,
+ patch: Partial<Session> & { status: Session['status'] },
+ ): SessionStatusTransitionToken | null {
+ if (!id) return null;
+ statusTransitionToken += 1;
+ const token = statusTransitionToken;
+ const existing = pendingStatusTransitions.get(id);
+ if (existing?.optimisticStatus === patch.status) {
+ existing.tokens.add(token);
+ return { sessionId: id, token };
+ }
+ const source = this.findById(id);
+ const buckets = new Map<ListStatusFilter, StatusBucketSnapshot>();
+ for (const [filter, list] of cache) {
+ buckets.set(filter, {
+ tailBefore: list.length >= DEFAULT_LIMIT ? (list[list.length - 1] ?? null) : null,
+ evictedByOptimisticInsert: null,
+ });
+ }
+ const rollbackPatch: Partial<Session> = {
+ status:
+ source?.status ??
+ (patch.status === 'archived' ? 'active' : patch.status === 'active' ? 'archived' : 'active'),
+ ...(patch.pinnedAt !== undefined ? { pinnedAt: source?.pinnedAt } : {}),
+ };
+ pendingStatusTransitions.set(id, {
+ tokens: new Set([token]),
+ optimisticStatus: patch.status,
+ optimisticRevision: sessionStatusRevision + 1,
+ hasSucceeded: false,
+ rollbackPatch,
+ sourceSession: source,
+ concurrentAuthoritativePatch: {},
+ titleRevisionAtStart: sessionTitleRevision,
+ spendRevisionAtStart: sessionSpendRevision,
+ buckets,
+ vacatedFullBuckets: new Set(),
+ });
+ this.patchLocal(id, patch);
+ for (const [filter, snapshot] of buckets) {
+ const tail = snapshot.tailBefore;
+ const current = cache.get(filter);
+ if (tail && current && !current.some((item) => item.id === tail.id)) {
+ snapshot.evictedByOptimisticInsert = tail;
+ }
+ }
+ return { sessionId: id, token };
+ },
+
+ hasPendingStatusTransition(id: string): boolean {
+ return Boolean(id) && pendingStatusTransitions.has(id);
+ },
+
+ /** 等同一会话的状态写收敛;reset 代表数据 owner 已切换,返回 false 让旧动作停止。 */
+ async waitForStatusTransition(id: string): Promise<boolean> {
+ if (!id) return false;
+ const generation = statusTransitionGeneration;
+ while (pendingStatusTransitions.has(id)) {
+ await new Promise<void>((resolve) => {
+ const waiters = pendingStatusTransitionWaiters.get(id) ?? new Set<() => void>();
+ waiters.add(resolve);
+ pendingStatusTransitionWaiters.set(id, waiters);
+ });
+ if (generation !== statusTransitionGeneration) return false;
+ }
+ return generation === statusTransitionGeneration;
+ },
+
+ /**
+ * 等待既有状态写收敛后原子地 begin;多个等待者即使同时被唤醒,后续等待者也会
+ * 看到前一个刚登记的 pending,不会用异向迁移覆盖它。apply 可保留调用侧 flushSync。
+ */
+ async beginStatusTransitionWhenReady(
+ id: string,
+ patch: Partial<Session> & { status: Session['status'] },
+ apply?: (
+ begin: () => SessionStatusTransitionToken | null,
+ ) => SessionStatusTransitionToken | null,
+ ): Promise<SessionStatusTransitionToken | null> {
+ if (!id) return null;
+ const generation = statusTransitionGeneration;
+ while (pendingStatusTransitions.has(id)) {
+ await new Promise<void>((resolve) => {
+ const waiters = pendingStatusTransitionWaiters.get(id) ?? new Set<() => void>();
+ waiters.add(resolve);
+ pendingStatusTransitionWaiters.set(id, waiters);
+ });
+ if (generation !== statusTransitionGeneration) return null;
+ }
+ if (generation !== statusTransitionGeneration) return null;
+ const begin = () => this.beginStatusTransition(id, patch);
+ return apply ? apply(begin) : begin();
+ },
+
+ /** 用写库返回的完整行结束乐观迁移,并按服务端 updatedAt DESC 重排所有已加载桶。 */
+ completeStatusTransition(token: SessionStatusTransitionToken, persisted: Session): boolean {
+ const pending = pendingStatusTransitions.get(token.sessionId);
+ if (!pending || persisted.id !== token.sessionId || !pending.tokens.delete(token.token)) {
+ return false;
+ }
+ const latestOverride = sessionStatusOverrides.get(token.sessionId);
+ if (latestOverride?.patch.status !== persisted.status) {
+ clearPendingStatusTransition(token.sessionId, pending);
+ if (latestOverride?.patch.status) {
+ restorePendingStatusEvictions(pending, latestOverride.patch.status);
+ requestPendingStatusVacancyBackfills(pending, latestOverride.patch.status);
+ }
+ return false;
+ }
+ pending.hasSucceeded = true;
+ if (pending.tokens.size === 0) clearPendingStatusTransition(token.sessionId, pending);
+ const current = this.findById(token.sessionId);
+ const authoritativeBase =
+ current?.status === persisted.status && updatedAtMs(current) >= updatedAtMs(persisted)
+ ? current
+ : persisted;
+ // 只有源桶加载时,乐观归档会先移除最后一份缓存行;这期间到达的 settings-only
+ // 权威广播无法从 findById 取回。它们晚于状态请求起飞,必须在 persisted 完整行之上
+ // 最后重放,同时保留 persisted 的新 status / updatedAt。
+ const authoritative = mergeSession(authoritativeBase, pending.concurrentAuthoritativePatch);
+ const [withOverrides] = applyAutoTitlePreviews(
+ applySessionTitleOverrides(
+ applySessionSpendOverrides([authoritative], pending.spendRevisionAtStart),
+ pending.titleRevisionAtStart,
+ ),
+ );
+ applyAuthoritativeStatusSession(withOverrides ?? authoritative, pending);
+ if (pending.tokens.size === 0) {
+ requestPendingStatusVacancyBackfills(pending, persisted.status);
+ }
+ return true;
+ },
+
+ /** 写库失败时恢复原状态,并补回乐观插入在 1000 条上限处挤出的尾项。 */
+ rollbackStatusTransition(token: SessionStatusTransitionToken): boolean {
+ const pending = pendingStatusTransitions.get(token.sessionId);
+ if (!pending || !pending.tokens.delete(token.token)) return false;
+ const latestOverride = sessionStatusOverrides.get(token.sessionId);
+ if (latestOverride?.patch.status !== pending.optimisticStatus) {
+ clearPendingStatusTransition(token.sessionId, pending);
+ if (latestOverride?.patch.status) {
+ restorePendingStatusEvictions(pending, latestOverride.patch.status);
+ requestPendingStatusVacancyBackfills(pending, latestOverride.patch.status);
+ }
+ return false;
+ }
+ if (pending.tokens.size > 0) return true;
+ clearPendingStatusTransition(token.sessionId, pending);
+ if (
+ pending.hasSucceeded ||
+ (latestOverride.revision !== pending.optimisticRevision &&
+ latestOverride.patch.status === pending.optimisticStatus)
+ ) {
+ requestPendingStatusVacancyBackfills(pending, pending.optimisticStatus);
+ return true;
+ }
+ if (pending.sourceSession) {
+ const [withOverrides] = applyAutoTitlePreviews(
+ applySessionTitleOverrides(
+ applySessionSpendOverrides(
+ [mergeSession(pending.sourceSession, pending.rollbackPatch)],
+ pending.spendRevisionAtStart,
+ ),
+ pending.titleRevisionAtStart,
+ ),
+ );
+ applyAuthoritativeStatusSession(
+ withOverrides ?? mergeSession(pending.sourceSession, pending.rollbackPatch),
+ pending,
+ );
+ } else {
+ this.patchLocal(token.sessionId, pending.rollbackPatch);
+ }
+ restorePendingStatusEvictions(
+ pending,
+ pending.rollbackPatch.status ?? pending.sourceSession?.status ?? 'active',
+ );
+ requestPendingStatusVacancyBackfills(
+ pending,
+ pending.rollbackPatch.status ?? pending.sourceSession?.status ?? 'active',
+ );
+ return true;
+ },
+
/**
* 局部合并(rename / pin / title / updatedAt / model / clearSession 等
* "字段变化"全部走这里)。遍历所有桶:命中即合并字段,保留位置不重排序。
@@ -367,19 +898,30 @@ export const sessionsStore = {
* 1. 旧桶里"假活着"(status 已变但条目仍在)
* 2. 新桶 cache 命中但缺这一条(用户切桶后看不到)
*
- * 两种不一致的修正方式**不对称**,别退回"一律 drop 重拉":
+ * 两种不一致都优先在本地修正,别退回"一律 drop 重拉":
* - 「在桶里但已不该在」(归档时的 active 桶)→ **就地移除**。归属判定是
- * 确定的(status 已经变了),本地就能得出正确结果,无需等 IPC。
+ * 确定的(status 已经变了),无需等 IPC。
* 这里 drop 桶是曾经的性能陷阱:桶变 null 后 useCCSessions 的
* `next !== null` 守卫会跳过 setState,视图停在**仍含该行**的陈旧快照,
* 一直等到重拉的 sessions:list 回来才更新 —— 表现为"点归档后半秒对话
* 才消失",把调用方 useSessionLifecycleActions 的乐观更新整段抵消掉。
- * - 「不在桶里但该在」(归档时的 archived 桶)→ drop + 重拉。本地没有这条
- * 的完整 row,构造不出来,只能问 DB。这类桶通常不是当前可见桶。
- * deleted 走前面的独立分支:归属确定,从所有桶移除即可。'all' 桶仅排除 deleted。
+ * - 「不在桶里但该在」(归档时的 archived 桶)→ 从 active / all 任一桶捕获
+ * 完整 row 后直接插入。所有桶都找不到 row,或 status 广播没有携带 DB 已更新的
+ * updatedAt 时,再定向补查目标桶以校正排序和 1000 条边界。
+ * deleted 从所有桶移除即可;旧在途请求由 status override 过滤,不再取消并重启。
*/
patchLocal(id: string, patch: Partial<Session>): void {
if (!id || !patch) return;
+ const pendingBeforePatch =
+ patch.status !== undefined ? pendingStatusTransitions.get(id) : undefined;
+ const sourceSession = patch.status !== undefined ? this.findById(id) : null;
+ const migratedSession = sourceSession ? mergeSession(sourceSession, patch) : null;
+ const needsTargetBackfill = statusPatchNeedsTargetBackfill(patch);
+ if (patch.status !== undefined) {
+ recordStatusOverride(id, patch, migratedSession);
+ } else {
+ mergeAuthoritativePatchIntoStatusOverride(id, patch);
+ }
// 权威标题落地(main 写完占位 / 智能标题后经 sessions:patched 回流,或用户手动改名)
// → 无条件回收预览条目。留着它会在下一次全量刷新时把真实标题又顶掉。
//
@@ -411,28 +953,6 @@ export const sessionsStore = {
autoTitlePreviews.delete(id);
sessionTitleOverrides.delete(id);
sessionSpendOverrides.delete(id);
- // 删除前发出的请求可能仍会返回包含该 session 的旧快照。先解除这些
- // request 对桶的认领,再为对应桶发起替代请求,避免旧响应重新写回。
- const toRefetch = Array.from(inflight.keys());
- for (const filter of toRefetch) {
- inflight.delete(filter);
- }
- let removed = false;
- for (const [filter, list] of cache) {
- if (!list.some((session) => session.id === id)) continue;
- cache.set(
- filter,
- list.filter((session) => session.id !== id),
- );
- removed = true;
- }
- if (removed) notify();
- for (const filter of toRefetch) {
- void this.ensureByFilter(filter, { fresh: true }).catch(() => {
- /* 静默:后续主动操作或 refresh 会再次兜底。 */
- });
- }
- return;
}
if (patch.totalCostUsd !== undefined || patch.totalMoney !== undefined) {
sessionSpendRevision += 1;
@@ -444,57 +964,76 @@ export const sessionsStore = {
});
}
let touched = false;
- for (const [k, list] of cache) {
- const idx = list.findIndex((s) => s.id === id);
- if (idx !== -1) {
- const merged = mergeSession(list[idx], patch);
- cache.set(k, [...list.slice(0, idx), merged, ...list.slice(idx + 1)]);
+ const toBackfill = new Set<ListStatusFilter>();
+ if (patch.status === undefined) {
+ for (const [filter, list] of cache) {
+ const idx = list.findIndex((session) => session.id === id);
+ if (idx === -1) continue;
+ cache.set(filter, [
+ ...list.slice(0, idx),
+ mergeSession(list[idx], patch),
+ ...list.slice(idx + 1),
+ ]);
touched = true;
}
- }
- const toRefetch: ListStatusFilter[] = [];
- if (patch.status !== undefined) {
- const newStatus = patch.status;
- const belongsIn = (filter: ListStatusFilter): boolean => {
- if (filter === 'all') return true;
- return filter === newStatus;
- };
- // 进行中的 list 请求发起于本次 status 变更之前,回来会把旧归属整桶写回
- // (cache.set 覆盖,连就地移除也会被撤销)。先解除这些 request 对桶的认领,
- // 循环后统一重发 —— 与 deleted 分支同口径。稳态下 inflight 为空:桶进
- // cache 时 ensureByFilter 会同时清掉 inflight,故与下面的 cache 循环无交集。
- for (const filter of Array.from(inflight.keys())) {
- inflight.delete(filter);
- toRefetch.push(filter);
- }
- for (const filter of Array.from(cache.keys())) {
+ } else {
+ const loadedFilters = new Set<ListStatusFilter>([...cache.keys(), ...inflight.keys()]);
+ for (const filter of loadedFilters) {
+ const belongs = belongsInFilter(patch.status, filter);
+ // sessions.setStatus 等批量入口只广播 { status },但 DB 已把 updatedAt bump 到当前
+ // 时间。先用缓存行即时迁移,再补拉应包含它的桶,否则会按旧时间错排,满 1000 条
+ // 时甚至可能把本应进入结果集的新近任务裁掉。pending 本地写入会在下方继续延后,
+ // 由 completeStatusTransition 返回的完整持久行直接收敛,避免多打一轮请求。
+ if (belongs && needsTargetBackfill) toBackfill.add(filter);
const list = cache.get(filter);
- if (!list) continue;
- const has = list.some((s) => s.id === id);
- if (has === belongsIn(filter)) continue;
- if (has) {
- // 已不该在本桶:本地即可得出正确结果,就地移除,桶保持非 null,
- // 订阅者当帧就能拿到不含该行的新快照(见上方注释的性能陷阱)。
+ if (!list) {
+ if (belongs && !migratedSession) toBackfill.add(filter);
+ continue;
+ }
+ const idx = list.findIndex((session) => session.id === id);
+ if (!belongs) {
+ if (idx === -1) continue;
+ const next = [...list.slice(0, idx), ...list.slice(idx + 1)];
+ cache.set(filter, next);
+ if (recordFullBucketVacancy(id, filter, list, next)) {
+ toBackfill.add(filter);
+ }
+ touched = true;
+ continue;
+ }
+ if (idx !== -1) {
+ const merged = mergeSession(list[idx], patch);
cache.set(
filter,
- list.filter((session) => session.id !== id),
+ needsTargetBackfill
+ ? [...list.slice(0, idx), merged, ...list.slice(idx + 1)]
+ : upsertSessionByUpdatedAt(list, merged),
);
+ touched = true;
+ continue;
+ }
+ if (migratedSession) {
+ cache.set(filter, upsertSessionByUpdatedAt(list, migratedSession));
+ touched = true;
} else {
- // 本桶缺这一条且本地没有它的 row → 只能 drop 后问 DB。
- cache.delete(filter);
- toRefetch.push(filter);
+ toBackfill.add(filter);
}
- touched = true;
}
}
if (touched) notify();
- // 被 drop 的桶通常有 active 订阅者(否则不会进 cache);只 drop 不主动拉,
- // 订阅者的 subscribe 回调拿到 null 不会 setState,会一直停在陈旧 snapshot。
- // 主动 ensure 一下,IPC 回来后 notify → 订阅者拿到新数据自动 swap。
- for (const filter of toRefetch) {
- void this.ensureByFilter(filter, { fresh: true }).catch(() => {
- /* 静默:网络/IPC 失败由后续主动操作或 refresh 兜底,不上报 toast */
- });
+ if (
+ pendingBeforePatch &&
+ patch.status !== undefined &&
+ patch.status !== pendingBeforePatch.optimisticStatus &&
+ pendingStatusTransitions.get(id) === pendingBeforePatch
+ ) {
+ clearPendingStatusTransition(id, pendingBeforePatch);
+ restorePendingStatusEvictions(pendingBeforePatch, patch.status);
+ requestPendingStatusVacancyBackfills(pendingBeforePatch, patch.status);
+ }
+ if (pendingStatusTransitions.has(id)) return;
+ for (const filter of toBackfill) {
+ requestFilterBackfill(filter);
}
},
@@ -525,6 +1064,14 @@ export const sessionsStore = {
sessionSpendOverrides.clear();
autoTitlePreviews.clear();
sessionTitleOverrides.clear();
+ sessionStatusOverrides.clear();
+ statusTransitionGeneration += 1;
+ pendingStatusTransitions.clear();
+ for (const waiters of pendingStatusTransitionWaiters.values()) {
+ waiters.forEach((resolve) => resolve());
+ }
+ pendingStatusTransitionWaiters.clear();
+ trailingFilterRefreshes.clear();
initialFetchLogged.clear();
notify('reset');
},
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 82fcaba8c5..ccfd9b5291 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3900,10 +3900,7 @@ interface ElectronAPI {
reason?: 'gone' | 'no-worktree' | 'git-error';
detail?: string;
}>;
- /**
- * 「worktree 回收链已跑完」推送。归档/删除后 main 侧的回收是 fire-and-forget 的
- * 异步链,store 条目移除远晚于状态 IPC 返回,renderer 必须等这条才能拿到真实快照。
- */
+ /** worktree 回收完成后,按实际受影响的 sessionId 增量更新本机缓存。 */
onWorktreeChanged: (callback: (payload: { sessionId: string }) => void) => () => void;
// ── Slack Hook(中心 slack-hook-server 接入) ── 类型正本在 shared/hookControlIpc.ts