Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): sweep pending chat cleanups per agent on read and once per bind
Alfredo Lopez48e3b7fbe67a
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 9841bba29..08742a4be 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -1004,6 +1004,125 @@ describe('deleted-chat cleanup failure reporting', () => {})})+/**+ * `chat:getIndex` retries the pending cleanups before every read and the+ * renderer reads every agent's index in a fan-out, so a retry that walks every+ * agent costs N·(N+1) index reads per fan-out. The first retry after a bind+ * walks every agent once; later retries touch only the agent being read.+ */+describe('pending cleanup retry per agent', () => {+ const AGENTS = ['agent-1', 'agent-2', 'agent-3', 'agent-4', 'agent-5']+ const indexPathOf = (agentRef: string) => join(tempDir, agentRef, 'index.json')++ async function queueFailedCleanup(agentRef: string, chatId: string): Promise<void> {+ await store.createChat(agentRef, chatId)+ await store.saveMessages(agentRef, chatId, [+ { id: 'm1', role: 'user', content: 'x', timestamp: 1 },+ ])+ const rm = vi+ .spyOn(fs, 'rm')+ .mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ await expect(store.deleteChat(agentRef, chatId, TEAM_A_SCOPE)).resolves.toEqual({+ cleanupPending: true,+ })+ rm.mockRestore()+ warn.mockRestore()+ }++ /** Records every read of an agent's index.json until the mocks are restored. */+ function recordIndexReads(): string[] {+ const originalReadFile = fs.readFile.bind(fs)+ const reads: string[] = []+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (filePath.endsWith('index.json')) reads.push(filePath)+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })+ return reads+ }++ async function pendingOf(agentRef: string) {+ return (await store.getIndex(agentRef)).pendingChatCleanup ?? []+ }++ it('walks every agent once after a bind, then reads only the requested agent', async () => {+ for (const agentRef of AGENTS) await queueFailedCleanup(agentRef, `pending-${agentRef}`)+ // Witness: every agent really has a queued cleanup.+ for (const agentRef of AGENTS) expect(await pendingOf(agentRef)).toHaveLength(1)+ store.setAuthorityScope(TEAM_A_SCOPE)+ const reads = recordIndexReads()++ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')+ // The sweep reads each agent's index to find its queue, and once more to+ // drop the finished entry.+ expect(reads).toHaveLength(2 * AGENTS.length)+ const afterSweep = reads.length+ for (const agentRef of AGENTS.slice(1)) {+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, agentRef)+ }++ expect(reads.slice(afterSweep)).toEqual(AGENTS.slice(1).map(indexPathOf))+ expect(reads).toHaveLength(3 * AGENTS.length - 1)+ vi.restoreAllMocks()+ for (const agentRef of AGENTS) expect(await pendingOf(agentRef)).toEqual([])+ })++ it('finishes a cleanup queued after the sweep on the next read of that agent', async () => {+ await store.createChat('agent-1', 'kept')+ store.setAuthorityScope(TEAM_A_SCOPE)+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')+ await queueFailedCleanup('agent-3', 'late-delete')+ // Witness: the cleanup is really queued and its artifacts are on disk.+ expect(await pendingOf('agent-3')).toHaveLength(1)+ await expect(fs.access(join(tempDir, 'agent-3', 'chats', 'late-delete'))).resolves.toBe(+ undefined+ )+ const reads = recordIndexReads()++ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-3')++ const retryReads = [...reads]+ vi.restoreAllMocks()+ expect(await pendingOf('agent-3')).toEqual([])+ await expect(fs.access(join(tempDir, 'agent-3', 'chats', 'late-delete'))).rejects.toThrow()+ // Only agent-3 was touched: read to find its queue, then to drop the entry.+ expect(retryReads).toEqual([indexPathOf('agent-3'), indexPathOf('agent-3')])+ })++ it('walks every agent again after the next bind', async () => {+ for (const agentRef of AGENTS.slice(0, 3)) await store.createChat(agentRef, 'kept')+ store.setAuthorityScope(TEAM_A_SCOPE)+ const reads = recordIndexReads()++ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')+ // A team switch of the same user rebinds the store.+ store.setAuthorityScope(TEAM_B_SCOPE)+ await store.retryPendingDeleteCleanups(TEAM_B_SCOPE, 'agent-1')++ const sweep = AGENTS.slice(0, 3).map(indexPathOf)+ expect(reads).toEqual([...sweep, indexPathOf('agent-1'), ...sweep])+ })++ it('keeps the sweep armed when the agents directory cannot be listed', async () => {+ for (const agentRef of AGENTS.slice(0, 2)) await store.createChat(agentRef, 'kept')+ store.setAuthorityScope(TEAM_A_SCOPE)+ const readdir = vi+ .spyOn(fs, 'readdir')+ .mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }))++ await expect(store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')).rejects.toMatchObject({+ code: 'EACCES',+ })+ const reads = recordIndexReads()+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE, 'agent-1')++ expect(readdir.mock.calls.map(call => String(call[0]))).toEqual([tempDir, tempDir])+ expect(reads).toEqual(AGENTS.slice(0, 2).map(indexPathOf))+ })+})+// ── messages ─────────────────────────────────────────────────────────────────describe('messages', () => {diff --git a/desktop-app/src/__tests__/ipc.chatGetIndex.test.ts b/desktop-app/src/__tests__/ipc.chatGetIndex.test.tsindex 48cfe2523..c72bf81c0 100644--- a/desktop-app/src/__tests__/ipc.chatGetIndex.test.ts+++ b/desktop-app/src/__tests__/ipc.chatGetIndex.test.ts@@ -133,10 +133,29 @@ describe('chat:getIndex', () => {expect(tombstones(index)).toEqual(['deleted-chat'])})- it('still returns the tombstones and reports the code when the chats directory is unreadable', async () => {- vi.spyOn(fs, 'readdir').mockRejectedValueOnce(- Object.assign(new Error('permission denied'), { code: 'EACCES' })+ it('retries only the cleanups of the agent being read once the bind sweep ran', async () => {+ const binding = await import('../chatStoreBinding.js')+ // Earlier reads in this file already consumed the sweep of the bind.+ const retry = vi.spyOn(binding.requireChatStore(), 'retryPendingDeleteCleanups')+ const readdir = vi.spyOn(fs, 'readdir')++ const index = await call('chat:getIndex', { agentRef: 'agent-1' })++ expect(retry).toHaveBeenCalledWith(TEAM_A, 'agent-1')+ expect(readdir.mock.calls.map(entry => String(entry[0]))).not.toContain(+ join(base, 'env-a', 'user-a'))+ expect(tombstones(index)).toEqual(['deleted-chat'])+ })++ it('still returns the tombstones and reports the code when the chats directory is unreadable', async () => {+ const binding = await import('../chatStoreBinding.js')+ // Re-binding the same user (a team switch or a catalog refresh) arms the+ // sweep over every agent directory for the next read.+ await binding.bindChatStoreForUser('user-a', 'env-a', { teamId: 'team-a' })+ const readdir = vi+ .spyOn(fs, 'readdir')+ .mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' }))const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)const index = await call('chat:getIndex', { agentRef: 'agent-1' })@@ -144,5 +163,9 @@ describe('chat:getIndex', () => {const report = warn.mock.calls.find(entry => String(entry[0]).includes('[chat:getIndex]'))expect(String(report?.[0])).toContain('(EACCES)')expect(tombstones(index)).toEqual(['deleted-chat'])+ // The sweep that failed stays armed: the next read walks the directory again.+ await call('chat:getIndex', { agentRef: 'agent-1' })+ const userDir = join(base, 'env-a', 'user-a')+ expect(readdir.mock.calls.map(entry => String(entry[0]))).toEqual([userDir, userDir])})})diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 5f3cb81e8..92459aed7 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -394,6 +394,8 @@ export class ChatStore {private readonly pageSize: numberprivate readonly maxLocalSyncedMessages: numberprivate authorityScope: ChatAuthorityScope | null = null+ /** Set by every bind; the next cleanup retry walks every agent once. */+ private pendingCleanupSweep = trueconstructor(private readonly baseDir: string,@@ -405,6 +407,7 @@ export class ChatStore {setAuthorityScope(scope: ChatAuthorityScope): void {this.authorityScope = Object.freeze({ ...scope })+ this.pendingCleanupSweep = true}getAuthorityScope(): ChatAuthorityScope | null {@@ -1962,36 +1965,63 @@ export class ChatStore {}}- async retryPendingDeleteCleanups(authorityScope: ChatAuthorityScope): Promise<void> {+ /**+ * Retries the calling identity's queued artifact cleanups. With `agentRef`+ * only that agent's queue is retried, except on the first retry after a bind+ * (`setAuthorityScope`), which walks every agent once so the queues of agents+ * that are not read again still finish. Without `agentRef` every agent is+ * walked.+ */+ async retryPendingDeleteCleanups(+ authorityScope: ChatAuthorityScope,+ agentRef?: string+ ): Promise<void> {const scope = this.requireDeletionIdentity(authorityScope)+ if (agentRef !== undefined && !this.pendingCleanupSweep) {+ await this.retryAgentPendingDeleteCleanups(agentRef, scope)+ return+ }+ this.pendingCleanupSweep = falselet entriestry {entries = await fs.readdir(this.baseDir, { withFileTypes: true })} catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ // The walk did not happen: the next retry attempts it again.+ this.pendingCleanupSweep = truethrow error}for (const entry of entries) {if (!entry.isDirectory()) continue- const agentRef = entry.name- try {- const index = await this.getIndex(agentRef)- const pending = (index.pendingChatCleanup ?? []).filter(item =>- sameChatDeletionIdentity(item.authorityScope, scope)- )- for (const tombstone of pending) {- if (!this.authorityScope || !sameChatDeletionIdentity(this.authorityScope, scope)) return- await this.serializeChat(agentRef, tombstone.chatId, () =>- this.finishPendingDeleteCleanup(agentRef, tombstone)- )+ if (!(await this.retryAgentPendingDeleteCleanups(entry.name, scope))) return+ }+ }++ /** Retries one agent's queue; false once the identity changed and retrying must stop. */+ private async retryAgentPendingDeleteCleanups(+ agentRef: string,+ scope: ChatAuthorityScope+ ): Promise<boolean> {+ try {+ const index = await this.getIndex(agentRef)+ const pending = (index.pendingChatCleanup ?? []).filter(item =>+ sameChatDeletionIdentity(item.authorityScope, scope)+ )+ for (const tombstone of pending) {+ if (!this.authorityScope || !sameChatDeletionIdentity(this.authorityScope, scope)) {+ return false}- } catch (error) {- // An unrelated or unreadable agent index must not prevent other durable- // cleanup entries from being retried on the next authorized read, but the- // failure is reported (once per agent and code), never swallowed.- this.warnCleanupFailureOnce(agentRef, null, error)+ await this.serializeChat(agentRef, tombstone.chatId, () =>+ this.finishPendingDeleteCleanup(agentRef, tombstone)+ )}+ } catch (error) {+ // An unrelated or unreadable agent index must not prevent other durable+ // cleanup entries from being retried on the next authorized read, but the+ // failure is reported (once per agent and code), never swallowed.+ this.warnCleanupFailureOnce(agentRef, null, error)}+ return true}async loadMessages(diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 845195265..436abdaa3 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1729,9 +1729,11 @@ export function registerIpcHandlers(service: AppService): void {// chats directory) would otherwise reject the read and leave the renderer// without the tombstones it filters deleted chats with. The failure is// reported with its code and the cleanup stays queued for the next read.+ // Only this agent's queue is retried (the renderer reads every agent in a+ // fan-out); the store walks every agent once per bind on its own.try {const authority = service.getChatDeletionFenceAuthority()- await store.retryPendingDeleteCleanups(authority.authorityScope)+ await store.retryPendingDeleteCleanups(authority.authorityScope, agentRef)} catch (error) {const code = (error as NodeJS.ErrnoException | undefined)?.codeconsole.warn(