Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-ui): protect the chat catalog during host authority loss
Alfredo Lopez54c4919dd650
diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.tsindex bd21597ad..85bd52f64 100644--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts@@ -1,6 +1,14 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { classifyTier } from '@hooks/useTaskTier'+import {+ ipcGenericForbidden,+ ipcHostAccessDenied,+ ipcHostAccessRevoked,+ ipcHostWaking,+ ipcHttpError,+ ipcServerErrorMentioning403,+} from '../../../hooks/domain/__tests__/__fixtures__/ipcErrors'import { TaskTracker } from '../taskTracker'import { type TaskKey, type TaskState, makeTaskKey } from '../types'@@ -177,6 +185,57 @@ describe('TaskTracker', () => {expect(state.terminalResult).toMatchObject({ kind: 'error', source: 'result_fetch' })})+ // R2-B1 / NEW-dui-3: the result fetch fails with the real RpcProxyClient+ // rejection wrapped the way Electron IPC wraps it.+ it.each([+ [+ 'confirmed revocation',+ () => ipcHostAccessRevoked('rpc:getTaskResult'),+ 'authority',+ 'revoked',+ ],+ [+ 'host_access_denied',+ () => ipcHostAccessDenied('rpc:getTaskResult'),+ 'authority',+ 'uncertain',+ ],+ ['generic 403', () => ipcGenericForbidden('rpc:getTaskResult'), 'authority', 'uncertain'],+ [+ '401',+ () => ipcHttpError('rpc:getTaskResult', 401, 'Unauthorized', { error: 'expired' }),+ 'authority',+ 'uncertain',+ ],+ [+ '503 whose body mentions 403',+ () => ipcServerErrorMentioning403('rpc:getTaskResult'),+ 'result_fetch',+ undefined,+ ],+ [+ 'waking Host named support-401',+ async () => ipcHostWaking('rpc:getTaskResult', 'support-401'),+ 'result_fetch',+ undefined,+ ],+ ])(+ 'IPC-wrapped %s result-fetch failure classifies authority',+ async (_label, build, source, authority) => {+ rpc.getTaskResult.mockRejectedValueOnce(await build())+ const onTerminal = vi.fn()+ tracker.setCallbacks({ onTerminal })+ tracker.start(KEY, 'task-1', 'um-1')+ await rpc.emit({ type: 'terminal', data: { taskId: 'task-1', status: 'completed' } })++ expect(rpc.getTaskResult).toHaveBeenCalledWith('agent-x', 'task-1', ['agent-x'])+ const [, state] = onTerminal.mock.calls[0]!+ expect(state.status).toBe('failed')+ expect(state.terminalResult).toMatchObject({ kind: 'error', source })+ expect(state.terminalResult.authority).toBe(authority)+ }+ )+it('terminal completed does NOT corrupt a task that replaced it during the result fetch (H2)', async () => {const onTerminal = vi.fn(async () => undefined)tracker.setCallbacks({ onTerminal })diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.teamContext.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.teamContext.test.tsxindex d0c26fc19..de996a46e 100644--- a/desktop-app/ui/src/hooks/__tests__/useAppController.teamContext.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.teamContext.test.tsx@@ -58,4 +58,71 @@ describe('useAppController team context', () => {expect(switchedBack).toBe(true)expect(handle.switchTeam).toHaveBeenCalledWith(HARNESS_ME.teamId)})++ // R1-L10: the delete fence binds to the authenticated principal's team only.+ // The team directory is display data; a directory team must never stand in+ // for an absent `me.teamId`, or a deletion would be fenced to a team the+ // session never proved membership of.+ it.each([+ ['an absent me.teamId stays null despite a directory team', '', null],+ ['a padded me.teamId is trimmed', ' team-1 ', 'team-1'],+ ])('fences chat deletion to %s', async (_label, meTeamId, expectedTeamId) => {+ const { clerum } = installAppControllerClerum({+ me: { teamId: meTeamId },+ teamDirectory: { items: [], currentTeamId: 'team-dir' },+ })+ const app = renderAppController()+ unmount = app.unmount++ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))+ // Witness: the directory team is visible to the rest of the app, so a+ // fallback to it would have a value to use.+ expect(app.result.current.currentTeamId).toBe(meTeamId || 'team-dir')++ await act(async () => {+ await app.result.current.captureChatDeleteFence('agent-x')+ })++ expect(clerum.chat.captureDeleteFence).toHaveBeenCalledTimes(1)+ expect(clerum.chat.captureDeleteFence).toHaveBeenCalledWith({+ environmentKey: expect.any(String),+ userId: HARNESS_ME.id,+ teamId: expectedTeamId,+ })+ })++ // The cache scope (`currentTeamId`) and the delete fence read `me.teamId`+ // from one point: while it is present both carry it, and both follow it when+ // the session switches team, whatever the (unchanged) directory reports.+ it('derives the chat cache scope and the delete fence from the same me.teamId', async () => {+ const { clerum, handle } = installAppControllerClerum({+ teamDirectory: { items: [], currentTeamId: 'team-dir' },+ })+ const app = renderAppController()+ unmount = app.unmount++ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))++ const fencedTeamId = async () => {+ clerum.chat.captureDeleteFence.mockClear()+ await act(async () => {+ await app.result.current.captureChatDeleteFence('agent-x')+ })+ expect(clerum.chat.captureDeleteFence).toHaveBeenCalledTimes(1)+ return clerum.chat.captureDeleteFence.mock.calls[0]?.[0]?.teamId+ }++ expect(app.result.current.currentTeamId).toBe(HARNESS_ME.teamId)+ expect(await fencedTeamId()).toBe(HARNESS_ME.teamId)++ await act(async () => {+ await app.result.current.handleEnsureTeamContext({ teamId: 'team-2' })+ })+ // Witness: the switch really went through and moved me.teamId.+ expect(handle.switchTeam).toHaveBeenCalledWith('team-2')+ await waitFor(() => expect(app.result.current.currentTeamId).toBe('team-2'))+ expect(await fencedTeamId()).toBe('team-2')+ })})diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsxindex 7f8b47c0d..74e712324 100644--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx@@ -2,24 +2,11 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import {- getHostAuthorityEpochForAgent,loadWorkflowRunsWithArtifactsForApprovalRefresh,loadWorkflowRunsWithArtifactsForWorkflowTarget,scheduleAfterFirstPaintForSession,} from '../useAppController'-describe('getHostAuthorityEpochForAgent', () => {- it('keeps Host X chat-list authority unchanged when Host Y is revoked', () => {- const epochs = new Map<string, number>()- const hostXChatListEpoch = getHostAuthorityEpochForAgent(epochs, 'host-x')-- epochs.set('host-y', 1)-- expect(getHostAuthorityEpochForAgent(epochs, 'host-x')).toBe(hostXChatListEpoch)- expect(getHostAuthorityEpochForAgent(epochs, 'host-y')).toBe(1)- })-})-function installWorkflowHarness(runsResult: unknown) {const runs = vi.fn(async () => runsResult)const listRunArtifacts = vi.fn(async () => ({diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsxindex 2c9d24a96..2e3fa8863 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx@@ -108,6 +108,8 @@ export interface AppControllerClerumOptions {desktopReleaseStatus?: typeof DEFAULT_DESKTOP_RELEASE_STATUS/** Payload for `team.directory` / `team.initialDirectory` / `team.list`. */teamDirectory?: { items: unknown[]; currentTeamId: string }+ /** Overrides on the authenticated `me` the session state reports. */+ me?: Partial<typeof HARNESS_ME>}export interface AppControllerClerumHandle {@@ -146,7 +148,7 @@ export function extendMockClerumForAppController(const bridge = clerum as unknown as Record<string, unknown>let authenticated = options.startAuthenticated ?? true- let sessionMe = { ...HARNESS_ME }+ let sessionMe = { ...HARNESS_ME, ...options.me }const teamDirectoryPayload = options.teamDirectory ?? {items: [],currentTeamId: HARNESS_ME.teamId,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/catalogFixtures.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/catalogFixtures.tsnew file mode 100644index 000000000..8d0a9d6c4--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/catalogFixtures.ts@@ -0,0 +1,55 @@+import { parseSessionsListResult } from '../../../../../../src/rpcProxyClient'+import type { ChatIndex, SessionsListResult } from '../../../../../../src/types'++export const CATALOG_NOW = '2026-09-12T00:00:00.000Z'++/**+ * A server catalog page built by the REAL wire parser, so fixtures are derived+ * from the producer instead of hand-built parsed shapes.+ */+export function serverSessions(+ items: Array<{ agent: string; chatId: string; title?: string }>,+ nextCursor?: string+): SessionsListResult {+ return parseSessionsListResult({+ items: items.map(i => ({+ agent: i.agent,+ chatId: i.chatId,+ turnCount: 1,+ lastActivityAt: CATALOG_NOW,+ ...(i.title !== undefined ? { title: i.title } : {}),+ })),+ ...(nextCursor !== undefined ? { nextCursor } : {}),+ })+}++/** A local chat index whose tombstones carry the harness's authority scope. */+export function localIndex(+ chats: Array<{ id: string; title: string }>,+ deletedChatIds: string[] = []+): ChatIndex {+ const authorityScope = { environmentKey: 'env-test', userId: 'unknown-user', teamId: 'team-1' }+ return {+ version: 1,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: chats.map(c => ({+ id: c.id,+ title: c.title,+ createdAt: CATALOG_NOW,+ updatedAt: CATALOG_NOW,+ messageCount: 0,+ })),+ deletedChatTombstones: deletedChatIds.map(chatId => ({ chatId, authorityScope })),+ }+}++export function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason: unknown) => void+ const promise = new Promise<T>((finish, fail) => {+ resolve = finish+ reject = fail+ })+ return { promise, resolve, reject }+}diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex ca91cb722..830d83e39 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -1,23 +1,30 @@import type { ReactNode } from 'react'import { vi } from 'vitest'import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'-import { renderHook } from '@testing-library/react'+import { act, renderHook } from '@testing-library/react'+import type { HostAuthorityHoldKind } from '../../../../lib/hostAuthorityStore'import { useAgentChatController } from '../../useAgentChatController'--const onHostAccessRevoked = () => {}-const onHostAuthorityUncertain = () => {}-const isHostAccessBlocked = () => false-const getHostAuthorityEpoch = () => 0+import { type HarnessHostAuthority, useHarnessHostAuthority } from './hostAuthorityHarness'type ControllerParams = Parameters<typeof useAgentChatController>[0]export interface RenderControllerResult {result: ReturnType<- typeof renderHook<ReturnType<typeof useAgentChatController>, ControllerParams>+ typeof renderHook<ReturnType<typeof useAgentChatController>, Partial<ControllerParams>>>['result']rerender: (props?: Partial<ControllerParams>) => voidunmount: () => void- params: ControllerParams+ params: Partial<ControllerParams>+ /**+ * The mount's Host authority, from the production store factory. Only+ * meaningful when the test did not override the authority params.+ */+ hostAuthority: {+ hold: (agentRef: string, kind: HostAuthorityHoldKind) => void+ release: (agentRef: string) => void+ getEpoch: (agentRef: string) => number+ isBlocked: (agentRef: string) => boolean+ }spies: {pushToast: ReturnType<typeof vi.fn>pushNotification: ReturnType<typeof vi.fn>@@ -35,6 +42,9 @@ export interface RenderControllerResult {* (`useAgentChatController.ts:492`) does NOT auto-switchToChat on mount —* tests that exercise `switchToChat` / `sendAgentMessage` control the chat* explicitly. Pass `navItem: 'chat'` to exercise the auto-select path.+ *+ * Host authority defaults to `useHarnessHostAuthority`, the production store+ * factory, so epoch comparisons in the controller are exercised for real.*/export function renderController(overrides: Partial<ControllerParams> = {}@@ -48,19 +58,16 @@ export function renderController(canDeliverChatResponseNotification: vi.fn(() => true),}- const params = {+ const params: Partial<ControllerParams> = {selectedAgent: 'agent-x',agentNames: ['agent-x'],currentTeamId: 'team-1',+ chatAuthorityTeamId: 'team-1',currentEnvironmentKey: 'env-test',currentTeamName: 'Team 1',isAuthenticated: true,loadMenuData: true,navItem: 'agents',- onHostAccessRevoked,- onHostAuthorityUncertain,- isHostAccessBlocked,- getHostAuthorityEpoch,pushToast: spies.pushToast,pushNotification: spies.pushNotification,// Identity resolver by default (no catalog display layer in the harness).@@ -70,18 +77,38 @@ export function renderController(openAgentConversationFromNotification: spies.openAgentConversationFromNotification,decideApprovalFromNotification: spies.decideApprovalFromNotification,...overrides,- } as ControllerParams+ }++ let authority: HarnessHostAuthority | null = null+ const currentAuthority = (): HarnessHostAuthority => {+ if (!authority) throw new Error('controller is not mounted')+ return authority+ }// Post-D.3 the controller reads the task tracker from context and registers// its own onTerminal/onSuspended callbacks, so the provider must wrap it. No// callbacks are injected here — the controller owns them (it has pushToast,// pushNotification, chatStore and the visibility refs).- const utils = renderHook((p: ControllerParams) => useAgentChatController(p), {- initialProps: params,- wrapper: ({ children }: { children: ReactNode }) => (- <AgentTaskTrackerProvider>{children}</AgentTaskTrackerProvider>- ),- })+ const utils = renderHook(+ (p: Partial<ControllerParams>) => {+ const hostAuthority = useHarnessHostAuthority()+ authority = hostAuthority+ return useAgentChatController({+ onHostAccessRevoked: hostAuthority.onHostAccessRevoked,+ onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,+ isHostAccessBlocked: hostAuthority.isHostAccessBlocked,+ getHostAuthorityEpoch: hostAuthority.getHostAuthorityEpoch,+ hostAuthorityRevision: hostAuthority.revision,+ ...p,+ } as ControllerParams)+ },+ {+ initialProps: params,+ wrapper: ({ children }: { children: ReactNode }) => (+ <AgentTaskTrackerProvider>{children}</AgentTaskTrackerProvider>+ ),+ }+ )return {result: utils.result,@@ -89,6 +116,20 @@ export function renderController(utils.rerender({ ...params, ...(props ?? {}) }),unmount: utils.unmount,params,+ hostAuthority: {+ hold: (agentRef, kind) =>+ act(() => {+ const hostAuthority = currentAuthority()+ if (kind === 'revoked') hostAuthority.onHostAccessRevoked(agentRef)+ else hostAuthority.onHostAuthorityUncertain(agentRef)+ }),+ release: agentRef =>+ act(() => {+ currentAuthority().release(agentRef)+ }),+ getEpoch: agentRef => currentAuthority().store.getEpoch(agentRef),+ isBlocked: agentRef => currentAuthority().store.isBlocked(agentRef),+ },spies,}}diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/hostAuthorityHarness.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/hostAuthorityHarness.tsnew file mode 100644index 000000000..313ce6c9a--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/hostAuthorityHarness.ts@@ -0,0 +1,56 @@+import { useRef, useState } from 'react'+import {+ type HostAuthorityHoldKind,+ type HostAuthorityStore,+ createHostAuthorityStore,+} from '../../../../lib/hostAuthorityStore'++/**+ * Host authority for controller tests, built on the SAME store factory+ * `useAppController` uses (R2-M5). A stub such as `getHostAuthorityEpoch = () =>+ * 0` makes every epoch comparison vacuous, so a regression in the production+ * epoch path could never turn a controller test red.+ *+ * The callbacks are stable for the mount, like the production `useCallback`s,+ * and a hold or release bumps `revision` exactly as `useAppController` does.+ */+export interface HarnessHostAuthority {+ store: HostAuthorityStore+ revision: number+ onHostAccessRevoked: (agentRef: string) => void+ onHostAuthorityUncertain: (agentRef: string) => void+ isHostAccessBlocked: (agentRef: string) => boolean+ getHostAuthorityEpoch: (agentRef: string) => number+ /** Release a hold the way a successful `verifyHostAccess` does. */+ release: (agentRef: string) => void+}++export type HostAuthorityListener = (agentRef: string, kind: HostAuthorityHoldKind) => void++export function useHarnessHostAuthority(listener?: HostAuthorityListener): HarnessHostAuthority {+ const [revision, setRevision] = useState(0)+ const listenerRef = useRef(listener)+ listenerRef.current = listener+ const [stable] = useState(() => {+ const store = createHostAuthorityStore()+ const bump = () => setRevision(value => value + 1)+ const hold = (agentRef: string, kind: HostAuthorityHoldKind) => {+ listenerRef.current?.(agentRef, kind)+ if (store.hold(agentRef, kind)) bump()+ }+ return {+ store,+ onHostAccessRevoked: (agentRef: string) => hold(agentRef, 'revoked'),+ onHostAuthorityUncertain: (agentRef: string) => hold(agentRef, 'uncertain'),+ isHostAccessBlocked: (agentRef: string) => store.isBlocked(agentRef),+ getHostAuthorityEpoch: (agentRef: string) => store.getEpoch(agentRef),+ release: (agentRef: string) => {+ const heldAtEpoch = store.heldAtEpoch(agentRef)+ if (heldAtEpoch === undefined) throw new Error(`${agentRef} is not held`)+ if (!store.release(agentRef, heldAtEpoch)) throw new Error(`${agentRef} hold moved`)+ bump()+ },+ }+ })+ return { ...stable, revision }+}diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/ipcErrors.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/ipcErrors.tsnew file mode 100644index 000000000..e36d59d36--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/ipcErrors.ts@@ -0,0 +1,170 @@+import { ApiError } from '../../../../../../src/httpClient'+import { RpcProxyClient } from '../../../../../../src/rpcProxyClient'++/**+ * Renderer-side error fixtures built from the REAL main-process producers.+ *+ * A main-process rejection never reaches the renderer as the producer's own+ * Error: `ipcRenderer.invoke` rejects with a new Error whose message is+ * `Error invoking remote method '<channel>': <String(error)>`. Every+ * classifier in `lib/format.ts` therefore parses that wrapped string, and a+ * fixture written by hand without the prefix (or with a message no producer+ * emits) certifies a parser that production never exercises (R2-B1).+ *+ * Each builder below drives the real producer (`RpcProxyClient` over a stubbed+ * `fetch`, `ApiError`, the `AppService` availability mapping) and wraps the+ * result exactly the way Electron does.+ */++const RPC_TOKEN = 'rpc-token'++/** rpc-proxy's own Host-access denial body (cross-layer contract, R1-M6). */+const HOST_ACCESS_DENIAL_ERROR = 'Forbidden: user cannot access this host'++export type RpcChannel =+ | 'rpc:listSessions'+ | 'rpc:loadSessionMessages'+ | 'rpc:renameSession'+ | 'rpc:invokeHostMessage'+ | 'rpc:getTaskResult'++/** The rejection `ipcRenderer.invoke` produces for a main-process throw. */+export function wrapLikeElectronIpc(channel: string, error: Error): Error {+ return new Error(`Error invoking remote method '${channel}': ${String(error)}`)+}++function jsonResponse(status: number, statusText: string, body: unknown): Response {+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), {+ status,+ statusText,+ headers: { 'content-type': 'application/json' },+ })+}++/**+ * Run one RpcProxyClient call against a single canned response and return the+ * Error it throws. Fails loudly when the producer resolves instead: a fixture+ * builder that silently returned nothing would hand the test an `undefined`.+ */+async function rejectionOf(+ response: Response,+ call: (client: RpcProxyClient) => Promise<unknown>+): Promise<Error> {+ const originalFetch = globalThis.fetch+ let fetchCalls = 0+ globalThis.fetch = (async () => {+ fetchCalls += 1+ return response.clone()+ }) as typeof fetch+ try {+ await call(new RpcProxyClient())+ } catch (error) {+ if (fetchCalls === 0) {+ throw new Error(`producer rejected before calling fetch: ${String(error)}`)+ }+ if (!(error instanceof Error)) throw new Error(`producer threw a non-Error: ${String(error)}`)+ return error+ } finally {+ globalThis.fetch = originalFetch+ }+ throw new Error(`producer resolved for HTTP ${response.status}; expected a rejection`)+}++function callFor(channel: RpcChannel): (client: RpcProxyClient) => Promise<unknown> {+ switch (channel) {+ case 'rpc:listSessions':+ return client => client.listSessions(RPC_TOKEN, 'agent-x', { agent: 'agent-x', limit: 1 })+ case 'rpc:loadSessionMessages':+ return client => client.loadSessionMessages(RPC_TOKEN, 'agent-x', 'agent-x', 'chat-1')+ case 'rpc:renameSession':+ return client => client.renameSession(RPC_TOKEN, 'agent-x', 'agent-x', 'chat-1', 'Title')+ case 'rpc:invokeHostMessage':+ return client =>+ client.invokeHostMessage(RPC_TOKEN, 'agent-x', { content: 'hello' }, { async: true })+ case 'rpc:getTaskResult':+ return client => client.getTaskResult(RPC_TOKEN, 'agent-x', 'task-1')+ }+}++/**+ * rpc-proxy's own authorization denial for a user whose access was removed+ * (`code: 'host_access_revoked'`), as the real RpcProxyClient projects it for+ * `channel`, wrapped by IPC.+ */+export async function ipcHostAccessRevoked(channel: RpcChannel): Promise<Error> {+ const error = await rejectionOf(+ jsonResponse(403, 'Forbidden', {+ error: HOST_ACCESS_DENIAL_ERROR,+ code: 'host_access_revoked',+ }),+ callFor(channel)+ )+ return wrapLikeElectronIpc(channel, error)+}++/**+ * rpc-proxy's own denial that is NOT a removal (`code: 'host_access_denied'`,+ * e.g. a disabled Host). The renderer must treat it as an uncertain 403.+ */+export async function ipcHostAccessDenied(channel: RpcChannel): Promise<Error> {+ const error = await rejectionOf(+ jsonResponse(403, 'Forbidden', {+ error: HOST_ACCESS_DENIAL_ERROR,+ code: 'host_access_denied',+ }),+ callFor(channel)+ )+ return wrapLikeElectronIpc(channel, error)+}++/**+ * A 403 that does not confirm revocation: an arbitrary upstream 403 body+ * (for example a scope denial passed through from mcp-host).+ */+export async function ipcGenericForbidden(channel: RpcChannel): Promise<Error> {+ const error = await rejectionOf(+ jsonResponse(403, 'Forbidden', { error: 'missing send scope' }),+ callFor(channel)+ )+ return wrapLikeElectronIpc(channel, error)+}++/** A plain HTTP failure through the real producer for `channel`. */+export async function ipcHttpError(+ channel: RpcChannel,+ status: number,+ statusText: string,+ body: unknown+): Promise<Error> {+ const error = await rejectionOf(jsonResponse(status, statusText, body), callFor(channel))+ return wrapLikeElectronIpc(channel, error)+}++/**+ * The "503 body mentions 403" case: a server error whose body text carries an+ * authorization status. Only the response status may classify it.+ */+export function ipcServerErrorMentioning403(channel: RpcChannel): Promise<Error> {+ return ipcHttpError(channel, 503, 'Service Unavailable', {+ error: 'upstream returned 403 Forbidden',+ })+}++/**+ * The exact `AppService.toHostAvailabilityError` text for a waking Host whose+ * name contains a status-looking number (R1-M16: `support-401 is waking`).+ * `AppService` pulls in Electron main-process modules, so the mapping's text+ * is reproduced here; `appService.hostWaking.test.ts` pins the producer side.+ */+export function ipcHostWaking(channel: RpcChannel, hostRef: string): Error {+ const cause = new ApiError(+ '503 Service Unavailable: Host is waking up',+ 503,+ JSON.stringify({ code: 'host_waking', hostRef, retryAfterMs: 2000 })+ )+ if (!cause.bodyText.includes('"host_waking"')) throw new Error('fixture lost its code')+ return wrapLikeElectronIpc(+ channel,+ new Error(`host_waking: agent host "${hostRef}" is waking up — retry shortly`)+ )+}diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.tsindex 7c349070f..8afe08c48 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts@@ -61,12 +61,19 @@ export interface MockClerum {hasProgressHandler: (taskId: string) => boolean/** True once an activity handler exists for `hostRef`. */hasActivityHandler: (hostRef: string) => boolean+ /** What the fake store holds for one chat after append/upsert writes. */+ persistedMessages: (agentRef: string, chatId: string) => Array<Record<string, unknown>>}export function installMockClerum(): MockClerum {const progressHandlers = new Map<string, Handler>()const activityHandlers = new Map<string, Handler>()- const upsertedMessageIds = new Set<string>()+ // What the fake store holds per chat, so `upsertMessages` can merge like the+ // real `ChatStore.upsertMessages` instead of dropping a second write of an id.+ const persistedByChat = new Map<string, Array<Record<string, unknown>>>()+ const persistedKey = (agentRef: string, chatId: string) => `${agentRef}\u0000${chatId}`+ const persistedIndexOf = (persisted: Array<Record<string, unknown>>, id: string) =>+ persisted.findIndex(message => message.id === id)const isoNow = () => new Date().toISOString()@@ -89,16 +96,40 @@ export function installMockClerum(): MockClerum {})),delete: vi.fn(async () => ({ cleanupPending: false })),loadMessages: vi.fn(async () => []),- appendMessages: vi.fn(- async (_agentRef: string, _chatId: string, _messages: unknown[]) => undefined- ),+ appendMessages: vi.fn(async (agentRef: string, chatId: string, messages: unknown[]) => {+ const key = persistedKey(agentRef, chatId)+ persistedByChat.set(key, [+ ...(persistedByChat.get(key) ?? []),+ ...(messages as Array<Record<string, unknown>>),+ ])+ }),+ /**+ * Mirrors `ChatStore.upsertMessages` (src/chatStore.ts, the id branch of+ * `mergeReconciledMessages`): per chat, an id already persisted is replaced+ * in place and keeps its existing `task_id`; a new id is appended. New ids+ * still go through `appendMessages` so suites that count persisted turns+ * keep observing them there.+ */upsertMessages: vi.fn(async (agentRef: string, chatId: string, messages: unknown[]) => {- const unseen = messages.filter(message => {- const id = (message as { id?: unknown }).id- if (typeof id !== 'string' || upsertedMessageIds.has(id)) return false- upsertedMessageIds.add(id)- return true- })+ const key = persistedKey(agentRef, chatId)+ const persisted = persistedByChat.get(key) ?? []+ const unseen: Array<Record<string, unknown>> = []+ for (const message of messages as Array<Record<string, unknown>>) {+ const id = message.id+ if (typeof id !== 'string') {+ throw new Error(`mockClerum.upsertMessages: message without a string id in ${chatId}`)+ }+ const index = persistedIndexOf(persisted, id)+ if (index < 0) {+ const pending = persistedIndexOf(unseen, id)+ if (pending < 0) unseen.push(message)+ else unseen[pending] = message+ continue+ }+ const taskId = persisted[index]?.task_id ?? message.task_id+ persisted[index] = { ...message, ...(taskId !== undefined ? { task_id: taskId } : {}) }+ }+ persistedByChat.set(key, persisted)if (unseen.length) await chat.appendMessages(agentRef, chatId, unseen)}),replaceMessages: vi.fn(async () => undefined),@@ -160,6 +191,9 @@ export function installMockClerum(): MockClerum {},hasProgressHandler: (taskId: string) => progressHandlers.has(taskId),hasActivityHandler: (hostRef: string) => activityHandlers.has(hostRef),+ persistedMessages: (agentRef: string, chatId: string) => [+ ...(persistedByChat.get(persistedKey(agentRef, chatId)) ?? []),+ ],}Object.defineProperty(window, 'clerum', {diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListCatalogAuthority.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListCatalogAuthority.test.tsxnew file mode 100644index 000000000..2cb238291--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListCatalogAuthority.test.tsx@@ -0,0 +1,406 @@+// @vitest-environment jsdom+/**+ * Catalog failure handling and per-Host authority in `useChatListController`,+ * driven through the real controller with IPC rejections built from the real+ * producers and the production Host-authority store.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, waitFor } from '@testing-library/react'+import type { SessionsListResult } from '../../../../../src/types'+import { isHostAvailabilityError } from '../../../lib/format'+import { deferred, localIndex, serverSessions } from './__fixtures__/catalogFixtures'+import { renderController } from './__fixtures__/controllerHarness'+import { ipcHttpError } from './__fixtures__/ipcErrors'+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let clerum: MockClerum++beforeEach(() => {+ clerum = installMockClerum()+})++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+ uninstallMockClerum()+})++type CatalogQuery = { agent: string; limit: number; cursor?: string } | undefined++const catalogToasts = (pushToast: ReturnType<typeof vi.fn>) =>+ pushToast.mock.calls.filter(([message]) => String(message).startsWith('Chat list for'))++const catalogUnavailable = () =>+ ipcHttpError('rpc:listSessions', 503, 'Service Unavailable', { error: 'upstream unavailable' })++/** Let pending promise continuations run without advancing any timer. */+async function flushMicrotasks(until: () => boolean): Promise<void> {+ for (let turn = 0; turn < 200 && !until(); turn += 1) {+ await Promise.resolve()+ }+ if (!until()) throw new Error('condition not reached within 200 microtask turns')+}++describe('load-more rejection for a Host that is no longer shown (NEW-dui-1)', () => {+ it("keeps agent-b's load-more state when agent-a's cursor is rejected late", async () => {+ const pendingA = deferred<SessionsListResult>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(+ async (agentRef: string, _teamId: string | undefined, query: CatalogQuery) => {+ if (query?.cursor) return pendingA.promise+ return serverSessions(+ [{ agent: agentRef, chatId: `${agentRef}-page-1` }],+ `${agentRef}-cursor`+ )+ }+ )+ const controller = renderController({+ selectedAgent: 'agent-a',+ agentNames: ['agent-a', 'agent-b'],+ })+ await waitFor(() => expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true))++ let loadMoreA!: Promise<void>+ act(() => {+ loadMoreA = controller.result.current.loadMoreChatSessions()+ })+ await waitFor(() =>+ expect(clerum.rpc.listSessions).toHaveBeenCalledWith('agent-a', undefined, {+ agent: 'agent-a',+ limit: 50,+ cursor: 'agent-a-cursor',+ })+ )++ controller.rerender({ selectedAgent: 'agent-b', agentNames: ['agent-a', 'agent-b'] })+ await waitFor(() =>+ expect(controller.result.current.chatList.map(chat => chat.id)).toContain('agent-b-page-1')+ )+ expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true)++ await act(async () => {+ pendingA.reject(+ await ipcHttpError('rpc:listSessions', 400, 'Bad Request', {+ error: 'Invalid sessions cursor',+ })+ )+ await loadMoreA+ })++ expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true)+ // Liveness: the rejection was the terminal kind (no retryable toast).+ expect(controller.spies.pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining("Couldn't load more chats"),+ 'info'+ )+ })+})++describe('load-more terminal cursor while the same Host is held (NEW-fa-3)', () => {+ it('leaves hasMore false and forgets the cursor when a cursor 400 arrives during an authority hold', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(+ async (agentRef: string, _teamId: string | undefined, query: CatalogQuery) => {+ if (query?.cursor) {+ throw await ipcHttpError('rpc:listSessions', 400, 'Bad Request', {+ error: 'Invalid sessions cursor',+ })+ }+ return serverSessions(+ [{ agent: agentRef, chatId: `${agentRef}-page-1` }],+ `${agentRef}-cursor`+ )+ }+ )+ const controller = renderController({ selectedAgent: 'agent-a', agentNames: ['agent-a'] })+ // Liveness: the first page left a valid cursor and a "Load more" button.+ await waitFor(() => expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true))++ // The Host is held before the load-more starts, so the request snapshots the+ // held epoch and the rejection reaches the blocked-Host branch.+ controller.hostAuthority.hold('agent-a', 'uncertain')++ await act(async () => {+ await controller.result.current.loadMoreChatSessions()+ })++ // Liveness: the cursor request really went out and was rejected.+ expect(clerum.rpc.listSessions).toHaveBeenCalledWith('agent-a', undefined, {+ agent: 'agent-a',+ limit: 50,+ cursor: 'agent-a-cursor',+ })+ expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(false)++ // The cursor was forgotten: another load-more issues no further read.+ const readsAfterFirst = clerum.rpc.listSessions.mock.calls.length+ await act(async () => {+ await controller.result.current.loadMoreChatSessions()+ })+ expect(clerum.rpc.listSessions.mock.calls.length).toBe(readsAfterFirst)+ // The terminal rejection is not a retryable failure: no toast.+ expect(controller.spies.pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining("Couldn't load more chats"),+ 'info'+ )+ })+})++describe('catalog offline toast (R2-L4, NEW-tq-5, NEW-dui-5/6)', () => {+ it('does not report a waking Host as offline', async () => {+ const waking = await ipcHttpError('rpc:listSessions', 503, 'Service Unavailable', {+ code: 'host_waking',+ hostRef: 'agent-a',+ retryAfterMs: 2000,+ message: 'Host is waking up',+ })+ // Fixture sanity: the real producer's wrapped 503 carries the waking code.+ expect(isHostAvailabilityError(waking)).toBe(true)+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))+ clerum.rpc.listSessions.mockRejectedValue(waking)+ const controller = renderController({ selectedAgent: 'agent-a', agentNames: ['agent-a'] })++ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())+ await waitFor(() =>+ expect(controller.result.current.chatList.map(chat => chat.id)).toEqual(['cached-a'])+ )+ // Let the post-paint selected-agent read settle too.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 60))+ })+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20))+ })+ expect(catalogToasts(controller.spies.pushToast)).toEqual([])+ expect(controller.hostAuthority.isBlocked('agent-a')).toBe(false)+ })++ it('shows one offline toast for several failing Hosts and none for a later failure', async () => {+ const unavailable = await catalogUnavailable()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockRejectedValue(unavailable)+ const controller = renderController({+ selectedAgent: null,+ agentNames: ['agent-a', 'agent-b'],+ })++ await waitFor(() => expect(catalogToasts(controller.spies.pushToast)).toHaveLength(1))+ expect(catalogToasts(controller.spies.pushToast)[0]).toEqual([+ 'Chat list for agent-a, agent-b is offline. Showing saved chats.',+ 'info',+ ])++ // A later failure while the outage is already reported.+ controller.rerender({ selectedAgent: null, agentNames: ['agent-a', 'agent-b', 'agent-c'] })+ await waitFor(() =>+ expect(clerum.rpc.listSessions).toHaveBeenCalledWith('agent-c', undefined, {+ agent: 'agent-c',+ limit: 50,+ })+ )+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20))+ })+ expect(catalogToasts(controller.spies.pushToast)).toHaveLength(1)+ })++ it('drops a queued offline toast when the controller unmounts', async () => {+ const pending = deferred<SessionsListResult>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockReturnValue(pending.promise)+ const controller = renderController({ selectedAgent: null, agentNames: ['agent-a'] })+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())+ const unavailable = await catalogUnavailable()++ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ pending.reject(unavailable)+ // Witness: the rejection reached the controller and queued the toast.+ await flushMicrotasks(() => vi.getTimerCount() === 1)++ controller.unmount()+ expect(vi.getTimerCount()).toBe(0)+ vi.runOnlyPendingTimers()+ expect(catalogToasts(controller.spies.pushToast)).toEqual([])+ })++ it('drops the previous scope’s queued offline toast when the scope changes', async () => {+ const pending = deferred<SessionsListResult>()+ const unavailable = await catalogUnavailable()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementationOnce(() => pending.promise)+ clerum.rpc.listSessions.mockRejectedValue(unavailable)+ const controller = renderController({ selectedAgent: null, agentNames: ['agent-a'] })+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalledTimes(1))++ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ pending.reject(unavailable)+ // Witness: the old scope's rejection queued its toast.+ await flushMicrotasks(() => vi.getTimerCount() === 1)++ // The new scope is down as well and queues its own toast.+ act(() => {+ controller.rerender({ selectedAgent: null, agentNames: ['agent-a'], currentTeamId: 'team-2' })+ })+ await flushMicrotasks(() => clerum.rpc.listSessions.mock.calls.length === 2)+ for (let turn = 0; turn < 200; turn += 1) await Promise.resolve()+ act(() => {+ vi.runOnlyPendingTimers()+ })++ // One toast for the one outage the user is looking at, never a second+ // one flushed from the scope they left.+ expect(catalogToasts(controller.spies.pushToast)).toEqual([+ ['Chat list for agent-a is offline. Showing saved chats.', 'info'],+ ])+ })++ it('ignores a success from an earlier scope when deduplicating the next outage', async () => {+ const lateOldScopeSuccess = deferred<SessionsListResult>()+ const unavailable = await catalogUnavailable()+ let teamOneReads = 0+ let scope: 'team-1' | 'team-2' = 'team-1'+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async () => {+ // team-1: held until after the scope change, then succeeds late.+ if (scope === 'team-1') {+ teamOneReads += 1+ return lateOldScopeSuccess.promise+ }+ // team-2 is down.+ throw unavailable+ })+ // The selected-agent read reports catalog success before its own scope+ // guard, so it is the path whose stale success must be ignored.+ const controller = renderController({ selectedAgent: 'agent-a', agentNames: ['agent-a'] })+ await waitFor(() => expect(teamOneReads).toBeGreaterThanOrEqual(1))+ await waitFor(() => expect(clerum.chat.getIndex.mock.calls.length).toBeGreaterThanOrEqual(2))+ // Let the post-paint selected-agent read attach to the pending request.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 60))+ })++ scope = 'team-2'+ controller.rerender({+ selectedAgent: 'agent-a',+ agentNames: ['agent-a'],+ currentTeamId: 'team-2',+ })+ await waitFor(() => expect(catalogToasts(controller.spies.pushToast)).toHaveLength(1))++ await act(async () => {+ lateOldScopeSuccess.resolve(serverSessions([{ agent: 'agent-a', chatId: 'old-scope' }]))+ await lateOldScopeSuccess.promise+ })++ // Another failure in team-2, via a catalog change that re-reads every Host.+ controller.rerender({+ selectedAgent: 'agent-a',+ agentNames: ['agent-a', 'agent-b'],+ currentTeamId: 'team-2',+ })+ await waitFor(() =>+ expect(clerum.rpc.listSessions).toHaveBeenCalledWith('agent-b', undefined, {+ agent: 'agent-b',+ limit: 50,+ })+ )+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20))+ })+ expect(catalogToasts(controller.spies.pushToast)).toHaveLength(1)+ expect(controller.result.current.chatList.map(chat => chat.id)).not.toContain('old-scope')+ })+})++describe('per-Host authority in the cross-agent list (R2-M5, R1-L11, R1-M10)', () => {+ function pendingCatalogs() {+ const pending = new Map<string, Array<ReturnType<typeof deferred<SessionsListResult>>>>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation((agentRef: string) => {+ const read = deferred<SessionsListResult>()+ pending.set(agentRef, [...(pending.get(agentRef) ?? []), read])+ return read.promise+ })+ const resolveAll = (agentRef: string) => {+ for (const read of pending.get(agentRef) ?? []) {+ read.resolve(serverSessions([{ agent: agentRef, chatId: `${agentRef}-session` }]))+ }+ pending.delete(agentRef)+ }+ return { pending, resolveAll }+ }++ it("keeps Host X's in-flight sessions when Host Y is held", async () => {+ const { pending, resolveAll } = pendingCatalogs()+ const controller = renderController({+ selectedAgent: null,+ agentNames: ['host-x', 'host-y'],+ })+ await waitFor(() => expect(pending.has('host-x') && pending.has('host-y')).toBe(true))+ const readsBeforeHold = clerum.rpc.listSessions.mock.calls.length++ controller.hostAuthority.hold('host-y', 'revoked')+ await act(async () => {+ resolveAll('host-x')+ resolveAll('host-y')+ })++ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.map(chat => chat.id)).toEqual([+ 'host-x-session',+ ])+ )+ // A hold reloads nothing: the in-flight read is the one that published.+ expect(clerum.rpc.listSessions.mock.calls.length).toBe(readsBeforeHold)+ })++ it('reloads a Host whose sessions were discarded while it was held', async () => {+ const { pending, resolveAll } = pendingCatalogs()+ const controller = renderController({ selectedAgent: null, agentNames: ['host-y'] })+ await waitFor(() => expect(pending.has('host-y')).toBe(true))++ controller.hostAuthority.hold('host-y', 'uncertain')+ await act(async () => {+ resolveAll('host-y')+ })+ await waitFor(() => expect(controller.result.current.latestChatSessionsLoading).toBe(false))+ expect(controller.result.current.latestChatSessions).toEqual([])++ controller.hostAuthority.release('host-y')+ // The reload may reuse the renderer's short-lived catalog request cache or+ // issue a new read; resolve any new read so either path can publish.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20))+ resolveAll('host-y')+ })+ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.map(chat => chat.id)).toEqual([+ 'host-y-session',+ ])+ )+ })++ it('returns the same latestChatSessions reference until its inputs change', async () => {+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>+ serverSessions([{ agent: agentRef, chatId: `${agentRef}-session` }])+ )+ const controller = renderController({+ selectedAgent: null,+ agentNames: ['host-x', 'host-y'],+ })+ await waitFor(() => expect(controller.result.current.latestChatSessions).toHaveLength(2))+ await waitFor(() => expect(controller.result.current.latestChatSessionsLoading).toBe(false))++ const first = controller.result.current.latestChatSessions+ controller.rerender({ selectedAgent: null, agentNames: ['host-x', 'host-y'] })+ expect(controller.result.current.latestChatSessions).toBe(first)++ controller.hostAuthority.hold('host-y', 'uncertain')+ const afterHold = controller.result.current.latestChatSessions+ expect(afterHold).not.toBe(first)+ expect(afterHold.map(chat => chat.id)).toEqual(['host-x-session'])+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsxindex 7f132dd38..d4e7ff41b 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx@@ -12,10 +12,18 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'import { act, waitFor } from '@testing-library/react'-import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'-import type { ChatIndex, SessionsListResult } from '../../../../../src/types'-import { httpErrorStatus } from '../../../lib/format'+import type { SessionsListResult } from '../../../../../src/types'+import { httpErrorStatus, isConfirmedHostAccessRevoked } from '../../../lib/format'+import { deferred, localIndex, serverSessions } from './__fixtures__/catalogFixtures'import { renderController } from './__fixtures__/controllerHarness'+import {+ ipcGenericForbidden,+ ipcHostAccessDenied,+ ipcHostAccessRevoked,+ ipcHostWaking,+ ipcHttpError,+ ipcServerErrorMentioning403,+} from './__fixtures__/ipcErrors'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -31,62 +39,79 @@ afterEach(() => {uninstallMockClerum()})-const NOW = '2026-09-12T00:00:00.000Z'-describe('HTTP status parsing through Electron IPC', () => {it.each([- ['Error invoking remote method: Error: 403 Forbidden: host_access_revoked', 403],- ['Error invoking remote method: Error: 401 Unauthorized', 401],- ['Error invoking remote method: Error: 503 Service Unavailable: upstream mentioned 403', 503],+ [+ "Error invoking remote method 'rpc:listSessions': Error: 403 Forbidden: host_access_revoked",+ 403,+ ],+ ["Error invoking remote method 'rpc:listSessions': Error: 401 Unauthorized", 401],+ [+ "Error invoking remote method 'rpc:listSessions': Error: 503 Service Unavailable: upstream mentioned 403",+ 503,+ ],["Error invoking remote method 'rpc:invoke': Error: 403 Forbidden", 403],['request to support-401 failed', undefined],])('parses %s as %s', (message, expected) => {expect(httpErrorStatus(message)).toBe(expected)})-})-/** Parse a raw wire payload through the real producer parser (T1). */-function serverSessions(- items: Array<{ agent: string; chatId: string; title?: string }>-): SessionsListResult {- return parseSessionsListResult({- items: items.map(i => ({- agent: i.agent,- chatId: i.chatId,- turnCount: 1,- lastActivityAt: NOW,- ...(i.title !== undefined ? { title: i.title } : {}),- })),+ // Electron never emits the wrapper without the quoted channel, so a+ // quote-less prefix is not stripped and no status is read through it.+ it('does not strip a wrapper that lacks the quoted channel Electron always emits', () => {+ expect(+ httpErrorStatus("Error invoking remote method 'rpc:listSessions': Error: 403 Forbidden")+ ).toBe(403)+ expect(httpErrorStatus('Error invoking remote method: Error: 403 Forbidden')).toBeUndefined()})-}--function localIndex(- chats: Array<{ id: string; title: string }>,- deletedChatIds: string[] = []-): ChatIndex {- const authorityScope = { environmentKey: 'env-test', userId: 'unknown-user', teamId: 'team-1' }- return {- version: 1,- lastActiveChatId: null,- onboardingDismissed: false,- chats: chats.map(c => ({- id: c.id,- title: c.title,- createdAt: NOW,- updatedAt: NOW,- messageCount: 0,- })),- deletedChatTombstones: deletedChatIds.map(chatId => ({ chatId, authorityScope })),- }-}--function deferred<T>() {- let resolve!: (value: T) => void- const promise = new Promise<T>(finish => {- resolve = finish++ // R2-B1 / NEW-dui-3: every shape the real producers emit, wrapped by IPC.+ it.each([+ ['listSessions revoked', () => ipcHostAccessRevoked('rpc:listSessions'), 403, true],+ [+ 'loadSessionMessages revoked',+ () => ipcHostAccessRevoked('rpc:loadSessionMessages'),+ 403,+ true,+ ],+ ['renameSession revoked', () => ipcHostAccessRevoked('rpc:renameSession'), 403, true],+ ['invokeHostMessage revoked', () => ipcHostAccessRevoked('rpc:invokeHostMessage'), 403, true],+ ['getTaskResult revoked', () => ipcHostAccessRevoked('rpc:getTaskResult'), 403, true],+ ['listSessions host_access_denied', () => ipcHostAccessDenied('rpc:listSessions'), 403, false],+ ['List sessions failed (403)', () => ipcGenericForbidden('rpc:listSessions'), 403, false],+ ['Rename session failed (403)', () => ipcGenericForbidden('rpc:renameSession'), 403, false],+ ['ApiError 403 Forbidden: …', () => ipcGenericForbidden('rpc:invokeHostMessage'), 403, false],+ [+ 'ApiError 401 Unauthorized: …',+ () => ipcHttpError('rpc:getTaskResult', 401, 'Unauthorized', { error: 'expired' }),+ 401,+ false,+ ],+ [+ 'List sessions 503 body mentions 403',+ () => ipcServerErrorMentioning403('rpc:listSessions'),+ 503,+ false,+ ],+ [+ 'ApiError 503 body mentions 403',+ () => ipcServerErrorMentioning403('rpc:invokeHostMessage'),+ 503,+ false,+ ],+ [+ 'host_waking for support-401',+ async () => ipcHostWaking('rpc:invokeHostMessage', 'support-401'),+ undefined,+ false,+ ],+ ])('classifies the real %s', async (_label, build, status, revoked) => {+ const error = await build()+ expect(error.message).toMatch(/^Error invoking remote method 'rpc:[A-Za-z]+': Error: /)+ expect(httpErrorStatus(error)).toBe(status)+ expect(isConfirmedHostAccessRevoked(error)).toBe(revoked)})- return { promise, resolve }-}+})describe('chat list title merge (spec 15 §2.2, cases A–D)', () => {it('case A: server-only session with a title shows the server title (no placeholder)', async () => {@@ -223,7 +248,6 @@ describe('confirmed deletion catalog protection', () => {describe('revoked host catalog protection', () => {it('filters held-host sessions from the sidebar while retaining them for recovery', async () => {- const blocked = new Set<string>()clerum.chat.getIndex.mockResolvedValue(localIndex([]))clerum.rpc.listSessions.mockResolvedValue(serverSessions([{ agent: 'agent-a', chatId: 'cached-session', title: 'Private title' }])@@ -231,7 +255,6 @@ describe('revoked host catalog protection', () => {const controller = renderController({selectedAgent: null,agentNames: ['agent-a'],- isHostAccessBlocked: agentRef => blocked.has(agentRef),})await waitFor(() =>@@ -240,15 +263,16 @@ describe('revoked host catalog protection', () => {]))- blocked.add('agent-a')- controller.rerender()+ controller.hostAuthority.hold('agent-a', 'uncertain')+ expect(controller.hostAuthority.isBlocked('agent-a')).toBe(true)expect(controller.result.current.latestChatSessions).toEqual([])- blocked.delete('agent-a')- controller.rerender()- expect(controller.result.current.latestChatSessions.map(session => session.id)).toEqual([- 'cached-session',- ])+ controller.hostAuthority.release('agent-a')+ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.map(session => session.id)).toEqual([+ 'cached-session',+ ])+ )})it('hides a nonselected host after 403 and blocks direct reselection', async () => {@@ -273,7 +297,7 @@ describe('revoked host catalog protection', () => {)clerum.rpc.loadSessionMessages.mockRejectedValue(- new Error('403 forbidden: host_access_revoked')+ await ipcHostAccessRevoked('rpc:loadSessionMessages'))await expect(controller.result.current.reconcileChat(makeTaskKey('agent-y', 'protected-y'), {@@ -296,54 +320,89 @@ describe('revoked host catalog protection', () => {)})- it.each([401, 403])(- 'blocks the Host after a generic %i catalog denial survives the forced retry',- async status => {- const blocked = new Set<string>()+ it.each([+ [+ 'List sessions failed (401)',+ () => ipcHttpError('rpc:listSessions', 401, 'Unauthorized', { error: 'expired' }),+ ],+ ['List sessions failed (403)', () => ipcGenericForbidden('rpc:listSessions')],+ ['403 Forbidden: host_access_denied', () => ipcHostAccessDenied('rpc:listSessions')],+ ])(+ 'holds the Host as uncertain after a generic %s survives the forced retry',+ async (_label, build) => {+ const revoked = new Set<string>()+ const uncertain = new Set<string>()clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'protected-a', title: 'Cached protected chat' }]))- clerum.rpc.listSessions.mockRejectedValue(new Error(`${status} forbidden`))+ clerum.rpc.listSessions.mockRejectedValue(await build())const { result } = renderController({selectedAgent: null,agentNames: ['agent-a'],- onHostAccessRevoked: agentRef => blocked.add(agentRef),- onHostAuthorityUncertain: agentRef => blocked.add(agentRef),- isHostAccessBlocked: agentRef => blocked.has(agentRef),+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked: agentRef => revoked.has(agentRef) || uncertain.has(agentRef),})- await waitFor(() => expect(blocked.has('agent-a')).toBe(true))+ await waitFor(() => expect(uncertain.has('agent-a')).toBe(true))+ expect(revoked.has('agent-a')).toBe(false)expect(clerum.rpc.listSessions).toHaveBeenCalledTimes(2)expect(result.current.latestChatSessions.some(chat => chat.id === 'protected-a')).toBe(false)})+ it('revokes the Host on the first confirmed catalog denial without a forced retry', async () => {+ const revoked = new Set<string>()+ const uncertain = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(+ localIndex([{ id: 'protected-a', title: 'Cached protected chat' }])+ )+ clerum.rpc.listSessions.mockRejectedValue(await ipcHostAccessRevoked('rpc:listSessions'))+ const { result, spies } = renderController({+ selectedAgent: null,+ agentNames: ['agent-a'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked: agentRef => revoked.has(agentRef) || uncertain.has(agentRef),+ })++ await waitFor(() => expect(revoked.has('agent-a')).toBe(true))+ expect(uncertain.has('agent-a')).toBe(false)+ expect(clerum.rpc.listSessions).toHaveBeenCalledTimes(1)+ expect(result.current.latestChatSessions.some(chat => chat.id === 'protected-a')).toBe(false)+ expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('Chat list'), 'info')+ })+it('keeps the selected agent and cached chat list after a 503 catalog failure', async () => {- const blocked = new Set<string>()clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))- clerum.rpc.listSessions.mockRejectedValue(new Error('503 Service Unavailable'))+ clerum.rpc.listSessions.mockRejectedValue(+ await ipcHttpError('rpc:listSessions', 503, 'Service Unavailable', {+ error: 'upstream unavailable',+ })+ )const controller = renderController({selectedAgent: 'agent-a',agentNames: ['agent-a'],- onHostAccessRevoked: agentRef => blocked.add(agentRef),- onHostAuthorityUncertain: agentRef => blocked.add(agentRef),- isHostAccessBlocked: agentRef => blocked.has(agentRef),+ // R2-L4: the toast names the Host the way the catalog displays it.+ agentDisplayName: agentRef => (agentRef === 'agent-a' ? 'Research Agent' : agentRef),})await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())await waitFor(() =>expect(controller.result.current.chatList.some(chat => chat.id === 'cached-a')).toBe(true))- expect(blocked.has('agent-a')).toBe(false)+ expect(controller.hostAuthority.isBlocked('agent-a')).toBe(false)await waitFor(() => expect(controller.spies.pushToast).toHaveBeenCalledTimes(1))expect(controller.spies.pushToast).toHaveBeenCalledWith(- 'Chat list for agent-a is offline. Showing saved chats.',+ 'Chat list for Research Agent is offline. Showing saved chats.','info')})it('does not show the offline toast for a client-side catalog error', async () => {clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))- clerum.rpc.listSessions.mockRejectedValue(new Error('400 Bad Request: invalid cursor'))+ clerum.rpc.listSessions.mockRejectedValue(+ await ipcHttpError('rpc:listSessions', 400, 'Bad Request', { error: 'invalid cursor' })+ )const controller = renderController({selectedAgent: 'agent-a',agentNames: ['agent-a'],@@ -359,14 +418,16 @@ describe('revoked host catalog protection', () => {)})- it('clears a rejected load-more cursor after a client-side cursor error', async () => {+ // NEW-dui-2: every non-auth, non-429 client error ends the page chain.+ it.each([+ [400, 'Bad Request', { error: 'Invalid sessions cursor' }],+ [404, 'Not Found', { error: 'cursor session not found' }],+ ])('clears a rejected load-more cursor after a terminal %s', async (status, statusText, body) => {+ const rejection = await ipcHttpError('rpc:listSessions', status, statusText, body)clerum.rpc.listSessions.mockImplementation(async (_agentRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {- if (query?.cursor) throw new Error('400 Bad Request: Invalid sessions cursor')- return {- ...serverSessions([{ agent: 'agent-x', chatId: 'remote-page-1' }]),- nextCursor: 'cursor-invalid',- }+ if (query?.cursor) throw rejection+ return serverSessions([{ agent: 'agent-x', chatId: 'remote-page-1' }], 'cursor-invalid')})const controller = renderController()@@ -375,42 +436,67 @@ describe('revoked host catalog protection', () => {await act(async () => {await controller.result.current.loadMoreChatSessions()})-expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(false)++ // The cursor is gone: a second request never re-sends it.+ await act(async () => {+ await controller.result.current.loadMoreChatSessions()+ })expect(clerum.rpc.listSessions.mock.calls.filter(call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-invalid')).toHaveLength(1)+ expect(controller.spies.pushToast).not.toHaveBeenCalledWith(+ expect.stringContaining("Couldn't load more chats"),+ 'info'+ )})- it('preserves the load-more cursor during a transient rate limit', async () => {+ // NEW-dui-2: 429 and 5xx keep the cursor, tell the user once per attempt and+ // never retry on their own.+ it.each([+ [429, 'Too Many Requests'],+ [503, 'Service Unavailable'],+ ])('preserves the load-more cursor after a retryable %s', async (status, statusText) => {+ const rejection = await ipcHttpError('rpc:listSessions', status, statusText, {+ error: 'try later',+ })clerum.rpc.listSessions.mockImplementation(async (_agentRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {- if (query?.cursor) throw new Error('429 Too Many Requests')- return {- ...serverSessions([{ agent: 'agent-x', chatId: 'remote-page-1' }]),- nextCursor: 'cursor-rate-limited',- }+ if (query?.cursor) throw rejection+ return serverSessions([{ agent: 'agent-x', chatId: 'remote-page-1' }], 'cursor-retryable')})- const controller = renderController()+ const controller = renderController({+ agentDisplayName: agentRef => (agentRef === 'agent-x' ? 'Agent X' : agentRef),+ })await waitFor(() => expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true))await act(async () => {await controller.result.current.loadMoreChatSessions()})expect(controller.result.current.chatListHasMoreRemoteSessions).toBe(true)+ expect(controller.spies.pushToast).toHaveBeenCalledTimes(1)+ expect(controller.spies.pushToast).toHaveBeenCalledWith(+ "Couldn't load more chats for Agent X. Try again shortly.",+ 'info'+ )await act(async () => {await controller.result.current.loadMoreChatSessions()})+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20))+ })+ // Exactly the two user-initiated attempts: no automatic retry loop.expect(clerum.rpc.listSessions.mock.calls.filter(- call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-rate-limited'+ call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-retryable')).toHaveLength(2)+ expect(controller.spies.pushToast).toHaveBeenCalledTimes(2)})})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsxindex 08685ed5e..3d2908e06 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx@@ -16,6 +16,7 @@ import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'import type { ChatIndex } from '../../../../../src/types'import { MAX_RENAME_SYNC_ATTEMPTS, deletedChatIdsForScope } from '../useChatListController'import { renderController } from './__fixtures__/controllerHarness'+import { ipcGenericForbidden, ipcHostAccessRevoked, ipcHttpError } from './__fixtures__/ipcErrors'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -54,7 +55,9 @@ function localIndex(chats: Array<{ id: string; title: string }>): ChatIndex {}describe('scoped deletion visibility', () => {- it('filters tombstones by environment, user, and team', () => {+ // Same identity as main's `sameChatDeletionIdentity`: environment + user. A+ // deletion confirmed under one team keeps holding after a team switch.+ it('filters tombstones by environment and user, across team switches', () => {const index: ChatIndex = {...localIndex([]),deletedChatTombstones: [@@ -66,30 +69,24 @@ describe('scoped deletion visibility', () => {chatId: 'other-environment-delete',authorityScope: { environmentKey: 'env-2', userId: 'user-1', teamId: 'team-a' },},+ {+ chatId: 'other-user-delete',+ authorityScope: { environmentKey: 'env-1', userId: 'user-2', teamId: 'team-a' },+ },],}+ for (const teamId of ['team-a', 'team-b', null]) {+ expect(+ deletedChatIdsForScope(index, { environmentKey: 'env-1', userId: 'user-1', teamId })+ ).toEqual(['team-a-delete'])+ }expect(- deletedChatIdsForScope(index, {- environmentKey: 'env-1',- userId: 'user-1',- teamId: 'team-a',- })- ).toEqual(['team-a-delete'])- expect(- deletedChatIdsForScope(index, {- environmentKey: 'env-1',- userId: 'user-1',- teamId: 'team-b',- })- ).toEqual([])+ deletedChatIdsForScope(index, { environmentKey: 'env-2', userId: 'user-1', teamId: null })+ ).toEqual(['other-environment-delete'])expect(- deletedChatIdsForScope(index, {- environmentKey: 'env-1',- userId: 'user-1',- teamId: null,- })- ).toEqual([])+ deletedChatIdsForScope(index, { environmentKey: 'env-1', userId: 'user-2', teamId: 'x' })+ ).toEqual(['other-user-delete'])})})@@ -158,45 +155,57 @@ function reportedSessions(chats: Array<{ chatId: string; title?: string }>) {}describe('rename pending queue (spec 15 §2.5)', () => {+ // R2-B1: the rename and read failures are the real RpcProxyClient rejections+ // wrapped the way Electron IPC wraps them.it.each([{label: 'exact Host denial',- renameError: 'Rename session failed (403): host_access_revoked',- readStatus: null,+ renameError: () => ipcHostAccessRevoked('rpc:renameSession'),+ readError: null,shouldRevoke: true,shouldBeUncertain: false,},{label: 'operation-scope denial',- renameError: 'Rename session failed (403)',- readStatus: null,+ renameError: () => ipcGenericForbidden('rpc:renameSession'),+ readError: null,shouldRevoke: false,shouldBeUncertain: false,},{label: 'read also denied',- renameError: 'Rename session failed (403)',- readStatus: 403,+ renameError: () => ipcGenericForbidden('rpc:renameSession'),+ readError: () => ipcGenericForbidden('rpc:listSessions'),shouldRevoke: false,shouldBeUncertain: true,},+ {+ label: 'read revoked',+ renameError: () => ipcGenericForbidden('rpc:renameSession'),+ readError: () => ipcHostAccessRevoked('rpc:listSessions'),+ shouldRevoke: true,+ shouldBeUncertain: false,+ },{label: 'read unavailable',- renameError: 'Rename session failed (403)',- readStatus: 503,+ renameError: () => ipcGenericForbidden('rpc:renameSession'),+ readError: () =>+ ipcHttpError('rpc:listSessions', 503, 'Service Unavailable', { error: 'unavailable' }),shouldRevoke: false,shouldBeUncertain: true,},])('$label applies the transcript authority decision',- async ({ renameError, readStatus, shouldRevoke, shouldBeUncertain }) => {+ async ({ renameError, readError, shouldRevoke, shouldBeUncertain }) => {const revoked = new Set<string>()const uncertain = new Set<string>()+ const renameFailure = await renameError()+ const readFailure = readError ? await readError() : nullclerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))- clerum.rpc.renameSession.mockRejectedValue(new Error(renameError))+ clerum.rpc.renameSession.mockRejectedValue(renameFailure)clerum.rpc.listSessions.mockImplementation(async (_hostRef: string, _teamId: string | undefined, query?: { limit?: number }) => {- if (query?.limit === 1 && readStatus !== null) throw new Error(`${readStatus} response`)+ if (query?.limit === 1 && readFailure !== null) throw readFailurereturn reportedSessions([{ chatId: 'c1', title: 'old' }])})@@ -211,6 +220,8 @@ describe('rename pending queue (spec 15 §2.5)', () => {await act(async () => {await result.current.handleRenameChatForAgent('agent-x', 'c1', 'new')})+ // Liveness witness: the rename reached the producer.+ expect(clerum.rpc.renameSession).toHaveBeenCalledWith('agent-x', 'agent-x', 'c1', 'new')expect(revoked.has('agent-x')).toBe(shouldRevoke)expect(uncertain.has('agent-x')).toBe(shouldBeUncertain)if (shouldRevoke) expect(result.current.chatList).toEqual([])diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsxindex 3eb511eb4..c0178a627 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.characterization.test.tsx@@ -224,3 +224,39 @@ describe('sendAgentMessage — auto-title on send (B10)', () => {)})})++// R1-M11: the fake store must merge a second write of the same turn the way+// `ChatStore.upsertMessages` does. The send path persists the user turn before+// the POST and again with its task_id once the Host accepts it; a fake that+// drops the second write hides a lost task_id.+describe('sendAgentMessage — outgoing user turn persistence', () => {+ it('keeps the task_id the acknowledgement adds to the persisted user turn', async () => {+ clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-77' })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.handleSendAgentMessage('hello')+ })++ // Witness: the same turn was written twice, the second time with its task.+ await waitFor(() => expect(clerum.chat.upsertMessages).toHaveBeenCalledTimes(2))+ const [agentRef, chatId, firstWrite] = clerum.chat.upsertMessages.mock.calls[0] as [+ string,+ string,+ Array<{ id: string }>,+ ]+ const turnId = firstWrite[0]?.id+ expect(clerum.chat.upsertMessages.mock.calls[1]?.[2]?.[0]).toMatchObject({+ id: turnId,+ task_id: 'task-77',+ })++ const persistedUserTurns = clerum+ .persistedMessages(agentRef, chatId)+ .filter(message => message.role === 'user')+ expect(persistedUserTurns).toEqual([+ expect.objectContaining({ id: turnId, content: 'hello', task_id: 'task-77' }),+ ])+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsxindex 30d09eff6..c8f1ddb66 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx@@ -15,7 +15,9 @@ import {resetComposerDraftStore,setComposerDraft,} from '@lib/composerDraftStore'+import { localIndex, serverSessions } from './__fixtures__/catalogFixtures'import { renderController } from './__fixtures__/controllerHarness'+import { ipcGenericForbidden, ipcHostAccessRevoked } from './__fixtures__/ipcErrors'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'let clerum: MockClerum@@ -1094,6 +1096,110 @@ describe('switchToChat (unified, D.4)', () => {})+ // R1-M8: the two hold kinds share one tear-down of the Host's live work and+ // differ only in what they hide. An uncertain hold (401 after refresh, or a 403+ // without a revocation code) must not destroy state the user may still own+ // once the hold is released: the chat and its list stay. The deselection+ // itself is the `onHostAuthorityUncertain` callback (`useAppController`).+ it('uncertain host-access hold releases the tracker, resets the chat state and deselects the agent, but does not hide the agent or clear the list; a confirmed revocation does', async () => {+ const chatKey = makeTaskKey('agent-x', 'older-hold')+ const runScenario = async (readError: () => Promise<Error>) => {+ const revoked = new Set<string>()+ const uncertain = new Set<string>()+ clerum.rpc.loadSessionMessages.mockReset()+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'older-hold', title: 'Held chat' }]))+ clerum.chat.loadMessages.mockResolvedValue([])+ clerum.rpc.listSessions.mockResolvedValue(+ serverSessions([{ agent: 'agent-x', chatId: 'older-hold' }])+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef, _agent, chatId, _teamId, query?: { beforeTurn?: number }) => {+ if (query?.beforeTurn !== undefined) throw await readError()+ return {+ agent: 'agent-x',+ chatId,+ state: 'processing',+ activeTaskId: 'task-hold',+ turns: [turn(5, 'question')],+ hasMoreBefore: true,+ hasMoreAfter: false,+ }+ }+ )+ // Stable callbacks, like the production `useCallback`s: a new+ // `isHostAccessBlocked` identity per render would re-run the+ // agent-selection effect, which clears the list of a blocked Host by itself.+ const isHostAccessBlocked = (agentRef: string) =>+ revoked.has(agentRef) || uncertain.has(agentRef)+ const controller = renderController({+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked,+ })+ await settleMount()+ await waitFor(() =>+ expect(controller.result.current.chatList.map(chat => chat.id)).toContain('older-hold')+ )+ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.map(chat => chat.id)).toContain(+ 'older-hold'+ )+ )+ await act(async () => {+ await controller.result.current.switchToChat('agent-x', 'older-hold')+ })+ // Liveness: the tracker is following the task, the FSM tracks the chat and+ // an older page exists, so the tear-down below has something to undo.+ await waitFor(() => expect(clerum.hasProgressHandler('task-hold')).toBe(true))+ const phaseBefore = controller.result.current.sessionFsmStore.getState(chatKey)?.phase+ expect(phaseBefore).toBeDefined()+ expect(phaseBefore).not.toBe('idle')+ expect(controller.result.current.hasOlderMessages).toBe(true)++ await act(async () => {+ await controller.result.current.handleLoadOlderMessages()+ })+ const observed = {+ revoked: revoked.has('agent-x'),+ uncertain: uncertain.has('agent-x'),+ trackerFollowsTask: clerum.hasProgressHandler('task-hold'),+ phaseAfter: controller.result.current.sessionFsmStore.getState(chatKey)?.phase,+ activeChatId: controller.result.current.activeChatId,+ }+ // The published lists mask a held Host on their own. Lift the hold to read+ // the state underneath: what the hold tore down is what is gone.+ revoked.clear()+ uncertain.clear()+ act(() => controller.rerender())+ const unmasked = {+ chatListIds: controller.result.current.chatList.map(chat => chat.id),+ latestIds: controller.result.current.latestChatSessions.map(chat => chat.id),+ }+ controller.unmount()+ return { phaseBefore, ...observed, ...unmasked }+ }++ const held = await runScenario(() => ipcGenericForbidden('rpc:loadSessionMessages'))+ expect(held.uncertain).toBe(true)+ expect(held.revoked).toBe(false)+ expect(held.trackerFollowsTask).toBe(false)+ expect(held.phaseAfter).not.toBe(held.phaseBefore)+ expect(held.chatListIds).toEqual(['older-hold'])+ expect(held.latestIds).toEqual(['older-hold'])+ expect(held.activeChatId).toBe('older-hold')++ const revokedRun = await runScenario(() => ipcHostAccessRevoked('rpc:loadSessionMessages'))+ expect(revokedRun.revoked).toBe(true)+ expect(revokedRun.uncertain).toBe(false)+ // Same tear-down of the Host's live work...+ expect(revokedRun.trackerFollowsTask).toBe(false)+ expect(revokedRun.phaseAfter).not.toBe(revokedRun.phaseBefore)+ // ...plus the hide: the list is cleared and the chat is closed.+ expect(revokedRun.chatListIds).toEqual([])+ expect(revokedRun.latestIds).toEqual([])+ expect(revokedRun.activeChatId).toBeNull()+ })+it('re-fetches the newest cached turn so a response completed after caching is recovered', async () => {clerum.chat.loadMessages.mockResolvedValue([{ id: 'turn-1-user', role: 'user' as const, content: 'q', timestamp: 1, serverTurnNumber: 1 },diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsxindex 64e06d3e8..36aad7b89 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsx@@ -14,19 +14,24 @@ import { useAgentChatController } from '@hooks/domain/useAgentChatController'import { useComposerDraft } from '@hooks/useComposerDraft'import { getComposerDraft, resetComposerDraftStore } from '@lib/composerDraftStore'import type { TaskProgressStreamEvent } from '../../../../../src/types'+import { useHarnessHostAuthority } from './__fixtures__/hostAuthorityHarness'+import {+ ipcGenericForbidden,+ ipcHostAccessDenied,+ ipcHostAccessRevoked,+ ipcHostWaking,+ ipcHttpError,+ ipcServerErrorMentioning403,+} from './__fixtures__/ipcErrors'type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>+// Record every hold the controller requests; the hold itself goes through the+// production store (useHarnessHostAuthority), so epochs are real.const revokedAgents = new Set<string>()const uncertainAgents = new Set<string>()-const onHostAccessRevoked = (agentRef: string) => {- revokedAgents.add(agentRef)+const recordHold = (agentRef: string, kind: 'revoked' | 'uncertain') => {+ ;(kind === 'revoked' ? revokedAgents : uncertainAgents).add(agentRef)}-const onHostAuthorityUncertain = (agentRef: string) => {- uncertainAgents.add(agentRef)-}-const isHostAccessBlocked = (agentRef: string) =>- revokedAgents.has(agentRef) || uncertainAgents.has(agentRef)-const getHostAuthorityEpoch = () => 0function getDraftInputValue(): string {return (screen.getByTestId('draft-input') as HTMLInputElement).value@@ -160,19 +165,22 @@ function AgentChatHarness() {const [selectionState, setSelectionState] = React.useState('idle')const [sendState, setSendState] = React.useState('idle')const [selectedAgent, setSelectedAgent] = React.useState('trader')+ const hostAuthority = useHarnessHostAuthority(recordHold)const vm = useAgentChatController({selectedAgent,agentNames: ['trader', 'chatllm-stateless'],currentTeamId: 'team-1',+ chatAuthorityTeamId: 'team-1',currentEnvironmentKey: 'env-test',currentTeamName: 'Team One',isAuthenticated: true,loadMenuData: true,navItem: 'chat',- onHostAccessRevoked,- onHostAuthorityUncertain,- isHostAccessBlocked,- getHostAuthorityEpoch,+ onHostAccessRevoked: hostAuthority.onHostAccessRevoked,+ onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,+ isHostAccessBlocked: hostAuthority.isHostAccessBlocked,+ getHostAuthorityEpoch: hostAuthority.getHostAuthorityEpoch,+ hostAuthorityRevision: hostAuthority.revision,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,@@ -522,7 +530,7 @@ describe('useAgentChatController (cross-chat, migrated)', () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }))await waitFor(() => expect(invokeHostMessage).toHaveBeenCalledTimes(1))- loadSessionMessages.mockRejectedValue(new Error('403 forbidden: host_access_revoked'))+ loadSessionMessages.mockRejectedValue(await ipcHostAccessRevoked('rpc:loadSessionMessages'))fireEvent.click(screen.getByRole('button', { name: `Select chat ${chatId}` }))await waitFor(() => expect(revokedAgents.has('trader')).toBe(true))await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).toBe(''))@@ -537,38 +545,70 @@ describe('useAgentChatController (cross-chat, migrated)', () => {expect(progressHandlers.has('late-task')).toBe(false)})+ // R2-B1: every failure is the real RpcProxyClient rejection wrapped the way+ // Electron IPC wraps it, never a hand-written bare message.it.each([{label: '401',- sendError: '401 unauthorized',+ sendError: () =>+ ipcHttpError('rpc:invokeHostMessage', 401, 'Unauthorized', { error: 'expired' }),readError: null,revoked: false,uncertain: true,},{label: 'exact Host-wide 403',- sendError: '403 Forbidden: host_access_revoked',- readError: '503 unavailable',+ sendError: () => ipcHostAccessRevoked('rpc:invokeHostMessage'),+ readError: () =>+ ipcHttpError('rpc:listSessions', 503, 'Service Unavailable', { error: 'unavailable' }),revoked: true,uncertain: false,},+ {+ label: 'host_access_denied 403 with readable catalog',+ sendError: () => ipcHostAccessDenied('rpc:invokeHostMessage'),+ readError: null,+ revoked: false,+ uncertain: false,+ },{label: 'generic 403 with readable catalog',- sendError: '403 missing send scope',+ sendError: () => ipcGenericForbidden('rpc:invokeHostMessage'),readError: null,revoked: false,uncertain: false,},{label: 'generic 403 with denied catalog',- sendError: '403 missing send scope',- readError: '403 forbidden',+ sendError: () => ipcGenericForbidden('rpc:invokeHostMessage'),+ readError: () => ipcGenericForbidden('rpc:listSessions'),revoked: false,uncertain: true,},+ {+ label: 'generic 403 with revoked catalog',+ sendError: () => ipcGenericForbidden('rpc:invokeHostMessage'),+ readError: () => ipcHostAccessRevoked('rpc:listSessions'),+ revoked: true,+ uncertain: false,+ },{label: '404',- sendError: '404 transient',+ sendError: () => ipcHttpError('rpc:invokeHostMessage', 404, 'Not Found', { error: 'gone' }),+ readError: null,+ revoked: false,+ uncertain: false,+ },+ {+ label: '503 whose body mentions 403',+ sendError: () => ipcServerErrorMentioning403('rpc:invokeHostMessage'),+ readError: null,+ revoked: false,+ uncertain: false,+ },+ {+ label: 'waking Host named support-401',+ sendError: async () => ipcHostWaking('rpc:invokeHostMessage', 'support-401'),readError: null,revoked: false,uncertain: false,@@ -576,8 +616,10 @@ describe('useAgentChatController (cross-chat, migrated)', () => {])('send $label applies the transcript authority decision',async ({ sendError, readError, revoked, uncertain }) => {+ const sendFailure = await sendError()+ const readFailure = readError ? await readError() : nullconst { invokeHostMessage, listSessions } = installClerumHarness()- invokeHostMessage.mockRejectedValueOnce(new Error(sendError))+ invokeHostMessage.mockRejectedValueOnce(sendFailure)render(<AgentTaskTrackerProvider><AgentChatHarness />@@ -586,9 +628,11 @@ describe('useAgentChatController (cross-chat, migrated)', () => {fireEvent.click(screen.getByRole('button', { name: 'Create chat' }))await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).not.toBe(''))const chatId = screen.getByTestId('active-chat-id').textContent || ''- if (readError) listSessions.mockRejectedValue(new Error(readError))+ if (readFailure) listSessions.mockRejectedValue(readFailure)fireEvent.click(screen.getByRole('button', { name: 'Send message' }))await waitFor(() => expect(screen.getByTestId('send-state').textContent).toBe('settled'))+ // Liveness witness: the send reached the producer and failed with it.+ expect(invokeHostMessage).toHaveBeenCalledTimes(1)expect(revokedAgents.has('trader')).toBe(revoked)expect(uncertainAgents.has('trader')).toBe(uncertain)if (revoked) {diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsxindex 2efc854f1..0e93b4f9d 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx@@ -17,12 +17,9 @@ import { useComposerDraft } from '@hooks/useComposerDraft'import { resetComposerDraftStore } from '@lib/composerDraftStore'import { resetHostModelSelectionStore } from '@lib/hostModelSelectionStore'import type { TaskProgressStreamEvent } from '../../../../../src/types'+import { useHarnessHostAuthority } from './__fixtures__/hostAuthorityHarness'type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>-const onHostAccessRevoked = () => {}-const onHostAuthorityUncertain = () => {}-const isHostAccessBlocked = () => false-const getHostAuthorityEpoch = () => 0function createChatMeta(chatId: string) {const now = new Date().toISOString()@@ -130,19 +127,22 @@ function installClerumHarness() {}function AgentChatHarness() {+ const hostAuthority = useHarnessHostAuthority()const vm = useAgentChatController({selectedAgent: 'trader',agentNames: ['trader'],currentTeamId: 'team-1',+ chatAuthorityTeamId: 'team-1',currentEnvironmentKey: 'env-test',currentTeamName: 'Team One',isAuthenticated: true,loadMenuData: true,navItem: 'chat',- onHostAccessRevoked,- onHostAuthorityUncertain,- isHostAccessBlocked,- getHostAuthorityEpoch,+ onHostAccessRevoked: hostAuthority.onHostAccessRevoked,+ onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,+ isHostAccessBlocked: hostAuthority.isHostAccessBlocked,+ getHostAuthorityEpoch: hostAuthority.getHostAuthorityEpoch,+ hostAuthorityRevision: hostAuthority.revision,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsxindex 0e5e38bd6..589b92d67 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx@@ -27,6 +27,7 @@ import type { NavItem } from '../../../uiTypes'import { useAgentChatController } from '../useAgentChatController'// React 18/19 needs this flag for act() to flush effects in the test env.import { useHostPrewarmController } from '../useHostPrewarmController'+import { useHarnessHostAuthority } from './__fixtures__/hostAuthorityHarness'import { installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -81,27 +82,25 @@ interface HarnessProps {isAuthenticated: booleannavItem: NavItem}-const onHostAccessRevoked = () => {}-const onHostAuthorityUncertain = () => {}-const isHostAccessBlocked = () => false-const getHostAuthorityEpoch = () => 0-/** Both real hooks, mounted together under the task-tracker the chat controller needs. */function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navItem }: HarnessProps) {useHostPrewarmController({ agentNames, isAuthenticated })+ const hostAuthority = useHarnessHostAuthority()return useAgentChatController({selectedAgent,agentNames,currentTeamId: 'team-1',+ chatAuthorityTeamId: 'team-1',currentEnvironmentKey: 'env-test',currentTeamName: 'Team 1',isAuthenticated,loadMenuData: true,navItem,- onHostAccessRevoked,- onHostAuthorityUncertain,- isHostAccessBlocked,- getHostAuthorityEpoch,+ onHostAccessRevoked: hostAuthority.onHostAccessRevoked,+ onHostAuthorityUncertain: hostAuthority.onHostAuthorityUncertain,+ isHostAccessBlocked: hostAuthority.isHostAccessBlocked,+ getHostAuthorityEpoch: hostAuthority.getHostAuthorityEpoch,+ hostAuthorityRevision: hostAuthority.revision,...stableCallbacks,})}diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 9622afe20..f86544b29 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -365,6 +365,14 @@ interface UseAgentChatControllerParams {onHostAuthorityUncertain: (agentRef: string) => voidisHostAccessBlocked: (agentRef: string) => booleangetHostAuthorityEpoch: (agentRef: string) => number+ /** Changes whenever a Host is held, released, or the authority scope resets. */+ hostAuthorityRevision: number+ /**+ * The authenticated principal's own team (`me.teamId`), with no directory+ * fallback. The chat delete fence and its tombstones are scoped to it, the+ * same value AppService's `getChatDeletionFenceAuthority` uses.+ */+ chatAuthorityTeamId: string}export function useAgentChatController({@@ -388,17 +396,20 @@ export function useAgentChatController({onHostAuthorityUncertain,isHostAccessBlocked,getHostAuthorityEpoch,+ hostAuthorityRevision,+ chatAuthorityTeamId,}: UseAgentChatControllerParams) {const chatStore = useChatStore()const userScopeKey = currentUserId ?? 'unknown-user'const normalizedTeamId = String(currentTeamId || '').trim() || null+ const fenceTeamId = chatAuthorityTeamId.trim() || nullconst authorityScope = useMemo(() => ({environmentKey: currentEnvironmentKey,userId: userScopeKey,- teamId: normalizedTeamId,+ teamId: fenceTeamId,}),- [currentEnvironmentKey, normalizedTeamId, userScopeKey]+ [currentEnvironmentKey, fenceTeamId, userScopeKey])const authenticatedScope = `${currentEnvironmentKey}:${userScopeKey}:${normalizedTeamId ?? ''}`@@ -454,6 +465,7 @@ export function useAgentChatController({host: chatListHostRef,isHostAccessBlocked,getHostAuthorityEpoch,+ hostAuthorityRevision,onHostAccessRevoked: onCatalogHostAccessRevoked,onHostAuthorityUncertain: onCatalogHostAuthorityUncertain,})@@ -1094,6 +1106,7 @@ export function useAgentChatController({},shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,pushToast,+ agentDisplayName,}})diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 7c87b7d66..c29050904 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -1,7 +1,8 @@-import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'+import { type MutableRefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'+import { byUpdatedDesc, mergeCatalogPage } from '@lib/catalogMerge'import { agentChatPlaceholder, remotePlaceholder } from '@lib/chatTitle'-import { type PendingRename, resolveSessionTitle } from '@lib/resolveSessionTitle'+import type { PendingRename } from '@lib/resolveSessionTitle'import type {ChatAuthorityScope,ChatDeleteFence,@@ -13,6 +14,7 @@ import {httpErrorStatus,isAuthorizationError,isConfirmedHostAccessRevoked,+ isHostAvailabilityError,isHttpServerError,isNetworkError,} from '../../lib/format'@@ -111,6 +113,8 @@ export interface ChatListControllerHost {* rather than taking `pushToast` as a param (its callers don't have it).*/pushToast: (message: string, tone: 'success' | 'error' | 'info') => void+ /** The catalog display name for an agent reference, used in user-facing copy. */+ agentDisplayName: (agentRef: string) => string}interface UseChatListControllerParams {@@ -133,6 +137,8 @@ interface UseChatListControllerParams {host: MutableRefObject<ChatListControllerHost | null>isHostAccessBlocked: (agentRef: string) => booleangetHostAuthorityEpoch: (agentRef: string) => number+ /** Changes whenever `isHostAccessBlocked` may answer differently. */+ hostAuthorityRevision: numberonHostAccessRevoked: (agentRef: string) => voidonHostAuthorityUncertain: (agentRef: string) => void}@@ -142,24 +148,29 @@ function sortableTimestamp(value: string): number {return Number.isFinite(timestamp) ? timestamp : 0}-const byUpdatedDesc = (a: { updatedAt: string }, b: { updatedAt: string }) =>- sortableTimestamp(b.updatedAt) - sortableTimestamp(a.updatedAt)-const byLastActivityDesc = (a: { lastActivityAt: string }, b: { lastActivityAt: string }) =>sortableTimestamp(b.lastActivityAt) - sortableTimestamp(a.lastActivityAt)-function isRecoverableCatalogCursorError(error: unknown): boolean {- const message = (error instanceof Error ? error.message : String(error)).toLowerCase()+/**+ * A load-more failure the same cursor can never recover from: any client error+ * other than an authorization status (handled as authority) or a rate limit+ * (retryable). Re-sending the cursor after a 400/404/409/410 only repeats the+ * rejection, so the page chain ends here.+ */+function isTerminalCatalogCursorError(error: unknown): boolean {const status = httpErrorStatus(error)- const invalidCursor = /invalid (?:sessions )?cursor/.test(message)- if (status === 429) return false- if (status !== undefined) {- return status === 400 && invalidCursor- }- return invalidCursor+ return (+ status !== undefined &&+ status >= 400 &&+ status < 500 &&+ status !== 401 &&+ status !== 403 &&+ status !== 429+ )}function isCatalogOutageError(error: unknown): boolean {+ if (isHostAvailabilityError(error)) return falseconst status = httpErrorStatus(error)if (status !== undefined) return isHttpServerError(error)return isNetworkError(error)@@ -201,6 +212,38 @@ function knownServerMessageCount(session: SessionsListResult['items'][number]):return typeof count === 'number' && Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0}+/** A cross-agent catalog session tagged with the agent whose page reported it. */+type LatestCatalogSession = SessionsListResult['items'][number] & { agentRef: string }++/** The selected agent's sidebar: entries keyed by chat id, "Chat <id>" placeholder. */+function mergeSelectedAgentCatalogPage(+ cached: SidebarChatEntry[],+ sessions: SessionsListResult['items'],+ agentRef: string,+ pendingRenameStateFor: (agentRef: string, chatId: string) => PendingRename+): SidebarChatEntry[] {+ return mergeCatalogPage<SidebarChatEntry, SessionsListResult['items'][number]>({+ cached,+ sessions,+ entryKey: entry => entry.id,+ sessionKey: session => session.chatId,+ entryPendingRename: entry => pendingRenameStateFor(agentRef, entry.id),+ sessionPendingRename: session => pendingRenameStateFor(agentRef, session.chatId),+ placeholderFor: agentChatPlaceholder,+ serverOnlyEntry: (session, title) => ({+ id: session.chatId,+ title,+ createdAt: session.lastActivityAt,+ updatedAt: session.lastActivityAt,+ // Older hosts omit messageCount. Keep that unknown value at zero instead+ // of fabricating two messages per turn and overstating Activity totals+ // when tool/system messages vary by session.+ messageCount: knownServerMessageCount(session),+ remote: true,+ }),+ })+}+function sameAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {return (left.environmentKey === right.environmentKey &&@@ -209,11 +252,20 @@ function sameAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope))}+/**+ * The identity a local deletion is bound to, identical to main's+ * `sameChatDeletionIdentity`: environment + user. The team is not part of it,+ * so a confirmed deletion keeps holding after a team switch.+ */+function sameChatDeletionIdentity(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {+ return left.environmentKey === right.environmentKey && left.userId === right.userId+}+export function deletedChatIdsForScope(index: ChatIndex, scope: ChatAuthorityScope): string[] {return [...new Set((index.deletedChatTombstones ?? [])- .filter(tombstone => sameAuthorityScope(tombstone.authorityScope, scope))+ .filter(tombstone => sameChatDeletionIdentity(tombstone.authorityScope, scope)).map(tombstone => tombstone.chatId)),]@@ -232,6 +284,7 @@ export function useChatListController({host,isHostAccessBlocked,getHostAuthorityEpoch,+ hostAuthorityRevision,onHostAccessRevoked,onHostAuthorityUncertain,}: UseChatListControllerParams) {@@ -322,11 +375,15 @@ export function useChatListController({deletedChatIdsByAgentRef.current.clear()catalogOfflineByAgentRef.current.clear()catalogOfflineToastShownRef.current = false- if (catalogOfflineToastTimerRef.current !== null) {- clearTimeout(catalogOfflineToastTimerRef.current)- catalogOfflineToastTimerRef.current = null+ // A toast queued for this scope must never flush into the next scope or+ // after unmount: the cleanup runs on both.+ return () => {+ if (catalogOfflineToastTimerRef.current !== null) {+ clearTimeout(catalogOfflineToastTimerRef.current)+ catalogOfflineToastTimerRef.current = null+ }+ catalogOfflineToastQueuedRef.current = false}- catalogOfflineToastQueuedRef.current = false}, [isAuthenticated, scopeKey])// R1-H1 — the pending-rename queue is per-USER identity. mcp-host keys a chat@@ -352,21 +409,23 @@ export function useChatListController({}if (catalogOfflineToastShownRef.current || catalogOfflineToastQueuedRef.current) returncatalogOfflineToastQueuedRef.current = true+ const authorityScopeGeneration = authorityScopeGenerationRef.currentcatalogOfflineToastTimerRef.current = setTimeout(() => {catalogOfflineToastTimerRef.current = nullcatalogOfflineToastQueuedRef.current = false+ if (authorityScopeGenerationRef.current !== authorityScopeGeneration) returnconst affectedAgents = [...catalogOfflineByAgentRef.current]- if (!affectedAgents.length || catalogOfflineToastShownRef.current) return+ const currentHost = host.current+ if (!currentHost || !affectedAgents.length) returncatalogOfflineToastShownRef.current = true- const scope =- affectedAgents.length === 1- ? `for ${affectedAgents[0]}`- : `for ${affectedAgents.join(', ')}`- host.current?.pushToast(`Chat list ${scope} is offline. Showing saved chats.`, 'info')+ const names = affectedAgents.map(ref => currentHost.agentDisplayName(ref)).join(', ')+ currentHost.pushToast(`Chat list for ${names} is offline. Showing saved chats.`, 'info')}, 0)}- const reportCatalogOnline = (agentRef: string) => {+ /** A success from an earlier authority scope says nothing about this one. */+ const reportCatalogOnline = (agentRef: string, authorityScopeGeneration: number) => {+ if (authorityScopeGenerationRef.current !== authorityScopeGeneration) returncatalogOfflineByAgentRef.current.delete(agentRef)if (catalogOfflineByAgentRef.current.size === 0) {catalogOfflineToastShownRef.current = false@@ -493,7 +552,7 @@ export function useChatListController({}return}- reportCatalogOnline(agentRef)+ reportCatalogOnline(agentRef, authorityScopeGeneration)if (selectedAgentRef.current !== agentRef ||requestGenerationRef.current !== requestGeneration ||@@ -539,44 +598,13 @@ export function useChatListController({const dedupedPrevious = dedupeSidebarChats(previous).filter(chat => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id))- const serverById = new Map(visibleSessions.map(s => [s.chatId, s]))- const knownIds = new Set(dedupedPrevious.map(c => c.id))- // Cases C/D/E/F (§2.2): the server is authoritative for a cached chat's- // title when it reports one AND no local rename is pending; a pending- // rename (in-flight / offline) keeps the local title until it lands.- const reconciled = dedupedPrevious.map(chat => {- const server = serverById.get(chat.id)- if (!server) return chat- const { title } = resolveSessionTitle({- inCache: true,- localTitle: chat.title,- serverTitle: server.title,- pendingRename: pendingRenameStateFor(agentRef, chat.id),- placeholder: agentChatPlaceholder(chat.id),- })- return title === chat.title ? chat : { ...chat, title }- })- // Cases A/B (§2.2): a server-only chat shows the server title when the- // host reports one, else the "Chat <id>" placeholder.- const fromServerOnly: SidebarChatEntry[] = visibleSessions- .filter(s => !knownIds.has(s.chatId))- .map(s => ({- id: s.chatId,- title: resolveSessionTitle({- inCache: false,- serverTitle: s.title,- pendingRename: pendingRenameStateFor(agentRef, s.chatId),- placeholder: agentChatPlaceholder(s.chatId),- }).title,- createdAt: s.lastActivityAt,- updatedAt: s.lastActivityAt,- // Older hosts omit messageCount. Keep that unknown value at zero- // instead of fabricating two messages per turn and overstating- // Activity totals when tool/system messages vary by session.- messageCount: knownServerMessageCount(s),- remote: true,- }))- return [...reconciled, ...fromServerOnly].sort(byUpdatedDesc)+ // §2.2 precedence (cases A-F) lives in `mergeCatalogPage`.+ return mergeSelectedAgentCatalogPage(+ dedupedPrevious,+ visibleSessions,+ agentRef,+ pendingRenameStateFor+ )})// §2.5: a rename that 404'd (session not yet server-side) retries now that@@ -667,6 +695,11 @@ export function useChatListController({{ force: true })} catch (error) {+ // The sidebar's "Load more" state belongs to whichever agent is selected+ // now; a late rejection for another agent may only touch its own cursor.+ const stillShowingRequest = () =>+ selectedAgentRef.current === agentRef &&+ requestGenerationRef.current === requestGenerationif (authorityScopeGenerationRef.current === authorityScopeGeneration &&getHostAuthorityEpoch(agentRef) === hostAuthorityEpoch &&@@ -675,15 +708,18 @@ export function useChatListController({) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)else if (isAuthorizationError(error)) onHostAuthorityUncertain(agentRef)- else if (isRecoverableCatalogCursorError(error)) {+ else if (isTerminalCatalogCursorError(error)) {chatListNextCursorByAgentRef.current[agentRef] = null- setChatListHasMoreRemoteSessions(false)- } else if (- !isConfirmedHostAccessRevoked(error) &&- !isAuthorizationError(error) &&- isCatalogOutageError(error)- ) {- reportCatalogOffline(agentRef)+ if (stillShowingRequest()) setChatListHasMoreRemoteSessions(false)+ } else if (stillShowingRequest() && host.current) {+ // 429, 5xx, a waking Host or a transport failure: the cursor stays+ // valid and the user retries with the same button. No automatic+ // retry is scheduled.+ const currentHost = host.current+ currentHost.pushToast(+ `Couldn't load more chats for ${currentHost.agentDisplayName(agentRef)}. Try again shortly.`,+ 'info'+ )}return}@@ -693,7 +729,7 @@ export function useChatListController({currentAuthorityScopeRef.current === authorityScopeAtRequest &&selectedAgentRef.current === agentRef) {- if (isRecoverableCatalogCursorError(error)) {+ if (isTerminalCatalogCursorError(error)) {chatListNextCursorByAgentRef.current[agentRef] = nullsetChatListHasMoreRemoteSessions(false)} else {@@ -702,7 +738,7 @@ export function useChatListController({}return}- reportCatalogOnline(agentRef)+ reportCatalogOnline(agentRef, authorityScopeGeneration)if (requestGenerationRef.current !== requestGeneration ||getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||@@ -734,39 +770,13 @@ export function useChatListController({const dedupedPrevious = dedupeSidebarChats(previous).filter(chat => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id))- const serverById = new Map(visibleSessions.map(s => [s.chatId, s]))- const knownIds = new Set(dedupedPrevious.map(c => c.id))- // Cases C/D/E/F (§2.2): reconcile the title of any cached chat this page- // also reports; server wins when it has a title and no rename is pending.- const reconciled = dedupedPrevious.map(chat => {- const server = serverById.get(chat.id)- if (!server) return chat- const { title } = resolveSessionTitle({- inCache: true,- localTitle: chat.title,- serverTitle: server.title,- pendingRename: pendingRenameStateFor(agentRef, chat.id),- placeholder: agentChatPlaceholder(chat.id),- })- return title === chat.title ? chat : { ...chat, title }- })- // Cases A/B (§2.2): server-only page entries.- const fromServerOnly: SidebarChatEntry[] = visibleSessions- .filter(s => !knownIds.has(s.chatId))- .map(s => ({- id: s.chatId,- title: resolveSessionTitle({- inCache: false,- serverTitle: s.title,- pendingRename: pendingRenameStateFor(agentRef, s.chatId),- placeholder: agentChatPlaceholder(s.chatId),- }).title,- createdAt: s.lastActivityAt,- updatedAt: s.lastActivityAt,- messageCount: knownServerMessageCount(s),- remote: true,- }))- return [...reconciled, ...fromServerOnly].sort(byUpdatedDesc)+ // §2.2 precedence (cases A-F) lives in `mergeCatalogPage`.+ return mergeSelectedAgentCatalogPage(+ dedupedPrevious,+ visibleSessions,+ agentRef,+ pendingRenameStateFor+ )})try {@@ -1433,6 +1443,21 @@ export function useChatListController({[handleDeleteChatForAgent])+ // A hold is enforced synchronously (the published list below filters held+ // Hosts, and every in-flight read compares its Host's epoch), so holding a+ // Host needs no reload. Releasing one does: its sessions were dropped while+ // it was held, so the cross-agent list reloads when a held Host comes back.+ const [latestReloadRevision, setLatestReloadRevision] = useState(0)+ const heldAgentsRef = useRef(new Set<string>())+ useEffect(() => {+ const held = new Set(agentNamesRef.current.filter(agentRef => isHostAccessBlocked(agentRef)))+ const released = [...heldAgentsRef.current].some(+ agentRef => !held.has(agentRef) && agentNamesRef.current.includes(agentRef)+ )+ heldAgentsRef.current = held+ if (released) setLatestReloadRevision(revision => revision + 1)+ }, [agentNamesKey, hostAuthorityRevision, isHostAccessBlocked])+// ─── Cross-agent latest-sessions loader (seeds badges via SERVER_SNAPSHOT) ───useEffect(() => {@@ -1540,14 +1565,16 @@ export function useChatListController({}return { agentRef, sessions: [] as SessionsListResult['items'] }}- reportCatalogOnline(agentRef)if (+ cancelled ||+ authorityScopeGenerationRef.current !== authorityScopeGeneration ||currentAuthorityScopeRef.current !== authorityScopeAtRequest ||getHostAuthorityEpoch(agentRef) !== hostAuthorityEpochByAgent.get(agentRef) ||isHostAccessBlocked(agentRef)) {return { agentRef, sessions: [] as SessionsListResult['items'] }}+ reportCatalogOnline(agentRef, authorityScopeGeneration)return {agentRef,sessions: serverResult.items.filter(@@ -1576,44 +1603,7 @@ export function useChatListController({)}setLatestChatSessions(previous => {- const serverByKey = new Map<string, SessionsListResult['items'][number]>()- for (const group of sessionGroups) {- if (- getHostAuthorityEpoch(group.agentRef) !==- hostAuthorityEpochByAgent.get(group.agentRef) ||- isHostAccessBlocked(group.agentRef)- )- continue- for (const session of group.sessions) {- if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))- continue- serverByKey.set(`${group.agentRef}:${session.chatId}`, session)- }- }- // Cases C/D/E/F (§2.2): server-authoritative title for cached entries,- // unless a local rename is pending for that (agentRef, chatId).- const reconciled = previous- .filter(- item =>- getHostAuthorityEpoch(item.agentRef) ===- hostAuthorityEpochByAgent.get(item.agentRef) &&- !isHostAccessBlocked(item.agentRef) &&- !deletedChatIdsByAgentRef.current.get(item.agentRef)?.has(item.id)- )- .map(item => {- const server = serverByKey.get(`${item.agentRef}:${item.id}`)- if (!server) return item- const { title } = resolveSessionTitle({- inCache: true,- localTitle: item.title,- serverTitle: server.title,- pendingRename: pendingRenameStateFor(item.agentRef, item.id),- placeholder: remotePlaceholder(item.id),- })- return title === item.title ? item : { ...item, title }- })- const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))- const remoteOnly: LatestSidebarChatEntry[] = []+ const sessions: LatestCatalogSession[] = []for (const group of sessionGroups) {if (getHostAuthorityEpoch(group.agentRef) !==@@ -1624,27 +1614,37 @@ export function useChatListController({for (const session of group.sessions) {if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))continue- const key = `${group.agentRef}:${session.chatId}`- if (knownKeys.has(key)) continue- knownKeys.add(key)- // Cases A/B (§2.2): server title, else "Remote · <id>" placeholder.- remoteOnly.push({- id: session.chatId,- title: resolveSessionTitle({- inCache: false,- serverTitle: session.title,- pendingRename: pendingRenameStateFor(group.agentRef, session.chatId),- placeholder: remotePlaceholder(session.chatId),- }).title,- createdAt: session.lastActivityAt,- updatedAt: session.lastActivityAt,- messageCount: knownServerMessageCount(session),- remote: true,- agentRef: group.agentRef,- })+ sessions.push({ ...session, agentRef: group.agentRef })}}- return [...reconciled, ...remoteOnly].sort(byUpdatedDesc)+ const cached = previous.filter(+ item =>+ getHostAuthorityEpoch(item.agentRef) ===+ hostAuthorityEpochByAgent.get(item.agentRef) &&+ !isHostAccessBlocked(item.agentRef) &&+ !deletedChatIdsByAgentRef.current.get(item.agentRef)?.has(item.id)+ )+ // §2.2 precedence (cases A-F) lives in `mergeCatalogPage`; Latest keys+ // entries by (agentRef, chatId) and uses the "Remote · <id>" placeholder.+ return mergeCatalogPage<LatestSidebarChatEntry, LatestCatalogSession>({+ cached,+ sessions,+ entryKey: item => `${item.agentRef}:${item.id}`,+ sessionKey: session => `${session.agentRef}:${session.chatId}`,+ entryPendingRename: item => pendingRenameStateFor(item.agentRef, item.id),+ sessionPendingRename: session =>+ pendingRenameStateFor(session.agentRef, session.chatId),+ placeholderFor: remotePlaceholder,+ serverOnlyEntry: (session, title) => ({+ id: session.chatId,+ title,+ createdAt: session.lastActivityAt,+ updatedAt: session.lastActivityAt,+ messageCount: knownServerMessageCount(session),+ remote: true,+ agentRef: session.agentRef,+ }),+ })})// §2.5: retry any rename that 404'd, now that this cross-agent poll@@ -1684,17 +1684,26 @@ export function useChatListController({getHostAuthorityEpoch,isHostAccessBlocked,onHostAccessRevoked,+ latestReloadRevision,])+ // Stable across renders whose inputs did not change, so consumers keyed on the+ // list identity do not recompute on every parent render (R1-M10).+ const visibleLatestChatSessions = useMemo(+ () => latestChatSessions.filter(session => !isHostAccessBlocked(session.agentRef)),+ // `isHostAccessBlocked` reads mutable authority state; the revision is what+ // changes when its answers do.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [latestChatSessions, isHostAccessBlocked, hostAuthorityRevision]+ )+return {// State (public contract, re-exported unchanged by the parent).chatList: selectedAgent && isHostAccessBlocked(selectedAgent) ? [] : chatList,chatListLoading,chatListMoreLoading,chatListHasMoreRemoteSessions,- latestChatSessions: latestChatSessions.filter(- session => !isHostAccessBlocked(session.agentRef)- ),+ latestChatSessions: visibleLatestChatSessions,latestChatSessionsLoading,hideAgent,// CRUD (public contract).diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex b313f8a70..d00ec2320 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -11,6 +11,11 @@ import type {import { AGENT_WORKSPACE_ROUTES, DESKTOP_ROUTES } from '../constants/navigation'import { pickLatestAgent } from '../lib/agents'import { toPrettyJson } from '../lib/format'+import {+ type HostAuthorityHoldKind,+ type HostAuthorityStore,+ createHostAuthorityStore,+} from '../lib/hostAuthorityStore'import { selectUnauthenticatedView } from '../lib/unauthenticatedView'import { summarizeWorkflowResource } from '../lib/workflows'import type {@@ -71,13 +76,6 @@ const DENY_REASON_BY_SOURCE: Record<ApprovalDecisionTarget['source'], string> =connect_completed: 'User denied',}-export function getHostAuthorityEpochForAgent(- epochByAgent: ReadonlyMap<string, number>,- agentRef: string-): number {- return epochByAgent.get(agentRef) ?? 0-}-export async function loadWorkflowRunsWithArtifactsForWorkflowTarget(target: Pick<WorkflowCompletionNotificationTarget, 'namespace' | 'name'>): Promise<WorkflowRunsResult> {@@ -219,7 +217,12 @@ export function useAppController() {// here (see refreshAuthenticatedData / handleLogout / switchTeamForWorkspace).const connectorsData = useConnectorsController()const teamsData = useTeamsDataController()- const currentTeamId = auth.me?.teamId || teamsData.currentTeamId || ''+ // The authenticated principal's own team: the ONE place `me.teamId` is read.+ // The chat-list cache scope (`currentTeamId`) may fall back to the display+ // directory when it is empty; the delete fence (`chatAuthorityTeamId`) never+ // does, because a directory team was never proven to be the session's.+ const principalTeamId = auth.me?.teamId ?? ''+ const currentTeamId = principalTeamId || teamsData.currentTeamId || ''const availableTeamIds = useMemo(() => teamsData.teams.map(team => team.id), [teamsData.teams])const authenticatedPrincipalIdentity =auth.isAuthenticated && auth.me@@ -316,44 +319,34 @@ export function useAppController() {const authorityScope = `${auth.runtimeConfigState?.envKey ?? ''}:${auth.isAuthenticated}:${authenticatedPrincipalIdentity ?? ''}:${currentTeamId}`const authorityScopeRef = useRef(authorityScope)authorityScopeRef.current = authorityScope- const hostAuthorityEpochRef = useRef(0)- const hostAuthorityEpochByAgentRef = useRef(new Map<string, number>())const navigationIntentEpochRef = useRef(0)- const blockedHostsRef = useRef(- new Map<string, { kind: 'revoked' | 'uncertain'; epoch: number }>()- )+ // Lazy-init: the factory must run once per mount, like the FSM store.+ const hostAuthorityRef = useRef<HostAuthorityStore | null>(null)+ if (!hostAuthorityRef.current) hostAuthorityRef.current = createHostAuthorityStore()+ const hostAuthority = hostAuthorityRef.currentconst [hostAuthorityRevision, setHostAuthorityRevision] = useState(0)const selectedAgentRef = useRef(nav.selectedAgent)selectedAgentRef.current = nav.selectedAgentconst isHostAccessBlocked = useCallback(- (agentRef: string) => blockedHostsRef.current.has(agentRef),- []+ (agentRef: string) => hostAuthority.isBlocked(agentRef),+ [hostAuthority])const getHostAuthorityEpoch = useCallback(- (agentRef: string) =>- getHostAuthorityEpochForAgent(hostAuthorityEpochByAgentRef.current, agentRef),- []+ (agentRef: string) => hostAuthority.getEpoch(agentRef),+ [hostAuthority])useEffect(() => {- blockedHostsRef.current.clear()- hostAuthorityEpochRef.current += 1- hostAuthorityEpochByAgentRef.current.clear()+ hostAuthority.reset()setHostAuthorityRevision(revision => revision + 1)- }, [authorityScope])+ }, [authorityScope, hostAuthority])const blockHostAccess = useCallback(- (agentRef: string, kind: 'revoked' | 'uncertain') => {- const existing = blockedHostsRef.current.get(agentRef)- if (existing?.kind === 'revoked' && kind === 'uncertain') return- blockedHostsRef.current.set(agentRef, {- kind,- epoch: ++hostAuthorityEpochRef.current,- })- hostAuthorityEpochByAgentRef.current.set(agentRef, hostAuthorityEpochRef.current)+ (agentRef: string, kind: HostAuthorityHoldKind) => {+ if (!hostAuthority.hold(agentRef, kind)) returnsetHostAuthorityRevision(revision => revision + 1)if (selectedAgentRef.current === agentRef) nav.setSelectedAgent(null)void agentsData.refresh()},- [agentsData.refresh, nav.setSelectedAgent]+ [agentsData.refresh, hostAuthority, nav.setSelectedAgent])const onHostAccessRevoked = useCallback((agentRef: string) => blockHostAccess(agentRef, 'revoked'),@@ -363,26 +356,23 @@ export function useAppController() {(agentRef: string) => blockHostAccess(agentRef, 'uncertain'),[blockHostAccess])- const verifyHostAccess = useCallback(async (agentRef: string): Promise<boolean> => {- const blocked = blockedHostsRef.current.get(agentRef)- if (!blocked) return true- const scope = authorityScopeRef.current- const epoch = blocked.epoch- try {- await window.clerum.rpc.listSessions(agentRef, undefined, { agent: agentRef, limit: 1 })- } catch {- return false- }- if (- authorityScopeRef.current !== scope ||- blockedHostsRef.current.get(agentRef)?.epoch !== epoch- )- return false- blockedHostsRef.current.delete(agentRef)- hostAuthorityEpochByAgentRef.current.set(agentRef, ++hostAuthorityEpochRef.current)- setHostAuthorityRevision(revision => revision + 1)- return true- }, [])+ const verifyHostAccess = useCallback(+ async (agentRef: string): Promise<boolean> => {+ const heldAtEpoch = hostAuthority.heldAtEpoch(agentRef)+ if (heldAtEpoch === undefined) return true+ const scope = authorityScopeRef.current+ try {+ await window.clerum.rpc.listSessions(agentRef, undefined, { agent: agentRef, limit: 1 })+ } catch {+ return false+ }+ if (authorityScopeRef.current !== scope || !hostAuthority.release(agentRef, heldAtEpoch))+ return false+ setHostAuthorityRevision(revision => revision + 1)+ return true+ },+ [hostAuthority]+ )const chat = useAgentChatController({selectedAgent: nav.selectedAgent,agentNames: agentsData.agentNames,@@ -404,6 +394,8 @@ export function useAppController() {onHostAuthorityUncertain,isHostAccessBlocked,getHostAuthorityEpoch,+ hostAuthorityRevision,+ chatAuthorityTeamId: principalTeamId,})// §4.7.4: the ONE central approval-decision function, bound to the chatdiff --git a/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts b/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.tsnew file mode 100644index 000000000..0faa9f704--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts@@ -0,0 +1,187 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import { byUpdatedDesc, mergeCatalogPage } from '../catalogMerge'+import type { PendingRename } from '../resolveSessionTitle'++/**+ * R1-M9 — property suite for the single sidebar/catalog merge precedence rule+ * (spec 15 §2.2). The expected titles are written out from the case table, not+ * computed by calling `resolveSessionTitle`, so a regression in either the+ * merge or the resolver fails here.+ */++interface Entry {+ id: string+ title: string+ updatedAt: string+ /** A field the merge must never touch. */+ messageCount: number+}++interface Session {+ chatId: string+ title?: string+ lastActivityAt: string+}++const CHAT_IDS = ['a', 'b', 'c', 'd', 'e', 'f'] as const+const PENDING: PendingRename[] = ['none', 'in-flight', 'offline']++const placeholderFor = (chatId: string) => `Chat ${chatId}`++const timestampArb = fc.oneof(+ fc+ .integer({ min: Date.UTC(2020, 0, 1), max: Date.UTC(2030, 0, 1) })+ .map(ms => new Date(ms).toISOString()),+ fc.constant('not-a-date')+)+const titleArb = fc.constantFrom('', 'Local plan', 'Server plan', 'Renamed')++const entriesArb = fc.uniqueArray(+ fc.record({+ id: fc.constantFrom(...CHAT_IDS),+ title: titleArb,+ updatedAt: timestampArb,+ messageCount: fc.nat({ max: 50 }),+ }),+ { selector: entry => entry.id, maxLength: CHAT_IDS.length }+)+const sessionsArb = fc.array(+ fc.record(+ {+ chatId: fc.constantFrom(...CHAT_IDS),+ title: titleArb,+ lastActivityAt: timestampArb,+ },+ { requiredKeys: ['chatId', 'lastActivityAt'] }+ ),+ { maxLength: 10 }+)+const pendingArb = fc.dictionary(fc.constantFrom(...CHAT_IDS), fc.constantFrom(...PENDING))++function merge(cached: Entry[], sessions: Session[], pending: Record<string, PendingRename>) {+ const pendingFor = (chatId: string): PendingRename => pending[chatId] ?? 'none'+ return mergeCatalogPage<Entry, Session>({+ cached,+ sessions,+ entryKey: entry => entry.id,+ sessionKey: session => session.chatId,+ entryPendingRename: entry => pendingFor(entry.id),+ sessionPendingRename: session => pendingFor(session.chatId),+ placeholderFor,+ serverOnlyEntry: (session, title) => ({+ id: session.chatId,+ title,+ updatedAt: session.lastActivityAt,+ messageCount: 0,+ }),+ })+}++/** §2.2 cases C/D/E/F for a cached entry the page also reports. */+function expectedCachedTitle(local: string, server: string | undefined, pending: PendingRename) {+ if (pending !== 'none' && local !== '') return local // E/F+ if (server) return server // C+ if (local !== '') return local // D+ return 'placeholder'+}++/** §2.2 cases A/B for a session the cache does not hold. */+function expectedServerOnlyTitle(server: string | undefined, chatId: string) {+ return server ? server : placeholderFor(chatId)+}++const firstReport = (sessions: Session[], chatId: string) =>+ sessions.find(session => session.chatId === chatId)++describe('mergeCatalogPage', () => {+ it('holds every cached entry and every reported chat exactly once', () => {+ fc.assert(+ fc.property(entriesArb, sessionsArb, pendingArb, (cached, sessions, pending) => {+ const ids = merge(cached, sessions, pending).map(entry => entry.id)+ const expected = new Set([+ ...cached.map(entry => entry.id),+ ...sessions.map(session => session.chatId),+ ])+ expect(ids).toHaveLength(expected.size)+ expect(new Set(ids)).toEqual(expected)+ })+ )+ })++ it('titles a cached entry by the §2.2 precedence and leaves its other fields alone', () => {+ fc.assert(+ fc.property(entriesArb, sessionsArb, pendingArb, (cached, sessions, pending) => {+ const merged = merge(cached, sessions, pending)+ for (const entry of cached) {+ const out = merged.find(candidate => candidate.id === entry.id)+ const session = firstReport(sessions, entry.id)+ if (!session) {+ expect(out).toBe(entry)+ continue+ }+ const expected = expectedCachedTitle(+ entry.title,+ session.title,+ pending[entry.id] ?? 'none'+ )+ expect(out).toEqual({+ ...entry,+ title: expected === 'placeholder' ? placeholderFor(entry.id) : expected,+ })+ if (out?.title === entry.title) expect(out).toBe(entry)+ }+ })+ )+ })++ it('builds one server-only entry from the first report of each new chat', () => {+ fc.assert(+ fc.property(entriesArb, sessionsArb, pendingArb, (cached, sessions, pending) => {+ const merged = merge(cached, sessions, pending)+ const cachedIds = new Set(cached.map(entry => entry.id))+ for (const chatId of new Set(sessions.map(session => session.chatId))) {+ if (cachedIds.has(chatId)) continue+ const first = firstReport(sessions, chatId) as Session+ expect(merged.find(entry => entry.id === chatId)).toEqual({+ id: chatId,+ title: expectedServerOnlyTitle(first.title, chatId),+ updatedAt: first.lastActivityAt,+ messageCount: 0,+ })+ }+ })+ )+ })++ it('orders the result newest first', () => {+ fc.assert(+ fc.property(entriesArb, sessionsArb, pendingArb, (cached, sessions, pending) => {+ const merged = merge(cached, sessions, pending)+ for (let i = 1; i < merged.length; i += 1) {+ expect(byUpdatedDesc(merged[i - 1] as Entry, merged[i] as Entry)).toBeLessThanOrEqual(0)+ }+ })+ )+ })++ it('is idempotent: merging the same page again changes nothing', () => {+ fc.assert(+ fc.property(entriesArb, sessionsArb, pendingArb, (cached, sessions, pending) => {+ const once = merge(cached, sessions, pending)+ expect(merge(once, sessions, pending)).toEqual(once)+ })+ )+ })++ it('keeps a pending local rename over a server title (case E)', () => {+ const cached: Entry[] = [+ { id: 'a', title: 'Renamed', updatedAt: '2026-09-12T00:00:00.000Z', messageCount: 3 },+ ]+ const sessions: Session[] = [+ { chatId: 'a', title: 'Server plan', lastActivityAt: '2026-09-13T00:00:00.000Z' },+ ]+ expect(merge(cached, sessions, { a: 'in-flight' })[0]?.title).toBe('Renamed')+ expect(merge(cached, sessions, {})[0]?.title).toBe('Server plan')+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/classifyErrorKind.test.ts b/desktop-app/ui/src/lib/__tests__/classifyErrorKind.test.tsindex e128b53ef..5a643c3bd 100644--- a/desktop-app/ui/src/lib/__tests__/classifyErrorKind.test.ts+++ b/desktop-app/ui/src/lib/__tests__/classifyErrorKind.test.ts@@ -5,7 +5,7 @@ describe('classifyErrorKind — host availability codes', () => {it('classifies host_waking messages as waking, even wrapped by Electron IPC', () => {expect(classifyErrorKind(- 'Error invoking remote method rpc:invokeHostMessage: ' ++ "Error invoking remote method 'rpc:invokeHostMessage': " +'Error: host_waking: agent host "chatllm" is waking up — retry shortly')).toBe('waking')diff --git a/desktop-app/ui/src/lib/__tests__/hostAuthorityStore.test.ts b/desktop-app/ui/src/lib/__tests__/hostAuthorityStore.test.tsnew file mode 100644index 000000000..54fe9fbc3--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/hostAuthorityStore.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest'+import { createHostAuthorityStore } from '../hostAuthorityStore'++describe('createHostAuthorityStore', () => {+ it('keeps Host X authority unchanged when Host Y is held', () => {+ const store = createHostAuthorityStore()+ const hostXEpoch = store.getEpoch('host-x')++ expect(store.hold('host-y', 'revoked')).toBe(true)++ expect(store.getEpoch('host-x')).toBe(hostXEpoch)+ expect(store.getEpoch('host-y')).not.toBe(hostXEpoch)+ expect(store.isBlocked('host-y')).toBe(true)+ expect(store.isBlocked('host-x')).toBe(false)+ })++ it('never downgrades a confirmed revocation to an uncertain hold', () => {+ const store = createHostAuthorityStore()+ store.hold('host-y', 'revoked')+ const heldAt = store.heldAtEpoch('host-y')++ expect(store.hold('host-y', 'uncertain')).toBe(false)+ expect(store.heldAtEpoch('host-y')).toBe(heldAt)+ })++ it('refuses a stale release and moves the epoch on a valid one', () => {+ const store = createHostAuthorityStore()+ store.hold('host-y', 'uncertain')+ const firstHold = store.heldAtEpoch('host-y')+ if (firstHold === undefined) throw new Error('host-y must be held')+ store.hold('host-y', 'revoked')++ expect(store.release('host-y', firstHold)).toBe(false)+ expect(store.isBlocked('host-y')).toBe(true)++ const currentHold = store.heldAtEpoch('host-y')+ if (currentHold === undefined) throw new Error('host-y must still be held')+ const beforeRelease = store.getEpoch('host-y')+ expect(store.release('host-y', currentHold)).toBe(true)+ expect(store.isBlocked('host-y')).toBe(false)+ expect(store.getEpoch('host-y')).not.toBe(beforeRelease)+ })++ it('reset clears every hold and changes the epoch of a previously held Host', () => {+ const store = createHostAuthorityStore()+ store.hold('host-y', 'revoked')+ const heldEpoch = store.getEpoch('host-y')++ store.reset()++ expect(store.isBlocked('host-y')).toBe(false)+ expect(store.getEpoch('host-y')).not.toBe(heldEpoch)+ })+})diff --git a/desktop-app/ui/src/lib/__tests__/httpErrorStatus.test.ts b/desktop-app/ui/src/lib/__tests__/httpErrorStatus.test.tsnew file mode 100644index 000000000..85f61fbc8--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/httpErrorStatus.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import { httpErrorStatus, isAuthorizationError } from '../format'++describe('httpErrorStatus labeled-status boundary (NEW-dui-4)', () => {+ it.each([+ ['request to status401 failed', undefined],+ ['upstream support-http500 refused the call', undefined],+ ['status 503 from upstream', 503],+ ['upstream returned status: 429', 429],+ ['request failed (status=404)', 404],+ ['upstream http status 502', 502],+ ['proxy error, status code 504', 504],+ ])('parses %j as %s', (message, expected) => {+ expect(httpErrorStatus(new Error(message))).toBe(expected)+ })++ it('never reads a status out of a waking or draining Host reference', () => {+ const waking = new Error('host_waking: agent host "status401" is waking up — retry shortly')+ const draining = new Error('host_draining: agent host "status403" is draining — retry shortly')++ expect(httpErrorStatus(waking)).toBeUndefined()+ expect(isAuthorizationError(waking)).toBe(false)+ expect(httpErrorStatus(draining)).toBeUndefined()+ // Liveness witness: the same Host reference outside the availability+ // projection still reaches the parser, which reads the real status.+ expect(httpErrorStatus(new Error('403 Forbidden: agent host "status401"'))).toBe(403)+ })+})++describe('httpErrorStatus bounded parsing (NEW-sec-2)', () => {+ it('finishes a 40k whitespace run after a status label quickly', () => {+ const hostile = new Error(`upstream status${' '.repeat(40_000)}x`)++ const startedAt = performance.now()+ const status = httpErrorStatus(hostile)+ const elapsedMs = performance.now() - startedAt++ expect(status).toBeUndefined()+ expect(elapsedMs).toBeLessThan(200)+ // Liveness witness: an ordinary labeled message still parses.+ expect(httpErrorStatus(new Error('upstream status: 503'))).toBe(503)+ })++ it('reads only the leading 2 KB of a message', () => {+ const padding = 'x'.repeat(3000)++ expect(httpErrorStatus(new Error(`${padding} status 500`))).toBeUndefined()+ // Liveness witness: the same label inside the bound is parsed.+ expect(httpErrorStatus(new Error(`${'x'.repeat(100)} status 500`))).toBe(500)+ })+})diff --git a/desktop-app/ui/src/lib/catalogMerge.ts b/desktop-app/ui/src/lib/catalogMerge.tsnew file mode 100644index 000000000..1061b84bd--- /dev/null+++ b/desktop-app/ui/src/lib/catalogMerge.ts@@ -0,0 +1,97 @@+import { type PendingRename, resolveSessionTitle } from '@lib/resolveSessionTitle'++/**+ * Merge precedence between the sidebar's cached chat entries and one page of the+ * server session catalog (spec 15 §2.2). The same rule set used to be written+ * out three times in `useChatListController` (the selected agent's first page,+ * its load-more pages, and the cross-agent Latest list); this is the single+ * definition.+ *+ * - Every cached entry survives, with every field but `title` untouched. Its+ * title follows `resolveSessionTitle` (cases C/D/E/F): the server title wins+ * when the Host reports one and no local rename is pending; a pending rename+ * keeps the local title. An entry whose title is unchanged keeps its object+ * identity.+ * - A server session with no cached entry becomes one new entry (cases A/B),+ * titled by the server or by the placeholder. A key reported twice by the+ * page yields one entry, and the first report decides it.+ * - The result is ordered by `updatedAt`, newest first; an unparseable+ * timestamp sorts as the epoch.+ *+ * Callers own everything that is not precedence: authority epochs, deletion+ * tombstones and cached-entry de-duplication happen before this runs.+ */++export interface CatalogMergeEntry {+ id: string+ title: string+ updatedAt: string+}++export interface CatalogMergeSession {+ chatId: string+ title?: string+ lastActivityAt: string+}++export interface CatalogMergeInput<E extends CatalogMergeEntry, S extends CatalogMergeSession> {+ cached: readonly E[]+ sessions: readonly S[]+ /** Identity shared by an entry and the session that describes it. */+ entryKey: (entry: E) => string+ sessionKey: (session: S) => string+ entryPendingRename: (entry: E) => PendingRename+ sessionPendingRename: (session: S) => PendingRename+ placeholderFor: (chatId: string) => string+ /** Builds the entry for a server-only session from its resolved title. */+ serverOnlyEntry: (session: S, title: string) => E+}++function sortableTimestamp(value: string): number {+ const timestamp = Date.parse(value)+ return Number.isFinite(timestamp) ? timestamp : 0+}++export function byUpdatedDesc(a: { updatedAt: string }, b: { updatedAt: string }): number {+ return sortableTimestamp(b.updatedAt) - sortableTimestamp(a.updatedAt)+}++export function mergeCatalogPage<E extends CatalogMergeEntry, S extends CatalogMergeSession>(+ input: CatalogMergeInput<E, S>+): E[] {+ const sessionByKey = new Map<string, S>()+ for (const session of input.sessions) {+ const key = input.sessionKey(session)+ if (!sessionByKey.has(key)) sessionByKey.set(key, session)+ }++ const cachedKeys = new Set<string>()+ const reconciled = input.cached.map(entry => {+ const key = input.entryKey(entry)+ cachedKeys.add(key)+ const session = sessionByKey.get(key)+ if (!session) return entry+ const { title } = resolveSessionTitle({+ inCache: true,+ localTitle: entry.title,+ serverTitle: session.title,+ pendingRename: input.entryPendingRename(entry),+ placeholder: input.placeholderFor(entry.id),+ })+ return title === entry.title ? entry : { ...entry, title }+ })++ const serverOnly: E[] = []+ for (const [key, session] of sessionByKey) {+ if (cachedKeys.has(key)) continue+ const { title } = resolveSessionTitle({+ inCache: false,+ serverTitle: session.title,+ pendingRename: input.sessionPendingRename(session),+ placeholder: input.placeholderFor(session.chatId),+ })+ serverOnly.push(input.serverOnlyEntry(session, title))+ }++ return [...reconciled, ...serverOnly].sort(byUpdatedDesc)+}diff --git a/desktop-app/ui/src/lib/format.ts b/desktop-app/ui/src/lib/format.tsindex 8d30ae2fe..cee2abde4 100644--- a/desktop-app/ui/src/lib/format.ts+++ b/desktop-app/ui/src/lib/format.ts@@ -159,6 +159,23 @@ function errorText(err: unknown): string {return (err instanceof Error ? err.message : String(err)).toLowerCase()}+/**+ * Every producer puts the response status in the first few dozen characters+ * (`NNN StatusText: …`, `List sessions failed (NNN): …`). Parsing a bounded+ * prefix keeps the cost of a status read independent of an upstream body that+ * an error message may echo.+ */+const HTTP_STATUS_PARSE_MAX_CHARS = 2048++/**+ * Labeled statuses must be introduced by the start of the text, whitespace or+ * `(`, and separated from the digits by `:`/`=` or whitespace, so a Host named+ * `status401` or `support-http500` never yields a status. Each quantifier is+ * followed by a disjoint token, which keeps a long whitespace run linear.+ */+const HTTP_STATUS_PATTERN =+ /^(?:http\s+)?(?<leading>[1-5]\d{2})\b|(?:^|[\s(])(?:http(?:\s+status)?|status(?:\s+code)?)(?:\s*[:=]\s*|\s+)(?<labeled>[1-5]\d{2})\b|\((?<parenthesized>[1-5]\d{2})\)/i+/** IPC preserves error messages but not always custom status fields. */export function httpErrorStatus(err: unknown): number | undefined {if (err && typeof err === 'object') {@@ -167,16 +184,30 @@ export function httpErrorStatus(err: unknown): number | undefined {const causeStatus = (err as { cause?: { status?: unknown } }).cause?.statusif (typeof causeStatus === 'number') return causeStatus}+ const text = stripIpcWrapper(errorText(err).slice(0, HTTP_STATUS_PARSE_MAX_CHARS))+ // AppService's Host-availability projection carries no status, only the+ // Host reference, whose digits are never a response status.+ if (text.startsWith('host_waking:') || text.startsWith('host_draining:')) return undefined// Parse only labeled HTTP statuses so digits in a host name or body aren't// mistaken for the response status.- const match =- /^(?:http\s+)?(?<leading>[1-5]\d{2})\b|\b(?:http(?:\s+status)?|status(?:\s+code)?)\s*[:=]?\s*(?<labeled>[1-5]\d{2})\b|\((?<parenthesized>[1-5]\d{2})\)/i.exec(- stripIpcWrapper(errorText(err))- )+ const match = HTTP_STATUS_PATTERN.exec(text)const status = match?.groups?.leading ?? match?.groups?.labeled ?? match?.groups?.parenthesizedreturn status ? Number(status) : undefined}+const HOST_AVAILABILITY_BODY_PATTERN = /"code"\s*:\s*"host_(?:waking|draining)"/++/**+ * The Host is waking or draining: an expected transition, not an outage. Invoke+ * failures arrive as AppService's `host_waking:`/`host_draining:` projection;+ * catalog reads arrive as the rpc-proxy 503 whose body carries the same code.+ */+export function isHostAvailabilityError(err: unknown): boolean {+ const text = stripIpcWrapper(errorText(err).slice(0, HTTP_STATUS_PARSE_MAX_CHARS))+ if (text.startsWith('host_waking:') || text.startsWith('host_draining:')) return true+ return httpErrorStatus(err) === 503 && HOST_AVAILABILITY_BODY_PATTERN.test(text)+}+/** True when the parsed response status is in the server-error range. */export function isHttpServerError(err: unknown): boolean {const status = httpErrorStatus(err)diff --git a/desktop-app/ui/src/lib/gfsGrantErrors.ts b/desktop-app/ui/src/lib/gfsGrantErrors.tsindex 5f7ea6032..ff602a9e1 100644--- a/desktop-app/ui/src/lib/gfsGrantErrors.ts+++ b/desktop-app/ui/src/lib/gfsGrantErrors.ts@@ -36,8 +36,13 @@ const GFS_GRANT_ERROR_MESSAGES: Record<string, string> = {* is an implementation detail of our own main/renderer split; the server* verdict that follows it is the part a user can act on. This strips exactly* the wrapper and leaves the verdict intact.+ *+ * The quoted channel is mandatory: Electron's renderer always formats the+ * rejection as `Error invoking remote method '${channel}': ${error}`, so a+ * prefix without it is not an IPC wrapper and must stay visible to the+ * classifiers rather than be treated as one.*/-const IPC_WRAPPER_PREFIX = /^Error invoking remote method(?: '[^']*')?:\s*(?:[A-Za-z]*Error:\s*)?/i+const IPC_WRAPPER_PREFIX = /^Error invoking remote method '[^']*':\s*(?:[A-Za-z]*Error:\s*)?/iexport function stripIpcWrapper(message: string): string {return message.replace(IPC_WRAPPER_PREFIX, '')diff --git a/desktop-app/ui/src/lib/hostAuthorityStore.ts b/desktop-app/ui/src/lib/hostAuthorityStore.tsnew file mode 100644index 000000000..45d9aef03--- /dev/null+++ b/desktop-app/ui/src/lib/hostAuthorityStore.ts@@ -0,0 +1,67 @@+/**+ * Per-Host authority state for the renderer: which Hosts are held after an+ * authorization failure, and an epoch per Host that changes whenever that+ * Host's authority changes.+ *+ * Catalog and transcript reads snapshot `getEpoch(agentRef)` before an await+ * and discard the result when it moved. The epoch is per Host on purpose: a+ * revocation of Host Y must never invalidate an in-flight read of Host X, so+ * an agent that never changed authority reads as epoch 0, never as a global+ * counter.+ *+ * `useAppController` owns the production instance; the controller test+ * harnesses build theirs from this same factory so the epoch path under test+ * is the production one.+ */++export type HostAuthorityHoldKind = 'revoked' | 'uncertain'++export interface HostAuthorityStore {+ isBlocked: (agentRef: string) => boolean+ getEpoch: (agentRef: string) => number+ /** The epoch at which the Host was held, or undefined when it is not held. */+ heldAtEpoch: (agentRef: string) => number | undefined+ /**+ * Hold the Host. Returns false when nothing changed: a confirmed revocation+ * is never downgraded to an uncertain hold.+ */+ hold: (agentRef: string, kind: HostAuthorityHoldKind) => boolean+ /**+ * Release a hold after a successful verification. Returns false when the+ * hold changed since `heldAtEpoch` was read (the verification is stale).+ */+ release: (agentRef: string, heldAtEpoch: number) => boolean+ /** Forget every hold and epoch (a new authority scope). */+ reset: () => void+}++export function createHostAuthorityStore(): HostAuthorityStore {+ let epoch = 0+ const epochByAgent = new Map<string, number>()+ const holds = new Map<string, { kind: HostAuthorityHoldKind; epoch: number }>()++ return {+ isBlocked: agentRef => holds.has(agentRef),+ getEpoch: agentRef => epochByAgent.get(agentRef) ?? 0,+ heldAtEpoch: agentRef => holds.get(agentRef)?.epoch,+ hold: (agentRef, kind) => {+ if (holds.get(agentRef)?.kind === 'revoked' && kind === 'uncertain') return false+ epoch += 1+ holds.set(agentRef, { kind, epoch })+ epochByAgent.set(agentRef, epoch)+ return true+ },+ release: (agentRef, heldAtEpoch) => {+ if (holds.get(agentRef)?.epoch !== heldAtEpoch) return false+ holds.delete(agentRef)+ epoch += 1+ epochByAgent.set(agentRef, epoch)+ return true+ },+ reset: () => {+ holds.clear()+ epoch += 1+ epochByAgent.clear()+ },+ }+}