The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(desktop): share the duplicated fixtures
Brooklyn Nicholson808fde106dc7
diff --git a/apps/desktop/e2e/batch-clarify.spec.ts b/apps/desktop/e2e/batch-clarify.spec.tsindex 8658bd3b1b5..acf97ddb2e3 100644--- a/apps/desktop/e2e/batch-clarify.spec.ts+++ b/apps/desktop/e2e/batch-clarify.spec.ts@@ -5,8 +5,8 @@* model's tool_call_id while `clarify.request` carries a gateway-generated* request_id. A batch payload has no top-level `question`, so the two rows* only merge when the correlation key comes from the question list- * (`batchClarifyMatchValue` in lib/chat-messages.ts). Before that fix this- * exact flow rendered two identical interactive cards.+ * (`batchClarifyMatchValue` in lib/chat-messages/tool-parts.ts). Before that+ * fix this exact flow rendered two identical interactive cards.** The flow runs the real chain: composer → gateway → agent → clarify tool →* clarify.request event → renderer, against the mock inference server.diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsxindex bbffc396ecb..c687d310e45 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx@@ -2,6 +2,8 @@ import { render } from '@testing-library/react'import { createRef, type RefObject } from 'react'import { describe, expect, it, vi } from 'vitest'+import { placeCaretAtEnd } from '../test-utils'+import { useComposerUndo } from './use-composer-undo'/** Mount the hook against a real contentEditable, exposing its API. */@@ -36,19 +38,10 @@ function makeEditor(text: string) {return { editor, ref }}-const caretAtEnd = (editor: HTMLElement) => {- const range = document.createRange()- const selection = window.getSelection()!- range.selectNodeContents(editor)- range.collapse(false)- selection.removeAllRanges()- selection.addRange(range)-}-describe('useComposerUndo', () => {it('restores the pre-edit text, which is what a paste destroyed', () => {const { editor, ref } = makeEditor('before')- caretAtEnd(editor)+ placeCaretAtEnd(editor)const { api, view } = mountUndo(ref, () => editor.textContent || '')@@ -69,7 +62,7 @@ describe('useComposerUndo', () => {it('withUndoPoint banks only when the edit actually ran', () => {const { editor, ref } = makeEditor('text')- caretAtEnd(editor)+ placeCaretAtEnd(editor)const { api, view } = mountUndo(ref, () => editor.textContent || '')@@ -95,7 +88,7 @@ describe('useComposerUndo', () => {it('claims a native historyUndo aimed at the focused editor', () => {const { editor, ref } = makeEditor('kept')editor.focus()- caretAtEnd(editor)+ placeCaretAtEnd(editor)const { api, view } = mountUndo(ref, () => editor.textContent || '')@@ -162,7 +155,7 @@ describe('useComposerUndo', () => {it('reset drops history so undo cannot cross a draft swap', () => {const { editor, ref } = makeEditor('session A')- caretAtEnd(editor)+ placeCaretAtEnd(editor)const { api, view } = mountUndo(ref, () => editor.textContent || '')diff --git a/apps/desktop/src/app/chat/composer/rich-editor.test.ts b/apps/desktop/src/app/chat/composer/rich-editor.test.tsindex 6c3d2f87332..d3bfd60eedb 100644--- a/apps/desktop/src/app/chat/composer/rich-editor.test.ts+++ b/apps/desktop/src/app/chat/composer/rich-editor.test.ts@@ -11,16 +11,7 @@ import {replaceBeforeCaret,RICH_INPUT_SLOT} from './rich-editor'--const caretIn = (editor: HTMLElement) => {- const range = document.createRange()- const selection = window.getSelection()!-- range.selectNodeContents(editor)- range.collapse(false)- selection.removeAllRanges()- selection.addRange(range)-}+import { placeCaretAtEnd } from './test-utils'describe('renderComposerContents', () => {it('renders refs and raw text without interpreting user text as HTML', () => {@@ -160,7 +151,7 @@ describe('insertInlineRefsIntoEditor', () => {editor.dataset.slot = RICH_INPUT_SLOTeditor.append(document.createTextNode('review'))document.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)expect(insertInlineRefsIntoEditor(editor, ['@file:`src/a.ts`'])).toBe('review @file:`src/a.ts` ')@@ -172,7 +163,7 @@ describe('insertInlineRefsIntoEditor', () => {editor.dataset.slot = RICH_INPUT_SLOTeditor.append(document.createTextNode('review '))document.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)expect(insertInlineRefsIntoEditor(editor, ['@file:`src/a.ts`'])).toBe('review @file:`src/a.ts` ')@@ -185,7 +176,7 @@ describe('insertComposerContentsAtCaret', () => {const editor = document.createElement('div')editor.dataset.slot = RICH_INPUT_SLOTdocument.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, 'one\ntwo\nthree')@@ -221,7 +212,7 @@ describe('insertComposerContentsAtCaret', () => {const editor = document.createElement('div')editor.dataset.slot = RICH_INPUT_SLOTdocument.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, 'read @url:`https://example.dev/a` now')@@ -237,7 +228,7 @@ describe('insertComposerContentsAtCaret', () => {const editor = document.createElement('div')editor.dataset.slot = RICH_INPUT_SLOTdocument.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, '/some-skill')@@ -253,7 +244,7 @@ describe('insertComposerContentsAtCaret', () => {const editor = document.createElement('div')editor.dataset.slot = RICH_INPUT_SLOTdocument.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, 'clean @file:`a.ts` with /some-skill then ship')@@ -268,7 +259,7 @@ describe('insertComposerContentsAtCaret', () => {const editor = document.createElement('div')editor.dataset.slot = RICH_INPUT_SLOTdocument.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, 'see /usr/local/bin and /goal ship it')@@ -283,7 +274,7 @@ describe('insertComposerContentsAtCaret', () => {editor.dataset.slot = RICH_INPUT_SLOTeditor.textContent = 'foo'document.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, '/some-skill')@@ -298,7 +289,7 @@ describe('insertComposerContentsAtCaret', () => {editor.dataset.slot = RICH_INPUT_SLOTeditor.append(refChipElement('file', '`a.ts`'))document.body.append(editor)- caretIn(editor)+ placeCaretAtEnd(editor)insertComposerContentsAtCaret(editor, '/some-skill')diff --git a/apps/desktop/src/app/chat/composer/test-utils.ts b/apps/desktop/src/app/chat/composer/test-utils.tsnew file mode 100644index 00000000000..23c71f74d48--- /dev/null+++ b/apps/desktop/src/app/chat/composer/test-utils.ts@@ -0,0 +1,14 @@+/** Collapse the selection to the end of the editor's contents.+ *+ * The composer's undo stack, ref rendering, and trigger detection all read the+ * live selection, and jsdom starts with none — without this they see a caret+ * at offset 0 and take the wrong branch. */+export function placeCaretAtEnd(editor: HTMLElement) {+ const range = document.createRange()+ const selection = window.getSelection()!++ range.selectNodeContents(editor)+ range.collapse(false)+ selection.removeAllRanges()+ selection.addRange(range)+}diff --git a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx b/apps/desktop/src/app/chat/session-tile-attachments.test.tsxindex b9a97a86113..b756f821e4d 100644--- a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx+++ b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx@@ -13,6 +13,8 @@ import {import { $connection, $sessions } from '@/store/session'import { $sessionStates, type SessionTileDelegate, setSessionTileDelegate } from '@/store/session-states'+import { deferred } from '../../test/deferred'+const requestGateway = vi.fn()vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({@@ -44,16 +46,6 @@ const STAGED_PATH = '/root/.hermes/attachments/photo.png'const THUMBNAIL = 'data:image/png;base64,dGh1bWJuYWls'const FULL_SOURCE = 'data:image/png;base64,b3JpZ2luYWw='-function deferred<T>() {- let resolve!: (value: T) => void-- const promise = new Promise<T>(res => {- resolve = res- })-- return { promise, resolve }-}-function makeAttachment(occurrenceId = createComposerAttachmentOccurrenceId()): ComposerAttachment {return {detail: HOST_PATH,diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.tsindex bd32d4fd4a8..c81f1d72b11 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import type { HermesGitWorktree } from '@/global'+import { makeCwdSession } from '@/test/session-info'import type { ProjectInfo, SessionInfo } from '@/types/hermes'import {@@ -22,29 +23,6 @@ import {// covered by tests/tui_gateway/test_project_tree.py). This file only covers the// thin render helpers the desktop still owns + the VISUAL worktree enhancer.-let nextId = 0--function makeSession(cwd: null | string, overrides: Partial<SessionInfo> = {}): SessionInfo {- return {- archived: false,- cwd,- ended_at: null,- id: `s${nextId++}`,- input_tokens: 0,- is_active: false,- last_active: 1_000,- message_count: 1,- model: 'claude',- output_tokens: 0,- preview: null,- source: 'cli',- started_at: 1_000,- title: null,- tool_call_count: 0,- ...overrides- }-}-const lane = (over: Partial<SidebarSessionGroup> & Pick<SidebarSessionGroup, 'id' | 'label'>): SidebarSessionGroup => ({path: null,sessions: [],@@ -76,7 +54,7 @@ describe('kanbanWorktreeDir', () => {describe('sortWorktreeGroups', () => {it('pins trunk to the top, sinks kanban to the bottom, and orders the rest by recency', () => {- const at = (t: number) => [makeSession('/x', { last_active: t })]+ const at = (t: number) => [makeCwdSession('/x', { last_active: t })]const groups = [lane({ id: 'k', label: 'kanban', isKanban: true, sessions: at(999) }),@@ -92,7 +70,7 @@ describe('sortWorktreeGroups', () => {it('pins the live home checkout above trunk, even when it has no sessions yet', () => {const groups = [- lane({ id: 'main', label: 'main', isMain: true, sessions: [makeSession('/x', { last_active: 999 })] }),+ lane({ id: 'main', label: 'main', isMain: true, sessions: [makeCwdSession('/x', { last_active: 999 })] }),lane({ id: 'home', label: 'bb/projects-paradigm', isMain: true, isHome: true })]@@ -150,7 +128,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo')]+ sessions: [makeCwdSession('/repo')]})]}@@ -176,7 +154,13 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {it('does not add a second "main" for a linked worktree checked out on main', () => {const groups = [- lane({ id: '/repo::branch::main', label: 'main', isMain: true, path: '/repo', sessions: [makeSession('/repo')] })+ lane({+ id: '/repo::branch::main',+ label: 'main',+ isMain: true,+ path: '/repo',+ sessions: [makeCwdSession('/repo')]+ })]const discovered: HermesGitWorktree[] = [@@ -216,14 +200,14 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo')]+ sessions: [makeCwdSession('/repo')]}),lane({id: '/repo-ci',label: 'hermes-agent-ci',isMain: false,path: '/repo-ci',- sessions: [makeSession('/repo-ci')]+ sessions: [makeCwdSession('/repo-ci')]})]}@@ -256,7 +240,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'bb/attempts',isMain: false,path: '/repo/.worktrees/attempts',- sessions: [makeSession('/repo/.worktrees/attempts')]+ sessions: [makeCwdSession('/repo/.worktrees/attempts')]})]}@@ -291,7 +275,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'bb/feature',isMain: false,path: '/repo-feature',- sessions: [makeSession('/repo-feature'), makeSession('/repo-feature')]+ sessions: [makeCwdSession('/repo-feature'), makeCwdSession('/repo-feature')]})]}@@ -313,7 +297,13 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {id: '/repo',path: '/repo',groups: [- lane({ id: '/repo-ci', label: 'repo-ci', isMain: false, path: '/repo-ci', sessions: [makeSession('/repo-ci')] })+ lane({+ id: '/repo-ci',+ label: 'repo-ci',+ isMain: false,+ path: '/repo-ci',+ sessions: [makeCwdSession('/repo-ci')]+ })]}@@ -334,7 +324,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo')]+ sessions: [makeCwdSession('/repo')]})]}@@ -366,7 +356,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo')]+ sessions: [makeCwdSession('/repo')]})]}@@ -391,14 +381,14 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo', { id: 'a' })]+ sessions: [makeCwdSession('/repo', { id: 'a' })]}),lane({id: '/repo::branch::old',label: 'old-feature',isMain: true,path: '/repo',- sessions: [makeSession('/repo', { id: 'b' })]+ sessions: [makeCwdSession('/repo', { id: 'b' })]})]}@@ -425,7 +415,7 @@ describe('mergeRepoWorktreeGroups (visual enhancer)', () => {label: 'main',isMain: true,path: '/repo',- sessions: [makeSession('/repo')]+ sessions: [makeCwdSession('/repo')]})]}@@ -481,11 +471,11 @@ const homeNode = (sessions: SessionInfo[]): SidebarProjectTree =>describe('liveSessionProjectId', () => {it('maps a brand-new (unpersisted) session to its auto project (the repo root)', () => {- expect(liveSessionProjectId(makeSession('/www/app'), [])).toBe('/www/app')+ expect(liveSessionProjectId(makeCwdSession('/www/app'), [])).toBe('/www/app')})it('routes a session under an explicit project folder to that project', () => {- const id = liveSessionProjectId(makeSession('/www/app/src', { git_repo_root: '/www/app', git_branch: 'feat' }), [+ const id = liveSessionProjectId(makeCwdSession('/www/app/src', { git_repo_root: '/www/app', git_branch: 'feat' }), [makeProject('p_app', ['/www/app'])])@@ -495,31 +485,31 @@ describe('liveSessionProjectId', () => {it('anchors a cwd-less session on its git_repo_root (backend groups it there too)', () => {// Older/imported rows carry only a repo root; the sidebar files them under// the repo's project, so membership (and color) must resolve from the root.- expect(liveSessionProjectId(makeSession(null, { git_repo_root: '/www/app' }), [])).toBe('/www/app')+ expect(liveSessionProjectId(makeCwdSession(null, { git_repo_root: '/www/app' }), [])).toBe('/www/app')expect(- liveSessionProjectId(makeSession(null, { git_repo_root: '/www/app' }), [makeProject('p_app', ['/www/app'])])+ liveSessionProjectId(makeCwdSession(null, { git_repo_root: '/www/app' }), [makeProject('p_app', ['/www/app'])])).toBe('p_app')})it('skips cwd-less, kanban-task, and out-of-tree (sibling) worktree sessions', () => {- expect(liveSessionProjectId(makeSession(null), [])).toBeNull()+ expect(liveSessionProjectId(makeCwdSession(null), [])).toBeNull()// Kanban task worktree → folds into the kanban bucket, not a project preview.- expect(liveSessionProjectId(makeSession('/repo/.worktrees/t_aaaaaaaa'), [])).toBeNull()+ expect(liveSessionProjectId(makeCwdSession('/repo/.worktrees/t_aaaaaaaa'), [])).toBeNull()// Sibling worktree OUTSIDE the repo root → project can't be derived from the row.- expect(liveSessionProjectId(makeSession('/elsewhere/wt', { git_repo_root: '/repo' }), [])).toBeNull()+ expect(liveSessionProjectId(makeCwdSession('/elsewhere/wt', { git_repo_root: '/repo' }), [])).toBeNull()})it('places an in-tree worktree session under its repo project (the root is in the path)', () => {// "Convert a branch" / "new worktree" land at `<repoRoot>/.worktrees/<slug>`,// so they belong to the same auto project as the repo root and must show in// the overview at once, not wait for the next backend refresh.- expect(liveSessionProjectId(makeSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [])).toBe(+ expect(liveSessionProjectId(makeCwdSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [])).toBe('/www/app')})it('routes an in-tree worktree session to the owning explicit project', () => {- const id = liveSessionProjectId(makeSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [+ const id = liveSessionProjectId(makeCwdSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [makeProject('p_app', ['/www/app'])])@@ -532,13 +522,13 @@ describe('liveSessionProjectId', () => {// only the auto-project (repo root) fallback needs cwd-under-root// confidence. Match via the repo root...expect(- liveSessionProjectId(makeSession('/www/elsewhere', { git_repo_root: '/home/u/proj' }), [+ liveSessionProjectId(makeCwdSession('/www/elsewhere', { git_repo_root: '/home/u/proj' }), [makeProject('p_proj', ['/home/u/proj'])])).toBe('p_proj')// ...and via the cwd.expect(- liveSessionProjectId(makeSession('/www/elsewhere/sub', { git_repo_root: '/home/u/proj' }), [+ liveSessionProjectId(makeCwdSession('/www/elsewhere/sub', { git_repo_root: '/home/u/proj' }), [makeProject('p_www', ['/www/elsewhere'])])).toBe('p_www')@@ -547,13 +537,13 @@ describe('liveSessionProjectId', () => {it('matches a mixed-case/separator Windows cwd to its explicit project in the live overlay', () => {// The bug: a fresh Windows session drops into the overlay before the next// backend refresh; case-sensitive matching missed its project until then.- const id = liveSessionProjectId(makeSession('c:/work/notes/SUB'), [makeProject('p_notes', ['C:\\Work\\Notes'])])+ const id = liveSessionProjectId(makeCwdSession('c:/work/notes/SUB'), [makeProject('p_notes', ['C:\\Work\\Notes'])])expect(id).toBe('p_notes')})it('matches a root-relative WSL cwd (single backslash) case-insensitively', () => {- const id = liveSessionProjectId(makeSession('//wsl.localhost/Ubuntu/home/alice/PROJ'), [+ const id = liveSessionProjectId(makeCwdSession('//wsl.localhost/Ubuntu/home/alice/PROJ'), [makeProject('p_proj', ['\\wsl.localhost\\Ubuntu\\home\\alice\\proj'])])@@ -562,7 +552,7 @@ describe('liveSessionProjectId', () => {it('keeps POSIX cwd matching case-sensitive (no false project match)', () => {// Distinct case on POSIX is a distinct path → falls back to its own auto id.- expect(liveSessionProjectId(makeSession('/work/notes'), [makeProject('p_notes', ['/Work/Notes'])])).toBe(+ expect(liveSessionProjectId(makeCwdSession('/work/notes'), [makeProject('p_notes', ['/Work/Notes'])])).toBe('/work/notes')})@@ -575,19 +565,19 @@ describe('sessionProjectColor', () => {})it('inherits the color of the explicit project the session belongs to', () => {- const session = makeSession('/www/app/src', { git_repo_root: '/www/app' })+ const session = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })expect(sessionProjectColor(session, [colored('p_app', ['/www/app'], '#4a9eff')])).toBe('#4a9eff')})it('returns null when the owning project has no color set', () => {- const session = makeSession('/www/app/src', { git_repo_root: '/www/app' })+ const session = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })expect(sessionProjectColor(session, [makeProject('p_app', ['/www/app'])])).toBeNull()})it('colors a cwd-less session by its git_repo_root project (the grouped-but-grey fix)', () => {- const session = makeSession(null, { git_repo_root: '/www/app' })+ const session = makeCwdSession(null, { git_repo_root: '/www/app' })expect(sessionProjectColor(session, [colored('p_app', ['/www/app'], '#4a9eff')])).toBe('#4a9eff')})@@ -595,7 +585,7 @@ describe('sessionProjectColor', () => {it('colors a cwd-outside-root session when an explicit project folder matches', () => {// The backend tree groups such a row under the project; the client color// derivation must agree instead of leaving the row (and its tab) grey.- const session = makeSession('/www/elsewhere', { git_repo_root: '/home/u/proj' })+ const session = makeCwdSession('/www/elsewhere', { git_repo_root: '/home/u/proj' })expect(sessionProjectColor(session, [colored('p_proj', ['/home/u/proj'], '#4a9eff')])).toBe('#4a9eff')})@@ -603,15 +593,15 @@ describe('sessionProjectColor', () => {it('returns null for a session that only maps to an auto repo root (no explicit project)', () => {// liveSessionProjectId falls back to the repo root id, which is not a// project row and therefore carries no color.- expect(sessionProjectColor(makeSession('/www/app'), [])).toBeNull()+ expect(sessionProjectColor(makeCwdSession('/www/app'), [])).toBeNull()})it('returns null for an unplaceable (cwd-less) session', () => {- expect(sessionProjectColor(makeSession(null), [colored('p_app', ['/www/app'], '#4a9eff')])).toBeNull()+ expect(sessionProjectColor(makeCwdSession(null), [colored('p_app', ['/www/app'], '#4a9eff')])).toBeNull()})it('uses the longest-prefix project when nested projects both match', () => {- const session = makeSession('/www/app/packages/api/src', { git_repo_root: '/www/app' })+ const session = makeCwdSession('/www/app/packages/api/src', { git_repo_root: '/www/app' })const projects = [colored('p_root', ['/www/app'], '#111111'),@@ -630,7 +620,7 @@ describe('overlayLiveLanes', () => {repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]})- const live = [makeSession('/www/app', { id: 'fresh', git_branch: 'main' })]+ const live = [makeCwdSession('/www/app', { id: 'fresh', git_branch: 'main' })]const overlaid = overlayLiveLanes(project, live)const lane = overlaid.repos[0].groups.find(g => g.label === 'main')@@ -649,7 +639,7 @@ describe('overlayLiveLanes', () => {repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]})- const live = [makeSession('/www/app/.worktrees/baby', { id: 'fresh' })]+ const live = [makeCwdSession('/www/app/.worktrees/baby', { id: 'fresh' })]const overlaid = overlayLiveLanes(project, live)const lane = overlaid.repos[0].groups.find(g => g.id === '/www/app/.worktrees/baby')@@ -665,7 +655,7 @@ describe('overlayLiveLanes', () => {repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]})- const live = [makeSession('/www/app/.worktrees/t_abc12345', { id: 'k' })]+ const live = [makeCwdSession('/www/app/.worktrees/t_abc12345', { id: 'k' })]const overlaid = overlayLiveLanes(project, live)const lane = overlaid.repos[0].groups.find(g => g.isKanban)@@ -675,7 +665,7 @@ describe('overlayLiveLanes', () => {})it('does not duplicate a session already present in a backend lane', () => {- const existing = makeSession('/www/app', { id: 'dup', git_branch: 'main' })+ const existing = makeCwdSession('/www/app', { id: 'dup', git_branch: 'main' })const project = projectNode({id: '/www/app',@@ -704,8 +694,8 @@ describe('overlayLiveLanes', () => {// and CREATE a second main lane with the same sessions — dual lanes in the// project drill-in (e.g. main + codex-research-guardian).const root = '/home/hermes/hermes-workspace/codex-research-guardian'- const a = makeSession(root, { id: 's1' }) // empty git_branch / git_repo_root- const b = makeSession(root, { id: 's2' })+ const a = makeCwdSession(root, { id: 's1' }) // empty git_branch / git_repo_root+ const b = makeCwdSession(root, { id: 's2' })const project = projectNode({id: root,@@ -742,7 +732,7 @@ describe('overlayLiveLanes', () => {it('joins a fresh live session into an existing non-git workspace lane (no branch id)', () => {const root = '/work/notes'- const existing = makeSession(root, { id: 'old' })+ const existing = makeCwdSession(root, { id: 'old' })const project = projectNode({id: root,@@ -759,7 +749,7 @@ describe('overlayLiveLanes', () => {]})- const fresh = makeSession(root, { id: 'fresh' })+ const fresh = makeCwdSession(root, { id: 'fresh' })const overlaid = overlayLiveLanes(project, [existing, fresh])const groups = overlaid.repos[0].groups@@ -769,14 +759,14 @@ describe('overlayLiveLanes', () => {})it('preserves backend recency order when live sessions overlay a lane', () => {- const recentlyActive = makeSession('/www/app', {+ const recentlyActive = makeCwdSession('/www/app', {id: 'recently-active',git_branch: 'main',started_at: 1,last_active: 3})- const newlyCreated = makeSession('/www/app', {+ const newlyCreated = makeCwdSession('/www/app', {id: 'newly-created',git_branch: 'main',started_at: 2,@@ -816,7 +806,7 @@ describe('overlayLiveLanes', () => {// Backend keyed the worktree lane off a branch-style id (no live git probe),// but the lane PATH is the worktree dir. A new session under that worktree// must join the existing lane, not spawn a twin.- const existing = makeSession('/www/app/.worktrees/baby', { id: 'old' })+ const existing = makeCwdSession('/www/app/.worktrees/baby', { id: 'old' })const project = projectNode({id: '/www/app',@@ -838,7 +828,7 @@ describe('overlayLiveLanes', () => {]})- const fresh = makeSession('/www/app/.worktrees/baby', { id: 'fresh' })+ const fresh = makeCwdSession('/www/app/.worktrees/baby', { id: 'fresh' })const overlaid = overlayLiveLanes(project, [existing, fresh])const lanes = overlaid.repos[0].groups.filter(g => g.path === '/www/app/.worktrees/baby')@@ -850,7 +840,7 @@ describe('overlayLiveLanes', () => {it('places a session into an out-of-tree (sibling) worktree lane by its path', () => {// `hermes-agent-ci` is a linked worktree living BESIDE the repo, not under// it — repo-root nesting fails, but the existing lane carries its real path.- const existing = makeSession('/www/app-ci', { id: 'old' })+ const existing = makeCwdSession('/www/app-ci', { id: 'old' })const project = projectNode({id: '/www/app',@@ -868,7 +858,7 @@ describe('overlayLiveLanes', () => {]})- const fresh = makeSession('/www/app-ci', { id: 'fresh' })+ const fresh = makeCwdSession('/www/app-ci', { id: 'fresh' })const overlaid = overlayLiveLanes(project, [existing, fresh])const ci = overlaid.repos[0].groups.find(g => g.path === '/www/app-ci')@@ -890,7 +880,7 @@ describe('overlayLiveLanes', () => {repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups }]})- const fresh = makeSession('/www/app-retry', { id: 'fresh' })+ const fresh = makeCwdSession('/www/app-retry', { id: 'fresh' })const overlaid = overlayLiveLanes(project, [fresh])const lane = overlaid.repos[0].groups.find(g => g.path === '/www/app-retry')@@ -899,8 +889,8 @@ describe('overlayLiveLanes', () => {})it('evicts a deleted/archived snapshot row (and drops the lane once empty)', () => {- const a = makeSession('/www/app', { id: 'keep', git_branch: 'main' })- const b = makeSession('/www/app/.worktrees/baby', { id: 'gone' })+ const a = makeCwdSession('/www/app', { id: 'keep', git_branch: 'main' })+ const b = makeCwdSession('/www/app/.worktrees/baby', { id: 'gone' })const project = projectNode({id: '/www/app',@@ -927,11 +917,11 @@ describe('overlayLiveLanes', () => {})it('adds a brand-new detached chat to Home, and evicts a deleted one', () => {- const existing = makeSession(null, { id: 'old', started_at: 1 })- const doomed = makeSession(null, { id: 'gone', started_at: 2 })+ const existing = makeCwdSession(null, { id: 'old', started_at: 1 })+ const doomed = makeCwdSession(null, { id: 'gone', started_at: 2 })const home = homeNode([existing, doomed])- const overlaid = overlayLiveLanes(home, [makeSession(null, { id: 'fresh', started_at: 9 })], new Set(['gone']))+ const overlaid = overlayLiveLanes(home, [makeCwdSession(null, { id: 'fresh', started_at: 9 })], new Set(['gone']))expect(overlaid.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['fresh', 'old'])expect(overlaid.sessionCount).toBe(2)@@ -943,14 +933,14 @@ describe('overlayLiveLanes', () => {// and back out on the next snapshot.const home = homeNode([])- expect(overlayLiveLanes(home, [makeSession('/www/app', { id: 'fresh' })])).toBe(home)+ expect(overlayLiveLanes(home, [makeCwdSession('/www/app', { id: 'fresh' })])).toBe(home)})it('evicts a session from the main lane when the live overlay places it into a worktree lane', () => {// Session was in main when the backend tree was captured, but the live// $sessions cache now has it under a worktree cwd. The overlay must place// it ONLY in the worktree lane — not both.- const session = makeSession('/www/app/.worktrees/feature', { id: 'moved', git_branch: 'feature' })+ const session = makeCwdSession('/www/app/.worktrees/feature', { id: 'moved', git_branch: 'feature' })const project = projectNode({id: '/www/app',@@ -989,10 +979,10 @@ describe('overlayLivePreviews', () => {it('merges live sessions into a project preview, live first, capped to the limit', () => {const project = projectNode({id: '/www/app',- previewSessions: [makeSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })]+ previewSessions: [makeCwdSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })]})- const live = [makeSession('/www/app', { id: 'fresh', started_at: 99, last_active: 99 })]+ const live = [makeCwdSession('/www/app', { id: 'fresh', started_at: 99, last_active: 99 })]const previews = overlayLivePreviews([project], live, [], 3)@@ -1003,8 +993,8 @@ describe('overlayLivePreviews', () => {const project = projectNode({id: '/www/app',previewSessions: [- makeSession('/www/app', { id: 'gone', started_at: 5, last_active: 5 }),- makeSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })+ makeCwdSession('/www/app', { id: 'gone', started_at: 5, last_active: 5 }),+ makeCwdSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })]})@@ -1017,9 +1007,9 @@ describe('overlayLivePreviews', () => {const project = projectNode({id: '/www/app',previewSessions: [- makeSession('/www/app', { id: 'newest', last_active: 9, started_at: 9 }),- makeSession('/www/app', { id: 'cheap', last_active: 8, started_at: 8 }),- makeSession('/www/app', { id: 'priciest', last_active: 1, started_at: 1 })+ makeCwdSession('/www/app', { id: 'newest', last_active: 9, started_at: 9 }),+ makeCwdSession('/www/app', { id: 'cheap', last_active: 8, started_at: 8 }),+ makeCwdSession('/www/app', { id: 'priciest', last_active: 1, started_at: 1 })]})@@ -1029,7 +1019,7 @@ describe('overlayLivePreviews', () => {})it('previews a detached session under Home, which no cwd could place', () => {- const previews = overlayLivePreviews([homeNode([])], [makeSession(null, { id: 'fresh' })], [], 3)+ const previews = overlayLivePreviews([homeNode([])], [makeCwdSession(null, { id: 'fresh' })], [], 3)expect(previews[NO_PROJECT_ID].map(s => s.id)).toEqual(['fresh'])})@@ -1037,8 +1027,8 @@ describe('overlayLivePreviews', () => {describe('excludeProjectSessions', () => {it('drops matching rows from every lane and recounts the subtree', () => {- const keep = makeSession('/www/app', { id: 'keep' })- const pinnedRow = makeSession('/www/app', { id: 'pinned' })+ const keep = makeCwdSession('/www/app', { id: 'keep' })+ const pinnedRow = makeCwdSession('/www/app', { id: 'pinned' })const project = projectNode({id: '/www/app',@@ -1062,7 +1052,7 @@ describe('excludeProjectSessions', () => {})it('keeps a lane the filter emptied — a worktree is structure, not a row', () => {- const pinnedRow = makeSession('/www/app/wt', { id: 'pinned' })+ const pinnedRow = makeCwdSession('/www/app/wt', { id: 'pinned' })const project = projectNode({id: '/www/app',@@ -1090,7 +1080,7 @@ describe('excludeProjectSessions', () => {it('returns the same node when nothing matches (memo-stable)', () => {const project = projectNode({id: '/www/app',- previewSessions: [makeSession('/www/app', { id: 'keep' })],+ previewSessions: [makeCwdSession('/www/app', { id: 'keep' })],repos: [{id: '/www/app',@@ -1098,7 +1088,7 @@ describe('excludeProjectSessions', () => {path: '/www/app',sessionCount: 1,groups: [- lane({ id: 'main', isMain: true, label: 'main', sessions: [makeSession('/www/app', { id: 'keep' })] })+ lane({ id: 'main', isMain: true, label: 'main', sessions: [makeCwdSession('/www/app', { id: 'keep' })] })]}],@@ -1111,7 +1101,7 @@ describe('excludeProjectSessions', () => {it('survives the live overlay: a lane left empty by the filter is not pruned', () => {// The two run in sequence on an entered project (filter, then overlay), and// the overlay drops lanes it empties — it must not take the filter's with it.- const pinnedRow = makeSession('/www/app/wt', { id: 'pinned' })+ const pinnedRow = makeCwdSession('/www/app/wt', { id: 'pinned' })const project = projectNode({id: '/www/app',diff --git a/apps/desktop/src/app/command-palette/highlight-watcher.test.tsx b/apps/desktop/src/app/command-palette/highlight-watcher.test.tsxindex d2929fcc1e1..2e92a24678b 100644--- a/apps/desktop/src/app/command-palette/highlight-watcher.test.tsx+++ b/apps/desktop/src/app/command-palette/highlight-watcher.test.tsx@@ -9,18 +9,12 @@ import { render } from '@testing-library/react'import { Command } from 'cmdk'import { describe, expect, it, vi } from 'vitest'-import { HighlightWatcher } from './highlight-watcher'--// cmdk observes group headings with a ResizeObserver, which jsdom lacks.-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'-vi.stubGlobal('ResizeObserver', TestResizeObserver)+import { HighlightWatcher } from './highlight-watcher'-Element.prototype.scrollIntoView = function scrollIntoView() {}+stubResizeObserver()+stubMenuDomApis()const palette = (onValue: (value: string) => void, onRootValueChange?: (value: string) => void) => (<Command onValueChange={onRootValueChange}>diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsxindex 6a6e47397af..5dd54083cff 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx@@ -6,6 +6,8 @@ import { _resetLegacyDiscardForTests } from '@/store/session'import type * as WindowsStore from '@/store/windows'import type { SessionInfo } from '@/types/hermes'+import { makeSessionInfo } from '../../../test/session-info'+import { useDesktopIntegrations } from './use-desktop-integrations'// Mutable HUD-window flag so the restore tests can flip the window kind the@@ -36,24 +38,7 @@ vi.mock('@/store/windows', async importOriginal => {const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }const initialHermesDesktop = desktopWindow.hermesDesktop-const session = (over: Partial<SessionInfo> = {}): SessionInfo => ({- archived: false,- cwd: null,- ended_at: null,- id: 'live',- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 0,- model: null,- output_tokens: 0,- preview: null,- source: null,- started_at: 0,- title: null,- tool_call_count: 0,- ...over-})+const session = (over: Partial<SessionInfo> = {}): SessionInfo => makeSessionInfo({ id: 'live', ...over })describe('useDesktopIntegrations', () => {let navigate: ReturnType<typeof vi.fn<(...args: unknown[]) => void>>diff --git a/apps/desktop/src/app/cron/cron-actions.test.ts b/apps/desktop/src/app/cron/cron-actions.test.tsindex d79246a69a4..f7cbe89755e 100644--- a/apps/desktop/src/app/cron/cron-actions.test.ts+++ b/apps/desktop/src/app/cron/cron-actions.test.ts@@ -12,17 +12,9 @@ vi.mock('@/hermes', () => ({import { beginCronJobsRequest } from '@/store/cron'-import { mutateAndRefreshCronJobs, refreshCronJobs, triggerAndRefreshCronJobs } from './cron-actions'--function deferred<T>() {- let resolve!: (value: T) => void+import { deferred } from '../../test/deferred'- const promise = new Promise<T>(res => {- resolve = res- })-- return { promise, resolve }-}+import { mutateAndRefreshCronJobs, refreshCronJobs, triggerAndRefreshCronJobs } from './cron-actions'describe('triggerAndRefreshCronJobs', () => {beforeEach(() => {diff --git a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsxindex a9c013301b2..5cf40b6ee64 100644--- a/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx+++ b/apps/desktop/src/app/right-sidebar/terminal/persistent.test.tsx@@ -1,10 +1,11 @@-import { act, type ReactNode } from 'react'-import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { hiddenPaneProps, PANE_HIDDEN_ATTR } from '@/components/pane-shell/pane-visibility'import { $paneStates } from '@/store/panes'+import { reactRoot } from '@/test/react-root'+import { installWindowStateBridge, setDocumentHidden, type WindowStateBridge } from '../../../test/window-state'import { $terminalTakeover } from '../store'import { PersistentTerminal, TerminalSlot } from './persistent'@@ -24,54 +25,8 @@ vi.mock('./workspace', () => ({let resizeObserverCallback: ResizeObserverCallback | null = nulllet mutationObserverCallback: MutationCallback | null = nulllet mutationObserveCalls: Array<{ options?: MutationObserverInit; target: Node }> = []-let root: Root | null = null-let container: HTMLDivElement | null = null-let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null--function render(ui: ReactNode) {- container = document.createElement('div')- document.body.append(container)- root = createRoot(container)-- act(() => {- root!.render(ui)- })-}--function cleanup() {- if (root) {- act(() => {- root!.unmount()- })- }-- container?.remove()- root = null- container = null-}--function setVisibility(hidden: boolean) {- Object.defineProperty(document, 'hidden', { configurable: true, value: hidden })- Object.defineProperty(document, 'visibilityState', { configurable: true, value: hidden ? 'hidden' : 'visible' })-}--function installWindowStateBridge() {- windowStateCallback = null- Object.defineProperty(window, 'hermesDesktop', {- configurable: true,- value: {- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {- windowStateCallback = callback-- return () => {- if (windowStateCallback === callback) {- windowStateCallback = null- }- }- })- }- })-}+const mount = reactRoot()+let windowState: WindowStateBridgefunction rect(top: number, left: number, width: number, height: number): DOMRect {return {@@ -146,9 +101,9 @@ function HiddenPaneHarness({ hidden }: { hidden: boolean }) {describe('PersistentTerminal rect tracking', () => {beforeEach(() => {;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true- setVisibility(false)+ setDocumentHidden(false)vi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()resizeObserverCallback = nullmutationObserverCallback = nullmutationObserveCalls = []@@ -181,11 +136,11 @@ describe('PersistentTerminal rect tracking', () => {})afterEach(() => {- cleanup()+ mount.unmount()$terminalTakeover.set(false)vi.unstubAllGlobals()vi.restoreAllMocks()- setVisibility(false)+ setDocumentHidden(false)delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})@@ -194,7 +149,7 @@ describe('PersistentTerminal rect tracking', () => {let currentRect = rect(10, 20, 200, 100)vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(() => currentRect)- render(<Harness />)+ mount.render(<Harness />)expect(raf.request).toHaveBeenCalledTimes(1)@@ -231,7 +186,7 @@ describe('PersistentTerminal rect tracking', () => {let currentRect = rect(10, 20, 200, 100)vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(() => currentRect)- render(<Harness />)+ mount.render(<Harness />)expect(mutationObserveCalls.length).toBeGreaterThan(0)expect(mutationObserveCalls.every(call => call.options?.subtree === false)).toBe(true)@@ -240,7 +195,7 @@ describe('PersistentTerminal rect tracking', () => {raf.runNext()})- const overlay = container!.lastElementChild as HTMLElement+ const overlay = mount.container!.lastElementChild as HTMLElementexpect(overlay.style.top).toBe('10px')expect(overlay.style.left).toBe('20px')expect(raf.pending()).toBe(0)@@ -271,7 +226,7 @@ describe('PersistentTerminal rect tracking', () => {const before = $paneStates.get()vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))- render(<Harness />)+ mount.render(<Harness />)raf.runNext()expect(raf.pending()).toBe(0)@@ -291,12 +246,12 @@ describe('PersistentTerminal rect tracking', () => {const raf = installRaf()vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))- render(<Harness />)+ mount.render(<Harness />)expect(raf.request).toHaveBeenCalledTimes(1)act(() => {- windowStateCallback?.({ isMinimized: true, isVisible: false })+ windowState.emit({ isMinimized: true, isVisible: false })})expect(raf.cancel).toHaveBeenCalledTimes(1)@@ -309,7 +264,7 @@ describe('PersistentTerminal rect tracking', () => {expect(raf.request).toHaveBeenCalledTimes(1)act(() => {- windowStateCallback?.({ isMinimized: false, isVisible: true })+ windowState.emit({ isMinimized: false, isVisible: true })})expect(raf.request).toHaveBeenCalledTimes(2)@@ -319,7 +274,7 @@ describe('PersistentTerminal rect tracking', () => {const raf = installRaf()vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))- render(<Harness />)+ mount.render(<Harness />)expect(raf.pending()).toBe(1)act(() => window.dispatchEvent(new Event('blur')))@@ -328,7 +283,7 @@ describe('PersistentTerminal rect tracking', () => {act(() => window.dispatchEvent(new Event('focus')))expect(raf.pending()).toBe(1)- cleanup()+ mount.unmount()expect(raf.pending()).toBe(0)act(() => {@@ -344,7 +299,7 @@ describe('PersistentTerminal rect tracking', () => {vi.mocked(document.hasFocus).mockReturnValue(false)vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))- render(<Harness />)+ mount.render(<Harness />)expect(raf.request).not.toHaveBeenCalled()@@ -358,10 +313,10 @@ describe('PersistentTerminal rect tracking', () => {vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect(10, 20, 200, 100))$terminalTakeover.set(true)- render(<HiddenPaneHarness hidden={false} />)+ mount.render(<HiddenPaneHarness hidden={false} />)- const overlay = container!.lastElementChild as HTMLElement- const workspace = container!.querySelector('[data-testid="terminal-workspace"]')+ const overlay = mount.container!.lastElementChild as HTMLElement+ const workspace = mount.container!.querySelector('[data-testid="terminal-workspace"]')expect(overlay.style.visibility).toBe('visible')expect(overlay.style.opacity).toBe('1')@@ -377,7 +332,7 @@ describe('PersistentTerminal rect tracking', () => {expect(raf.pending()).toBe(0)act(() => {- root!.render(<HiddenPaneHarness hidden />)+ mount.root!.render(<HiddenPaneHarness hidden />)mutationObserverCallback?.([], {} as MutationObserver)})expect(raf.pending()).toBe(1)@@ -389,7 +344,7 @@ describe('PersistentTerminal rect tracking', () => {expect(overlay.style.visibility).toBe('hidden')expect(overlay.style.opacity).toBe('0')expect(overlay.style.pointerEvents).toBe('none')- expect(container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)+ expect(mount.container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)act(() => {raf.runNext()@@ -397,7 +352,7 @@ describe('PersistentTerminal rect tracking', () => {expect(raf.pending()).toBe(0)act(() => {- root!.render(<HiddenPaneHarness hidden={false} />)+ mount.root!.render(<HiddenPaneHarness hidden={false} />)mutationObserverCallback?.([], {} as MutationObserver)})@@ -408,6 +363,6 @@ describe('PersistentTerminal rect tracking', () => {expect(overlay.style.visibility).toBe('visible')expect(overlay.style.opacity).toBe('1')expect(overlay.style.pointerEvents).toBe('auto')- expect(container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)+ expect(mount.container!.querySelector('[data-testid="terminal-workspace"]')).toBe(workspace)})})diff --git a/apps/desktop/src/app/session/hooks/use-cwd-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-cwd-actions.test.tsxindex 213c5d2054d..964fe142f89 100644--- a/apps/desktop/src/app/session/hooks/use-cwd-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-cwd-actions.test.tsx@@ -13,20 +13,12 @@ import {setNewChatWorkspaceTarget} from '@/store/session'+import { deferred } from '../../../test/deferred'+import { useCwdActions } from './use-cwd-actions'type CwdActionsHandle = ReturnType<typeof useCwdActions>-function deferred<T>() {- let resolve!: (value: T) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}-function Harness({activeSessionIdRef,onReady,diff --git a/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts b/apps/desktop/src/app/session/hooks/use-hermes-config.test.tsindex ca0ca4dc0a4..9003ad34914 100644--- a/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.test.ts@@ -18,6 +18,8 @@ import {setDefaultReasoningEffort} from '@/store/session'+import { deferred } from '../../../test/deferred'+import { useHermesConfig } from './use-hermes-config'vi.mock('@/hermes', () => ({@@ -27,16 +29,6 @@ vi.mock('@/hermes', () => ({const WORKSPACE_CWD_KEY = 'hermes.desktop.workspace-cwd'-function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}-const mockConfig = (config: Record<string, unknown>) =>vi.mocked(getHermesConfig).mockResolvedValue(config as Awaited<ReturnType<typeof getHermesConfig>>)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/agent-init-error.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/agent-init-error.test.tsxindex 86875e42f3f..3be0467bd8b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/agent-init-error.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/agent-init-error.test.tsx@@ -1,59 +1,24 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'import { textPart } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { $notifications, clearNotifications } from '@/store/notifications'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'rt-new-session'-let handleEvent: ((event: RpcEvent) => void) | null = null-let sessionStates: Map<string, ClientSessionState> | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- sessionStates = sessionStateByRuntimeIdRef.current- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarness-async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}/** Seed the session as it looks right after a first-message submit: the* optimistic user row is present, the turn is awaiting its response. */function seedOptimisticFirstMessage() {- sessionStates!.set(SID, {+ stream.states.set(SID, {...createClientSessionState('stored-new-session', [{ id: 'user-123-abc', role: 'user', parts: [textPart('first message of a new chat')] }]),@@ -64,8 +29,6 @@ function seedOptimisticFirstMessage() {describe('useMessageStream agent-init error surfacing (#63078)', () => {beforeEach(() => {- handleEvent = null- sessionStates = nullclearNotifications()})@@ -76,11 +39,11 @@ describe('useMessageStream agent-init error surfacing (#63078)', () => {})it('renders an agent-init failure as a visible in-transcript error and keeps the optimistic first message', async () => {- await mountStream()+ mountStream()seedOptimisticFirstMessage()act(() =>- handleEvent!({+ stream.handleEvent({payload: {message:'agent initialization timed out after 601s — your message was not sent; retry once the session is ready'@@ -90,7 +53,7 @@ describe('useMessageStream agent-init error surfacing (#63078)', () => {}))- const state = sessionStates!.get(SID)!+ const state = stream.state()// The user's optimistic first message must survive — the failure mode of// #63078 was the message silently vanishing into a blank session.@@ -111,19 +74,19 @@ describe('useMessageStream agent-init error surfacing (#63078)', () => {expect($notifications.get().some(n => n.kind === 'error' && n.message?.includes('was not sent'))).toBe(true)})- it('renders the pre-ready cancel error event (#65567 server emit) visibly', async () => {- await mountStream()+ it('renders the pre-ready cancel error event (#65567 server emit) visibly', () => {+ mountStream()seedOptimisticFirstMessage()act(() =>- handleEvent!({+ stream.handleEvent({payload: { message: 'Turn cancelled before the agent was ready' },session_id: SID,type: 'error'}))- const state = sessionStates!.get(SID)!+ const state = stream.state()expect(state.messages.some(m => m.role === 'assistant' && m.error?.includes('cancelled'))).toBe(true)expect(state.messages.some(m => m.id === 'user-123-abc')).toBe(true)expect(state.busy).toBe(false)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/approval-mode-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/approval-mode-event.test.tsxindex a8d7fdb5513..fcd5126104d 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/approval-mode-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/approval-mode-event.test.tsx@@ -1,55 +1,20 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import { $approvalModes, approvalModeForProfile } from '@/store/approval-mode'import { $activeGatewayProfile } from '@/store/profile'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const ACTIVE_SID = 'session-active'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarness-function Harness() {- const activeSessionIdRef = useRef<string | null>(ACTIVE_SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(ACTIVE_SID)}describe('live session.info approval mode reconciliation', () => {beforeEach(() => {- handleEvent = null$approvalModes.set({})$activeGatewayProfile.set('work')})@@ -59,11 +24,11 @@ describe('live session.info approval mode reconciliation', () => {vi.restoreAllMocks()})- it('reconciles an active-session event under its source gateway profile', async () => {- await mountStream()+ it('reconciles an active-session event under its source gateway profile', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { approval_mode: 'off' },profile: 'work',session_id: ACTIVE_SID,@@ -75,11 +40,11 @@ describe('live session.info approval mode reconciliation', () => {expect(approvalModeForProfile('default')).toBe('smart')})- it('ignores stale session.info from a non-active session on the active gateway', async () => {- await mountStream()+ it('ignores stale session.info from a non-active session on the active gateway', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { approval_mode: 'off' },profile: 'work',session_id: 'session-stale',@@ -90,11 +55,11 @@ describe('live session.info approval mode reconciliation', () => {expect(approvalModeForProfile('work')).toBe('smart')})- it('does not cache an event under a different active profile when its source profile is absent', async () => {- await mountStream()+ it('does not cache an event under a different active profile when its source profile is absent', () => {+ mountStream()$activeGatewayProfile.set('personal')- act(() => handleEvent!({ payload: { approval_mode: 'off' }, session_id: ACTIVE_SID, type: 'session.info' }))+ act(() => stream.handleEvent({ payload: { approval_mode: 'off' }, session_id: ACTIVE_SID, type: 'session.info' }))expect(approvalModeForProfile('personal')).toBe('smart')expect(approvalModeForProfile('work')).toBe('smart')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsxindex b64171cc7ec..8f2fe2defcd 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/clarify-hydration.test.tsx@@ -1,15 +1,10 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { type MutableRefObject, useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import { $clarifyRequests, clearClarifyRequest } from '@/store/clarify'import { onScrollToBottomRequest } from '@/store/thread-scroll'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'// A `clarify.request` must leave an answerable inline row even when the// `tool.start` that normally mounts it was missed (stream reconnect /@@ -18,62 +13,29 @@ import { useMessageStream } from './index'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null-let stateRef: MutableRefObject<Map<string, ClientSessionState>> | null = null+let stream: MessageStreamHarnesslet stopScrollListener: (() => void) | null = nullconst scrollToBottom = vi.fn()-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- stateRef = sessionStateByRuntimeIdRef- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}const clarifyRequest = (payload: Record<string, unknown>) =>- act(() => handleEvent!({ payload, session_id: SID, type: 'clarify.request' }))+ act(() => stream.handleEvent({ payload, session_id: SID, type: 'clarify.request' }))const toolStart = (payload: Record<string, unknown>) =>- act(() => handleEvent!({ payload, session_id: SID, type: 'tool.start' }))+ act(() => stream.handleEvent({ payload, session_id: SID, type: 'tool.start' }))function clarifyParts() {- const messages = stateRef?.current.get(SID)?.messages ?? []+ const messages = stream.state().messages ?? []return messages.flatMap(m => m.parts).filter(p => p.type === 'tool-call' && p.toolName === 'clarify')}describe('clarify.request stream hydration', () => {beforeEach(() => {- handleEvent = null- stateRef = nullclearClarifyRequest()scrollToBottom.mockClear()stopScrollListener = onScrollToBottomRequest(scrollToBottom)@@ -87,8 +49,8 @@ describe('clarify.request stream hydration', () => {vi.restoreAllMocks()})- it('mounts an answerable clarify row when the tool.start row was missed', async () => {- await mountStream()+ it('mounts an answerable clarify row when the tool.start row was missed', () => {+ mountStream()clarifyRequest({ choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-1' })@@ -101,19 +63,19 @@ describe('clarify.request stream hydration', () => {})})- it('reveals a clarify prompt raised by the active session', async () => {- await mountStream()+ it('reveals a clarify prompt raised by the active session', () => {+ mountStream()clarifyRequest({ choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-reveal' })expect(scrollToBottom).toHaveBeenCalledOnce()})- it('does not move the active thread for a background session clarify', async () => {- await mountStream()+ it('does not move the active thread for a background session clarify', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { choices: ['yes', 'no'], question: 'Ship it?', request_id: 'req-background' },session_id: 'session-background',type: 'clarify.request'@@ -123,8 +85,8 @@ describe('clarify.request stream hydration', () => {expect(scrollToBottom).not.toHaveBeenCalled()})- it('preserves multi-select through the store and hydrated tool row', async () => {- await mountStream()+ it('preserves multi-select through the store and hydrated tool row', () => {+ mountStream()clarifyRequest({choices: ['read', 'write'],@@ -149,8 +111,8 @@ describe('clarify.request stream hydration', () => {})})- it('merges with the real tool.start row even though its id differs from the request id', async () => {- await mountStream()+ it('merges with the real tool.start row even though its id differs from the request id', () => {+ mountStream()// Reality: tool.start carries the model's tool_call_id, clarify.request a// separately-generated request_id. They must still collapse to ONE card@@ -161,8 +123,8 @@ describe('clarify.request stream hydration', () => {expect(clarifyParts()).toHaveLength(1)})- it('does not duplicate when clarify.request arrives before the tool.start row', async () => {- await mountStream()+ it('does not duplicate when clarify.request arrives before the tool.start row', () => {+ mountStream()clarifyRequest({ choices: ['a'], question: 'Pick', request_id: 'req-3' })toolStart({ args: { choices: ['a'], question: 'Pick' }, name: 'clarify', tool_id: 'call-xyz' })@@ -170,8 +132,8 @@ describe('clarify.request stream hydration', () => {expect(clarifyParts()).toHaveLength(1)})- it('merges a BATCH tool.start row with its clarify.request (no top-level question)', async () => {- await mountStream()+ it('merges a BATCH tool.start row with its clarify.request (no top-level question)', () => {+ mountStream()// The batch shape: tool args carry `questions`, no top-level `question`.// The correlation key must come from the question list, or the two ids@@ -190,10 +152,11 @@ describe('clarify.request stream hydration', () => {})expect(clarifyParts()).toHaveLength(1)+ expect($clarifyRequests.get()[SID]?.questions).toHaveLength(2)})- it('does not duplicate when the batch clarify.request arrives before tool.start', async () => {- await mountStream()+ it('does not duplicate when the batch clarify.request arrives before tool.start', () => {+ mountStream()clarifyRequest({questions: [@@ -209,5 +172,6 @@ describe('clarify.request stream hydration', () => {})expect(clarifyParts()).toHaveLength(1)+ expect($clarifyRequests.get()[SID]?.questions).toHaveLength(2)})})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/compaction-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/compaction-event.test.tsxindex 9fcabadcd1e..0343dd37e32 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/compaction-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/compaction-event.test.tsx@@ -1,59 +1,25 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import { $compactingSessions, setSessionCompacting } from '@/store/compaction'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'const OTHER_SID = 'session-2'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarness-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}) {- act(() => handleEvent!({ payload, session_id: SID, type }))+ act(() => stream.handleEvent({ payload, session_id: SID, type }))}describe('useMessageStream compaction lifecycle', () => {beforeEach(() => {- handleEvent = null$compactingSessions.set({})})@@ -68,8 +34,8 @@ describe('useMessageStream compaction lifecycle', () => {['thinking.delta', { text: 'still working' }],['reasoning.delta', { text: 'thinking again' }],['tool.start', { name: 'terminal', tool_id: 'tool-1' }]- ] as const)('clears the stale compaction phase when %s resumes the turn', async (type, payload) => {- await mountStream()+ ] as const)('clears the stale compaction phase when %s resumes the turn', (type, payload) => {+ mountStream()setSessionCompacting(OTHER_SID, true)emit('status.update', { kind: 'compacting' })@@ -80,8 +46,8 @@ describe('useMessageStream compaction lifecycle', () => {expect($compactingSessions.get()).toEqual({ [OTHER_SID]: true })})- it('clears the compaction phase on the structured completion edge', async () => {- await mountStream()+ it('clears the compaction phase on the structured completion edge', () => {+ mountStream()setSessionCompacting(OTHER_SID, true)emit('status.update', { kind: 'compacting' })diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/composer-model-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/composer-model-event.test.tsxindex 7d8e4f69aa2..245b168a4e0 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/composer-model-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/composer-model-event.test.tsx@@ -1,10 +1,6 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import {$currentModel,$currentProvider,@@ -12,50 +8,17 @@ import {setCurrentModelSource,setCurrentProvider} from '@/store/session'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarness-function Harness({ activeSessionId }: { activeSessionId: string | null }) {- const sessionIdRef = useRef<string | null>(activeSessionId)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- sessionIdRef.current = activeSessionId-- const stream = useMessageStream({- activeSessionIdRef: sessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream(activeSessionId: string | null) {- render(<Harness activeSessionId={activeSessionId} />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream(activeSessionId: string | null) {+ stream = renderMessageStream(activeSessionId)}describe('session.info does not clobber composer model selection', () => {beforeEach(() => {- handleEvent = nullsetCurrentModel('deepseek-v4-flash')setCurrentProvider('deepseek')setCurrentModelSource('manual')@@ -69,11 +32,11 @@ describe('session.info does not clobber composer model selection', () => {setCurrentModelSource('')})- it('keeps a sticky manual pick when a global session.info carries the profile default', async () => {- await mountStream(null)+ it('keeps a sticky manual pick when a global session.info carries the profile default', () => {+ mountStream(null)act(() =>- handleEvent!({+ stream.handleEvent({payload: { model: 'deepseek-chat', provider: 'deepseek' },type: 'session.info'})@@ -83,11 +46,11 @@ describe('session.info does not clobber composer model selection', () => {expect($currentProvider.get()).toBe('deepseek')})- it('keeps the composer pick when an unscoped session.info arrives with no live session', async () => {- await mountStream(null)+ it('keeps the composer pick when an unscoped session.info arrives with no live session', () => {+ mountStream(null)act(() =>- handleEvent!({+ stream.handleEvent({payload: { cwd: '/tmp/project', model: 'deepseek-chat', provider: 'deepseek' },type: 'session.info'})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/delta-flush.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/delta-flush.test.tsxindex a630d9dcf32..73d2c7e65dc 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/delta-flush.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/delta-flush.test.tsx@@ -9,10 +9,12 @@ import { createClientSessionState } from '@/lib/chat-runtime'import { useSessionStateCache } from '../use-session-state-cache'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'+import { useMessageStream } from './index'const SID = 'session-1'-let appendAssistantDelta: ((sessionId: string, delta: string) => void) | null = null+let stream: MessageStreamHarnesslet states: Map<string, ClientSessionState>type UpdateSessionState = (sessionId: string,@@ -21,44 +23,17 @@ type UpdateSessionState = () => ClientSessionStatelet updateSessionState: ReturnType<typeof vi.fn<UpdateSessionState>>-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(states)- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState- })-- useEffect(() => {- appendAssistantDelta = stream.appendAssistantDelta- }, [stream.appendAssistantDelta])-- return null-}-+/** The shared harness, but writing through a spy so the unmount test can count+ * the writes that happen after teardown. */function mountStream() {- render(<Harness />)- expect(appendAssistantDelta).not.toBeNull()+ stream = renderMessageStream(SID, { states, updateSessionState })}-function assistantText() {- const message = states.get(SID)?.messages.at(-1)- const part = message?.parts.at(-1)-- return part?.type === 'text' ? part.text : ''-}+const assistantText = () => stream.text()describe('useMessageStream delta flush scheduling', () => {beforeEach(() => {vi.useFakeTimers()- appendAssistantDelta = nullstates = new Map()updateSessionState = vi.fn((sessionId: string, updater: (state: ClientSessionState) => ClientSessionState) => {const next = updater(states.get(sessionId) ?? createClientSessionState())@@ -81,7 +56,7 @@ describe('useMessageStream delta flush scheduling', () => {it('flushes streaming text on a bounded timer while the window is unfocused', async () => {mountStream()- act(() => appendAssistantDelta!(SID, 'still streaming'))+ act(() => stream.appendDelta(SID, 'still streaming'))expect(window.requestAnimationFrame).not.toHaveBeenCalled()expect(assistantText()).toBe('')@@ -97,7 +72,7 @@ describe('useMessageStream delta flush scheduling', () => {vi.mocked(performance.now).mockReturnValue(0)mountStream()- act(() => appendAssistantDelta!(SID, 'caught up on focus'))+ act(() => stream.appendDelta(SID, 'caught up on focus'))expect(assistantText()).toBe('')expect(vi.getTimerCount()).toBe(1)@@ -120,7 +95,7 @@ describe('useMessageStream delta flush scheduling', () => {})mountStream()- act(() => appendAssistantDelta!(SID, 'focused without visibility change'))+ act(() => stream.appendDelta(SID, 'focused without visibility change'))expect(assistantText()).toBe('')expect(vi.getTimerCount()).toBe(1)@@ -133,7 +108,7 @@ describe('useMessageStream delta flush scheduling', () => {vi.mocked(performance.now).mockReturnValue(0)mountStream()- act(() => appendAssistantDelta!(SID, 'final delta'))+ act(() => stream.appendDelta(SID, 'final delta'))expect(vi.getTimerCount()).toBe(1)cleanup()@@ -164,7 +139,7 @@ describe('useMessageStream delta flush scheduling', () => {mountStream()- act(() => appendAssistantDelta!(SID, 'first'))+ act(() => stream.appendDelta(SID, 'first'))await act(async () => {await vi.advanceTimersByTimeAsync(0)})@@ -177,7 +152,7 @@ describe('useMessageStream delta flush scheduling', () => {now = 1100act(() => rafCallbacks[0](1040))- act(() => appendAssistantDelta!(SID, 'second'))+ act(() => stream.appendDelta(SID, 'second'))await act(async () => {await vi.advanceTimersByTimeAsync(79)})@@ -201,7 +176,7 @@ describe('useMessageStream delta flush scheduling', () => {mountStream()- act(() => appendAssistantDelta!(SID, 'first'))+ act(() => stream.appendDelta(SID, 'first'))await act(async () => {await vi.advanceTimersByTimeAsync(0)})@@ -210,7 +185,7 @@ describe('useMessageStream delta flush scheduling', () => {// 100ms later (well past the 33ms floor): the next flush is immediate.now = 1100- act(() => appendAssistantDelta!(SID, 'second'))+ act(() => stream.appendDelta(SID, 'second'))await act(async () => {await vi.advanceTimersByTimeAsync(0)})@@ -230,14 +205,14 @@ describe('useMessageStream delta flush scheduling', () => {mountStream()- act(() => appendAssistantDelta!(SID, 'a'))+ act(() => stream.appendDelta(SID, 'a'))await act(async () => {await vi.advanceTimersByTimeAsync(0)})// A second flush starts before the first flush's frame lands.now = 1010- act(() => appendAssistantDelta!(SID, 'b'))+ act(() => stream.appendDelta(SID, 'b'))await act(async () => {await vi.advanceTimersByTimeAsync(23)})@@ -250,7 +225,7 @@ describe('useMessageStream delta flush scheduling', () => {now = 1030act(() => rafCallbacks[0](1000))- act(() => appendAssistantDelta!(SID, 'c'))+ act(() => stream.appendDelta(SID, 'c'))await act(async () => {await vi.advanceTimersByTimeAsync(13)})@@ -267,6 +242,7 @@ describe('useMessageStream composed with the real useSessionStateCache', () => {// measured frame cost includes the deferred $messages commit it adapts to.let cache: ReturnType<typeof useSessionStateCache> | null = nulllet published: ChatMessage[]+ let appendAssistantDelta: ((sessionId: string, delta: string) => void) | null = nullfunction ComposedHarness() {const busyRef: MutableRefObject<boolean> = { current: false }diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/interim-sealing.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/interim-sealing.test.tsxindex 0aa549ec50f..1f84dc0e7f6 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/interim-sealing.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/interim-sealing.test.tsx@@ -1,72 +1,41 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'import { chatMessageText } from '@/lib/chat-messages'-import { createClientSessionState } from '@/lib/chat-runtime'import { clearSessionTodos } from '@/store/todos'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null-let sessionStates: Map<string, ClientSessionState>+let stream: MessageStreamHarnesslet mockCompleteSound: ReturnType<typeof vi.fn>let mockHaptic: ReturnType<typeof vi.fn>-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)- sessionStates.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null+function mountStream() {+ stream = renderMessageStream(SID)}-async function mountStream() {- sessionStates = new Map()- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())-}+const start = () => act(() => stream.handleEvent({ payload: {}, session_id: SID, type: 'message.start' }))-const start = () => act(() => handleEvent!({ payload: {}, session_id: SID, type: 'message.start' }))-const delta = (text: string) => act(() => handleEvent!({ payload: { text }, session_id: SID, type: 'message.delta' }))+const delta = (text: string) =>+ act(() => stream.handleEvent({ payload: { text }, session_id: SID, type: 'message.delta' }))const interim = (text: string) =>- act(() => handleEvent!({ payload: { text, already_streamed: true }, session_id: SID, type: 'message.interim' }))+ act(() => stream.handleEvent({ payload: { text, already_streamed: true }, session_id: SID, type: 'message.interim' }))const complete = (text: string) =>- act(() => handleEvent!({ payload: { text }, session_id: SID, type: 'message.complete' }))+ act(() => stream.handleEvent({ payload: { text }, session_id: SID, type: 'message.complete' }))const completePreviewed = (text: string) =>- act(() => handleEvent!({ payload: { text, response_previewed: true }, session_id: SID, type: 'message.complete' }))+ act(() =>+ stream.handleEvent({ payload: { text, response_previewed: true }, session_id: SID, type: 'message.complete' })+ )function getState(): ClientSessionState {- return sessionStates.get(SID) ?? createClientSessionState()+ return stream.state()}function assistantText(): string {@@ -87,7 +56,6 @@ function assistantMessages(): string[] {describe('useMessageStream interim text sealing', () => {beforeEach(() => {- handleEvent = nullclearSessionTodos(SID)})@@ -98,7 +66,7 @@ describe('useMessageStream interim text sealing', () => {})it('preserves interim text that the final response does not include', async () => {- await mountStream()+ mountStream()await start()await delta('awaaaaa clean!! tsc zero errors')@@ -112,7 +80,7 @@ describe('useMessageStream interim text sealing', () => {})it('marks sealed interim bubbles interim and leaves the final reply unmarked', async () => {- await mountStream()+ mountStream()await start()await delta('Let me check the files.')@@ -130,7 +98,7 @@ describe('useMessageStream interim text sealing', () => {})it('clears the interim mark when a previewed final settles onto the interim bubble', async () => {- await mountStream()+ mountStream()await start()await interim('same reply')@@ -142,7 +110,7 @@ describe('useMessageStream interim text sealing', () => {})it('dedupes interim text when the final response includes it', async () => {- await mountStream()+ mountStream()await start()await delta('Let me check the files.')@@ -156,7 +124,7 @@ describe('useMessageStream interim text sealing', () => {})it('clears interimBoundaryPending at turn end so the next turn starts clean', async () => {- await mountStream()+ mountStream()await start()await delta('interim text')@@ -175,7 +143,7 @@ describe('useMessageStream interim text sealing', () => {})it('finalizes an interim segment without settling the turn', async () => {- await mountStream()+ mountStream()await start()await delta('streaming text')@@ -187,7 +155,7 @@ describe('useMessageStream interim text sealing', () => {})it('settles an identical final onto a non-previewed interim (tool-call turn) instead of duplicating (#63679)', async () => {- await mountStream()+ mountStream()await start()// A plain tool-call turn: the streamed text is sealed as an interim at the@@ -203,7 +171,7 @@ describe('useMessageStream interim text sealing', () => {})it('settles a prefix-extended final onto a non-previewed interim (streamed + trailing delta)', async () => {- await mountStream()+ mountStream()await start()// The stream dropped/settled early at the tool boundary; the final adds a@@ -218,7 +186,7 @@ describe('useMessageStream interim text sealing', () => {})it('settles final onto interim even after message.start reset the boundary flag (#74560)', async () => {- await mountStream()+ mountStream()await start()await delta('partial')await interim('partial')@@ -235,12 +203,12 @@ describe('useMessageStream interim text sealing', () => {})it('appends a distinct previewed final after a message.start reset instead of overwriting the interim', async () => {- await mountStream()+ mountStream()await start()await interim('old interim text')// A genuinely new turn begins — message.start resets interimBoundaryPending.// Production ordering: mid-turn compaction-resume events do NOT include- // message.start (COMPACTION_RESUME_EVENT_TYPES in gateway-event.ts), and+ // message.start (COMPACTION_RESUME_EVENT_TYPES in gateway-event/index.ts), and// the TUI gateway emits message.complete BEFORE goal-followup starts// (tui_gateway/server.py), so a previewed final arriving after the reset// is a DISTINCT reply, not a rewrite of the interim. It must append its@@ -255,7 +223,7 @@ describe('useMessageStream interim text sealing', () => {})it('appends a genuinely different final as its own bubble (two real assistant segments)', async () => {- await mountStream()+ mountStream()await start()// The interim is one segment (pre-tool commentary); the final is different@@ -271,7 +239,7 @@ describe('useMessageStream interim text sealing', () => {})it('settles an identical final completion onto the interim when response_previewed', async () => {- await mountStream()+ mountStream()await start()await interim('same reply')@@ -285,7 +253,7 @@ describe('useMessageStream interim text sealing', () => {})it('settles a prefix-matched final onto the interim when response_previewed', async () => {- await mountStream()+ mountStream()await start()// Interim text is a PREFIX of the final — the model streamed part of@@ -302,7 +270,7 @@ describe('useMessageStream interim text sealing', () => {})it('dedupes partial-stream-then-nudge: streamed prefix + interim + previewed final settles to one bubble', async () => {- await mountStream()+ mountStream()await start()// The model streamed part of its answer via message.delta, then the@@ -319,16 +287,16 @@ describe('useMessageStream interim text sealing', () => {})it('ignores malformed message.interim payload', async () => {- await mountStream()+ mountStream()await start()// No payload at all- await act(() => handleEvent!({ type: 'message.interim' } as RpcEvent))+ await act(() => stream.handleEvent({ type: 'message.interim' } as RpcEvent))// Empty text- await act(() => handleEvent!({ payload: { text: '' }, session_id: SID, type: 'message.interim' } as RpcEvent))+ await act(() => stream.handleEvent({ payload: { text: '' }, session_id: SID, type: 'message.interim' } as RpcEvent))// Undefined textawait act(() =>- handleEvent!({ payload: { text: undefined }, session_id: SID, type: 'message.interim' } as RpcEvent)+ stream.handleEvent({ payload: { text: undefined }, session_id: SID, type: 'message.interim' } as RpcEvent))// Turn continues without finalizing or throwing@@ -337,7 +305,7 @@ describe('useMessageStream interim text sealing', () => {})it('clears interimBoundaryPending on message.start', async () => {- await mountStream()+ mountStream()await start()await delta('interim text')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/moa-progress-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/moa-progress-event.test.tsxindex 1e4c0d37867..73de97db07b 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/moa-progress-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/moa-progress-event.test.tsx@@ -1,88 +1,41 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null-let latestState: ClientSessionState | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)- latestState = next-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])+let stream: MessageStreamHarness- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}) {- act(() => handleEvent!({ payload, session_id: SID, type }))+ act(() => stream.handleEvent({ payload, session_id: SID, type }))}-function reasoningText(): string {- const message = latestState?.messages.at(-1)- const part = message?.parts.find(p => p.type === 'reasoning')-- return part?.type === 'reasoning' ? part.text : ''-}--beforeEach(() => {- handleEvent = null- latestState = null-})-afterEach(() => {cleanup()vi.restoreAllMocks()})describe('useMessageStream moa.progress / moa.phase surfacing', () => {- it('shows refs k/n lines in the reasoning block as references complete', async () => {- await mountStream()+ it('shows refs k/n lines in the reasoning block as references complete', () => {+ mountStream()emit('message.start')emit('moa.progress', { label: 'model-a', refs_done: 1, refs_total: 3 })emit('moa.progress', { label: 'model-b', refs_done: 2, refs_total: 3 })- const text = reasoningText()+ const text = stream.reasoningText()expect(text).toContain('MoA refs 1/3 — model-a')expect(text).toContain('MoA refs 2/3 — model-b')})- it('restarts the progress block on the first ref of a new fan-out', async () => {- await mountStream()+ it('restarts the progress block on the first ref of a new fan-out', () => {+ mountStream()emit('message.start')emit('moa.progress', { label: 'stale', refs_done: 1, refs_total: 2 })@@ -90,32 +43,32 @@ describe('useMessageStream moa.progress / moa.phase surfacing', () => {// A later turn's fan-out starts over at 1/N — old lines must not linger.emit('moa.progress', { label: 'fresh', refs_done: 1, refs_total: 2 })- const text = reasoningText()+ const text = stream.reasoningText()expect(text).toContain('MoA refs 1/2 — fresh')expect(text).not.toContain('stale')})- it('appends the aggregating marker on moa.phase and ignores unknown phases', async () => {- await mountStream()+ it('appends the aggregating marker on moa.phase and ignores unknown phases', () => {+ mountStream()emit('message.start')emit('moa.progress', { label: 'model-a', refs_done: 1, refs_total: 1 })emit('moa.phase', { phase: 'reference', refs_done: 1, refs_total: 1 })- expect(reasoningText()).not.toContain('aggregating')+ expect(stream.reasoningText()).not.toContain('aggregating')emit('moa.phase', { aggregator: 'agg-model', phase: 'aggregator', refs_done: 1, refs_total: 1 })- expect(reasoningText()).toContain('MoA aggregating…')+ expect(stream.reasoningText()).toContain('MoA aggregating…')})- it('a following moa.reference replaces the progress trail (self-cleaning)', async () => {- await mountStream()+ it('a following moa.reference replaces the progress trail (self-cleaning)', () => {+ mountStream()emit('message.start')emit('moa.progress', { label: 'model-a', refs_done: 1, refs_total: 1 })emit('moa.phase', { phase: 'aggregator', refs_done: 1, refs_total: 1 })emit('moa.reference', { count: 1, index: 1, label: 'model-a', text: 'advice-a' })- const text = reasoningText()+ const text = stream.reasoningText()expect(text).toContain('Reference 1/1 — model-a')expect(text).not.toContain('MoA refs')expect(text).not.toContain('aggregating')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/moa-reference-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/moa-reference-event.test.tsxindex ce3afeef67e..2bbb4c33256 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/moa-reference-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/moa-reference-event.test.tsx@@ -1,81 +1,34 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null-let latestState: ClientSessionState | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)- latestState = next-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])+let stream: MessageStreamHarness- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}) {- act(() => handleEvent!({ payload, session_id: SID, type }))-}--function reasoningText(): string {- const message = latestState?.messages.at(-1)- const part = message?.parts.find(p => p.type === 'reasoning')-- return part?.type === 'reasoning' ? part.text : ''+ act(() => stream.handleEvent({ payload, session_id: SID, type }))}describe('useMessageStream moa.reference accumulation (#64658)', () => {- beforeEach(() => {- handleEvent = null- latestState = null- })-afterEach(() => {cleanup()vi.restoreAllMocks()})- it('keeps every reference model labelled block instead of only the latest one', async () => {- await mountStream()+ it('keeps every reference model labelled block instead of only the latest one', () => {+ mountStream()emit('moa.reference', { count: 2, index: 1, label: 'model-a', text: 'advice-a' })emit('moa.reference', { count: 2, index: 2, label: 'model-b', text: 'advice-b' })- const text = reasoningText()+ const text = stream.reasoningText()expect(text).toContain('model-a')expect(text).toContain('advice-a')@@ -83,25 +36,25 @@ describe('useMessageStream moa.reference accumulation (#64658)', () => {expect(text).toContain('advice-b')})- it('handles a single-reference MoA turn (count=1) without regression', async () => {- await mountStream()+ it('handles a single-reference MoA turn (count=1) without regression', () => {+ mountStream()emit('moa.reference', { count: 1, index: 1, label: 'model-a', text: 'only-advice' })- const text = reasoningText()+ const text = stream.reasoningText()expect(text).toContain('model-a')expect(text).toContain('only-advice')})- it('accumulates three or more references in order', async () => {- await mountStream()+ it('accumulates three or more references in order', () => {+ mountStream()emit('moa.reference', { count: 3, index: 1, label: 'model-a', text: 'advice-a' })emit('moa.reference', { count: 3, index: 2, label: 'model-b', text: 'advice-b' })emit('moa.reference', { count: 3, index: 3, label: 'model-c', text: 'advice-c' })- const text = reasoningText()+ const text = stream.reasoningText()const orderOk =text.indexOf('advice-a') < text.indexOf('advice-b') && text.indexOf('advice-b') < text.indexOf('advice-c')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/pet-tool-failure-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/pet-tool-failure-event.test.tsxindex 452164b6c5e..f508e7501f5 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/pet-tool-failure-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/pet-tool-failure-event.test.tsx@@ -1,60 +1,26 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import { $petActivity, $petState, setPetActivity } from '@/store/pet'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'const OTHER_SID = 'session-2'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarness-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}, sessionId = SID) {- act(() => handleEvent!({ payload, session_id: sessionId, type }))+ act(() => stream.handleEvent({ payload, session_id: sessionId, type }))}describe('pet tool-failure reaction', () => {beforeEach(() => {- handleEvent = nullsetPetActivity({busy: false,awaitingInput: false,@@ -72,8 +38,8 @@ describe('pet tool-failure reaction', () => {vi.restoreAllMocks()})- it('briefly shows failed when the active session has an isolated tool error', async () => {- await mountStream()+ it('briefly shows failed when the active session has an isolated tool error', () => {+ mountStream()emit('tool.start', { name: 'terminal', tool_id: 'tool-1' })emit('tool.complete', { name: 'terminal', tool_id: 'tool-1', error: 'exit code 1' })@@ -82,8 +48,8 @@ describe('pet tool-failure reaction', () => {expect($petState.get()).toBe('failed')})- it('does not show failed for a successful tool or a background-session failure', async () => {- await mountStream()+ it('does not show failed for a successful tool or a background-session failure', () => {+ mountStream()emit('tool.complete', { name: 'terminal', tool_id: 'tool-1' })expect($petActivity.get().error).toBe(false)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/provider-wait-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/provider-wait-event.test.tsxindex 584a058ab7b..1136a141199 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/provider-wait-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/provider-wait-event.test.tsx@@ -1,57 +1,23 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import { $providerWaitSessions } from '@/store/provider-wait'import { clearAllSessionStates, dropSessionState } from '@/store/session-states'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarnessfunction emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}) {- act(() => handleEvent!({ payload, session_id: SID, type }))+ act(() => stream.handleEvent({ payload, session_id: SID, type }))}describe('provider wait visibility', () => {beforeEach(async () => {- handleEvent = null$providerWaitSessions.set({})- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+ stream = renderMessageStream(SID)})afterEach(() => {diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsxindex a60e72d40fe..bbc760a677f 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx@@ -1,6 +1,5 @@import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { isTargetSessionBusy } from '@/app/session/hooks/use-prompt-actions/utils'@@ -8,12 +7,10 @@ import type { ClientSessionState } from '@/app/types'import { createClientSessionState } from '@/lib/chat-runtime'import { modelOptionsQueryKey } from '@/lib/model-options'import { setCurrentModel, setCurrentProvider } from '@/store/session'-import type { RpcEvent } from '@/types/hermes'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'import { PRE_TURN_LIVE_SETTLE_GRACE_MS } from './utils'-import { useMessageStream } from './index'-// Per-turn REST amplification guards: session.info must not refetch config for// background sessions nor invalidate the model-options catalog when the model// string is merely PRESENT (the backend stamps it on every event) rather than@@ -21,53 +18,28 @@ import { useMessageStream } from './index'const ACTIVE_SID = 'session-active'const ACTIVE_PROFILE = 'compass'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarnesslet refreshHermesConfig: ReturnType<typeof vi.fn<() => Promise<void>>>let refreshSessions: ReturnType<typeof vi.fn<() => Promise<void>>>let hydrateFromStoredSession: ReturnType<typeof vi.fn<() => Promise<void>>>let queryClient: QueryClientlet sessionStates: Map<string, ClientSessionState> | null = null-function Harness() {- const activeSessionIdRef = useRef<string | null>(ACTIVE_SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())-- sessionStates = sessionStateByRuntimeIdRef.current-- const stream = useMessageStream({+function mountStream() {+ stream = renderMessageStream(ACTIVE_SID, {activeGatewayProfile: ACTIVE_PROFILE,- activeSessionIdRef,hydrateFromStoredSession,queryClient,refreshHermesConfig,- refreshSessions,- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }+ refreshSessions})-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+ sessionStates = stream.states}const sessionInfo = (sessionId: string, payload: Record<string, unknown>) =>- act(() => handleEvent!({ payload, session_id: sessionId, type: 'session.info' }))+ act(() => stream.handleEvent({ payload, session_id: sessionId, type: 'session.info' }))beforeEach(() => {- handleEvent = nullsessionStates = nullrefreshHermesConfig = vi.fn<() => Promise<void>>(async () => undefined)refreshSessions = vi.fn<() => Promise<void>>(async () => undefined)@@ -88,7 +60,7 @@ afterEach(() => {describe('session.info config refetch gating', () => {it('coalesces active-session bursts into one trailing config fetch', async () => {// Mount under real timers (waitFor), then freeze time for the debounce.- await mountStream()+ mountStream()vi.useFakeTimers()sessionInfo(ACTIVE_SID, { model: 'm1', running: true })@@ -105,7 +77,7 @@ describe('session.info config refetch gating', () => {})it('never fetches config for a background session heartbeat', async () => {- await mountStream()+ mountStream()vi.useFakeTimers()sessionInfo('session-background', { model: 'm1', running: true })@@ -120,8 +92,8 @@ describe('session.info config refetch gating', () => {})describe('session.info model-options invalidation gating', () => {- it('skips invalidation when model/provider merely restate the known values', async () => {- await mountStream()+ it('skips invalidation when model/provider merely restate the known values', () => {+ mountStream()const invalidate = vi.spyOn(queryClient, 'invalidateQueries')// Seed the session's cached runtime state.@@ -135,8 +107,8 @@ describe('session.info model-options invalidation gating', () => {expect(invalidate).not.toHaveBeenCalled()})- it('invalidates when the session model actually changes', async () => {- await mountStream()+ it('invalidates when the session model actually changes', () => {+ mountStream()const invalidate = vi.spyOn(queryClient, 'invalidateQueries')sessionInfo(ACTIVE_SID, { model: 'm1', provider: 'p1', running: true })@@ -159,10 +131,10 @@ describe('session.info settles a turn that produced no assistant payload', () =>const busyFor = (sessionId: string) => isTargetSessionBusy(Object.fromEntries(sessionStates!), sessionId, false)const startTurn = (sessionId: string) =>- act(() => handleEvent!({ payload: {}, session_id: sessionId, type: 'message.start' }))+ act(() => stream.handleEvent({ payload: {}, session_id: sessionId, type: 'message.start' }))it('leaves the session sendable after a started turn ends with no payload', async () => {- await mountStream()+ mountStream()startTurn(ACTIVE_SID)expect(busyFor(ACTIVE_SID)).toBe(true)@@ -179,7 +151,7 @@ describe('session.info settles a turn that produced no assistant payload', () =>})it('keeps waiting when running=false lands before the turn ever started', async () => {- await mountStream()+ mountStream()// submit arms busy/awaitingResponse optimistically — and seeds the visible// turn clock (turnStartedAt) at Enter — so this heartbeat is the pre-start@@ -213,7 +185,7 @@ describe('session.info settles a turn that produced no assistant payload', () =>// never fires. Only an app restart cleared it. Past the grace window the// gateway's running=false is authoritative and must settle the session.it('settles an armed-but-never-live turn once the pre-start grace expires (#86795)', async () => {- await mountStream()+ mountStream()act(() => {sessionStates!.set(ACTIVE_SID, {@@ -240,7 +212,7 @@ describe('session.info settles a turn that produced no assistant payload', () =>// one — submit and the rewind optimistic transforms both seed the clock —// but a regression that forgets the seed must fail open, not latch).it('settles an armed turn with no clock instead of latching busy (#86795)', async () => {- await mountStream()+ mountStream()act(() => {sessionStates!.set(ACTIVE_SID, {@@ -258,8 +230,8 @@ describe('session.info settles a turn that produced no assistant payload', () =>expect(busyFor(ACTIVE_SID)).toBe(false)})- it('un-latches a background session but does not hydrate its transcript', async () => {- await mountStream()+ it('un-latches a background session but does not hydrate its transcript', () => {+ mountStream()startTurn('session-background')sessionInfo('session-background', { running: false })@@ -273,7 +245,7 @@ describe('session.info settles a turn that produced no assistant payload', () =>})it('hydrates the foreground transcript once and coalesces the sidebar refresh', async () => {- await mountStream()+ mountStream()startTurn(ACTIVE_SID)vi.useFakeTimers()@@ -294,11 +266,11 @@ describe('session.info settles a turn that produced no assistant payload', () =>describe('message.complete sidebar refresh coalescing', () => {it('collapses near-simultaneous completions into one refresh', async () => {- await mountStream()+ mountStream()vi.useFakeTimers()- act(() => handleEvent!({ payload: { text: 'a' }, session_id: 's1', type: 'message.complete' }))- act(() => handleEvent!({ payload: { text: 'b' }, session_id: 's2', type: 'message.complete' }))+ act(() => stream.handleEvent({ payload: { text: 'a' }, session_id: 's1', type: 'message.complete' }))+ act(() => stream.handleEvent({ payload: { text: 'b' }, session_id: 's2', type: 'message.complete' }))expect(refreshSessions).not.toHaveBeenCalled()diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/session-reclaimed.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/session-reclaimed.test.tsxindex 2c865923eeb..7fd8473e16a 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/session-reclaimed.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/session-reclaimed.test.tsx@@ -1,6 +1,5 @@import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'@@ -8,7 +7,7 @@ import { createClientSessionState } from '@/lib/chat-runtime'import { $sessionStates, $sessionTiles, publishSessionState } from '@/store/session-states'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'// `session.reclaimed`: the backend tore down a live session we're still// holding (idle TTL, LRU cap, WS-orphan reap). Before this event the runtime id@@ -17,48 +16,18 @@ import { useMessageStream } from './index'const ACTIVE_SID = 'session-active'const ACTIVE_PROFILE = 'compass'-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarnesslet queryClient: QueryClientlet wiringCache: Map<string, ClientSessionState>-function Harness() {- const activeSessionIdRef = useRef<string | null>(ACTIVE_SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())-- wiringCache = sessionStateByRuntimeIdRef.current-- const stream = useMessageStream({- activeGatewayProfile: ACTIVE_PROFILE,- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient,- refreshHermesConfig: vi.fn<() => Promise<void>>(async () => undefined),- refreshSessions: vi.fn<() => Promise<void>>(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(ACTIVE_SID, { activeGatewayProfile: ACTIVE_PROFILE, queryClient })+ wiringCache = stream.states}const reclaim = (sessionId: string, reason = 'ws_orphan_reap') =>act(() =>- handleEvent!({+ stream.handleEvent({payload: { reason, session_id: sessionId, stored_session_id: 'stored-1' },session_id: '',type: 'session.reclaimed'@@ -66,7 +35,6 @@ const reclaim = (sessionId: string, reason = 'ws_orphan_reap') =>)beforeEach(() => {- handleEvent = nullqueryClient = new QueryClient()$sessionStates.set({})$sessionTiles.set([])@@ -80,8 +48,8 @@ afterEach(() => {})describe('session.reclaimed', () => {- it('drops the cached state for the reclaimed runtime', async () => {- await mountStream()+ it('drops the cached state for the reclaimed runtime', () => {+ mountStream()publishSessionState('live-gone', createClientSessionState())expect($sessionStates.get()['live-gone']).toBeDefined()@@ -90,8 +58,8 @@ describe('session.reclaimed', () => {expect($sessionStates.get()['live-gone']).toBeUndefined()})- it('leaves every other live session alone', async () => {- await mountStream()+ it('leaves every other live session alone', () => {+ mountStream()publishSessionState('live-gone', createClientSessionState())publishSessionState('live-kept', createClientSessionState())@@ -103,8 +71,8 @@ describe('session.reclaimed', () => {expect($sessionStates.get()['live-kept']).toBeDefined()})- it('ignores a payload with no runtime id instead of clearing everything', async () => {- await mountStream()+ it('ignores a payload with no runtime id instead of clearing everything', () => {+ mountStream()publishSessionState('live-a', createClientSessionState())publishSessionState('live-b', createClientSessionState())@@ -114,12 +82,11 @@ describe('session.reclaimed', () => {expect(Object.keys($sessionStates.get()).sort()).toEqual(['live-a', 'live-b'])})- it('drops the runtime regardless of which reclaim reason fired', async () => {+ it('drops the runtime regardless of which reclaim reason fired', () => {for (const reason of ['idle_timeout', 'lru_evict', 'ws_orphan_reap']) {$sessionStates.set({})cleanup()- handleEvent = null- await mountStream()+ mountStream()publishSessionState('live-gone', createClientSessionState())reclaim('live-gone', reason)@@ -132,8 +99,8 @@ describe('session.reclaimed', () => {// state drop above empties the tile's view, but with `runtimeId` still set// the tile's resume effect (gated on !runtimeId) never refires — an empty// transcript under live chrome, unrecoverable without closing the tab.- it('unbinds a tile holding the reclaimed runtime so its resume can refire', async () => {- await mountStream()+ it('unbinds a tile holding the reclaimed runtime so its resume can refire', () => {+ mountStream()publishSessionState('live-gone', createClientSessionState('stored-1'))$sessionTiles.set([{ runtimeId: 'live-gone', storedSessionId: 'stored-1' },@@ -152,8 +119,8 @@ describe('session.reclaimed', () => {// The wiring cache is resumeTile's warm path: a leftover entry for the dead// runtime would be handed straight back on the re-resume, rebinding the tile// to the same reclaimed id the backend just forgot.- it('purges the wiring cache entry for the reclaimed runtime', async () => {- await mountStream()+ it('purges the wiring cache entry for the reclaimed runtime', () => {+ mountStream()wiringCache.set('live-gone', createClientSessionState('stored-1'))wiringCache.set('live-kept', createClientSessionState('stored-2'))diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsxindex 52973d7fdeb..568d39f02f7 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/stale-pending-settle.test.tsx@@ -4,56 +4,21 @@// mid-transcript — the dither block anywhere but the tail. session.info// running=false is the turn's finally-block signal and the only settle edge// those paths still emit, so it must finalize the bubble.-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render } from '@testing-library/react'-import { useEffect, useRef } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import type { RpcEvent } from '@/types/hermes'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'import { STREAM_DELTA_FLUSH_MS } from './utils'-import { useMessageStream } from './index'-const SID = 'stale-pending-session'-let handleEvent: ((event: RpcEvent) => void) | null = null-let states: Map<string, ClientSessionState>--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- states = sessionStateByRuntimeIdRef.current- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarnessasync function mountHarness() {vi.useFakeTimers()- render(<Harness />)+ stream = renderMessageStream(SID)await act(async () => {await Promise.resolve()})@@ -65,14 +30,9 @@ const flushDeltas = async () => {})}-const emit = (event: RpcEvent) => act(() => handleEvent?.(event))+const emit = (event: RpcEvent) => act(() => stream.handleEvent(event))describe('turn end without message.complete (session.info running=false)', () => {- beforeEach(() => {- handleEvent = null- states = new Map()- })-afterEach(() => {cleanup()vi.useRealTimers()@@ -86,11 +46,11 @@ describe('turn end without message.complete (session.info running=false)', () =>emit({ payload: { text: 'partial answer' }, session_id: SID, type: 'message.delta' })await flushDeltas()- expect(states.get(SID)?.messages.at(-1)?.pending).toBe(true)+ expect(stream.state()?.messages.at(-1)?.pending).toBe(true)emit({ payload: { running: false }, session_id: SID, type: 'session.info' })- const state = states.get(SID)+ const state = stream.state()const tail = state?.messages.at(-1)expect(tail?.role).toBe('assistant')@@ -118,7 +78,7 @@ describe('turn end without message.complete (session.info running=false)', () =>emit({ payload: { running: false }, session_id: SID, type: 'session.info' })- const state = states.get(SID)+ const state = stream.state()// Same math as Stop: an empty-text placeholder is dropped, nothing stays// pending, and the stream binding is released.diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsxindex d14f0f4fe93..31da62b1eb5 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/stream-flush.test.tsx@@ -1,56 +1,14 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render } from '@testing-library/react'-import { useEffect, useRef } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'--import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'-import type { RpcEvent } from '@/types/hermes'+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'import { STREAM_DELTA_FLUSH_MS } from './utils'-import { useMessageStream } from './index'-const SID = 'stream-session'-let handleEvent: ((event: RpcEvent) => void) | null = null-let states: Map<string, ClientSessionState>--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- states = sessionStateByRuntimeIdRef.current- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarnessdescribe('stream delta delivery', () => {- beforeEach(() => {- handleEvent = null- states = new Map()- })-afterEach(() => {cleanup()vi.useRealTimers()@@ -64,7 +22,7 @@ describe('stream delta delivery', () => {const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1)vi.useFakeTimers()- render(<Harness />)+ stream = renderMessageStream(SID)await act(async () => {await Promise.resolve()})@@ -72,7 +30,7 @@ describe('stream delta delivery', () => {// Reach the frame-gated branch: it is only taken once the coalescing floor// has already elapsed since the previous flush. Send one delta, let it// flush, then idle past the floor so the NEXT delta schedules immediately.- act(() => handleEvent?.({ payload: { text: 'first ' }, session_id: SID, type: 'message.delta' }))+ act(() => stream.handleEvent({ payload: { text: 'first ' }, session_id: SID, type: 'message.delta' }))await act(async () => {await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS)})@@ -80,13 +38,13 @@ describe('stream delta delivery', () => {await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS * 2)})- act(() => handleEvent?.({ payload: { text: 'and the rest' }, session_id: SID, type: 'message.delta' }))+ act(() => stream.handleEvent({ payload: { text: 'and the rest' }, session_id: SID, type: 'message.delta' }))await act(async () => {await vi.advanceTimersByTimeAsync(STREAM_DELTA_FLUSH_MS)})- expect(states.get(SID)?.messages.at(-1)?.parts).toMatchObject([{ type: 'text', text: 'first and the rest' }])+ expect(stream.state()?.messages.at(-1)?.parts).toMatchObject([{ type: 'text', text: 'first and the rest' }])// The flush must not have depended on a frame: this mock parks every rAF// callback, yet the text arrived. runFlush still registers its// adaptive-floor measurement callback here; that one is allowed to waitdiff --git a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsxindex a2c775a9124..303cf10a2e2 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx@@ -1,63 +1,29 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'import { chatMessageText } from '@/lib/chat-messages'-import { createClientSessionState } from '@/lib/chat-runtime'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'-let handleEvent: ((event: RpcEvent) => void) | null = null-let sessionStates: Map<string, ClientSessionState>--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)- sessionStates.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])+let stream: MessageStreamHarness- return null+function mountStream() {+ stream = renderMessageStream(SID)}-async function mountStream() {- sessionStates = new Map()- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())-}+const start = () => act(() => stream.handleEvent({ payload: {}, session_id: SID, type: 'message.start' }))-const start = () => act(() => handleEvent!({ payload: {}, session_id: SID, type: 'message.start' }))-const delta = (text: string) => act(() => handleEvent!({ payload: { text }, session_id: SID, type: 'message.delta' }))+const delta = (text: string) =>+ act(() => stream.handleEvent({ payload: { text }, session_id: SID, type: 'message.delta' }))const completeWithError = (payload: Record<string, unknown>) =>- act(() => handleEvent!({ payload: { status: 'error', ...payload }, session_id: SID, type: 'message.complete' }))+ act(() => stream.handleEvent({ payload: { status: 'error', ...payload }, session_id: SID, type: 'message.complete' }))function getState(): ClientSessionState {- return sessionStates.get(SID) ?? createClientSessionState()+ return stream.state()}function lastAssistant() {@@ -65,17 +31,13 @@ function lastAssistant() {}describe('terminal error message.complete frames', () => {- beforeEach(() => {- handleEvent = null- })-afterEach(() => {cleanup()vi.restoreAllMocks()})it('marks the bubble failed from the structured error field, not the text heuristic', async () => {- await mountStream()+ mountStream()await start()await delta('…')@@ -89,7 +51,7 @@ describe('terminal error message.complete frames', () => {})it('keeps streamed partial text visible on a partial failure', async () => {- await mountStream()+ mountStream()await start()await delta('half an ans')@@ -107,7 +69,7 @@ describe('terminal error message.complete frames', () => {})it('falls back to the frame text when no error field is present', async () => {- await mountStream()+ mountStream()await start()await delta('…')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsxnew file mode 100644index 00000000000..4104bd5e87f--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/test-harness.tsx@@ -0,0 +1,117 @@+import { QueryClient } from '@tanstack/react-query'+import { render } from '@testing-library/react'+import { useEffect, useRef } from 'react'+import { vi } from 'vitest'++import type { ClientSessionState } from '@/app/types'+import { createClientSessionState } from '@/lib/chat-runtime'+import type { RpcEvent } from '@/types/hermes'++import { useMessageStream } from './index'++export interface MessageStreamHarnessOptions extends Partial<Parameters<typeof useMessageStream>[0]> {+ /** Session-state map to mount with, for tests that seed state up front. */+ states?: Map<string, ClientSessionState>+}++export interface MessageStreamHarness {+ /** Feed a gateway event into the mounted hook. */+ handleEvent: (event: RpcEvent) => void+ /** Push streaming assistant text, bypassing the event envelope. For the specs+ * about flush scheduling rather than about a particular event. */+ appendDelta: (sessionId: string, delta: string) => void+ /** The hook's session-state map, so callers can seed or inspect it directly. */+ states: Map<string, ClientSessionState>+ /** State for a session, blank before the hook has written any. */+ state: (sessionId?: string) => ClientSessionState+ /** Last state written for any session — for assertions about the write itself. */+ latest: () => ClientSessionState | null+ /** Text of the trailing text part on a session's newest message, '' when the+ * tail is not text. What streamed deltas accumulate into. */+ text: (sessionId?: string) => string+ /** Text of the reasoning part on the newest message, '' when there is none.+ * MoA events land there, so the moa specs read the stream through it. */+ reasoningText: () => string+}++/** Mount `useMessageStream` with inert dependencies and hand back the event sink+ * plus the state it produces.+ *+ * Every event test needs the same wiring — the real hook, stubbed refresh and+ * hydrate callbacks, a session-state map it owns — and differs only in which+ * events it sends and what it asserts. `overrides` takes any of the hook's own+ * options for the tests that need a seeded state map, a shared query client, a+ * named gateway profile, or a callback they can assert against. Callers still+ * own `cleanup()`. */+export function renderMessageStream(+ sessionId: string | null,+ { states = new Map<string, ClientSessionState>(), ...overrides }: MessageStreamHarnessOptions = {}+): MessageStreamHarness {+ let dispatch: ((event: RpcEvent) => void) | null = null+ let appendDelta: ((sessionId: string, delta: string) => void) | null = null+ let latest: ClientSessionState | null = null++ function Harness() {+ const activeSessionIdRef = useRef<string | null>(sessionId)+ const sessionStateByRuntimeIdRef = useRef(states)+ const queryClientRef = useRef(new QueryClient())++ const stream = useMessageStream({+ activeSessionIdRef,+ hydrateFromStoredSession: vi.fn(async () => undefined),+ queryClient: queryClientRef.current,+ refreshHermesConfig: vi.fn(async () => undefined),+ refreshSessions: vi.fn(async () => undefined),+ sessionStateByRuntimeIdRef,+ updateSessionState: (id, updater) => {+ const next = updater(states.get(id) ?? createClientSessionState())+ states.set(id, next)+ latest = next++ return next+ },+ ...overrides+ })++ useEffect(() => {+ dispatch = stream.handleGatewayEvent+ appendDelta = stream.appendAssistantDelta+ }, [stream.appendAssistantDelta, stream.handleGatewayEvent])++ return null+ }++ render(<Harness />)++ const state = (id = sessionId ?? '') => states.get(id) ?? createClientSessionState()++ return {+ handleEvent: event => {+ if (!dispatch) {+ throw new Error('renderMessageStream: the hook never mounted')+ }++ dispatch(event)+ },+ appendDelta: (id, delta) => {+ if (!appendDelta) {+ throw new Error('renderMessageStream: the hook never mounted')+ }++ appendDelta(id, delta)+ },+ states,+ state,+ latest: () => latest,+ text: id => {+ const part = state(id).messages.at(-1)?.parts.at(-1)++ return part?.type === 'text' ? part.text : ''+ },+ reasoningText: () => {+ const part = latest?.messages.at(-1)?.parts.find(p => p.type === 'reasoning')++ return part?.type === 'reasoning' ? part.text : ''+ }+ }+}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsxindex cfeccbc0c5f..07d45ca56a7 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/timeline-events.test.tsx@@ -1,57 +1,18 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'-import type { RpcEvent } from '@/types/hermes'--import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'timeline-session'-let handleEvent: ((event: RpcEvent) => void) | null = null-let states: Map<string, ClientSessionState>--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)- states.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarnessconst event = (type: string, timestamp: number, payload: Record<string, unknown> = {}) =>- act(() => handleEvent?.({ payload: { ...payload, timestamp }, session_id: SID, type }))+ act(() => stream.handleEvent({ payload: { ...payload, timestamp }, session_id: SID, type }))describe('live transcript timeline events', () => {beforeEach(async () => {- handleEvent = null- states = new Map()- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+ stream = renderMessageStream(SID)})afterEach(() => {@@ -68,7 +29,7 @@ describe('live transcript timeline events', () => {event('message.delta', 105.625, { text: 'The file looks good.' })event('message.complete', 106.875, { text: 'The file looks good.' })- const assistants = states.get(SID)?.messages.filter(message => message.role === 'assistant') ?? []+ const assistants = stream.state(SID).messages.filter(message => message.role === 'assistant') ?? []expect(assistants).toHaveLength(2)expect([assistants[0].timestamp, assistants[0].completedAt]).toEqual([101.125, 101.75])@@ -88,7 +49,7 @@ describe('live transcript timeline events', () => {event('message.delta', 202.25, { text: 'Then speaking.' })event('tool.start', 203.5, { args: {}, name: 'terminal', tool_id: 'call-2' })- const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')+ const assistant = stream.state(SID).messages.find(message => message.role === 'assistant')expect(assistant?.parts.map(part => part.type)).toEqual(['reasoning', 'text', 'tool-call'])expect(assistant?.parts.map(part => part.timestamp)).toEqual([201.125, 202.25, 203.5])@@ -98,7 +59,7 @@ describe('live transcript timeline events', () => {event('message.start', 300)event('error', 301.875, { error: 'provider failed' })- const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')+ const assistant = stream.state(SID).messages.find(message => message.role === 'assistant')expect(assistant?.error).toBeTruthy()expect([assistant?.timestamp, assistant?.completedAt]).toEqual([301.875, 301.875])@@ -107,7 +68,7 @@ describe('live transcript timeline events', () => {it('uses the gateway event time for a review summary system row', () => {event('review.summary', 401.625, { text: 'Review saved.' })- const system = states.get(SID)?.messages.find(message => message.role === 'system')+ const system = stream.state(SID).messages.find(message => message.role === 'system')expect(system?.timestamp).toBe(401.625)expect(system?.parts[0].timestamp).toBe(401.625)@@ -118,7 +79,7 @@ describe('live transcript timeline events', () => {event('tool.start', 501, { args: {}, name: 'terminal', tool_id: 'call-3' })event('session.info', 502.75, { running: false })- const assistant = states.get(SID)?.messages.find(message => message.role === 'assistant')+ const assistant = stream.state(SID).messages.find(message => message.role === 'assistant')expect(assistant?.completedAt).toBe(502.75)expect(assistant?.parts[0].completedAt).toBe(502.75)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/todo-cleanup.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/todo-cleanup.test.tsxindex 6b676976e5d..d56f639d69d 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/todo-cleanup.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/todo-cleanup.test.tsx@@ -1,59 +1,25 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ClientSessionState } from '@/app/types'-import { createClientSessionState } from '@/lib/chat-runtime'import type { TodoItem } from '@/lib/todos'import { $todosBySession, clearSessionTodos, setSessionTodos } from '@/store/todos'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'const todo = (id: string, status: TodoItem['status']): TodoItem => ({ content: `task ${id}`, id, status })-let handleEvent: ((event: RpcEvent) => void) | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(new Map<string, ClientSessionState>())- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarness-async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID)}-const complete = () => act(() => handleEvent!({ payload: { text: 'done' }, session_id: SID, type: 'message.complete' }))+const complete = () =>+ act(() => stream.handleEvent({ payload: { text: 'done' }, session_id: SID, type: 'message.complete' }))describe('useMessageStream turn-end todo cleanup', () => {beforeEach(() => {- handleEvent = nullclearSessionTodos(SID)})@@ -63,8 +29,8 @@ describe('useMessageStream turn-end todo cleanup', () => {vi.restoreAllMocks()})- it('drops a still-active task list when the turn completes', async () => {- await mountStream()+ it('drops a still-active task list when the turn completes', () => {+ mountStream()setSessionTodos(SID, [todo('a', 'completed'), todo('b', 'in_progress')])complete()@@ -72,8 +38,8 @@ describe('useMessageStream turn-end todo cleanup', () => {expect($todosBySession.get()[SID]).toBeUndefined()})- it('keeps a finished list on completion so its linger shows the final checkmarks', async () => {- await mountStream()+ it('keeps a finished list on completion so its linger shows the final checkmarks', () => {+ mountStream()setSessionTodos(SID, [todo('a', 'completed')])complete()@@ -82,11 +48,11 @@ describe('useMessageStream turn-end todo cleanup', () => {expect($todosBySession.get()[SID]).toHaveLength(1)})- it('drops a still-active task list when the turn errors out', async () => {- await mountStream()+ it('drops a still-active task list when the turn errors out', () => {+ mountStream()setSessionTodos(SID, [todo('a', 'in_progress')])- act(() => handleEvent!({ payload: { message: 'boom' }, session_id: SID, type: 'error' }))+ act(() => stream.handleEvent({ payload: { message: 'boom' }, session_id: SID, type: 'error' }))expect($todosBySession.get()[SID]).toBeUndefined()})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/tool-drafting-event.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/tool-drafting-event.test.tsxindex 57d5c5b1ced..119c5b5cae5 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/tool-drafting-event.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/tool-drafting-event.test.tsx@@ -1,6 +1,4 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'@@ -8,7 +6,7 @@ import { createClientSessionState } from '@/lib/chat-runtime'import { $draftingToolSessions } from '@/store/tool-drafting'import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'const OTHER_SID = 'session-2'@@ -16,42 +14,14 @@ const OTHER_SID = 'session-2'// Module-scoped so a test can seed session state (e.g. interrupted) before the// handler reads it — `sessionInterrupted` resolves against this map.const sessionStates = new Map<string, ClientSessionState>()-let handleEvent: ((event: RpcEvent) => void) | null = null--function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(sessionStates)- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const next = updater(sessionStates.get(sessionId) ?? createClientSessionState())- sessionStates.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}+let stream: MessageStreamHarness-async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID, { states: sessionStates })}function emit(type: RpcEvent['type'], payload: RpcEvent['payload'] = {}, sessionId = SID) {- act(() => handleEvent!({ payload, session_id: sessionId, type }))+ act(() => stream.handleEvent({ payload, session_id: sessionId, type }))}function draftedTool(sessionId = SID) {@@ -60,7 +30,6 @@ function draftedTool(sessionId = SID) {describe('drafting-tool label lifecycle', () => {beforeEach(() => {- handleEvent = nullsessionStates.clear()$draftingToolSessions.set({})})@@ -72,8 +41,8 @@ describe('drafting-tool label lifecycle', () => {vi.restoreAllMocks()})- it('names the tool the model is drafting', async () => {- await mountStream()+ it('names the tool the model is drafting', () => {+ mountStream()emit('tool.generating', { name: 'write_file' })@@ -92,8 +61,8 @@ describe('drafting-tool label lifecycle', () => {['tool.complete', { name: 'terminal', tool_id: 'tool-1' }],['message.complete', { text: 'done' }],['error', { message: 'boom' }]- ] as const)('retires the label when %s proves the model moved on', async (type, payload) => {- await mountStream()+ ] as const)('retires the label when %s proves the model moved on', (type, payload) => {+ mountStream()emit('tool.generating', { name: 'write_file' })emit(type, payload)@@ -101,8 +70,8 @@ describe('drafting-tool label lifecycle', () => {expect(draftedTool()).toBeUndefined()})- it('leaves another session’s label alone', async () => {- await mountStream()+ it('leaves another session’s label alone', () => {+ mountStream()emit('tool.generating', { name: 'patch' }, OTHER_SID)emit('tool.generating', { name: 'write_file' })@@ -113,9 +82,9 @@ describe('drafting-tool label lifecycle', () => {})// A stopped turn can still emit a frame or two before the backend notices.- it('ignores a tool announced after the user hit stop', async () => {+ it('ignores a tool announced after the user hit stop', () => {sessionStates.set(SID, { ...createClientSessionState(), interrupted: true })- await mountStream()+ mountStream()emit('tool.generating', { name: 'write_file' })diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsxindex 924e845dd03..a610d316c73 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/usage.test.tsx@@ -1,59 +1,26 @@-import { QueryClient } from '@tanstack/react-query'-import { act, cleanup, render, waitFor } from '@testing-library/react'-import { useEffect, useRef } from 'react'+import { act, cleanup } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { ClientSessionState } from '@/app/types'import { createClientSessionState } from '@/lib/chat-runtime'import { $currentUsage } from '@/store/session'-import type { RpcEvent } from '@/types/hermes'-import { useMessageStream } from './index'+import { type MessageStreamHarness, renderMessageStream } from './test-harness'const SID = 'session-1'// $currentUsage mirrors the primary session; ClientSessionState.usage drives// the same status bar when a secondary tile is focused.const BASELINE = { calls: 2, input: 500, output: 40, total: 540 }-let handleEvent: ((event: RpcEvent) => void) | null = null+let stream: MessageStreamHarnesslet sessionStates = new Map<string, ClientSessionState>()-function Harness() {- const activeSessionIdRef = useRef<string | null>(SID)- const sessionStateByRuntimeIdRef = useRef(sessionStates)- const queryClientRef = useRef(new QueryClient())-- const stream = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession: vi.fn(async () => undefined),- queryClient: queryClientRef.current,- refreshHermesConfig: vi.fn(async () => undefined),- refreshSessions: vi.fn(async () => undefined),- sessionStateByRuntimeIdRef,- updateSessionState: (sessionId, updater) => {- const current = sessionStateByRuntimeIdRef.current.get(sessionId) ?? createClientSessionState()- const next = updater(current)- sessionStateByRuntimeIdRef.current.set(sessionId, next)-- return next- }- })-- useEffect(() => {- handleEvent = stream.handleGatewayEvent- }, [stream.handleGatewayEvent])-- return null-}--async function mountStream() {- render(<Harness />)- await waitFor(() => expect(handleEvent).not.toBeNull())+function mountStream() {+ stream = renderMessageStream(SID, { states: sessionStates })}describe('useMessageStream status-bar usage scoping', () => {beforeEach(() => {- handleEvent = nullsessionStates = new Map([[SID, { ...createClientSessionState(), usage: { ...BASELINE } }]])$currentUsage.set({ ...BASELINE })})@@ -63,11 +30,11 @@ describe('useMessageStream status-bar usage scoping', () => {vi.restoreAllMocks()})- it('merges a live session.usage tick from the focused session', async () => {- await mountStream()+ it('merges a live session.usage tick from the focused session', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { usage: { context_percent: 42, input: 1200, total: 1280 } },session_id: SID,type: 'session.usage'@@ -84,11 +51,11 @@ describe('useMessageStream status-bar usage scoping', () => {})})- it('caches a background session.usage tick without overwriting the primary status bar', async () => {- await mountStream()+ it('caches a background session.usage tick without overwriting the primary status bar', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { usage: { input: 9999, total: 9999 } },session_id: 'background-session',type: 'session.usage'@@ -104,11 +71,11 @@ describe('useMessageStream status-bar usage scoping', () => {})})- it('applies message.complete usage from the focused session', async () => {- await mountStream()+ it('applies message.complete usage from the focused session', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { text: 'done', usage: { calls: 3, input: 1500, output: 90, total: 1590 } },session_id: SID,type: 'message.complete'@@ -118,11 +85,11 @@ describe('useMessageStream status-bar usage scoping', () => {expect($currentUsage.get()).toEqual({ calls: 3, input: 1500, output: 90, total: 1590 })})- it('ignores message.complete usage from a background session', async () => {- await mountStream()+ it('ignores message.complete usage from a background session', () => {+ mountStream()act(() =>- handleEvent!({+ stream.handleEvent({payload: { text: 'done', usage: { calls: 9, input: 9999, output: 999, total: 9999 } },session_id: 'background-session',type: 'message.complete'diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsxindex 71296aa8f3d..f3b9c5e0209 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-model-controls.test.tsx@@ -16,21 +16,13 @@ import {} from '@/store/session'import type * as SessionStates from '@/store/session-states'+import { deferred } from '../../../test/deferred'+import { useModelControls } from './use-model-controls'const setGlobalModel = vi.fn()const notifyError = vi.fn()-function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}-vi.mock('@/hermes', () => ({getGlobalModelInfo: vi.fn(),setApiRequestProfile: vi.fn(),diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.tsindex a7b785bad46..43d16f79a22 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/rewind.test.ts@@ -139,7 +139,7 @@ describe('truncateSubmitParams', () => {})it('drops renderer-synthetic message ids but keeps durable row ids', () => {- // chat-messages.ts: `${timestamp}-${index}-${role}`+ // chat-messages/hydration.ts: `${timestamp}-${index}-${role}`expect(truncateSubmitParams(1, '1723456789-0-user', 456)).toEqual({confirm_truncate: true,truncate_before_user_ordinal: 1,@@ -490,7 +490,7 @@ describe('runRewindSubmit durable-address discipline (#87059)', () => {})describe('optimistic rewind/reload turn-clock seeding (#86795)', () => {- // The no-payload settle gate in gateway-event.ts holds a running=false+ // The no-payload settle gate in gateway-event/session-info.ts holds a running=false// heartbeat off while an optimistically armed turn waits for the backend —// but only for a bounded grace window measured from turnStartedAt. These// transforms are the arm sites for restore/edit/regenerate, so they mustdiff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 5a0c89a754a..1ab86bcb92e 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -49,6 +49,7 @@ import {import { $sessionTiles } from '@/store/session-states'import sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'+import { deferred } from '../../../test/deferred'import { sessionRoute } from '../../routes'import type { ClientSessionState } from '../../types'@@ -79,16 +80,6 @@ vi.mock('@/components/pane-shell/tree/store', async importOriginal => ({const RUNTIME_SESSION_ID = 'rt-new-001'-function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}-type HarnessHandle = Pick<ReturnType<typeof useSessionActions>,'createBackendSessionForSend' | 'selectSidebarItem' | 'startFreshSessionDraft'diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsxindex a78dc433cb6..79456f627bb 100644--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx@@ -18,6 +18,8 @@ import {setSessionsLoading} from '@/store/session'+import { deferred } from '../../../test/deferred'+import { useSessionListActions } from './use-session-list-actions'// Sidebar refresh hygiene: a content-identical refresh (turn complete,@@ -68,15 +70,6 @@ interface Deferred<T> {}/** Create a promise whose completion order the stale-response tests control. */-function deferred<T>(): Deferred<T> {- let resolve!: (value: T) => void-- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}vi.mock('@/hermes', async importOriginal => ({...(await importOriginal<Record<string, unknown>>()),diff --git a/apps/desktop/src/app/session/workspace-session-target.test.ts b/apps/desktop/src/app/session/workspace-session-target.test.tsindex 3a83f605a32..4a3ff10d4b5 100644--- a/apps/desktop/src/app/session/workspace-session-target.test.ts+++ b/apps/desktop/src/app/session/workspace-session-target.test.ts@@ -9,17 +9,9 @@ import {setNewChatWorkspaceTarget} from '@/store/session'-import { startWorkspaceSession } from './workspace-session-target'--function deferred<T>() {- let resolve!: (value: T) => void+import { deferred } from '../../test/deferred'- const promise = new Promise<T>(done => {- resolve = done- })-- return { promise, resolve }-}+import { startWorkspaceSession } from './workspace-session-target'describe('startWorkspaceSession', () => {afterEach(() => {diff --git a/apps/desktop/src/app/settings/keys-settings.test.tsx b/apps/desktop/src/app/settings/keys-settings.test.tsxindex 483be4eb33b..87217b2e15c 100644--- a/apps/desktop/src/app/settings/keys-settings.test.tsx+++ b/apps/desktop/src/app/settings/keys-settings.test.tsx@@ -2,17 +2,13 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { MemoryRouter, useNavigate } from 'react-router'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { EnvVarInfo } from '@/types/hermes'+import { stubResizeObserver } from '@/test/jsdom'-const getEnvVars = vi.fn()+import { envVar } from './test-utils'-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}+const getEnvVars = vi.fn()-vi.stubGlobal('ResizeObserver', TestResizeObserver)+stubResizeObserver()vi.mock('@/hermes', () => ({deleteEnvVar: vi.fn(),@@ -22,20 +18,6 @@ vi.mock('@/hermes', () => ({setEnvVar: vi.fn()}))-function envVar(category: string, patch: Partial<EnvVarInfo> = {}): EnvVarInfo {- return {- advanced: false,- category,- description: '',- is_password: true,- is_set: false,- redacted_value: null,- tools: [],- url: '',- ...patch- }-}-beforeEach(() => {getEnvVars.mockResolvedValue({})Object.defineProperty(Element.prototype, 'scrollIntoView', {diff --git a/apps/desktop/src/app/settings/searchable-select.test.tsx b/apps/desktop/src/app/settings/searchable-select.test.tsxindex 2e87c15c92f..61f0d77ffa7 100644--- a/apps/desktop/src/app/settings/searchable-select.test.tsx+++ b/apps/desktop/src/app/settings/searchable-select.test.tsx@@ -1,21 +1,14 @@import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import { stubResizeObserver } from '@/test/jsdom'import type { ConfigFieldSchema } from '@/types/hermes'import { ConfigField } from './config-field'import { rankSearchOption, SearchableSelect } from './searchable-select'-// Radix Popover + cmdk call scrollIntoView / pointer-capture / ResizeObserver-// APIs jsdom lacks.-class TestResizeObserver {- disconnect() {}- observe() {}- unobserve() {}-}-beforeAll(() => {- vi.stubGlobal('ResizeObserver', TestResizeObserver)+ stubResizeObserver()Element.prototype.scrollIntoView = vi.fn()Element.prototype.hasPointerCapture = vi.fn(() => false)Element.prototype.releasePointerCapture = vi.fn()diff --git a/apps/desktop/src/app/settings/settings-search.test.ts b/apps/desktop/src/app/settings/settings-search.test.tsindex 051a9a643b9..34935cc9b7c 100644--- a/apps/desktop/src/app/settings/settings-search.test.ts+++ b/apps/desktop/src/app/settings/settings-search.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'import { Settings2, Wrench } from '@/lib/icons'-import type { ConfigFieldSchema, EnvVarInfo, HermesConfigRecord } from '@/types/hermes'+import type { ConfigFieldSchema, HermesConfigRecord } from '@/types/hermes'import {buildConfigSearchEntries,@@ -9,20 +9,7 @@ import {credentialSettingsView,filterSettingsSearchEntries} from './settings-search'--function envVar(category: string, patch: Partial<EnvVarInfo> = {}): EnvVarInfo {- return {- advanced: false,- category,- description: '',- is_password: true,- is_set: false,- redacted_value: null,- tools: [],- url: '',- ...patch- }-}+import { envVar } from './test-utils'const searchCopy = {fieldDescriptions: {diff --git a/apps/desktop/src/app/settings/test-utils.ts b/apps/desktop/src/app/settings/test-utils.tsnew file mode 100644index 00000000000..92f8eab966a--- /dev/null+++ b/apps/desktop/src/app/settings/test-utils.ts@@ -0,0 +1,17 @@+import type { EnvVarInfo } from '@/types/hermes'++/** An unset secret in `category`. The Keys tab and the settings search both+ * bucket by category and branch on `is_set`, so those are what tests vary. */+export function envVar(category: string, patch: Partial<EnvVarInfo> = {}): EnvVarInfo {+ return {+ advanced: false,+ category,+ description: '',+ is_password: true,+ is_set: false,+ redacted_value: null,+ tools: [],+ url: '',+ ...patch+ }+}diff --git a/apps/desktop/src/app/shell/approval-mode-menu.test.tsx b/apps/desktop/src/app/shell/approval-mode-menu.test.tsxindex 040471a19e6..4702fc7abd9 100644--- a/apps/desktop/src/app/shell/approval-mode-menu.test.tsx+++ b/apps/desktop/src/app/shell/approval-mode-menu.test.tsx@@ -5,21 +5,13 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'import { StatusbarControls } from '@/app/shell/statusbar-controls'import { I18nProvider } from '@/i18n'import { $approvalModes } from '@/store/approval-mode'+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'import { useApprovalModeStatusbarItem } from './approval-mode-menu'-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-beforeAll(() => {- vi.stubGlobal('ResizeObserver', TestResizeObserver)- Element.prototype.hasPointerCapture ??= () => false- Element.prototype.setPointerCapture ??= () => undefined- Element.prototype.releasePointerCapture ??= () => undefined- HTMLElement.prototype.scrollIntoView ??= () => undefined+ stubResizeObserver()+ stubMenuDomApis()})afterEach(() => {diff --git a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.tsindex 547fef6876a..94859b09add 100644--- a/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts+++ b/apps/desktop/src/app/shell/hooks/use-status-snapshot.test.ts@@ -3,6 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { getStatus } from '@/hermes'+import { deferred } from '../../../test/deferred'+import { useStatusSnapshot } from './use-status-snapshot'vi.mock('@/hermes', () => ({@@ -11,18 +13,6 @@ vi.mock('@/hermes', () => ({type GatewayRequester = <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>-function deferred<T>() {- let resolve: (value: T) => void = () => undefined- let reject: (reason?: unknown) => void = () => undefined-- const promise = new Promise<T>((nextResolve, nextReject) => {- resolve = nextResolve- reject = nextReject- })-- return { promise, reject, resolve }-}-async function flushAsync() {await act(async () => {await vi.advanceTimersByTimeAsync(0)diff --git a/apps/desktop/src/app/shell/statusbar-visibility.test.tsx b/apps/desktop/src/app/shell/statusbar-visibility.test.tsxindex e65f272e055..d558c11d11f 100644--- a/apps/desktop/src/app/shell/statusbar-visibility.test.tsx+++ b/apps/desktop/src/app/shell/statusbar-visibility.test.tsx@@ -1,6 +1,6 @@import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'import { MemoryRouter } from 'react-router'-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeAll, describe, expect, it } from 'vitest'import { StatusbarControls, type StatusbarItem } from '@/app/shell/statusbar-controls'import {@@ -9,19 +9,11 @@ import {STATUSBAR_HIDDEN_BY_DEFAULT,toggleStatusbarVisible} from '@/store/statusbar-prefs'--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'beforeAll(() => {- vi.stubGlobal('ResizeObserver', TestResizeObserver)- Element.prototype.hasPointerCapture ??= () => false- Element.prototype.setPointerCapture ??= () => undefined- Element.prototype.releasePointerCapture ??= () => undefined- HTMLElement.prototype.scrollIntoView ??= () => undefined+ stubResizeObserver()+ stubMenuDomApis()})afterEach(() => {diff --git a/apps/desktop/src/components/assistant-ui/test-utils.tsx b/apps/desktop/src/components/assistant-ui/test-utils.tsxnew file mode 100644index 00000000000..f17284ec0a7--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/test-utils.tsx@@ -0,0 +1,86 @@+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import type { ReactNode } from 'react'+import { vi } from 'vitest'++import { stubResizeObserver } from '@/test/jsdom'++/** Fixed clock for message fixtures, so nothing sorts by "now". */+export const createdAt = new Date('2026-05-01T00:00:00.000Z')++/** The browser APIs the transcript renders against — a resize observer,+ * animation frames, `CSS.escape` for its selector lookups, and the scroll and+ * WAAPI calls the message list makes on mount. jsdom has none of them, and a+ * thread that cannot mount fails every assertion in the file for the wrong+ * reason. */+export function stubThreadEnvironment() {+ stubResizeObserver()++ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>+ window.setTimeout(() => callback(performance.now()), 0)+ )+ vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))+ vi.stubGlobal('CSS', { escape: (value: string) => value })++ Element.prototype.scrollTo = function scrollTo() {}++ Element.prototype.animate = function animate() {+ return { cancel() {}, finished: Promise.resolve() } as unknown as Animation+ }+}++/** Give jsdom a viewport that the thread's virtualizer treats as scrollable.+ *+ * jsdom reports every `offsetWidth`/`offsetHeight` as 0, which makes the+ * message list measure itself as having no room and skip the rendering paths+ * these tests are about. The stub falls through to a real value when one+ * exists, so a test that sets its own dimensions still wins. */+export function stubThreadViewportSize() {+ const stub = (prop: 'offsetHeight' | 'offsetWidth', clientProp: 'clientHeight' | 'clientWidth', fallback: number) => {+ const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)++ Object.defineProperty(HTMLElement.prototype, prop, {+ configurable: true,+ get() {+ return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback+ }+ })+ }++ stub('offsetWidth', 'clientWidth', 800)+ stub('offsetHeight', 'clientHeight', 600)+}++/** Wrap a transcript subtree in a runtime driven by a fixed message list, the+ * way the app's external store drives it: the thread is running while the tail+ * message is. */+export function ThreadRuntime({ children, messages }: { children: ReactNode; messages: ThreadMessage[] }) {+ const runtime = useExternalStoreRuntime<ThreadMessage>({+ messages,+ isRunning: messages.at(-1)?.status?.type === 'running',+ onNew: async () => {}+ })++ return <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>+}++export function userMessage(id = 'user-1', text = 'edit me please'): ThreadMessage {+ return {+ id,+ role: 'user',+ content: [{ type: 'text', text }],+ attachments: [],+ createdAt,+ metadata: { custom: {} }+ } as ThreadMessage+}++export function assistantMessage(): ThreadMessage {+ return {+ id: 'assistant-1',+ role: 'assistant',+ content: [{ type: 'text', text: 'done' }],+ status: { type: 'complete', reason: 'stop' },+ createdAt,+ metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }+ } as ThreadMessage+}diff --git a/apps/desktop/src/components/assistant-ui/thread-remount.test.tsx b/apps/desktop/src/components/assistant-ui/thread-remount.test.tsxindex 88454751e1b..5ec52f4c75b 100644--- a/apps/desktop/src/components/assistant-ui/thread-remount.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread-remount.test.tsx@@ -1,54 +1,12 @@import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'import { act, render, screen, waitFor } from '@testing-library/react'-import { describe, expect, it, vi } from 'vitest'+import { describe, expect, it } from 'vitest'+import { createdAt, stubThreadEnvironment, stubThreadViewportSize } from './test-utils'import { Thread } from './thread'-class NoopResizeObserver {- observe() {}-- unobserve() {}-- disconnect() {}-}--vi.stubGlobal('ResizeObserver', NoopResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))--Element.prototype.scrollTo = function scrollTo() {}--Element.prototype.animate = function animate() {- return {- cancel: () => {},- finished: Promise.resolve()- } as unknown as Animation-}--// jsdom returns 0 for offset*; the virtualizer reads those to size its-// viewport. Fall through to client* or a sane default so virtualized-// items render (same stub as streaming.test.tsx).-function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)--const createdAt = new Date('2026-05-01T00:00:00.000Z')+stubThreadEnvironment()+stubThreadViewportSize()const MESSAGES: ThreadMessage[] = [{diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsxindex 986c4a42482..82f1f44b549 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx@@ -6,10 +6,12 @@// supplied, matching how onDismissError/onRestoreToMessage already behave.import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'import { cleanup, render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'import { $displayTimestamps } from '@/store/display-timestamps'+import { stubThreadEnvironment } from '../test-utils'+import { formatTimelineRange, formatTimelineTimestamp } from './timestamp'import { Thread } from '.'@@ -19,20 +21,7 @@ $displayTimestamps.set(true)const createdAt = new Date('2026-05-01T00:00:00.000Z')const completedAt = createdAt.getTime() / 1000 + 1.25--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+stubThreadEnvironment()afterEach(() => {cleanup()diff --git a/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx b/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsxindex 227f9e63b02..62711211ab5 100644--- a/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx@@ -8,44 +8,16 @@// resolve dir="auto", so the contract is asserted at the attribute level.import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'import { render, screen } from '@testing-library/react'-import { describe, expect, it, vi } from 'vitest'+import { describe, expect, it } from 'vitest'++import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'import { Thread } from '.'const createdAt = new Date('2026-06-01T00:00:00.000Z')+stubThreadEnvironment()-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}--function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)+stubThreadViewportSize()function userMessage(): ThreadMessage {return {diff --git a/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx b/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsxindex 20ee08f1c61..67a7016b7f5 100644--- a/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx@@ -8,25 +8,12 @@ import type * as ReactionsStore from '@/store/reactions'import { $reactionsEnabled } from '@/store/reactions-enabled'import { $localReactions } from '@/store/reactions-local'+import { assistantMessage, stubThreadEnvironment } from '../test-utils'+import { isTapbackDoubleClick } from './use-message-reactions'import { Thread } from '.'--const createdAt = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+stubThreadEnvironment()// The gesture persists through the gateway; this suite is about the local// paint, which is what the user actually sees on the click.@@ -35,17 +22,6 @@ vi.mock('@/store/reactions', async importOriginal => ({toggleMessageReaction: vi.fn(async () => {})}))-function assistantMessage(): ThreadMessage {- return {- id: 'assistant-1',- role: 'assistant',- content: [{ type: 'text', text: 'done' }],- status: { type: 'complete', reason: 'stop' },- createdAt,- metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }- } as ThreadMessage-}-function Harness() {const runtime = useExternalStoreRuntime<ThreadMessage>({messages: [assistantMessage()],diff --git a/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx b/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsxindex ac659b99a5b..b20846f776f 100644--- a/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/duplicate-activity-indicator.test.tsx@@ -11,65 +11,20 @@ import { __resetElapsedTimerRegistryForTests } from '@/components/chat/activity-import { setSessionCompacting } from '@/store/compaction'import { $activeSessionId, $turnStartedAt } from '@/store/session'+import { stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'+import { Thread } from '.'// Layout/observer stubs mirrored from streaming.test.tsx. jsdom has no// ResizeObserver, rAF, or real layout, and the Thread scroll container needs// non-zero dimensions to mount without throwing.-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}--Element.prototype.animate = function animate() {- return {- cancel: () => {},- finished: Promise.resolve()- } as unknown as Animation-}--function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}+stubThreadEnvironment()-stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)+stubThreadViewportSize()const createdAt = new Date('2026-05-01T00:00:00.000Z')const sessionId = 'session-68634'-function userMessage(id: string, text: string): ThreadMessage {- return {- id,- role: 'user',- content: [{ type: 'text', text }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}-// This shape mirrors the `/steer` note appended by appendSessionTextMessage// in apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts.function systemMessage(id: string, text: string): ThreadMessage {diff --git a/apps/desktop/src/components/assistant-ui/thread/edit-context.test.tsx b/apps/desktop/src/components/assistant-ui/thread/edit-context.test.tsxindex f9c4f7129f1..4c19447478f 100644--- a/apps/desktop/src/components/assistant-ui/thread/edit-context.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/edit-context.test.tsx@@ -17,6 +17,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'+import { assistantMessage, stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'+import { Thread } from '.'interface MockComposerProps {@@ -34,23 +36,7 @@ vi.mock('./user-edit-composer', () => ({return <div data-testid="edit-composer">{props.cwd}</div>}}))--const createdAt = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+stubThreadEnvironment()afterEach(() => {cleanup()@@ -60,54 +46,7 @@ beforeEach(() => {composerRenders.length = 0})-// jsdom returns 0 for offset*; the virtualizer reads those to size its-// viewport. Fall through to client* or a sane default so virtualized-// items render (same stub as user-message-edit.test.tsx).-function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)--function userMessage(): ThreadMessage {- return {- id: 'user-1',- role: 'user',- content: [{ type: 'text', text: 'edit me please' }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}--function assistantMessage(): ThreadMessage {- return {- id: 'assistant-1',- role: 'assistant',- content: [{ type: 'text', text: 'done' }],- status: { type: 'complete', reason: 'stop' },- createdAt,- metadata: {- unstable_state: null,- unstable_annotations: [],- unstable_data: [],- steps: [],- custom: {}- }- } as ThreadMessage-}+stubThreadViewportSize()const noopAsync = async () => {}diff --git a/apps/desktop/src/components/assistant-ui/thread/status-tail-only.test.tsx b/apps/desktop/src/components/assistant-ui/thread/status-tail-only.test.tsxindex 1ec8feb7fc8..8e2cf85ebf0 100644--- a/apps/desktop/src/components/assistant-ui/thread/status-tail-only.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/status-tail-only.test.tsx@@ -3,32 +3,16 @@// there (missed settle event, steer race, upstream state bug) — must render// its content with no spinner: a live indicator above a later user message// reads as the agent answering out of order.-import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import { type ThreadMessage } from '@assistant-ui/react'import { cleanup, render, screen } from '@testing-library/react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'++import { stubThreadEnvironment, ThreadRuntime, userMessage } from '../test-utils'import { Thread } from '.'const createdAt = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}--// Enter animation fires for running messages; jsdom has no WAAPI.-Element.prototype.animate = function animate() {- return { cancel() {}, finished: Promise.resolve() } as unknown as Animation-}+stubThreadEnvironment()afterEach(() => {cleanup()@@ -42,17 +26,6 @@ const assistantMetadata = {custom: {}}-function user(id: string, text: string): ThreadMessage {- return {- id,- role: 'user',- content: [{ type: 'text', text }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}-function assistant(id: string, text: string, running: boolean): ThreadMessage {return {id,@@ -64,23 +37,15 @@ function assistant(id: string, text: string, running: boolean): ThreadMessage {} as ThreadMessage}-function Harness({ messages }: { messages: ThreadMessage[] }) {- const runtime = useExternalStoreRuntime<ThreadMessage>({- messages,- isRunning: messages.at(-1)?.status?.type === 'running',- onNew: async () => {}- })-- return (- <AssistantRuntimeProvider runtime={runtime}>- <Thread />- </AssistantRuntimeProvider>- )-}+const Harness = ({ messages }: { messages: ThreadMessage[] }) => (+ <ThreadRuntime messages={messages}>+ <Thread />+ </ThreadRuntime>+)describe('thinking indicator is tail-only', () => {it('shows the loading indicator on a running placeholder at the tail', async () => {- const { container } = render(<Harness messages={[user('u1', 'question'), assistant('a1', '', true)]} />)+ const { container } = render(<Harness messages={[userMessage('u1', 'question'), assistant('a1', '', true)]} />)expect(await screen.findByRole('status', { name: 'Hermes is loading a response' })).toBeTruthy()expect(container.querySelector('[data-slot="aui_response-loading"]')).toBeTruthy()@@ -91,9 +56,9 @@ describe('thinking indicator is tail-only', () => {const { container } = render(<Harnessmessages={[- user('u1', 'first question'),+ userMessage('u1', 'first question'),assistant('a1', '', true),- user('u2', 'second question'),+ userMessage('u2', 'second question'),assistant('a2', 'answered', false)]}/>diff --git a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsxindex 566e5b04e81..de9bb5cb8ac 100644--- a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx@@ -5,6 +5,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { $reasoningCollapsedByDefault } from '@/store/reasoning-disclosure'+import { stubThreadEnvironment, stubThreadViewportSize, ThreadRuntime } from '../test-utils'+import { Thread } from '.'const createdAt = new Date('2026-05-01T00:00:00.000Z')@@ -45,42 +47,12 @@ class TestResizeObserver {}}-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}--Element.prototype.animate = function animate() {- return {- cancel: () => {},- finished: Promise.resolve()- } as unknown as Animation-}+stubThreadEnvironment()-// jsdom returns 0 for offset*; some layout code reads those to size the-// viewport. Fall through to client* (which tests can override) or a sane-// default so message rows render with non-zero dimensions.-function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}+// This suite drives the virtualizer, so it needs an observer that reports.+vi.stubGlobal('ResizeObserver', TestResizeObserver)-stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)+stubThreadViewportSize()async function wait(ms: number) {await act(async () => {@@ -331,19 +303,11 @@ function StreamingHarness({ onControls }: { onControls?: (controls: StreamingCon)}-function TodoHarness({ message }: { message: ThreadMessage }) {- const runtime = useExternalStoreRuntime<ThreadMessage>({- messages: [message],- isRunning: message.status?.type === 'running',- onNew: async () => {}- })-- return (- <AssistantRuntimeProvider runtime={runtime}>- <Thread />- </AssistantRuntimeProvider>- )-}+const TodoHarness = ({ message }: { message: ThreadMessage }) => (+ <ThreadRuntime messages={[message]}>+ <Thread />+ </ThreadRuntime>+)function MessageHarness({ message }: { message: ThreadMessage }) {const runtime = useExternalStoreRuntime<ThreadMessage>({diff --git a/apps/desktop/src/components/assistant-ui/thread/system-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/system-message.test.tsxindex d0249fc45a4..14ea92d7ac2 100644--- a/apps/desktop/src/components/assistant-ui/thread/system-message.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/system-message.test.tsx@@ -1,30 +1,18 @@import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'import { cleanup, render } from '@testing-library/react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'import { $displayTimestamps } from '@/store/display-timestamps'+import { stubThreadEnvironment } from '../test-utils'+import { Thread } from '.'// Timeline timestamps render only when `display.timestamps` is enabled.$displayTimestamps.set(true)const timestamp = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+stubThreadEnvironment()function Harness({ text }: { text: string }) {const message = {diff --git a/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx b/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsxindex f40b5b71a7f..8554e7525ff 100644--- a/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/turn-gap-indicator.test.tsx@@ -2,48 +2,21 @@// is armed, but the tail bubble has settled — a sealed interim row, or a turn// whose last message completed while the agent kept going. The transcript used// to show nothing there, and the seconds went uncounted.-import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import { type ThreadMessage } from '@assistant-ui/react'import { act, cleanup, render, screen } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { __resetElapsedTimerRegistryForTests } from '@/components/chat/activity-timer'import { $activeSessionId, $busy, $messages, $turnStartedAt } from '@/store/session'-import { Thread } from '.'--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })+import { stubThreadEnvironment, ThreadRuntime, userMessage } from '../test-utils'-Element.prototype.scrollTo = function scrollTo() {}--Element.prototype.animate = function animate() {- return { cancel() {}, finished: Promise.resolve() } as unknown as Animation-}+import { Thread } from '.'+stubThreadEnvironment()const createdAt = new Date('2026-05-01T00:00:00.000Z')const sessionId = 'session-turn-gap'-function user(id: string, text: string): ThreadMessage {- return {- id,- role: 'user',- content: [{ type: 'text', text }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}-function assistant(id: string, content: unknown[], running: boolean): ThreadMessage {return {id,@@ -63,19 +36,11 @@ const toolCall = (toolName: string, settled: boolean) => ({...(settled ? { result: 'ok' } : {})})-function Harness({ messages }: { messages: ThreadMessage[] }) {- const runtime = useExternalStoreRuntime<ThreadMessage>({- messages,- isRunning: messages.at(-1)?.status?.type === 'running',- onNew: async () => {}- })-- return (- <AssistantRuntimeProvider runtime={runtime}>- <Thread />- </AssistantRuntimeProvider>- )-}+const Harness = ({ messages }: { messages: ThreadMessage[] }) => (+ <ThreadRuntime messages={messages}>+ <Thread />+ </ThreadRuntime>+)const timerText = (value: string) => screen.getAllByText((_, node) => node?.textContent === value)@@ -106,7 +71,9 @@ describe('the turn timer covers the gaps, not just the streaming', () => {// is busy, so the transcript owes the user a line and a count — measured// from the last thing the turn produced, not from when the row appeared.const { container } = render(- <Harness messages={[user('u1', 'do the thing'), assistant('a1', [{ type: 'text', text: 'On it.' }], false)]} />+ <Harness+ messages={[userMessage('u1', 'do the thing'), assistant('a1', [{ type: 'text', text: 'On it.' }], false)]}+ />)act(() => vi.advanceTimersByTime(7_000))@@ -117,7 +84,7 @@ describe('the turn timer covers the gaps, not just the streaming', () => {it('times the gap between a finished tool call and the next thing', () => {const { container } = render(- <Harness messages={[user('u1', 'read it'), assistant('a1', [toolCall('read_file', true)], true)]} />+ <Harness messages={[userMessage('u1', 'read it'), assistant('a1', [toolCall('read_file', true)], true)]} />)act(() => vi.advanceTimersByTime(9_000))@@ -128,7 +95,7 @@ describe('the turn timer covers the gaps, not just the streaming', () => {it('stays silent under a tool call still in flight — that row has its own timer', () => {const { container } = render(- <Harness messages={[user('u1', 'run it'), assistant('a1', [toolCall('terminal', false)], true)]} />+ <Harness messages={[userMessage('u1', 'run it'), assistant('a1', [toolCall('terminal', false)], true)]} />)act(() => vi.advanceTimersByTime(9_000))@@ -140,7 +107,9 @@ describe('the turn timer covers the gaps, not just the streaming', () => {$busy.set(false)const { container } = render(- <Harness messages={[user('u1', 'do the thing'), assistant('a1', [{ type: 'text', text: 'Done.' }], false)]} />+ <Harness+ messages={[userMessage('u1', 'do the thing'), assistant('a1', [{ type: 'text', text: 'Done.' }], false)]}+ />)act(() => vi.advanceTimersByTime(7_000))diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsxindex b6deaa742d9..2007730c8e2 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx@@ -9,68 +9,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'-import { Thread } from '.'--const createdAt = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}+import { assistantMessage, stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+import { Thread } from '.'+stubThreadEnvironment()afterEach(() => {cleanup()})-function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)--function userMessage(): ThreadMessage {- return {- id: 'user-1',- role: 'user',- content: [{ type: 'text', text: 'edit me please' }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}--function assistantMessage(): ThreadMessage {- return {- id: 'assistant-1',- role: 'assistant',- content: [{ type: 'text', text: 'done' }],- status: { type: 'complete', reason: 'stop' },- createdAt,- metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }- } as ThreadMessage-}+stubThreadViewportSize()function Harness({ onEdit }: { onEdit: (message: AppendMessage) => Promise<void> }) {const repository = ExportedMessageRepository.fromArray([userMessage(), assistantMessage()])diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsxindex 07e0bf13528..bd441fdb445 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx@@ -13,46 +13,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'-import { Thread } from '.'--const createdAt = new Date('2026-05-01T00:00:00.000Z')--class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}+import { assistantMessage, stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'-vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))-vi.stubGlobal('CSS', { escape: (str: string) => str })--Element.prototype.scrollTo = function scrollTo() {}+import { Thread } from '.'+stubThreadEnvironment()afterEach(() => {cleanup()})-function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)+stubThreadViewportSize()async function moveFocusOutside(editor: HTMLElement) {const outside = window.document.createElement('button')@@ -67,34 +37,6 @@ async function moveFocusOutside(editor: HTMLElement) {outside.remove()}-function userMessage(): ThreadMessage {- return {- id: 'user-1',- role: 'user',- content: [{ type: 'text', text: 'edit me please' }],- attachments: [],- createdAt,- metadata: { custom: {} }- } as ThreadMessage-}--function assistantMessage(): ThreadMessage {- return {- id: 'assistant-1',- role: 'assistant',- content: [{ type: 'text', text: 'done' }],- status: { type: 'complete', reason: 'stop' },- createdAt,- metadata: {- unstable_state: null,- unstable_annotations: [],- unstable_data: [],- steps: [],- custom: {}- }- } as ThreadMessage-}-// Mirrors chat/index.tsx: incremental runtime + messageRepository + onEdit.function IncrementalHarness({ onEdit }: { onEdit: (message: AppendMessage) => Promise<void> }) {const repository = ExportedMessageRepository.fromArray([userMessage(), assistantMessage()])diff --git a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsxindex 7402bd90520..5d66c9d9d39 100644--- a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx@@ -1,4 +1,4 @@-import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import { type ThreadMessage } from '@assistant-ui/react'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -8,6 +8,7 @@ import { $activeSessionId } from '@/store/session'import { clearDismissedToolRows } from '@/store/tool-dismiss'import { $toolDisclosureStates } from '@/store/tool-view'+import { stubThreadEnvironment, stubThreadViewportSize, ThreadRuntime } from '../test-utils'import { Thread } from '../thread'import { formatTimelineRange } from '../thread/timestamp'@@ -25,6 +26,7 @@ const createdAt = new Date('2026-06-03T00:00:00.000Z')const resizeObservers = new Set<TestResizeObserver>()+// This suite drives resizes by hand, so it needs observers it can reach.class TestResizeObserver {private target: Element | null = null@@ -43,38 +45,9 @@ class TestResizeObserver {}}+stubThreadEnvironment()+stubThreadViewportSize()vi.stubGlobal('ResizeObserver', TestResizeObserver)-vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0)-)-vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))--Element.prototype.scrollTo = function scrollTo() {}--Element.prototype.animate = function animate() {- return {- cancel: () => {},- finished: Promise.resolve()- } as unknown as Animation-}--function stubOffsetDimension(- prop: 'offsetHeight' | 'offsetWidth',- clientProp: 'clientHeight' | 'clientWidth',- fallback: number-) {- const previous = Object.getOwnPropertyDescriptor(HTMLElement.prototype, prop)-- Object.defineProperty(HTMLElement.prototype, prop, {- configurable: true,- get() {- return previous?.get?.call(this) || (this as HTMLElement)[clientProp] || fallback- }- })-}--stubOffsetDimension('offsetWidth', 'clientWidth', 800)-stubOffsetDimension('offsetHeight', 'clientHeight', 600)// A running assistant message with two tools: a completed read_file plus a// pending terminal (no result), rendered as a flat two-row list.@@ -406,19 +379,11 @@ function movedOnMessage(): ThreadMessage {} as unknown as ThreadMessage}-function GroupHarness({ message }: { message: ThreadMessage }) {- const runtime = useExternalStoreRuntime<ThreadMessage>({- messages: [message],- isRunning: message.status?.type === 'running',- onNew: async () => {}- })-- return (- <AssistantRuntimeProvider runtime={runtime}>- <Thread />- </AssistantRuntimeProvider>- )-}+const GroupHarness = ({ message }: { message: ThreadMessage }) => (+ <ThreadRuntime messages={[message]}>+ <Thread />+ </ThreadRuntime>+)beforeEach(() => {clearAllPrompts()diff --git a/apps/desktop/src/components/chat/image-generation-placeholder.test.tsx b/apps/desktop/src/components/chat/image-generation-placeholder.test.tsxindex 312e89f0dcc..6d439afb0d1 100644--- a/apps/desktop/src/components/chat/image-generation-placeholder.test.tsx+++ b/apps/desktop/src/components/chat/image-generation-placeholder.test.tsx@@ -2,11 +2,13 @@ import { act } from 'react'import { createRoot, type Root } from 'react-dom/client'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { installWindowStateBridge, type WindowStateBridge } from '../../test/window-state'+import { DiffusionCanvas } from './image-generation-placeholder'let root: Root | null = nulllet container: HTMLDivElement | null = null-let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null+let windowState: WindowStateBridgefunction render() {container = document.createElement('div')@@ -65,29 +67,11 @@ function installRaf() {}}-function installWindowStateBridge() {- windowStateCallback = null- Object.defineProperty(window, 'hermesDesktop', {- configurable: true,- value: {- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {- windowStateCallback = callback-- return () => {- if (windowStateCallback === callback) {- windowStateCallback = null- }- }- })- }- })-}-describe('DiffusionCanvas scheduling', () => {beforeEach(() => {;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = truevi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({setTransform: vi.fn()} as unknown as CanvasRenderingContext2D)@@ -117,7 +101,7 @@ describe('DiffusionCanvas scheduling', () => {expect(raf.pending()).toBe(1)act(() => {- windowStateCallback?.({ isMinimized: true, isVisible: false })+ windowState.emit({ isMinimized: true, isVisible: false })})expect(raf.pending()).toBe(0)@@ -170,7 +154,7 @@ describe('DiffusionCanvas frame budget', () => {beforeEach(() => {;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = truevi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()})afterEach(() => {diff --git a/apps/desktop/src/components/language-switcher.test.tsx b/apps/desktop/src/components/language-switcher.test.tsxindex 3792012171a..cdd3d60318b 100644--- a/apps/desktop/src/components/language-switcher.test.tsx+++ b/apps/desktop/src/components/language-switcher.test.tsx@@ -3,22 +3,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import type { HermesConfigRecord } from '@/hermes'import { type I18nConfigClient, I18nProvider } from '@/i18n'+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'import { LanguageSwitcher } from './language-switcher'-// cmdk (the searchable list) wires a ResizeObserver and scrolls the active-// item into view — neither exists in jsdom. Stub them, matching the polyfill-// idiom in tool-approval-group.test.tsx.-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}--vi.stubGlobal('ResizeObserver', TestResizeObserver)--Element.prototype.scrollIntoView = function scrollIntoView() {}-+stubResizeObserver()+stubMenuDomApis()describe('LanguageSwitcher', () => {afterEach(() => {cleanup()diff --git a/apps/desktop/src/components/onboarding/index.test.tsx b/apps/desktop/src/components/onboarding/index.test.tsxindex ad81560e096..ef099f93e09 100644--- a/apps/desktop/src/components/onboarding/index.test.tsx+++ b/apps/desktop/src/components/onboarding/index.test.tsx@@ -2,21 +2,11 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { afterEach, describe, expect, it } from 'vitest'import { $desktopOnboarding, type DesktopOnboardingState, type OnboardingContext } from '@/store/onboarding'+import { makeOAuthProvider } from '@/test/oauth-provider'import type { OAuthProvider } from '@/types/hermes'import { Picker } from '.'-function provider(id: string, name = id): OAuthProvider {- return {- cli_command: `hermes login ${id}`,- docs_url: `https://example.com/${id}`,- flow: 'pkce',- id,- name,- status: { logged_in: false }- }-}-function setProviders(providers: OAuthProvider[]) {$desktopOnboarding.set({configured: false,@@ -57,7 +47,7 @@ afterEach(() => {describe('onboarding Picker', () => {it('features Nous Portal and hides other providers behind a disclosure', () => {- setProviders([provider('anthropic', 'Anthropic Claude'), provider('nous', 'Nous Portal')])+ setProviders([makeOAuthProvider('anthropic', 'Anthropic Claude'), makeOAuthProvider('nous', 'Nous Portal')])render(<Picker ctx={ctx} />)expect(screen.getByText('Nous Portal')).toBeTruthy()@@ -76,9 +66,9 @@ describe('onboarding Picker', () => {it('shows Fireworks first in the expanded list, ahead of other OAuth providers', () => {setProviders([- provider('openai-codex', 'OpenAI Codex / ChatGPT'),- provider('minimax-oauth', 'MiniMax'),- provider('nous', 'Nous Portal')+ makeOAuthProvider('openai-codex', 'OpenAI Codex / ChatGPT'),+ makeOAuthProvider('minimax-oauth', 'MiniMax'),+ makeOAuthProvider('nous', 'Nous Portal')])render(<Picker ctx={ctx} />)fireEvent.click(screen.getByRole('button', { name: 'Other providers' }))@@ -96,7 +86,10 @@ describe('onboarding Picker', () => {})it('shows every provider directly when Nous Portal is absent', () => {- setProviders([provider('anthropic', 'Anthropic Claude'), provider('openai-codex', 'OpenAI Codex / ChatGPT')])+ setProviders([+ makeOAuthProvider('anthropic', 'Anthropic Claude'),+ makeOAuthProvider('openai-codex', 'OpenAI Codex / ChatGPT')+ ])render(<Picker ctx={ctx} />)expect(screen.getByText('Fireworks AI')).toBeTruthy()@@ -107,7 +100,7 @@ describe('onboarding Picker', () => {})it('offers "choose later" on first run and persists the skip', () => {- setProviders([provider('nous', 'Nous Portal')])+ setProviders([makeOAuthProvider('nous', 'Nous Portal')])render(<Picker ctx={ctx} />)const skip = screen.getByRole('button', { name: "I'll choose a provider later" })@@ -119,7 +112,7 @@ describe('onboarding Picker', () => {})it('hides "choose later" in manual (add-provider) mode', () => {- setProviders([provider('nous', 'Nous Portal')])+ setProviders([makeOAuthProvider('nous', 'Nous Portal')])$desktopOnboarding.set({ ...$desktopOnboarding.get(), manual: true })render(<Picker ctx={ctx} />)diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/floating-panes.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/floating-panes.test.tsxindex 62b825659f1..8306b14f710 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/floating-panes.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/floating-panes.test.tsx@@ -6,28 +6,17 @@* floating-rect.test.ts).*/-import { act, type ReactNode } from 'react'-import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { registry } from '@/contrib/registry'+import { reactRoot } from '@/test/react-root'import { FloatingPanes } from './floating-panes'-let root: null | Root = null-let container: HTMLDivElement | null = null+const mount = reactRoot()let disposers: (() => void)[] = []-function render(ui: ReactNode) {- container = document.createElement('div')- document.body.append(container)- root = createRoot(container)-- act(() => {- root!.render(ui)- })-}-const card = () => document.querySelector<HTMLElement>('[data-floating-pane="hud"]')const grab = () => card()!.querySelector('header')!@@ -74,20 +63,14 @@ describe('FloatingPanes (live DOM)', () => {})afterEach(() => {- if (root) {- act(() => root!.unmount())- }-- container?.remove()- root = null- container = null+ mount.unmount()disposers.forEach(dispose => dispose())disposers = []})it('mounts a fixed card in the anchored corner with the pane body inside', () => {registerHud({ anchor: 'top-right', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)const el = card()!@@ -102,14 +85,14 @@ describe('FloatingPanes (live DOM)', () => {it('renders nothing for a non-floating placement', () => {registerHud({ placement: 'right', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)expect(card()).toBeNull()})it('moves with a real pointer drag on the header', () => {registerHud({ anchor: 'top-left', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)expect(card()!.style.left).toBe('12px')@@ -123,7 +106,7 @@ describe('FloatingPanes (live DOM)', () => {it('persists the dragged position across a remount', () => {registerHud({ anchor: 'top-left', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)pointer(grab(), 'pointerdown', 100, 100)pointer(grab(), 'pointermove', 300, 300)@@ -131,16 +114,15 @@ describe('FloatingPanes (live DOM)', () => {const moved = card()!.style.left- act(() => root!.unmount())- container!.remove()- render(<FloatingPanes />)+ mount.unmount()+ mount.render(<FloatingPanes />)expect(card()!.style.left).toBe(moved)})it('rides the right edge when the window shrinks', () => {registerHud({ anchor: 'top-right', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)expect(card()!.style.left).toBe('1204px')@@ -152,7 +134,7 @@ describe('FloatingPanes (live DOM)', () => {it('never lets a drag push the card under the titlebar', () => {registerHud({ anchor: 'top-left', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)pointer(grab(), 'pointerdown', 100, 100)pointer(grab(), 'pointermove', 100, -900)@@ -163,7 +145,7 @@ describe('FloatingPanes (live DOM)', () => {it('collapses to the header and drops the body, and does not drag from the button', () => {registerHud({ anchor: 'top-left', height: '132px', placement: 'floating', width: '224px' })- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)const before = card()!.style.leftconst toggle = card()!.querySelector('button')!@@ -201,7 +183,7 @@ describe('FloatingPanes (live DOM)', () => {}))- render(<FloatingPanes />)+ mount.render(<FloatingPanes />)expect(document.querySelectorAll('[data-floating-pane]').length).toBe(2)})diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsxindex 40f6e9fcfcd..9f5e2baa8ce 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx@@ -1,8 +1,9 @@import { act, cleanup, fireEvent, render } from '@testing-library/react'-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'import { registry } from '@/contrib/registry'+import { stubResizeObserver } from '@/test/jsdom'import { group, split } from '../model'import { $hiddenTreePanes, $layoutTree, $narrowViewport, declareDefaultTree } from '../store'@@ -15,14 +16,8 @@ import { NarrowOverlays } from './narrow-overlays'// edge overlay must mirror the zone's tab strip so the docked pane stays// reachable — not just the zone's first pane.-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-beforeAll(() => {- vi.stubGlobal('ResizeObserver', TestResizeObserver)+ stubResizeObserver()})const disposers: (() => void)[] = []diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tool-panel-close.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tool-panel-close.test.tsxindex db5c2a70a91..49f8e4824e0 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/tool-panel-close.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tool-panel-close.test.tsx@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { registry } from '@/contrib/registry'+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'import { group, split } from '../model'import {@@ -19,20 +20,11 @@ import { TreeGroup } from './tree-group'// doesn't close it". Renders the REAL zone renderer and opens the REAL// context menu.-class TestResizeObserver {- observe() {}- unobserve() {}- disconnect() {}-}-beforeAll(() => {- vi.stubGlobal('ResizeObserver', TestResizeObserver)+ stubResizeObserver()+ stubMenuDomApis()// jsdom lacks CSS.escape, which tab-strip-scroll uses in a layout effect.vi.stubGlobal('CSS', { ...globalThis.CSS, escape: (value: string) => value })- Element.prototype.hasPointerCapture ??= () => false- Element.prototype.setPointerCapture ??= () => undefined- Element.prototype.releasePointerCapture ??= () => undefined- HTMLElement.prototype.scrollIntoView ??= () => undefined})const disposers: (() => void)[] = []diff --git a/apps/desktop/src/components/pet/pet-sprite.test.tsx b/apps/desktop/src/components/pet/pet-sprite.test.tsxindex 2d0ac017601..719269bf18f 100644--- a/apps/desktop/src/components/pet/pet-sprite.test.tsx+++ b/apps/desktop/src/components/pet/pet-sprite.test.tsx@@ -1,5 +1,4 @@-import { act, type ReactNode } from 'react'-import { createRoot, type Root } from 'react-dom/client'+import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'vi.mock('@/store/pet', () => {@@ -19,6 +18,10 @@ vi.mock('@/store/pet', () => {}})+import { reactRoot } from '@/test/react-root'++import { installWindowStateBridge, setDocumentHidden, type WindowStateBridge } from '../../test/window-state'+import { PetSprite } from './pet-sprite'const INFO = {@@ -32,56 +35,10 @@ const INFO = {stateRows: ['idle']}-let root: Root | null = null-let container: HTMLDivElement | null = null-let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null+const mount = reactRoot()+let windowState: WindowStateBridgelet drawImage: ReturnType<typeof vi.fn>-function render(ui: ReactNode) {- container = document.createElement('div')- document.body.append(container)- root = createRoot(container)-- act(() => {- root!.render(ui)- })-}--function cleanup() {- if (root) {- act(() => {- root!.unmount()- })- }-- container?.remove()- root = null- container = null-}--function setVisibility(hidden: boolean) {- Object.defineProperty(document, 'hidden', { configurable: true, value: hidden })- Object.defineProperty(document, 'visibilityState', { configurable: true, value: hidden ? 'hidden' : 'visible' })-}--function installWindowStateBridge() {- windowStateCallback = null- Object.defineProperty(window, 'hermesDesktop', {- configurable: true,- value: {- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {- windowStateCallback = callback-- return () => {- if (windowStateCallback === callback) {- windowStateCallback = null- }- }- })- }- })-}-function installRaf() {let nextId = 1const frames = new Map<number, FrameRequestCallback>()@@ -122,10 +79,10 @@ describe('PetSprite RAF scheduling', () => {beforeEach(() => {;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = truevi.useFakeTimers()- setVisibility(false)+ setDocumentHidden(false)Object.defineProperty(window, 'devicePixelRatio', { configurable: true, value: 1 })vi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()vi.stubGlobal('Image',class extends EventTarget {@@ -143,18 +100,18 @@ describe('PetSprite RAF scheduling', () => {})afterEach(() => {- cleanup()+ mount.unmount()vi.useRealTimers()vi.unstubAllGlobals()vi.restoreAllMocks()- setVisibility(false)+ setDocumentHidden(false)delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})it('sleeps between visible sprite frames instead of chaining RAFs', () => {const raf = installRaf()- render(<PetSprite info={INFO} />)+ mount.render(<PetSprite info={INFO} />)expect(raf.request).toHaveBeenCalledTimes(1)@@ -177,9 +134,9 @@ describe('PetSprite RAF scheduling', () => {Object.defineProperty(window, 'devicePixelRatio', { configurable: true, value: 2 })const raf = installRaf()- render(<PetSprite info={INFO} />)+ mount.render(<PetSprite info={INFO} />)- const canvas = container?.querySelector('canvas')+ const canvas = mount.container?.querySelector('canvas')expect(canvas).not.toBeNull()expect(canvas?.width).toBe(32)@@ -197,19 +154,19 @@ describe('PetSprite RAF scheduling', () => {it('cancels pending RAF work while the Electron window is paused and resumes when visible', () => {const raf = installRaf()- render(<PetSprite info={INFO} />)+ mount.render(<PetSprite info={INFO} />)expect(raf.request).toHaveBeenCalledTimes(1)act(() => {- windowStateCallback?.({ isMinimized: true, isVisible: false })+ windowState.emit({ isMinimized: true, isVisible: false })})expect(raf.cancel).toHaveBeenCalledTimes(1)expect(raf.pending()).toBe(0)act(() => {- windowStateCallback?.({ isMinimized: false, isVisible: true })+ windowState.emit({ isMinimized: false, isVisible: true })})expect(raf.request).toHaveBeenCalledTimes(2)@@ -218,7 +175,7 @@ describe('PetSprite RAF scheduling', () => {it('suspends while unfocused, resumes on focus, and leaves no work after unmount', () => {const raf = installRaf()- render(<PetSprite info={INFO} />)+ mount.render(<PetSprite info={INFO} />)act(() => window.dispatchEvent(new Event('blur')))expect(raf.pending()).toBe(0)@@ -229,7 +186,7 @@ describe('PetSprite RAF scheduling', () => {act(() => raf.runNext(0))expect(vi.getTimerCount()).toBe(1)- cleanup()+ mount.unmount()expect(raf.pending()).toBe(0)expect(vi.getTimerCount()).toBe(0)@@ -243,7 +200,7 @@ describe('PetSprite RAF scheduling', () => {it('keeps the intentionally non-activating pop-out overlay animated while unfocused', () => {const raf = installRaf()- render(<PetSprite info={INFO} pauseWhenUnfocused={false} />)+ mount.render(<PetSprite info={INFO} pauseWhenUnfocused={false} />)act(() => window.dispatchEvent(new Event('blur')))expect(raf.pending()).toBe(1)@@ -261,7 +218,7 @@ describe('PetSprite RAF scheduling', () => {vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctxMock)- render(<PetSprite info={INFO} />)+ mount.render(<PetSprite info={INFO} />)act(() => raf.runNext(0))// Petdex sheets are illustration frames, not pixel art — nearest-neighbourdiff --git a/apps/desktop/src/components/pet/use-pet-roam.test.tsx b/apps/desktop/src/components/pet/use-pet-roam.test.tsxindex c906a8a2976..c306800ecfa 100644--- a/apps/desktop/src/components/pet/use-pet-roam.test.tsx+++ b/apps/desktop/src/components/pet/use-pet-roam.test.tsx@@ -1,5 +1,4 @@-import { act, type ReactNode, type RefObject, useRef } from 'react'-import { createRoot, type Root } from 'react-dom/client'+import { act, type RefObject, useRef } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'vi.mock('@/store/pet', () => ({@@ -7,56 +6,14 @@ vi.mock('@/store/pet', () => ({$petRoamDir: { set: () => undefined }}))-import { usePetRoam } from './use-pet-roam'--let root: Root | null = null-let container: HTMLDivElement | null = null-let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null--function render(ui: ReactNode) {- container = document.createElement('div')- document.body.append(container)- root = createRoot(container)-- act(() => {- root!.render(ui)- })-}--function cleanup() {- if (root) {- act(() => {- root!.unmount()- })- }+import { reactRoot } from '@/test/react-root'- container?.remove()- root = null- container = null-}+import { installWindowStateBridge, setDocumentHidden, type WindowStateBridge } from '../../test/window-state'-function setVisibility(hidden: boolean) {- Object.defineProperty(document, 'hidden', { configurable: true, value: hidden })- Object.defineProperty(document, 'visibilityState', { configurable: true, value: hidden ? 'hidden' : 'visible' })-}+import { usePetRoam } from './use-pet-roam'-function installWindowStateBridge() {- windowStateCallback = null- Object.defineProperty(window, 'hermesDesktop', {- configurable: true,- value: {- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {- windowStateCallback = callback-- return () => {- if (windowStateCallback === callback) {- windowStateCallback = null- }- }- })- }- })-}+const mount = reactRoot()+let windowState: WindowStateBridgefunction installRaf() {const request = vi.fn((_callback: FrameRequestCallback) => 1)@@ -89,9 +46,9 @@ describe('usePetRoam RAF scheduling', () => {beforeEach(() => {;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = truevi.useFakeTimers()- setVisibility(false)+ setDocumentHidden(false)vi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()vi.spyOn(Math, 'random').mockReturnValue(0)vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({bottom: 164,@@ -107,17 +64,17 @@ describe('usePetRoam RAF scheduling', () => {})afterEach(() => {- cleanup()+ mount.unmount()vi.useRealTimers()vi.restoreAllMocks()- setVisibility(false)+ setDocumentHidden(false)delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop})it('uses a pause timer, not RAF, while dwelling at idle', () => {const raf = installRaf()- render(<RoamHarness />)+ mount.render(<RoamHarness />)expect(raf.request).not.toHaveBeenCalled()expect(vi.getTimerCount()).toBe(1)@@ -126,16 +83,16 @@ describe('usePetRoam RAF scheduling', () => {it('clears the pause wakeup while the Electron window is paused and restarts it when visible', () => {const raf = installRaf()- render(<RoamHarness />)+ mount.render(<RoamHarness />)expect(vi.getTimerCount()).toBe(1)- windowStateCallback?.({ isMinimized: true, isVisible: false })+ windowState.emit({ isMinimized: true, isVisible: false })expect(raf.cancel).not.toHaveBeenCalled()expect(raf.request).not.toHaveBeenCalled()expect(vi.getTimerCount()).toBe(0)- windowStateCallback?.({ isMinimized: false, isVisible: true })+ windowState.emit({ isMinimized: false, isVisible: true })expect(raf.request).not.toHaveBeenCalled()expect(vi.getTimerCount()).toBe(1)@@ -144,7 +101,7 @@ describe('usePetRoam RAF scheduling', () => {it('suspends idle movement while unfocused and cleans up its wake timer on unmount', () => {const raf = installRaf()- render(<RoamHarness />)+ mount.render(<RoamHarness />)expect(vi.getTimerCount()).toBe(1)act(() => window.dispatchEvent(new Event('blur')))@@ -153,7 +110,7 @@ describe('usePetRoam RAF scheduling', () => {act(() => window.dispatchEvent(new Event('focus')))expect(vi.getTimerCount()).toBe(1)- cleanup()+ mount.unmount()expect(vi.getTimerCount()).toBe(0)act(() => {diff --git a/apps/desktop/src/components/ui/status-pulse.test.tsx b/apps/desktop/src/components/ui/status-pulse.test.tsxindex 8f496229289..24f32ccc053 100644--- a/apps/desktop/src/components/ui/status-pulse.test.tsx+++ b/apps/desktop/src/components/ui/status-pulse.test.tsx@@ -1,6 +1,8 @@import { act, cleanup, render } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { installWindowStateBridge, type WindowStateBridge } from '../../test/window-state'+import { StatusPulse } from './status-pulse'interface PlayedAnimation {@@ -9,12 +11,7 @@ interface PlayedAnimation {options: KeyframeAnimationOptions}-interface WindowStatePayload {- isMinimized?: boolean- isVisible?: boolean-}--let windowStateCallback: ((payload: WindowStatePayload) => void) | undefined+let windowState: WindowStateBridgefunction installMatchMedia(matches: boolean) {vi.stubGlobal(@@ -29,20 +26,6 @@ function installMatchMedia(matches: boolean) {)}-function installWindowStateBridge() {- const off = vi.fn()-- window.hermesDesktop = {- onWindowStateChanged: vi.fn(callback => {- windowStateCallback = callback-- return off- })- } as unknown as typeof window.hermesDesktop-- return off-}-describe('StatusPulse', () => {const played: PlayedAnimation[] = []@@ -50,7 +33,7 @@ describe('StatusPulse', () => {vi.useFakeTimers()vi.spyOn(window.document, 'hasFocus').mockReturnValue(true)installMatchMedia(false)- installWindowStateBridge()+ windowState = installWindowStateBridge()Object.defineProperty(HTMLElement.prototype, 'animate', {configurable: true,value: (keyframes: Keyframe[], options: KeyframeAnimationOptions) => {@@ -71,7 +54,6 @@ describe('StatusPulse', () => {afterEach(() => {cleanup()played.length = 0- windowStateCallback = undefinedReflect.deleteProperty(HTMLElement.prototype, 'animate')delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktopvi.useRealTimers()@@ -98,12 +80,12 @@ describe('StatusPulse', () => {})it('cancels scheduled work while minimized and restarts once visible', () => {- const offWindowState = installWindowStateBridge()+ windowState = installWindowStateBridge()const mounted = render(<StatusPulse kind="opacity" />)expect(played).toHaveLength(1)- act(() => windowStateCallback?.({ isMinimized: true, isVisible: false }))+ act(() => windowState.emit({ isMinimized: true, isVisible: false }))expect(played[0]?.cancel).toHaveBeenCalledTimes(1)expect(vi.getTimerCount()).toBe(0)@@ -111,12 +93,12 @@ describe('StatusPulse', () => {act(() => vi.advanceTimersByTime(5_000))expect(played).toHaveLength(1)- act(() => windowStateCallback?.({ isMinimized: false, isVisible: true }))+ act(() => windowState.emit({ isMinimized: false, isVisible: true }))expect(played).toHaveLength(2)mounted.unmount()expect(played[1]?.cancel).toHaveBeenCalledTimes(1)- expect(offWindowState).toHaveBeenCalledTimes(1)+ expect(windowState.off).toHaveBeenCalledTimes(1)expect(vi.getTimerCount()).toBe(0)})diff --git a/apps/desktop/src/lib/budgeted-loop.test.ts b/apps/desktop/src/lib/budgeted-loop.test.tsindex 3741518c65c..edcc027e87d 100644--- a/apps/desktop/src/lib/budgeted-loop.test.ts+++ b/apps/desktop/src/lib/budgeted-loop.test.ts@@ -1,8 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { installWindowStateBridge, type WindowStateBridge } from '../test/window-state'+import { createBudgetedLoop } from './budgeted-loop'-let windowStateCallback: ((payload: { isMinimized?: boolean; isVisible?: boolean }) => void) | null = null+let windowState: WindowStateBridgefunction installRaf() {let nextId = 1@@ -38,28 +40,10 @@ function installRaf() {}}-function installWindowStateBridge() {- windowStateCallback = null- Object.defineProperty(window, 'hermesDesktop', {- configurable: true,- value: {- onWindowStateChanged: vi.fn((callback: typeof windowStateCallback) => {- windowStateCallback = callback-- return () => {- if (windowStateCallback === callback) {- windowStateCallback = null- }- }- })- }- })-}-describe('createBudgetedLoop', () => {beforeEach(() => {vi.spyOn(document, 'hasFocus').mockReturnValue(true)- installWindowStateBridge()+ windowState = installWindowStateBridge()})afterEach(() => {@@ -100,10 +84,10 @@ describe('createBudgetedLoop', () => {window.dispatchEvent(new Event('focus'))expect(raf.pending()).toBe(1)- windowStateCallback?.({ isMinimized: true, isVisible: false })+ windowState.emit({ isMinimized: true, isVisible: false })expect(raf.pending()).toBe(0)- windowStateCallback?.({ isMinimized: false, isVisible: true })+ windowState.emit({ isMinimized: false, isVisible: true })expect(raf.pending()).toBe(1)loop.dispose()diff --git a/apps/desktop/src/lib/session-branch-tree.test.ts b/apps/desktop/src/lib/session-branch-tree.test.tsindex acdc0a3abf9..8de1803012b 100644--- a/apps/desktop/src/lib/session-branch-tree.test.ts+++ b/apps/desktop/src/lib/session-branch-tree.test.ts@@ -2,25 +2,12 @@ import { describe, expect, it } from 'vitest'import type { SessionInfo } from '@/types/hermes'+import { makeSessionInfo } from '../test/session-info'+import { flattenSessionsWithBranches } from './session-branch-tree'const session = (id: string, overrides: Partial<SessionInfo> = {}): SessionInfo =>- ({- ended_at: null,- id,- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 1,- model: null,- output_tokens: 0,- preview: null,- source: 'cli',- started_at: 0,- title: id,- tool_call_count: 0,- ...overrides- }) as SessionInfo+ makeSessionInfo({ id, message_count: 1, source: 'cli', title: id, ...overrides })describe('flattenSessionsWithBranches', () => {it('nests branch rows under their parent with tree stems', () => {diff --git a/apps/desktop/src/lib/session-date-groups.test.ts b/apps/desktop/src/lib/session-date-groups.test.tsindex 1bcaf587ece..b485d053a1c 100644--- a/apps/desktop/src/lib/session-date-groups.test.ts+++ b/apps/desktop/src/lib/session-date-groups.test.ts@@ -2,26 +2,13 @@ import { describe, expect, it } from 'vitest'import type { SessionInfo } from '@/types/hermes'+import { makeSessionInfo } from '../test/session-info'+import type { SidebarSessionEntry } from './session-branch-tree'import { groupEntriesByRecency, toSessionRows } from './session-date-groups'const session = (id: string, overrides: Partial<SessionInfo> = {}): SessionInfo =>- ({- ended_at: null,- id,- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 1,- model: null,- output_tokens: 0,- preview: null,- source: 'cli',- started_at: 0,- title: id,- tool_call_count: 0,- ...overrides- }) as SessionInfo+ makeSessionInfo({ id, message_count: 1, source: 'cli', title: id, ...overrides })const entry = (s: SessionInfo, branchStem?: string): SidebarSessionEntry =>branchStem ? { branchStem, session: s } : { session: s }diff --git a/apps/desktop/src/store/approval-mode.test.ts b/apps/desktop/src/store/approval-mode.test.tsindex 3f5112df816..3ec7a6daede 100644--- a/apps/desktop/src/store/approval-mode.test.ts+++ b/apps/desktop/src/store/approval-mode.test.ts@@ -1,5 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'+import { deferred } from '../test/deferred'+import {$approvalModes,approvalModeForProfile,@@ -8,18 +10,6 @@ import {syncApprovalModeForProfile} from './approval-mode'-function deferred<T>() {- let resolve!: (value: T) => void- let reject!: (error: unknown) => void-- const promise = new Promise<T>((res, rej) => {- resolve = res- reject = rej- })-- return { promise, reject, resolve }-}-describe('profile-scoped approval mode cache', () => {beforeEach(() => $approvalModes.set({}))diff --git a/apps/desktop/src/store/cron-model-impact.test.ts b/apps/desktop/src/store/cron-model-impact.test.tsindex 04f5e54d565..f854808809c 100644--- a/apps/desktop/src/store/cron-model-impact.test.ts+++ b/apps/desktop/src/store/cron-model-impact.test.ts@@ -18,6 +18,8 @@ import {setMainModelAssignment} from '@/store/cron-model-impact'+import { deferred } from '../test/deferred'+function response(impact: ModelAssignmentResponse['cron_model_impact']): ModelAssignmentResponse {return {ok: true,@@ -38,16 +40,6 @@ function positive(name = 'Morning summary'): ModelAssignmentResponse['cron_model}}-function deferred<T>() {- let resolve!: (value: T) => void-- const promise = new Promise<T>(res => {- resolve = res- })-- return { promise, resolve }-}-beforeEach(() => {setModelAssignment.mockReset()getApiRequestProfile.mockReset()diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.tsindex f9696599206..d5392634d50 100644--- a/apps/desktop/src/store/onboarding.test.ts+++ b/apps/desktop/src/store/onboarding.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import * as notifications from '@/store/notifications'+import { makeOAuthProvider } from '@/test/oauth-provider'import type { OAuthProvider } from '@/types/hermes'import {@@ -13,17 +14,6 @@ import {submitOnboardingCode} from './onboarding'-function provider(id: string, name = id): OAuthProvider {- return {- cli_command: `hermes login ${id}`,- docs_url: `https://example.com/${id}`,- flow: 'pkce',- id,- name,- status: { logged_in: false }- }-}-function baseState(overrides: Partial<DesktopOnboardingState> = {}): DesktopOnboardingState {return {configured: false,@@ -103,14 +93,14 @@ describe('refreshOnboarding', () => {it('refreshes OAuth providers again when onboarding was explicitly requested', async () => {const api = vi.fn(async ({ path }: { path: string }) => {if (path === '/api/providers/oauth') {- return { providers: [provider('fresh')] }+ return { providers: [makeOAuthProvider('fresh')] }}throw new Error(`unexpected api path: ${path}`)})installApiMock(api)- $desktopOnboarding.set(baseState({ providers: [provider('cached')] }))+ $desktopOnboarding.set(baseState({ providers: [makeOAuthProvider('cached')] }))requestDesktopOnboarding('Need provider setup')const ready = await refreshOnboarding(onboardingContext(emptyOpenRouterGateway()))@@ -125,14 +115,14 @@ describe('refreshOnboarding', () => {it('keeps cached providers when onboarding was not re-requested', async () => {const api = vi.fn(async ({ path }: { path: string }) => {if (path === '/api/providers/oauth') {- return { providers: [provider('fresh')] }+ return { providers: [makeOAuthProvider('fresh')] }}throw new Error(`unexpected api path: ${path}`)})installApiMock(api)- $desktopOnboarding.set(baseState({ providers: [provider('cached')] }))+ $desktopOnboarding.set(baseState({ providers: [makeOAuthProvider('cached')] }))const ready = await refreshOnboarding(onboardingContext(emptyOpenRouterGateway()))@@ -144,7 +134,7 @@ describe('refreshOnboarding', () => {it('does not downgrade configured=true on fallback-only readiness failures', async () => {const api = vi.fn(async ({ path }: { path: string }) => {if (path === '/api/providers/oauth') {- return { providers: [provider('fresh')] }+ return { providers: [makeOAuthProvider('fresh')] }}throw new Error(`unexpected api path: ${path}`)@@ -156,7 +146,7 @@ describe('refreshOnboarding', () => {$desktopOnboarding.set(baseState({configured: true,- providers: [provider('cached')],+ providers: [makeOAuthProvider('cached')],reason: null,requested: false})@@ -179,7 +169,7 @@ describe('refreshOnboarding', () => {$desktopOnboarding.set(baseState({configured: true,- providers: [provider('cached')],+ providers: [makeOAuthProvider('cached')],reason: null,requested: false})@@ -202,7 +192,7 @@ describe('refreshOnboarding', () => {$desktopOnboarding.set(baseState({configured: true,- providers: [provider('cached')],+ providers: [makeOAuthProvider('cached')],reason: null,requested: false})@@ -236,7 +226,7 @@ describe('refreshOnboarding', () => {it('does not preserve configured when onboarding was explicitly requested', async () => {const api = vi.fn(async ({ path }: { path: string }) => {if (path === '/api/providers/oauth') {- return { providers: [provider('fresh')] }+ return { providers: [makeOAuthProvider('fresh')] }}throw new Error(`unexpected api path: ${path}`)@@ -246,7 +236,7 @@ describe('refreshOnboarding', () => {$desktopOnboarding.set(baseState({configured: true,- providers: [provider('cached')],+ providers: [makeOAuthProvider('cached')],reason: null,requested: true})@@ -263,7 +253,7 @@ describe('refreshOnboarding', () => {it('still surfaces onboarding when fallback failure happens before configured state', async () => {const api = vi.fn(async ({ path }: { path: string }) => {if (path === '/api/providers/oauth') {- return { providers: [provider('fresh')] }+ return { providers: [makeOAuthProvider('fresh')] }}throw new Error(`unexpected api path: ${path}`)@@ -305,7 +295,7 @@ describe('refreshOnboarding', () => {await vi.waitFor(() => expect(api).toHaveBeenCalledTimes(1))- resolveProviders({ providers: [provider('shared')] })+ resolveProviders({ providers: [makeOAuthProvider('shared')] })await Promise.all([first, second])expect($desktopOnboarding.get().providers?.map(p => p.id)).toEqual(['shared'])@@ -380,7 +370,7 @@ describe('OAuth onboarding', () => {baseState({flow: {status: 'awaiting_user',- provider: provider('nous', 'Nous Portal'),+ provider: makeOAuthProvider('nous', 'Nous Portal'),start: {auth_url: 'https://portal.example/auth',expires_in: 600,@@ -458,7 +448,7 @@ describe('OAuth onboarding', () => {baseState({flow: {status: 'awaiting_user',- provider: provider('nous', 'Nous Portal'),+ provider: makeOAuthProvider('nous', 'Nous Portal'),start: {auth_url: 'https://portal.example/auth',expires_in: 600,diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.tsindex da089502e8d..fb822d69d13 100644--- a/apps/desktop/src/store/profile-agent-activation.test.ts+++ b/apps/desktop/src/store/profile-agent-activation.test.ts@@ -3,6 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { HermesConnection } from '@/global'+import { deferred } from '../test/deferred'+// Registry-agent activation (ensureGatewayAgent — the SDK ensureAgent door).// Two regressions pinned here:// 1. Activating an ALREADY-OPEN registry agent must still resync@@ -47,16 +49,6 @@ const getConnection = vi.fn<(profile?: string | null) => Promise<HermesConnectioconst getConnectionFor =vi.fn<(payload: { connectionId?: null | string; profile?: null | string }) => Promise<HermesConnection>>()-function deferred(): { promise: Promise<void>; resolve: () => void } {- let resolve!: () => void-- const promise = new Promise<void>(r => {- resolve = r- })-- return { promise, resolve }-}-beforeEach(() => {getConnection.mockReset()getConnectionFor.mockReset()diff --git a/apps/desktop/src/store/session-color.test.ts b/apps/desktop/src/store/session-color.test.tsindex 30bb96c6525..964d0a18761 100644--- a/apps/desktop/src/store/session-color.test.ts+++ b/apps/desktop/src/store/session-color.test.ts@@ -1,34 +1,13 @@import { afterEach, describe, expect, it } from 'vitest'-import type { ProjectInfo, SessionInfo } from '@/types/hermes'+import type { ProjectInfo } from '@/types/hermes'++import { makeCwdSession } from '../test/session-info'import { $projects } from './projects'import { $sessions } from './session'import { $sessionColorById, $sessionColorOverrides, sessionColorFor, setSessionColorOverride } from './session-color'-let nextId = 0--function makeSession(cwd: null | string, overrides: Partial<SessionInfo> = {}): SessionInfo {- return {- archived: false,- cwd,- ended_at: null,- id: `s${nextId++}`,- input_tokens: 0,- is_active: false,- last_active: 1_000,- message_count: 1,- model: 'claude',- output_tokens: 0,- preview: null,- source: 'cli',- started_at: 1_000,- title: null,- tool_call_count: 0,- ...overrides- }-}-function makeProject(id: string, folders: string[], color: null | string): ProjectInfo {return {archived: false,@@ -53,8 +32,8 @@ afterEach(() => {describe('$sessionColorById', () => {it('maps each session under a colored project to that color, keyed by live id', () => {- const a = makeSession('/www/app/src', { git_repo_root: '/www/app' })- const b = makeSession('/other/place')+ const a = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })+ const b = makeCwdSession('/other/place')$projects.set([makeProject('p_app', ['/www/app'], '#4a9eff')])$sessions.set([a, b])@@ -67,7 +46,7 @@ describe('$sessionColorById', () => {})it('omits a session whose project has no color', () => {- const a = makeSession('/www/app', { git_repo_root: '/www/app' })+ const a = makeCwdSession('/www/app', { git_repo_root: '/www/app' })$projects.set([makeProject('p_app', ['/www/app'], null)])$sessions.set([a])@@ -76,7 +55,7 @@ describe('$sessionColorById', () => {})it('recomputes when the projects list changes (color applied later)', () => {- const a = makeSession('/www/app', { git_repo_root: '/www/app' })+ const a = makeCwdSession('/www/app', { git_repo_root: '/www/app' })$sessions.set([a])$projects.set([makeProject('p_app', ['/www/app'], null)])@@ -89,7 +68,7 @@ describe('$sessionColorById', () => {describe('$sessionColorOverrides', () => {it('an override wins over the inherited project color', () => {- const a = makeSession('/www/app', { git_repo_root: '/www/app' })+ const a = makeCwdSession('/www/app', { git_repo_root: '/www/app' })$projects.set([makeProject('p_app', ['/www/app'], '#4a9eff')])$sessions.set([a])@@ -99,7 +78,7 @@ describe('$sessionColorOverrides', () => {})it('clearing an override falls back to the project color', () => {- const a = makeSession('/www/app', { git_repo_root: '/www/app' })+ const a = makeCwdSession('/www/app', { git_repo_root: '/www/app' })$projects.set([makeProject('p_app', ['/www/app'], '#4a9eff')])$sessions.set([a])@@ -114,8 +93,8 @@ describe('$sessionColorOverrides', () => {it('keys on the durable lineage id so a color survives compression', () => {// The live id rotates on auto-compression; the override is stored against the// lineage root, so the continuation tip still resolves to the same color.- const root = makeSession('/x', { id: 'root' })- const tip = makeSession('/x', { id: 'tip', _lineage_root_id: 'root' })+ const root = makeCwdSession('/x', { id: 'root' })+ const tip = makeCwdSession('/x', { id: 'tip', _lineage_root_id: 'root' })setSessionColorOverride('root', '#abcdef')@@ -126,7 +105,7 @@ describe('$sessionColorOverrides', () => {describe('sessionColorFor', () => {it('reads a single session through the same shared map', () => {- const a = makeSession('/www/app', { git_repo_root: '/www/app' })+ const a = makeCwdSession('/www/app', { git_repo_root: '/www/app' })$projects.set([makeProject('p_app', ['/www/app'], '#5865f2')])$sessions.set([a])diff --git a/apps/desktop/src/store/session-unread.test.ts b/apps/desktop/src/store/session-unread.test.tsindex f1d0224c9b0..1af657415cd 100644--- a/apps/desktop/src/store/session-unread.test.ts+++ b/apps/desktop/src/store/session-unread.test.ts@@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it } from 'vitest'import type { SessionInfo } from '@/types/hermes'+import { makeSessionInfo } from '../test/session-info'+import { $activeGatewayProfile } from './profile'import {$cronSessions,@@ -20,24 +22,7 @@ import {markSessionUnreadFinished} from './session-unread'-const session = (over: Partial<SessionInfo>): SessionInfo => ({- archived: false,- cwd: null,- ended_at: null,- id: 'live',- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 0,- model: null,- output_tokens: 0,- preview: null,- source: null,- started_at: 0,- title: null,- tool_call_count: 0,- ...over-})+const session = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ id: 'live', ...over })function resetAll() {clearAllSessionStates()diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex ab7961dc038..3ebb0c56947 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -15,6 +15,8 @@ vi.mock('@/hermes', () => ({setSessionUnreadRemote: (id: string, unread: boolean, profile?: null | string) => setUnreadRemote(id, unread, profile)}))+import { makeSessionInfo } from '../test/session-info'+import {$activeSessionId,$connection,@@ -49,24 +51,7 @@ import {publishSessionState} from './session-states'-const session = (over: Partial<SessionInfo>): SessionInfo => ({- archived: false,- cwd: null,- ended_at: null,- id: 'live',- input_tokens: 0,- is_active: false,- last_active: 0,- message_count: 0,- model: null,- output_tokens: 0,- preview: null,- source: null,- started_at: 0,- title: null,- tool_call_count: 0,- ...over-})+const session = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ id: 'live', ...over })describe('computed $attentionSessionIds', () => {beforeEach(() => {diff --git a/apps/desktop/src/test/deferred.ts b/apps/desktop/src/test/deferred.tsnew file mode 100644index 00000000000..b5c8913dcf5--- /dev/null+++ b/apps/desktop/src/test/deferred.ts@@ -0,0 +1,16 @@+/** A promise plus the handle that settles it.+ *+ * For tests that need a call to stay in flight — asserting the pending UI,+ * proving a second call is coalesced or ignored, ordering two resolutions —+ * and then release it on their own schedule. */+export function deferred<T = void>() {+ let resolve!: (value: PromiseLike<T> | T) => void+ let reject!: (reason?: unknown) => void++ const promise = new Promise<T>((done, fail) => {+ resolve = done+ reject = fail+ })++ return { promise, reject, resolve }+}diff --git a/apps/desktop/src/test/jsdom.ts b/apps/desktop/src/test/jsdom.tsnew file mode 100644index 00000000000..e9034e8c335--- /dev/null+++ b/apps/desktop/src/test/jsdom.ts@@ -0,0 +1,26 @@+// jsdom implements no layout and no animation, so component libraries that+// call those APIs unconditionally throw on mount. These install inert+// stand-ins: enough for the component to render, never enough to assert on. A+// test that needs one of them to actually report should install its own.++import { vi } from 'vitest'++class InertResizeObserver {+ disconnect() {}+ observe() {}+ unobserve() {}+}++/** A ResizeObserver that accepts observers and never calls them back. */+export function stubResizeObserver() {+ vi.stubGlobal('ResizeObserver', InertResizeObserver)+}++/** The pointer-capture and scroll calls Radix and cmdk make while opening a+ * popover, menu, or combobox — and again on the item they focus. */+export function stubMenuDomApis() {+ Element.prototype.hasPointerCapture ??= () => false+ Element.prototype.setPointerCapture ??= () => undefined+ Element.prototype.releasePointerCapture ??= () => undefined+ Element.prototype.scrollIntoView ??= () => undefined+}diff --git a/apps/desktop/src/test/oauth-provider.ts b/apps/desktop/src/test/oauth-provider.tsnew file mode 100644index 00000000000..8e477ac5ff3--- /dev/null+++ b/apps/desktop/src/test/oauth-provider.ts@@ -0,0 +1,14 @@+import type { OAuthProvider } from '@/types/hermes'++/** A logged-out PKCE provider. Onboarding branches on `flow` and+ * `status.logged_in`; the rest is filler the UI only echoes. */+export function makeOAuthProvider(id: string, name = id): OAuthProvider {+ return {+ cli_command: `hermes login ${id}`,+ docs_url: `https://example.com/${id}`,+ flow: 'pkce',+ id,+ name,+ status: { logged_in: false }+ }+}diff --git a/apps/desktop/src/test/react-root.ts b/apps/desktop/src/test/react-root.tsnew file mode 100644index 00000000000..ba54305dea7--- /dev/null+++ b/apps/desktop/src/test/react-root.ts@@ -0,0 +1,44 @@+import { act, type ReactNode } from 'react'+import { createRoot, type Root } from 'react-dom/client'++/** A React root in a container attached to the document, for the handful of+ * suites that cannot use Testing Library's `render`.+ *+ * They need the component mounted in the real document — a canvas that must+ * paint, an element measured by its parent, a portal that reads+ * `document.body` — and they need to unmount inside `act` mid-test to assert+ * on teardown. Cleanup is idempotent so `afterEach` can call it after a test+ * already did. */+export function reactRoot() {+ let root: Root | null = null+ let container: HTMLDivElement | null = null++ return {+ get container() {+ return container+ },+ /** The root itself, for a re-render that has to share an `act` with+ * something else — a mutation-observer callback, a timer flush. */+ get root() {+ return root+ },+ render(ui: ReactNode) {+ container = document.createElement('div')+ document.body.append(container)+ root = createRoot(container)++ act(() => {+ root!.render(ui)+ })+ },+ unmount() {+ if (root) {+ act(() => root!.unmount())+ }++ container?.remove()+ root = null+ container = null+ }+ }+}diff --git a/apps/desktop/src/test/session-info.ts b/apps/desktop/src/test/session-info.tsnew file mode 100644index 00000000000..9c39a4eb0f3--- /dev/null+++ b/apps/desktop/src/test/session-info.ts@@ -0,0 +1,46 @@+import type { SessionInfo } from '@/types/hermes'++/** A `SessionInfo` with every field at its zero value.+ *+ * `SessionInfo` mirrors a backend row and grows a field whenever the API does.+ * Spelling the whole shape out per test file meant each new field broke a+ * handful of unrelated suites; here it breaks one line. Tests override only+ * what they assert on. */+export function makeSessionInfo(overrides: Partial<SessionInfo> = {}): SessionInfo {+ return {+ archived: false,+ cwd: null,+ ended_at: null,+ id: 'session',+ input_tokens: 0,+ is_active: false,+ last_active: 0,+ message_count: 0,+ model: null,+ output_tokens: 0,+ preview: null,+ source: null,+ started_at: 0,+ title: null,+ tool_call_count: 0,+ ...overrides+ }+}++let nextId = 0++/** A real-looking CLI session rooted at `cwd`, with a fresh id. What the+ * folder-grouping and per-project colour tests bucket; they care about the+ * path and that the session is otherwise unremarkable. */+export function makeCwdSession(cwd: null | string, overrides: Partial<SessionInfo> = {}): SessionInfo {+ return makeSessionInfo({+ cwd,+ id: `s${nextId++}`,+ last_active: 1_000,+ message_count: 1,+ model: 'claude',+ source: 'cli',+ started_at: 1_000,+ ...overrides+ })+}diff --git a/apps/desktop/src/test/window-state.ts b/apps/desktop/src/test/window-state.tsnew file mode 100644index 00000000000..512da0f5ff1--- /dev/null+++ b/apps/desktop/src/test/window-state.ts@@ -0,0 +1,47 @@+// Stand-ins for the two window-visibility signals the renderer reacts to:+// Electron's `hermesDesktop.onWindowStateChanged` bridge and the DOM's own+// `document.hidden`. Both are read-only under jsdom, and anything that pauses+// work while the window is hidden — the pet, the terminal pane, budgeted loops,+// pulse animations — needs to drive them.++import { vi } from 'vitest'++export interface WindowStatePayload {+ isMinimized?: boolean+ isVisible?: boolean+}++export interface WindowStateBridge {+ /** Push a state change to whoever subscribed through the bridge. */+ emit: (payload: WindowStatePayload) => void+ /** The unsubscribe handed back to the subscriber, for teardown assertions. */+ off: ReturnType<typeof vi.fn>+}++/** Install a fake `window.hermesDesktop` window-state channel. */+export function installWindowStateBridge(): WindowStateBridge {+ let callback: ((payload: WindowStatePayload) => void) | null = null++ const off = vi.fn(() => {+ callback = null+ })++ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: {+ onWindowStateChanged: vi.fn((next: (payload: WindowStatePayload) => void) => {+ callback = next++ return off+ })+ }+ })++ return { emit: payload => callback?.(payload), off }+}++/** Drive `document.hidden` / `document.visibilityState` together. */+export function setDocumentHidden(hidden: boolean) {+ Object.defineProperty(document, 'hidden', { configurable: true, value: hidden })+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: hidden ? 'hidden' : 'visible' })+}