Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(stateless): contain watch loss and preserve desktop chats
Alfredo Lopezc4b7f0917189
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 7c78ed7a0..5d6875a2b 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -178,6 +178,51 @@ describe('renameChat', () => {// ── deleteChat ───────────────────────────────────────────────────────────────describe('deleteChat', () => {+ it('persists a confirmed deletion across a new store instance', async () => {+ await store.createChat('agent-1', 'deleted-session')+ await store.createChat('agent-1', 'kept-session')+ await store.deleteChat('agent-1', 'deleted-session')++ const restartedStore = new ChatStore(tempDir)+ expect((await restartedStore.listChats('agent-1')).map(chat => chat.id)).toEqual([+ 'kept-session',+ ])+ expect((await restartedStore.getIndex('agent-1')).deletedChatIds).toContain('deleted-session')+ })++ it('does not recreate a deleted transcript from queued or restarted writes', async () => {+ const agentRef = 'agent-1'+ const chatId = 'deleted-while-sending'+ const message: ChatMessage = {+ id: 'late-message',+ role: 'user',+ content: 'arrived after delete',+ timestamp: 1,+ }+ await store.createChat(agentRef, chatId)+ await store.saveMessages(agentRef, chatId, [+ { id: 'original', role: 'user', content: 'original', timestamp: 0 },+ ])++ // Invocation order is the per-chat serialization order: both writes must+ // observe the tombstone published by the preceding confirmed delete.+ const deletion = store.deleteChat(agentRef, chatId)+ const queuedAppend = store.appendMessages(agentRef, chatId, [message])+ const queuedReplace = store.replaceMessages(agentRef, chatId, [message])+ await Promise.all([deletion, queuedAppend, queuedReplace])++ const restartedStore = new ChatStore(tempDir)+ await restartedStore.appendMessages(agentRef, chatId, [message])+ await restartedStore.replaceMessages(agentRef, chatId, [message])+ await expect(restartedStore.createChat(agentRef, chatId)).rejects.toThrow(+ 'Chat was deleted locally'+ )+ expect(await restartedStore.loadMessages(agentRef, chatId)).toEqual([])+ expect(await restartedStore.listChats(agentRef)).toEqual([])+ expect((await restartedStore.getIndex(agentRef)).deletedChatIds).toContain(chatId)+ await expect(fs.access(chatCacheDir(chatId))).rejects.toThrow()+ })+it('removes from index and deletes message cache', async () => {await store.createChat('agent-1', 'del-1')await store.saveMessages('agent-1', 'del-1', [@@ -1665,12 +1710,14 @@ describe('corrupt/missing files', () => {lastActiveChatId: null,onboardingDismissed: false,chats: [],+ deletedChatIds: [],})await expect(store.getIndex('agent-1')).resolves.toEqual({version: 2,lastActiveChatId: null,onboardingDismissed: false,chats: [],+ deletedChatIds: [],})const quarantinedIndexes = (await fs.readdir(agentPath('.corrupt'))).filter(name =>name.startsWith('index-')diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 83f1860fb..49980d5ea 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -4277,12 +4277,10 @@ export class AppService {try {return await this.rpcClient.listSessions(rpc.token, targetHostRef, query)} catch (error) {- const message = error instanceof Error ? error.message : String(error)- if (message.includes('401') && message.toLowerCase().includes('missing token')) {- console.warn(- '[AppService] Session catalog unavailable because the runtime rejected the session token.'- )- return { items: [] }+ if (AppService.shouldRefreshRpcToken(error)) {+ this.rpcTokenManager.clear()+ const retried = await this.issueRpcTokenForHostRefs(HOST_SESSION_SCOPES, effectiveHostRefs)+ return this.rpcClient.listSessions(retried.token, targetHostRef, query)}throw error}@@ -4310,19 +4308,16 @@ export class AppService {query)} catch (error) {- const message = error instanceof Error ? error.message : String(error)- if (message.includes('401') && message.toLowerCase().includes('missing token')) {- console.warn(- '[AppService] Session messages unavailable because the runtime rejected the session token.'- )- return {+ if (AppService.shouldRefreshRpcToken(error)) {+ this.rpcTokenManager.clear()+ const retried = await this.issueRpcTokenForHostRefs(HOST_SESSION_SCOPES, effectiveHostRefs)+ return this.rpcClient.loadSessionMessages(+ retried.token,+ targetHostRef,agent,chatId,- turns: [],- totalTurns: 0,- hasMoreBefore: false,- hasMoreAfter: false,- }+ query+ )}throw error}diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 563a7842f..58d560118 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -166,7 +166,10 @@ function parseChatIndex(raw: string): ChatIndex {(candidate.version !== 2 && candidate.version !== 3) ||(candidate.lastActiveChatId !== null && typeof candidate.lastActiveChatId !== 'string') ||typeof candidate.onboardingDismissed !== 'boolean' ||- !Array.isArray(candidate.chats)+ !Array.isArray(candidate.chats) ||+ (candidate.deletedChatIds !== undefined &&+ (!Array.isArray(candidate.deletedChatIds) ||+ !candidate.deletedChatIds.every((id: unknown) => typeof id === 'string')))) {throw new Error('Invalid chat index')}@@ -283,6 +286,7 @@ function emptyIndex(): ChatIndex {lastActiveChatId: null,onboardingDismissed: false,chats: [],+ deletedChatIds: [],}}@@ -1520,6 +1524,9 @@ export class ChatStore {const index = await this.getIndex(agentRef)const existing = index.chats.find(c => c.id === chatId)if (existing) return existing+ if (index.deletedChatIds?.includes(chatId)) {+ throw new Error('Chat was deleted locally')+ }const now = new Date().toISOString()const meta: ChatMetadata = {@@ -1551,6 +1558,9 @@ export class ChatStore {await this.serializeIndex(agentRef, async () => {const index = await this.getIndex(agentRef)index.chats = index.chats.filter(c => c.id !== chatId)+ if (!index.deletedChatIds?.includes(chatId)) {+ index.deletedChatIds = [...(index.deletedChatIds ?? []), chatId]+ }if (index.lastActiveChatId === chatId) {index.lastActiveChatId = null}@@ -1639,7 +1649,8 @@ export class ChatStore {options: { preserveExistingTotals?: boolean } = {}): Promise<void> {return this.serializeChat(agentRef, chatId, async () => {- await this.getIndex(agentRef)+ const index = await this.getIndex(agentRef)+ if (index.deletedChatIds?.includes(chatId)) returnconst indexedCount = options.preserveExistingTotals? await this.indexedMessageCount(agentRef, chatId): undefined@@ -1672,7 +1683,8 @@ export class ChatStore {options: ReplaceChatMessagesOptions = {}): Promise<void> {await this.serializeChat(agentRef, chatId, async () => {- await this.getIndex(agentRef)+ const index = await this.getIndex(agentRef)+ if (index.deletedChatIds?.includes(chatId)) returnconst existingMeta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)const existingMessages = existingMeta? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta)@@ -1713,7 +1725,8 @@ export class ChatStore {newMessages: ChatMessage[]): Promise<void> {return this.serializeChat(agentRef, chatId, async () => {- await this.getIndex(agentRef)+ const indexBeforeAppend = await this.getIndex(agentRef)+ if (indexBeforeAppend.deletedChatIds?.includes(chatId)) returnconst existing =(await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??(await this.writePagedChatUnlocked(agentRef, chatId, []))diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 3f7a45e94..5fdcaabe2 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -520,7 +520,16 @@ export class RpcProxyClient {token: rpcAccessToken,body: payload,}- )+ ).catch(error => {+ if (+ error instanceof ApiError &&+ error.status === 403 &&+ errorCodeFromBody(error.bodyText) === 'Forbidden: user cannot access this host'+ ) {+ throw new ApiError('403 Forbidden: host_access_revoked', 403, error.bodyText)+ }+ throw error+ })}async getTaskResult(@@ -1032,8 +1041,8 @@ export class RpcProxyClient {signal: withTimeout(),})if (response.status === 404) {- // Keep the '404' token in the message: the renderer's `isHttp404` matches on- // it to evict a stale local chat.+ // Preserve the status for the renderer. A transcript 404 is ambiguous+ // during Host wake and never confirms that local data may be deleted.throw new ApiError(`Session not found (404)`, 404, '')}if (!response.ok) {@@ -1229,7 +1238,20 @@ export class RpcProxyClient {// Body may echo the invalid title; read it for the ApiError payload but// keep the raw title out of the human-facing message.const body = await readErrorBody(response)- throw new ApiError(`Rename session failed (${response.status})`, response.status, body)+ let hostAccessRevoked = false+ if (response.status === 403) {+ try {+ const parsed = JSON.parse(body) as { error?: unknown }+ hostAccessRevoked = parsed?.error === 'Forbidden: user cannot access this host'+ } catch {+ // A non-JSON or interposed 403 is not an authoritative Host denial.+ }+ }+ throw new ApiError(+ `Rename session failed (${response.status})${hostAccessRevoked ? ': host_access_revoked' : ''}`,+ response.status,+ body+ )}const parsed = (await response.json().catch(() => ({}))) as { title?: unknown }// Re-sanitize the server's echoed title on read (defense in depth, A14 rule).diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 42d99f7cf..21a233b14 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -914,6 +914,8 @@ export interface ChatIndex {lastActiveChatId: string | nullonboardingDismissed: booleanchats: ChatMetadata[]+ /** Optional for older indexes. User-confirmed local deletions stay hidden from remote lists. */+ deletedChatIds?: string[]}/** Server-reported session lifecycle (D.1). `idle` once no task is in flight. */diff --git a/desktop-app/test/rpcProxyClient.test.ts b/desktop-app/test/rpcProxyClient.test.tsindex 5990c4e95..913b9de14 100644--- a/desktop-app/test/rpcProxyClient.test.ts+++ b/desktop-app/test/rpcProxyClient.test.ts@@ -207,6 +207,36 @@ describe('RpcProxyClient — openTaskProgressStream()', () => {})describe('RpcProxyClient — renameSession() (spec 15 Fase B)', () => {+ it.each([+ {+ status: 403,+ body: JSON.stringify({ error: 'Forbidden: user cannot access this host' }),+ marked: true,+ },+ {+ status: 403,+ body: JSON.stringify({ error: 'Forbidden: missing rename scope' }),+ marked: false,+ },+ { status: 403, body: 'Forbidden: user cannot access this host', marked: false },+ {+ status: 503,+ body: JSON.stringify({ error: 'Forbidden: user cannot access this host' }),+ marked: false,+ },+ ])(+ 'marks exact Host-wide denial only for authoritative 403 body ($status, $marked)',+ async ({ status, body, marked }) => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body, { status })))+ const client = new RpcProxyClient()+ const error = await client+ .renameSession('rpc-token', 'chatllm', 'chatllm', 'chat-1', 'name')+ .catch((caught: Error) => caught)+ expect(error).toBeInstanceOf(Error)+ expect((error as Error).message.includes('host_access_revoked')).toBe(marked)+ }+ )+it('PATCHes the name route with the title and returns the (re-sanitized) server title', async () => {const fetchMock = vi.fn()diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex 56ec8e565..b6af0ba5a 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -4,6 +4,9 @@ import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'import { renderHook } from '@testing-library/react'import { useAgentChatController } from '../../useAgentChatController'+const onHostAccessRevoked = () => {}+const isHostAccessRevoked = () => false+type ControllerParams = Parameters<typeof useAgentChatController>[0]export interface RenderControllerResult {@@ -51,6 +54,8 @@ export function renderController(isAuthenticated: true,loadMenuData: true,navItem: 'agents',+ onHostAccessRevoked,+ isHostAccessRevoked,pushToast: spies.pushToast,pushNotification: spies.pushNotification,// Identity resolver by default (no catalog display layer in the harness).diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsxindex 5e824d3de..18e0b3ae0 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx@@ -10,7 +10,8 @@* fixtures are derived from the producer instead of hand-built parsed shapes.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { waitFor } from '@testing-library/react'+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 { renderController } from './__fixtures__/controllerHarness'@@ -46,7 +47,10 @@ function serverSessions(})}-function localIndex(chats: Array<{ id: string; title: string }>): ChatIndex {+function localIndex(+ chats: Array<{ id: string; title: string }>,+ deletedChatIds: string[] = []+): ChatIndex {return {version: 1,lastActiveChatId: null,@@ -58,9 +62,18 @@ function localIndex(chats: Array<{ id: string; title: string }>): ChatIndex {updatedAt: NOW,messageCount: 0,})),+ deletedChatIds,}}+function deferred<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(finish => {+ resolve = finish+ })+ 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 () => {clerum.chat.getIndex.mockResolvedValue(localIndex([]))@@ -166,3 +179,176 @@ describe('cross-agent "Latest sessions" title merge (spec 15 §2.2)', () => {)})})++describe('confirmed deletion catalog protection', () => {+ it('keeps a deleted session out of selected-agent and cross-agent catalogs after reload', async () => {+ clerum.chat.getIndex.mockImplementation(async (agentRef: string) =>+ agentRef === 'agent-y'+ ? localIndex([], ['deleted-y'])+ : localIndex([{ id: 'kept-x', title: 'Kept chat' }], ['deleted-x'])+ )+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>+ agentRef === 'agent-y'+ ? serverSessions([{ agent: 'agent-y', chatId: 'deleted-y' }])+ : serverSessions([+ { agent: 'agent-x', chatId: 'deleted-x' },+ { agent: 'agent-x', chatId: 'kept-x' },+ ])+ )++ const { result } = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x', 'agent-y'],+ })+ await waitFor(() => expect(result.current.chatList.map(chat => chat.id)).toEqual(['kept-x']))+ await waitFor(() => expect(result.current.latestChatSessionsLoading).toBe(false))+ expect(result.current.latestChatSessions.map(session => session.id)).not.toContain('deleted-x')+ expect(result.current.latestChatSessions.map(session => session.id)).not.toContain('deleted-y')+ })+})++describe('revoked host catalog protection', () => {+ it('hides a nonselected host after 403 and blocks direct reselection', async () => {+ const revoked = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>+ agentRef === 'agent-y'+ ? serverSessions([{ agent: 'agent-y', chatId: 'protected-y' }])+ : serverSessions([])+ )+ const controller = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x', 'agent-y'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.some(s => s.id === 'protected-y')).toBe(+ true+ )+ )++ clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ await expect(+ controller.result.current.reconcileChat(makeTaskKey('agent-y', 'protected-y'), {+ reason: 'background_refresh',+ })+ ).resolves.toBe('revoked')+ expect(revoked.has('agent-y')).toBe(true)+ await waitFor(() =>+ expect(controller.result.current.latestChatSessions.some(s => s.id === 'protected-y')).toBe(+ false+ )+ )++ await controller.result.current.switchToChat('agent-y', 'protected-y')+ expect(controller.result.current.activeChatId).toBeNull()+ expect(clerum.chat.loadMessages).not.toHaveBeenCalledWith(+ 'agent-y',+ 'protected-y',+ expect.anything()+ )+ })++ it.each([401, 403])(+ 'hides cached sessions when the catalog explicitly returns %i',+ async status => {+ const revoked = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(+ localIndex([{ id: 'protected-a', title: 'Cached protected chat' }])+ )+ clerum.rpc.listSessions.mockRejectedValue(new Error(`${status} forbidden`))+ const { result } = renderController({+ selectedAgent: null,+ agentNames: ['agent-a'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })++ await waitFor(() => expect(revoked.has('agent-a')).toBe(true))+ expect(result.current.latestChatSessions.some(chat => chat.agentRef === 'agent-a')).toBe(+ false+ )+ }+ )++ it('retains cached sessions when a 503 body merely mentions 403', async () => {+ const revoked = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))+ clerum.rpc.listSessions.mockRejectedValue(+ new Error('503 Service Unavailable: upstream body mentioned 403')+ )+ const { result } = renderController({+ selectedAgent: null,+ agentNames: ['agent-a'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await waitFor(() =>+ expect(result.current.latestChatSessions.some(chat => chat.id === 'cached-a')).toBe(true)+ )+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())+ expect(revoked.has('agent-a')).toBe(false)+ expect(result.current.latestChatSessions.some(chat => chat.id === 'cached-a')).toBe(true)+ })+})++describe('late global catalog response', () => {+ it.each(['revocation', 'confirmed deletion'])(+ 'does not republish Host A after %s while Host B is pending',+ async action => {+ const revoked = new Set<string>()+ const deliveredA = deferred<void>()+ const pendingB = deferred<SessionsListResult>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ clerum.rpc.listSessions.mockImplementation(async (agentRef: string) => {+ if (agentRef === 'agent-a') {+ deliveredA.resolve()+ return serverSessions([{ agent: 'agent-a', chatId: 'session-a' }])+ }+ return pendingB.promise+ })+ const controller = renderController({+ selectedAgent: null,+ agentNames: ['agent-a', 'agent-b'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await deliveredA.promise+ await waitFor(() =>+ expect(clerum.rpc.listSessions).toHaveBeenCalledWith('agent-b', undefined, {+ agent: 'agent-b',+ limit: 50,+ })+ )++ if (action === 'revocation') {+ clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ await act(async () => {+ await controller.result.current.reconcileChat(makeTaskKey('agent-a', 'session-a'), {+ reason: 'background_refresh',+ })+ })+ expect(revoked.has('agent-a')).toBe(true)+ } else {+ await act(async () => {+ await controller.result.current.handleDeleteChatForAgent('agent-a', 'session-a')+ })+ expect(clerum.chat.delete).toHaveBeenCalledWith('agent-a', 'session-a')+ }++ await act(async () => {+ pendingB.resolve(serverSessions([{ agent: 'agent-b', chatId: 'session-b' }]))+ await pendingB.promise+ })+ await waitFor(() =>+ expect(+ controller.result.current.latestChatSessions.some(chat => chat.id === 'session-b')+ ).toBe(true)+ )+ expect(+ controller.result.current.latestChatSessions.some(chat => chat.id === 'session-a')+ ).toBe(false)+ }+ )+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.tsindex 29191d7bf..6d01c34a3 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts@@ -25,6 +25,8 @@ function liveResp(overrides: Partial<SessionMessagesResult> = {}): SessionMessagclass NetErr extends Error {}class NotFound extends Error {}+class Unavailable extends Error {}+class Unauthorized extends Error {}function buildDeps(overrides: Partial<ReconcileChatDeps> = {}): ReconcileChatDeps {const fsm = createSessionFsmStore()@@ -35,9 +37,10 @@ function buildDeps(overrides: Partial<ReconcileChatDeps> = {}): ReconcileChatDep// the view (so a rejoin can anchor to the rendered bubble, P1-A) before attach.attachLiveTask: vi.fn(async () => 'reconcile_rejoined' as const),settleIdle: vi.fn(async () => 'fell_through_to_resend' as const),- evictChat: vi.fn(async () => {}),+ revokeAccess: vi.fn(),isNetworkError: (e): e is NetErr => e instanceof NetErr,isHttp404: (e): e is NotFound => e instanceof NotFound,+ isAuthorizationError: (e): e is Unauthorized => e instanceof Unauthorized,telemetry: vi.fn(),networkRetryBackoffMs: [0, 0, 0],...overrides,@@ -78,22 +81,36 @@ describe('reconcileChat — precedence branches', () => {})})- it('404 evicts the chat, dispatches RESET, and does NOT re-finish', async () => {+ it.each([+ ['transient 404', new NotFound('not found during wake')],+ ['503', new Unavailable('service unavailable')],+ ['timeout', new NetErr('timeout')],+ ])('%s retains the selected conversation and draft state', async (_name, error) => {const deps = buildDeps({loadSessionMessages: vi.fn(async () => {- throw new NotFound('gone')+ throw error}),})- // Seed an entry so we can observe RESET removing it.+ // The FSM entry represents the selected conversation. A destructive reset+ // would also cause the controller to clear its conversation and composer.deps.fsm.dispatch(chatKey, { type: 'SEND_STARTED', taskId: 't1' })const reconcile = createReconcileChat(deps)await reconcile(chatKey, { reason: 'user_refresh' })- expect(deps.evictChat).toHaveBeenCalledWith(chatKey)- expect(deps.fsm.getState(chatKey)).toBeUndefined() // RESET removed it, FINISHED skipped- expect(deps.telemetry).toHaveBeenCalledWith('stream_recovery', {- reason: 'user_refresh',- outcome: '404',+ expect(deps.revokeAccess).not.toHaveBeenCalled()+ expect(deps.fsm.getState(chatKey)).toBeDefined()+ })++ it.each([401, 403])('%i revokes access and resets protected conversation state', async status => {+ const deps = buildDeps({+ loadSessionMessages: vi.fn(async () => {+ throw new Unauthorized(String(status))+ }),})+ deps.fsm.dispatch(chatKey, { type: 'SEND_STARTED', taskId: 't1' })+ const reconcile = createReconcileChat(deps)+ await reconcile(chatKey, { reason: 'user_refresh' })+ expect(deps.revokeAccess).toHaveBeenCalledWith(chatKey)+ expect(deps.fsm.getState(chatKey)).toBeUndefined()})it('exhausted network retries → WENT_OFFLINE + offline outcome', async () => {@@ -234,7 +251,7 @@ describe('reconcileChat — single-flight', () => {)})- it('drops a late 404 after reset instead of evicting the next session cache', async () => {+ it('drops a late 404 after reset without changing the next session cache', async () => {let rejectLoad: (reason: unknown) => void = () => {}const load = vi.fn((_agentRef: string, _chatId: string, _query: unknown, stillRelevant?: () => boolean) => {@@ -255,10 +272,53 @@ describe('reconcileChat — single-flight', () => {rejectLoad(new NotFound('late response'))await expect(pending).resolves.toBe('noop')- expect(deps.evictChat).not.toHaveBeenCalled()+ expect(deps.revokeAccess).not.toHaveBeenCalled()expect(deps.fsm.getState(chatKey)).toBeUndefined()})+ it('revokes a Host when an old chat read returns 403 after selection moves to another chat', async () => {+ let rejectLoad: (reason: unknown) => void = () => {}+ let firstChatSelected = true+ const deps = buildDeps({+ loadSessionMessages: vi.fn(+ () =>+ new Promise<SessionMessagesResult>((_resolve, reject) => {+ rejectLoad = reject+ })+ ),+ })+ const reconcile = createReconcileChat(deps)+ const pending = reconcile(chatKey, {+ reason: 'switch_to_chat',+ isRelevant: () => firstChatSelected,+ })+ firstChatSelected = false+ rejectLoad(new Unauthorized('403 forbidden'))++ await expect(pending).resolves.toBe('revoked')+ expect(deps.revokeAccess).toHaveBeenCalledWith(chatKey)+ })++ it('ignores a late 403 after reset tears down the principal scope', async () => {+ let rejectLoad: (reason: unknown) => void = () => {}+ const deps = buildDeps({+ loadSessionMessages: vi.fn(+ () =>+ new Promise<SessionMessagesResult>((_resolve, reject) => {+ rejectLoad = reject+ })+ ),+ })+ const reconcile = createReconcileChat(deps)+ const pending = reconcile(chatKey, { reason: 'old-principal' })+ reconcile.reset()+ deps.fsm.reset()+ rejectLoad(new Unauthorized('403 forbidden'))++ await expect(pending).resolves.toBe('stale_drop')+ expect(deps.revokeAccess).not.toHaveBeenCalled()+ })+it('a coalesced caller donates its taskIdHint to a hint-less in-flight run (M6)', async () => {let resolveFirst: (v: SessionMessagesResult) => void = () => {}const load = vidiff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsxindex 075d63c2d..34f2af9bc 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx@@ -118,6 +118,59 @@ function reportedSessions(chats: Array<{ chatId: string; title?: string }>) {}describe('rename pending queue (spec 15 §2.5)', () => {+ it.each([+ {+ label: 'exact Host denial',+ renameError: 'Rename session failed (403): host_access_revoked',+ readStatus: null,+ shouldRevoke: true,+ },+ {+ label: 'operation-scope denial',+ renameError: 'Rename session failed (403)',+ readStatus: null,+ shouldRevoke: false,+ },+ {+ label: 'read also denied',+ renameError: 'Rename session failed (403)',+ readStatus: 403,+ shouldRevoke: true,+ },+ {+ label: 'read unavailable',+ renameError: 'Rename session failed (403)',+ readStatus: 503,+ shouldRevoke: false,+ },+ ])(+ '$label applies the transcript authority decision',+ async ({ renameError, readStatus, shouldRevoke }) => {+ const revoked = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))+ clerum.rpc.renameSession.mockRejectedValue(new Error(renameError))+ clerum.rpc.listSessions.mockImplementation(+ async (_hostRef: string, _teamId: string | undefined, query?: { limit?: number }) => {+ if (query?.limit === 1 && readStatus !== null) throw new Error(`${readStatus} response`)+ return reportedSessions([{ chatId: 'c1', title: 'old' }])+ }+ )+ const { result } = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))+ await act(async () => {+ await result.current.handleRenameChatForAgent('agent-x', 'c1', 'new')+ })+ expect(revoked.has('agent-x')).toBe(shouldRevoke)+ if (shouldRevoke) expect(result.current.chatList).toEqual([])+ else expect(titleInList(result.current, 'c1')).toBe('old')+ }+ )+it('200: optimistic local title + RPC sync (hostRef===agent===agentRef), no toast', async () => {clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))clerum.rpc.renameSession.mockResolvedValue({ title: 'renamed' })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 b1359eb4e..26513af6c 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@@ -10,6 +10,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'import { act, waitFor } from '@testing-library/react'+import {+ getComposerDraft,+ resetComposerDraftStore,+ setComposerDraft,+} from '@lib/composerDraftStore'import { renderController } from './__fixtures__/controllerHarness'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'@@ -29,6 +34,7 @@ beforeEach(() => {afterEach(() => {vi.restoreAllMocks()vi.useRealTimers()+ resetComposerDraftStore()uninstallMockClerum()})@@ -989,6 +995,238 @@ describe('switchToChat (unified, D.4)', () => {expect(result.current.olderMessagesLoading).toBe(false)})+ it.each([401, 403, 404])(+ 'older-message HTTP %i applies the correct Host authority decision',+ async status => {+ const revoked = new Set<string>()+ clerum.chat.loadMessages.mockImplementation(async (_agentRef, _chatId, _limit, offset) =>+ offset === undefined+ ? [+ {+ id: 'turn-10-user',+ role: 'user',+ content: 'cached',+ timestamp: 10,+ serverTurnNumber: 10,+ },+ ]+ : []+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef, _agent, chatId, _teamId, query?: { beforeTurn?: number }) => {+ if (query?.beforeTurn !== undefined) throw new Error(`${status} response`)+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ turns: [],+ hasMoreBefore: true,+ hasMoreAfter: false,+ }+ }+ )+ const { result } = renderController({+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await settleMount()+ await act(async () => {+ await result.current.switchToChat('agent-x', 'older-authority')+ })+ expect(result.current.hasOlderMessages).toBe(true)++ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })+ if (status === 404) {+ expect(revoked.has('agent-x')).toBe(false)+ expect(result.current.activeChatId).toBe('older-authority')+ expect(result.current.chatMessages.map(message => message.content)).toEqual(['cached'])+ } else {+ expect(revoked.has('agent-x')).toBe(true)+ expect(result.current.activeChatId).toBeNull()+ expect(result.current.chatMessages).toEqual([])+ }+ }+ )++ it('ignores a send 403 from the prior team scope', async () => {+ const revoked = new Set<string>()+ let rejectSend!: (reason: unknown) => void+ clerum.rpc.invokeHostMessage.mockImplementation(+ () =>+ new Promise((_resolve, reject) => {+ rejectSend = reject+ })+ )+ const controller = renderController({+ currentTeamId: 'team-before',+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await settleMount()+ await act(async () => {+ await controller.result.current.switchToChat('agent-x', 'old-team-chat')+ })++ const pendingSend = controller.result.current.handleSendAgentMessage('hello')+ await waitFor(() => expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1))+ controller.rerender({ currentTeamId: 'team-after' })+ await act(async () => {+ rejectSend(new Error('403 forbidden'))+ await pendingSend+ })+ expect(revoked.has('agent-x')).toBe(false)+ })++ it('ignores an older-message 403 from the prior team scope', async () => {+ const revoked = new Set<string>()+ let rejectOlder!: (reason: unknown) => void+ clerum.chat.loadMessages.mockImplementation(async (_agentRef, _chatId, _limit, offset) =>+ offset === undefined+ ? [+ {+ id: 'turn-10-user',+ role: 'user',+ content: 'cached',+ timestamp: 10,+ serverTurnNumber: 10,+ },+ ]+ : []+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef, _agent, chatId, _teamId, query?: { beforeTurn?: number }) => {+ if (query?.beforeTurn !== undefined) {+ return new Promise((_resolve, reject) => {+ rejectOlder = reject+ })+ }+ return { agent: 'agent-x', chatId, state: 'idle', turns: [], hasMoreBefore: true }+ }+ )+ const controller = renderController({+ currentTeamId: 'team-before',+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await settleMount()+ await act(async () => {+ await controller.result.current.switchToChat('agent-x', 'old-team-chat')+ })+ const pendingOlder = controller.result.current.handleLoadOlderMessages()+ await waitFor(() => expect(rejectOlder).toEqual(expect.any(Function)))+ controller.rerender({ currentTeamId: 'team-after' })+ await act(async () => {+ rejectOlder(new Error('403 forbidden'))+ await pendingOlder+ })+ expect(revoked.has('agent-x')).toBe(false)+ })++ it.each([401, 403, 404])(+ 'durable task-result HTTP %i applies the correct Host authority decision',+ async status => {+ const revoked = new Set<string>()+ clerum.chat.loadMessages.mockResolvedValue([])+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'result-authority',+ state: 'idle',+ turns: [],+ })+ clerum.rpc.getTaskResult.mockRejectedValue(new Error(`${status} response`))+ const { result } = renderController({+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await settleMount()+ await act(async () => {+ await result.current.switchToChat('agent-x', 'result-authority')+ })++ await act(async () => {+ await result.current.reconcileChat(makeTaskKey('agent-x', 'result-authority'), {+ reason: 'task_result_recovery',+ taskIdHint: 'task-missing-turn',+ })+ })+ expect(clerum.rpc.getTaskResult).toHaveBeenCalled()+ if (status === 404) {+ expect(revoked.has('agent-x')).toBe(false)+ expect(result.current.activeChatId).toBe('result-authority')+ } else {+ expect(revoked.has('agent-x')).toBe(true)+ expect(result.current.activeChatId).toBeNull()+ }+ }+ )++ it.each(['revocation', 'confirmed deletion', 'team switch'])(+ 'does not publish a late durable task reply after %s',+ async action => {+ const revoked = new Set<string>()+ const lateResult = deferred<{ response: string }>()+ clerum.chat.loadMessages.mockResolvedValue([])+ clerum.rpc.loadSessionMessages.mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'late-result',+ state: 'processing',+ activeTaskId: 'task-late-result',+ turns: [turn(1, 'question')],+ })+ const controller = renderController({+ currentTeamId: 'team-before',+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ isHostAccessRevoked: agentRef => revoked.has(agentRef),+ })+ await settleMount()+ await act(async () => {+ await controller.result.current.switchToChat('agent-x', 'late-result')+ })+ await waitFor(() => expect(clerum.hasProgressHandler('task-late-result')).toBe(true))++ // The initial processing snapshot may fetch attachments. Hold only the+ // terminal fallback read whose late completion is under test.+ clerum.rpc.getTaskResult.mockClear()+ clerum.rpc.getTaskResult.mockImplementation(() => lateResult.promise)+ clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('unexpected transcript failure'))+ clerum.emitTaskProgress('task-late-result', { type: 'error', message: 'stream dropped' })+ await waitFor(() => expect(clerum.rpc.getTaskResult).toHaveBeenCalledTimes(1))++ if (action === 'revocation') {+ clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ await act(async () => {+ await controller.result.current.reconcileChat(makeTaskKey('agent-x', 'late-result'), {+ reason: 'authority_refresh',+ })+ })+ expect(revoked.has('agent-x')).toBe(true)+ } else if (action === 'confirmed deletion') {+ await act(async () => {+ await controller.result.current.handleDeleteChatForAgent('agent-x', 'late-result')+ })+ expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', 'late-result')+ } else {+ controller.rerender({ currentTeamId: 'team-after' })+ }++ const writesBefore = clerum.chat.appendMessages.mock.calls.length+ const notificationsBefore = controller.spies.pushNotification.mock.calls.length+ const toastsBefore = controller.spies.pushToast.mock.calls.length+ await act(async () => {+ lateResult.resolve({ response: 'late protected reply' })+ await lateResult.promise+ })+ expect(clerum.chat.appendMessages.mock.calls.length).toBe(writesBefore)+ expect(controller.spies.pushNotification.mock.calls.length).toBe(notificationsBefore)+ expect(controller.spies.pushToast.mock.calls.length).toBe(toastsBefore)+ expect(controller.result.current.chatMessages.map(message => message.content)).not.toContain(+ 'late protected reply'+ )+ }+ )+it('ignores an older-page response when switching away and back before it resolves', async () => {let resolveOlder!: (messages: unknown[]) => voidconst olderPage = new Promise<unknown[]>(resolve => {@@ -1665,10 +1903,12 @@ describe('switchToChat (unified, D.4)', () => {expect(clerum.hasProgressHandler('task-NEW')).toBe(true)})- it('404 evicts the stale local chat and resets the active selection', async () => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)- clerum.chat.loadMessages.mockResolvedValue([])+ it('ambiguous 404 preserves the selected chat, cached messages and unsent draft', async () => {+ clerum.chat.loadMessages.mockResolvedValue([+ { id: 'cached-turn', role: 'user' as const, content: 'known conversation', timestamp: 1 },+ ])clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('404 Not Found'))+ setComposerDraft('gone', 'unsent message')const { result } = renderController()await settleMount()@@ -1676,10 +1916,16 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'gone')})- expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', 'gone')- expect(result.current.activeChatId).toBeNull()- expect(result.current.sessionStateByChatKey['agent-x::gone']).toBeUndefined()- expect(warn).toHaveBeenCalled()+ expect(clerum.chat.delete).not.toHaveBeenCalled()+ expect(result.current.activeChatId).toBe('gone')+ expect(result.current.chatMessages.map(message => message.content)).toEqual([+ 'known conversation',+ ])+ expect(getComposerDraft('gone')).toBe('unsent message')+ expect(result.current.sessionStateByChatKey['agent-x::gone']).toMatchObject({+ syncing: false,+ offlineMode: true,+ })})it('network error keeps the Phase-1 cache and flags offline mode', async () => {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 563745c9a..eda3cc67b 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@@ -12,10 +12,15 @@ import { AgentTaskTrackerProvider } from '@contexts/AgentTaskTrackerContext'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { useAgentChatController } from '@hooks/domain/useAgentChatController'import { useComposerDraft } from '@hooks/useComposerDraft'-import { resetComposerDraftStore } from '@lib/composerDraftStore'+import { getComposerDraft, resetComposerDraftStore } from '@lib/composerDraftStore'import type { TaskProgressStreamEvent } from '../../../../../src/types'type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>+const revokedAgents = new Set<string>()+const onHostAccessRevoked = (agentRef: string) => {+ revokedAgents.add(agentRef)+}+const isHostAccessRevoked = (agentRef: string) => revokedAgents.has(agentRef)function getDraftInputValue(): string {return (screen.getByTestId('draft-input') as HTMLInputElement).value@@ -35,8 +40,14 @@ function createChatMeta(chatId: string) {function installClerumHarness() {let taskIndex = 0const chats: Array<ReturnType<typeof createChatMeta>> = []+ const deletedChatIds = new Set<string>()const messagesByChat = new Map<string, unknown[]>()const progressHandlers = new Map<string, ProgressHandler>()+ const loadSessionMessages = vi.fn(async () => ({ agent: 'trader', chatId: '', turns: [] }))+ const listSessions = vi.fn(async () => ({ items: [] }))+ const appendMessages = vi.fn(async (_agentRef: string, chatId: string, messages: unknown[]) => {+ messagesByChat.set(chatId, [...(messagesByChat.get(chatId) || []), ...messages])+ })const invokeHostMessage = vi.fn(async (_agentRef: string, _payload: { threadId?: string }) => {taskIndex += 1@@ -51,18 +62,22 @@ function installClerumHarness() {list: vi.fn(async () => chats),create: vi.fn(async (_agentRef: string, chatId: string) => {const meta = createChatMeta(chatId)+ deletedChatIds.delete(chatId)chats.push(meta)messagesByChat.set(chatId, [])return meta}),rename: vi.fn(async () => undefined),- delete: vi.fn(async () => undefined),+ delete: vi.fn(async (_agentRef: string, chatId: string) => {+ deletedChatIds.add(chatId)+ const index = chats.findIndex(chat => chat.id === chatId)+ if (index >= 0) chats.splice(index, 1)+ messagesByChat.delete(chatId)+ }),loadMessages: vi.fn(async (_agentRef: string, chatId: string) => messagesByChat.get(chatId) || []),- appendMessages: vi.fn(async (_agentRef: string, chatId: string, messages: unknown[]) => {- messagesByChat.set(chatId, [...(messagesByChat.get(chatId) || []), ...messages])- }),+ appendMessages,replaceMessages: vi.fn(async (_agentRef: string, chatId: string, messages: unknown[]) => {messagesByChat.set(chatId, [...messages])}),@@ -70,12 +85,12 @@ function installClerumHarness() {clearUnreadTerminal: vi.fn(async () => undefined),getLastActive: vi.fn(async () => null),setLastActive: vi.fn(async () => undefined),- getIndex: vi.fn(async () => ({ chats })),+ getIndex: vi.fn(async () => ({ chats, deletedChatIds: [...deletedChatIds] })),dismissOnboarding: vi.fn(async () => undefined),},rpc: {- listSessions: vi.fn(async () => ({ items: [] })),- loadSessionMessages: vi.fn(async () => ({ agent: 'trader', chatId: '', turns: [] })),+ listSessions,+ loadSessionMessages,subscribeHostActivity: vi.fn(async () => async () => undefined),invokeHostMessage,subscribeTaskProgress: vi.fn(@@ -94,10 +109,22 @@ function installClerumHarness() {},})- return { invokeHostMessage, progressHandlers }+ return {+ invokeHostMessage,+ appendMessages,+ progressHandlers,+ loadSessionMessages,+ listSessions,+ seedMessage: (chatId: string, content: string) =>+ messagesByChat.set(chatId, [+ { id: `message-${chatId}`, role: 'user', content, createdAt: new Date().toISOString() },+ ]),+ }}function AgentChatHarness() {+ const [selectionState, setSelectionState] = React.useState('idle')+ const [sendState, setSendState] = React.useState('idle')const vm = useAgentChatController({selectedAgent: 'trader',agentNames: ['trader'],@@ -106,6 +133,8 @@ function AgentChatHarness() {isAuthenticated: true,loadMenuData: true,navItem: 'chat',+ onHostAccessRevoked,+ isHostAccessRevoked,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,@@ -123,6 +152,13 @@ function AgentChatHarness() {<div><div data-testid="active-chat-id">{vm.activeChatId || ''}</div><div data-testid="agent-sending">{String(vm.agentSending)}</div>+ <div data-testid="chat-message-count">{vm.chatMessages.length}</div>+ <div data-testid="chat-list-ids">{vm.chatList.map(chat => chat.id).join(',')}</div>+ <div data-testid="latest-list-ids">+ {vm.latestChatSessions.map(chat => chat.id).join(',')}+ </div>+ <div data-testid="selection-state">{selectionState}</div>+ <div data-testid="send-state">{sendState}</div><inputdata-testid="draft-input"value={draft}@@ -131,13 +167,30 @@ function AgentChatHarness() {<button type="button" onClick={() => void vm.handleCreateChat()}>Create chat</button>- <button type="button" onClick={() => void vm.handleSendAgentMessage('hello')}>+ <button+ type="button"+ onClick={() => {+ setSendState('pending')+ void vm.handleSendAgentMessage('hello').then(() => setSendState('settled'))+ }}+ >Send message</button>{vm.chatList.map(chat => (- <button key={chat.id} type="button" onClick={() => void vm.handleSelectChat(chat.id)}>- Select chat {chat.id}- </button>+ <React.Fragment key={chat.id}>+ <button+ type="button"+ onClick={() => {+ setSelectionState('pending')+ void vm.handleSelectChat(chat.id).then(() => setSelectionState('settled'))+ }}+ >+ Select chat {chat.id}+ </button>+ <button type="button" onClick={() => void vm.handleDeleteChatForAgent('trader', chat.id)}>+ Delete chat {chat.id}+ </button>+ </React.Fragment>))}</div>)@@ -148,6 +201,7 @@ describe('useAgentChatController (cross-chat, migrated)', () => {cleanup()vi.restoreAllMocks()resetComposerDraftStore()+ revokedAgents.clear()delete (window as { clerum?: unknown }).clerum})@@ -243,4 +297,176 @@ describe('useAgentChatController (cross-chat, migrated)', () => {await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).toBe(secondChatId))expect(getDraftInputValue()).toBe('draft for session B')})++ it.each(['404', '503', 'timeout'])(+ 'keeps chat, selection and draft after a transient transcript %s',+ async failure => {+ const { loadSessionMessages, seedMessage } = installClerumHarness()+ render(+ <AgentTaskTrackerProvider>+ <AgentChatHarness />+ </AgentTaskTrackerProvider>+ )++ fireEvent.click(screen.getByRole('button', { name: 'Create chat' }))+ await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).not.toBe(''))+ const firstChatId = screen.getByTestId('active-chat-id').textContent || ''+ seedMessage(firstChatId, 'known conversation turn')+ fireEvent.click(screen.getByRole('button', { name: 'Create chat' }))+ await waitFor(() =>+ expect(screen.getByTestId('active-chat-id').textContent).not.toBe(firstChatId)+ )+ fireEvent.click(screen.getByRole('button', { name: `Select chat ${firstChatId}` }))+ await waitFor(() => expect(screen.getByTestId('chat-message-count').textContent).toBe('1'))+ fireEvent.change(screen.getByTestId('draft-input'), {+ target: { value: 'unsent draft' },+ })++ const readsBeforeFault = loadSessionMessages.mock.calls.length+ loadSessionMessages.mockRejectedValue(new Error(failure))+ fireEvent.click(screen.getByRole('button', { name: `Select chat ${firstChatId}` }))+ await waitFor(() =>+ expect(loadSessionMessages.mock.calls.length).toBeGreaterThan(readsBeforeFault)+ )+ await waitFor(() => expect(screen.getByTestId('selection-state').textContent).toBe('settled'))+ await waitFor(() => expect(screen.getByTestId('chat-message-count').textContent).toBe('1'))+ expect(screen.getByTestId('active-chat-id').textContent).toBe(firstChatId)+ expect(screen.getByTestId('chat-message-count').textContent).toBe('1')+ expect(getDraftInputValue()).toBe('unsent draft')+ expect(screen.getByRole('button', { name: `Select chat ${firstChatId}` })).toBeTruthy()+ }+ )++ it('does not restore protected chat or messages when a pending send resolves after revocation', async () => {+ const { invokeHostMessage, loadSessionMessages, progressHandlers } = installClerumHarness()+ let finishInvoke!: (result: { taskId: string; status: string }) => void+ invokeHostMessage.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishInvoke = resolve+ })+ )+ render(+ <AgentTaskTrackerProvider>+ <AgentChatHarness />+ </AgentTaskTrackerProvider>+ )++ 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 || ''+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ await waitFor(() => expect(invokeHostMessage).toHaveBeenCalledTimes(1))++ loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ 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(''))+ expect(screen.getByTestId('chat-message-count').textContent).toBe('0')++ finishInvoke({ taskId: 'late-task', status: 'pending' })+ await waitFor(() => expect(screen.getByTestId('send-state').textContent).toBe('settled'))+ await waitFor(() => expect(screen.getByTestId('agent-sending').textContent).toBe('false'))+ expect(screen.getByTestId('active-chat-id').textContent).toBe('')+ expect(screen.getByTestId('chat-message-count').textContent).toBe('0')+ expect(screen.queryByRole('button', { name: `Select chat ${chatId}` })).toBeNull()+ expect(progressHandlers.has('late-task')).toBe(false)+ })++ it.each([+ { label: '401', sendError: '401 unauthorized', readError: null, revoked: true },+ {+ label: 'exact Host-wide 403',+ sendError: '403 Forbidden: host_access_revoked',+ readError: '503 unavailable',+ revoked: true,+ },+ {+ label: 'generic 403 with readable catalog',+ sendError: '403 missing send scope',+ readError: null,+ revoked: false,+ },+ {+ label: 'generic 403 with denied catalog',+ sendError: '403 missing send scope',+ readError: '403 forbidden',+ revoked: true,+ },+ { label: '404', sendError: '404 transient', readError: null, revoked: false },+ ])(+ 'send $label applies the transcript authority decision',+ async ({ sendError, readError, revoked }) => {+ const { invokeHostMessage, listSessions } = installClerumHarness()+ invokeHostMessage.mockRejectedValueOnce(new Error(sendError))+ render(+ <AgentTaskTrackerProvider>+ <AgentChatHarness />+ </AgentTaskTrackerProvider>+ )+ 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))+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ await waitFor(() => expect(screen.getByTestId('send-state').textContent).toBe('settled'))+ expect(revokedAgents.has('trader')).toBe(revoked)+ if (revoked) {+ expect(screen.getByTestId('active-chat-id').textContent).toBe('')+ expect(screen.getByTestId('chat-message-count').textContent).toBe('0')+ } else {+ expect(screen.getByTestId('active-chat-id').textContent).toBe(chatId)+ }+ }+ )++ it('does not republish a confirmed deleted chat after its pending send resolves', async () => {+ const { invokeHostMessage, appendMessages } = installClerumHarness()+ let finishInvoke!: (result: { taskId: string; status: string }) => void+ invokeHostMessage.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishInvoke = resolve+ })+ )+ render(+ <AgentTaskTrackerProvider>+ <AgentChatHarness />+ </AgentTaskTrackerProvider>+ )++ fireEvent.click(screen.getByRole('button', { name: 'Create chat' }))+ await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).not.toBe(''))+ const deletedChatId = screen.getByTestId('active-chat-id').textContent || ''+ await waitFor(() =>+ expect(screen.getByTestId('latest-list-ids').textContent).toContain(deletedChatId)+ )+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ await waitFor(() => expect(invokeHostMessage).toHaveBeenCalledTimes(1))+ fireEvent.change(screen.getByTestId('draft-input'), {+ target: { value: 'draft to clear on delete' },+ })+ expect(getComposerDraft(deletedChatId)).toBe('draft to clear on delete')++ fireEvent.click(screen.getByRole('button', { name: `Delete chat ${deletedChatId}` }))+ await waitFor(() =>+ expect(screen.queryByRole('button', { name: `Select chat ${deletedChatId}` })).toBeNull()+ )+ expect(getComposerDraft(deletedChatId)).toBe('')+ const writesBeforeLateAck = appendMessages.mock.calls.length++ finishInvoke({ taskId: 'late-deleted-task', status: 'pending' })+ await waitFor(() => expect(screen.getByTestId('send-state').textContent).toBe('settled'))+ expect(screen.getByTestId('chat-list-ids').textContent).not.toContain(deletedChatId)+ expect(screen.getByTestId('latest-list-ids').textContent).not.toContain(deletedChatId)+ expect(getComposerDraft(deletedChatId)).toBe('')+ expect(appendMessages.mock.calls.length).toBe(writesBeforeLateAck)++ const survivingChatId = screen.getByTestId('active-chat-id').textContent || ''+ expect(survivingChatId).not.toBe('')+ expect(survivingChatId).not.toBe(deletedChatId)+ fireEvent.click(screen.getByRole('button', { name: 'Send message' }))+ await waitFor(() => expect(invokeHostMessage).toHaveBeenCalledTimes(2))+ expect(invokeHostMessage.mock.calls[1]?.[1]).toMatchObject({ threadId: survivingChatId })+ })})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 041c5b4fb..d1d996dcf 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@@ -19,6 +19,8 @@ import { resetHostModelSelectionStore } from '@lib/hostModelSelectionStore'import type { TaskProgressStreamEvent } from '../../../../../src/types'type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>+const onHostAccessRevoked = () => {}+const isHostAccessRevoked = () => falsefunction createChatMeta(chatId: string) {const now = new Date().toISOString()@@ -121,6 +123,8 @@ function AgentChatHarness() {isAuthenticated: true,loadMenuData: true,navItem: 'chat',+ onHostAccessRevoked,+ isHostAccessRevoked,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsxindex 9e82e9687..ad9c72f68 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx@@ -431,6 +431,50 @@ describe('useAgentChatController — characterization (D.0)', () => {expect(appended?.[0]?.errorCode).toBe('provider_error')})+ it('does not toast or repaint a terminal error after its append crosses a team switch', async () => {+ const pendingAppend = deferred<void>()+ clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-old-team' })+ clerum.chat.appendMessages.mockImplementation(+ async (_agentRef: string, _chatId: string, messages: Array<{ role?: string }>) => {+ if (messages[0]?.role === 'assistant') await pendingAppend.promise+ }+ )+ const controller = renderController({ currentTeamId: 'team-before' })+ await settleMount()+ await act(async () => {+ await controller.result.current.handleSendAgentMessage('question')+ })+ await waitFor(() => expect(clerum.hasProgressHandler('task-old-team')).toBe(true))++ clerum.emitTaskProgress('task-old-team', {+ type: 'terminal',+ data: {+ taskId: 'task-old-team',+ status: 'failed',+ error: { message: 'protected old-team failure', code: 'provider_error' },+ },+ })+ await waitFor(() =>+ expect(+ clerum.chat.appendMessages.mock.calls.some(+ call => (call[2] as Array<{ role?: string }>)[0]?.role === 'assistant'+ )+ ).toBe(true)+ )+ controller.rerender({ currentTeamId: 'team-after' })+ const toastCount = controller.spies.pushToast.mock.calls.length+ const notificationCount = controller.spies.pushNotification.mock.calls.length+ const progressAfterSwitch = controller.result.current.progressByMessageId++ await act(async () => {+ pendingAppend.resolve()+ await pendingAppend.promise+ })+ expect(controller.spies.pushToast.mock.calls.length).toBe(toastCount)+ expect(controller.spies.pushNotification.mock.calls.length).toBe(notificationCount)+ expect(controller.result.current.progressByMessageId).toEqual(progressAfterSwitch)+ })+it('4.6 marks the task cancelled without fetching a result', async () => {clerum.rpc.invokeHostMessage.mockResolvedValue({ taskId: 'task-abc' })const { result } = renderController()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 9c323fbd2..8f000b5c6 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@@ -81,6 +81,8 @@ interface HarnessProps {isAuthenticated: booleannavItem: NavItem}+const onHostAccessRevoked = () => {}+const isHostAccessRevoked = () => false/** Both real hooks, mounted together under the task-tracker the chat controller needs. */function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navItem }: HarnessProps) {@@ -93,6 +95,8 @@ function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navIteisAuthenticated,loadMenuData: true,navItem,+ onHostAccessRevoked,+ isHostAccessRevoked,...stableCallbacks,})}diff --git a/desktop-app/ui/src/hooks/domain/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.tsindex a186fe027..9302de791 100644--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts@@ -8,14 +8,14 @@ import type { SessionFsmStore } from './sessionFsm'* second invocation while one runs coalesces onto the same promise) and routes* the server truth through the four precedence branches, dispatching* `SERVER_SNAPSHOT`/`RECONCILE_*` to the FSM. The side-effectful branch bodies- * (attach a live stream, materialize/persist idle turns + durable result, evict a- * 404 chat) are injected so the module stays pure and exhaustively unit-testable.+ * (attach a live stream, materialize/persist idle turns + durable result, hide+ * protected data after an authorization rejection) are injected.** Telemetry (§4.8): one `stream_recovery` emission per `RECONCILE_FINISHED`,* carrying `{reason, outcome}` and preserving the existing outcome names* (`reconcile_rejoined`, `rejoin_capped_offline`, `reconcile_replaced`,- * `recovered_from_task_result`, `fell_through_to_resend`, `404`) plus new ones- * (`stale_drop`, `offline`, `error`).+ * `recovered_from_task_result`, `fell_through_to_resend`) plus `revoked`,+ * `stale_drop`, `offline`, and `error`.*//** Precedence-branch outcomes (stable telemetry names + Fase-3 additions). */@@ -30,7 +30,7 @@ export type ReconcileOutcome =| 'recovered_error'| 'fell_through_to_resend'| 'stale_drop'- | '404'+ | 'revoked'| 'offline'| 'error'| 'noop'@@ -77,10 +77,11 @@ export interface ReconcileChatDeps {/** Same post-await teardown guard as `attachLiveTask` (see there). */stillRelevant: () => boolean) => Promise<ReconcileOutcome>- /** Local eviction for a chat the server 404s (cache + sidebar + deselect). */- evictChat: (chatKey: string) => Promise<void>+ /** Hide protected data after an explicit authorization rejection. */+ revokeAccess: (chatKey: string) => voidisNetworkError: (err: unknown) => booleanisHttp404: (err: unknown) => boolean+ isAuthorizationError: (err: unknown) => booleantelemetry: (event: string, data: Record<string, unknown>) => void/** Guard: `false` aborts the reconcile mid-flight (chat switched away). */isStillRelevant?: (chatKey: string) => boolean@@ -165,9 +166,13 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {try {return await deps.loadSessionMessages(agentRef, chatId, query, stillRelevant)} catch (err) {+ // Chat selection may change while this request is pending, but an+ // explicit Host authorization denial still applies to the active scope.+ // The outer catch checks the principal/team generation before revoking.+ if (deps.isAuthorizationError(err)) throw errif (!stillRelevant()) return undefined- // Non-network (404, etc.) rethrows to the branch handler; a network blip- // is retried with backoff up to the cap (mirrors switchToChat P2-A).+ // Transport failures retry with backoff. An ambiguous 404 and an+ // authorization rejection reach the classification branch immediately.if (!deps.isNetworkError(err) || attempt === attempts - 1) throw err}if (!stillRelevant()) return undefined@@ -216,15 +221,20 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {)return outcome} catch (err) {- if (!stillRelevant()) {+ // An authority rejection applies to the Host, even if the user switched+ // from chat A to B while A's request was pending. The reset generation is+ // the principal/team boundary; an old scope cannot revoke a new one.+ if (deps.isAuthorizationError(err) && generation === startGeneration) {+ deps.revokeAccess(chatKey)+ deps.fsm.dispatch(chatKey, { type: 'RESET' })+ outcome = 'revoked'+ } else if (!stillRelevant()) {outcome = 'stale_drop'return outcome- }- if (deps.isHttp404(err)) {- await deps.evictChat(chatKey)- deps.fsm.dispatch(chatKey, { type: 'RESET' })- outcome = '404'- } else if (deps.isNetworkError(err)) {+ } else if (deps.isHttp404(err) || deps.isNetworkError(err)) {+ // A transcript 404 is anti-enumeration and can also occur while a Host+ // wakes. It does not prove the session was deleted. Keep the local chat,+ // selection and draft for a later successful reconcile.deps.fsm.dispatch(chatKey, { type: 'WENT_OFFLINE' })outcome = 'offline'} else {@@ -239,10 +249,10 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {}return outcome} finally {- // RESET already tore the entry down on 404; re-dispatching FINISHED would+ // RESET already tore the entry down on revocation; re-dispatching FINISHED would// resurrect an empty entry, so skip the finalizer in that case.if (- outcome !== '404' &&+ outcome !== 'revoked' &&generation === startGeneration &&(chatGenerations.get(chatKey) ?? 0) === startChatGeneration) {diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex d37893f25..8b2590a99 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -43,6 +43,9 @@ import {classifyErrorKind,errorRecoveryHint,extractAssistantReply,+ isAuthorizationError,+ isConfirmedHostAccessRevoked,+ isHttp403,isHttp404,isNetworkError,} from '../../lib/format'@@ -314,7 +317,8 @@ async function loadTaskResultResponseFileAttachments(try {const result = await window.clerum.rpc.getTaskResult(agentRef, taskId, [agentRef])return buildResponseFileAttachments(result)- } catch {+ } catch (error) {+ if (isAuthorizationError(error)) throw errorreturn []}}@@ -354,6 +358,8 @@ interface UseAgentChatControllerParams {target: AgentConversationNotificationTarget) => Promise<void>decideApprovalFromNotification: (target: AgentApprovalNotificationTarget) => Promise<void>+ onHostAccessRevoked: (agentRef: string) => void+ isHostAccessRevoked: (agentRef: string) => boolean}export function useAgentChatController({@@ -372,6 +378,8 @@ export function useAgentChatController({showDesktopNotification,openAgentConversationFromNotification,decideApprovalFromNotification,+ onHostAccessRevoked,+ isHostAccessRevoked,}: UseAgentChatControllerParams) {const chatStore = useChatStore()const authenticatedScope = `${currentUserId ?? 'unknown-user'}:${currentTeamId}`@@ -401,6 +409,11 @@ export function useAgentChatController({// activeChatId) are injected through `chatListHostRef`, filled each render once// those parent callbacks are defined (created here so the hook can receive it).const chatListHostRef = useRef<ChatListControllerHost | null>(null)+ const revokeHostAccessRef = useRef<((agentRef: string) => void) | null>(null)+ const onCatalogHostAccessRevoked = useCallback(+ (agentRef: string) => revokeHostAccessRef.current!(agentRef),+ []+ )const autoSelectedChatIdRef = useRef<string | null>(null)const chatListCtl = useChatListController({selectedAgent,@@ -414,6 +427,8 @@ export function useAgentChatController({chatStore,fsm,host: chatListHostRef,+ isHostAccessRevoked,+ onHostAccessRevoked: onCatalogHostAccessRevoked,})const {chatList,@@ -422,6 +437,7 @@ export function useAgentChatController({chatListHasMoreRemoteSessions,latestChatSessions,latestChatSessionsLoading,+ hideAgent,loadChatList,loadMoreChatSessions,setChatListLoading,@@ -438,6 +454,7 @@ export function useAgentChatController({readPendingSelection,writePendingSelection,clearPendingSelection,+ isChatDeleted,} = chatListCtlconst [chatMessages, setChatMessages] = useState<AgentChatMessage[]>([])const [chatMessagesLoading, setChatMessagesLoading] = useState(false)@@ -497,6 +514,8 @@ export function useAgentChatController({failRetainedSend,} = retainedSendsconst sendScopeGeneration = useRef(0)+ const currentAuthScopeRef = useRef(`${isAuthenticated}:${authenticatedScope}`)+ currentAuthScopeRef.current = `${isAuthenticated}:${authenticatedScope}`// #654 M5 — the userMessageId of the most recent send that retained its// payload. A retry compares it before and after to learn whether it retained// a snapshot of its own; `sendAgentMessage` has several early returns (image@@ -508,6 +527,7 @@ export function useAgentChatController({if (lastRetentionScope.current === scope) returnlastRetentionScope.current = scopesendScopeGeneration.current += 1+ agentSendSetupOwnerRef.current = nullagentSendInFlightRef.current = falsesetAgentSending(false)retainedSends.resetRetainedSendStore()@@ -519,6 +539,7 @@ export function useAgentChatController({const activityInFlightByAgentRef = useRef<Record<string, string[]>>({})const activityTaskToMessageByAgentRef = useRef<Record<string, Record<string, string>>>({})const agentSendInFlightRef = useRef(false)+ const agentSendSetupOwnerRef = useRef<{ id: symbol; agentRef: string } | null>(null)// (Phase-2 AbortController + `recoveringTaskIdByKeyRef` removed in Fase 5b: the// reconcile gate's per-call `isRelevant` covers the A→B→A abort, and the// epoch-anchored zombie-ack in `settleIdle` (R2) covers the residual-recreated-@@ -553,7 +574,7 @@ export function useAgentChatController({loadSessionMessages: ReconcileChatDeps['loadSessionMessages']attachLiveTask: ReconcileChatDeps['attachLiveTask']settleIdle: ReconcileChatDeps['settleIdle']- evictChat: ReconcileChatDeps['evictChat']+ revokeAccess: ReconcileChatDeps['revokeAccess']} | null>(null)const reconcileChatRef = useRef<ReconcileChat | null>(null)if (!reconcileChatRef.current) {@@ -565,9 +586,10 @@ export function useAgentChatController({reconcileBranchesRef.current!.attachLiveTask(chatKey, resp, epoch, stillRelevant),settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>reconcileBranchesRef.current!.settleIdle(chatKey, resp, epoch, hint, stillRelevant),- evictChat: chatKey => reconcileBranchesRef.current!.evictChat(chatKey),+ revokeAccess: chatKey => reconcileBranchesRef.current!.revokeAccess(chatKey),isNetworkError,isHttp404,+ isAuthorizationError,telemetry: (event, data) => console.log(`[telemetry] ${event}`, data),})}@@ -825,6 +847,7 @@ export function useAgentChatController({// main-process half (`stopAllStreams` on logout) is Fase 4.tracker.releaseAll()sendScopeGeneration.current += 1+ agentSendSetupOwnerRef.current = nullagentSendInFlightRef.current = falseretainedSends.resetRetainedSendStore()// Abort any in-flight reconcile so a run mid-backoff can't resurrect a@@ -861,6 +884,7 @@ export function useAgentChatController({// chat, and a task in flight is rejoined via the tracker D.3 already mounts.const switchToChat = useCallback(async (agentRef: string, chatId: string) => {+ if (isHostAccessRevoked(agentRef) || isChatDeleted(agentRef, chatId)) returnconst switchRequest = Symbol(`${agentRef}:${chatId}`)activeChatSwitchRequestRef.current = switchRequestconst key = makeTaskKey(agentRef, chatId)@@ -891,6 +915,7 @@ export function useAgentChatController({setAgentError(null)setFailedAgentSend(null)await chatStore.setLastActive(agentRef, chatId)+ if (isHostAccessRevoked(agentRef) || isChatDeleted(agentRef, chatId)) returnunfillableServerGapUpperBoundsRef.current.delete(key)@@ -948,7 +973,7 @@ export function useAgentChatController({// clean.tracker.resetRejoinAttempts(key)- // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, 404 evict,+ // PHASE 2/3 — the single reconcile gate (§4.3) owns fetch+retry, ambiguous 404,// offline, the SERVER_SNAPSHOT, the idle replace (auto-title / S4 upsert /// epoch-anchored zombie-ack) and the live rejoin (approval re-seed).// `taskIdHint` = the pre-await zombie's task, which drives the durable@@ -977,6 +1002,8 @@ export function useAgentChatController({},[currentTeamId,+ isHostAccessRevoked,+ isChatDeleted,dispatchSession,tracker,reconcileChat,@@ -1020,17 +1047,24 @@ export function useAgentChatController({const handleSelectChat = useCallback(async (chatId: string) => {- if (!selectedAgent) return+ if (+ !selectedAgent ||+ isHostAccessRevoked(selectedAgent) ||+ isChatDeleted(selectedAgent, chatId)+ )+ returnautoSelectedChatIdRef.current = nullawait switchToChat(selectedAgent, chatId)},- [selectedAgent, switchToChat]+ [selectedAgent, isHostAccessRevoked, isChatDeleted, switchToChat])const handleLoadOlderMessages = useCallback(async () => {if (!selectedAgent || !activeChatId || olderMessagesRequestRef.current) returnconst requestAgent = selectedAgentconst requestChatId = activeChatId+ const requestScope = sendScopeGeneration.current+ const requestScopeIdentity = currentAuthScopeRef.currentconst requestToken = Symbol(`${requestAgent}:${requestChatId}`)olderMessagesRequestRef.current = requestTokenconst isStillRelevant = () => {@@ -1129,6 +1163,15 @@ export function useAgentChatController({oldestMergedTurn > 1))} catch (error) {+ if (+ isAuthorizationError(error) &&+ requestScope === sendScopeGeneration.current &&+ requestScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(requestAgent)+ ) {+ revokeHostAccessRef.current!(requestAgent)+ return+ }console.warn('[chat-history] failed to load older messages', {agentRef: requestAgent,chatId: requestChatId,@@ -1149,12 +1192,13 @@ export function useAgentChatController({ignoredServerGapUpperBounds,markServerGapUnfillable,selectedAgent,+ isHostAccessRevoked,tracker,])// Agent selection → load chatsuseEffect(() => {- if (!selectedAgent) {+ if (!selectedAgent || isHostAccessRevoked(selectedAgent)) {autoSelectedChatIdRef.current = nullactiveChatVisibilityRef.current = {...activeChatVisibilityRef.current,@@ -1212,7 +1256,7 @@ export function useAgentChatController({setChatListLoading(true);(async () => {const result = await loadChatList(selectedAgent)- if (cancelled) return+ if (cancelled || isHostAccessRevoked(selectedAgent)) returnsetChatListLoading(false)if (!result) {setChatMessagesLoading(false)@@ -1276,7 +1320,7 @@ export function useAgentChatController({return () => {cancelled = true}- }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent])+ }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent, isHostAccessRevoked])const mapComposerAttachmentsToHostRequest = (attachments: ComposerImageAttachment[]@@ -1446,6 +1490,14 @@ export function useAgentChatController({const appendAssistantMessage = useCallback(async (agentName: string, chatId: string | null, message: AgentChatMessage) => {+ const messageScope = sendScopeGeneration.current+ const messageScopeIdentity = currentAuthScopeRef.current+ const mayAppend = () =>+ messageScope === sendScopeGeneration.current &&+ messageScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(agentName) &&+ (!chatId || !isChatDeleted(agentName, chatId))+ if (!mayAppend()) return// Update the in-memory view FIRST (synchronously), then persist. For a// rejoined task the in-flight placeholder hides the moment the tracker// emits 'completed'; landing the reply before the await closes the visual@@ -1457,6 +1509,7 @@ export function useAgentChatController({if (chatId) {try {await chatStore.appendMessages(agentName, chatId, [message])+ if (!mayAppend()) returnbumpActivity(agentName, chatId, new Date(message.timestamp).toISOString())} catch {// persistence is best-effort; the in-memory view already updated@@ -1466,12 +1519,13 @@ export function useAgentChatController({// onTrackerTerminal can't escape before its final tracker.ack(key) — a// throw here would otherwise leak the tracked (agent, chat) entry.try {+ if (!mayAppend()) returnpushAssistantReplyNotification(agentName, message, chatId)} catch {// notification delivery is best-effort}},- [bumpActivity, chatStore, pushAssistantReplyNotification]+ [bumpActivity, chatStore, pushAssistantReplyNotification, isHostAccessRevoked, isChatDeleted])// ─── reconcileChat branch callbacks (§4.3) ───@@ -1508,6 +1562,8 @@ export function useAgentChatController({const v = activeChatVisibilityRef.currentreturn v.selectedAgent === agentRef && v.activeChatId === chatId}+ const mayHydrate = () =>+ stillRelevant() && !isHostAccessRevoked(agentRef) && !isChatDeleted(agentRef, chatId)const cached = (await chatStore.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE).catch(error => {@@ -1531,7 +1587,7 @@ export function useAgentChatController({cached: localMessages,stale: true,})- if (!stillRelevant()) return staleResult()+ if (!mayHydrate()) return staleResult()if (!isActive() || tracker.get(chatKey)) {return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }}@@ -1553,7 +1609,7 @@ export function useAgentChatController({hydrated,taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : [])- if (!stillRelevant()) return staleResult()+ if (!mayHydrate()) return staleResult()if (!isActive() || tracker.get(chatKey)) {return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }}@@ -1575,7 +1631,7 @@ export function useAgentChatController({: hydratedWithAttachmentsconst hasOlderAfterMerge =hasOlderFromServer || nextServerBackfillBeforeTurn(rendered) !== undefined- if (!stillRelevant()) return staleResult(rendered)+ if (!mayHydrate()) return staleResult(rendered)if (latestPageFallback) {setHasOlderMessages(hasOlderAfterMerge)} else {@@ -1584,11 +1640,11 @@ export function useAgentChatController({if (sameMessageSequence(rendered, localMessages)) {return { rendered: localMessages, replaced: false, cached: localMessages, stale: false }}- if (!stillRelevant()) return staleResult(rendered)+ if (!mayHydrate()) return staleResult(rendered)chatMessagesRef.current = renderedsetChatMessages(rendered)const meta = await chatStore.createChat(agentRef, chatId)- if (!stillRelevant()) return staleResult(rendered)+ if (!mayHydrate()) return staleResult(rendered)if (resp.activeTaskId) {await chatStore.replaceMessages(agentRef, chatId, rendered, {activeTaskIds: [resp.activeTaskId],@@ -1596,7 +1652,7 @@ export function useAgentChatController({} else {await chatStore.replaceMessages(agentRef, chatId, rendered)}- if (!stillRelevant()) return staleResult(rendered)+ if (!mayHydrate()) return staleResult(rendered)if (!isActive()) {return { rendered, replaced: true, cached: localMessages, stale: false }}@@ -1624,6 +1680,8 @@ export function useAgentChatController({},[tracker,+ isHostAccessRevoked,+ isChatDeleted,chatStore.loadMessages,chatStore.createChat,chatStore.replaceMessages,@@ -1735,7 +1793,10 @@ export function useAgentChatController({if (cached.some(m => m.role === 'assistant' && m.task_id === taskIdHint)) return 'noop'const taskResult = await window.clerum.rpc.getTaskResult(agentRef, taskIdHint, [agentRef])- .catch(() => null)+ .catch(error => {+ if (isAuthorizationError(error)) throw error+ return null+ })if (!taskResult) return 'fell_through_to_resend'// Post-await teardown guard (parity with attachLiveTask): a `reset()` during// the getTaskResult await must not let the durable materialization persist a@@ -1786,29 +1847,70 @@ export function useAgentChatController({[fsm, tracker, hydrateActiveChatFromServer, appendAssistantMessage])- const reconcileEvictChat = useCallback<ReconcileChatDeps['evictChat']>(- async chatKey => {- const { agentRef, chatId } = parseTaskKey(chatKey)- // The local cache referenced a chat the server 404s. Post-spec this- // shouldn't happen (every chat originates from a POST the server records) →- // treat as a stale-cache bug: log + evict locally (parity with the old- // switchToChat 404 branch, so its characterization pin keeps warning).- console.warn('[reconcileChat] chat unknown to server, evicting local cache', {- agentRef,- chatId,+ const revokeHostAccess = useCallback(+ (agentRef: string) => {+ for (const chatKey of Object.keys(fsm.getSnapshot())) {+ if (parseTaskKey(chatKey).agentRef !== agentRef) continue+ tracker.release(chatKey as TaskKey)+ reconcileChatRef.current?.supersede(chatKey)+ fsm.dispatch(chatKey, { type: 'RESET' })+ }+ const stopActivity = activityUnsubByAgentRef.current[agentRef]+ if (stopActivity) {+ delete activityUnsubByAgentRef.current[agentRef]+ void stopActivity().catch(() => undefined)+ }+ delete activityInFlightByAgentRef.current[agentRef]+ delete activityTaskToMessageByAgentRef.current[agentRef]+ setActivityByAgentMessage(previous => {+ const { [agentRef]: _removed, ...remaining } = previous+ return remaining})- tracker.release(chatKey as TaskKey)- await chatStore.deleteChat(agentRef, chatId).catch(() => undefined)- chatStore.clearCachedRemoteData()- removeFromList(chatId)+ setProgressByAgentMessage(previous => {+ const { [agentRef]: _removed, ...remaining } = previous+ return remaining+ })+ hideAgent(agentRef)const view = activeChatVisibilityRef.current- if (view.selectedAgent === agentRef && view.activeChatId === chatId) {- activeChatVisibilityRef.current = { ...view, activeChatId: null }+ if (agentSendSetupOwnerRef.current?.agentRef === agentRef) {+ agentSendSetupOwnerRef.current = null+ agentSendInFlightRef.current = false+ setAgentSending(false)+ }+ if (view.selectedAgent === agentRef) {+ chatStore.clearCachedRemoteData()+ clearList()+ resetComposerAttachments()+ activeChatVisibilityRef.current = { ...view, selectedAgent: null, activeChatId: null }setActiveChatId(null)setChatMessages([])+ setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()}+ onHostAccessRevoked(agentRef)},- [tracker, chatStore.deleteChat, chatStore.clearCachedRemoteData, removeFromList]+ [+ tracker,+ fsm,+ hideAgent,+ chatStore.clearCachedRemoteData,+ clearList,+ resetComposerAttachments,+ cancelOlderMessagesLoad,+ onHostAccessRevoked,+ ]+ )+ useEffect(() => {+ revokeHostAccessRef.current = revokeHostAccess+ }, [revokeHostAccess])++ const reconcileRevokeAccess = useCallback<ReconcileChatDeps['revokeAccess']>(+ chatKey => {+ const { agentRef } = parseTaskKey(chatKey)+ revokeHostAccess(agentRef)+ },+ [revokeHostAccess])useEffect(() => {@@ -1918,14 +2020,14 @@ export function useAgentChatController({},attachLiveTask: reconcileAttachLiveTask,settleIdle: reconcileSettleIdle,- evictChat: reconcileEvictChat,+ revokeAccess: reconcileRevokeAccess,}}, [chatStore.loadSessionMessages,chatStore.loadMessages,reconcileAttachLiveTask,reconcileSettleIdle,- reconcileEvictChat,+ reconcileRevokeAccess,])// ─── Tracker callbacks + subscription (the post-D.3 fire & forget glue) ───@@ -1933,6 +2035,13 @@ export function useAgentChatController({const onTrackerTerminal = useCallback(async (key: TaskKey, state: TaskState) => {const { agentRef, chatId } = parseTaskKey(key)+ const terminalScope = sendScopeGeneration.current+ const terminalScopeIdentity = currentAuthScopeRef.current+ const terminalStillAuthorized = () =>+ terminalScope === sendScopeGeneration.current &&+ terminalScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(agentRef) &&+ !isChatDeleted(agentRef, chatId)// `task_duration_seconds` telemetry is now emitted by the coordinator// (`fireTerminal`, §4.8) — the lifecycle owner — so it is not duplicated here.const result = state.terminalResult@@ -1977,6 +2086,7 @@ export function useAgentChatController({// Telemetry for this recovery is emitted once by the reconcile gate (§4.8,// `deps.telemetry`) with the real outcome, so no manual log here.const applyFallback = () => {+ if (!terminalStillAuthorized()) returndropActivity()liveDepsRef.current.pushToast(`Message to ${agentRef} failed.`, 'error')updateMessageProgress(agentRef, state.userMessageId, () => ({@@ -2020,9 +2130,28 @@ export function useAgentChatController({// Mirrors taskTracker's interpretation of `getTaskResult` (source:'failed'// vs a durable reply) so the rendered bubble matches the direct path.const recoverFromDurableTaskResult = async (): Promise<boolean> => {- const taskResult = await window.clerum.rpc- .getTaskResult(agentRef, state.taskId, [agentRef])- .catch(() => null)+ const mayRecover = () =>+ terminalScope === sendScopeGeneration.current &&+ terminalScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(agentRef) &&+ !isChatDeleted(agentRef, chatId)+ let taskResult: Awaited<ReturnType<typeof window.clerum.rpc.getTaskResult>>+ try {+ taskResult = await window.clerum.rpc.getTaskResult(agentRef, state.taskId, [agentRef])+ } catch (error) {+ if (isAuthorizationError(error)) {+ if (+ terminalScope === sendScopeGeneration.current &&+ terminalScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(agentRef)+ ) {+ revokeHostAccessRef.current!(agentRef)+ }+ return true+ }+ return false+ }+ if (!mayRecover()) return trueif (!taskResult) return false// The awaits in this branch (incl. `getTaskResult` above) open a window@@ -2058,6 +2187,7 @@ export function useAgentChatController({...(errorCode ? { errorCode } : {}),...(errorProvider ? { errorProvider } : {}),})+ if (!mayRecover()) return trueupdateMessageProgress(agentRef, state.userMessageId, () => ({taskId: state.taskId,status: 'error',@@ -2096,6 +2226,7 @@ export function useAgentChatController({task_id: state.taskId,...(attachments.length ? { attachments } : {}),})+ if (!mayRecover()) return trueupdateMessageProgress(agentRef, state.userMessageId, () => ({taskId: state.taskId,status: 'completed',@@ -2154,6 +2285,7 @@ export function useAgentChatController({taskIdHint: state.taskId,isRelevant: isActive,})+ if (!terminalStillAuthorized()) returnswitch (outcome) {case 'reconcile_rejoined':case 'rejoin_capped_offline':@@ -2207,8 +2339,8 @@ export function useAgentChatController({dropActivity()setIdle()break- case '404':- // The reconcile evicted the chat + reset the FSM already.+ case 'revoked':+ // The authorization rejection hid the protected chat + reset the FSM.dropActivity()breakcase 'offline':@@ -2254,6 +2386,7 @@ export function useAgentChatController({...(toolSteps ? { toolSteps } : {}),})}+ if (!terminalStillAuthorized()) returnliveDepsRef.current.pushToast(`Message sent to ${agentRef}.`, 'success')} else if (result?.kind === 'error') {// Terminal failure: the payload stays retained for explicit recovery.@@ -2275,6 +2408,7 @@ export function useAgentChatController({errorCode: result.code,errorProvider: result.provider,})+ if (!terminalStillAuthorized()) returnliveDepsRef.current.pushToast(`Message to ${agentRef} failed: ${result.message}`, 'error')} else if (result.source === 'result_fetch') {await appendAssistantMessage(agentRef, chatId, {@@ -2285,10 +2419,12 @@ export function useAgentChatController({task_id: state.taskId,isError: true,})+ if (!terminalStillAuthorized()) returnliveDepsRef.current.pushToast(`Failed to retrieve result for ${agentRef}.`, 'error')}// `source: 'stream'` is intercepted + reconciled at the top of this handler.}+ if (!terminalStillAuthorized()) return// The Resend payload is dropped by the coordinator on `release` below (B15).// Reflect the terminal state into progress/activity directly. The live// subscription also does this, but a task can finish before its chat's@@ -2354,6 +2490,8 @@ export function useAgentChatController({updateMessageProgress,updateMessageActivity,reconcileChat,+ isHostAccessRevoked,+ isChatDeleted,])@@ -2495,6 +2633,7 @@ export function useAgentChatController({preserveComposer = false) => {const sendScope = sendScopeGeneration.current+ const sendScopeIdentity = currentAuthScopeRef.currentconst originalDraftChat = activeChatVisibilityRef.current.activeChatIdconst originalDraftRevision = getComposerDraftRevision(originalDraftChat)const originalAttachmentRevision = composerAttachmentRevisionRef.current@@ -2503,6 +2642,7 @@ export function useAgentChatController({const effectiveReferences = [...references]if (!selectedAgent ||+ isHostAccessRevoked(selectedAgent) ||(!trimmedContent && !effectiveAttachments.length && !effectiveReferences.length))return@@ -2511,10 +2651,19 @@ export function useAgentChatController({// Read the chat id from the ref (updated synchronously by auto-create /// switchToChat) rather than state, which may not have committed yet.const currentChatId = activeChatVisibilityRef.current.activeChatId+ if (currentChatId && isChatDeleted(selectedAgent, currentChatId)) returnif (currentChatId && tracker.get(makeTaskKey(selectedAgent, currentChatId))) returnif (agentSendInFlightRef.current) return- agentSendInFlightRef.current = trueconst sendAgent = selectedAgent+ const sendSetupOwner = { id: Symbol('agent-send-setup'), agentRef: sendAgent }+ agentSendSetupOwnerRef.current = sendSetupOwner+ agentSendInFlightRef.current = true+ const releaseSendSetup = () => {+ if (agentSendSetupOwnerRef.current !== sendSetupOwner) return+ agentSendSetupOwnerRef.current = null+ agentSendInFlightRef.current = false+ setAgentSending(false)+ }// Issue #654 — send-time image guard. Runs BEFORE the chat is created (a// blocked visual send must not leave a stray empty chat) and long before// the optimistic message/attachment clear. `readHostModelSelection` is the@@ -2534,7 +2683,7 @@ export function useAgentChatController({'Image attachments are not available for the selected model yet.'setAgentError(blocker)pushToast(blocker, 'error')- agentSendInFlightRef.current = false+ releaseSendSetup()return}// Capture the model the guard just validated; the request below must@@ -2542,7 +2691,12 @@ export function useAgentChatController({visualModelForSend = selection.intentModel ?? selection.effectiveModel ?? undefinedvisualModelRevisionForSend = selection.confirmedRevision ?? undefined}- let sendChatId = activeChatId+ let sendChatId = currentChatId ?? activeChatId+ const sendStillAuthorized = () =>+ sendScope === sendScopeGeneration.current &&+ sendScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(sendAgent) &&+ (!sendChatId || !isChatDeleted(sendAgent, sendChatId))// Captured for the retention snapshot: the model this attempt actually// asked for (issue #654), readable from the catch below.let requestModelForRetention: string | undefined@@ -2555,11 +2709,14 @@ export function useAgentChatController({try {const chatId = crypto.randomUUID()const meta = await chatStore.createChat(sendAgent, chatId)- if (sendScope !== sendScopeGeneration.current) return+ sendChatId = chatId+ if (!sendStillAuthorized()) {+ releaseSendSetup()+ return+ }chatStore.clearCachedRemoteData()autoCreatedMeta = metaappendNewEntry(sendAgent, meta)- sendChatId = chatId// R2 new-chat composer: a per-session model picked BEFORE this chat// existed was held in the agent-keyed pre-chat slot (no chatId to key a// pending entry, no session to POST to). Now that the chatId exists,@@ -2579,13 +2736,18 @@ export function useAgentChatController({setActiveChatId(chatId)setChatMessages([])await chatStore.setLastActive(sendAgent, chatId)- if (sendScope !== sendScopeGeneration.current) return+ if (!sendStillAuthorized()) {+ releaseSendSetup()+ return+ }} catch (error) {- if (sendScope !== sendScopeGeneration.current) return+ if (!sendStillAuthorized()) {+ releaseSendSetup()+ return+ }const message = error instanceof Error ? error.message : String(error)pushToast(`Could not create a chat session: ${message}`, 'error')- agentSendInFlightRef.current = false- setAgentSending(false)+ releaseSendSetup()return}}@@ -2700,7 +2862,7 @@ export function useAgentChatController({// R2 "Option A": a per-session model chosen while the host was suspended// couldn't be persisted server-side, so it was held as pending. Piggyback// it here — this send wakes the host and applies the model to this task.- if (sendScope !== sendScopeGeneration.current) return+ if (!sendStillAuthorized()) returnconst pendingModel = pendingModelForSendconst requestModel = requestModelForRetentionconst request = {@@ -2729,7 +2891,7 @@ export function useAgentChatController({// A successful send creates or updates the durable server session. Do not// let the short-lived sidebar cache hide that new catalog state.chatStore.clearCachedRemoteData()- if (sendScope !== sendScopeGeneration.current) return+ if (!sendStillAuthorized()) returnconst responseRecord = response as Record<string, unknown>const ackOk = !responseRecord.error && responseRecord.success !== false// #654 H1 — the send IS the write. Its ack carries the revision that@@ -2898,7 +3060,31 @@ export function useAgentChatController({fsm.dispatch(taskKey, { type: 'TASK_CREATED', taskId })}} catch (error) {- if (sendScope !== sendScopeGeneration.current) return+ if (+ isAuthorizationError(error) &&+ sendScope === sendScopeGeneration.current &&+ sendScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(sendAgent)+ ) {+ if (isConfirmedHostAccessRevoked(error) || !isHttp403(error)) {+ revokeHostAccess(sendAgent)+ return+ }+ try {+ await chatStore.listSessions(sendAgent, { agent: sendAgent, limit: 1 }, { force: true })+ } catch (readError) {+ if (+ isAuthorizationError(readError) &&+ sendScope === sendScopeGeneration.current &&+ sendScopeIdentity === currentAuthScopeRef.current &&+ !isHostAccessRevoked(sendAgent)+ ) {+ revokeHostAccess(sendAgent)+ return+ }+ }+ }+ if (!sendStillAuthorized()) returnconst message = error instanceof Error ? error.message : String(error)const normalized = message.toLowerCase()const isRequestEntityTooLarge =@@ -2969,14 +3155,14 @@ export function useAgentChatController({} finally {// Fire & forget: release the synchronous setup guard immediately. The// task (if any) keeps running in the tracker.- if (sendScope === sendScopeGeneration.current) {- agentSendInFlightRef.current = false- setAgentSending(false)- }+ releaseSendSetup()}},[selectedAgent,+ isHostAccessRevoked,+ isChatDeleted,+ revokeHostAccess,activeChatId,composerImageAttachments,composerReferenceAttachments,@@ -3178,6 +3364,7 @@ export function useAgentChatController({isRemote?: boolean} = {}) => {+ if (isHostAccessRevoked(agentName) || (chatId && isChatDeleted(agentName, chatId))) returnif (options.selectLatest) {writePendingSelection(agentName, { mode: 'latest', chatId: null })return@@ -3209,7 +3396,14 @@ export function useAgentChatController({upsertProvisionalEntry(chatId, options.title, options.isRemote === true)}},- [cancelOlderMessagesLoad, currentTeamId, writePendingSelection, upsertProvisionalEntry]+ [+ cancelOlderMessagesLoad,+ currentTeamId,+ writePendingSelection,+ upsertProvisionalEntry,+ isHostAccessRevoked,+ isChatDeleted,+ ])const clearActiveChat = useCallback(() => {diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 2620728fe..41f0bd2d5 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -3,6 +3,7 @@ import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'import { agentChatPlaceholder, remotePlaceholder } from '@lib/chatTitle'import { type PendingRename, resolveSessionTitle } from '@lib/resolveSessionTitle'import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'+import { isAuthorizationError, isConfirmedHostAccessRevoked } from '../../lib/format'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import type { useChatStore } from '../useChatStore'import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from './sessionFsm'@@ -100,6 +101,8 @@ interface UseChatListControllerParams {chatStore: ReturnType<typeof useChatStore>fsm: SessionFsmStorehost: MutableRefObject<ChatListControllerHost | null>+ isHostAccessRevoked: (agentRef: string) => boolean+ onHostAccessRevoked: (agentRef: string) => void}function sortableTimestamp(value: string): number {@@ -162,6 +165,8 @@ export function useChatListController({chatStore,fsm,host,+ isHostAccessRevoked,+ onHostAccessRevoked,}: UseChatListControllerParams) {// Per-agent list for the SELECTED agent (the sidebar's chat list).const [chatList, setChatList] = useState<SidebarChatEntry[]>([])@@ -178,7 +183,9 @@ export function useChatListController({const suppressAutoSelectionSequenceRef = useRef(0)const chatListNextCursorByAgentRef = useRef<Record<string, string | null | undefined>>({})const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())+ const deletedChatIdsByAgentRef = useRef(new Map<string, Set<string>>())const requestGenerationRef = useRef(0)+ const authorityScopeGenerationRef = useRef(0)// Spec 15 §2.5 (B21) — pending-rename queue. A user rename is optimistic-local// first, then synced by RPC; while unconfirmed the local title wins over the@@ -229,6 +236,8 @@ export function useChatListController({useEffect(() => {requestGenerationRef.current += 1+ authorityScopeGenerationRef.current += 1+ deletedChatIdsByAgentRef.current.clear()}, [isAuthenticated, scopeKey])// R1-H1 — the pending-rename queue is per-USER identity. mcp-host keys a chat@@ -269,14 +278,27 @@ export function useChatListController({// ─── Cross-agent latest-sessions mutators ───- const upsertLatestChatSession = useCallback((agentRef: string, chat: SidebarChatEntry) => {- setLatestChatSessions(previous => {- const next = [- { ...chat, agentRef },- ...previous.filter(item => item.agentRef !== agentRef || item.id !== chat.id),- ]- return next.sort(byUpdatedDesc)- })+ const upsertLatestChatSession = useCallback(+ (agentRef: string, chat: SidebarChatEntry) => {+ if (+ isHostAccessRevoked(agentRef) ||+ deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id)+ )+ return+ setLatestChatSessions(previous => {+ if (deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id)) return previous+ const next = [+ { ...chat, agentRef },+ ...previous.filter(item => item.agentRef !== agentRef || item.id !== chat.id),+ ]+ return next.sort(byUpdatedDesc)+ })+ },+ [isHostAccessRevoked]+ )++ const hideAgent = useCallback((agentRef: string) => {+ setLatestChatSessions(previous => previous.filter(chat => chat.agentRef !== agentRef))}, [])const removeLatestChatSession = useCallback((agentRef: string, chatId: string) => {@@ -292,29 +314,48 @@ export function useChatListController({agentRef: string,requestGeneration: number): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {+ const authorityScopeGeneration = authorityScopeGenerationRef.currentchatListNextCursorByAgentRef.current[agentRef] = nullif (selectedAgentRef.current === agentRef) {setChatListHasMoreRemoteSessions(false)setChatListMoreLoading(chatListLoadingMoreByAgentRef.current.has(agentRef))}const index = await chatStore.getIndex(agentRef)- const merged = [...index.chats].sort(byUpdatedDesc)if (selectedAgentRef.current !== agentRef ||- requestGenerationRef.current !== requestGeneration+ requestGenerationRef.current !== requestGeneration ||+ isHostAccessRevoked(agentRef)) {- return { index, merged }+ return { index, merged: [...index.chats].sort(byUpdatedDesc) }}+ const deleted = deletedChatIdsByAgentRef.current.get(agentRef) ?? new Set<string>()+ for (const chatId of index.deletedChatIds ?? []) deleted.add(chatId)+ deletedChatIdsByAgentRef.current.set(agentRef, deleted)+ const merged = index.chats.filter(chat => !deleted.has(chat.id)).sort(byUpdatedDesc)setChatList(merged)const suppressionMarkerAtRequest = suppressAutoSelectionByAgentRef.current.get(agentRef)scheduleAfterFirstPaint(async () => {- const serverResult = await chatStore- .listSessions(agentRef, { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT })- .catch((): SessionsListResult => ({ items: [] }))+ let serverResult: SessionsListResult+ try {+ serverResult = await chatStore.listSessions(agentRef, {+ agent: agentRef,+ limit: SESSION_CATALOG_PAGE_LIMIT,+ })+ } catch (error) {+ if (+ isAuthorizationError(error) &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(agentRef)+ ) {+ onHostAccessRevoked(agentRef)+ }+ return+ }if (selectedAgentRef.current !== agentRef ||- requestGenerationRef.current !== requestGeneration+ requestGenerationRef.current !== requestGeneration ||+ isHostAccessRevoked(agentRef)) {if (suppressionMarkerAtRequest !== undefined &&@@ -329,7 +370,10 @@ export function useChatListController({// older hosts and malformed proxy responses so another agent's catalog// entry can never leak into the selected agent's sidebar.const serverSessions = serverResult.items- .filter(s => s.agent === agentRef)+ .filter(+ s =>+ s.agent === agentRef && !deletedChatIdsByAgentRef.current.get(agentRef)?.has(s.chatId)+ ).sort(byLastActivityDesc)chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? nullsetChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))@@ -344,8 +388,14 @@ export function useChatListController({// "Remote ·" label, no isRemote branch; switchToChat's unified path// hydrates them.setChatList(previous => {- const dedupedPrevious = dedupeSidebarChats(previous)- const serverById = new Map(serverSessions.map(s => [s.chatId, s]))+ if (isHostAccessRevoked(agentRef)) return []+ const visibleSessions = serverSessions.filter(+ session => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)+ )+ 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@@ -364,7 +414,7 @@ export function useChatListController({})// 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[] = serverSessions+ const fromServerOnly: SidebarChatEntry[] = visibleSessions.filter(s => !knownIds.has(s.chatId)).map(s => ({id: s.chatId,@@ -434,7 +484,14 @@ export function useChatListController({return { index, merged }},- [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]+ [+ chatStore.getIndex,+ chatStore.listSessions,+ chatStore.reconcileServerSessions,+ fsm,+ isHostAccessRevoked,+ onHostAccessRevoked,+ ])const loadMoreChatSessions = useCallback(async () => {@@ -450,6 +507,7 @@ export function useChatListController({chatListLoadingMoreByAgentRef.current.add(agentRef)const requestGeneration = requestGenerationRef.current+ const authorityScopeGeneration = authorityScopeGenerationRef.currentsetChatListMoreLoading(true)try {let serverResult: SessionsListResult@@ -460,6 +518,14 @@ export function useChatListController({{ force: true })} catch (error) {+ if (+ isAuthorizationError(error) &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(agentRef)+ ) {+ onHostAccessRevoked(agentRef)+ return+ }if (requestGenerationRef.current === requestGeneration &&selectedAgentRef.current === agentRef@@ -475,15 +541,23 @@ export function useChatListController({}if (requestGenerationRef.current !== requestGeneration) return- const serverSessions = serverResult.items.filter(s => s.agent === agentRef)- if (selectedAgentRef.current !== agentRef) return+ const serverSessions = serverResult.items.filter(+ s => s.agent === agentRef && !deletedChatIdsByAgentRef.current.get(agentRef)?.has(s.chatId)+ )+ if (selectedAgentRef.current !== agentRef || isHostAccessRevoked(agentRef)) returnchatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? nullsetChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))seedSessionSnapshots(fsm, agentRef, serverSessions)setChatList(previous => {- const dedupedPrevious = dedupeSidebarChats(previous)- const serverById = new Map(serverSessions.map(s => [s.chatId, s]))+ if (isHostAccessRevoked(agentRef)) return []+ const visibleSessions = serverSessions.filter(+ session => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)+ )+ 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.@@ -500,7 +574,7 @@ export function useChatListController({return title === chat.title ? chat : { ...chat, title }})// Cases A/B (§2.2): server-only page entries.- const fromServerOnly: SidebarChatEntry[] = serverSessions+ const fromServerOnly: SidebarChatEntry[] = visibleSessions.filter(s => !knownIds.has(s.chatId)).map(s => ({id: s.chatId,@@ -534,7 +608,13 @@ export function useChatListController({setChatListMoreLoading(false)}}- }, [chatStore.listSessions, chatStore.reconcileServerSessions, fsm])+ }, [+ chatStore.listSessions,+ chatStore.reconcileServerSessions,+ fsm,+ isHostAccessRevoked,+ onHostAccessRevoked,+ ])const loadChatList = useCallback(async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] } | null> => {@@ -642,10 +722,14 @@ export function useChatListController({* just refresh the title on the existing entry.*/const upsertHydratedEntry = useCallback((meta: ChatMetadata, title: string) => {+ const agentRef = selectedAgentRef.current+ if (agentRef && deletedChatIdsByAgentRef.current.get(agentRef)?.has(meta.id)) returnsetChatList(prev =>- prev.some(c => c.id === meta.id)- ? prev.map(c => (c.id === meta.id ? { ...c, ...meta, title, remote: false } : c))- : [...prev, { ...meta, title }]+ agentRef && deletedChatIdsByAgentRef.current.get(agentRef)?.has(meta.id)+ ? prev+ : prev.some(c => c.id === meta.id)+ ? prev.map(c => (c.id === meta.id ? { ...c, ...meta, title, remote: false } : c))+ : [...prev, { ...meta, title }])}, [])@@ -679,7 +763,9 @@ export function useChatListController({/** Append a freshly-created chat to both lists (create / send auto-create). */const appendNewEntry = useCallback((agentRef: string, meta: ChatMetadata) => {+ if (deletedChatIdsByAgentRef.current.get(agentRef)?.has(meta.id)) returnsetChatList(prev => {+ if (deletedChatIdsByAgentRef.current.get(agentRef)?.has(meta.id)) return prevconst next = prev.some(chat => chat.id === meta.id) ? prev : [...prev, meta]return dedupeSidebarChats(next)})@@ -713,6 +799,11 @@ export function useChatListController({const clearPendingSelection = useCallback((agentName: string) => {delete pendingChatSelectionByAgentRef.current[agentName]}, [])+ const isChatDeleted = useCallback(+ (agentRef: string, chatId: string) =>+ deletedChatIdsByAgentRef.current.get(agentRef)?.has(chatId) ?? false,+ []+ )// ─── Chat CRUD ───@@ -795,6 +886,7 @@ export function useChatListController({if (entry.sending) returnif (pendingRenamesRef.current.get(key) !== entry) returnentry.sending = true+ const authorityScopeGeneration = authorityScopeGenerationRef.currenttry {await chatStore.renameSession(entry.agentRef, entry.chatId, entry.title)// Only clear if this attempt still owns the key (a stale 200 must never@@ -803,6 +895,42 @@ export function useChatListController({pendingRenamesRef.current.delete(key)}} catch (error) {+ if (+ isConfirmedHostAccessRevoked(error) &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(entry.agentRef)+ ) {+ onHostAccessRevoked(entry.agentRef)+ if (pendingRenamesRef.current.get(key) === entry) {+ pendingRenamesRef.current.delete(key)+ }+ return+ }+ if (+ isAuthorizationError(error) &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(entry.agentRef)+ ) {+ try {+ await chatStore.listSessions(+ entry.agentRef,+ { agent: entry.agentRef, limit: 1 },+ { force: true }+ )+ } catch (readError) {+ if (+ isAuthorizationError(readError) &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(entry.agentRef)+ ) {+ onHostAccessRevoked(entry.agentRef)+ if (pendingRenamesRef.current.get(key) === entry) {+ pendingRenamesRef.current.delete(key)+ }+ return+ }+ }+ }// A newer rename superseded this one: leave the key entirely to it — no// rollback, no re-mark (FIX 2).if (pendingRenamesRef.current.get(key) !== entry) return@@ -844,7 +972,7 @@ export function useChatListController({entry.sending = false}},- [chatStore, applyLocalTitleOnly, host]+ [chatStore, applyLocalTitleOnly, host, isHostAccessRevoked, onHostAccessRevoked])/**@@ -961,10 +1089,13 @@ export function useChatListController({// FIRST (before the delete), preserving the ack-before-delete ordering.host.current?.dispatchSession(deletedKey, { type: 'CHAT_DELETED' })await chatStore.deleteChat(agentRef, chatId)+ const deleted = deletedChatIdsByAgentRef.current.get(agentRef) ?? new Set<string>()+ deleted.add(chatId)+ deletedChatIdsByAgentRef.current.set(agentRef, deleted)chatStore.clearCachedRemoteData()- if (requestGenerationRef.current !== requestGeneration) returnhost.current?.clearComposerDraft(chatId)removeLatestChatSession(agentRef, chatId)+ if (requestGenerationRef.current !== requestGeneration) return// Post-await guards read the LIVE committed values (selectedAgentRef /// getActiveChatId), intentionally — if the user switched agent during the// delete IPC we must not yank a reselection into the agent they just left.@@ -1008,6 +1139,7 @@ export function useChatListController({}let cancelled = false+ const authorityScopeGeneration = authorityScopeGenerationRef.currentsetLatestChatSessionsLoading(true);(async () => {try {@@ -1021,17 +1153,33 @@ export function useChatListController({...chat,agentRef,})),+ deletedChatIds: index.deletedChatIds ?? [],}} catch {return {agentRef,entries: [] as LatestSidebarChatEntry[],+ deletedChatIds: [] as string[],}}}))if (cancelled) return- setLatestChatSessions(localGroups.flatMap(group => group.entries).sort(byUpdatedDesc))+ for (const group of localGroups) {+ const deleted = deletedChatIdsByAgentRef.current.get(group.agentRef) ?? new Set<string>()+ for (const chatId of group.deletedChatIds) deleted.add(chatId)+ deletedChatIdsByAgentRef.current.set(group.agentRef, deleted)+ }+ setLatestChatSessions(+ localGroups+ .flatMap(group => group.entries)+ .filter(+ chat =>+ !isHostAccessRevoked(chat.agentRef) &&+ !deletedChatIdsByAgentRef.current.get(chat.agentRef)?.has(chat.id)+ )+ .sort(byUpdatedDesc)+ )setLatestChatSessionsLoading(false)const sessionGroups = await Promise.all(@@ -1039,47 +1187,82 @@ export function useChatListController({// This feeds only the cross-agent sidebar preview. Do not follow// cursors here; the selected-agent session list exposes explicit// on-demand pagination through `loadMoreChatSessions`.- const serverResult: SessionsListResult = await chatStore- .listSessions(agentRef, {+ let serverResult: SessionsListResult+ try {+ serverResult = await chatStore.listSessions(agentRef, {agent: agentRef,limit: SESSION_CATALOG_PAGE_LIMIT,})- .catch((): SessionsListResult => ({ items: [] }))+ } catch (error) {+ if (+ isAuthorizationError(error) &&+ !cancelled &&+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ !isHostAccessRevoked(agentRef)+ ) {+ onHostAccessRevoked(agentRef)+ }+ return { agentRef, sessions: [] as SessionsListResult['items'] }+ }return {agentRef,- sessions: serverResult.items.filter(session => session.agent === agentRef),+ sessions: serverResult.items.filter(+ session =>+ session.agent === agentRef &&+ !isHostAccessRevoked(agentRef) &&+ !deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)+ ),}}))if (cancelled) returnfor (const group of sessionGroups) {- seedSessionSnapshots(fsm, group.agentRef, group.sessions)+ if (isHostAccessRevoked(group.agentRef)) continue+ seedSessionSnapshots(+ fsm,+ group.agentRef,+ group.sessions.filter(+ session => !deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId)+ )+ )}setLatestChatSessions(previous => {const serverByKey = new Map<string, SessionsListResult['items'][number]>()for (const group of sessionGroups) {+ if (isHostAccessRevoked(group.agentRef)) continuefor (const session of group.sessions) {+ if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))+ continueserverByKey.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.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),+ const reconciled = previous+ .filter(+ item =>+ !isHostAccessRevoked(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 }})- return title === item.title ? item : { ...item, title }- })const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))const remoteOnly: LatestSidebarChatEntry[] = []for (const group of sessionGroups) {+ if (isHostAccessRevoked(group.agentRef)) continuefor (const session of group.sessions) {+ if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))+ continueconst key = `${group.agentRef}:${session.chatId}`if (knownKeys.has(key)) continueknownKeys.add(key)@@ -1108,7 +1291,14 @@ export function useChatListController({flushPendingRenamesRef.current(new Set(sessionGroups.flatMap(group =>- group.sessions.map(session => `${group.agentRef}:${session.chatId}`)+ isHostAccessRevoked(group.agentRef)+ ? []+ : group.sessions+ .filter(+ session =>+ !deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId)+ )+ .map(session => `${group.agentRef}:${session.chatId}`))))@@ -1130,6 +1320,8 @@ export function useChatListController({loadMenuData,scopeKey,fsm,+ isHostAccessRevoked,+ onHostAccessRevoked,])return {@@ -1140,6 +1332,7 @@ export function useChatListController({chatListHasMoreRemoteSessions,latestChatSessions,latestChatSessionsLoading,+ hideAgent,// CRUD (public contract).handleCreateChat,handleRenameChat,@@ -1166,5 +1359,6 @@ export function useChatListController({readPendingSelection,writePendingSelection,clearPendingSelection,+ isChatDeleted,}}diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 99965d61f..14a0e3bc5 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -306,6 +306,22 @@ export function useAppController() {(agentName: string) => agentsData.agentDisplayByName[agentName] ?? agentName,[agentsData.agentDisplayByName])+ const revokedAgentRefsRef = useRef(new Set<string>())+ const isHostAccessRevoked = useCallback(+ (agentRef: string) => revokedAgentRefsRef.current.has(agentRef),+ []+ )+ useEffect(() => {+ revokedAgentRefsRef.current.clear()+ }, [authenticatedPrincipalIdentity, currentTeamId])+ const onHostAccessRevoked = useCallback(+ (agentRef: string) => {+ revokedAgentRefsRef.current.add(agentRef)+ if (nav.selectedAgent === agentRef) nav.setSelectedAgent(null)+ void agentsData.refresh()+ },+ [agentsData.refresh, nav.selectedAgent, nav.setSelectedAgent]+ )const chat = useAgentChatController({selectedAgent: nav.selectedAgent,agentNames: agentsData.agentNames,@@ -322,6 +338,8 @@ export function useAppController() {showDesktopNotification: notificationSettings.showDesktopNotification,openAgentConversationFromNotification,decideApprovalFromNotification,+ onHostAccessRevoked,+ isHostAccessRevoked,})// §4.7.4: the ONE central approval-decision function, bound to the chat@@ -597,7 +615,10 @@ export function useAppController() {useEffect(() => {if (!auth.isAuthenticated) returnif (agentsData.accessCatalog && nav.selectedAgent) {- if (!agentsData.agentNames.includes(nav.selectedAgent)) {+ if (+ !agentsData.agentNames.includes(nav.selectedAgent) ||+ isHostAccessRevoked(nav.selectedAgent)+ ) {nav.setSelectedAgent(null)}}@@ -607,6 +628,7 @@ export function useAppController() {auth.isAuthenticated,nav.selectedAgent,nav.setSelectedAgent,+ isHostAccessRevoked,])const switchTeamForWorkspace = useCallback(diff --git a/desktop-app/ui/src/lib/format.ts b/desktop-app/ui/src/lib/format.tsindex 37942b9ae..693352c5a 100644--- a/desktop-app/ui/src/lib/format.ts+++ b/desktop-app/ui/src/lib/format.ts@@ -158,23 +158,48 @@ function errorText(err: unknown): string {return (err instanceof Error ? err.message : String(err)).toLowerCase()}-/**- * True when an error reflects an HTTP 404 (the server doesn't know a chat the- * local cache references). Used by the D.4 reconcile to evict a stale local- * chat — which is destructive, so we require the 404 status token specifically- * rather than a generic "not found" substring (a "host/agent not found"- * transport error must NOT evict the user's cache).- */+/** IPC preserves error messages but not always custom status fields. */+function httpErrorStatus(err: unknown): number | undefined {+ if (err && typeof err === 'object') {+ const status = (err as { status?: unknown; cause?: { status?: unknown } }).status+ if (typeof status === 'number') return status+ const causeStatus = (err as { cause?: { status?: unknown } }).cause?.status+ if (typeof causeStatus === 'number') return causeStatus+ }+ // ApiError puts the response status before the body. Using the first token+ // keeps a 503 body that mentions 403 from becoming a revocation signal.+ const match = /\b([1-5]\d{2})\b/.exec(errorText(err))+ return match ? Number(match[1]) : undefined+}++/** A transcript 404 is ambiguous: absence, authority and wake failure share it. */export function isHttp404(err: unknown): boolean {- const value = errorText(err)+ return httpErrorStatus(err) === 404+}++/** Only an explicit authorization status can revoke the visible chat scope. */+export function isAuthorizationError(err: unknown): boolean {+ const status = httpErrorStatus(err)+ return status === 401 || status === 403+}++export function isHttp403(err: unknown): boolean {+ return httpErrorStatus(err) === 403+}++/** Exact Host-wide denial projected by the trusted Desktop RPC client. */+export function isConfirmedHostAccessRevoked(err: unknown): boolean {return (- /\b404\b/.test(value) || value.includes('chat not found') || value.includes('session not found')+ httpErrorStatus(err) === 403 &&+ /(?:^|error: )(?:403 forbidden: host_access_revoked|rename session failed \(403\): host_access_revoked)$/.test(+ errorText(err)+ ))}/**- * True when an error reflects a transport/connectivity failure rather than a- * server-side rejection. The D.4 reconcile stays in offline mode on these.+ * True when a transcript read failed without an authority decision. The+ * reconcile keeps the cached conversation while these errors recover.*/export function isNetworkError(err: unknown): boolean {const value = errorText(err)@@ -184,7 +209,8 @@ export function isNetworkError(err: unknown): boolean {value.includes('network') ||value.includes('fetch failed') ||value.includes('econnrefused') ||- value.includes('failed to fetch')+ value.includes('failed to fetch') ||+ [502, 503, 504].includes(httpErrorStatus(err) ?? 0))}diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex cf00311fa..961897acb 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.351",+ "version": "0.1.352","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.351",+ "version": "0.1.352","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 73798aa7e..e0a845ff6 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.351",+ "version": "0.1.352","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/statelessLifecycle.types.ts b/host-context-controller/src/statelessLifecycle.types.tsindex 70a3d8cff..ffeeb016a 100644--- a/host-context-controller/src/statelessLifecycle.types.ts+++ b/host-context-controller/src/statelessLifecycle.types.ts@@ -8,13 +8,14 @@ import { HostCondition, HostLifecycleState, HostLifecycleStatus } from './types'/*** Effective lifecycle of a Host after the reconcile-time rejection checks.- * `stateless` is false when spec.lifecycle.stateless is off OR a rejection- * applies (legacy force-always-on CommunicationChannel policy, spec.desktop- * present, unsatisfiable SharedFileSystem co-location).+ * `stateless` is false when spec.lifecycle.stateless is off OR a confirmed+ * incompatibility applies. Cache uncertainty keeps the stateless runtime+ * identity but blocks suspension until channel authority returns.*/export interface EffectiveHostLifecycle {stateless: booleanstate: HostLifecycleState+ suspensionBlocked?: boolean}/** Reconcile-time lifecycle assessment: effective mode + durable status + condition. */diff --git a/host-context-controller/src/statelessLifecycleExecutor.ts b/host-context-controller/src/statelessLifecycleExecutor.tsindex f731391ca..1551fbc10 100644--- a/host-context-controller/src/statelessLifecycleExecutor.ts+++ b/host-context-controller/src/statelessLifecycleExecutor.ts@@ -218,13 +218,12 @@ export class StatelessLifecycleExecutor {return { stateless: false, state: 'active' }}const hasCommunicationChannels = this.countCommunicationChannels(host.name) > 0- if (- !this.isCommunicationChannelCacheSynced() ||- host.spec.desktop !== undefined ||- hasCommunicationChannels- ) {+ if (host.spec.desktop !== undefined || hasCommunicationChannels) {return { stateless: false, state: 'active' }}+ if (!this.isCommunicationChannelCacheSynced()) {+ return { stateless: true, state: 'active', suspensionBlocked: true }+ }return { stateless: true, state: host.status?.lifecycle?.state ?? 'active' }}@@ -234,10 +233,6 @@ export class StatelessLifecycleExecutor {} {const reasons: string[] = []const messages: string[] = []- if (!this.isCommunicationChannelCacheSynced()) {- reasons.push(COMMUNICATION_CHANNEL_CACHE_UNSYNCED_REASON)- messages.push(COMMUNICATION_CHANNEL_CACHE_UNSYNCED_MESSAGE)- }const ccCount = this.countCommunicationChannels(hostName)if (ccCount > 0) {// Addendum 6 (operator visibility): the rejection message names both the@@ -321,6 +316,10 @@ export class StatelessLifecycleExecutor {}}+ if (!this.isCommunicationChannelCacheSynced()) {+ return this.holdActiveDuringChannelCacheRecovery(wakeHandledGeneration)+ }+// Accepted: preserve the durable state from the CRD status — a suspended// Host must survive HCC restarts and periodic resyncs.const state = host.status?.lifecycle?.state ?? 'active'@@ -351,13 +350,33 @@ export class StatelessLifecycleExecutor {}}+ /** Unknown channel inventory blocks suspension without changing the runtime template. */+ private holdActiveDuringChannelCacheRecovery(+ wakeHandledGeneration: number+ ): HostLifecycleAssessment {+ return {+ effective: { stateless: true, state: 'active', suspensionBlocked: true },+ lifecycle: {+ state: 'active',+ wakeHandledGeneration,+ reason: COMMUNICATION_CHANNEL_CACHE_UNSYNCED_MESSAGE,+ },+ condition: {+ type: STATELESS_REJECTED_CONDITION_TYPE,+ status: 'False',+ reason: COMMUNICATION_CHANNEL_CACHE_UNSYNCED_REASON,+ message: COMMUNICATION_CHANNEL_CACHE_UNSYNCED_MESSAGE,+ },+ pullPolicyCondition: statelessPullPolicyCondition(config.hostImage),+ }+ }+/*** Close the interval between the initial lifecycle assessment and the* Deployment write. Reconciliation performs several Kubernetes operations- * in between; if the CommunicationChannel watch ends or a channel starts- * referencing this Host during that interval, an assessment that was safe- * when computed must not still scale the Host to zero or leave it on the- * stateless runtime template.+ * in between; if the CommunicationChannel watch ends, retain the stateless+ * template but hold the Host active. A confirmed channel still applies the+ * established incompatible-mode policy.** This synchronous cache check adds no Kubernetes API calls to steady state.*/@@ -371,6 +390,9 @@ export class StatelessLifecycleExecutor {const { reasons, messages } = this.communicationChannelPolicyRejection(hostName)if (reasons.length === 0) {+ if (!this.isCommunicationChannelCacheSynced() && !assessment.effective.suspensionBlocked) {+ return this.holdActiveDuringChannelCacheRecovery(assessment.lifecycle.wakeHandledGeneration)+ }return assessment}const message = messages.join('; ')@@ -575,44 +597,19 @@ export class StatelessLifecycleExecutor {freshLifecycle?.wakeHandledGeneration ?? 0)const cachedState = host.status?.lifecycle?.state ?? 'active'- // A rejection is an INTENDED reason override even when it does not- // change state. The reject/kill-switch path sets- // assessment.lifecycle = { state:'active', reason:<rejection message> }- // with condition.status='True' (StatelessEnableRejected). When the- // Host is ALREADY active a first-ever/steady rejection has- // assessment.state ('active') === cachedState ('active'), so the plain- // state-diff discriminator would route it to the ECHO branch, which- // re-sources reason via isHeartbeatManagedLifecycleReason and DROPS the- // rejection message (not heartbeat-managed) — silently losing the- // rejection explanation the CRD documents. Detect it via the condition- // transitioning to Rejected:True so the rejection reason is stamped on- // the fresh state instead of folded into the heartbeat-managed-only- // echo. (StatelessDisabled kill-switch carries status:'False' and no- // lifecycle reason, so it never trips this branch.)- const assessmentIsRejection = assessment.condition.status === 'True'+ // Confirmed rejection and channel-cache uncertainty both require an+ // active state and an explanatory reason, even when the cached state+ // was already active. A state-only discriminator would treat that+ // reason as an echo and drop it; it could also preserve a fresh drain+ // decision made just before the cache lost authority.+ const assessmentForcesActive =+ assessment.condition.status === 'True' || assessment.effective.suspensionBlocked === trueconst assessmentIntendsStateOverride = assessment.lifecycle.state !== cachedStatelet lifecycle: HostLifecycleStatus- if (assessmentIntendsStateOverride) {- // The assessment DIFFERS from the cached snapshot's state: it- // INTENDED a transition (kill-switch/rejection forcing active over a- // suspended snapshot, or a resolveWakeBeforeScaleDown wake- // transition). That override wins; only wakeHandledGeneration stays- // monotonic against fresh.+ if (assessmentIntendsStateOverride || assessmentForcesActive) {+ // The assessment requires a transition or forces active by policy.+ // Only wakeHandledGeneration is sourced monotonically from fresh.lifecycle = { ...assessment.lifecycle, wakeHandledGeneration }- } else if (assessmentIsRejection) {- // Reject-while-active: state does not change, but the assessment's- // rejection reason is an INTENDED override. Keep state from FRESH- // (never reintroduce the 8th costume — a heartbeat suspend/wake that- // landed since the snapshot must still be preserved) and stamp the- // rejection reason onto it instead of dropping it into the- // heartbeat-managed-only echo.- lifecycle = {- state: freshLifecycle?.state ?? 'active',- wakeHandledGeneration,- ...(assessment.lifecycle.reason !== undefined- ? { reason: assessment.lifecycle.reason }- : {}),- }} else {// The assessment's state was a pass-through ECHO of the cached// snapshot — prefer the FRESH durable state and the heartbeat-managed@@ -672,6 +669,11 @@ export class StatelessLifecycleExecutor {return this.effectiveLifecycleFromCache(host)}+ private canSuspendFromCache(host: HostCRD): boolean {+ const lifecycle = this.effectiveLifecycleFromCache(host)+ return lifecycle.stateless && !lifecycle.suspensionBlocked+ }+/** Public view of the clerum.io/wake-requested generation parser. */getWakeRequestedGeneration(host: HostCRD): number {return this.wakeRequestedGeneration(host)@@ -788,10 +790,7 @@ export class StatelessLifecycleExecutor {// cache trails the API. Re-evaluate the complete effective stateless// policy from every fresh read/retry before honoring old heartbeat// evidence.- if (- !this.sameHostSpecRevision(host, fresh) ||- !this.effectiveLifecycleFromCache(fresh).stateless- ) {+ if (!this.sameHostSpecRevision(host, fresh) || !this.canSuspendFromCache(fresh)) {return { skip: true }}const freshLifecycle = fresh.status?.lifecycle@@ -1057,10 +1056,7 @@ export class StatelessLifecycleExecutor {const result = await this.patchStatusWithPrecondition(host,fresh => {- if (- !this.sameHostSpecRevision(host, fresh) ||- !this.effectiveLifecycleFromCache(fresh).stateless- ) {+ if (!this.sameHostSpecRevision(host, fresh) || !this.canSuspendFromCache(fresh)) {return { skip: true }}const freshLifecycle = fresh.status?.lifecycle@@ -1763,6 +1759,11 @@ export class StatelessLifecycleExecutor {host: HostCRD,assessment: HostLifecycleAssessment): Promise<HostLifecycleAssessment | null> {+ if (assessment.effective.suspensionBlocked) {+ // Cache authority loss intentionally forces active even when the fresh+ // durable state is suspended; there is no scale-down to validate.+ return assessment+ }if (!assessment.effective.stateless) {// Kill-switch/rejection assessments INTEND active+replicas:1 regardless// of the durable state — never second-guess them from fresh.diff --git a/host-context-controller/src/statelessLifecycleTracker.ts b/host-context-controller/src/statelessLifecycleTracker.tsindex d3c74c345..ae7d93a99 100644--- a/host-context-controller/src/statelessLifecycleTracker.ts+++ b/host-context-controller/src/statelessLifecycleTracker.ts@@ -438,6 +438,11 @@ export class StatelessLifecycleTracker implements HeartbeatLifecycleTracker {this.clearDrainGrace(hostRef)return { drain: false }}+ if (effective.suspensionBlocked) {+ this.clearDrainGrace(hostRef)+ await this.cancelDrainOnEvidence(hostRef, host)+ return { drain: false }+ }this.noteWakeHandledGeneration(hostRef, host)let wakePending =@@ -793,7 +798,8 @@ export class StatelessLifecycleTracker implements HeartbeatLifecycleTracker {)return}- if (!this.reconciler.getEffectiveLifecycle(host).stateless) {+ const effective = this.reconciler.getEffectiveLifecycle(host)+ if (!effective.stateless || effective.suspensionBlocked) {return}// KZ-R1: the informer-cached Host can be STALE here exactly as it is on thediff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex 3a177dce1..404ac4628 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -544,7 +544,7 @@ export interface HostLifecycleStatus {* Written by the mcp-host runtime; HCC only preserves it across writes.*/wakeHandledGeneration: number- /** Human-readable explanation when the stateless request was rejected. */+ /** Human-readable rejection or temporary suspension-block reason. */reason?: string}diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.tsindex d947e9601..a92d82a45 100644--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@ -297,7 +297,7 @@ describe('HostReconciler stateless lifecycle — buildDeployment replicas', () =})const dep = reconciler.buildDeployment(makeStatelessHost({ status: suspendedStatus() }))expect(dep.spec?.replicas).toBe(1)- expect(dep.spec?.template.spec?.priorityClassName).toBeUndefined()+ expect(dep.spec?.template.spec?.priorityClassName).toBe('clerum-interactive-host')})it('derives replicas=1 for stateless+active and stateless+draining', () => {@@ -737,22 +737,69 @@ describe('HostReconciler stateless lifecycle — env injection', () => {})describe('HostReconciler stateless lifecycle — rejection matrix', () => {- it('fails closed while the CommunicationChannel cache is unsynced', async () => {+ it('reconciles an active Host twice through cache loss without changing its session path or template', async () => {+ let cacheSynced = true+ const host = makeStatelessHost({+ status: { lifecycle: { state: 'active', wakeHandledGeneration: 2 } },+ })+ let serverHost = host+ const { reconciler, appsApi, customApi } = createReconciler({+ isCommunicationChannelCacheSynced: () => cacheSynced,+ })+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(serverHost))++ await reconciler.reconcile(host)+ const baseline = structuredClone(hostDeploymentBody(appsApi, host.name).spec?.template)+ expect(envValue(hostDeploymentBody(appsApi, host.name), 'CLERUM_SESSION_DB_DIR')).toBe(+ '/var/lib/clerum/state'+ )++ for (let cycle = 1; cycle <= 2; cycle++) {+ cacheSynced = false+ // Exercise the fresh-read race as well as the cached active state: a+ // suspend may have landed after the initial Host watch event.+ serverHost = makeStatelessHost({ status: suspendedStatus(2 + cycle) })+ appsApi.createNamespacedDeployment.mockClear()+ appsApi.replaceNamespacedDeployment.mockClear()+ await reconciler.reconcile(host)++ const deployment = hostDeploymentBody(appsApi, host.name)+ expect(deployment.spec?.replicas).toBe(1)+ expect(deployment.spec?.template).toEqual(baseline)+ expect(envValue(deployment, 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')+ expect(reconciler.getEffectiveLifecycle(host)).toMatchObject({+ stateless: true,+ state: 'active',+ suspensionBlocked: true,+ })+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(+ 'CommunicationChannelCacheUnsynced'+ )+ expect(lifecycleStatusWrites(customApi).at(-1)?.lifecycle?.state).toBe('active')+ cacheSynced = true+ }+ })++ it('keeps the stateless template active while the CommunicationChannel cache is unsynced', async () => {const { reconciler, appsApi, customApi } = createReconciler({isCommunicationChannelCacheSynced: () => false,})await reconciler.reconcile(makeStatelessHost({ status: suspendedStatus() }))- expect(hostDeploymentBody(appsApi, 'stateless-host').spec?.replicas).toBe(1)+ const deployment = hostDeploymentBody(appsApi, 'stateless-host')+ expect(deployment.spec?.replicas).toBe(1)+ expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')+ expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')+ expect(envValue(deployment, 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')const writes = lifecycleStatusWrites(customApi)expect(writes).toHaveLength(1)expect(writes[0].lifecycle?.state).toBe('active')const condition = rejectedCondition(writes[0])- expect(condition.status).toBe('True')+ expect(condition.status).toBe('False')expect(condition.reason).toContain('CommunicationChannelCacheUnsynced')})- it('fails closed when the channel cache becomes unsynced during reconciliation', async () => {+ it('preserves the stateless template when the channel cache becomes unsynced during reconciliation', async () => {let cacheSynced = trueconst { reconciler, appsApi, customApi, networkingApi } = createReconciler({isCommunicationChannelCacheSynced: () => cacheSynced,@@ -778,9 +825,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {)const deployment = hostDeploymentBody(appsApi, host.name)expect(deployment.spec?.replicas).toBe(1)- expect(containerEnv(deployment).map(entry => entry.name)).not.toContain(- 'CLERUM_STATELESS_LIFECYCLE'- )+ expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')+ expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')+ expect(envValue(deployment, 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')const writes = lifecycleStatusWrites(customApi)expect(writes).toHaveLength(2)expect(writes[0].lifecycle?.state).toBe('suspended')@@ -790,6 +837,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {reason: 'CommunicationChannel cache is not synchronized; stateless lifecycle is held active',})expect(rejectedCondition(writes[1]).reason).toBe('CommunicationChannelCacheUnsynced')+ expect(rejectedCondition(writes[1]).status).toBe('False')})it('fails closed when a channel starts referencing the Host during reconciliation', async () => {@@ -1076,9 +1124,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {expect(provision).toHaveBeenCalledOnce()const deployment = hostDeploymentBody(appsApi, host.name)expect(deployment.spec?.replicas).toBe(1)- expect(containerEnv(deployment).map(entry => entry.name)).not.toContain(- 'CLERUM_STATELESS_LIFECYCLE'- )+ expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')+ expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')+ expect(envValue(deployment, 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')})it('rejects stateless by default when CommunicationChannels reference the host', async () => {@@ -1742,15 +1790,12 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',})})- it('reject-while-active keeps state from FRESH (8th costume preserved): a suspend that landed is not resurrected', async () => {+ it('confirmed incompatibility restores active state after a concurrent suspend', async () => {const { reconciler, customApi } = createReconciler({countCommunicationChannels: () => 1,})- // Cached active, but a heartbeat suspend landed between the snapshot and- // the writer's fresh read (fresh = suspended, gen 5). The rejection reason- // is an intended override, but STATE must still come from fresh — the- // reject branch must NOT reintroduce the 8th costume by echoing the cached- // active state over a just-suspended Host.+ // A confirmed channel conflict has the existing always-on policy. If a+ // heartbeat suspended the Host during the fresh read, reconcile wakes it.const host = makeStatelessHost({status: { lifecycle: { state: 'active', wakeHandledGeneration: 3 } },})@@ -1762,7 +1807,7 @@ describe('HostReconciler stateless lifecycle — AP-1 fresh-read status writer',const writes = lifecycleStatusWrites(customApi)expect(writes.at(-1)?.lifecycle).toEqual({- state: 'suspended',+ state: 'active',wakeHandledGeneration: 5,reason:'1 CommunicationChannel(s) reference this Host; disassociate them to enable the requested stateless lifecycle',diff --git a/host-context-controller/test/statelessLifecycleTracker.test.ts b/host-context-controller/test/statelessLifecycleTracker.test.tsindex c6836057a..3d057643b 100644--- a/host-context-controller/test/statelessLifecycleTracker.test.ts+++ b/host-context-controller/test/statelessLifecycleTracker.test.ts@@ -174,6 +174,22 @@ describe('StatelessLifecycleTracker — D8 idle rule', () => {})})+ it('does not drain or suspend a stateless Host while channel authority is unavailable', async () => {+ const port = makePort()+ port.getEffectiveLifecycle.mockReturnValue({+ stateless: true,+ state: 'active',+ suspensionBlocked: true,+ })+ const tracker = makeTracker({ port })+ for (let cycle = 0; cycle < 2; cycle++) {+ expect(await tracker.handleHeartbeat(payload({ lastActivityTs: NOW - 10 * HOUR }))).toEqual({+ drain: false,+ })+ }+ expect(port.suspendHostFromHeartbeat).not.toHaveBeenCalled()+ })+it('answers drain:false for an unknown host', async () => {const port = makePort()const tracker = new StatelessLifecycleTracker({diff --git a/scripts/e2e/_lib/hcc-watch-api-proxy.mjs b/scripts/e2e/_lib/hcc-watch-api-proxy.mjsindex 31eca8cfb..c53ef402e 100644--- a/scripts/e2e/_lib/hcc-watch-api-proxy.mjs+++ b/scripts/e2e/_lib/hcc-watch-api-proxy.mjs@@ -46,7 +46,11 @@ export function validateCommand(command, allowedPaths) {} else if (command.action === 'release') {if (typeof command.pauseId !== 'string' || !/^[a-zA-Z0-9-]{1,80}$/.test(command.pauseId))throw new Error('invalid_pause_id')- } else if (command.action !== 'observe-bookmarks') throw new Error('invalid_control_action')+ } else if (command.action === 'hold-channel') {+ if (!Number.isInteger(command.durationMs) || command.durationMs < 1000 || command.durationMs > 60000)+ throw new Error('invalid_channel_hold_duration')+ } else if (command.action !== 'release-channel' && command.action !== 'observe-bookmarks')+ throw new Error('invalid_control_action')return command}@@ -60,12 +64,15 @@ export function createProxy({controlDir,periodMs,minAgeMs,+ channelPath,+ churnEnabled = true,}) {// CA bytes configure TLS trust only; they never enter the request or destination.const upstreamSecureContext = createSecureContext({ ca: upstreamCa })const streams = new Set()const bookmarks = createBookmarkObservation()let pause = null+ let channelHold = nulllet commandId = nulllet commandContent = nullconst writeRecord = (name, fields) => {@@ -83,6 +90,13 @@ export function createProxy({old.resume?.()acknowledge({ id: old.id, state: reason })}+ const finishChannelHold = reason => {+ if (!channelHold) return+ const held = channelHold+ channelHold = null+ clearTimeout(held.timer)+ writeRecord('channel-hold', { id: held.id, state: reason, rejected: held.rejected })+ }const server = https.createServer({ key, cert }, (request, response) => {const url = new URL(request.url, 'https://fixture.invalid')if (!request.url.startsWith('/') || request.url.startsWith('//')) {@@ -90,6 +104,12 @@ export function createProxy({return}const watch = url.searchParams.get('watch') === 'true'+ if (channelHold && request.method === 'GET' && url.pathname === channelPath) {+ channelHold.rejected+++ response.writeHead(503, { 'content-type': 'application/json' })+ response.end(JSON.stringify({ kind: 'Status', apiVersion: 'v1', status: 'Failure', reason: 'ServiceUnavailable', code: 503 }))+ return+ }const kind = url.pathname.endsWith('/mcpservers')? 'McpServer': url.pathname.endsWith('/contexts')@@ -188,6 +208,27 @@ export function createProxy({throw new Error('pause_not_held')finishPause('released')acknowledge({ id: command.id, state: 'released' })+ } else if (command.action === 'hold-channel') {+ if (!channelPath || channelHold) throw new Error('channel_hold_unavailable')+ let count = 0+ channelHold = {+ id: command.id,+ rejected: 0,+ timer: setTimeout(() => finishChannelHold('expired'), command.durationMs),+ }+ for (const stream of streams) {+ if (stream.watch && stream.request.method === 'GET' &&+ new URL(stream.request.url, 'https://fixture.invalid').pathname === channelPath) {+ stream.close()+ count+++ }+ }+ writeRecord('channel-hold', { id: command.id, state: 'held', cut: count, rejected: 0 })+ acknowledge({ id: command.id, state: 'held', count })+ } else if (command.action === 'release-channel') {+ if (!channelHold) throw new Error('channel_hold_not_active')+ finishChannelHold('released')+ acknowledge({ id: command.id, state: 'released' })} else if (command.action === 'observe-bookmarks') {writeRecord('bookmarks', bookmarks.finish())acknowledge({ id: command.id, state: 'observed' })@@ -210,15 +251,16 @@ export function createProxy({acknowledge({ id: observedId, state: 'rejected' })}}, 100)- const churn = setInterval(() => {+ const churn = churnEnabled ? setInterval(() => {if (fs.existsSync(`${controlDir}/paused`)) returnfor (const stream of streams)if (stream.watch && Date.now() - stream.born >= minAgeMs) stream.close()- }, periodMs)+ }, periodMs) : nullconst close = () => {clearInterval(poll)- clearInterval(churn)+ if (churn) clearInterval(churn)finishPause('shutdown')+ finishChannelHold('shutdown')for (const stream of streams) stream.close()server.close()}@@ -235,6 +277,8 @@ if (import.meta.main) {controlDir: '/churn-ctl',periodMs: Number(process.env.CHURN_PERIOD_MS),minAgeMs: Number(process.env.CHURN_MIN_AGE_MS),+ channelPath: process.env.CHANNEL_PATH,+ churnEnabled: process.env.CHURN_DISABLED !== '1',})proxy.server.listen(8443, '0.0.0.0')process.on('SIGTERM', proxy.close)diff --git a/scripts/e2e/_lib/hcc-watch-pr-a.sh b/scripts/e2e/_lib/hcc-watch-pr-a.shindex 0b24d121b..8cb517078 100755--- a/scripts/e2e/_lib/hcc-watch-pr-a.sh+++ b/scripts/e2e/_lib/hcc-watch-pr-a.sh@@ -15,7 +15,7 @@ hcc_pr_a_command() {pod="$(hcc_pr_a_proxy_pod)" || return 1HCC_PR_A_COMMAND_ID="${RUN_ID}-$(date +%s)-${RANDOM}"command="$(jq -cn --arg id "$HCC_PR_A_COMMAND_ID" --arg action "$action" --arg value "$value" \- '{id:$id,action:$action} + (if $action=="arm" then {path:$value,method:"GET",durationMs:25000} elif $action=="cut" then {kind:$value} elif $action=="release" then {pauseId:$value} else {} end)')"+ '{id:$id,action:$action} + (if $action=="arm" then {path:$value,method:"GET",durationMs:25000} elif $action=="cut" then {kind:$value} elif $action=="release" then {pauseId:$value} elif $action=="hold-channel" then {durationMs:($value|tonumber)} else {} end)')"printf '%s' "$command" | kctl exec -i "pod/$pod" -n "$HCC_NS" -c proxy -- node -e \'const fs=require("fs");const value=fs.readFileSync(0);fs.writeFileSync("/churn-ctl/next.json",value,{mode:384});fs.renameSync("/churn-ctl/next.json","/churn-ctl/command.json")'}@@ -24,7 +24,7 @@ hcc_pr_a_ack() {local state=$1 podpod="$(hcc_pr_a_proxy_pod)" || return 1kctl exec "pod/$pod" -n "$HCC_NS" -c proxy -- node -e \- 'const fs=require("fs");try{const a=JSON.parse(fs.readFileSync("/churn-ctl/ack.json"));if(a.id!==process.argv[1]||a.state!==process.argv[2]||(a.state==="cut"&&a.count<1))process.exit(1)}catch{process.exit(1)}' \+ 'const fs=require("fs");try{const a=JSON.parse(fs.readFileSync("/churn-ctl/ack.json"));if(a.id!==process.argv[1]||a.state!==process.argv[2]||((a.state==="cut"||a.state==="held")&&a.count<1))process.exit(1)}catch{process.exit(1)}' \"$HCC_PR_A_COMMAND_ID" "$state" >/dev/null 2>&1}@@ -386,15 +386,19 @@ hcc_pr_a_enable_proxy() {# Generated private material stays in this anonymous pipe, never an artifact.node "$HCC_PR_A_LIB/hcc-watch-tls-manifest.mjs" "$PROXY_NAME" "$HCC_NS" "$RUN_ID" \"$HCC_PR_A_LIB/hcc-watch-api-proxy.mjs" | kctl create -f - >/dev/null 2>&1 || die 'PR A TLS fixture creation failed'- patch="$(jq -cn --arg name "$PROXY_NAME" --arg paths "$paths" '{spec:{template:{spec:{+ patch="$(jq -cn --arg name "$PROXY_NAME" --arg paths "$paths" --arg channel_ns "${CHANNEL_NS:-channels}" \+ --argjson selective "${HCC_PR_A_SELECTIVE_CHANNEL:-0}" '{spec:{template:{spec:{securityContext:{fsGroup:1000}, containers:[{name:"proxy",command:["node","/fixture/proxy.mjs"],args:[],- env:[{name:"PAUSE_PATHS",value:$paths}],volumeMounts:[+ env:([{name:"PAUSE_PATHS",value:$paths},{name:"CHANNEL_PATH",value:("/apis/clerum.io/v1alpha1/namespaces/"+$channel_ns+"/communicationchannels")}] ++ (if $selective==1 then [{name:"CHURN_DISABLED",value:"1"}] else [] end)),volumeMounts:[{name:"fixture-code",mountPath:"/fixture",readOnly:true},{name:"fixture-tls",mountPath:"/fixture-tls",readOnly:true},- {name:"upstream-ca",mountPath:"/upstream-ca",readOnly:true}]}],+ {name:"upstream-ca",mountPath:"/upstream-ca",readOnly:true},+ {name:"churn-control",mountPath:"/churn-ctl"}]}],volumes:[{name:"fixture-code",configMap:{name:$name}},{name:"fixture-tls","secret":{secretName:$name,defaultMode:288}},- {name:"upstream-ca",configMap:{name:"kube-root-ca.crt"}}]}}}}')"+ {name:"upstream-ca",configMap:{name:"kube-root-ca.crt"}},+ {name:"churn-control",emptyDir:{}}]}}}}')"kctl patch deployment "$PROXY_NAME" -n "$HCC_NS" --type=strategic -p "$patch" >/dev/nullkctl rollout status deployment "$PROXY_NAME" -n "$HCC_NS" --timeout=60s >/dev/null || die 'PR A TLS proxy not Ready'}diff --git a/scripts/e2e/e2e-hcc-stateless-cache-containment.sh b/scripts/e2e/e2e-hcc-stateless-cache-containment.shnew file mode 100755index 000000000..ae46f512c--- /dev/null+++ b/scripts/e2e/e2e-hcc-stateless-cache-containment.sh@@ -0,0 +1,228 @@+#!/usr/bin/env bash+# Branch-owned live gate for #396. The TLS fixture cuts only the+# CommunicationChannel watch/list while forwarding all other Kubernetes API+# requests. A known conversation is created through rpc-proxy before the cut.+set -euo pipefail+umask 077+# shellcheck disable=SC2034 # Shared fixture helpers consume these globals.++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+# shellcheck source=scripts/e2e/e2e-lib.sh+source "${SCRIPT_DIR}/e2e-lib.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-fixture.sh+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-fixture.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-assertions.sh+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-assertions.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-logs.sh+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-logs.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-lock.sh+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"+# shellcheck source=scripts/e2e/_lib/hcc-watch-pr-a.sh+source "${SCRIPT_DIR}/_lib/hcc-watch-pr-a.sh"++die() { fail "$*"; exit 1; }+wait_until() {+ local timeout=$1 description=$2 elapsed=0+ shift 2+ while [ "$elapsed" -lt "$timeout" ]; do+ "$@" && return 0+ sleep 1+ elapsed=$((elapsed + 1))+ done+ echo "Timed out waiting for ${description}" >&2+ return 1+}++if [ -z "$E2E_KUBECONTEXT" ] || ! is_branch_scoped_e2e_context "$E2E_KUBECONTEXT"; then+ die 'select an explicit branch-scoped Minikube context'+fi+require_safe_kube_context+[ "${E2E_HCC_WATCH_FAULT_INJECTION:-0}" = 1 ] || die 'set E2E_HCC_WATCH_FAULT_INJECTION=1'+[ -n "${E2E_BRANCH_PROFILE_ENV:-}" ] && [ -r "$E2E_BRANCH_PROFILE_ENV" ] ||+ die 'provide E2E_BRANCH_PROFILE_ENV from the owned branch profile'+[ -n "${E2E_PROFILE_PORTS_ENV:-}" ] && [ -r "$E2E_PROFILE_PORTS_ENV" ] ||+ die 'provide E2E_PROFILE_PORTS_ENV from the owned branch profile'+require_branch_profile_urls "$E2E_KUBECONTEXT" "$E2E_PROFILE_PORTS_ENV" ||+ die 'profile URLs do not match the owned ports'+kctl get nodes -o json | jq -e --arg c "$E2E_KUBECONTEXT" \+ 'any(.items[]; .metadata.labels["minikube.k8s.io/name"]==$c)' >/dev/null ||+ die 'target is not the selected Minikube profile'++HCC_NS=control-plane HCC_DEPLOY=host-context-controller+HOST_NS=mcp-host MCP_NS=mcp-server CHANNEL_NS=channels+HOST_REF="${E2E_STATELESS_HOST_REF:-chatllm-stateless}"+RUN_ID="$(date +%s)-$$"+PROXY_NAME="$(truncate_rfc1123 "e2e-hcc-channel-${RUN_ID}")"+PROBE_NAME="$(truncate_rfc1123 "${PROXY_NAME}-negative-probe")"+PROXY_EGRESS_NP="$(truncate_rfc1123 "${PROXY_NAME}-api")"+HCC_PROXY_NP="$(truncate_rfc1123 "${PROXY_NAME}-from-hcc")"+PROBE_EGRESS_NP="$(truncate_rfc1123 "${PROXY_NAME}-from-probe")"+THREAD_ID="e2e-hcc-cache-${RUN_ID}"+MARKER="hcc-cache-${RUN_ID}"+START_TIME="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"+HCC_LOG_BUFFER="$(mktemp "${TMPDIR:-/tmp}/hcc-channel-log.XXXXXX")"+HCC_LOG_STREAM_PID=''+HCC_GATE_LOCK_ACQUIRED=0 HCC_GATE_LOCK_NAME='' HCC_GATE_LOCK_UID=''+HCC_GATE_FINALIZATION_FAILURE=''+HCC_PATCHED=0 PROXY_CREATED=0 PROBE_CREATED=0 HCC_PR_A_TLS_CREATED=0+HCC_UID='' HCC_RESTARTS=''+ORIGINAL_REPLICAS=''++cleanup() {+ local status=$? cleanup_failed=0 restore_ok=1+ set +e+ stop_hcc_recovery_log_stream+ if [ "$HCC_PATCHED" = 1 ]; then+ if hcc_pr_a_restore && kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" --timeout=180s >/dev/null; then+ HCC_PATCHED=0+ else+ restore_ok=0+ fi+ fi+ if [ "$restore_ok" = 1 ]; then+ [ "$PROXY_CREATED" = 0 ] || delete_hcc_proxy_fixture || cleanup_failed=1+ if [ "$HCC_PR_A_TLS_CREATED" = 1 ]; then+ kctl delete configmap "$PROXY_NAME" -n "$HCC_NS" --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || cleanup_failed=1+ kctl delete secret "$PROXY_NAME" -n "$HCC_NS" --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || cleanup_failed=1+ fi+ else+ cleanup_failed=1+ echo "HCC restoration failed; retained proxy ${HCC_NS}/${PROXY_NAME} on ${E2E_KUBECONTEXT}" >&2+ fi+ finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok" || cleanup_failed=1+ rm -f "$HCC_LOG_BUFFER" "${HCC_PR_A_CONFIG_SNAPSHOT:-}"+ [ "$cleanup_failed" = 0 ] || status=1+ print_results+ exit "$status"+}+trap cleanup EXIT++header 'Stateless Host containment during CommunicationChannel cache uncertainty'+require_branch_owned_hcc_gate+acquire_hcc_watch_gate_lock || die 'another HCC watch gate owns this profile'+ORIGINAL_REPLICAS="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o jsonpath='{.spec.replicas}')"+[ "$ORIGINAL_REPLICAS" = 1 ] || die 'HCC must have exactly one replica'+[ "$(kctl get host "$HOST_REF" -n "$HOST_NS" -o jsonpath='{.spec.lifecycle.stateless}')" = true ] ||+ die 'selected Host must request stateless lifecycle'++HCC_IMAGE="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o jsonpath='{.spec.template.spec.containers[?(@.name=="host-context-controller")].image}')"+[ -n "$HCC_IMAGE" ] || die 'could not resolve the running HCC image'+K8S_API_SERVICE_HOST="$(kctl exec deployment/"$HCC_DEPLOY" -n "$HCC_NS" -c host-context-controller -- printenv KUBERNETES_SERVICE_HOST)"+node -e 'process.exit(require("node:net").isIP(process.argv[1])===4?0:1)' "$K8S_API_SERVICE_HOST" ||+ die 'Kubernetes API service address is not IPv4'+K8S_API_CIDR="${K8S_API_SERVICE_HOST}/32"+hcc_pr_a_preflight+create_hcc_api_proxy+HCC_PR_A_SELECTIVE_CHANNEL=1 hcc_pr_a_enable_proxy+E2E_HCC_PR_A=1 verify_hcc_proxy_network_policy+HCC_PATCHED=1+kctl patch deployment "$HCC_DEPLOY" -n "$HCC_NS" --type=strategic -p "$(hcc_pr_a_redirect_patch)" >/dev/null+kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" --timeout=180s >/dev/null ||+ die 'HCC did not become Ready through selective TLS proxy'+read -r HCC_UID HCC_RESTARTS <<<"$(wait_for_hcc_identity 30)"+start_hcc_recovery_log_stream++EXT_BASE="${EXTERNAL_REST_API_BASE_URL%/}"+RPC_BASE="${RPC_PROXY_BASE_URL%/}"+DEV_EMAIL="${E2E_DEV_LOGIN_EMAIL:[email protected]}"+DEV_PASSWORD="${E2E_USER_PASSWORD:-${ADMIN_PASSWORD:-}}"+[ -n "$DEV_PASSWORD" ] || die 'E2E_USER_PASSWORD is required for the known-session proof'+curl -fsS -m 10 "${EXT_BASE}/health" >/dev/null || die 'external-rest-api unavailable'+curl -fsS -m 10 "${RPC_BASE}/health" >/dev/null || die 'rpc-proxy unavailable'+login="$(curl -fsS -m 20 -X POST "${EXT_BASE}/api/v1/auth/password-login" \+ -H 'Content-Type: application/json' -d "$(jq -cn --arg e "$DEV_EMAIL" --arg p "$DEV_PASSWORD" '{email:$e,password:$p}')")" ||+ die 'E2E user login failed'+SESSION_TOKEN="$(jq -er '.token' <<<"$login")" || die 'login returned no token'+mint_rpc_token() {+ local body+ body="$(curl -fsS -m 20 -X POST "${EXT_BASE}/api/v1/rpc/token" \+ -H "Authorization: Bearer ${SESSION_TOKEN}" -H 'Content-Type: application/json' \+ -d "$(jq -cn --arg host "$HOST_REF" '{hostRefs:[$host],scopes:["host:message:invoke","host:session:read","host:status:read","host:health:read"]}')")" || return 1+ RPC_TOKEN="$(jq -er '.token' <<<"$body")"+}+mint_rpc_token || die 'could not mint authorized RPC token'+message="$(jq -cn --arg content "Remember ${MARKER}." --arg thread "$THREAD_ID" '{content:$content,threadId:$thread}')"+baseline_accepted=0+for attempt in 1 2 3; do+ mint_rpc_token || die 'could not refresh authorized RPC token'+ response="$(curl -sS -m 120 -w '\n%{http_code}' -X POST "${RPC_BASE}/api/v1/rpc/hosts/${HOST_REF}/messages" \+ -H "Authorization: Bearer ${RPC_TOKEN}" -H 'Content-Type: application/json' -d "$message")" ||+ die 'baseline message through rpc-proxy failed'+ if [ "${response##*$'\n'}" = 200 ]; then+ baseline_accepted=1+ break+ fi+ if [ "$attempt" = 3 ] || [ "${response##*$'\n'}" != 503 ] ||+ ! jq -e '.code=="host_waking"' <<<"${response%$'\n'*}" >/dev/null; then+ die 'baseline message was not accepted'+ fi+ wait_until 90 'Host wake after retryable response' host_runtime_is_always_on "$HOST_REF" ||+ die 'Host did not wake after retryable response'+done+[ "$baseline_accepted" = 1 ] || die 'baseline message was not accepted'++session_visible() {+ local response status body+ mint_rpc_token || return 1+ response="$(curl -sS -m 30 -w '\n%{http_code}' \+ -H "Authorization: Bearer ${RPC_TOKEN}" \+ "${RPC_BASE}/api/v1/rpc/hosts/${HOST_REF}/sessions/${HOST_REF}/${THREAD_ID}/messages")" || return 1+ status="${response##*$'\n'}" body="${response%$'\n'*}"+ [ "$status" = 200 ] && jq -e --arg marker "$MARKER" \+ 'any(.turns[]?; .user_input|contains($marker))' <<<"$body" >/dev/null+}+session_listed() {+ local response status body+ mint_rpc_token || return 1+ response="$(curl -sS -m 30 -w '\n%{http_code}' \+ -H "Authorization: Bearer ${RPC_TOKEN}" \+ "${RPC_BASE}/api/v1/rpc/hosts/${HOST_REF}/sessions?agent=${HOST_REF}&limit=100")" || return 1+ status="${response##*$'\n'}" body="${response%$'\n'*}"+ [ "$status" = 200 ] && jq -e --arg thread "$THREAD_ID" --arg agent "$HOST_REF" \+ 'any(.items[]?; .chatId==$thread and .agent==$agent)' <<<"$body" >/dev/null+}+wait_until 30 'baseline session transcript' session_visible || die 'known session was not readable'+wait_until 30 'baseline session list' session_listed || die 'known session was not listed'+wait_until 90 'baseline active Host' host_runtime_is_always_on "$HOST_REF" ||+ die 'Host was not active before fault injection'+baseline="$(kctl get deployment "$HOST_REF" -n "$HOST_NS" -o json)"+baseline_template="$(jq -Sc '.spec.template' <<<"$baseline")"+baseline_pod="$(kctl get pods -n "$HOST_NS" -l "app=${HOST_REF}" -o json |+ jq -er '[.items[]|select(.metadata.deletionTimestamp==null)|select(any(.status.conditions[]?;.type=="Ready" and .status=="True"))]|if length==1 then .[0].metadata.uid else error("pod identity ambiguous") end')"+jq -e '[.spec.template.spec.containers[].env[]? | select(.name=="CLERUM_SESSION_DB_DIR" and .value=="/var/lib/clerum/state")]|length==1' <<<"$baseline" >/dev/null ||+ die 'baseline SQLite directory is not the stateless path'++cache_held_active() {+ local status deployment pod+ status="$(kctl get host "$HOST_REF" -n "$HOST_NS" -o json)" || return 1+ jq -e '[.status.conditions[]?|select(.type=="StatelessEnableRejected")][0] |+ .status=="False" and .reason=="CommunicationChannelCacheUnsynced"' <<<"$status" >/dev/null || return 1+ host_runtime_is_always_on "$HOST_REF" || return 1+ deployment="$(kctl get deployment "$HOST_REF" -n "$HOST_NS" -o json)" || return 1+ [ "$(jq -Sc '.spec.template' <<<"$deployment")" = "$baseline_template" ] || return 1+ pod="$(kctl get pods -n "$HOST_NS" -l "app=${HOST_REF}" -o json |+ jq -er '[.items[]|select(.metadata.deletionTimestamp==null)|select(any(.status.conditions[]?;.type=="Ready" and .status=="True"))]|if length==1 then .[0].metadata.uid else error("pod identity ambiguous") end')" || return 1+ [ "$pod" = "$baseline_pod" ]+}++for cycle in 1 2; do+ before="$(log_count 'CommunicationChannel watch ended;')"+ hcc_pr_a_command hold-channel 60000 || die "cycle ${cycle}: fault command failed"+ wait_until 5 'selective hold acknowledgement' hcc_pr_a_ack held ||+ die "cycle ${cycle}: no live channel watch was cut"+ wait_log_count 'CommunicationChannel watch ended;' "$((before + 1))" 20 ||+ die "cycle ${cycle}: HCC did not lose channel authority"+ wait_until 30 'reconciliation while channel cache is unsynced' cache_held_active ||+ die "cycle ${cycle}: active stateless Host did not converge during watch loss"+ session_visible || die "cycle ${cycle}: known session unavailable through rpc-proxy"+ session_listed || die "cycle ${cycle}: known session absent from authorized list"+ cache_held_active || die "cycle ${cycle}: template, SQLite path or pod identity changed"+ hcc_pr_a_command release-channel || die "cycle ${cycle}: release command failed"+ wait_until 5 'selective release acknowledgement' hcc_pr_a_ack released ||+ die "cycle ${cycle}: release was not acknowledged"+ wait_until 30 'CommunicationChannel watch recovery' wait_host_mode "$HOST_REF" accepted 1 ||+ die "cycle ${cycle}: channel authority did not recover"+ ok "cycle ${cycle}: reconciled active stateless Host, stable template/pod and readable session"+done+assert_hcc_identity+ok 'two selective watch-loss cycles completed without HCC restart'diff --git a/scripts/tests/hcc-watch-api-proxy.test.mjs b/scripts/tests/hcc-watch-api-proxy.test.mjsindex 3edfde08d..898b6eab4 100644--- a/scripts/tests/hcc-watch-api-proxy.test.mjs+++ b/scripts/tests/hcc-watch-api-proxy.test.mjs@@ -30,10 +30,86 @@ const allowedPath = '/api/v1/namespaces/mcp-server/services/runtime-witness'const mcpPath = '/apis/clerum.io/v1alpha1/namespaces/mcp-server/mcpservers?watch=true'const contextPath = '/apis/clerum.io/v1alpha1/namespaces/mcp-server/contexts?watch=true'const otherPath = '/api/v1/namespaces/mcp-server/pods?watch=true'+const channelPath = '/apis/clerum.io/v1alpha1/namespaces/channels/communicationchannels'let frontlet upstreamTlslet publicConfig+test('channel hold accepts only a bounded duration', () => {+ assert.throws(() => validateCommand({ id: 'hold', action: 'hold-channel', durationMs: 0 }, []))+ assert.throws(() => validateCommand({ id: 'hold', action: 'hold-channel', durationMs: 60001 }, []))+ assert.deepEqual(validateCommand({ id: 'hold', action: 'hold-channel', durationMs: 60000 }, []),+ { id: 'hold', action: 'hold-channel', durationMs: 60000 })+})++test('channel hold cuts only its watch and keeps Host API requests available', { timeout: 10000 }, async () => {+ const controlDir = mkdtempSync(join(tmpdir(), 'hcc-channel-hold-'))+ const seen = []+ const upstream = https.createServer(upstreamTls, (request, response) => {+ seen.push(request.url)+ if (request.url.includes('watch=true')) {+ response.writeHead(200)+ response.flushHeaders()+ } else {+ response.writeHead(200, { 'content-type': 'application/json' })+ response.end('{}')+ }+ })+ let proxy+ let watchRequest+ const get = path => new Promise((resolveResponse, rejectResponse) => {+ https.get({ hostname: '127.0.0.1', port: proxy.server.address().port, path,+ servername: 'proxy-fixture.test-fixture.svc', ca: front.cert }, response => {+ response.resume()+ response.once('end', () => resolveResponse(response.statusCode))+ }).once('error', rejectResponse)+ })+ const ack = async (id, state) => {+ for (let attempt = 0; attempt < 50; attempt++) {+ if (existsSync(join(controlDir, 'ack.json'))) {+ const value = JSON.parse(readFileSync(join(controlDir, 'ack.json'), 'utf8'))+ if (value.id === id && value.state === state) return value+ }+ await new Promise(resolveWait => setTimeout(resolveWait, 20))+ }+ throw new Error(`missing ${state} acknowledgement`)+ }+ try {+ await new Promise(resolveListen => upstream.listen(0, '127.0.0.1', resolveListen))+ proxy = createProxy({ ...front, upstreamCa: upstreamTls.cert,+ upstreamHost: '127.0.0.1', upstreamPort: upstream.address().port,+ allowedPaths: [], controlDir, periodMs: 60000, minAgeMs: 60000, channelPath })+ await new Promise(resolveListen => proxy.server.listen(0, '127.0.0.1', resolveListen))+ await new Promise((resolveHeaders, rejectHeaders) => {+ watchRequest = https.get({ hostname: '127.0.0.1', port: proxy.server.address().port,+ path: `${channelPath}?watch=true`, servername: 'proxy-fixture.test-fixture.svc',+ ca: front.cert }, resolveHeaders)+ watchRequest.once('error', rejectHeaders)+ })+ writeFileSync(join(controlDir, 'command.json'), JSON.stringify({+ id: 'hold-1', action: 'hold-channel', durationMs: 5000,+ }))+ const held = await ack('hold-1', 'held')+ assert.equal(held.count, 1, 'live CommunicationChannel watch was cut')+ assert.equal(await get(channelPath), 503, 'channel LIST remains unavailable')+ assert.equal(await get('/apis/clerum.io/v1alpha1/namespaces/mcp-host/hosts/test'), 200)+ assert.equal(await get('/api/v1/namespaces/mcp-host/pods'), 200)+ assert.equal(seen.filter(path => path.startsWith(channelPath)).length, 1,+ 'blocked channel retries never reached upstream')+ writeFileSync(join(controlDir, 'command.json'), JSON.stringify({+ id: 'release-1', action: 'release-channel',+ }))+ await ack('release-1', 'released')+ assert.equal(await get(channelPath), 200, 'authoritative LIST works after release')+ } finally {+ watchRequest?.destroy()+ proxy?.close()+ upstream.closeAllConnections()+ await new Promise(resolveClose => upstream.close(resolveClose))+ rmSync(controlDir, { recursive: true, force: true })+ }+})+test('quiet upstream WATCH headers reach the client before its first body event',{ timeout: 5000 },diff --git a/scripts/tests/test-hcc-stateless-cache-containment.sh b/scripts/tests/test-hcc-stateless-cache-containment.shnew file mode 100755index 000000000..48dd5a994--- /dev/null+++ b/scripts/tests/test-hcc-stateless-cache-containment.sh@@ -0,0 +1,74 @@+#!/usr/bin/env bash+# Static contract for the branch-owned selective watch gate. Runtime behavior+# of the TLS fault is exercised by hcc-watch-api-proxy.test.mjs.+set -euo pipefail+# shellcheck disable=SC2034,SC2329 # Fixture globals/functions are consumed by the sourced helper.+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+GATE="${ROOT}/scripts/e2e/e2e-hcc-stateless-cache-containment.sh"+PROXY="${ROOT}/scripts/e2e/_lib/hcc-watch-api-proxy.mjs"+HELPER="${ROOT}/scripts/e2e/_lib/hcc-watch-pr-a.sh"++bash -n "$GATE" "$HELPER"+node --check "$PROXY"+grep -Fq 'require_branch_owned_hcc_gate' "$GATE"+grep -Fq 'E2E_BRANCH_PROFILE_ENV' "$GATE"+grep -Fq 'E2E_PROFILE_PORTS_ENV' "$GATE"+grep -Fq 'acquire_hcc_watch_gate_lock' "$GATE"+# shellcheck disable=SC2016 # Match literal shell source.+grep -Fq 'finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok"' "$GATE"+grep -Fq 'hcc_pr_a_command hold-channel 60000' "$GATE"+grep -Fq 'hcc_pr_a_command release-channel' "$GATE"+grep -Fq 'wait_log_count '\''CommunicationChannel watch ended;' "$GATE"+grep -Fq 'CommunicationChannelCacheUnsynced' "$GATE"+# shellcheck disable=SC2016 # Match literal shell source.+grep -Fq 'host_runtime_is_always_on "$HOST_REF"' "$GATE"+grep -Fq 'jq -Sc '\''.spec.template' "$GATE"+grep -Fq 'baseline_pod' "$GATE"+grep -Fq 'CLERUM_SESSION_DB_DIR' "$GATE"+# shellcheck disable=SC2016 # Match literal shell source.+grep -Fq '/sessions/${HOST_REF}/${THREAD_ID}/messages' "$GATE"+grep -Fq '/sessions?agent=${HOST_REF}&limit=100' "$GATE"+grep -Fq 'session_visible || die "cycle' "$GATE"+grep -Fq 'session_listed || die "cycle' "$GATE"+grep -Fq 'HCC_PR_A_SELECTIVE_CHANNEL=1 hcc_pr_a_enable_proxy' "$GATE"+grep -Fq 'response.writeHead(503' "$PROXY"+grep -Fq 'url.pathname === channelPath' "$PROXY"+if grep -Eq 'scale_proxy|kill .*HCC|kubectl .*delete pod' "$GATE"; then+ echo 'Selective gate contains a broad API or pod fault' >&2+ exit 1+fi++# The proxy image has a read-only root filesystem. Exercise the real fixture+# builder and inspect the Deployment patch, so command/ack files have an owned+# writable mount in the effective pod configuration.+capture="$(mktemp "${TMPDIR:-/tmp}/hcc-channel-patch.XXXXXX")"+trap 'rm -f "$capture"' EXIT+(+ # shellcheck source=scripts/e2e/_lib/hcc-watch-pr-a.sh+ source "$HELPER"+ PROXY_NAME=fixture-proxy HCC_NS=control-plane MCP_NS=mcp-server CHANNEL_NS=channels RUN_ID=fixture-run+ HCC_PR_A_SELECTIVE_CHANNEL=1+ CAPTURE="$capture"+ truncate_rfc1123() { printf '%.63s' "$1"; }+ die() { echo "$*" >&2; exit 1; }+ node() { printf '{}'; }+ kctl() {+ if [ "$1" = patch ]; then+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -p ]; then printf '%s' "$2" > "$CAPTURE"; break; fi+ shift+ done+ fi+ }+ hcc_pr_a_enable_proxy+)+jq -e '+ .spec.template.spec as $pod |+ $pod.securityContext.fsGroup==1000 and+ (any($pod.volumes[]; .name=="churn-control" and .emptyDir=={})) and+ (any($pod.containers[]; .name=="proxy" and+ any(.volumeMounts[]; .name=="churn-control" and .mountPath=="/churn-ctl" and (.readOnly!=true)) and+ any(.env[]; .name=="CHURN_DISABLED" and .value=="1")))+' "$capture" >/dev/null+grep -Fq 'readOnlyRootFilesystem: true' "${ROOT}/scripts/e2e/_lib/hcc-watch-recovery-fixture.sh"+echo 'Selective stateless-cache containment shell contract: PASS'