Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(desktop-ui): delegate the chat fixture to the real ChatStore

Alfredo Lopezf48785b212b8
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
index 8afe08c48..165c0edd3 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
@@ -1,4 +1,9 @@
-import { type Mock, vi } from 'vitest'
+import { type Mock, inject, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { join } from 'node:path'
+import { ChatStore } from '../../../../../../src/chatStore'
+import type { ChatDeleteFence, ChatMessage } from '../../../../../../src/types'
+import type {} from './mockClerumStoreRoot'
/**
* D.0 characterization fixture — installs a fake `window.clerum` bridge.
@@ -8,8 +13,19 @@ import { type Mock, vi } from 'vitest'
* `useAppController.test.tsx`). `useChatStore` is a thin wrapper over
* `window.clerum.chat.*` / `window.clerum.rpc.*`, so this exercises the real
* hook code path and keeps the suite consistent with the rest of the repo.
+ *
+ * R1-M11: the transcript writes and reads (`create`, `delete`, `loadMessages`,
+ * `appendMessages`, `upsertMessages`) delegate to a real `ChatStore` on a
+ * per-install directory under the run's temporary root, so suites observe the
+ * merge, delete tombstone and paging behavior the IPC handlers run in
+ * production. They stay `vi.fn` wrappers, so call assertions and per-test
+ * overrides keep working. `uninstallMockClerum` removes the directory; the
+ * global setup in `mockClerumStoreRoot.ts` removes the root after the run,
+ * including any directory a late store write recreated.
*/
+const storeDirs = new Set<string>()
+
type Handler = (event: unknown) => void
// `ReturnType<typeof vi.fn>` resolves to `Mock<Procedure | Constructable>`, and
// that union does not satisfy `(...args: any) => any`. Callers here write
@@ -61,31 +77,26 @@ export interface MockClerum {
hasProgressHandler: (taskId: string) => boolean
/** True once an activity handler exists for `hostRef`. */
hasActivityHandler: (hostRef: string) => boolean
- /** What the fake store holds for one chat after append/upsert writes. */
- persistedMessages: (agentRef: string, chatId: string) => Array<Record<string, unknown>>
+ /** What the real store holds for one chat, read straight from it. */
+ persistedMessages: (agentRef: string, chatId: string) => Promise<Array<Record<string, unknown>>>
}
export function installMockClerum(): MockClerum {
const progressHandlers = new Map<string, Handler>()
const activityHandlers = new Map<string, Handler>()
- // What the fake store holds per chat, so `upsertMessages` can merge like the
- // real `ChatStore.upsertMessages` instead of dropping a second write of an id.
- const persistedByChat = new Map<string, Array<Record<string, unknown>>>()
- const persistedKey = (agentRef: string, chatId: string) => `${agentRef}\u0000${chatId}`
- const persistedIndexOf = (persisted: Array<Record<string, unknown>>, id: string) =>
- persisted.findIndex(message => message.id === id)
-
- const isoNow = () => new Date().toISOString()
+ const root = inject('mockClerumStoreRoot')
+ if (!root) {
+ throw new Error(
+ 'mockClerum needs the mockClerumStoreRoot global setup; add it to the vitest globalSetup list'
+ )
+ }
+ const storeDir = mkdtempSync(join(root, 'store-'))
+ storeDirs.add(storeDir)
+ const store = new ChatStore(storeDir)
const chat = {
list: vi.fn(async () => []),
- create: vi.fn(async (_agentRef: string, chatId: string) => ({
- id: chatId,
- title: 'New Chat',
- createdAt: isoNow(),
- updatedAt: isoNow(),
- messageCount: 0,
- })),
+ create: vi.fn((agentRef: string, chatId: string) => store.createChat(agentRef, chatId)),
rename: vi.fn(async () => undefined),
getBindingGeneration: vi.fn(async () => 1),
captureDeleteFence: vi.fn(async (authorityScope: unknown) => ({
@@ -94,44 +105,21 @@ export function installMockClerum(): MockClerum {
bindingGeneration: 1,
sessionGeneration: 1,
})),
- delete: vi.fn(async () => ({ cleanupPending: false })),
- loadMessages: vi.fn(async () => []),
- appendMessages: vi.fn(async (agentRef: string, chatId: string, messages: unknown[]) => {
- const key = persistedKey(agentRef, chatId)
- persistedByChat.set(key, [
- ...(persistedByChat.get(key) ?? []),
- ...(messages as Array<Record<string, unknown>>),
- ])
- }),
- /**
- * Mirrors `ChatStore.upsertMessages` (src/chatStore.ts, the id branch of
- * `mergeReconciledMessages`): per chat, an id already persisted is replaced
- * in place and keeps its existing `task_id`; a new id is appended. New ids
- * still go through `appendMessages` so suites that count persisted turns
- * keep observing them there.
- */
- upsertMessages: vi.fn(async (agentRef: string, chatId: string, messages: unknown[]) => {
- const key = persistedKey(agentRef, chatId)
- const persisted = persistedByChat.get(key) ?? []
- const unseen: Array<Record<string, unknown>> = []
- for (const message of messages as Array<Record<string, unknown>>) {
- const id = message.id
- if (typeof id !== 'string') {
- throw new Error(`mockClerum.upsertMessages: message without a string id in ${chatId}`)
- }
- const index = persistedIndexOf(persisted, id)
- if (index < 0) {
- const pending = persistedIndexOf(unseen, id)
- if (pending < 0) unseen.push(message)
- else unseen[pending] = message
- continue
- }
- const taskId = persisted[index]?.task_id ?? message.task_id
- persisted[index] = { ...message, ...(taskId !== undefined ? { task_id: taskId } : {}) }
- }
- persistedByChat.set(key, persisted)
- if (unseen.length) await chat.appendMessages(agentRef, chatId, unseen)
+ // `chat:delete` hands the fence's scope to the store once main has matched
+ // it against the current authority; the store holds that same scope.
+ delete: vi.fn((agentRef: string, chatId: string, fence: ChatDeleteFence) => {
+ store.setAuthorityScope(fence.authorityScope)
+ return store.deleteChat(agentRef, chatId, fence.authorityScope)
}),
+ loadMessages: vi.fn((agentRef: string, chatId: string, limit?: number, offset?: number) =>
+ store.loadMessages(agentRef, chatId, limit, offset)
+ ),
+ appendMessages: vi.fn((agentRef: string, chatId: string, messages: ChatMessage[]) =>
+ store.appendMessages(agentRef, chatId, messages)
+ ),
+ upsertMessages: vi.fn((agentRef: string, chatId: string, messages: ChatMessage[]) =>
+ store.upsertMessages(agentRef, chatId, messages)
+ ),
replaceMessages: vi.fn(async () => undefined),
markUnreadTerminal: vi.fn(async () => undefined),
clearUnreadTerminal: vi.fn(async () => undefined),
@@ -191,9 +179,8 @@ export function installMockClerum(): MockClerum {
},
hasProgressHandler: (taskId: string) => progressHandlers.has(taskId),
hasActivityHandler: (hostRef: string) => activityHandlers.has(hostRef),
- persistedMessages: (agentRef: string, chatId: string) => [
- ...(persistedByChat.get(persistedKey(agentRef, chatId)) ?? []),
- ],
+ persistedMessages: async (agentRef: string, chatId: string) =>
+ (await store.loadMessages(agentRef, chatId)) as unknown as Array<Record<string, unknown>>,
}
Object.defineProperty(window, 'clerum', {
@@ -207,4 +194,6 @@ export function installMockClerum(): MockClerum {
export function uninstallMockClerum(): void {
delete (window as { clerum?: unknown }).clerum
+ for (const dir of storeDirs) rmSync(dir, { recursive: true, force: true })
+ storeDirs.clear()
}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerumStoreRoot.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerumStoreRoot.ts
new file mode 100644
index 000000000..66c3d50aa
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerumStoreRoot.ts
@@ -0,0 +1,27 @@
+import type { TestProject } from 'vitest/node'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+declare module 'vitest' {
+ export interface ProvidedContext {
+ mockClerumStoreRoot: string
+ }
+}
+
+/**
+ * Vitest global setup for the `mockClerum` fixture: one temporary root per run
+ * that holds every per-install `ChatStore` directory.
+ *
+ * A hook can still be writing through the store after a test unmounts it, and
+ * that write recreates a per-install directory the fixture has already
+ * removed. Removing the whole root here runs after every test file has
+ * finished, so no directory outlives the run.
+ */
+export default function setup(project: TestProject): () => void {
+ const root = mkdtempSync(join(tmpdir(), 'mockclerum-'))
+ project.provide('mockClerumStoreRoot', root)
+ return () => {
+ rmSync(root, { recursive: true, force: true })
+ }
+}
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/imageInputJourney.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/imageInputJourney.test.tsx
index 89abdfec5..1369a17ad 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/imageInputJourney.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/imageInputJourney.test.tsx
@@ -73,6 +73,17 @@ async function mountedVisualController() {
return rendered
}
+// The terminal handler releases the chat's task only after the reply is written
+// to the store, and the real ChatStore writes it to disk. A second send issued
+// before that write lands is refused while the first task still holds the chat.
+async function waitForPersistedReply(chatId: string) {
+ await waitFor(async () =>
+ expect(
+ (await bridge.persistedMessages('agent-x', chatId)).map(message => message.role)
+ ).toEqual(['user', 'assistant'])
+ )
+}
+
describe('#654 visual send and recovery', () => {
it('blocks pending images after selecting a text-only model, before creating a chat', async () => {
const { result } = await mountedVisualController()
@@ -229,6 +240,7 @@ describe('#654 visual send and recovery', () => {
})
})
await waitFor(() => expect(bridge.rpc.getTaskResult).toHaveBeenCalled())
+ await waitForPersistedReply(chatId)
// The chat now exists, so its own catalog read settles — carrying the server's
// OWN revision 0, which is older than the ack and must not overwrite it.
@@ -288,6 +300,7 @@ describe('#654 visual send and recovery', () => {
})
})
await waitFor(() => expect(bridge.rpc.getTaskResult).toHaveBeenCalled())
+ await waitForPersistedReply(chatId)
await act(async () => {
await loadHostModels(modelTransport, 'agent-x', chatId)
@@ -331,7 +344,9 @@ describe('#654 visual send and recovery', () => {
})
expect(result.current.failedAgentSend).toBeNull()
expect(result.current.agentError).toBeNull()
+ // Witness: the outgoing turn was persisted once, before the POST. The real
+ // store keeps that write in `upsertMessages`; the failure path added none.
expect(bridge.chat.upsertMessages).toHaveBeenCalledTimes(1)
- expect(bridge.chat.appendMessages).toHaveBeenCalledTimes(1)
+ expect(bridge.chat.appendMessages).not.toHaveBeenCalled()
})
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/mockClerum.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/mockClerum.test.ts
new file mode 100644
index 000000000..dfe6b661e
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/mockClerum.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+/**
+ * R1-M11: the `window.clerum.chat` fixture must persist exactly like the real
+ * `ChatStore` behind the IPC bridge. A hand-rolled merge that drifts from it
+ * certifies suites against a store production never runs.
+ */
+import { afterEach, describe, expect, it } from 'vitest'
+import type { ChatAuthorityScope } from '../../../../../src/types'
+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
+
+const AGENT = 'agent-x'
+const CHAT = 'chat-1'
+const SCOPE: ChatAuthorityScope = { environmentKey: 'env-test', userId: 'user-1', teamId: null }
+
+async function persistedIds(clerum: MockClerum): Promise<unknown[]> {
+ return (await clerum.persistedMessages(AGENT, CHAT)).map(message => message.id)
+}
+
+describe('mockClerum chat persistence', () => {
+ afterEach(() => {
+ uninstallMockClerum()
+ })
+
+ it('reconciles a turnless local message with its server turn like ChatStore', async () => {
+ const clerum = installMockClerum()
+ await clerum.chat.create(AGENT, CHAT)
+ await clerum.chat.appendMessages(AGENT, CHAT, [
+ { id: 'local-1', role: 'user', content: 'hello', timestamp: 1 },
+ ])
+ await clerum.chat.upsertMessages(AGENT, CHAT, [
+ { id: 'srv-1', role: 'user', content: 'hello', timestamp: 2, serverTurnNumber: 1 },
+ ])
+
+ expect(await persistedIds(clerum)).toEqual(['srv-1'])
+ // Witness: the bridge's own read returns the real store's result.
+ const loaded = (await clerum.chat.loadMessages(AGENT, CHAT)) as Array<{ id: string }>
+ expect(loaded.map(message => message.id)).toEqual(['srv-1'])
+ })
+
+ it('drops a late upsert into a chat deleted in the current scope like ChatStore', async () => {
+ const clerum = installMockClerum()
+ await clerum.chat.create(AGENT, CHAT)
+ await clerum.chat.appendMessages(AGENT, CHAT, [
+ { id: 'before', role: 'user', content: 'kept until delete', timestamp: 1 },
+ ])
+ // Witness: the chat held a message before the delete.
+ expect(await persistedIds(clerum)).toEqual(['before'])
+
+ const fence = await clerum.chat.captureDeleteFence(SCOPE)
+ await clerum.chat.delete(AGENT, CHAT, fence)
+ await clerum.chat.upsertMessages(AGENT, CHAT, [
+ { id: 'late', role: 'assistant', content: 'late reply', timestamp: 3 },
+ ])
+
+ expect(await persistedIds(clerum)).toEqual([])
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
index 2584ab806..7e0a7078a 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
@@ -127,12 +127,16 @@ describe('pendingChatSelection effect', () => {
})
await waitFor(() => expect(result.current.activeChatId).toBe('c-latest'))
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
- 'agent-x',
- 'agent-x',
- 'c-latest',
- undefined,
- { limit: 40 }
+ // The remote load follows the local store read, which crosses IPC (here, the
+ // real ChatStore's disk read), so it lands after the selection flips.
+ await waitFor(() =>
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'c-latest',
+ undefined,
+ { limit: 40 }
+ )
)
})
@@ -161,12 +165,14 @@ describe('pendingChatSelection effect', () => {
})
await waitFor(() => expect(result.current.activeChatId).toBe('c-newest'))
- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
- 'agent-x',
- 'agent-x',
- 'c-newest',
- undefined,
- { limit: 40 }
+ await waitFor(() =>
+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'agent-x',
+ 'c-newest',
+ undefined,
+ { limit: 40 }
+ )
)
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
index c0178a627..81a08120b 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx
@@ -49,8 +49,16 @@ describe('sendAgentMessage — synchronous (non-async) response', () => {
// No async task → no progress subscription was ever opened.
expect(clerum.rpc.subscribeTaskProgress).not.toHaveBeenCalled()
- // user message + assistant reply persisted.
- expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(2)
+ // user message (upserted before the POST) + assistant reply (appended) are
+ // both in the store.
+ const chatId = result.current.activeChatId!
+ expect(
+ (await clerum.persistedMessages('agent-x', chatId)).map(m => [m.role, m.content])
+ ).toEqual([
+ ['user', 'quick question'],
+ ['assistant', 'direct answer'],
+ ])
+ expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(1)
const assistant = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
| Array<{ role?: string; content?: string; isError?: boolean }>
| undefined
@@ -96,7 +104,7 @@ describe('sendAgentMessage — POST failure', () => {
expect(result.current.failedAgentSend?.kind).toBe('network')
// Late persist: the POST threw before the single post-taskId persist, so the
// user's typed input is still written to the store (best-effort durability).
- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.upsertMessages).toHaveBeenCalledWith(
'agent-x',
expect.any(String),
expect.arrayContaining([
@@ -252,9 +260,9 @@ describe('sendAgentMessage — outgoing user turn persistence', () => {
task_id: 'task-77',
})
- const persistedUserTurns = clerum
- .persistedMessages(agentRef, chatId)
- .filter(message => message.role === 'user')
+ const persistedUserTurns = (await clerum.persistedMessages(agentRef, chatId)).filter(
+ message => message.role === 'user'
+ )
expect(persistedUserTurns).toEqual([
expect.objectContaining({ id: turnId, content: 'hello', task_id: 'task-77' }),
])
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sessionStateRecovery.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sessionStateRecovery.characterization.test.tsx
index 8065de512..edff824e0 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/sessionStateRecovery.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/sessionStateRecovery.characterization.test.tsx
@@ -250,9 +250,12 @@ describe('onTrackerTerminal — recover via reconcile catch', () => {
| undefined
expect(appended?.[0]?.errorCode).toBe('BUDGET_EXCEEDED')
expect(appended?.[0]?.content).toBe('Budget exceeded')
- expect(spies.pushToast).toHaveBeenCalledWith(
- 'Message to agent-x failed: Budget exceeded',
- 'error'
+ // The failure toast follows the store write of the error reply.
+ await waitFor(() =>
+ expect(spies.pushToast).toHaveBeenCalledWith(
+ 'Message to agent-x failed: Budget exceeded',
+ 'error'
+ )
)
// A durable failure still retains the input for explicit recovery/retry.
expect(result.current.failedAgentSend).toMatchObject({ content: 'spend' })
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
index ad9c72f68..98fd39c54 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
@@ -124,9 +124,11 @@ describe('useAgentChatController — characterization (D.0)', () => {
{ limit: 40 }
)
expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'chat-2')
- // Server is source of truth → replace, not append.
+ // Server is source of truth → replace, not append (nor upsert, which the
+ // real store keeps apart from append).
expect(clerum.chat.replaceMessages).toHaveBeenCalled()
expect(clerum.chat.appendMessages).not.toHaveBeenCalled()
+ expect(clerum.chat.upsertMessages).not.toHaveBeenCalled()
// spec 15 §2.2/A19: the first-turn auto-title is shown EPHEMERALLY in the
// sidebar (observable output, T4) but is NOT persisted via rename — the
// server title is authoritative and a persisted client-derived title would
@@ -325,8 +327,18 @@ describe('useAgentChatController — characterization (D.0)', () => {
await sendPromise
expect(sendResolved).toBe(true)
- // user message + assistant reply
- expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(2)
+ // The user message is upserted before the POST and the assistant reply is
+ // appended after the terminal; the store holds both, in order.
+ const chatId = result.current.activeChatId!
+ await waitFor(async () =>
+ expect(
+ (await clerum.persistedMessages('agent-x', chatId)).map(m => [m.role, m.content])
+ ).toEqual([
+ ['user', 'hola'],
+ ['assistant', 'done!'],
+ ])
+ )
+ expect(clerum.chat.appendMessages).toHaveBeenCalledTimes(1)
expect(clerum.rpc.getTaskResult).toHaveBeenCalledWith('agent-x', 'task-abc', ['agent-x'])
expect(spies.pushToast).toHaveBeenCalledWith('Message sent to agent-x.', 'success')
})
@@ -423,7 +435,10 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
await sendPromise
- expect(spies.pushToast).toHaveBeenCalledWith('Message to agent-x failed: LLM down', 'error')
+ // The failure toast follows the store write of the error reply.
+ await waitFor(() =>
+ expect(spies.pushToast).toHaveBeenCalledWith('Message to agent-x failed: LLM down', 'error')
+ )
const appended = clerum.chat.appendMessages.mock.calls.at(-1)?.[2] as
| Array<{ isError?: boolean; errorCode?: string }>
| undefined
@@ -562,11 +577,12 @@ describe('useAgentChatController — characterization (D.0)', () => {
sendError = e
})
- // Flush the async send setup until the progress subscription is wired.
+ // Flush the async send setup until the progress subscription is wired. The
+ // send persists the user turn to the real ChatStore first, which is disk
+ // I/O that fake timers do not advance: poll for the subscription instead.
await act(async () => {
- await vi.advanceTimersByTimeAsync(0)
+ await vi.waitFor(() => expect(clerum.hasProgressHandler('task-abc')).toBe(true))
})
- expect(clerum.hasProgressHandler('task-abc')).toBe(true)
await act(async () => {
// Open the stream, then go silent and advance past the 30s watchdog.
@@ -581,7 +597,12 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
await sendPromise
- expect(spies.pushToast).toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
+ // The failure toast follows the store write of the error reply.
+ await act(async () => {
+ await vi.waitFor(() =>
+ expect(spies.pushToast).toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
+ )
+ })
expect(result.current.agentSending).toBe(false)
expect(sendError).toBeNull() // controller catches internally, does not reject
})
@@ -612,9 +633,12 @@ describe('useAgentChatController — characterization (D.0)', () => {
| undefined
expect(appended?.[0]?.isError).toBe(true)
expect(appended?.[0]?.content).toContain('Failed to retrieve task result')
- expect(spies.pushToast).toHaveBeenCalledWith(
- expect.stringContaining('Failed to retrieve result'),
- 'error'
+ // The failure toast follows the store write of the error reply.
+ await waitFor(() =>
+ expect(spies.pushToast).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to retrieve result'),
+ 'error'
+ )
)
})
@@ -630,10 +654,11 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
const sendPromise = result.current.handleSendAgentMessage('hola').catch(() => undefined)
+ // The user turn is persisted to the real ChatStore (disk I/O fake timers do
+ // not advance) before the subscription is wired: poll for it.
await act(async () => {
- await vi.advanceTimersByTimeAsync(0)
+ await vi.waitFor(() => expect(clerum.hasProgressHandler('task-abc')).toBe(true))
})
- expect(clerum.hasProgressHandler('task-abc')).toBe(true)
await act(async () => {
// Never emit 'open'. Advance past the 5s connection timeout.
@@ -641,9 +666,15 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
await sendPromise
- const progress = result.current.progressByAgentMessage['agent-x']
- const entry = progress && Object.values(progress)[0]
- expect(entry?.status).toBe('error')
+ // The timeout's recovery reads the store (disk I/O) before it settles the
+ // entry as an error: poll for the settled state.
+ await act(async () => {
+ await vi.waitFor(() => {
+ const progress = result.current.progressByAgentMessage['agent-x']
+ const entry = progress && Object.values(progress)[0]
+ expect(entry?.status).toBe('error')
+ })
+ })
})
// ── stream-recovery spec: a lost stream reconciles instead of failing ──
@@ -840,6 +871,9 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
})
+ // The reconcile reads the local store (IPC; here the real ChatStore's disk
+ // read) before it fetches the server turns, so wait for that fetch.
+ await waitFor(() => expect(clerum.rpc.loadSessionMessages).toHaveBeenCalled())
// The live subscription has fired for the `failed` state, but the reconcile
// is still pending → no message may be painted as an error (no flash).
const midProgress = result.current.progressByAgentMessage['agent-x'] ?? {}
@@ -933,8 +967,22 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
})
- // The durable reply lands as a delta; no error/resend and no zombie block.
- await waitFor(() => expect(clerum.chat.appendMessages).toHaveBeenCalled())
+ // The durable reply lands in the reconciled transcript the controller writes
+ // back with `replaceMessages`; no error/resend and no zombie block. (The old
+ // wait on `appendMessages` was met by the user turn the fake store forwarded
+ // there, never by the reply.)
+ await waitFor(() =>
+ expect(
+ clerum.chat.replaceMessages.mock.calls.some(call =>
+ (call[2] as Array<{ role?: string; content?: string }>).some(
+ message => message.role === 'assistant' && message.content === 'here is your report'
+ )
+ )
+ ).toBe(true)
+ )
+ expect(result.current.chatMessages).toContainEqual(
+ expect.objectContaining({ role: 'assistant', content: 'here is your report' })
+ )
expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')
expect(result.current.failedAgentSend).toBeNull()
await sendPromise
@@ -981,10 +1029,9 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
// The durable error is rendered as a failed assistant message. Wait for the
- // ASSISTANT append specifically: `appendMessages` fires first for the user
- // message, so a bare "was called" wait would race the recovery's append
- // (which lands after the `getTaskResult` await) — read the last call only
- // once its message is the error bubble.
+ // ASSISTANT append specifically: the recovery's append lands after the
+ // `getTaskResult` await — read the last call only once its message is the
+ // error bubble.
await waitFor(() => {
const last = clerum.chat.appendMessages.mock.calls.at(-1)?.[2]?.[0] as
| { isError?: boolean }
@@ -997,9 +1044,12 @@ describe('useAgentChatController — characterization (D.0)', () => {
expect(appended?.[0]?.isError).toBe(true)
expect(appended?.[0]?.errorCode).toBe('BUDGET_EXCEEDED')
expect(appended?.[0]?.content).toContain('Token budget exceeded')
- expect(spies.pushToast).toHaveBeenCalledWith(
- 'Message to agent-x failed: Token budget exceeded for this workspace.',
- 'error'
+ // The failure toast follows the store write of the error reply.
+ await waitFor(() =>
+ expect(spies.pushToast).toHaveBeenCalledWith(
+ 'Message to agent-x failed: Token budget exceeded for this workspace.',
+ 'error'
+ )
)
// #654 deliberately retains failed input, while preserving the real
// budget error instead of presenting a misleading lost-connection error.
@@ -1046,8 +1096,8 @@ describe('useAgentChatController — characterization (D.0)', () => {
})
})
- // Wait for the ASSISTANT append specifically (the user-message append fires
- // first; the recovery's reply lands after the `getTaskResult` await).
+ // Wait for the ASSISTANT append specifically (the recovery's reply lands
+ // after the `getTaskResult` await).
await waitFor(() => {
const last = clerum.chat.appendMessages.mock.calls.at(-1)?.[2]?.[0] as
| { role?: string }
@@ -1752,11 +1802,15 @@ describe('useAgentChatController — characterization (D.0)', () => {
// The user message was persisted (a chat was auto-created and the typed
// input written to it) — the input is durable across reload.
expect(clerum.chat.create).toHaveBeenCalled()
- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(
+ expect(clerum.chat.upsertMessages).toHaveBeenCalledWith(
'agent-x',
expect.any(String),
expect.arrayContaining([expect.objectContaining({ role: 'user', content: 'persist me' })])
)
+ const persisted = await clerum.persistedMessages('agent-x', result.current.activeChatId!)
+ expect(persisted).toContainEqual(
+ expect.objectContaining({ role: 'user', content: 'persist me', task_id: 'task-ga' })
+ )
})
})
})
diff --git a/desktop-app/vitest.config.ts b/desktop-app/vitest.config.ts
index f4901843e..3d4886410 100644
--- a/desktop-app/vitest.config.ts
+++ b/desktop-app/vitest.config.ts
@@ -29,6 +29,9 @@ export default defineConfig({
// which serves an out-of-root setup file under `/@fs/` and cannot resolve
// it from a path relative to this package.
setupFiles: [path.resolve(__dirname, '../scripts/testing/bind-loopback-in-tests.mjs')],
+ // Owns the temporary root of the renderer chat fixture's real ChatStore
+ // directories and removes it once every test file has finished.
+ globalSetup: ['ui/src/hooks/domain/__tests__/__fixtures__/mockClerumStoreRoot.ts'],
fileParallelism: false,
teardownTimeout: 60_000,
include: [