diff --git a/src/renderer/stores/sessions/index.ts b/src/renderer/stores/sessions/index.ts index 29a5c34c9..0fa7fe012 100644 --- a/src/renderer/stores/sessions/index.ts +++ b/src/renderer/stores/sessions/index.ts @@ -272,6 +272,15 @@ function dropCoworkerTab( forgetUnknownSessionClocks(conversations); } +/** 投影里已经没有这个会话才清折叠分桶。set 回调里可能提前 return,所以放在 set 之后。 */ +function forgetCollapsedIfGone( + conversations: Record, + conversationId: string +): void { + if (conversationId in conversations) return; + useTurnCollapseStore.getState().forgetConversation(conversationId); +} + /** * worker 回流的 child metadata 来源恒为 typed-mention、不带 mode;这两项沿用 Main 预约时的权威值。 * 落盘的就是这份,Main 重启后靠它认领 agent-tool coworker。 @@ -1703,16 +1712,15 @@ export const useSessionsStore = create()( ended: true, historyOnly: true, }; - setTimeout( - () => - set((current) => { - if (!current.conversations[coworker.id]?.ended) return current; - const next = { ...current.conversations }; - dropCoworkerTab(next, id, coworker.id); - return { conversations: next }; - }), - TASK_TAB_LINGER_MS - ); + setTimeout(() => { + set((current) => { + if (!current.conversations[coworker.id]?.ended) return current; + const next = { ...current.conversations }; + dropCoworkerTab(next, id, coworker.id); + return { conversations: next }; + }); + forgetCollapsedIfGone(get().conversations, coworker.id); + }, TASK_TAB_LINGER_MS); return { conversations }; } dropCoworkerTab(conversations, id, coworker.id); @@ -1770,6 +1778,9 @@ export const useSessionsStore = create()( } return { conversations }; }); + if (event.coworker.status === 'dismissed') { + forgetCollapsedIfGone(get().conversations, event.coworker.id); + } return; } @@ -3549,6 +3560,7 @@ export const useSessionsStore = create()( delete conversations[id]; return { conversations }; }); + forgetCollapsedIfGone(get().conversations, id); }, async send(text, target, images, conversationId) { @@ -4422,6 +4434,7 @@ export const useSessionsStore = create()( forgetUnknownSessionClocks(conversations); return { conversations }; }); + forgetCollapsedIfGone(get().conversations, coworkerId); }, removeQueuedMessage(conversationId, messageId) { diff --git a/src/renderer/stores/sessions/turnCollapseCleanup.test.ts b/src/renderer/stores/sessions/turnCollapseCleanup.test.ts new file mode 100644 index 000000000..780eb973c --- /dev/null +++ b/src/renderer/stores/sessions/turnCollapseCleanup.test.ts @@ -0,0 +1,225 @@ +import type { RendererAgentEvent, SourceAuthorityProjection } from '@shared/types/agent'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { useTurnCollapseStore } from '@/stores/turnCollapse'; +import { + bindSessionProjection, + btwDispose, + dismissCoworker, + installSessionGlobals, + loadSessionModules, + onAgentEvent, + resetSessionHarness, + sessionsModule, +} from './index.testUtils'; + +let sourceProjection: SourceAuthorityProjection = { projects: [], conversations: [] }; +let nextConversationId = 'parent'; +bindSessionProjection({ + get sourceProjection() { + return sourceProjection; + }, + set sourceProjection(value) { + sourceProjection = value; + }, + get nextConversationId() { + return nextConversationId; + }, + set nextConversationId(value) { + nextConversationId = value; + }, +}); +installSessionGlobals(); + +const buckets = (id: string) => { + const state = useTurnCollapseStore.getState(); + return { + turns: state.byConversation[id], + rows: state.toolRowsByConversation[id], + }; +}; + +function mark(id: string) { + useTurnCollapseStore.getState().setTurnCollapsed(id, 'entry', true); + useTurnCollapseStore.getState().setToolRowCollapsed(id, 'call', true); +} + +describe('会话离开投影时清掉折叠分桶', () => { + beforeAll(async () => { + await loadSessionModules(); + }); + + beforeEach(async () => { + dismissCoworker.mockReset(); + dismissCoworker.mockResolvedValue({ ok: true }); + btwDispose.mockReset(); + btwDispose.mockResolvedValue({ ok: true }); + nextConversationId = 'parent'; + await resetSessionHarness(); + useTurnCollapseStore.setState({ byConversation: {}, toolRowsByConversation: {}, recent: [] }); + }); + + function seedCoworker(id: string, extra: Record = {}) { + sessionsModule.useSessionsStore.setState((state) => ({ + conversations: { + ...state.conversations, + parent: { + ...state.conversations.parent, + generation: 'pg1', + coworkerIds: [id], + activeTabId: id, + }, + [id]: { + ...state.conversations.parent, + id, + parentId: 'parent', + coworkerName: 'bob', + coworkerIds: undefined, + activeTabId: undefined, + generation: undefined, + started: true, + spawning: false, + ...extra, + }, + }, + })); + } + + let seq = 0; + const dismissed = (id: string): RendererAgentEvent => ({ + type: 'coworker-update', + identity: { sessionId: 'parent', generation: 'pg1' }, + seq: ++seq, + coworker: { id, name: 'bob', status: 'dismissed', createdAt: 0 }, + }); + + it('用户解雇 coworker 后清掉该会话的两类折叠记录,父会话的留下', async () => { + const id = 'parent::cw-user'; + seedCoworker(id, { child: { mode: 'task' } }); + mark(id); + mark('parent'); + await sessionsModule.useSessionsStore.getState().dismissCoworkerFromUI('parent', id); + onAgentEvent?.(dismissed(id)); + + const state = sessionsModule.useSessionsStore.getState(); + expect(state.conversations[id]).toBeUndefined(); + expect(buckets(id)).toEqual({ turns: undefined, rows: undefined }); + expect(buckets('parent')).toEqual({ turns: { entry: true }, rows: { call: true } }); + }); + + it('coworker 模式被回收时立即清掉折叠记录', () => { + const id = 'parent::cw-mode'; + seedCoworker(id, { child: { mode: 'coworker' } }); + mark(id); + mark('parent'); + onAgentEvent?.(dismissed(id)); + + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeUndefined(); + expect(buckets(id)).toEqual({ turns: undefined, rows: undefined }); + expect(buckets('parent').turns).toEqual({ entry: true }); + }); + + it('task 停留期间保留折叠记录,收进历史后才清', () => { + const id = 'parent::cw-task'; + vi.useFakeTimers(); + try { + seedCoworker(id, { child: { mode: 'task' } }); + mark(id); + mark('parent'); + onAgentEvent?.(dismissed(id)); + + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeDefined(); + expect(buckets(id)).toEqual({ + turns: { entry: true }, + rows: { call: true }, + }); + vi.advanceTimersByTime(7_999); + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeDefined(); + expect(buckets(id).turns).toEqual({ entry: true }); + + vi.advanceTimersByTime(1); + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeUndefined(); + expect(buckets(id)).toEqual({ turns: undefined, rows: undefined }); + expect(buckets('parent').rows).toEqual({ call: true }); + } finally { + vi.useRealTimers(); + } + }); + + it('task 停留期间被复活后,到点不删会话也不清折叠记录', () => { + const id = 'parent::cw-revived'; + vi.useFakeTimers(); + try { + seedCoworker(id, { child: { mode: 'task' } }); + mark(id); + onAgentEvent?.(dismissed(id)); + sessionsModule.useSessionsStore.setState((state) => ({ + conversations: { + ...state.conversations, + [id]: { + ...state.conversations[id], + ended: undefined, + historyOnly: undefined, + started: true, + }, + }, + })); + vi.advanceTimersByTime(8_000); + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeDefined(); + expect(buckets(id)).toEqual({ turns: { entry: true }, rows: { call: true } }); + } finally { + vi.useRealTimers(); + } + }); + + it('死 tab 兑底删掉会话时清掉折叠记录', async () => { + const id = 'parent::cw-dead'; + seedCoworker(id, { started: false }); + mark(id); + mark('parent'); + dismissCoworker.mockResolvedValueOnce({ ok: false, error: 'not-found' }); + await sessionsModule.useSessionsStore.getState().dismissCoworkerFromUI('parent', id); + + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeUndefined(); + expect(buckets(id)).toEqual({ turns: undefined, rows: undefined }); + expect(buckets('parent').turns).toEqual({ entry: true }); + }); + + it('活会话 dismiss 失败时折叠记录还在', async () => { + const id = 'parent::cw-live'; + seedCoworker(id, { started: true }); + mark(id); + dismissCoworker.mockResolvedValueOnce({ ok: false, error: 'transient' }); + await sessionsModule.useSessionsStore.getState().dismissCoworkerFromUI('parent', id); + + expect(sessionsModule.useSessionsStore.getState().conversations[id]).toBeDefined(); + expect(buckets(id)).toEqual({ turns: { entry: true }, rows: { call: true } }); + }); + + it('关掉 btw 后清掉它的折叠记录,主会话的留下', async () => { + const parentId = sessionsModule.useSessionsStore.getState().activeId; + if (!parentId) throw new Error('parent missing'); + sessionsModule.useSessionsStore.getState().ensureBtwConversation({ + id: 'btw-1', + projectId: 'project', + btwParentId: parentId, + rolePrompt: 'aside', + }); + mark('btw-1'); + mark(parentId); + await sessionsModule.useSessionsStore.getState().disposeBtwConversation('btw-1'); + + expect(sessionsModule.useSessionsStore.getState().conversations['btw-1']).toBeUndefined(); + expect(buckets('btw-1')).toEqual({ turns: undefined, rows: undefined }); + expect(buckets(parentId)).toEqual({ turns: { entry: true }, rows: { call: true } }); + }); + + it('对普通会话调用 disposeBtw 不会清掉它的折叠记录', async () => { + const parentId = sessionsModule.useSessionsStore.getState().activeId; + if (!parentId) throw new Error('parent missing'); + mark(parentId); + await sessionsModule.useSessionsStore.getState().disposeBtwConversation(parentId); + + expect(sessionsModule.useSessionsStore.getState().conversations[parentId]).toBeDefined(); + expect(buckets(parentId)).toEqual({ turns: { entry: true }, rows: { call: true } }); + }); +}); diff --git a/src/renderer/stores/turnCollapse.test.ts b/src/renderer/stores/turnCollapse.test.ts index 017c275d9..687347d30 100644 --- a/src/renderer/stores/turnCollapse.test.ts +++ b/src/renderer/stores/turnCollapse.test.ts @@ -31,9 +31,19 @@ const store = () => useTurnCollapseStore.getState(); beforeEach(() => { storage.clear(); - useTurnCollapseStore.setState({ byConversation: {}, toolRowsByConversation: {} }); + useTurnCollapseStore.setState({ byConversation: {}, toolRowsByConversation: {}, recent: [] }); }); +function persisted(): { + byConversation?: Record; + toolRowsByConversation?: Record; + recent?: string[]; +} { + const raw = storage.get('enso-turn-collapse'); + if (!raw) return {}; + return (JSON.parse(raw) as { state?: ReturnType }).state ?? {}; +} + describe('轮次折叠态按会话记', () => { it('只记用户显式操作过的轮次,会话之间互不影响', () => { store().setTurnCollapsed('c1', 'entry-a', true); @@ -146,3 +156,86 @@ describe('带图工具行的收起选择', () => { }); }); }); + +/** 两类分桶按会话 id 合计,超出这个数就丢最久没写过的整桶。 */ +const CONVERSATION_BUCKET_LIMIT = 100; + +describe('折叠分桶按会话封顶', () => { + it('超过上限时丢掉最久没写过的会话,轮次和工具行一起没', () => { + for (let i = 0; i < CONVERSATION_BUCKET_LIMIT; i++) { + store().setTurnCollapsed(`c${i}`, 'a', true); + store().setToolRowCollapsed(`c${i}`, 'call', true); + } + store().setTurnCollapsed('c-new', 'a', true); + + expect(store().byConversation.c0).toBeUndefined(); + expect(store().toolRowsByConversation.c0).toBeUndefined(); + expect(store().byConversation.c1).toEqual({ a: true }); + expect(store().toolRowsByConversation.c1).toEqual({ call: true }); + expect(store().byConversation['c-new']).toEqual({ a: true }); + expect(Object.keys(store().byConversation)).toHaveLength(CONVERSATION_BUCKET_LIMIT); + }); + + it('只有工具行的会话也占一个名额', () => { + for (let i = 0; i < CONVERSATION_BUCKET_LIMIT; i++) { + store().setToolRowCollapsed(`t${i}`, 'call', true); + } + store().setTurnCollapsed('t-new', 'a', true); + + expect(store().toolRowsByConversation.t0).toBeUndefined(); + expect(store().toolRowsByConversation.t1).toEqual({ call: true }); + expect(store().byConversation['t-new']).toEqual({ a: true }); + }); + + it('再次写入把该会话留到最后,没改状态的重复写入不刷新', () => { + for (let i = 0; i < CONVERSATION_BUCKET_LIMIT; i++) { + store().setTurnCollapsed(`c${i}`, 'a', true); + } + store().setTurnCollapsed('c0', 'b', true); + store().setToolRowCollapsed('c0', 'call', true); + store().setTurnCollapsed('c1', 'a', true); + store().setToolRowCollapsed('c0', 'call', true); + store().setTurnCollapsed('c-new', 'a', true); + + expect(store().byConversation.c0).toEqual({ a: true, b: true }); + expect(store().toolRowsByConversation.c0).toEqual({ call: true }); + expect(store().byConversation.c1).toBeUndefined(); + expect(store().byConversation.c2).toEqual({ a: true }); + expect(store().byConversation['c-new']).toEqual({ a: true }); + }); + + it('没出现在最近顺序里的老会话比记过的更旧', () => { + const byConversation: Record = {}; + for (let i = 0; i < CONVERSATION_BUCKET_LIMIT; i++) byConversation[`old-${i}`] = { a: true }; + const patch: { + byConversation: Record; + toolRowsByConversation: Record>; + recent: string[]; + } = { + byConversation, + toolRowsByConversation: { 'old-0': { call: true }, 'old-1': { call: true } }, + recent: ['old-0'], + }; + useTurnCollapseStore.setState(patch); + store().setTurnCollapsed('old-new', 'a', true); + + expect(store().byConversation['old-0']).toEqual({ a: true }); + expect(store().toolRowsByConversation['old-0']).toEqual({ call: true }); + expect(store().byConversation['old-1']).toBeUndefined(); + expect(store().toolRowsByConversation['old-1']).toBeUndefined(); + expect(store().byConversation['old-2']).toEqual({ a: true }); + expect(store().byConversation['old-new']).toEqual({ a: true }); + }); + + it('最近顺序写进 localStorage,删会话时一并去掉', () => { + store().setTurnCollapsed('c1', 'a', true); + store().setToolRowCollapsed('c2', 'call', true); + store().setTurnCollapsed('c1', 'b', false); + expect(persisted().recent).toEqual(['c2', 'c1']); + + store().forgetConversation('c1'); + expect(persisted().recent).toEqual(['c2']); + expect(persisted().byConversation?.c1).toBeUndefined(); + expect(store().toolRowsByConversation.c2).toEqual({ call: true }); + }); +}); diff --git a/src/renderer/stores/turnCollapse.ts b/src/renderer/stores/turnCollapse.ts index 2aa21fd37..9f8905624 100644 --- a/src/renderer/stores/turnCollapse.ts +++ b/src/renderer/stores/turnCollapse.ts @@ -18,6 +18,11 @@ export type TurnCollapseMap = Record; /** 每个会话每类记录最多记住多少条;超出按写入顺序丢最早的,历史很长的会话不会无限增长。 */ export const TURN_COLLAPSE_LIMIT = 400; +/** + * 两类分桶按会话 id 合计的上限。单桶最多 400 条轮次加 400 条工具行, + * 100 个会话最坏约 3–4MB,仍在 localStorage 5MB 配额内;实际桶都很小。 + */ +export const TURN_COLLAPSE_CONVERSATION_LIMIT = 100; const STORE_NAME = 'enso-turn-collapse'; const AUTO_COLLAPSE_FIRST_PAINT_KEY = 'enso-auto-collapse-turns'; @@ -28,6 +33,8 @@ interface TurnCollapseState { byConversation: Record; /** 用户收起过的带图工具行/卡片:会话 → 工具调用 id → true */ toolRowsByConversation: Record>; + /** 最近改过折叠记录的会话 id,最近的在末尾。老数据里没有的会话视为最久未用。 */ + recent: string[]; setTurnCollapsed: (conversationId: string, turnId: string, collapsed: boolean) => void; setToolRowCollapsed: (conversationId: string, rowId: string, collapsed: boolean) => void; forgetConversation: (conversationId: string) => void; @@ -42,6 +49,57 @@ function capOldest>(map: T): T { return map; } +function liveConversationIds( + byConversation: Record, + toolRowsByConversation: Record +): string[] { + const ids = Object.keys(byConversation); + for (const id of Object.keys(toolRowsByConversation)) { + if (!(id in byConversation)) ids.push(id); + } + return ids; +} + +/** + * 这次写入把会话标成最近使用,并在会话数超限时丢掉最久未用的整桶(两类记录一起)。 + * 没进 recent 的老会话排在任何记过的会话之前,按当前键顺序淘汰。 + */ +function boundConversations( + byConversation: Record, + toolRowsByConversation: Record>, + recent: string[] | undefined, + touched: string +): Pick { + const liveList = liveConversationIds(byConversation, toolRowsByConversation); + const live = new Set(liveList); + const seen = new Set(); + const nextRecent: string[] = []; + for (const id of recent ?? []) { + if (id === touched || !live.has(id) || seen.has(id)) continue; + seen.add(id); + nextRecent.push(id); + } + if (live.has(touched)) nextRecent.push(touched); + + const ranked = new Set(nextRecent); + const oldestFirst = [...liveList.filter((id) => !ranked.has(id)), ...nextRecent]; + const overflow = oldestFirst.length - TURN_COLLAPSE_CONVERSATION_LIMIT; + if (overflow <= 0) return { byConversation, toolRowsByConversation, recent: nextRecent }; + + const drop = new Set(oldestFirst.slice(0, overflow)); + const keptBy = { ...byConversation }; + const keptRows = { ...toolRowsByConversation }; + for (const id of drop) { + delete keptBy[id]; + delete keptRows[id]; + } + return { + byConversation: keptBy, + toolRowsByConversation: keptRows, + recent: nextRecent.filter((id) => !drop.has(id)), + }; +} + /** 没有可用 localStorage(node 测试、隐私模式)时的兜底:本次运行内有效,不落盘。 */ function createMemoryStorage(): Storage { const memory = new Map(); @@ -101,13 +159,19 @@ export const useTurnCollapseStore = create()( (set) => ({ byConversation: {}, toolRowsByConversation: {}, + recent: [], setTurnCollapsed: (conversationId, turnId, collapsed) => set((state) => { const current = state.byConversation[conversationId] ?? {}; if (current[turnId] === collapsed) return state; const next = capOldest({ ...current, [turnId]: collapsed }); - return { byConversation: { ...state.byConversation, [conversationId]: next } }; + return boundConversations( + { ...state.byConversation, [conversationId]: next }, + state.toolRowsByConversation, + state.recent, + conversationId + ); }), setToolRowCollapsed: (conversationId, rowId, collapsed) => @@ -118,10 +182,14 @@ export const useTurnCollapseStore = create()( if (collapsed) next[rowId] = true; else delete next[rowId]; const { [conversationId]: _previous, ...rest } = state.toolRowsByConversation; - return { - toolRowsByConversation: - Object.keys(next).length > 0 ? { ...rest, [conversationId]: capOldest(next) } : rest, - }; + const toolRowsByConversation = + Object.keys(next).length > 0 ? { ...rest, [conversationId]: capOldest(next) } : rest; + return boundConversations( + state.byConversation, + toolRowsByConversation, + state.recent, + conversationId + ); }), forgetConversation: (conversationId) => { @@ -129,14 +197,19 @@ export const useTurnCollapseStore = create()( const current = useTurnCollapseStore.getState(); if ( !(conversationId in current.byConversation) && - !(conversationId in current.toolRowsByConversation) + !(conversationId in current.toolRowsByConversation) && + !current.recent.includes(conversationId) ) return; set((state) => { const { [conversationId]: _forgotten, ...byConversation } = state.byConversation; const { [conversationId]: _rows, ...toolRowsByConversation } = state.toolRowsByConversation; - return { byConversation, toolRowsByConversation }; + return { + byConversation, + toolRowsByConversation, + recent: state.recent.filter((id) => id !== conversationId), + }; }); }, }), @@ -146,6 +219,7 @@ export const useTurnCollapseStore = create()( partialize: (state) => ({ byConversation: state.byConversation, toolRowsByConversation: state.toolRowsByConversation, + recent: state.recent, }), } )