Skip to content

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

TypeScript

Merge branch 'dev' into feat/ux-improvements-35

Mf81e1d0afc82
diff --cc control-api/src/services/auth/passwordAdmissionError.ts
index 000000000,504655b17..8760b6c50
mode 000000,100644..100644
--- a/control-api/src/services/auth/passwordAdmissionError.ts
+++ b/control-api/src/services/auth/passwordAdmissionError.ts
@@@ -1,0 -1,43 +1,48 @@@
+ import type { PasswordAdmissionDenialReason } from '../../observability/metrics.js'
+
+ export class PasswordAdmissionError extends Error {
+ constructor(
+ readonly status: 429 | 503,
+ readonly retryAfterSeconds: number,
+ readonly reason: PasswordAdmissionDenialReason,
+ readonly publicError:
- 'rate_limited' | 'authority_unavailable' | 'recovery_outcome_unknown' = status === 429
- ? 'rate_limited'
- : 'authority_unavailable'
++ | 'rate_limited'
++ | 'authority_unavailable'
++ | 'recovery_outcome_unknown' = status === 429 ? 'rate_limited' : 'authority_unavailable'
+ ) {
+ super(status === 429 ? 'rate_limited' : 'authority_unavailable')
+ }
+ }
+
+ /** Safe, non-retryable result for an unexpected password mutation callback failure. */
+ export class PasswordMutationInternalError extends Error {
+ readonly code = 'internal_error'
+ readonly cause: unknown
+
+ constructor(cause?: unknown) {
+ super('internal_error')
+ this.name = 'PasswordMutationInternalError'
+ Object.defineProperty(this, 'cause', { value: cause, enumerable: false })
+ }
+ }
+
+ export type PasswordMutationCauseKind =
- 'type_error' | 'reference_error' | 'range_error' | 'syntax_error' | 'error' | 'non_error'
++ | 'type_error'
++ | 'reference_error'
++ | 'range_error'
++ | 'syntax_error'
++ | 'error'
++ | 'non_error'
+
+ export function passwordMutationCauseKind(cause: unknown): PasswordMutationCauseKind {
+ try {
+ if (cause instanceof TypeError) return 'type_error'
+ if (cause instanceof ReferenceError) return 'reference_error'
+ if (cause instanceof RangeError) return 'range_error'
+ if (cause instanceof SyntaxError) return 'syntax_error'
+ if (cause instanceof Error) return 'error'
+ } catch {
+ // A hostile thrown value must not prevent the sanitized response path.
+ }
+ return 'non_error'
+ }
diff --cc desktop-app/src/appService.ts
index e6d54a533,ce2d96580..78089d7ba
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@@ -877,9 -891,8 +891,9 @@@ export class AppService
},
requestJson,
fetchBytes: (url, token, opts) => fetchBoundedBytes(url, token, opts),
+ fetchByteStream: (url, token, opts, onChunk) => streamBoundedBytes(url, token, opts, onChunk),
})
- private readonly tokenStore = new TokenStore()
+ private readonly tokenStore: TokenStore
private readonly rpcTokenManager = new RpcTokenManager(this.authClient)
private sessionToken: string | null = null
private me: SessionMe | null = null
diff --cc desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
index 000000000,974624aef..669ab9e2a
mode 000000,100644..100644
--- a/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
+++ b/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
@@@ -1,0 -1,1202 +1,1203 @@@
+ import { type ElectronApplication, type Page, expect, test } from '@playwright/test'
+ import { execFileSync, spawnSync } from 'node:child_process'
+ import fs from 'node:fs'
+ import os from 'node:os'
+ import path from 'node:path'
+ import { ChatStore } from '../../src/chatStore'
+ import { isPathInside } from '../../src/devIsolation'
+ import { assertSafeFilesystemSegment } from '../../src/pathSafety'
+ import { type ChatAuthorityScope } from '../../src/types'
+ import { SIDEBAR_SESSION_PREVIEW_LIMIT as SIDEBAR_PREVIEW } from '../../ui/src/constants/navigation'
+ import { assertAllowedKubeContext } from './global-setup'
+ import { createFixture } from './helpers/chatCacheFixture.mjs'
+ import {
+ type HostSnapshot,
+ readHostSnapshot,
+ waitForStatelessReady,
+ waitForStatelessSuspended,
+ } from './helpers/hostSnapshot'
+ import {
+ EXTERNAL_REST_API_BASE_URL,
+ MAIN_ENTRY,
+ RPC_PROXY_BASE_URL,
+ assertAllowedTarget,
+ desktopCredentials,
+ launchDesktopApp,
+ login,
+ validateMainEntry,
+ } from './qa-recorder-helpers'
+
+ // E2E_GUARDIAN_IPC_FLOW: server reads are preconditions through Desktop IPC;
+ // the measured journey clicks real rows and observes the visible transcript.
+ // Inputs: CHAT_OPEN_AB_BEFORE_MAIN, CHAT_OPEN_AB_AFTER_MAIN, CHAT_OPEN_AB_KUBE_CONTEXT,
+ // CHAT_OPEN_AB_OUTPUT_JSON, CHAT_OPEN_AB_PHASE. Run only with playwright.chat-open-ab.config.ts.
+ // Phase OL (cached opens, large-cache relaunch) needs the stateless Host to stay up for the
+ // whole phase; phase W needs it to suspend within minutes. They run as two invocations so the
+ // HCC idle cadence can differ between them.
+ // O measures each chat's first open after launch (open_cached_ms, read from disk) apart from
+ // its reopen in the same session (open_memo_ms), which the AFTER build serves from memory.
+ type Build = 'before' | 'after'
+ type Chat = { id: string; count: number; lastText: string }
+ type Catalog = {
+ host: string
+ size: number
+ eligible: number
+ K: number
+ chats: Chat[]
+ latestActivity: string[]
+ }
+ type Sample = {
+ round: number
+ build: Build
+ host: string
+ metric: string
+ ms: number
+ pass?: number
+ chatId?: string
+ observed_at_install?: boolean
+ observer_installed_ms?: number
+ /** The "Loading conversation" skeleton was visible between the click and the measurement. */
+ blank?: boolean
+ /** What the observer saw just before the click and on its first callbacks after it. */
+ trace?: OpenObservation[]
+ /** Relaunch metrics: observed before the test's first pointer event in the window. */
+ before_first_click?: boolean
+ }
+ /** Runs a measured window; the Host snapshot loop of the round is paused while it runs. */
+ type Timed = <T>(work: () => Promise<T>) => Promise<T>
+ const untimed: Timed = work => work()
+ type OpenObservation = {
+ ms: number
+ lists: number
+ bubbles: number
+ skeleton: boolean
+ dedicated: boolean
+ }
+ const HOSTS = ['chatllm', 'chatllm-stateless'] as const
+ // The Desktop remembers the last 8 transcripts it showed (`transcriptMemo`); reopens stay within it.
+ const REMEMBERED_CHATS = 8
+ const MESSAGES = '[data-testid="user-message"], [data-testid="agent-response"]'
+ // Rendered by ChatThread while an active chat has no messages and is loading (both builds).
+ const LOADING_SKELETON = '[aria-label="Loading conversation"]'
+ const TRACE_LIMIT = 8
+ const LIMIT_WINDOW_MS = 65_000
+ const RATE_LIMITED = /\b429\b|Too Many Requests/g
+ // Relaunch rounds per build in L and W.
+ const RELAUNCH_ROUNDS = 3
+ // A live Desktop from an earlier A/B run would hold the Keychain item this run needs.
+ const AB_PROCESS = /Evenfire Issue1091Ab/
+ const rows = (host: string) =>
+ `[data-testid="latest-session-row"][data-agent-ref=${JSON.stringify(host)}]`
+ const row = (host: string, id: string) => `${rows(host)}[data-chat-id=${JSON.stringify(id)}]`
+ const agentRow = (host: string, id: string) =>
+ `[data-testid="agent-chat-row"][data-agent-ref=${JSON.stringify(host)}][data-chat-id=${JSON.stringify(id)}]`
+ const quantiles = (values: number[]) => {
+ if (!values.length || values.some(value => !Number.isFinite(value)))
+ throw new Error('Missing or invalid timing samples.')
+ const sorted = [...values].sort((a, b) => a - b)
+ return {
+ p50: sorted[Math.ceil(sorted.length * 0.5) - 1]!,
+ p95: sorted[Math.ceil(sorted.length * 0.95) - 1]!,
+ n: sorted.length,
+ }
+ }
+ function required(name: string): string {
+ const value = process.env[name]
+ if (!value || !value.trim()) throw new Error(`${name} is required for the Desktop A/B benchmark.`)
+ return value
+ }
+ function isolatedPath(runDir: string, target: string): string {
+ if (!isPathInside(runDir, target))
+ throw new Error(`Cache target must be inside the isolated run directory: ${target}`)
+ let ancestor = target
+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor)
+ const resolved = path.resolve(fs.realpathSync(ancestor), path.relative(ancestor, target))
+ if (!isPathInside(fs.realpathSync(runDir), resolved))
+ throw new Error(`Cache target escapes isolation through a symlink: ${target}`)
+ return target
+ }
+ // Each open sends about 8 REST requests, several of them counted by control-api's 120/min
+ // per-session limit; spacing opens keeps a launch under that limit. The wait is outside the timing.
+ const OPEN_PACE_MS = 4_000
+ let lastOpenAt = 0
+ async function openChat(
+ page: Page,
+ host: string,
+ label: string,
+ chat: Chat,
+ timed: Timed
+ ): Promise<{ ms: number; blank: boolean; trace: OpenObservation[] }> {
+ // A deadline, not a fixed sleep: wait only for what is left of the pace since the last open.
+ const pace = lastOpenAt + OPEN_PACE_MS - Date.now()
+ if (pace > 0) await new Promise(resolve => setTimeout(resolve, pace))
+ lastOpenAt = Date.now()
+ await page
+ .getByRole('navigation', { name: 'Chat breadcrumb', exact: true })
+ .getByRole('button', { name: 'Chat', exact: true })
+ .click()
+ // Switch Hosts from the Chat page: the Agents page refreshes the access catalog and the
+ // team directory on every visit, which exhausts the per-minute API limits at this pace.
+ const switchAgent = page.getByRole('button', { name: /^Switch chat agent$/ })
+ await expect(switchAgent).toBeVisible()
+ if (!(await switchAgent.getByText(label, { exact: true }).isVisible())) {
+ await switchAgent.click()
+ await page.getByRole('menuitem', { name: label, exact: true }).click()
+ }
+ await expect(switchAgent).toContainText(label)
+ await expect(page.getByRole('textbox', { name: 'Agent message composer' })).toBeVisible()
+ const more = page.getByRole('button', { name: 'Show more', exact: true })
+ const loadMore = page.getByRole('button', { name: 'Load more', exact: true })
+ const target = page.locator(agentRow(host, chat.id))
+ await expect
+ .poll(
+ async () => {
+ if (await target.isVisible()) return true
+ if (await more.isVisible()) await more.click()
+ else if ((await loadMore.isVisible()) && (await loadMore.isEnabled()))
+ await loadMore.click()
+ return target.isVisible()
+ },
+ {
+ timeout: 30_000,
+ message: `The selected Host must expose server chat ${chat.id} through its session list.`,
+ }
+ )
+ .toBe(true)
+ return timed(() =>
+ page.evaluate(
+ ({ selector, chat, messages, skeleton, traceLimit }) =>
+ new Promise<{ ms: number; blank: boolean; trace: OpenObservation[] }>((resolve, reject) => {
+ const button = document.querySelector<HTMLButtonElement>(`${selector} button`)
+ if (!button || button.disabled)
+ throw new Error(`Chat row has no enabled open button: ${selector}`)
+ let blank = false
+ const trace: OpenObservation[] = []
+ // Before the click the Chat breadcrumb shows the Host's chat list with no active chat, which
+ // already has zero bubbles; only the loading skeleton marks a chat that was opened empty.
+ const observe = (ms: number) => {
+ const transcripts = document.querySelectorAll('[data-testid="message-list"]')
+ const observation = {
+ ms,
+ lists: transcripts.length,
+ bubbles: transcripts[0]?.querySelectorAll(messages).length ?? 0,
+ skeleton: document.querySelector(skeleton) !== null,
+ dedicated: transcripts[0]?.classList.contains('chat-thread-dedicated') ?? false,
+ }
+ if (trace.length < traceLimit) trace.push(observation)
+ return observation
+ }
+ observe(-1)
+ // The sidebar previews only the latest sessions, so the active-row witness is checked outside the timing.
+ let scheduled = false
+ const finish = () => {
+ scheduled = false
+ const transcripts = document.querySelectorAll('[data-testid="message-list"]')
+ if (transcripts.length > 1) {
+ observer.disconnect()
+ clearTimeout(deadline)
+ reject(new Error(`Expected one transcript, found ${transcripts.length}.`))
+ return
+ }
+ const transcript = transcripts[0]
+ const bubbles = transcript?.querySelectorAll(messages)
+ if (observe(performance.now() - started).skeleton) blank = true
+ if (
+ bubbles?.length === chat.count &&
+ bubbles[chat.count - 1]?.textContent?.includes(chat.lastText) &&
+ transcript &&
+ transcript.getBoundingClientRect().height > 0
+ ) {
+ observer.disconnect()
+ clearTimeout(deadline)
+ resolve({ ms: performance.now() - started, blank, trace })
+ }
+ }
+ // One check per animation frame: a mutation only schedules it, so layout is read once
+ // per frame instead of once per mutation. Callbacks run after the click below sets `started`.
+ const observer = new MutationObserver(() => {
+ if (scheduled) return
+ scheduled = true
+ requestAnimationFrame(finish)
+ })
+ observer.observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ })
+ const deadline = setTimeout(() => {
+ observer.disconnect()
+ reject(new Error(`Transcript did not match server chat ${chat.id}`))
+ }, 120_000)
+ const started = performance.now()
+ button.click()
+ finish()
+ }),
+ {
+ selector: agentRow(host, chat.id),
+ chat,
+ messages: MESSAGES,
+ skeleton: LOADING_SKELETON,
+ traceLimit: TRACE_LIMIT,
+ }
+ )
+ )
+ }
+ async function relaunchPaint(
+ page: Page,
+ targets: Array<{ host: string; metric: string; selector: string; chat?: Chat }>
+ ) {
+ return page.evaluate(
+ ({ targets, messages }) =>
+ new Promise<
+ Array<{
+ host: string
+ metric: string
+ ms: number
+ observed_at_install: boolean
+ observer_installed_ms: number
+ before_first_click: boolean
+ }>
+ >((resolve, reject) => {
+ const navigation = performance.getEntriesByType('navigation')[0] as
- PerformanceNavigationTiming | undefined
++ | PerformanceNavigationTiming
++ | undefined
+ if (!navigation) throw new Error('Window navigation timing is unavailable.')
+ const installed = performance.now()
+ const observed = new Map<string, { at: number; initial: boolean; beforeClick: boolean }>()
+ let initial = true
+ // Witness for metrics that must be observed before the test clicks anything.
+ let clicked = false
+ document.addEventListener(
+ 'pointerdown',
+ () => {
+ clicked = true
+ },
+ { capture: true, once: true }
+ )
+ let scheduled = false
+ const visible = (element: Element) =>
+ element.getBoundingClientRect().height > 0 &&
+ getComputedStyle(element).visibility !== 'hidden'
+ const finish = () => {
+ scheduled = false
+ const transcripts = document.querySelectorAll('[data-testid="message-list"]')
+ if (transcripts.length > 1) {
+ observer.disconnect()
+ clearTimeout(deadline)
+ reject(new Error(`Expected one transcript, found ${transcripts.length}.`))
+ return
+ }
+ const transcript = transcripts[0]
+ for (const target of targets) {
+ const ready =
+ Array.from(document.querySelectorAll(target.selector)).some(visible) &&
+ (!target.chat ||
+ (transcript &&
+ visible(transcript) &&
+ transcript.querySelectorAll(messages).length === target.chat.count &&
+ transcript
+ .querySelectorAll(messages)
+ [target.chat.count - 1]?.textContent?.includes(target.chat.lastText)))
+ if (ready && !observed.has(target.metric)) {
+ observed.set(target.metric, {
+ at: performance.now(),
+ initial,
+ beforeClick: !clicked,
+ })
+ // The test's clicks wait on this, so the witness is not decided by frame timing.
+ ;(window as { __abRelaunchObserved?: string[] }).__abRelaunchObserved = [
+ ...observed.keys(),
+ ]
+ }
+ }
+ if (observed.size === targets.length && navigation.loadEventEnd > 0) {
+ observer.disconnect()
+ clearTimeout(deadline)
+ resolve(
+ targets.map(target => {
+ const result = observed.get(target.metric)!
+ return {
+ host: target.host,
+ metric: target.metric,
+ ms: Math.max(0, result.at - navigation.loadEventEnd),
+ observed_at_install: result.initial,
+ observer_installed_ms: installed - navigation.loadEventEnd,
+ before_first_click: result.beforeClick,
+ }
+ })
+ )
+ }
+ initial = false
+ }
+ // One check per animation frame, as in openChat.
+ const observer = new MutationObserver(() => {
+ if (scheduled) return
+ scheduled = true
+ requestAnimationFrame(finish)
+ })
+ observer.observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ })
+ const deadline = setTimeout(() => {
+ observer.disconnect()
+ reject(new Error('Relaunch did not expose the required rows/transcript.'))
+ }, 120_000)
+ window.addEventListener('load', () => requestAnimationFrame(finish), { once: true })
+ finish()
+ }),
+ { targets, messages: MESSAGES }
+ )
+ }
+
+ if (
+ process.env.DESKTOP_CHAT_OPEN_AB_CONFIG ===
+ path.join(__dirname, 'playwright.chat-open-ab.config.ts')
+ ) {
+ test('compare two Desktop builds: cached chat open, large-cache relaunch and stateless wake', async ({}, testInfo) => {
+ if (process.env.EVENFIRE_RENDERER_URL?.trim())
+ throw new Error(
+ "Unset EVENFIRE_RENDERER_URL: the A/B run must use each build's bundled renderer."
+ )
+ const entries = {
+ before: required('CHAT_OPEN_AB_BEFORE_MAIN'),
+ after: required('CHAT_OPEN_AB_AFTER_MAIN'),
+ }
+ for (const entry of Object.values(entries)) validateMainEntry(entry)
+ if (
+ path.resolve(entries.after) !== MAIN_ENTRY ||
+ path.dirname(entries.before) === path.dirname(entries.after)
+ )
+ throw new Error(
+ 'AFTER must be this worktree build; BEFORE must be a different worktree build.'
+ )
+ const context = required('CHAT_OPEN_AB_KUBE_CONTEXT')
+ if (context !== context.trim() || context.startsWith('-'))
+ throw new Error('CHAT_OPEN_AB_KUBE_CONTEXT must be the literal Kubernetes context.')
+ // The shared global setup is disabled for this config; apply its context guard before any kubectl call.
+ assertAllowedKubeContext(context, 'CHAT_OPEN_AB_KUBE_CONTEXT')
+ const output = required('CHAT_OPEN_AB_OUTPUT_JSON')
+ if (!path.isAbsolute(output) || path.extname(output) !== '.json')
+ throw new Error('CHAT_OPEN_AB_OUTPUT_JSON must be an absolute JSON path.')
+ const phase = required('CHAT_OPEN_AB_PHASE')
+ if (phase !== 'OL' && phase !== 'W') throw new Error('CHAT_OPEN_AB_PHASE must be OL or W.')
+ const builds = Object.fromEntries(
+ Object.entries(entries).map(([build, entry]) => {
+ const git = (...args: string[]) =>
+ execFileSync('git', ['-C', path.resolve(path.dirname(entry), '../..'), ...args], {
+ encoding: 'utf8',
+ }).trim()
+ // A build must be exactly its commit: a clean tree, and dist/main.js built after the commit.
+ const dirty = git('status', '--porcelain')
+ if (dirty) throw new Error(`precondition: the ${build} worktree has uncommitted changes.`)
+ const committedAt = Number(git('log', '-1', '--format=%ct')) * 1000
+ const builtAt = fs.statSync(entry).mtimeMs
+ if (!(builtAt > committedAt))
+ throw new Error(`precondition: the ${build} build is older than its HEAD commit.`)
+ return [build, { entry, sha: git('rev-parse', 'HEAD'), committedAt, builtAt }]
+ })
+ )
+ const samples: Sample[] = []
+ const rounds: Array<{
+ id: number
+ scenario: string
+ build: Build
+ loadavg: number[]
+ cache: { before: unknown; after?: unknown }
+ snapshots: HostSnapshot[]
+ invalidated: boolean
+ }> = []
+ const report = {
+ phase,
+ builds,
+ node: process.version,
+ machine: {
+ platform: os.platform(),
+ arch: os.arch(),
+ cpus: os.cpus().length,
+ model: os.cpus()[0]!.model,
+ },
+ startedAt: new Date().toISOString(),
+ catalogs: [] as Catalog[],
+ fixtureRoot: '',
+ rounds,
+ samples,
+ cells: {} as Record<string, ReturnType<typeof quantiles>>,
+ gates: [] as Array<Record<string, string | number | boolean>>,
+ // Reported, not gated: another branch profile shares the machine (plan addendum A9.2).
+ loadSpread: [] as Array<Record<string, string | number | boolean>>,
+ // L rounds that found the stateless Host suspended and woke it first.
+ statelessWakes: [] as Array<{ build: Build; iteration: number; at: string }>,
+ complete: false,
+ }
+ let app: ElectronApplication | undefined
+ let page: Page
+ // The agent switcher shows display names; the app falls back to the ref when none is set.
+ let hostLabels: Record<string, string> = {}
+ const runDir = testInfo.outputPath('electron-isolation')
+ let closedAt = 0
+ const close = async () => {
+ if (app) {
+ await app.close()
+ app = undefined
+ closedAt = Date.now()
+ }
+ }
+ // One app identity per run, so Electron creates its own `<appName> Safe Storage` Keychain item
+ // instead of reading one an earlier run left behind. BEFORE and AFTER share it and the user data.
+ const isolationTarget = `issue-1091-ab-${Date.now().toString(36)}`
+ const electronPath = fs.realpathSync(require('electron') as unknown as string)
+ let launches = 0
+ let mainLog = ''
+ // The current launch's main-process output, kept in memory so a round reads all of it.
+ let mainOutput: string[] = []
+ let launchedBuild: Build | undefined
+ // A first window that never opens is usually a Keychain prompt nobody answers. Record what the
+ // process was doing and whether macOS shows a prompt; never answer or bypass it.
+ const diagnoseFirstWindow = (starting: ElectronApplication): string => {
+ const samplePath = testInfo.outputPath(`sample-${launches}.txt`)
+ // A failed sample is reported in the diagnosis; it must not replace the timeout.
+ let sampleNote = `sample in ${samplePath}`
+ try {
+ execFileSync('sample', [String(starting.process().pid), '5', '-file', samplePath])
+ } catch (error) {
+ sampleNote = `sample failed (${String((error as Error)?.message ?? error)})`
+ }
+ const agent = spawnSync('pgrep', ['-x', 'SecurityAgent'])
+ if (agent.status !== 0 && agent.status !== 1)
+ throw new Error(`pgrep SecurityAgent failed with status ${agent.status}.`)
+ return agent.status === 0
+ ? `KEYCHAIN_PROMPT_PENDING: SecurityAgent is running; ${sampleNote}`
+ : `FIRST_WINDOW_TIMEOUT: no SecurityAgent process; ${sampleNote}`
+ }
+ // A closed build's background requests can exhaust control-api's per-minute
+ // limits; the next build's session restore then fails. Start each launch in
+ // a fresh window, outside every timed section.
+ const awaitQuietWindow = async () => {
+ await close()
+ const quiet = closedAt + LIMIT_WINDOW_MS - Date.now()
+ if (quiet > 0) await new Promise(resolve => setTimeout(resolve, quiet))
+ }
+ const launch = async (build: Build) => {
+ await awaitQuietWindow()
+ const live = execFileSync('ps', ['-axo', 'pid=,args='], { encoding: 'utf8' })
+ .split('\n')
+ .filter(line => AB_PROCESS.test(line))
+ .map(line => line.trim().split(/\s+/)[0])
+ if (live.length)
+ throw new Error(`precondition: an A/B Desktop is still running (pids ${live.join(', ')}).`)
+ // Keep each main process's output so a lost session can be explained after the run.
+ mainLog = testInfo.outputPath(`main-${++launches}-${build}.log`)
+ const log = fs.createWriteStream(mainLog, { mode: 0o600 })
+ const output: string[] = []
+ mainOutput = output
+ let starting: ElectronApplication | undefined
+ try {
+ const launched = await launchDesktopApp(testInfo, isolationTarget, entries[build], {
+ executablePath: electronPath,
+ beforeFirstWindow: started => {
+ starting = started
+ for (const stream of [started.process().stdout, started.process().stderr])
+ stream?.on('data', (chunk: Buffer) => {
+ output.push(chunk.toString('utf8'))
+ log.write(chunk)
+ })
+ },
+ })
+ app = launched.app
+ page = launched.page
+ } catch (error) {
+ // The starting process is closed even when the diagnosis itself throws.
+ try {
+ if (starting && /firstWindow: Timeout/.test(String((error as Error)?.message)))
+ throw new Error(diagnoseFirstWindow(starting), { cause: error })
+ throw error
+ } finally {
+ await starting?.close()
+ }
+ }
+ launchedBuild = build
+ // Public process identities only: the pinned Electron, this build's code and the run's profile.
+ const runtime = await app.evaluate(({ app: electronApp }) => ({
+ executablePath: process.execPath,
+ appPath: electronApp.getAppPath(),
+ userData: electronApp.getPath('userData'),
+ }))
+ expect(fs.realpathSync(runtime.executablePath)).toBe(electronPath)
+ expect(fs.realpathSync(runtime.appPath)).toBe(fs.realpathSync(path.dirname(entries[build])))
+ expect(fs.realpathSync(runtime.userData)).toBe(
+ fs.realpathSync(path.join(runDir, 'user-data'))
+ )
+ }
+ const authenticated = async () => {
+ try {
+ await expect(page.getByTestId('nav-chat')).toBeVisible()
+ await expect(page.locator('#email-input')).toBeHidden()
+ } catch (error) {
+ const userData = path.join(runDir, 'user-data')
+ const tokenName = fs
+ .readdirSync(userData)
+ .find(name => /^session-token-.*\.enc$/.test(name))
+ const diagnosis = {
+ build: launchedBuild,
+ launch: launches,
+ token: tokenName
+ ? {
+ bytes: fs.statSync(path.join(userData, tokenName)).size,
+ mtime: fs.statSync(path.join(userData, tokenName)).mtime.toISOString(),
+ decrypt: await app!.evaluate(
+ async ({ safeStorage }, file) => {
+ try {
+ const fsp = process.mainModule!.require('node:fs/promises')
+ return `ok length=${safeStorage.decryptString(await fsp.readFile(file)).length}`
+ } catch (failure) {
+ return `error: ${String((failure as Error)?.message).slice(0, 160)}`
+ }
+ },
+ path.join(userData, tokenName)
+ ),
+ }
+ : 'absent',
+ session: await page
+ .evaluate(async () => {
+ const state = await window.clerum.auth.getSessionState()
+ return { authenticated: Boolean(state.authenticated), hasMe: Boolean(state.me) }
+ })
+ .catch(failure => `error: ${String((failure as Error)?.message).slice(0, 160)}`),
+ }
+ fs.writeFileSync(
+ testInfo.outputPath(`session-diagnosis-${launches}.json`),
+ JSON.stringify(diagnosis, null, 2),
+ { mode: 0o600 }
+ )
+ throw error
+ }
+ }
+ const snapshot = () => readHostSnapshot(HOSTS[1], HOSTS[1], context)
+ const ready = () => waitForStatelessReady(270_000, context, HOSTS[1], HOSTS[1])
+ // Between L rounds no Desktop is open, so the idle timer can suspend the stateless Host and
+ // `ready()` alone would wait for a wake nobody requests. Wake it the way phase W does: a
+ // Desktop launch requests its catalog, and rpc-proxy holds that request until the Host is Ready.
+ const wakeStateless = async (build: Build, iteration: number) => {
+ if ((await snapshot()).readyReplicas === 0) {
+ report.statelessWakes.push({ build, iteration, at: new Date().toISOString() })
+ await launch(build)
+ await authenticated()
+ }
+ await ready()
+ }
+ let cacheDir: string
+ const cacheState = () => {
+ if (!fs.existsSync(cacheDir)) return { agents: 0, chats: 0, pending: 0 }
+ const indexes = fs
+ .readdirSync(cacheDir, { withFileTypes: true })
+ .filter(entry => entry.isDirectory())
+ .map(entry =>
+ JSON.parse(fs.readFileSync(path.join(cacheDir, entry.name, 'index.json'), 'utf8'))
+ )
+ return {
+ agents: indexes.length,
+ chats: indexes.reduce((sum, index) => sum + index.chats.length, 0),
+ pending: indexes.reduce(
+ (sum, index) => sum + (index.pendingChatCleanup ? index.pendingChatCleanup.length : 0),
+ 0
+ ),
+ }
+ }
+ // `timed` wraps every measured window; the Host snapshots (each a few kubectl processes)
+ // run only between those windows, so they never compete with a measurement.
+ const round = async (
+ scenario: string,
+ build: Build,
+ action: (id: number, timed: Timed) => Promise<void>
+ ) => {
+ const record: (typeof rounds)[number] = {
+ id: rounds.length + 1,
+ scenario,
+ build,
+ loadavg: os.loadavg(),
+ cache: { before: cacheState() },
+ snapshots: [await snapshot()],
+ invalidated: false,
+ }
+ rounds.push(record)
+ let stopped = false
+ let paused = false
+ let sampling: Promise<void> = Promise.resolve()
+ let observationFailure: { error: unknown } | undefined
+ const observation = (async () => {
+ while (!stopped) {
+ if (!paused) {
+ sampling = snapshot().then(state => {
+ record.snapshots.push(state)
+ })
+ await sampling
+ }
+ if (!stopped) await new Promise(resolve => setTimeout(resolve, 250))
+ }
+ })().catch(error => {
+ observationFailure = { error }
+ })
+ const timed: Timed = async work => {
+ paused = true
+ try {
+ // A snapshot already running finishes before the measured window opens.
+ await sampling
+ return await work()
+ } finally {
+ paused = false
+ }
+ }
+ try {
+ await action(record.id, timed)
+ // A rate-limited round runs on stale or empty catalogs, so its timings are not valid samples.
+ const limited = mainOutput.join('').match(RATE_LIMITED)?.length ?? 0
+ if (limited)
+ throw new Error(
+ `Round ${record.id} (${scenario} ${build}) logged ${limited} rate-limited responses in ${path.basename(mainLog)}.`
+ )
+ } finally {
+ stopped = true
+ await observation
+ record.snapshots.push(await snapshot())
+ record.cache.after = cacheState()
+ record.invalidated =
+ scenario !== 'W' &&
+ record.snapshots.some(
+ (state, index, all) =>
+ index > 0 &&
+ state.readyReplicas > 0 &&
+ (all[index - 1]!.readyReplicas === 0 ||
+ state.podNames.join(',') !== all[0]!.podNames.join(','))
+ )
+ if (observationFailure) throw observationFailure.error
+ }
+ }
+ try {
+ await test.step('precondition: one isolated login and existing server chats with at least two turns', async () => {
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ // Every run starts without a session or chat cache, so no step can pass on an earlier run's history.
+ if (fs.existsSync(runDir))
+ throw new Error(`precondition: ${runDir} must not exist before the first launch.`)
+ await launch('before')
+ await login(page!, desktopCredentials())
+ await ready()
+ expect(
+ (await readHostSnapshot(HOSTS[0], HOSTS[0], context)).readyReplicas,
+ 'The stateful control Host must be Ready.'
+ ).toBeGreaterThan(0)
+ const scope = await page!.evaluate(async (): Promise<ChatAuthorityScope> => {
+ const state = await window.clerum.auth.getSessionState()
+ const config = await window.clerum.auth.getRuntimeConfigState()
+ if (!state.authenticated || !state.me || !config.envKey)
+ throw new Error('Logged-in authority scope is unavailable.')
+ return { environmentKey: config.envKey, userId: state.me.id, teamId: state.me.teamId }
+ })
+ assertSafeFilesystemSegment('environmentKey', scope.environmentKey)
+ assertSafeFilesystemSegment('userId', scope.userId)
+ cacheDir = isolatedPath(
+ runDir,
+ path.join(runDir, 'chats', scope.environmentKey, scope.userId)
+ )
+ hostLabels = await page!.evaluate(
+ async hosts => {
+ const catalog = await window.clerum.access.refreshCatalog()
+ return Object.fromEntries(
+ hosts.map(host => [host, catalog.agentDisplayByName?.[host] ?? host])
+ )
+ },
+ [...HOSTS]
+ )
+ report.catalogs = await page!.evaluate(
+ async hosts => {
+ const catalogs: Catalog[] = []
+ for (const host of hosts) {
+ const items: Awaited<ReturnType<typeof window.clerum.rpc.listSessions>>['items'] = []
+ let cursor: string | undefined
+ do {
+ const result = await window.clerum.rpc.listSessions(host, undefined, {
+ limit: 100,
+ cursor,
+ })
+ items.push(...result.items)
+ cursor = result.nextCursor
+ } while (cursor)
+ const eligible = items.filter(item => item.turnCount >= 2)
+ const K = Math.min(10, eligible.length)
+ if (K < 5)
+ throw new Error(
+ `precondition: ${host} has ${K} eligible chats; at least 5 are required, without seeding.`
+ )
+ const chats: Chat[] = []
+ for (const session of eligible.slice(0, K)) {
+ const result = await window.clerum.rpc.loadSessionMessages(
+ host,
+ session.agent,
+ session.chatId,
+ undefined,
+ { limit: session.turnCount }
+ )
+ const last = result.turns[result.turns.length - 1]
+ if (
+ result.turns.length !== session.turnCount ||
+ !last?.response ||
+ result.turns.some(turn => !turn.user_input || !turn.response)
+ )
+ throw new Error(
+ `precondition: ${host}/${session.chatId} must expose all completed turns.`
+ )
+ const count = result.turns.length * 2
+ if (session.messageCount !== undefined && session.messageCount !== count)
+ throw new Error(
+ `precondition: ${host}/${session.chatId} message count disagrees with completed turns.`
+ )
+ chats.push({ id: session.chatId, count, lastText: last.response })
+ }
+ catalogs.push({
+ host,
+ size: items.length,
+ eligible: eligible.length,
+ K,
+ chats,
+ latestActivity: items.map(item => item.lastActivityAt),
+ })
+ }
+ return catalogs
+ },
+ [...HOSTS]
+ )
+ // The transcript stop condition identifies a chat by its last text, so that text must be unique.
+ const lastTexts = report.catalogs.flatMap(catalog =>
+ catalog.chats.map(chat => chat.lastText)
+ )
+ if (new Set(lastTexts).size !== lastTexts.length)
+ throw new Error('precondition: every measured chat must end with a unique last text.')
+ if (phase === 'W') {
+ // W empties the cache, so its sidebar preview is the server's latest sessions across Hosts.
+ const previewHosts = new Set(
+ report.catalogs
+ .flatMap(catalog => catalog.latestActivity.map(at => ({ at, host: catalog.host })))
+ .sort((a, b) => b.at.localeCompare(a.at))
+ .slice(0, SIDEBAR_PREVIEW)
+ .map(entry => entry.host)
+ )
+ for (const host of HOSTS)
+ if (!previewHosts.has(host))
+ throw new Error(
+ `precondition: W needs a ${host} session among the server's ${SIDEBAR_PREVIEW} latest sessions.`
+ )
+ return
+ }
+ // The benchmark builder owns valid paged metadata; rebind its synthetic tombstones to the real session below.
+ const fixtureDir = isolatedPath(runDir, path.join(runDir, 'fixture'))
+ fs.mkdirSync(fixtureDir, { mode: 0o700 })
+ const fixture = await createFixture({
+ runDir: fixtureDir,
+ ChatStore,
+ adapter: {
+ bind(Store: typeof ChatStore, root: string) {
+ const store = new Store(root)
+ store.setAuthorityScope(scope)
+ return store
+ },
+ },
+ agents: 25,
+ chatsPerAgent: 200,
+ pendingCleanupsPerAgent: 10,
+ })
+ for (const agent of fixture.agentNames) {
+ const indexPath = isolatedPath(runDir, path.join(fixture.root, agent, 'index.json'))
+ const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'))
+ for (const key of ['deletedChatTombstones', 'pendingChatCleanup'])
+ for (const tombstone of index[key]) tombstone.authorityScope = scope
+ fs.writeFileSync(indexPath, JSON.stringify(index), { mode: 0o600 })
+ }
+ report.fixtureRoot = fixture.root
+ })
+ if (phase === 'OL') {
+ for (const build of ['before', 'after', 'after', 'before'] as const) {
+ await ready()
+ await test.step(`O: ${build} cached chat opens`, () =>
+ round('O', build, async (id, timed) => {
+ await launch(build)
+ await authenticated()
+ await page.getByTestId('nav-chat').click()
+ // Stateless first: the sidebar preview orders cached chats by their first load, and L needs stateful rows in it.
+ for (const catalog of [...report.catalogs].reverse()) {
+ const checked = new Set<string>()
+ // Round 1 is always BEFORE, so its first cached pass cannot be served from memory.
+ const firstCachedPass = id === 1 ? 2 : 1
+ // Reopens stay inside the remembered window: the last chats opened, newest first,
+ // with the last chat opened at the end.
+ const remembered = catalog.chats.slice(
+ -Math.min(catalog.chats.length, REMEMBERED_CHATS)
+ )
+ if (remembered.length < 2)
+ throw new Error(`precondition: ${catalog.host} needs two chats to reopen.`)
+ const reopenOrder = [
+ ...remembered.slice(0, -1).reverse(),
+ remembered[remembered.length - 1]!,
+ ]
+ for (let pass = 1; pass <= firstCachedPass + 1; pass++) {
+ const remote = id === 1 && pass === 1
+ const reopen = pass > firstCachedPass
+ if (!remote)
+ await test.step(`precondition: ${catalog.host} transcripts are cached`, async () => {
+ await expect
+ .poll(
+ () =>
+ page.evaluate(
+ async ({ host, chats }) => {
+ const messages = await Promise.all(
+ chats.map(chat => window.clerum.chat.loadMessages(host, chat.id))
+ )
+ return messages.every(
+ (items, index) =>
+ items.length === chats[index]!.count &&
+ items[items.length - 1]?.content === chats[index]!.lastText
+ )
+ },
+ { host: catalog.host, chats: catalog.chats }
+ ),
+ { timeout: 30_000 }
+ )
+ .toBe(true)
+ })
+ for (const chat of reopen ? reopenOrder : catalog.chats) {
+ const { ms, blank, trace } = await openChat(
+ page,
+ catalog.host,
+ hostLabels[catalog.host]!,
+ chat,
+ timed
+ )
+ samples.push({
+ round: id,
+ build,
+ host: catalog.host,
+ metric: remote
+ ? 'open_remote_ms'
+ : reopen
+ ? 'open_memo_ms'
+ : 'open_cached_ms',
+ pass,
+ chatId: chat.id,
+ ms,
+ blank,
+ trace,
+ })
+ if (!checked.has(chat.id)) {
+ await expect
+ .poll(() =>
+ page.evaluate(
+ host => window.clerum.chat.getLastActive(host),
+ catalog.host
+ )
+ )
+ .toBe(chat.id)
+ await expect(page.getByTestId('message-list').locator(MESSAGES)).toHaveCount(
+ chat.count
+ )
+ // The sidebar previews only the latest sessions: when this chat has a row it is the active one, otherwise none is.
+ // An empty preview would satisfy "none is active" without checking anything.
+ await expect(
+ page.locator('[data-testid="latest-session-row"]')
+ ).not.toHaveCount(0)
+ const inSidebar = (await page.locator(row(catalog.host, chat.id)).count()) > 0
+ await expect(
+ page.locator('[data-testid="latest-session-row"][aria-current="true"]')
+ ).toHaveCount(inSidebar ? 1 : 0)
+ if (inSidebar)
+ await expect(page.locator(row(catalog.host, chat.id))).toHaveAttribute(
+ 'aria-current',
+ 'true'
+ )
+ checked.add(chat.id)
+ }
+ }
+ }
+ }
+ }))
+ }
+ // A cached chat's updatedAt is set by its first remote load in round 1, so L times the
+ // most recently loaded stateful chat, which the reversed host order puts in the preview.
+ const statefulIndex = JSON.parse(
+ fs.readFileSync(
+ isolatedPath(runDir, path.join(cacheDir!, HOSTS[0], 'index.json')),
+ 'utf8'
+ )
+ ) as { chats: Array<{ id: string; updatedAt: string }> }
+ const updatedAt = new Map(statefulIndex.chats.map(chat => [chat.id, chat.updatedAt]))
+ const selected = report.catalogs[0]!.chats.reduce((latest, chat) => {
+ const at = updatedAt.get(chat.id)
+ if (!at)
+ throw new Error(`precondition: ${HOSTS[0]}/${chat.id} is missing from the cache.`)
+ return at > updatedAt.get(latest.id)! ? chat : latest
+ })
+ await openChat(page!, HOSTS[0], hostLabels[HOSTS[0]]!, selected, untimed)
+ await expect
+ .poll(() => page!.evaluate(host => window.clerum.chat.getLastActive(host), HOSTS[0]))
+ .toBe(selected.id)
+ // L times a sidebar row, which exists only for sessions inside the sidebar preview.
+ await expect(
+ page!.locator(row(HOSTS[0], selected.id)),
+ `precondition: L needs ${HOSTS[0]}/${selected.id} inside the sidebar preview.`
+ ).toBeVisible()
+ await close()
+ const savedCache = isolatedPath(runDir, path.join(runDir, 'cache-snapshot'))
+ fs.cpSync(isolatedPath(runDir, cacheDir!), savedCache, { recursive: true })
+ const fixtureRoot = report.fixtureRoot
+ for (const agent of fs.readdirSync(fixtureRoot))
+ fs.cpSync(
+ isolatedPath(runDir, path.join(fixtureRoot, agent)),
+ isolatedPath(runDir, path.join(savedCache, agent)),
+ { recursive: true }
+ )
+ // L: the large cache is in place and the app relaunches. Desktop does not reopen the last
+ // active chat on launch, so the user opens it: relaunch_rows_ms ends at the first stateful
+ // sidebar row (before any click), relaunch_ms at the transcript of the explicit open.
+ for (const build of ['before', 'after'] as const)
+ for (let iteration = 0; iteration < RELAUNCH_ROUNDS; iteration++) {
+ // The wake launch runs before the cache restore below, so it cannot change what L reads.
+ await wakeStateless(build, iteration)
+ await close()
+ fs.rmSync(isolatedPath(runDir, cacheDir!), { recursive: true })
+ fs.cpSync(savedCache, isolatedPath(runDir, cacheDir!), { recursive: true })
+ await test.step(`L: ${build} large-cache relaunch ${iteration + 1}`, () =>
+ round('L', build, async (id, timed) => {
+ await awaitQuietWindow()
+ const paint = await timed(async () => {
+ await launch(build)
+ const [observed] = await Promise.all([
+ relaunchPaint(page, [
+ { host: HOSTS[0], metric: 'relaunch_rows_ms', selector: rows(HOSTS[0]) },
+ {
+ host: HOSTS[0],
+ metric: 'relaunch_ms',
+ selector: row(HOSTS[0], selected.id),
+ chat: selected,
+ },
+ ]),
+ (async () => {
+ await authenticated()
+ await expect(page.locator(row(HOSTS[0], selected.id))).toBeVisible()
+ // Click only after the in-page observer has recorded the rows; otherwise a
+ // late animation frame records them after this click.
+ await page.waitForFunction(() =>
+ (
+ window as { __abRelaunchObserved?: string[] }
+ ).__abRelaunchObserved?.includes('relaunch_rows_ms')
+ )
+ await page.getByTestId('nav-chat').click()
+ await openChat(page, HOSTS[0], hostLabels[HOSTS[0]]!, selected, untimed)
+ })(),
+ ])
+ return observed
+ })
+ for (const sample of paint) samples.push({ round: id, build, ...sample })
+ await authenticated()
+ }))
+ }
+ }
+ if (phase === 'W')
+ for (const build of ['before', 'after'] as const)
+ for (let iteration = 0; iteration < RELAUNCH_ROUNDS; iteration++) {
+ await close()
+ await waitForStatelessSuspended(240_000, context, HOSTS[1], HOSTS[1])
+ // Empty only the isolated chat cache: both observed rows must come from the remote catalog.
+ if (fs.existsSync(cacheDir!))
+ fs.rmSync(isolatedPath(runDir, cacheDir!), { recursive: true })
+ await test.step(`W: ${build} suspended-stateless relaunch ${iteration + 1}`, () =>
+ round('W', build, async (id, timed) => {
+ await awaitQuietWindow()
+ const paint = await timed(async () => {
+ await launch(build)
+ return relaunchPaint(
+ page,
+ HOSTS.map((host, index) => ({
+ host,
+ selector: rows(host),
+ metric: index === 0 ? 'first_stateful_row_ms' : 'stateless_rows_ms',
+ }))
+ )
+ })
+ for (const sample of paint) samples.push({ round: id, build, ...sample })
+ await authenticated()
+ await ready()
+ }))
+ }
+ const values = (build: Build, host: string, metric: string, roundId?: number) =>
+ samples
+ .filter(
+ sample =>
+ sample.build === build &&
+ sample.host === host &&
+ sample.metric === metric &&
+ (roundId === undefined || sample.round === roundId)
+ )
+ .map(sample => sample.ms)
+ for (const sample of samples)
+ report.cells[`${sample.build}/${sample.host}/${sample.metric}`] = quantiles(
+ values(sample.build, sample.host, sample.metric)
+ )
+ if (phase === 'OL') {
+ for (const host of HOSTS) {
+ const before = quantiles(values('before', host, 'open_cached_ms')).p50,
+ after = quantiles(values('after', host, 'open_cached_ms')).p50
+ const spread = Math.abs(
+ quantiles(values('before', host, 'open_cached_ms', 1)).p50 -
+ quantiles(values('before', host, 'open_cached_ms', 4)).p50
+ )
+ const budget = Math.max(spread, before * 0.1)
+ report.gates.push({
+ metric: 'open_cached_ms',
+ host,
+ before,
+ after,
+ aa_spread_ms: spread,
+ budget_ms: budget,
+ passed: after <= before + budget,
+ })
+ const memoBefore = quantiles(values('before', host, 'open_memo_ms')).p50,
+ memoAfter = quantiles(values('after', host, 'open_memo_ms')).p50
+ report.gates.push({
+ metric: 'open_memo_ms',
+ host,
+ before: memoBefore,
+ after: memoAfter,
+ passed: memoAfter < memoBefore,
+ })
+ // AFTER reopens never show the loading skeleton. The witnesses prove the observer does see
+ // it where it happens: on AFTER first opens (disk path) and on BEFORE reopens.
+ const blanks = (build: Build, metric: string) =>
+ samples.filter(
+ sample =>
+ sample.build === build &&
+ sample.host === host &&
+ sample.metric === metric &&
+ sample.blank
+ ).length
+ const witness = {
+ after_reopen_blank: blanks('after', 'open_memo_ms'),
+ after_first_open_blank: blanks('after', 'open_cached_ms'),
+ before_reopen_blank: blanks('before', 'open_memo_ms'),
+ }
+ report.gates.push({
+ metric: 'reopen_blank_witness',
+ host,
+ ...witness,
+ passed:
+ values('after', host, 'open_memo_ms').length > 0 &&
+ witness.after_reopen_blank === 0 &&
+ witness.after_first_open_blank > 0 &&
+ witness.before_reopen_blank === values('before', host, 'open_memo_ms').length,
+ })
+ }
+ // Every relaunch round of both builds contributes one sample per L metric.
+ const relaunchSamples = (build: Build, metric: string) => {
+ const found = values(build, HOSTS[0], metric)
+ if (found.length !== RELAUNCH_ROUNDS)
+ throw new Error(`L recorded ${found.length} ${build} ${metric} samples.`)
+ return found
+ }
+ // The L claim is that chat:getIndex no longer waits for the 10 pending cleanups, so AFTER
+ // must keep most of that gain, not merely be faster. On 48fcd0b30 the p50 ratio was 0.05
+ // (rows) and 0.10 (transcript); with the inline cleanup await restored in AFTER it was
+ // 0.93 and 0.90. A ratio of at most 0.5 separates the two by a wide margin.
+ const RELAUNCH_MAX_RATIO = 0.5
+ // relaunch_rows_ms: window load to the first stateful sidebar row, observed before the
+ // test clicks anything; the non-blocking chat:getIndex is what shortens it.
+ const rowsUnclicked = samples
+ .filter(sample => sample.metric === 'relaunch_rows_ms')
+ .every(sample => sample.before_first_click === true)
+ const rowsBefore = quantiles(relaunchSamples('before', 'relaunch_rows_ms')).p50,
+ rowsAfter = quantiles(relaunchSamples('after', 'relaunch_rows_ms')).p50
+ report.gates.push({
+ metric: 'relaunch_rows_ms',
+ definition: 'window load -> first stateful sidebar row, before any click',
+ before: rowsBefore,
+ after: rowsAfter,
+ observed_before_click: rowsUnclicked,
+ max_ratio: RELAUNCH_MAX_RATIO,
+ passed: rowsUnclicked && rowsAfter <= RELAUNCH_MAX_RATIO * rowsBefore,
+ })
+ // relaunch_ms: window load to the transcript of the selected chat, including the explicit
+ // open. Desktop never restores the last active chat on launch.
+ const before = quantiles(relaunchSamples('before', 'relaunch_ms')).p50,
+ after = quantiles(relaunchSamples('after', 'relaunch_ms')).p50
+ report.gates.push({
+ metric: 'relaunch_ms',
+ definition: 'window load -> sidebar row -> explicit open -> transcript with all messages',
+ before,
+ after,
+ max_ratio: RELAUNCH_MAX_RATIO,
+ passed: after <= RELAUNCH_MAX_RATIO * before,
+ })
+ } else {
+ // W needs a control: BEFORE runs the same suspended-Host relaunches as AFTER.
+ const wake = (build: Build) => {
+ const found = values(build, HOSTS[0], 'first_stateful_row_ms')
+ if (found.length !== RELAUNCH_ROUNDS)
+ throw new Error(`W recorded ${found.length} ${build} first_stateful_row_ms samples.`)
+ return found
+ }
+ const wakeBefore = wake('before'),
+ wakeAfter = wake('after')
+ const afterMax = Math.max(...wakeAfter)
+ report.gates.push({
+ metric: 'first_stateful_row_ms',
+ after_max_ms: afterMax,
+ budget_ms: 2000,
+ passed: afterMax < 2000,
+ })
+ const beforeP50 = quantiles(wakeBefore).p50,
+ afterP50 = quantiles(wakeAfter).p50
+ report.gates.push({
+ metric: 'first_stateful_row_ms_vs_before',
+ before: beforeP50,
+ after: afterP50,
+ passed: afterP50 < beforeP50,
+ })
+ }
+ report.gates.push({
+ metric: 'round_validity',
+ invalidated: rounds.filter(round => round.invalidated).length,
+ passed: rounds.every(round => !round.invalidated),
+ })
+ // 1-minute load spread across the rounds of each scenario.
+ for (const scenario of phase === 'OL' ? ['O', 'L'] : ['W']) {
+ const loads = rounds
+ .filter(round => round.scenario === scenario)
+ .map(round => round.loadavg[0]!)
+ if (loads.length === 0) throw new Error(`Scenario ${scenario} recorded no rounds.`)
+ const spread = Math.max(...loads) - Math.min(...loads)
+ report.loadSpread.push({ scenario, spread, budget: 1, within_budget: spread <= 1 })
+ }
+ report.complete = true
+ } finally {
+ try {
+ await close()
+ } finally {
+ // Chat text stays in memory; evidence contains only catalog sizes, identities and raw timings.
+ const catalogs = report.catalogs.map(({ chats, ...catalog }) => ({
+ ...catalog,
+ chats: chats.map(({ id, count }) => ({ id, count })),
+ }))
+ fs.mkdirSync(path.dirname(output), { recursive: true })
+ fs.writeFileSync(output, JSON.stringify({ ...report, catalogs }, null, 2), { mode: 0o600 })
+ }
+ }
+ // O: three gates per Host; L: two; W: two; both phases: round validity.
+ expect(report.gates.length, 'Desktop A/B gate count').toBe(
+ phase === 'OL' ? HOSTS.length * 3 + 3 : 3
+ )
+ expect(
+ report.gates.every(gate => gate.passed),
+ `Desktop A/B gates: ${JSON.stringify(report.gates)}; evidence: ${output}`
+ ).toBe(true)
+ })
+ }
diff --cc desktop-app/ui/src/App.tsx
index b74ca08f2,f874248b6..44cd5b0b3
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@@ -3056,8 -3175,9 +3175,9 @@@ export function App()
<AuthPage />
)}
{environmentSetupConfirmationDialog}
+ {environmentSwitchConfirmationDialog}
{environmentSetupSuccessDialog}
- <ToastStack items={vm.toasts} />
+ <ToastStack items={vm.toasts} onDismiss={vm.dismissToast} />
</>
)}
</div>
diff --cc desktop-app/ui/src/components/agents/ComposerPanel.tsx
index 03e18d1cd,5160ee069..840d67274
--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx
+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx
@@@ -127,9 -165,10 +165,11 @@@ export function ComposerPanel({ inline
handleAddComposerImageAttachments: onAddComposerImageAttachments,
handleUpdateComposerImageAttachment: onUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment: onRemoveComposerImageAttachment,
+ handleAddComposerFiles: onAddComposerFiles,
+ handleRemoveComposerFileAttachment: onRemoveComposerFileAttachment,
handleAddComposerReferenceAttachments: onAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment: onRemoveComposerReferenceAttachment,
+ handleClearComposerAttachments: onClearComposerAttachments,
handleSendAgentMessage: onSend,
handleRetryFailedAgentSend: onRetryFailedSend,
handleRecoverFailedAgentSend: onRecoverFailedSend,
diff --cc desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
index 9e709d0ae,e85c5f97a..4a305b018
--- a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
@@@ -18,8 -20,8 +20,9 @@@ import
} from '../../../../../src/imageInputDecision'
import type { WorkflowRecipeListResult } from '../../../../../src/types'
import type {
+ ComposerFileAttachment,
ComposerImageAttachment,
+ ComposerReferenceAttachment,
FailedAgentSend,
} from '../../../uiTypes'
import { ComposerPanel } from '../ComposerPanel'
@@@ -50,9 -54,10 +55,11 @@@ const actionsMock =
handleAddComposerImageAttachments: vi.fn(),
handleUpdateComposerImageAttachment: vi.fn(),
handleRemoveComposerImageAttachment: vi.fn(),
+ handleAddComposerFiles: vi.fn(),
+ handleRemoveComposerFileAttachment: vi.fn(),
handleAddComposerReferenceAttachments: vi.fn(),
handleRemoveComposerReferenceAttachment: vi.fn(),
+ handleClearComposerAttachments: vi.fn(),
handleSendAgentMessage: vi.fn(),
handleRetryFailedAgentSend: vi.fn(),
handleRecoverFailedAgentSend: vi.fn(),
diff --cc desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts
index 5e0baf8b6,936c9fc35..915a6ab8c
--- a/desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts
+++ b/desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts
@@@ -31,9 -31,10 +31,11 @@@ export interface AgentChatActionsContex
handleAddComposerImageAttachments: (attachments: ComposerImageAttachment[]) => void
handleUpdateComposerImageAttachment: (attachment: ComposerImageAttachment) => void
handleRemoveComposerImageAttachment: (attachmentId: string) => void
+ handleAddComposerFiles: (files: File[], draft: string) => void
+ handleRemoveComposerFileAttachment: (attachmentId: string) => void
handleAddComposerReferenceAttachments: (attachments: ComposerReferenceAttachment[]) => void
handleRemoveComposerReferenceAttachment: (attachmentId: string) => void
+ handleClearComposerAttachments: () => void
handleSendAgentMessage: (text: string) => Promise<void>
handleRetryFailedAgentSend: () => Promise<void>
handleRecoverFailedAgentSend: () => void
diff --cc desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
index 830d83e39,f6c9deddf..4b8332963
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
@@@ -3,7 -3,8 +3,9 @@@ import { vi } from 'vitest
import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'
import { act, renderHook } from '@testing-library/react'
import type { HostAuthorityHoldKind } from '../../../../lib/hostAuthorityStore'
+ import type { Tone } from '../../../../uiTypes'
import { useAgentChatController } from '../../useAgentChatController'
++import type { PushToastOptions } from '../../useToastController'
import { type HarnessHostAuthority, useHarnessHostAuthority } from './hostAuthorityHarness'
type ControllerParams = Parameters<typeof useAgentChatController>[0]
@@@ -26,7 -27,7 +28,9 @@@ export interface RenderControllerResul
isBlocked: (agentRef: string) => boolean
}
spies: {
- pushToast: ReturnType<typeof vi.fn>
- pushToast: ReturnType<typeof vi.fn<(message: string, tone: Tone) => void>>
++ pushToast: ReturnType<
++ typeof vi.fn<(message: string, tone: Tone, options?: PushToastOptions) => void>
++ >
pushNotification: ReturnType<typeof vi.fn>
showDesktopNotification: ReturnType<typeof vi.fn>
openAgentConversationFromNotification: ReturnType<typeof vi.fn>
@@@ -47,10 -55,11 +58,11 @@@ export interface RenderControllerOption
* factory, so epoch comparisons in the controller are exercised for real.
*/
export function renderController(
- overrides: Partial<ControllerParams> = {}
+ overrides: Partial<ControllerParams> = {},
+ options: RenderControllerOptions = {}
): RenderControllerResult {
const spies = {
- pushToast: vi.fn(),
- pushToast: vi.fn<(message: string, tone: Tone) => void>(),
++ pushToast: vi.fn<(message: string, tone: Tone, options?: PushToastOptions) => void>(),
pushNotification: vi.fn(),
showDesktopNotification: vi.fn(async () => 'granted' as const),
openAgentConversationFromNotification: vi.fn(async () => undefined),
diff --cc desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
index c2d834c0b,000000000..6e5f5ee24
mode 100644,000000..100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
@@@ -1,572 -1,0 +1,572 @@@
+// @vitest-environment jsdom
+/**
+ * STORY-38 — canceling an in-flight task keeps the canceled message's
+ * attachments available: they return to the in-memory composer state (never
+ * GFS or another persisted store) and an "Attachments kept" toast offers an
+ * explicit "Discard all" action. The retained send snapshot itself is still
+ * released (a cancel stays terminal for delivery), and a cancel that fails
+ * upstream restores nothing.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, waitFor } from '@testing-library/react'
+import { loadHostModels, resetHostModelSelectionStore } from '@lib/hostModelSelectionStore'
+import type { HostModelsResult } from '../../../../../src/types'
+import type {
+ ComposerImageAttachment,
+ ComposerPluginReference,
+ ToastMessageAction,
+} from '../../../uiTypes'
+import { renderController } from './__fixtures__/controllerHarness'
+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'
+
+let clerum: MockClerum
+const image: ComposerImageAttachment = {
+ id: 'input-image',
+ name: 'input.png',
+ mimeType: 'image/png',
+ dataBase64: 'YWJj',
+ sizeBytes: 3,
+ previewDataUrl: 'data:image/png;base64,YWJj',
+}
+const pluginReference: ComposerPluginReference = {
+ id: 'plugin-ref',
+ type: 'plugin',
+ namespace: 'ns',
+ name: 'helper',
+ label: 'helper plugin',
+}
+/** A SECOND payload, for the R3-M4 "two batches" case. */
+const secondImage: ComposerImageAttachment = {
+ id: 'input-image-two',
+ name: 'input-two.png',
+ mimeType: 'image/png',
+ dataBase64: 'ZGVm',
+ sizeBytes: 3,
+ previewDataUrl: 'data:image/png;base64,ZGVm',
+}
+const secondReference: ComposerPluginReference = {
+ id: 'plugin-ref-two',
+ type: 'plugin',
+ namespace: 'ns',
+ name: 'helper-two',
+ label: 'helper plugin two',
+}
+const catalog: HostModelsResult = {
+ provider: 'zai',
+ hostDefault: 'glm-5.3-flash',
+ sessionModel: null,
+ degraded: false,
+ modelSelectionRevision: 0,
+ models: [{ name: 'glm-5.3-flash', imageInput: { state: 'supported', reason: 'supported' } }],
+}
+
+const modelTransport = {
+ getHostModels: vi.fn(async () => catalog),
+ setHostModel: vi.fn(async (_host: string, _chat: string, model: string) => ({
+ effective: 'next-task' as const,
+ provider: 'zai',
+ model,
+ modelSelectionRevision: 1,
+ })),
+}
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+beforeEach(() => {
+ clerum = installMockClerum()
+ Object.assign(clerum.rpc, modelTransport)
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ resetHostModelSelectionStore()
+ uninstallMockClerum()
+})
+
+function keptToastCall(
+ spies: ReturnType<typeof renderController>['spies']
+): [string, unknown, { action?: ToastMessageAction } | undefined] | undefined {
+ return spies.pushToast.mock.calls.find(([message]) =>
+ String(message).startsWith('Attachments kept')
+ ) as ReturnType<typeof keptToastCall>
+}
+
+function keptToastAction(
+ spies: ReturnType<typeof renderController>['spies']
+): ToastMessageAction | undefined {
+ return keptToastCall(spies)?.[2]?.action
+}
+
+/** Mounts with a capable model catalog, then attaches an image + a reference. */
+async function mountedControllerWithAttachments() {
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments([pluginReference]))
+ return rendered
+}
+
+/** Sends the pending payload as an async task and waits for its progress handler. */
+async function sendAsync(result: ReturnType<typeof renderController>['result'], taskId: string) {
+ clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId })
+ const send = act(async () => {
+ await result.current.handleSendAgentMessage('cancel me')
+ })
+ await waitFor(() => expect(clerum.hasProgressHandler(taskId)).toBe(true))
+ await send
+}
+
+describe('STORY-38 — attachments survive message cancel', () => {
+ it('returns the canceled message attachments to the composer with a Discard all toast', async () => {
+ const { result, spies } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-cancel')
+ // The accepted send cleared the composer.
+ expect(result.current.composerImageAttachments).toHaveLength(0)
+ expect(result.current.composerReferenceAttachments).toHaveLength(0)
+
+ await act(async () => {
+ await result.current.cancelTask('task-cancel')
+ })
+
+ expect(clerum.rpc.cancelTask).toHaveBeenCalledWith('agent-x', 'task-cancel')
+ expect(result.current.composerImageAttachments[0]).toMatchObject({
+ id: image.id,
+ dataBase64: image.dataBase64,
+ previewDataUrl: 'data:image/png;base64,YWJj',
+ })
+ expect(result.current.composerReferenceAttachments[0]).toMatchObject({
+ id: pluginReference.id,
+ })
+ const action = keptToastAction(spies)
+ expect(action?.label).toBe('Discard all')
+
+ act(() => action?.onAction())
+ expect(result.current.composerImageAttachments).toHaveLength(0)
+ expect(result.current.composerReferenceAttachments).toHaveLength(0)
+ })
+
+ it('restores the attachments when the task is already gone upstream', async () => {
+ clerum.rpc.cancelTask.mockRejectedValue(new Error('404 Not Found'))
+ const { result, spies } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-gone')
+
+ await act(async () => {
+ await result.current.cancelTask('task-gone')
+ })
+
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+ expect(result.current.composerReferenceAttachments).toHaveLength(1)
+ expect(keptToastAction(spies)?.label).toBe('Discard all')
+ })
+
+ it('restores nothing and toasts nothing for a text-only canceled message', async () => {
+ const rendered = renderController()
+ const { result, spies } = rendered
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await sendAsync(result, 'task-text')
+
+ await act(async () => {
+ await result.current.cancelTask('task-text')
+ })
+
+ expect(result.current.composerImageAttachments).toHaveLength(0)
+ expect(result.current.composerReferenceAttachments).toHaveLength(0)
+ expect(keptToastAction(spies)).toBeUndefined()
+ })
+
+ it('restores nothing when the cancel itself fails upstream', async () => {
+ clerum.rpc.cancelTask.mockRejectedValue(new Error('500 upstream exploded'))
+ const { result, spies } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-fail')
+
+ await act(async () => {
+ await result.current.cancelTask('task-fail')
+ })
+
+ expect(result.current.composerImageAttachments).toHaveLength(0)
+ expect(result.current.composerReferenceAttachments).toHaveLength(0)
+ expect(keptToastAction(spies)).toBeUndefined()
+ expect(spies.pushToast).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to cancel task'),
+ 'error'
+ )
+ })
+
+ it('reports images the composer cap drops instead of claiming all were kept (L2)', async () => {
+ const sent = [0, 1, 2].map(index => ({
+ ...image,
+ id: `sent-${index}`,
+ name: `sent-${index}.png`,
+ dataBase64: `c2VudC0-${index}`,
+ previewDataUrl: `data:image/png;base64,c2VudC0-${index}`,
+ }))
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments(sent))
+ await sendAsync(rendered.result, 'task-cap')
+
+ // While the task runs, the user fills the composer to the 20-image cap.
+ const filler = Array.from({ length: 19 }, (_, index) => ({
+ ...image,
+ id: `filler-${index}`,
+ name: `filler-${index}.png`,
+ dataBase64: `ZmlsbGVy-${index}`,
+ previewDataUrl: `data:image/png;base64,ZmlsbGVy-${index}`,
+ }))
+ act(() => rendered.result.current.handleAddComposerImageAttachments(filler))
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(19)
+
+ await act(async () => {
+ await rendered.result.current.cancelTask('task-cap')
+ })
+
+ // 19 held + 1 free slot: only 1 of the 3 canceled images returns, and the
+ // toast must say so instead of a plain "Attachments kept".
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(20)
+ const call = keptToastCall(rendered.spies)
+ expect(call?.[0]).toBe(
- 'Attachments kept — 2 of 3 images exceed the 20-image limit and were dropped.'
++ 'Attachments kept — 2 of 3 images exceed the 20-attachment limit and were dropped.'
+ )
+ expect(call?.[1]).toBe('info')
+ expect(call?.[2]?.action?.label).toBe('Discard all')
+ })
+
+ it('never clears another agent composer from a stale Discard all toast (L3)', async () => {
+ const { result, spies, rerender } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-switch')
+
+ await act(async () => {
+ await result.current.cancelTask('task-switch')
+ })
+ const staleAction = keptToastAction(spies)
+ expect(staleAction?.label).toBe('Discard all')
+
+ // The toast outlives an agent switch; the new agent's composer holds its
+ // own fresh attachment that the stale action must not destroy.
+ rerender({ selectedAgent: 'agent-y', agentNames: ['agent-x', 'agent-y'] })
+ const otherAgentImage = {
+ ...image,
+ id: 'agent-y-image',
+ dataBase64: 'YWdlbnQteQ',
+ previewDataUrl: 'data:image/png;base64,YWdlbnQteQ',
+ }
+ act(() => result.current.handleAddComposerImageAttachments([otherAgentImage]))
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+
+ act(() => staleAction?.onAction())
+
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+ expect(result.current.composerImageAttachments[0]).toMatchObject({ id: 'agent-y-image' })
+ })
+
+ it('does not restore attachments into another agent composer when the cancel answer lands late (L3)', async () => {
+ // The cancel RPC straddles an agent switch: its answer must not drop the
+ // canceled agent's attachments into the NEW agent's composer.
+ let resolveCancel!: () => void
+ clerum.rpc.cancelTask.mockReturnValue(
+ new Promise<void>(resolve => {
+ resolveCancel = resolve
+ })
+ )
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments([pluginReference]))
+ await sendAsync(rendered.result, 'task-slow')
+ const originChat = rendered.result.current.activeChatId
+
+ let cancelDone!: Promise<void>
+ act(() => {
+ cancelDone = rendered.result.current.cancelTask('task-slow')
+ })
+ // Switch agents while the RPC is still in flight.
+ rendered.rerender({ selectedAgent: 'agent-y', agentNames: ['agent-x', 'agent-y'] })
+
+ await act(async () => {
+ resolveCancel()
+ await cancelDone
+ })
+
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(0)
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(0)
+ expect(keptToastCall(rendered.spies)).toBeUndefined()
+ // R2-M1 — the canceled agent's attachments are not lost: returning to the
+ // originating agent and chat applies the parked restoration there.
+ rendered.rerender({ selectedAgent: 'agent-x', agentNames: ['agent-x', 'agent-y'] })
+ await act(async () => {
+ await rendered.result.current.switchToChat('agent-x', originChat!)
+ })
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(1)
+ expect(keptToastCall(rendered.spies)?.[0]).toBe('Attachments kept')
+ })
+
+ it.each([
+ ['first settles first', [0, 1]],
+ ['second settles first', [1, 0]],
+ ])(
+ 'keeps BOTH restorations when two cancels settle while another chat is viewed (R3-M4, %s)',
+ async (_name, settlementOrder) => {
+ // Two DISTINCT cancellations for the SAME originating chat settle while
+ // the user views a different chat. Both batches are parked under that
+ // chat's identity: the later one must NOT overwrite the earlier one, or
+ // the first batch's attachments are lost for good.
+ const cancelDeferreds: Array<() => void> = []
+ clerum.rpc.cancelTask.mockImplementation(
+ () =>
+ new Promise<void>(resolve => {
+ cancelDeferreds.push(resolve)
+ })
+ )
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments([pluginReference]))
+ await sendAsync(rendered.result, 'task-first')
+ const originChat = rendered.result.current.activeChatId
+
+ // The first task FAILS: its payload stays retained (that is what the
+ // cancel restores) and the chat is free to run a SECOND task.
+ clerum.rpc.getTaskResult.mockResolvedValue({ status: 'failed', error: 'the task failed' })
+ await act(async () => {
+ clerum.emitTaskProgress('task-first', { type: 'closed' })
+ })
+ await waitFor(() => expect(clerum.rpc.getTaskResult).toHaveBeenCalled())
+
+ // The first send auto-created the chat, and the visual send guard reads
+ // the CHAT-scoped model selection: reload it for the second send.
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', rendered.result.current.activeChatId, {
+ force: true,
+ })
+ })
+
+ // A SECOND send, with its own payload, in the SAME chat.
+ act(() => rendered.result.current.handleAddComposerImageAttachments([secondImage]))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments([secondReference]))
+ await sendAsync(rendered.result, 'task-second')
+
+ // Move to another chat, then let both cancels settle there.
+ await act(async () => {
+ await rendered.result.current.switchToChat('agent-x', 'another-chat')
+ })
+ let firstCancel!: Promise<void>
+ let secondCancel!: Promise<void>
+ act(() => {
+ firstCancel = rendered.result.current.cancelTask('task-first')
+ secondCancel = rendered.result.current.cancelTask('task-second')
+ })
+ expect(cancelDeferreds).toHaveLength(2)
+ await act(async () => {
+ for (const index of settlementOrder) cancelDeferreds[index]!()
+ await Promise.all([firstCancel, secondCancel])
+ })
+
+ // Nothing landed in the other chat's composer.
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(0)
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(0)
+
+ // Returning to the origin chat applies BOTH parked batches: no
+ // attachment was overwritten, whichever order they settled in.
+ await act(async () => {
+ await rendered.result.current.switchToChat('agent-x', originChat!)
+ })
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(2)
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(2)
+ expect(rendered.result.current.composerImageAttachments.map(item => item.id).sort()).toEqual(
+ [image.id, secondImage.id].sort()
+ )
+ // Each batch brought its own toast, bound to the same agent + chat.
+ const keptToasts = rendered.spies.pushToast.mock.calls.filter(([message]) =>
+ String(message).startsWith('Attachments kept')
+ )
+ expect(keptToasts).toHaveLength(2)
+ for (const [, , options] of keptToasts) {
+ expect((options as { action?: { label: string } } | undefined)?.action?.label).toBe(
+ 'Discard all'
+ )
+ }
+ }
+ )
+
+ it.each([
+ ['success answer', 'resolve'],
+ ['404 answer', '404'],
+ ])(
+ 'does not restore into another chat of the same agent when the cancel %s lands late (R1-H1)',
+ async (_name, mode) => {
+ let settleCancel!: (value?: void) => void
+ clerum.rpc.cancelTask.mockReturnValue(
+ new Promise<void>(resolve => {
+ settleCancel = resolve
+ })
+ )
+ if (mode === '404')
+ clerum.rpc.cancelTask.mockReturnValue(
+ new Promise((_resolve, reject) => {
+ settleCancel = () => reject(new Error('404 Not Found'))
+ })
+ )
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments([image]))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments([pluginReference]))
+ await sendAsync(rendered.result, 'task-chat-sw')
+ const originChat = rendered.result.current.activeChatId
+
+ let cancelDone!: Promise<void>
+ act(() => {
+ cancelDone = rendered.result.current.cancelTask('task-chat-sw')
+ })
+ // SAME agent, DIFFERENT chat while the RPC is in flight.
+ await act(async () => {
+ await rendered.result.current.switchToChat('agent-x', 'another-chat')
+ })
+ expect(rendered.result.current.activeChatId).toBe('another-chat')
+
+ await act(async () => {
+ settleCancel()
+ await cancelDone.catch(() => undefined)
+ })
+
+ // Nothing landed in the other chat's composer, and no kept-toast fired.
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(0)
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(0)
+ expect(keptToastCall(rendered.spies)).toBeUndefined()
+ // R2-M1 — returning to the origin chat PRESERVES the kept attachments:
+ // the parked restoration applies there with its toast.
+ await act(async () => {
+ await rendered.result.current.switchToChat('agent-x', originChat!)
+ })
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(1)
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(1)
+ expect(keptToastCall(rendered.spies)?.[0]).toBe('Attachments kept')
+ }
+ )
+
+ it('stale Discard all no-ops after a same-agent chat switch (R1-H1)', async () => {
+ const { result, spies } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-stale-chat')
+
+ await act(async () => {
+ await result.current.cancelTask('task-stale-chat')
+ })
+ const staleAction = keptToastAction(spies)
+ expect(staleAction?.label).toBe('Discard all')
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+
+ // Same agent, different chat: the kept attachments ride along (per-agent
+ // state), but the toast is bound to the chat it came from.
+ await act(async () => {
+ await result.current.switchToChat('agent-x', 'another-chat')
+ })
+ act(() => staleAction?.onAction())
+
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+ })
+
+ it('reports drops from the live composer state, not the render closure at cancel time (R1-M4)', async () => {
+ // The composer fills to 19 WHILE the cancel RPC is in flight — after the
+ // executing closure was captured. The toast must report drops against the
+ // state the merge actually reconciled with, not the stale empty snapshot.
+ let resolveCancel!: () => void
+ clerum.rpc.cancelTask.mockReturnValue(
+ new Promise<void>(resolve => {
+ resolveCancel = resolve
+ })
+ )
+ const sent = [0, 1, 2].map(index => ({
+ ...image,
+ id: `sent-${index}`,
+ name: `sent-${index}.png`,
+ dataBase64: `c2VudC0-${index}`,
+ previewDataUrl: `data:image/png;base64,c2VudC0-${index}`,
+ }))
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments(sent))
+ await sendAsync(rendered.result, 'task-race')
+
+ let cancelDone!: Promise<void>
+ act(() => {
+ cancelDone = rendered.result.current.cancelTask('task-race')
+ })
+ // 19 fresh images land in the composer while the RPC is pending.
+ const filler = Array.from({ length: 19 }, (_, index) => ({
+ ...image,
+ id: `filler-${index}`,
+ name: `filler-${index}.png`,
+ dataBase64: `ZmlsbGVy-${index}`,
+ previewDataUrl: `data:image/png;base64,ZmlsbGVy-${index}`,
+ }))
+ act(() => rendered.result.current.handleAddComposerImageAttachments(filler))
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(19)
+
+ await act(async () => {
+ resolveCancel()
+ await cancelDone
+ })
+
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(20)
+ const call = keptToastCall(rendered.spies)
+ expect(call?.[0]).toBe(
- 'Attachments kept — 2 of 3 images exceed the 20-image limit and were dropped.'
++ 'Attachments kept — 2 of 3 images exceed the 20-attachment limit and were dropped.'
+ )
+ })
+
+ it('enforces the reference cap while restoring and reports the overflow (R1-M5)', async () => {
+ const sentReferences = [0, 1].map(index => ({
+ ...pluginReference,
+ id: `sent-ref-${index}`,
+ name: `helper-${index}`,
+ label: `helper plugin ${index}`,
+ }))
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments(sentReferences))
+ await sendAsync(rendered.result, 'task-refs')
+
+ // Nine more references land while the task runs: 9 held + 2 restored
+ // would be 11 — one past the send-time file limit.
+ const heldReferences = Array.from({ length: 9 }, (_, index) => ({
+ ...pluginReference,
+ id: `held-ref-${index}`,
+ name: `held-${index}`,
+ label: `held plugin ${index}`,
+ }))
+ act(() => rendered.result.current.handleAddComposerReferenceAttachments(heldReferences))
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(11 - 2)
+
+ await act(async () => {
+ await rendered.result.current.cancelTask('task-refs')
+ })
+
+ // The composer ends AT the cap (sendable), and the toast reports the one
+ // reference that could not return.
+ expect(rendered.result.current.composerReferenceAttachments).toHaveLength(10)
+ const call = keptToastCall(rendered.spies)
+ expect(call?.[0]).toBe(
+ 'Attachments kept — 1 of 2 reference exceeds the 10-file limit and was dropped.'
+ )
+ })
+})
diff --cc desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx
index 35272c9dc,000000000..cdcf82505
mode 100644,000000..100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/composerMergeZipProperties.test.tsx
@@@ -1,420 -1,0 +1,420 @@@
+// @vitest-environment jsdom
+/**
+ * R1-M6 — property/invariant coverage for the merge, dedupe, cap and path
+ * normalization rules the cancel-restore and folder-zip paths rely on. These
+ * complement the example tests: the examples pin behavior at the boundaries,
+ * the properties pin the invariants for arbitrary inputs.
+ *
+ * The property runs are deliberately LARGE: the merge and allocation rules
+ * interact (caps, dedupe, ordering, case folding), and a small sample proves
+ * little about a rule that only misbehaves in a rare combination. Every run
+ * starts from a VALID composer state, so the invariants are provable against
+ * states production can actually hold.
+ */
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'
- import { COMPOSER_MAX_IMAGE_ATTACHMENTS } from '@constants/attachments'
++import { COMPOSER_MAX_ATTACHMENTS } from '@constants/attachments'
+import { GFS_ZIP_MAX_SEGMENT_NAME_BYTES, sanitizeZipSegment } from '@lib/gfsFolderZip'
+import type { ComposerImageAttachment, ComposerReferenceAttachment } from '@/uiTypes'
+import { ZipEntryNameAllocator, entryNameFitsZipFields } from '../../../../../src/gfs/zipEntryName'
+import {
+ mergeComposerImageAttachments,
+ mergeComposerReferenceAttachments,
+} from '../useComposerAttachments'
+
+/**
+ * Tens of thousands of cases per property. The properties are small (arrays
+ * of short strings), so this costs seconds, not minutes — and it is the
+ * difference between "the invariant held for 80 samples" and "the invariant
+ * held for 25 000".
+ */
+const PROPERTY_RUNS = 25_000
+
+const imageArbitrary = fc
+ .record({
+ id: fc.string({ minLength: 1, maxLength: 12 }),
+ dataBase64: fc.string({ minLength: 1, maxLength: 8 }),
+ sizeBytes: fc.nat(1000),
+ })
+ .map(record => ({
+ ...record,
+ name: `${record.id}.png`,
+ mimeType: 'image/png' as const,
+ previewDataUrl: `data:image/png;base64,${record.dataBase64}`,
+ }))
+
+const referenceArbitrary = fc
+ .record({
+ id: fc.string({ minLength: 1, maxLength: 12 }),
+ label: fc.string({ minLength: 0, maxLength: 12 }),
+ })
+ .map(record => ({
+ ...record,
+ type: 'plugin' as const,
+ namespace: 'ns',
+ name: record.id,
+ }))
+
+// R1-M6 (round 2): starting states must be VALID composer states. A generator
+// that can produce `existing` above the cap tests states production can never
+// hold, so every invariant below was provable against garbage. The existing
+// arrays are constrained to at-most-cap; incoming stays arbitrary.
+const heldImagesArbitrary = fc
+ .uniqueArray(imageArbitrary, {
+ minLength: 0,
- maxLength: COMPOSER_MAX_IMAGE_ATTACHMENTS,
++ maxLength: COMPOSER_MAX_ATTACHMENTS,
+ selector: item => `${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`,
+ })
+ .map(items => items as ComposerImageAttachment[])
+
+const heldReferencesArbitrary = fc
+ .uniqueArray(referenceArbitrary, {
+ minLength: 0,
+ maxLength: FILE_REFERENCE_MAX_COUNT,
+ selector: item => item.id,
+ })
+ .map(items => items as ComposerReferenceAttachment[])
+
+describe('composer merge invariants (R1-M6)', () => {
+ it('counts a cap-time duplicate as a duplicate, not a drop (R2-L1)', () => {
+ // Composer already at the cap; the restore payload is byte-identical to
+ // what is held. Nothing is lost — reporting a drop would be a lie.
- const held = Array.from({ length: COMPOSER_MAX_IMAGE_ATTACHMENTS }, (_, index) => ({
++ const held = Array.from({ length: COMPOSER_MAX_ATTACHMENTS }, (_, index) => ({
+ ...({} as ComposerImageAttachment),
+ id: `held-${index}`,
+ name: `held-${index}.png`,
+ mimeType: 'image/png' as const,
+ dataBase64: `aGVsZA-${index}`,
+ sizeBytes: 4,
+ previewDataUrl: `data:image/png;base64,aGVsZA-${index}`,
+ }))
+ const restore = [held[3]!, held[7]!]
+ const outcome = mergeComposerImageAttachments(held, restore)
+ expect(outcome.duplicates).toBe(2)
+ expect(outcome.dropped).toBe(0)
+ expect(outcome.kept).toBe(0)
- expect(outcome.next).toHaveLength(COMPOSER_MAX_IMAGE_ATTACHMENTS)
++ expect(outcome.next).toHaveLength(COMPOSER_MAX_ATTACHMENTS)
+ // The exact same set survives: restoring dropped nothing new.
+ expect(outcome.next).toEqual(held)
+ })
+
+ it('image merge: cap, count conservation, and existing-set stability', () => {
+ fc.assert(
+ fc.property(
+ heldImagesArbitrary,
+ fc.array(imageArbitrary, { maxLength: 30 }),
+ (existing, incoming) => {
+ // Valid starting state (R1-M6 round 2): a real composer is never
+ // above the cap, and never holds byte-duplicates.
- expect(existing.length).toBeLessThanOrEqual(COMPOSER_MAX_IMAGE_ATTACHMENTS)
++ expect(existing.length).toBeLessThanOrEqual(COMPOSER_MAX_ATTACHMENTS)
+ const outcome = mergeComposerImageAttachments(
+ existing,
+ incoming as ComposerImageAttachment[]
+ )
- expect(outcome.next.length).toBeLessThanOrEqual(COMPOSER_MAX_IMAGE_ATTACHMENTS)
++ expect(outcome.next.length).toBeLessThanOrEqual(COMPOSER_MAX_ATTACHMENTS)
+ expect(outcome.kept + outcome.duplicates + outcome.dropped).toBe(incoming.length)
+ // The composer never loses what it already held.
+ expect(outcome.next.slice(0, existing.length)).toEqual(existing)
+ // Duplicates never consume slots: keeping room is consistent with counts.
+ expect(outcome.kept).toBe(outcome.next.length - existing.length)
+ // Decision path (R2-L1): drops can only be NOT-held incoming items.
+ const heldKeys = new Set(
+ existing.map(item => `${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`)
+ )
+ const notHeldIncoming = incoming.filter(
+ item => !heldKeys.has(`${item.mimeType}:${item.sizeBytes}:${item.dataBase64}`)
+ )
+ expect(outcome.dropped).toBeLessThanOrEqual(notHeldIncoming.length)
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('image merge at cap: incoming duplicates never count as drops (decision path)', () => {
+ fc.assert(
+ fc.property(
- fc.integer({ min: 0, max: COMPOSER_MAX_IMAGE_ATTACHMENTS }),
++ fc.integer({ min: 0, max: COMPOSER_MAX_ATTACHMENTS }),
+ fc.array(imageArbitrary, { maxLength: 10 }),
+ (heldCount, extra) => {
+ // A composer at the cap whose restore payload includes held images:
+ // every held image reports as a duplicate and dropped is exactly the
+ // not-held overflow.
+ const held = Array.from({ length: heldCount }, (_, index) => ({
+ ...({} as ComposerImageAttachment),
+ id: `h-${index}`,
+ name: `h-${index}.png`,
+ mimeType: 'image/png' as const,
+ dataBase64: `aGQt${index}`,
+ sizeBytes: index,
+ previewDataUrl: `data:image/png;base64,aGQt${index}`,
+ }))
+ const payload = [
+ ...held.slice(0, Math.min(3, heldCount)),
+ ...(extra as ComposerImageAttachment[]),
+ ]
+ const outcome = mergeComposerImageAttachments(held, payload)
+ expect(outcome.next).toEqual(
+ held.length ? expect.arrayContaining(held) : expect.anything()
+ )
+ expect(outcome.next.length).toBe(Math.max(heldCount, 0) + outcome.kept)
+ const notHeld = payload.filter(
+ item =>
+ !held.some(h => h.dataBase64 === item.dataBase64 && h.sizeBytes === item.sizeBytes)
+ )
+ expect(outcome.dropped).toBe(
- Math.max(0, notHeld.length - Math.max(0, COMPOSER_MAX_IMAGE_ATTACHMENTS - heldCount))
++ Math.max(0, notHeld.length - Math.max(0, COMPOSER_MAX_ATTACHMENTS - heldCount))
+ )
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('image merge idempotence: a second identical restore changes nothing', () => {
+ fc.assert(
+ fc.property(
+ heldImagesArbitrary,
+ fc.array(imageArbitrary, { maxLength: 15 }),
+ (existing, incoming) => {
+ const first = mergeComposerImageAttachments(
+ existing,
+ incoming as ComposerImageAttachment[]
+ )
+ const second = mergeComposerImageAttachments(
+ first.next,
+ incoming as ComposerImageAttachment[]
+ )
+ // State stability: nothing new is kept, the composer is unchanged, and
+ // the payload still accounts entirely to duplicates + (persistent,
+ // cap-driven) drops — never to new losses.
+ expect(second.kept).toBe(0)
+ expect(second.next).toEqual(first.next)
+ expect(second.duplicates + second.dropped).toBe(incoming.length)
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('reference merge: file cap, count conservation, and id uniqueness', () => {
+ fc.assert(
+ fc.property(
+ heldReferencesArbitrary,
+ fc.array(referenceArbitrary, { maxLength: 25 }),
+ (existing, incoming) => {
+ const outcome = mergeComposerReferenceAttachments(
+ existing,
+ incoming as ComposerReferenceAttachment[]
+ )
+ expect(existing.length).toBeLessThanOrEqual(FILE_REFERENCE_MAX_COUNT)
+ expect(outcome.next.length).toBeLessThanOrEqual(FILE_REFERENCE_MAX_COUNT)
+ expect(outcome.kept + outcome.duplicates + outcome.dropped).toBe(incoming.length)
+ const ids = new Set(outcome.next.map(item => item.id))
+ expect(ids.size).toBe(outcome.next.length)
+ // Held references are never dropped (dedupe runs first).
+ expect(outcome.next.slice(0, existing.length)).toEqual(existing)
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('reference merge idempotence: a second identical restore changes nothing', () => {
+ fc.assert(
+ fc.property(
+ heldReferencesArbitrary,
+ fc.array(referenceArbitrary, { maxLength: 10 }),
+ (existing, incoming) => {
+ const first = mergeComposerReferenceAttachments(
+ existing,
+ incoming as ComposerReferenceAttachment[]
+ )
+ const second = mergeComposerReferenceAttachments(
+ first.next,
+ incoming as ComposerReferenceAttachment[]
+ )
+ expect(second.kept).toBe(0)
+ expect(second.next).toEqual(first.next)
+ expect(second.duplicates + second.dropped).toBe(incoming.length)
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('image merge: a duplicate arriving AFTER the cap is reached is a duplicate (R4-L1)', () => {
+ // The composer is full. The payload's FIRST item is unique — it is
+ // dropped — and the SECOND is a byte-identical copy of an image the
+ // composer already holds. Nothing was lost by the second item, so it is a
+ // DUPLICATE, not another drop: stopping the scan at the cap would
+ // classify it without looking at it and report a lost attachment.
- const held = Array.from({ length: COMPOSER_MAX_IMAGE_ATTACHMENTS }, (_, index) => ({
++ const held = Array.from({ length: COMPOSER_MAX_ATTACHMENTS }, (_, index) => ({
+ ...({} as ComposerImageAttachment),
+ id: `held-${index}`,
+ name: `held-${index}.png`,
+ mimeType: 'image/png' as const,
+ dataBase64: `aGQt${index}`,
+ sizeBytes: index,
+ previewDataUrl: `data:image/png;base64,aGQt${index}`,
+ }))
+ const outcome = mergeComposerImageAttachments(held, [
+ {
+ id: 'unique',
+ name: 'unique.png',
+ mimeType: 'image/png' as const,
+ dataBase64: 'dW5pcXVl',
+ sizeBytes: 7,
+ previewDataUrl: 'data:image/png;base64,dW5pcXVl',
+ },
+ // A byte-identical copy of the FIRST held image.
+ {
+ id: 'held-0',
+ name: 'held-0.png',
+ mimeType: 'image/png' as const,
+ dataBase64: 'aGQt0',
+ sizeBytes: 0,
+ previewDataUrl: 'data:image/png;base64,aGQt0',
+ },
+ ])
+ expect(outcome.kept).toBe(0)
+ expect(outcome.duplicates).toBe(1)
+ expect(outcome.dropped).toBe(1)
+ expect(outcome.next).toEqual(held)
+ })
+
+ it('reference merge: a duplicate arriving AFTER the cap is reached is a duplicate (R4-L1)', () => {
+ const held = Array.from({ length: FILE_REFERENCE_MAX_COUNT }, (_, index) => ({
+ ...({} as ComposerReferenceAttachment),
+ id: `held-${index}`,
+ type: 'plugin' as const,
+ namespace: 'ns',
+ name: `held-${index}`,
+ label: `held ${index}`,
+ }))
+ const outcome = mergeComposerReferenceAttachments(held, [
+ {
+ id: 'unique',
+ type: 'plugin' as const,
+ namespace: 'ns',
+ name: 'unique',
+ label: 'unique',
+ },
+ // A copy of the FIRST held reference.
+ {
+ id: 'held-0',
+ type: 'plugin' as const,
+ namespace: 'ns',
+ name: 'held-0',
+ label: 'held 0',
+ },
+ ])
+ expect(outcome.kept).toBe(0)
+ expect(outcome.duplicates).toBe(1)
+ expect(outcome.dropped).toBe(1)
+ expect(outcome.next).toEqual(held)
+ })
+})
+
+describe('zip path normalization invariants (R1-M6)', () => {
+ it('sanitized segments never carry separators, reserved chars, or excess length', () => {
+ fc.assert(
+ fc.property(fc.string({ maxLength: 2000 }), raw => {
+ const segment = sanitizeZipSegment(raw)
+ expect(segment.length).toBeGreaterThan(0)
+ expect(segment).not.toMatch(/[/\\:*?"<>|\u0000]/)
+ expect(new TextEncoder().encode(segment).length).toBeLessThanOrEqual(
+ GFS_ZIP_MAX_SEGMENT_NAME_BYTES
+ )
+ expect(segment).not.toBe('.')
+ expect(segment).not.toBe('..')
+ // A Windows DEVICE name is not a name: `CON` is the console device.
+ expect(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(segment)).toBe(false)
+ }),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('allocated entry names never collide case-folded and always fit the 16-bit fields', () => {
+ fc.assert(
+ fc.property(
+ fc.array(fc.string({ minLength: 1, maxLength: 24 }), { maxLength: 30 }),
+ names => {
+ const allocator = new ZipEntryNameAllocator()
+ const written: string[] = []
+ for (const name of names) {
+ const plan = allocator.plan(name)
+ if (!plan.fits) continue
+ allocator.commit(plan)
+ written.push(plan.name)
+ }
+ const folded = new Set(written.map(name => name.toLowerCase()))
+ expect(folded.size).toBe(written.length)
+ expect(written).toHaveLength(names.length)
+ for (const name of written) expect(entryNameFitsZipFields(name)).toBe(true)
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('never lets a FILE and a DIRECTORY share a path (R3-M5)', () => {
+ // The invariant that keeps an archive valid on a case-insensitive
+ // extractor: no committed file may sit at a path another committed file
+ // implies as a directory.
+ fc.assert(
+ fc.property(
+ fc.array(
+ fc.array(fc.string({ minLength: 1, maxLength: 12 }), { minLength: 1, maxLength: 4 }),
+ { maxLength: 20 }
+ ),
+ paths => {
+ const allocator = new ZipEntryNameAllocator()
+ const committed: string[] = []
+ for (const segments of paths) {
+ const plan = allocator.plan(segments.join('/'))
+ if (!plan.fits) continue
+ allocator.commit(plan)
+ committed.push(plan.name)
+ }
+ const files = new Set(committed.map(name => name.toLowerCase()))
+ const directories = new Set<string>()
+ for (const name of committed) {
+ const parts = name.split('/')
+ parts.pop()
+ let current = ''
+ for (const part of parts) {
+ current = current === '' ? part : `${current}/${part}`
+ directories.add(current.toLowerCase())
+ }
+ }
+ for (const file of files) {
+ expect(directories.has(file)).toBe(false)
+ }
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+
+ it('allocates deterministically: the same inputs give the same names', () => {
+ fc.assert(
+ fc.property(
+ fc.array(fc.string({ minLength: 1, maxLength: 16 }), { maxLength: 20 }),
+ names => {
+ const allocate = () => {
+ const allocator = new ZipEntryNameAllocator()
+ return names.map(name => {
+ const plan = allocator.plan(name)
+ if (plan.fits) allocator.commit(plan)
+ return plan.name
+ })
+ }
+ expect(allocate()).toEqual(allocate())
+ }
+ ),
+ { numRuns: PROPERTY_RUNS }
+ )
+ })
+})
diff --cc desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index eb6f0c8cf,2b4cee587..143fe7ce7
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@@ -6,8 -6,12 +6,13 @@@ import
parseTaskKey,
useAgentTaskTracker,
} from '@contexts/AgentTaskTrackerContext'
+import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'
- import { COMPOSER_MAX_IMAGE_ATTACHMENTS } from '@constants/attachments'
+ import {
+ COMPOSER_MAX_ATTACHMENTS,
+ COMPOSER_MAX_NON_IMAGE_BODY_BYTES,
+ COMPOSER_MAX_REQUEST_BODY_BYTES,
+ COMPOSER_MAX_TOTAL_FILE_BASE64_BYTES,
+ } from '@constants/attachments'
import {
buildChatMessageAttachments,
buildResponseFileAttachments,
@@@ -708,91 -876,23 +880,103 @@@ export function useAgentChatController(
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
+ handleAddComposerFiles,
+ handleRemoveComposerFileAttachment,
+ handleRestoreComposerFiles,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ restoreComposerImageAttachments,
+ restoreComposerReferenceAttachments,
} = useComposerAttachments({ selectedAgent, clearSendError: clearComposerSendError })
- // Only a fully read and hashed document can travel with a message (#678).
+ // R2-M1 — cancel-restorations parked while their originating chat is not the
+ // active one, keyed `${agentRef}::${chatId}`. Memory-only, same lifetime as
+ // composer state (cleared on session/agent-scope reset, never persisted): a
+ // cancel settling while another chat is viewed PRESERVES the kept
+ // attachments and applies them when the originating chat is active again.
+ //
+ // R3-M4 — the parked value is a QUEUE of restoration batches, not a single
+ // batch: two cancellations settling for the SAME originating chat while the
+ // user views another chat must not overwrite one another. Each batch keeps
+ // its own attachments, its own caps and its own toast.
+ const parkedRestorationsRef = useRef(
+ new Map<
+ string,
+ {
+ agentRef: string
+ chatId: string | null
+ batches: Array<{
+ images: ComposerImageAttachment[]
+ references: ComposerReferenceAttachment[]
+ }>
+ }
+ >()
+ )
+
+ /**
+ * Applies one kept-attachment restoration to the composer the user is
+ * currently viewing, with the atomic merge, honest drop reporting, and a
+ * Discard-all action bound to the originating agent AND chat. Shared by the
+ * settle-now path and the parked path (spec: round-2 extensions).
+ */
+ const applyKeptAttachments = useCallback(
+ (
+ agentRef: string,
+ chatId: string | null,
+ images: ComposerImageAttachment[],
+ references: ComposerReferenceAttachment[]
+ ) => {
+ const stillViewingOrigin = () =>
+ activeChatVisibilityRef.current.selectedAgent === agentRef &&
+ activeChatVisibilityRef.current.activeChatId === chatId
+ if (!stillViewingOrigin()) return
+ // One merge per kind against the live composer snapshot — the counts and
+ // the committed state can never disagree (R1-M4), and the reference cap
+ // is enforced while restoring so the composer stays sendable (R1-M5).
+ const imageOutcome = restoreComposerImageAttachments(images)
+ const referenceOutcome = restoreComposerReferenceAttachments(references)
+ const droppedParts: string[] = []
+ if (imageOutcome.dropped > 0) {
+ droppedParts.push(
- `${imageOutcome.dropped} of ${images.length} ${imageOutcome.dropped === 1 ? 'image exceeds' : 'images exceed'} the ${COMPOSER_MAX_IMAGE_ATTACHMENTS}-image limit`
++ `${imageOutcome.dropped} of ${images.length} ${imageOutcome.dropped === 1 ? 'image exceeds' : 'images exceed'} the ${COMPOSER_MAX_ATTACHMENTS}-attachment limit`
+ )
+ }
+ if (referenceOutcome.dropped > 0) {
+ droppedParts.push(
+ `${referenceOutcome.dropped} of ${references.length} ${referenceOutcome.dropped === 1 ? 'reference exceeds' : 'references exceed'} the ${FILE_REFERENCE_MAX_COUNT}-file limit`
+ )
+ }
+ const totalDropped = imageOutcome.dropped + referenceOutcome.dropped
+ const message = droppedParts.length
+ ? `Attachments kept — ${droppedParts.join('; ')} and ${totalDropped === 1 ? 'was' : 'were'} dropped.`
+ : 'Attachments kept'
+ pushToast(message, 'info', {
+ action: {
+ label: 'Discard all',
+ onAction: () => {
+ if (!stillViewingOrigin()) return
+ resetComposerAttachments()
+ },
+ },
+ })
+ },
+ [
+ pushToast,
+ resetComposerAttachments,
+ restoreComposerImageAttachments,
+ restoreComposerReferenceAttachments,
+ ]
+ )
+
+ const readyComposerFiles = useMemo(
+ () =>
+ composerFileAttachments.filter(
+ (file): file is ReadyComposerFileAttachment => file.status === 'ready'
+ ),
+ [composerFileAttachments]
+ )
+ const composerFilesBlockSend = composerFileAttachments.some(file => file.status !== 'ready')
+
const { chatEndRef, scrollChatToBottom } = useChatScroll({
selectedAgent,
activeChatId,
@@@ -3700,10 -4149,9 +4306,12 @@@
await window.clerum.rpc.cancelTask(hostRef, taskId)
markCancelled('Cancelled by user.')
// #654 M6 — a cancel is terminal by intent: the user does not want this
- // payload resent, so nothing will read the retained snapshot again. A
- // snapshot holding documents the Host never received stays for Recover
- // files (see releaseRetainedSendsForTask).
+ // payload resent, so nothing will read the retained snapshot again. The
+ // attachments themselves return to the composer (STORY-38) before the
- // snapshot that carried them is released.
++ // snapshot that carried them is released. A snapshot holding documents
++ // the Host never received stays for Recover files (see
++ // releaseRetainedSendsForTask).
+ restoreComposerAttachmentsAfterCancel(taskId, hostRef)
releaseRetainedSendsForTask(taskId)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
@@@ -3872,9 -4368,11 +4529,12 @@@
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
+ handleAddComposerFiles,
+ handleRemoveComposerFileAttachment,
+ handleRestoreComposerFiles,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ handleClearComposerAttachments: resetComposerAttachments,
cancelTask,
}
}
diff --cc desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
index e500ac7bd,47506011e..c898348c8
--- a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
+++ b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
@@@ -1,114 -1,21 +1,133 @@@
import { useCallback, useEffect, useRef, useState } from 'react'
+import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'
- import { COMPOSER_MAX_IMAGE_ATTACHMENTS } from '@constants/attachments'
- import { clearComposerDraft, clearComposerDraftAfterSend } from '@lib/composerDraftStore'
- import type { ComposerImageAttachment, ComposerReferenceAttachment } from '../../uiTypes'
+ import { COMPOSER_MAX_ATTACHMENTS } from '@constants/attachments'
+ import { clearComposerDraft } from '@lib/composerDraftStore'
+ import {
+ composerFileAdmissionError,
+ composerFileName,
+ readComposerFile,
+ } from '@lib/composerFileAdmission'
+ import { buildComposerFileReferences } from '@lib/composerFileReferences'
+ import { composerRequestBaseContent } from '@lib/composerHostRequest'
+ import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'
+ import type {
+ ComposerFileAttachment,
+ ComposerFileRefusal,
+ ComposerImageAttachment,
+ ComposerReferenceAttachment,
+ } from '../../uiTypes'
+export interface ComposerImageMergeOutcome {
+ /** The reconciled composer set (existing + accepted incoming, in order). */
+ next: ComposerImageAttachment[]
+ /** Incoming attachments that took a slot in the composer. */
+ kept: number
+ /** Incoming byte-identical copies of attachments already held (not added). */
+ duplicates: number
+ /** Incoming attachments the 20-image cap leaves no room for (lost). */
+ dropped: number
+}
+
+/**
+ * Reconciles incoming images into the composer's image set with the same
+ * dedupe/cap rules as the add handler, returning the merged set AND the
+ * counts. The restore path calls this against the live composer snapshot and
+ * commits the returned `next` directly, so the reported counts can never
+ * disagree with the state the user sees (spec: restore semantics).
+ */
+export function mergeComposerImageAttachments(
+ existing: ComposerImageAttachment[],
+ incoming: ComposerImageAttachment[],
- nextOrder: () => number = () => 0
++ nextOrder: () => number = () => 0,
++ /**
++ * Slots already taken by the OTHER attachment kinds. Images and documents
++ * share one per-message count, so the documents already attached occupy
++ * slots this restore must not take.
++ */
++ occupiedByFiles = 0
+): ComposerImageMergeOutcome {
+ const accepted = [...existing]
+ let kept = 0
+ let duplicates = 0
+ let dropped = 0
+ for (const attachment of incoming) {
+ // Dedupe BEFORE capacity (R2-L1): a byte-identical copy of an attachment
+ // the composer already holds is not "dropped at the cap" — nothing is
+ // lost, it is already there — so it must never consume the drop count (or
+ // a slot) even when the composer is full.
+ const duplicate = accepted.some(
+ candidate =>
+ candidate.mimeType === attachment.mimeType &&
+ candidate.sizeBytes === attachment.sizeBytes &&
+ candidate.dataBase64 === attachment.dataBase64
+ )
+ if (duplicate) {
+ duplicates += 1
+ continue
+ }
- if (accepted.length >= COMPOSER_MAX_IMAGE_ATTACHMENTS) {
++ if (accepted.length + occupiedByFiles >= COMPOSER_MAX_ATTACHMENTS) {
+ // The cap leaves no room: this attachment is dropped, but the loop
+ // CONTINUES (R4-L1). Stopping here would classify every LATER item as a
+ // drop without looking at it, so a duplicate that arrives after the cap
+ // was reached would be reported as a lost attachment when nothing was
+ // lost at all.
+ dropped += 1
+ continue
+ }
+ accepted.push(
+ attachment.addedOrder != null ? attachment : { ...attachment, addedOrder: nextOrder() }
+ )
+ kept += 1
+ }
+ return { next: accepted, kept, duplicates, dropped }
+}
+
+export interface ComposerReferenceMergeOutcome {
+ /** The reconciled composer set (existing + accepted incoming, in order). */
+ next: ComposerReferenceAttachment[]
+ /** Incoming references that took a slot in the composer. */
+ kept: number
+ /** Incoming references already held by id (not added). */
+ duplicates: number
+ /** Incoming references the send-time file limit leaves no room for (lost). */
+ dropped: number
+}
+
+/**
+ * Reconciles incoming references into the composer's reference set with the
+ * add handler's id-dedupe PLUS the send-time `FILE_REFERENCE_MAX_COUNT` cap: a
+ * restore that produces an unsendable composer is not a restore (spec: restore
+ * semantics), so the cap is enforced while restoring, not first at send.
+ */
+export function mergeComposerReferenceAttachments(
+ existing: ComposerReferenceAttachment[],
+ incoming: ComposerReferenceAttachment[],
+ nextOrder: () => number = () => 0
+): ComposerReferenceMergeOutcome {
+ const accepted = [...existing]
+ let kept = 0
+ let duplicates = 0
+ let dropped = 0
+ for (const attachment of incoming) {
+ if (accepted.some(candidate => candidate.id === attachment.id)) {
+ duplicates += 1
+ continue
+ }
+ if (accepted.length >= FILE_REFERENCE_MAX_COUNT) {
+ // The cap leaves no room: dropped, but the loop CONTINUES (R4-L1), so a
+ // duplicate arriving after the cap was reached is still classified as a
+ // duplicate rather than as a lost attachment.
+ dropped += 1
+ continue
+ }
+ accepted.push(
+ attachment.addedOrder != null ? attachment : { ...attachment, addedOrder: nextOrder() }
+ )
+ kept += 1
+ }
+ return { next: accepted, kept, duplicates, dropped }
+}
+
interface UseComposerAttachmentsParams {
/** Attachments are per-agent; switching agents clears the pending composer. */
selectedAgent: string | null
@@@ -127,12 -34,6 +146,12 @@@
* and the composer-draft-store integration. Extracted from `useAgentChatController`
* (Fase 1) with NO observable behavior change — the parent composes this and
* re-exposes the same public handlers to consumers.
+ *
- * The ref mirrors (`composerImageAttachmentsRef` / `composerReferenceAttachmentsRef`)
- * are written inside every state updater, so they always reflect the committed
- * transitions — never a stale render closure. The cancel-restore path reads and
- * writes through them so its reconciliation and its drop reporting use ONE
- * snapshot (R1-M4).
++ * The ref mirrors (`composerImagesRef` / `composerReferencesRef`) are written
++ * inside every state updater, so they always reflect the committed transitions
++ * — never a stale render closure. The cancel-restore path reads and writes
++ * through them so its reconciliation and its drop reporting use ONE snapshot
++ * (R1-M4).
*/
export function useComposerAttachments({
selectedAgent,
@@@ -144,11 -45,40 +163,53 @@@
const [composerReferenceAttachments, setComposerReferenceAttachments] = useState<
ComposerReferenceAttachment[]
>([])
+ const [composerFileAttachments, setComposerFileAttachments] = useState<ComposerFileAttachment[]>(
+ []
+ )
+ const [composerFileRefusals, setComposerFileRefusals] = useState<ComposerFileRefusal[]>([])
const composerAttachmentOrderRef = useRef(0)
const composerAttachmentRevisionRef = useRef(0)
- const composerImageAttachmentsRef = useRef<ComposerImageAttachment[]>([])
- const composerReferenceAttachmentsRef = useRef<ComposerReferenceAttachment[]>([])
+ // Mirrors of the state above. Admission of a file and the completion of its
+ // asynchronous read decide from the latest attachments, not from the render
+ // that started them.
+ const composerFilesRef = useRef<ComposerFileAttachment[]>([])
+ const composerImagesRef = useRef<ComposerImageAttachment[]>([])
+ const composerReferencesRef = useRef<ComposerReferenceAttachment[]>([])
+ composerReferencesRef.current = composerReferenceAttachments
+
+ const commitComposerFiles = useCallback(
+ (update: (previous: ComposerFileAttachment[]) => ComposerFileAttachment[]) => {
+ const next = update(composerFilesRef.current)
+ composerFilesRef.current = next
+ setComposerFileAttachments(next)
+ },
+ []
+ )
+
+ // Images and files share one per-message count, so both mirrors must hold
+ // what a gesture has already added before its next attach is decided.
+ const commitComposerImages = useCallback(
+ (update: (previous: ComposerImageAttachment[]) => ComposerImageAttachment[]) => {
+ const next = update(composerImagesRef.current)
+ composerImagesRef.current = next
+ setComposerImageAttachments(next)
+ },
+ []
+ )
+
++ // The same pattern for the references: the mirror is written inside the
++ // updater, so it always reflects the committed transitions — never a stale
++ // render closure. The cancel-restore path reads and writes through it, so
++ // its reconciliation and its drop reporting use ONE snapshot (R1-M4).
++ const commitComposerReferences = useCallback(
++ (update: (previous: ComposerReferenceAttachment[]) => ComposerReferenceAttachment[]) => {
++ const next = update(composerReferencesRef.current)
++ composerReferencesRef.current = next
++ setComposerReferenceAttachments(next)
++ },
++ []
++ )
+
const revokeComposerPreviewUrls = useCallback((attachments: ComposerImageAttachment[]) => {
composerAttachmentRevisionRef.current += 1
const canRevokeObjectUrl =
@@@ -166,31 -96,25 +227,25 @@@
const clearComposerImageAttachments = useCallback(() => {
composerAttachmentRevisionRef.current += 1
- setComposerImageAttachments(previous => {
+ commitComposerImages(previous => {
revokeComposerPreviewUrls(previous)
- composerImageAttachmentsRef.current = []
return []
})
- }, [revokeComposerPreviewUrls])
+ }, [commitComposerImages, revokeComposerPreviewUrls])
- /** Clear BOTH pending attachment kinds (revoking image blob URLs). */
+ const clearComposerFileAttachments = useCallback(() => {
+ composerAttachmentRevisionRef.current += 1
+ // A read still in flight finds no entry for its id and is dropped.
+ commitComposerFiles(() => [])
+ }, [commitComposerFiles])
+
+ /** Clear every pending attachment kind (revoking image blob URLs). */
const resetComposerAttachments = useCallback(() => {
clearComposerImageAttachments()
- setComposerReferenceAttachments(previous => {
- composerReferenceAttachmentsRef.current = []
- return []
- })
- }, [clearComposerImageAttachments])
-
- /** Post-send cleanup: clear the persisted draft for this chat, then the pending
- * attachments. Combines the three original send-path calls into one. */
- const clearComposerAfterSend = useCallback(
- (chatId: string | null) => {
- clearComposerDraftAfterSend(chatId)
- resetComposerAttachments()
- },
- [resetComposerAttachments]
- )
+ clearComposerFileAttachments()
+ setComposerFileRefusals([])
- setComposerReferenceAttachments([])
- }, [clearComposerFileAttachments, clearComposerImageAttachments])
++ commitComposerReferences(() => [])
++ }, [clearComposerFileAttachments, clearComposerImageAttachments, commitComposerReferences])
// Clear pending attachments when the selected agent changes (attachments are
// per-agent). The parent clears its own error/resend banner on the same change.
@@@ -266,46 -197,144 +328,174 @@@
if (removed.length) {
revokeComposerPreviewUrls(removed)
}
- return previous.filter(att => att.id !== attachmentId)
+ const next = previous.filter(att => att.id !== attachmentId)
- composerImageAttachmentsRef.current = next
+ return next
})
+ // Images and files share one per-message count, so removing an image
+ // frees a slot and a refusal such as the attachment count is stale.
+ setComposerFileRefusals([])
+ },
+ [commitComposerImages, revokeComposerPreviewUrls]
+ )
+
+ /**
+ * Adds picked documents (#678). Each accepted file appears at once as
+ * `reading` and becomes `ready` when its bytes are read and hashed. A file
+ * that breaks a limit, or cannot be read, gets no chip: its reason is shown
+ * as a refusal notice instead, so a refusal is never silent. The composer
+ * calls this once per gesture, with `[]` when the gesture carried only
+ * images, so each gesture replaces the refusals of the previous one; images
+ * of the same gesture refused later add to them.
+ */
+ const handleAddComposerFiles = useCallback(
+ (files: File[], draft: string) => {
+ composerAttachmentRevisionRef.current += 1
+ const refusals: ComposerFileRefusal[] = []
+ if (!files.length) {
+ setComposerFileRefusals(refusals)
+ return
+ }
+ // Admission measures the request the files would be sent with: the
+ // content with its references section, the structured references and the
+ // agent it is posted to. Without an agent, or with references the send
+ // itself would refuse, no file can be admitted.
+ const images = composerImagesRef.current
+ const references = composerReferencesRef.current
+ let referencesProblem: string | null = null
+ let fileReferences: ReturnType<typeof buildComposerFileReferences> = []
+ try {
+ fileReferences = buildComposerFileReferences(references)
+ } catch (error) {
+ referencesProblem = error instanceof Error ? error.message : String(error)
+ }
+ for (const file of files) {
+ const id = crypto.randomUUID()
+ const current = composerFilesRef.current
+ const error =
+ selectedAgent === null
+ ? 'Select an agent before attaching files.'
+ : (referencesProblem ??
+ composerFileAdmissionError(file, {
+ attachedCount: images.length + current.length,
+ files: current,
+ request: {
+ content: buildComposerRequestContent(
+ composerRequestBaseContent(draft.trim(), images.length, current.length + 1),
+ references
+ ),
+ fileReferences,
+ hostRef: selectedAgent,
+ images,
+ },
+ }))
+ composerAttachmentOrderRef.current += 1
+ const base = {
+ id,
+ addedOrder: composerAttachmentOrderRef.current,
+ type: 'file' as const,
+ filename: composerFileName(file),
+ sizeBytes: file.size,
+ declaredMediaType: file.type,
+ }
+ if (error) {
+ refusals.push({ id, text: error })
+ continue
+ }
+ commitComposerFiles(previous => [...previous, { ...base, status: 'reading' }])
+ void readComposerFile(file, id).then(result => {
+ // A file removed while it was read (by the user, a send or an agent
+ // change) leaves neither a chip nor a notice.
+ if (!composerFilesRef.current.some(item => item.id === id)) return
+ if (result.status === 'failed') {
+ commitComposerFiles(previous => previous.filter(item => item.id !== id))
+ setComposerFileRefusals(previous => [...previous, { id, text: result.error }])
+ return
+ }
+ // The same bytes under the same name are one document: the second copy
+ // leaves no chip, and the user is told why it did not appear.
+ const duplicate = composerFilesRef.current.some(
+ item =>
+ item.id !== id &&
+ item.status === 'ready' &&
+ item.filename === result.filename &&
+ item.digestHex === result.digestHex
+ )
+ if (duplicate) {
+ commitComposerFiles(previous => previous.filter(item => item.id !== id))
+ setComposerFileRefusals(previous => [
+ ...previous,
+ { id, text: `"${result.filename}" is already attached.` },
+ ])
+ return
+ }
+ commitComposerFiles(previous =>
+ previous.map(item =>
+ item.id === id ? { ...result, addedOrder: item.addedOrder } : item
+ )
+ )
+ })
+ }
+ setComposerFileRefusals(refusals)
+ clearSendError()
+ },
+ [clearSendError, commitComposerFiles, selectedAgent]
+ )
+
+ const handleRemoveComposerFileAttachment = useCallback(
+ (attachmentId: string) => {
+ composerAttachmentRevisionRef.current += 1
+ commitComposerFiles(previous => previous.filter(item => item.id !== attachmentId))
+ // Removing a file is how the user answers a refusal such as the
+ // attachment count or the file quota, so it must not stay on screen.
+ setComposerFileRefusals([])
+ clearSendError()
},
- [revokeComposerPreviewUrls]
+ [clearSendError, commitComposerFiles]
+ )
+
+ /** Puts back files that were attached to a send that failed. */
+ const handleRestoreComposerFiles = useCallback(
+ (files: ComposerFileAttachment[]) => {
+ composerAttachmentRevisionRef.current += 1
+ commitComposerFiles(() => files)
+ },
+ [commitComposerFiles]
)
+ /**
+ * Restore-path reconciliation for images (R1-M4): one merge against the live
+ * snapshot (the ref mirror written by every committed transition), committed
+ * directly, returning the counts that describe exactly that snapshot.
+ */
+ const restoreComposerImageAttachments = useCallback(
+ (incoming: ComposerImageAttachment[]): ComposerImageMergeOutcome => {
+ composerAttachmentRevisionRef.current += 1
+ const outcome = mergeComposerImageAttachments(
- composerImageAttachmentsRef.current,
++ composerImagesRef.current,
+ incoming,
+ () => {
+ composerAttachmentOrderRef.current += 1
+ return composerAttachmentOrderRef.current
- }
++ },
++ // Documents share the per-message count with images, so the ones
++ // already attached occupy slots this restore must not take.
++ composerFilesRef.current.length
+ )
+ for (const attachment of incoming) {
+ if (!outcome.next.includes(attachment)) revokeComposerPreviewUrls([attachment])
+ }
- composerImageAttachmentsRef.current = outcome.next
- setComposerImageAttachments(outcome.next)
++ commitComposerImages(() => outcome.next)
+ clearSendError()
+ return outcome
+ },
- [clearSendError, revokeComposerPreviewUrls]
++ [clearSendError, commitComposerImages, revokeComposerPreviewUrls]
+ )
+
const handleAddComposerReferenceAttachments = useCallback(
(attachments: ComposerReferenceAttachment[]) => {
composerAttachmentRevisionRef.current += 1
if (!attachments.length) return
-- setComposerReferenceAttachments(previous => {
++ commitComposerReferences(previous => {
const next = [...previous]
for (const attachment of attachments) {
if (!next.some(existing => existing.id === attachment.id)) {
@@@ -321,46 -349,18 +510,41 @@@
})
clearSendError()
},
-- [clearSendError]
++ [clearSendError, commitComposerReferences]
)
const handleRemoveComposerReferenceAttachment = useCallback(
(attachmentId: string) => {
composerAttachmentRevisionRef.current += 1
- setComposerReferenceAttachments(previous => {
- const next = previous.filter(att => att.id !== attachmentId)
- composerReferenceAttachmentsRef.current = next
- return next
- })
- setComposerReferenceAttachments(previous => previous.filter(att => att.id !== attachmentId))
++ commitComposerReferences(previous => previous.filter(att => att.id !== attachmentId))
// Removing a file is how the user answers the "at most 10 files" refusal,
// so the refusal must not stay on screen afterwards.
clearSendError()
},
-- [clearSendError]
++ [clearSendError, commitComposerReferences]
+ )
+
+ /**
+ * Restore-path reconciliation for references (R1-M5): id-dedupe plus the
+ * send-time file cap, applied against the live snapshot, with counts that
+ * describe exactly that reconciliation.
+ */
+ const restoreComposerReferenceAttachments = useCallback(
+ (incoming: ComposerReferenceAttachment[]): ComposerReferenceMergeOutcome => {
+ composerAttachmentRevisionRef.current += 1
+ const outcome = mergeComposerReferenceAttachments(
- composerReferenceAttachmentsRef.current,
++ composerReferencesRef.current,
+ incoming,
+ () => {
+ composerAttachmentOrderRef.current += 1
+ return composerAttachmentOrderRef.current
+ }
+ )
- composerReferenceAttachmentsRef.current = outcome.next
- setComposerReferenceAttachments(outcome.next)
++ commitComposerReferences(() => outcome.next)
+ clearSendError()
+ return outcome
+ },
- [clearSendError]
++ [clearSendError, commitComposerReferences]
)
return {
@@@ -373,9 -374,10 +558,12 @@@
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
+ handleAddComposerFiles,
+ handleRemoveComposerFileAttachment,
+ handleRestoreComposerFiles,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ restoreComposerImageAttachments,
+ restoreComposerReferenceAttachments,
}
}
diff --cc desktop-app/ui/src/hooks/useAgentChatActionsValue.ts
index d79891e84,f511f7d81..8375eaa07
--- a/desktop-app/ui/src/hooks/useAgentChatActionsValue.ts
+++ b/desktop-app/ui/src/hooks/useAgentChatActionsValue.ts
@@@ -57,9 -72,10 +73,11 @@@ export function useAgentChatActionsValu
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
+ handleAddComposerFiles,
+ handleRemoveComposerFileAttachment,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ handleClearComposerAttachments,
handleSendAgentMessage,
handleRetryFailedAgentSend,
handleRecoverFailedAgentSend,
@@@ -79,9 -95,10 +97,11 @@@
handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment,
+ handleAddComposerFiles,
+ handleRemoveComposerFileAttachment,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ handleClearComposerAttachments,
handleSendAgentMessage,
handleRetryFailedAgentSend,
handleRecoverFailedAgentSend,
diff --cc desktop-app/ui/src/hooks/useAppController.ts
index 1eecf6e4f,dce66d47f..257351dc0
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@@ -1564,9 -1639,10 +1640,11 @@@ export function useAppController()
handleAddComposerImageAttachments: chat.handleAddComposerImageAttachments,
handleUpdateComposerImageAttachment: chat.handleUpdateComposerImageAttachment,
handleRemoveComposerImageAttachment: chat.handleRemoveComposerImageAttachment,
+ handleAddComposerFiles: chat.handleAddComposerFiles,
+ handleRemoveComposerFileAttachment: chat.handleRemoveComposerFileAttachment,
handleAddComposerReferenceAttachments: chat.handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment: chat.handleRemoveComposerReferenceAttachment,
+ handleClearComposerAttachments: chat.handleClearComposerAttachments,
cancelTask: chat.cancelTask,
// MCP Server
diff --cc external-rest-api/src/services/invitationPasswordService.ts
index 000000000,73987faf9..717c1a003
mode 000000,100644..100644
--- a/external-rest-api/src/services/invitationPasswordService.ts
+++ b/external-rest-api/src/services/invitationPasswordService.ts
@@@ -1,0 -1,161 +1,171 @@@
+ import {
+ ControlApiError,
+ ControlApiTransportError,
+ ControlApiUnexpectedResponseError,
+ controlApiRequest,
+ } from '../controlApiClient.js'
+ import type { InvitationPreview } from './invitationsService.js'
+
+ type AuthContext = {
+ userId: string
+ email: string
+ sessionToken: string
+ }
+
+ type ResetPasswordDomainError =
- 'not_found' | 'forbidden' | 'not_pending' | 'expired' | 'invalid_invitation' | 'invalid_password'
++ | 'not_found'
++ | 'forbidden'
++ | 'not_pending'
++ | 'expired'
++ | 'invalid_invitation'
++ | 'invalid_password'
+
+ function invitationPasswordDomainError(
+ error: ControlApiError
+ ):
+ | 'not_found'
+ | 'forbidden'
+ | 'not_accepted'
+ | 'not_pending'
+ | 'expired'
+ | 'invalid_password'
+ | null {
+ const code = error.code
+ if (error.status === 400 && code === 'invalid_password') return 'invalid_password'
+ if (error.status === 401 && code === 'user_retired') return 'not_found'
+ if (error.status === 403 && code === 'forbidden') return 'forbidden'
+ if (error.status === 404 && code === 'not_found') return 'not_found'
+ if (error.status === 409 && code === 'invitation_not_accepted') return 'not_accepted'
+ if (error.status === 409 && code === 'invitation_not_pending') return 'not_pending'
+ if (error.status === 410 && code === 'expired') return 'expired'
+ return null
+ }
+
+ function resetPasswordDomainError(error: ControlApiError): ResetPasswordDomainError | null {
+ const code = error.code
+ if (error.status === 400 && code === 'invalid_password') return 'invalid_password'
+ if (error.status === 400 && code === 'invalid_invitation') return 'invalid_invitation'
+ if (error.status === 401 && code === 'user_retired') return 'invalid_invitation'
+ if (error.status === 403 && code === 'forbidden') return 'forbidden'
+ if (error.status === 404 && code === 'not_found') return 'not_found'
+ if (
+ error.status === 409 &&
+ (code === 'invitation_not_pending' || code === 'invitation_not_ready')
+ ) {
+ return 'not_pending'
+ }
+ if (error.status === 410 && code === 'expired') return 'expired'
+ return null
+ }
+
+ function unknownRecoveryOutcome(): ControlApiError {
+ return new ControlApiError(
+ 'Password recovery outcome is unknown',
+ 503,
+ { error: 'recovery_outcome_unknown' },
+ { 'retry-after': '2' }
+ )
+ }
+
+ function passwordAuthorityUnavailable(): ControlApiError {
+ return new ControlApiError(
+ 'Password recovery authority unavailable',
+ 503,
+ { error: 'authority_unavailable' },
+ { 'retry-after': '2' }
+ )
+ }
+
+ export async function setupInvitationPassword(
+ auth: AuthContext,
+ invitationId: string,
+ password: string
+ ): Promise<{
+ error?:
- 'not_found' | 'forbidden' | 'not_accepted' | 'not_pending' | 'expired' | 'invalid_password'
++ | 'not_found'
++ | 'forbidden'
++ | 'not_accepted'
++ | 'not_pending'
++ | 'expired'
++ | 'invalid_password'
+ data?: InvitationPreview & { passwordUpdated: boolean }
+ }> {
+ try {
+ const data = await controlApiRequest<InvitationPreview & { passwordUpdated: boolean }>(
+ 'POST',
+ '/external/invitations/password',
+ {
+ body: {
+ userId: auth.userId,
+ email: auth.email,
+ invitationId,
+ password,
+ },
+ userSessionToken: auth.sessionToken,
+ }
+ )
+ return { data }
+ } catch (error) {
+ if (error instanceof ControlApiTransportError) throw passwordAuthorityUnavailable()
+ if (
+ error instanceof ControlApiError &&
+ error.status === 500 &&
+ error.code === 'internal_error'
+ ) {
+ throw error
+ }
+ if (error instanceof ControlApiError && [429, 503].includes(error.status)) throw error
+ if (error instanceof ControlApiError) {
+ const domainError = invitationPasswordDomainError(error)
+ if (domainError) return { error: domainError }
+ if (error.status === 401) throw passwordAuthorityUnavailable()
+ if (error.status >= 500) throw passwordAuthorityUnavailable()
+ throw new ControlApiUnexpectedResponseError()
+ }
+ throw error
+ }
+ }
+
+ export async function setupInvitationPasswordWithToken(
+ token: string,
+ email: string,
+ invitationId: string,
+ password: string
+ ): Promise<{
+ error?:
+ | 'not_found'
+ | 'forbidden'
+ | 'not_accepted'
+ | 'not_pending'
+ | 'expired'
+ | 'invalid_invitation'
+ | 'invalid_password'
+ data?: InvitationPreview & { passwordUpdated: boolean; token: string }
+ }> {
+ try {
+ const data = await controlApiRequest<
+ InvitationPreview & { passwordUpdated: boolean; token: string }
+ >('POST', '/external/invitations/password-token', {
+ body: { email, token, invitationId, password },
+ })
+ return { data }
+ } catch (error) {
+ if (error instanceof ControlApiTransportError) throw unknownRecoveryOutcome()
+ if (error instanceof ControlApiError && error.status === 429) throw error
+ if (error instanceof ControlApiError) {
+ if (error.status === 500 && error.code === 'internal_error') throw error
+ if (
+ error.status === 503 &&
+ (error.code === 'authority_unavailable' || error.code === 'recovery_outcome_unknown')
+ ) {
+ throw error
+ }
+ const domainError = resetPasswordDomainError(error)
+ if (domainError) return { error: domainError }
+ if (error.status === 401) throw passwordAuthorityUnavailable()
+ if (error.status >= 500) throw unknownRecoveryOutcome()
+ throw new ControlApiUnexpectedResponseError()
+ }
+ throw error
+ }
+ }
diff --cc mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts
index 484df5044,c2cc8d641..fe5ccc0c3
--- a/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts
+++ b/mcp-host/src/core/conversation/persistence/__tests__/persistQueue.test.ts
@@@ -97,4 -184,686 +184,683 @@@ describe('PersistQueue', () =>
worker.emit('exit', 137)
await expect(promise).rejects.toThrow(/db worker exited/)
})
+
+ it('rejects async writes admitted after the worker exited instead of dropping them', async () => {
+ const worker = new FakeWorker()
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ // Liveness witness: while the worker is alive the async write is posted.
+ expect(worker.sent).toHaveLength(1)
+
+ worker.emit('exit', 137)
+ expect(() => q.enqueueAsync('s1', { kind: 'ping' })).toThrow(/db worker exited \(code=137\)/)
+ expect(worker.sent).toHaveLength(1)
+ })
+
+ it('fails the next write on the same queue after an async write failed', async () => {
+ const worker = new FakeWorker()
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ // Witness: a sync write before any failure resolves.
+ const first = q.enqueueSync({ kind: 'ping' })
+ worker.emit('message', {
+ id: worker.sent[0].id,
+ ok: true,
+ result: 'pong',
+ } satisfies WorkerReply)
+ await expect(first).resolves.toBe('pong')
+
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ worker.emit('message', {
+ id: worker.sent[1].id,
+ ok: false,
+ error: { code: 'SQLITE_FULL', message: 'database or disk is full' },
+ } satisfies WorkerReply)
+ await new Promise(r => setImmediate(r))
+
+ await expect(q.enqueueSync({ kind: 'ping' })).rejects.toThrow(
+ /async write failed \(sessionKey=s1\): database or disk is full/
+ )
+ expect(() => q.enqueueAsync('s2', { kind: 'ping' })).toThrow(/database or disk is full/)
+ })
+
+ it('calls onExit and onFailure once when the worker exits unexpectedly', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const exits: number[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ onFailure: err => failures.push(err),
+ onExit: code => exits.push(code),
+ })
+ // Liveness witness: with the worker alive a write is acknowledged and
+ // onFailure has not fired.
+ const ok = q.enqueueSync({ kind: 'ping' })
+ worker.emit('message', {
+ id: worker.sent[0].id,
+ ok: true,
+ result: 'pong',
+ } satisfies WorkerReply)
+ await expect(ok).resolves.toBe('pong')
+ expect(failures).toHaveLength(0)
+
+ worker.emit('exit', 1)
+ expect(exits).toEqual([1])
+ expect(failures.map(e => e.message)).toEqual(['db worker exited (code=1)'])
+ // A later rejected write does not report a second failure.
+ expect(() => q.enqueueAsync('s1', { kind: 'ping' })).toThrow(/db worker exited/)
+ expect(failures).toHaveLength(1)
+ })
+
+ it('calls onFailure once when an async write fails', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ onFailure: err => failures.push(err),
+ })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ q.enqueueAsync('s2', { kind: 'ping' })
+ await Promise.resolve()
+ expect(worker.sent).toHaveLength(2)
+
+ // Liveness witness: an acknowledged async write does not fire onFailure.
+ worker.emit('message', {
+ id: worker.sent[0].id,
+ ok: true,
+ result: 'pong',
+ } satisfies WorkerReply)
+ await new Promise(r => setImmediate(r))
+ expect(failures).toHaveLength(0)
+
+ worker.emit('message', {
+ id: worker.sent[1].id,
+ ok: false,
+ error: { code: 'SQLITE_FULL', message: 'database or disk is full' },
+ } satisfies WorkerReply)
+ await new Promise(r => setImmediate(r))
+ expect(failures.map(e => e.message)).toEqual([
+ 'async write failed (sessionKey=s2): database or disk is full',
+ ])
+
+ // A worker exit after the failure does not report a second one.
+ worker.emit('exit', 1)
+ expect(failures).toHaveLength(1)
+ })
+
+ it('keeps a slow async write pending past asyncTimeoutMs and its key ordered until the ACK', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 20,
+ stallTimeoutMs: 30_000,
+ onFailure: err => failures.push(err),
+ })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ // Liveness witness: the first write was posted.
+ expect(worker.sent).toHaveLength(1)
+ await new Promise(r => setTimeout(r, 80))
+ // Past the threshold: still pending, the second write still queued behind it.
+ expect(failures).toHaveLength(0)
+ expect(worker.sent).toHaveLength(1)
+
+ worker.emit('message', { id: worker.sent[0].id, ok: true, result: null } satisfies WorkerReply)
+ await new Promise(r => setImmediate(r))
+ expect(worker.sent).toHaveLength(2)
+ worker.emit('message', { id: worker.sent[1].id, ok: true, result: null } satisfies WorkerReply)
+ await q.drainSessionKey('s1')
+ expect(failures).toHaveLength(0)
+ // A later write on the same key is still admitted.
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ expect(worker.sent).toHaveLength(3)
+ })
+
+ it('reports neither onFailure nor onExit for the worker exit that follows a shutdown ACK', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const reportedExits: number[] = []
+ const observedExits: number[] = []
+ worker.on('exit', code => observedExits.push(code))
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ onFailure: err => failures.push(err),
+ onExit: code => reportedExits.push(code),
+ })
+ const closing = q.close()
+ await new Promise(r => setImmediate(r))
+ const shutdown = worker.sent.find(m => m.op.kind === 'shutdown')
+ expect(shutdown).toBeDefined()
+ worker.emit('message', { id: shutdown!.id, ok: true, result: null } satisfies WorkerReply)
+ // FakeWorker.terminate() emits the exit.
+ await closing
+ // Liveness witness: the exit was observed.
+ expect(observedExits).toEqual([0])
+ expect(reportedExits).toHaveLength(0)
+ expect(failures).toHaveLength(0)
+ })
+
+ it('waits for the worker shutdown ACK before terminating it', async () => {
+ const worker = new FakeWorker()
+ let terminateCalls = 0
+ worker.terminate = () => {
+ terminateCalls += 1
+ }
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ const closing = q.close()
+ await new Promise(r => setImmediate(r))
+
+ const shutdown = worker.sent.find(m => m.op.kind === 'shutdown')
+ // Witness: the shutdown op was posted.
+ expect(shutdown).toBeDefined()
+ expect(terminateCalls).toBe(0)
+
+ worker.emit('message', { id: shutdown!.id, ok: true, result: null } satisfies WorkerReply)
+ await closing
+ expect(terminateCalls).toBe(1)
+ })
+
+ it('drains queued async writes before posting shutdown and rejects close on a failed one', async () => {
+ const worker = new FakeWorker()
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ const closing = q.close()
+ await new Promise(r => setImmediate(r))
+ // The queued write is still in flight, so shutdown is not posted yet.
+ expect(worker.sent.map(m => m.op.kind)).toEqual(['ping'])
+
+ worker.emit('message', {
+ id: worker.sent[0].id,
+ ok: false,
+ error: { code: 'SQLITE_IOERR', message: 'disk I/O error' },
+ } satisfies WorkerReply)
+ await new Promise(r => setImmediate(r))
+ const shutdown = worker.sent.find(m => m.op.kind === 'shutdown')
+ expect(shutdown).toBeDefined()
+ worker.emit('message', { id: shutdown!.id, ok: true, result: null } satisfies WorkerReply)
+ await expect(closing).rejects.toThrow(/disk I\/O error/)
+ })
+
+ it('never posts a write chained behind a failed async write on the same key', async () => {
+ const worker = new FakeWorker()
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ q.enqueueAsync('s1', { kind: 'ping' })
+ const chainedSync = q.enqueueSync({ kind: 'ping' }, 's1')
+ await Promise.resolve()
+ // Liveness witness: the first write was posted; the others wait on it.
+ expect(worker.sent.map(m => m.op.kind)).toEqual(['ping'])
+
+ worker.emit('message', {
+ id: worker.sent[0].id,
+ ok: false,
+ error: { code: 'SQLITE_FULL', message: 'database or disk is full' },
+ } satisfies WorkerReply)
+ await expect(chainedSync).rejects.toThrow(
+ /async write failed \(sessionKey=s1\): database or disk is full/
+ )
+ await new Promise(r => setImmediate(r))
+ expect(worker.sent).toHaveLength(1)
+ })
+
+ it('resolves a concurrent second close only after the shutdown ACK', async () => {
+ const worker = new FakeWorker()
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ })
+ let secondSettled = false
+ const first = q.close()
+ const second = q.close().finally(() => {
+ secondSettled = true
+ })
+ await new Promise(r => setImmediate(r))
+ const shutdowns = worker.sent.filter(m => m.op.kind === 'shutdown')
+ // Witness: exactly one shutdown was posted, and it is not ACKed yet.
+ expect(shutdowns).toHaveLength(1)
+ expect(secondSettled).toBe(false)
+
+ worker.emit('message', { id: shutdowns[0].id, ok: true, result: null } satisfies WorkerReply)
+ await Promise.all([first, second])
+ expect(secondSettled).toBe(true)
+ })
+
+ it('rejects close when the worker reports a shutdown failure', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 500,
+ asyncTimeoutMs: 500,
+ stallTimeoutMs: 30_000,
+ onFailure: err => failures.push(err),
+ })
+ const closing = q.close()
+ await new Promise(r => setImmediate(r))
+ const shutdown = worker.sent.find(m => m.op.kind === 'shutdown')
+ expect(shutdown).toBeDefined()
+ worker.emit('message', {
+ id: shutdown!.id,
+ ok: false,
+ error: { code: 'SQLITE_BUSY', message: 'database is locked' },
+ } satisfies WorkerReply)
+ await expect(closing).rejects.toThrow(/database is locked/)
+ // The shutdown failure is the queue's failure; the exit that terminate()
+ // causes afterwards is not reported as a second one.
+ expect(failures.map(e => e.message)).toEqual(['database is locked'])
+ })
+ })
+
+ // A slow worker and a wedged worker differ in progress, not in how long a
+ // write waits: a slow worker keeps completing operations, a wedged one stops.
+ // These cases pin both, in service and at close(), so a change that fixes one
+ // by breaking another fails here.
+ describe('PersistQueue progress bound: slow vs wedged, in service and at close()', () => {
+ const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))
+ const ack = (worker: FakeWorker, msg: WorkerMessage) =>
+ worker.emit('message', { id: msg.id, ok: true, result: null } satisfies WorkerReply)
+
+ /** A queue whose open ping was answered, so the progress bound is armed. */
+ async function openQueue(opts: {
+ stallTimeoutMs: number
+ asyncTimeoutMs?: number
+ syncTimeoutMs?: number
+ }) {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ let terminateCalls = 0
+ worker.terminate = () => {
+ terminateCalls += 1
+ worker.emit('exit', 1)
+ }
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: opts.syncTimeoutMs ?? 5000,
+ asyncTimeoutMs: opts.asyncTimeoutMs ?? 5000,
+ stallTimeoutMs: opts.stallTimeoutMs,
+ onFailure: err => failures.push(err),
+ })
+ const open = q.awaitOpen()
+ ack(worker, worker.sent[0])
+ await open
+ return { worker, q, failures, terminateCalls: () => terminateCalls }
+ }
+
+ /**
+ * Answers every posted operation in order, one at a time, `delayMs` after
+ * the previous answer: a single-writer worker that is slow but alive.
+ */
+ function autoAck(worker: FakeWorker, delayMs: number): WorkerMessage[] {
+ const acked: WorkerMessage[] = []
+ let busy = false
+ const queue: WorkerMessage[] = []
+ const next = () => {
+ const msg = queue.shift()
+ if (!msg) {
+ busy = false
+ return
+ }
+ busy = true
+ setTimeout(() => {
+ acked.push(msg)
+ ack(worker, msg)
+ next()
+ }, delayMs)
+ }
+ const post = worker.postMessage.bind(worker)
+ worker.postMessage = msg => {
+ post(msg)
+ queue.push(msg)
+ if (!busy) next()
+ }
+ return acked
+ }
+
+ it('fails a wedged worker in service within the bound and releases everything queued behind it', async () => {
+ const { worker, q, failures, terminateCalls } = await openQueue({
+ stallTimeoutMs: 100,
+ asyncTimeoutMs: 20,
+ })
+ // Liveness witness: a write on the same key is acknowledged first.
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ ack(worker, worker.sent[1])
+ await q.drainSessionKey('s1')
+ expect(failures).toHaveLength(0)
+
+ // The worker stops answering.
+ q.enqueueAsync('s1', { kind: 'ping' })
+ const keyedSync = q.enqueueSync({ kind: 'ping' }, 's1')
+ await Promise.resolve()
+ expect(worker.sent).toHaveLength(3)
+ const started = Date.now()
+ const prefixDrained = q.drainPrefix('s')
+
+ await vi.waitFor(() => expect(failures).toHaveLength(1), { timeout: 1000, interval: 5 })
+ expect(Date.now() - started).toBeLessThan(400)
+ expect(failures[0].message).toMatch(/db worker made no progress for 100ms/)
+ await expect(keyedSync).rejects.toBe(failures[0])
+ await prefixDrained
+ expect(terminateCalls()).toBe(1)
+ // The write chained behind the stalled one was never posted.
+ expect(worker.sent).toHaveLength(3)
+ expect(() => q.enqueueAsync('s2', { kind: 'ping' })).toThrow(failures[0].message)
+ })
+
+ it('never fails a slow but alive worker with a backlog far longer than the bound', async () => {
+ // A 10x margin between the ACK gap and the bound keeps this stable under load.
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 500, asyncTimeoutMs: 20 })
+ const acked = autoAck(worker, 50)
+ const keys = ['a', 'b', 'c']
+ // The tag only identifies the write in this test; the queue never reads it.
+ const tagged = (tag: string) => ({ kind: 'ping', tag }) as WorkerOp
+ for (let i = 0; i < 10; i++) {
+ for (const key of keys) q.enqueueAsync(key, tagged(`${key}${i}`))
+ }
+ await Promise.all(keys.map(k => q.drainSessionKey(k)))
+ const tags = acked.map(m => (m.op as WorkerOp & { tag: string }).tag)
+ // Liveness witness: all 30 writes were acknowledged, 1.5 s of backlog
+ // against a 500 ms bound, each key in its enqueue order.
+ expect(tags).toHaveLength(30)
+ for (const key of keys) {
+ expect(tags.filter(t => t.startsWith(key))).toEqual(
+ Array.from({ length: 10 }, (_, i) => `${key}${i}`)
+ )
+ }
+ expect(failures).toHaveLength(0)
+ })
+
+ it('drains a slow backlog completely on close() before posting shutdown', async () => {
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 1000, asyncTimeoutMs: 50 })
+ const acked = autoAck(worker, 10)
+ for (let i = 0; i < 10; i++) q.enqueueAsync('s1', { kind: 'ping' })
+ await q.close()
+ const kinds = acked.map(m => m.op.kind)
+ // Liveness witness: the ten writes and then shutdown were acknowledged.
+ expect(kinds).toEqual([...Array(10).fill('ping'), 'shutdown'])
+ expect(failures).toHaveLength(0)
+ })
+
+ it('drains on close() a backlog longer than twice the bound, with no total deadline', async () => {
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 500 })
+ const acked = autoAck(worker, 50)
+ for (let i = 0; i < 30; i++) q.enqueueAsync('s1', { kind: 'ping' })
+ const started = Date.now()
+ await expect(q.close()).resolves.toBeUndefined()
+ // Liveness witness: 30 writes, then shutdown, all acknowledged; the
+ // backlog (30 x 50 ms) is longer than 2x the 500 ms bound.
+ expect(acked.map(m => m.op.kind)).toEqual([...Array(30).fill('ping'), 'shutdown'])
+ expect(Date.now() - started).toBeGreaterThan(1000)
+ expect(failures).toHaveLength(0)
+ })
+
+ it('does not count idle time against the bound on the next write', async () => {
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 200 })
+ // Idle for twice the bound with nothing in flight.
+ await sleep(400)
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ expect(worker.sent).toHaveLength(2)
+ await sleep(20)
+ ack(worker, worker.sent[1])
+ // Liveness witness: the write was posted and its ACK drained the key.
+ await q.drainSessionKey('s1')
+ expect(worker.sent[1].op.kind).toBe('ping')
+ await sleep(50)
+ expect(failures).toHaveLength(0)
+ })
+
+ it('fails close() within the bound when the worker is wedged', async () => {
+ const { worker, q, failures, terminateCalls } = await openQueue({ stallTimeoutMs: 100 })
+ // Liveness witness: a write is acknowledged before the worker stops.
+ const first = q.enqueueSync({ kind: 'ping' })
+ ack(worker, worker.sent[1])
+ await first
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ const started = Date.now()
+ await expect(q.close()).rejects.toThrow(/db worker made no progress for 100ms/)
+ expect(Date.now() - started).toBeLessThan(400)
+ expect(terminateCalls()).toBe(1)
+ expect(failures).toHaveLength(1)
+ expect(worker.sent.map(m => m.op.kind)).not.toContain('shutdown')
+ })
+
+ it('waits on close() for a sync write without a sessionKey before posting shutdown', async () => {
+ const { worker, q } = await openQueue({ stallTimeoutMs: 1000 })
+ const unkeyed = q.enqueueSync<string>({ kind: 'ping' })
+ const closing = q.close()
+ await sleep(20)
+ expect(worker.sent.map(m => m.op.kind)).toEqual(['ping', 'ping'])
+
+ worker.emit('message', {
+ id: worker.sent[1].id,
+ ok: true,
+ result: 'pong',
+ } satisfies WorkerReply)
+ // Liveness witness: the sync write resolves with the worker's result.
+ await expect(unkeyed).resolves.toBe('pong')
+ await vi.waitFor(() => expect(worker.sent.map(m => m.op.kind)).toContain('shutdown'))
+ ack(worker, worker.sent[2])
+ await closing
+ })
+
+ it('does not fail a healthy worker whose answer waited behind a main-thread stall', async () => {
+ const realWorker = new Worker(
+ `const { parentPort } = require('node:worker_threads')
+ parentPort.on('message', msg => setTimeout(() => parentPort.postMessage({ id: msg.id, ok: true, result: null }), 10))`,
+ { eval: true }
+ )
+ const failures: Error[] = []
+ const q = new PersistQueue(realWorker as unknown as WorkerLike, {
+ syncTimeoutMs: 5000,
+ asyncTimeoutMs: 5000,
+ stallTimeoutMs: 100,
+ onFailure: err => failures.push(err),
+ })
+ try {
+ await q.awaitOpen()
+ const write = q.enqueueSync({ kind: 'ping' }, 's1')
+ await sleep(1)
+ // The main thread is blocked well past the bound while the answer
+ // waits in the port. Blocking in the check phase makes the next loop
+ // iteration run the overdue timer before the poll phase reads the
+ // answer (blocking in the timers phase would not: libuv compares
+ // timers against the loop time cached when that phase started).
+ await new Promise<void>(resolve =>
+ setImmediate(() => {
+ const until = Date.now() + 300
+ while (Date.now() < until) {
+ /* block the event loop */
+ }
+ resolve()
+ })
+ )
+ // Liveness witness: the write resolves.
+ await expect(write).resolves.toBeNull()
+ await sleep(150)
+ expect(failures).toHaveLength(0)
+ } finally {
+ await realWorker.terminate()
+ }
+ })
+
+ it('does not start the bound before the database is open', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 5000,
+ asyncTimeoutMs: 5000,
+ stallTimeoutMs: 100,
+ onFailure: err => failures.push(err),
+ })
+ const open = q.awaitOpen()
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ expect(worker.sent).toHaveLength(2)
+ await sleep(300)
+ expect(failures).toHaveLength(0)
+
+ ack(worker, worker.sent[0])
+ await open
+ ack(worker, worker.sent[1])
+ await q.drainSessionKey('s1')
+ expect(failures).toHaveLength(0)
+
+ // Liveness witness: once open, a wedged write does fail the queue.
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await vi.waitFor(() => expect(failures).toHaveLength(1), { timeout: 1000, interval: 5 })
+ expect(failures[0].message).toMatch(/no progress for 100ms/)
+ })
+
+ it('fails close() within the bound when the worker never answers the open ping', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 5000,
+ asyncTimeoutMs: 5000,
+ stallTimeoutMs: 100,
+ onFailure: err => failures.push(err),
+ })
+ const open = q.awaitOpen().catch((err: unknown) => err)
+ q.enqueueAsync('s1', { kind: 'ping' })
+ await Promise.resolve()
+ // Both are posted before close(), so nothing sent after it can arm the bound.
+ expect(worker.sent).toHaveLength(2)
+ const closing = q.close()
+ let settled = false
+ const outcome = closing.then(
+ () => ({ ok: true as const }),
+ (err: Error) => ({ ok: false as const, err })
+ )
+ void outcome.then(() => {
+ settled = true
+ })
+ const started = Date.now()
+ // Bounded wait, so a hang fails the assertion instead of the test timeout.
+ await Promise.race([outcome, sleep(500)])
+ // Liveness witnesses: the open ping was posted, and close() started.
+ expect(worker.sent[0].op.kind).toBe('ping')
+ expect(() => q.enqueueAsync('s2', { kind: 'ping' })).toThrow()
+ expect(settled).toBe(true)
+ const result = await outcome
+ expect(result.ok).toBe(false)
+ expect(result.ok ? null : result.err.message).toMatch(/db worker made no progress for 100ms/)
+ expect(Date.now() - started).toBeLessThan(500)
+ expect(failures).toHaveLength(1)
+ expect(await open).toBe(failures[0])
+ })
+
+ it('lets a slow but healthy open finish during close()', async () => {
+ const worker = new FakeWorker()
+ const failures: Error[] = []
+ let terminateCalls = 0
+ worker.terminate = () => {
+ terminateCalls += 1
+ worker.emit('exit', 0)
+ }
+ const q = new PersistQueue(worker, {
+ syncTimeoutMs: 5000,
+ asyncTimeoutMs: 5000,
+ stallTimeoutMs: 300,
+ onFailure: err => failures.push(err),
+ })
+ const open = q.awaitOpen()
+ q.enqueueAsync('s1', { kind: 'ping' })
+ // The open takes longer than the bound before close() starts; the bound
+ // counts from close(), not from the ping.
+ await sleep(400)
+ expect(worker.sent).toHaveLength(2)
+ const closing = q.close()
+ await sleep(30)
+ ack(worker, worker.sent[0])
+ await open
+ ack(worker, worker.sent[1])
+ await vi.waitFor(() => expect(worker.sent.map(m => m.op.kind)).toContain('shutdown'))
+ // Liveness witness: the async write was acknowledged and shutdown posted.
+ expect(worker.sent.map(m => m.op.kind)).toEqual(['ping', 'ping', 'shutdown'])
+ ack(worker, worker.sent[2])
+ await expect(closing).resolves.toBeUndefined()
+ expect(failures).toHaveLength(0)
+ expect(terminateCalls).toBe(1)
+ })
+
+ it('stays failed when the stalled operation is acknowledged late', async () => {
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 100 })
+ const stalled = q.enqueueSync({ kind: 'ping' }).catch((err: unknown) => err)
+ await vi.waitFor(() => expect(failures).toHaveLength(1), { timeout: 1000, interval: 5 })
+ expect(await stalled).toBe(failures[0])
+
+ worker.emit('message', {
+ id: worker.sent[1].id,
+ ok: true,
+ result: 'late',
+ } satisfies WorkerReply)
+ await sleep(1)
+ expect(() => q.enqueueAsync('s1', { kind: 'ping' })).toThrow(failures[0].message)
+ await expect(q.enqueueSync({ kind: 'ping' })).rejects.toBe(failures[0])
+ expect(failures).toHaveLength(1)
+ })
+
+ it('waits for a shutdown that takes longer than syncTimeoutMs while within the bound', async () => {
+ const { worker, q, failures } = await openQueue({ stallTimeoutMs: 1000, syncTimeoutMs: 30 })
+ const closing = q.close()
+ await vi.waitFor(() => expect(worker.sent.map(m => m.op.kind)).toContain('shutdown'))
+ await sleep(90)
- ack(
- worker,
- worker.sent.find(m => m.op.kind === 'shutdown')!
- )
++ ack(worker, worker.sent.find(m => m.op.kind === 'shutdown')!)
+ // Liveness witness: close() resolves after the late shutdown ACK.
+ await expect(closing).resolves.toBeUndefined()
+ expect(failures).toHaveLength(0)
+ })
+
+ it('keeps the bound after an earlier failure, so close() does not wait forever', async () => {
+ const { worker, q, failures, terminateCalls } = await openQueue({ stallTimeoutMs: 100 })
+ q.enqueueAsync('a', { kind: 'ping' })
+ await vi.waitFor(() => expect(worker.sent).toHaveLength(2))
+ const hung = q.enqueueSync({ kind: 'ping' }).catch((err: unknown) => err)
+ expect(worker.sent).toHaveLength(3)
+ worker.emit('message', {
+ id: worker.sent[1].id,
+ ok: false,
+ error: { code: 'SQLITE_FULL', message: 'database or disk is full' },
+ } satisfies WorkerReply)
+ // Liveness witness: the async failure is latched first.
+ await vi.waitFor(() => expect(failures).toHaveLength(1))
+ const started = Date.now()
+ await expect(q.close()).rejects.toThrow(/database or disk is full/)
+ expect(Date.now() - started).toBeLessThan(400)
+ expect(terminateCalls()).toBe(1)
+ expect(await hung).toBeInstanceOf(Error)
+ expect(failures).toHaveLength(1)
+ })
})