Skip to content

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

TypeScript

fix(desktop,hcc): fence destructive scope, distinguish host authority, and preserve template

Alfredo Lopezf7349f468f29
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index 8a9b9f715..d4bb93200 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts
@@ -5,7 +5,9 @@ import path from 'node:path'
import {
__setChatStoreBaseDirForTests,
bindChatStoreForUser,
+ getChatStoreBindingGeneration,
requireChatStore,
+ requireChatStoreForBindingGeneration,
unbindChatStore,
} from '../chatStoreBinding'
@@ -39,6 +41,27 @@ describe('chatStoreBinding', () => {
expect(() => requireChatStore()).toThrow(/Not authenticated/)
})
+ it('fences destructive work to the binding that issued it', async () => {
+ await bindChatStoreForUser('user-a', ENV_A)
+ const firstBinding = getChatStoreBindingGeneration()
+ expect(requireChatStoreForBindingGeneration(firstBinding)).toBe(requireChatStore())
+
+ // Refreshing the same user's binding does not invalidate their work.
+ await bindChatStoreForUser('user-a', ENV_A)
+ expect(getChatStoreBindingGeneration()).toBe(firstBinding)
+
+ await bindChatStoreForUser('user-b', ENV_A)
+ const nextBinding = getChatStoreBindingGeneration()
+ expect(nextBinding).not.toBe(firstBinding)
+ expect(() => requireChatStoreForBindingGeneration(firstBinding)).toThrow(
+ /Chat store binding changed/
+ )
+ expect(requireChatStoreForBindingGeneration(nextBinding)).toBe(requireChatStore())
+
+ unbindChatStore()
+ expect(() => requireChatStoreForBindingGeneration(nextBinding)).toThrow()
+ })
+
it('does not follow symlinked quarantine roots during retention cleanup', async () => {
const externalDir = await fs.mkdtemp(path.join(os.tmpdir(), 'clerum-external-quarantine-'))
const sentinel = path.join(externalDir, 'corrupt-old')
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index 0a7b61d26..bea661689 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -343,6 +343,19 @@ export function requireChatStore(): ChatStore {
return activeChatStore
}
+/** Fences destructive IPC work to the store binding that issued the request. */
+export function getChatStoreBindingGeneration(): number {
+ requireChatStore()
+ return bindingGeneration
+}
+
+export function requireChatStoreForBindingGeneration(expectedGeneration: number): ChatStore {
+ if (!Number.isSafeInteger(expectedGeneration) || expectedGeneration !== bindingGeneration) {
+ throw new Error('Chat store binding changed')
+ }
+ return requireChatStore()
+}
+
/** Test-only helper. Do not call from production code. */
export function __setChatStoreBaseDirForTests(base: string | null): void {
baseDirOverride = base
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 88b88ba2e..1c458d896 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -11,7 +11,11 @@ import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { AppService } from './appService.js'
-import { requireChatStore } from './chatStoreBinding.js'
+import {
+ getChatStoreBindingGeneration,
+ requireChatStore,
+ requireChatStoreForBindingGeneration,
+} from './chatStoreBinding.js'
import { GFS_PREVIEW_MAX_BYTES } from './gfs/previewLimits.js'
import { assertSafeRouteSegment } from './pathSafety.js'
import {
@@ -1420,14 +1424,32 @@ export function registerIpcHandlers(service: AppService): void {
}
)
- ipcMain.handle('chat:delete', async (event, payload: { agentRef: string; chatId: string }) => {
+ ipcMain.handle('chat:bindingGeneration', event => {
assertTrustedSender(event)
- const agentRef = sanitizeString(payload?.agentRef)
- const chatId = sanitizeString(payload?.chatId)
- if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
- await requireChatStore().deleteChat(agentRef, chatId)
+ return getChatStoreBindingGeneration()
})
+ ipcMain.handle(
+ 'chat:delete',
+ async (
+ event,
+ payload: {
+ version?: number
+ bindingGeneration?: number
+ agentRef: string
+ chatId: string
+ }
+ ) => {
+ assertTrustedSender(event)
+ const agentRef = sanitizeString(payload?.agentRef)
+ const chatId = sanitizeString(payload?.chatId)
+ if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
+ if (payload?.version !== 2) throw new Error('Scoped chat deletion is required')
+ const store = requireChatStoreForBindingGeneration(payload.bindingGeneration as number)
+ await store.deleteChat(agentRef, chatId)
+ }
+ )
+
ipcMain.handle(
'chat:loadMessages',
async (
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 79a047e4f..595a67196 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -580,8 +580,9 @@ const clerum = Object.freeze({
ipcRenderer.invoke('chat:create', { agentRef, chatId }),
rename: (agentRef: string, chatId: string, title: string) =>
ipcRenderer.invoke('chat:rename', { agentRef, chatId, title }),
- delete: (agentRef: string, chatId: string) =>
- ipcRenderer.invoke('chat:delete', { agentRef, chatId }),
+ getBindingGeneration: () => ipcRenderer.invoke('chat:bindingGeneration'),
+ delete: (agentRef: string, chatId: string, bindingGeneration: number) =>
+ ipcRenderer.invoke('chat:delete', { version: 2, agentRef, chatId, bindingGeneration }),
loadMessages: (agentRef: string, chatId: string, limit?: number, offset?: number) =>
ipcRenderer.invoke('chat:loadMessages', { agentRef, chatId, limit, offset }),
appendMessages: (agentRef: string, chatId: string, messages: unknown[]) =>
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 1b9ba4585..f7b3c2486 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -696,7 +696,8 @@ declare global {
list: (agentRef: string) => Promise<ChatMetadata[]>
create: (agentRef: string, chatId: string) => Promise<ChatMetadata>
rename: (agentRef: string, chatId: string, title: string) => Promise<void>
- delete: (agentRef: string, chatId: string) => Promise<void>
+ getBindingGeneration: () => Promise<number>
+ delete: (agentRef: string, chatId: string, bindingGeneration: number) => Promise<void>
loadMessages: (
agentRef: string,
chatId: string,
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 21a233b14..6c4120219 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -916,6 +916,12 @@ export interface ChatIndex {
chats: ChatMetadata[]
/** Optional for older indexes. User-confirmed local deletions stay hidden from remote lists. */
deletedChatIds?: string[]
+ /** Logical deletions whose on-disk cache cleanup must be retried. */
+ pendingCleanupChatIds?: string[]
+}
+
+export interface ChatDeleteResult {
+ cleanupPending: boolean
}
/** Server-reported session lifecycle (D.1). `idle` once no task is in flight. */
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index 7802f9f10..439240e23 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -136,6 +136,15 @@ describe('ipc host status stream handlers', () => {
registerIpcHandlers(service as never)
})
+ it('rejects legacy chat deletion without a binding fence', async () => {
+ const handler = testState.handlers.get('chat:delete')
+ expect(handler).toBeDefined()
+ const { event } = makeTrustedEvent()
+ await expect(
+ Promise.resolve(handler?.(event, { agentRef: 'agent-x', chatId: 'chat-1' }))
+ ).rejects.toThrow('Scoped chat deletion is required')
+ })
+
it('rejects untrusted sender for stream start', async () => {
const handler = testState.handlers.get('rpc:hostStatusStreamStart')
expect(handler).toBeDefined()
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 14be2aca8..51cac4051 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -318,6 +318,15 @@ export function App() {
// The universal tab store lives in the controller (single writer; `vm.navItem`
// is its projection). App composes the strip/reveal/reconcile over it.
const workspaceTabs = vm.workspaceTabs
+ const visibleWorkspaceTabs = React.useMemo(
+ () =>
+ workspaceTabs.tabs.map(tab =>
+ tab.kind === 'chat' && tab.chat?.agentRef && vm.isHostAccessBlocked(tab.chat.agentRef)
+ ? { ...tab, title: 'Conversation unavailable' }
+ : tab
+ ),
+ [workspaceTabs.tabs, vm.hostAuthorityRevision, vm.isHostAccessBlocked]
+ )
const setWorkspaceTabs = vm.setWorkspaceTabs
const nextChatTabId = vm.nextWorkspaceTabId
const workspaceTabsRef = React.useRef(workspaceTabs)
@@ -2437,8 +2446,8 @@ export function App() {
// Its "current" chat is the controller's (selectedAgent, activeChatId) — NOT
// the store's active tab, which is the app tab while the drawer is open.
const chatWorkspaceTabs = React.useMemo(
- () => workspaceTabs.tabs.filter((tab): tab is WorkspaceTab => tab.kind === 'chat'),
- [workspaceTabs.tabs]
+ () => visibleWorkspaceTabs.filter((tab): tab is WorkspaceTab => tab.kind === 'chat'),
+ [visibleWorkspaceTabs]
)
const drawerActiveChatTabId =
chatWorkspaceTabs.find(
@@ -2540,7 +2549,7 @@ export function App() {
tab. Hidden only when the workspace is empty. */}
{workspaceTabs.tabs.length > 0 && (
<WorkspaceTabStrip
- tabs={workspaceTabs.tabs}
+ tabs={visibleWorkspaceTabs}
activeTabId={
vm.appsPickerActive ? null : workspaceTabs.activeTabId
}
diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
index 7d61459f1..61ad23880 100644
--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
@@ -1,6 +1,10 @@
import { classifyTier } from '@hooks/useTaskTier'
import { buildResponseFileAttachments } from '@lib/chatMessageAttachments'
-import { extractAssistantReply } from '@lib/format'
+import {
+ extractAssistantReply,
+ isAuthorizationError,
+ isConfirmedHostAccessRevoked,
+} from '@lib/format'
import type { ProgressStep } from '@/uiTypes'
import type {
ChatMessageAttachment,
@@ -629,7 +633,21 @@ export class TaskTracker implements AgentTaskTracker {
const { agentRef } = parseTaskKey(key)
const result = await window.clerum.rpc.getTaskResult(agentRef, failedTaskId, [agentRef])
attachments = buildResponseFileAttachments(result)
- } catch {
+ } catch (error) {
+ if (isAuthorizationError(error)) {
+ if (this.states.get(key)?.taskId !== failedTaskId) return
+ this.mutate(key, s => {
+ s.status = 'failed'
+ s.terminalResult = {
+ kind: 'error',
+ source: 'authority',
+ message: 'Host authorization rejected',
+ authority: isConfirmedHostAccessRevoked(error) ? 'revoked' : 'uncertain',
+ }
+ })
+ await this.fireTerminal(key)
+ return
+ }
// Preserve the authoritative terminal error if artifact retrieval fails.
}
if (this.states.get(key)?.taskId !== failedTaskId) return
@@ -694,7 +712,7 @@ export class TaskTracker implements AgentTaskTracker {
...(attachments.length ? { attachments } : {}),
}
})
- } catch {
+ } catch (error) {
// Same post-await identity guard on the failure branch — a replacement
// during the await must not have its state overwritten with this error.
if (this.states.get(key)?.taskId !== completedTaskId) return
@@ -702,8 +720,17 @@ export class TaskTracker implements AgentTaskTracker {
s.status = 'failed'
s.terminalResult = {
kind: 'error',
- source: 'result_fetch',
- message: 'Failed to retrieve task result after completion',
+ source: isAuthorizationError(error) ? 'authority' : 'result_fetch',
+ message: isAuthorizationError(error)
+ ? 'Host authorization rejected'
+ : 'Failed to retrieve task result after completion',
+ ...(isAuthorizationError(error)
+ ? {
+ authority: isConfirmedHostAccessRevoked(error)
+ ? ('revoked' as const)
+ : ('uncertain' as const),
+ }
+ : {}),
}
})
}
diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
index 9bc88667f..5232a41ac 100644
--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
@@ -57,7 +57,9 @@ export type TaskTerminalResult =
| { kind: 'reply'; content: string; attachments?: ChatMessageAttachment[] }
| {
kind: 'error'
- source: 'failed' | 'result_fetch' | 'stream'
+ source: 'failed' | 'result_fetch' | 'stream' | 'authority'
+ /** A final task-result read denial; no raw response body crosses this boundary. */
+ authority?: 'revoked' | 'uncertain'
attachments?: ChatMessageAttachment[]
message: string
code?: string
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
index b6af0ba5a..61005ad17 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx
@@ -5,7 +5,8 @@ import { renderHook } from '@testing-library/react'
import { useAgentChatController } from '../../useAgentChatController'
const onHostAccessRevoked = () => {}
-const isHostAccessRevoked = () => false
+const onHostAuthorityUncertain = () => {}
+const isHostAccessBlocked = () => false
type ControllerParams = Parameters<typeof useAgentChatController>[0]
@@ -55,7 +56,8 @@ export function renderController(
loadMenuData: true,
navItem: 'agents',
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
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__/__fixtures__/mockClerum.ts b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
index 125bb9392..44fd8435a 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts
@@ -21,6 +21,7 @@ interface ChatMock {
list: Fn
create: Fn
rename: Fn
+ getBindingGeneration: Fn
delete: Fn
loadMessages: Fn
appendMessages: Fn
@@ -76,6 +77,7 @@ export function installMockClerum(): MockClerum {
messageCount: 0,
})),
rename: vi.fn(async () => undefined),
+ getBindingGeneration: vi.fn(async () => 1),
delete: vi.fn(async () => undefined),
loadMessages: vi.fn(async () => []),
appendMessages: vi.fn(async () => undefined),
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatActions.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatActions.characterization.test.tsx
index 5624ea5c4..e6751a145 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/chatActions.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatActions.characterization.test.tsx
@@ -65,7 +65,7 @@ describe('handleDeleteChat', () => {
// ack tore down the SSE subscription (no handler left) so a late terminal
// can't resurrect the deleted chat.
expect(clerum.hasProgressHandler('task-del')).toBe(false)
- expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', chatId)
+ expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', chatId, 1)
// D.5 review #5: the deleted chat's session-state entry is dropped.
expect(result.current.sessionStateByChatKey[key]).toBeUndefined()
// It was the only/active chat → a fresh chat is created and selected.
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx
index 18e0b3ae0..165d810e0 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx
@@ -209,7 +209,7 @@ describe('confirmed deletion catalog protection', () => {
describe('revoked host catalog protection', () => {
it('hides a nonselected host after 403 and blocks direct reselection', async () => {
- const revoked = new Set<string>()
+ const blocked = new Set<string>()
clerum.chat.getIndex.mockResolvedValue(localIndex([]))
clerum.rpc.listSessions.mockImplementation(async (agentRef: string) =>
agentRef === 'agent-y'
@@ -219,8 +219,9 @@ describe('revoked host catalog protection', () => {
const controller = renderController({
selectedAgent: 'agent-x',
agentNames: ['agent-x', 'agent-y'],
- onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAccessRevoked: agentRef => blocked.add(agentRef),
+ onHostAuthorityUncertain: agentRef => blocked.add(agentRef),
+ isHostAccessBlocked: agentRef => blocked.has(agentRef),
})
await waitFor(() =>
expect(controller.result.current.latestChatSessions.some(s => s.id === 'protected-y')).toBe(
@@ -233,8 +234,8 @@ describe('revoked host catalog protection', () => {
controller.result.current.reconcileChat(makeTaskKey('agent-y', 'protected-y'), {
reason: 'background_refresh',
})
- ).resolves.toBe('revoked')
- expect(revoked.has('agent-y')).toBe(true)
+ ).resolves.toBe('authority_unverified')
+ expect(blocked.has('agent-y')).toBe(true)
await waitFor(() =>
expect(controller.result.current.latestChatSessions.some(s => s.id === 'protected-y')).toBe(
false
@@ -251,9 +252,9 @@ describe('revoked host catalog protection', () => {
})
it.each([401, 403])(
- 'hides cached sessions when the catalog explicitly returns %i',
+ 'hides cached sessions when the catalog returns an uncertain %i',
async status => {
- const revoked = new Set<string>()
+ const blocked = new Set<string>()
clerum.chat.getIndex.mockResolvedValue(
localIndex([{ id: 'protected-a', title: 'Cached protected chat' }])
)
@@ -261,11 +262,12 @@ describe('revoked host catalog protection', () => {
const { result } = renderController({
selectedAgent: null,
agentNames: ['agent-a'],
- onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAccessRevoked: agentRef => blocked.add(agentRef),
+ onHostAuthorityUncertain: agentRef => blocked.add(agentRef),
+ isHostAccessBlocked: agentRef => blocked.has(agentRef),
})
- await waitFor(() => expect(revoked.has('agent-a')).toBe(true))
+ await waitFor(() => expect(blocked.has('agent-a')).toBe(true))
expect(result.current.latestChatSessions.some(chat => chat.agentRef === 'agent-a')).toBe(
false
)
@@ -273,7 +275,7 @@ describe('revoked host catalog protection', () => {
)
it('retains cached sessions when a 503 body merely mentions 403', async () => {
- const revoked = new Set<string>()
+ const blocked = new Set<string>()
clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'cached-a', title: 'Cached chat' }]))
clerum.rpc.listSessions.mockRejectedValue(
new Error('503 Service Unavailable: upstream body mentioned 403')
@@ -281,14 +283,15 @@ describe('revoked host catalog protection', () => {
const { result } = renderController({
selectedAgent: null,
agentNames: ['agent-a'],
- onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAccessRevoked: agentRef => blocked.add(agentRef),
+ onHostAuthorityUncertain: agentRef => blocked.add(agentRef),
+ isHostAccessBlocked: agentRef => blocked.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(blocked.has('agent-a')).toBe(false)
expect(result.current.latestChatSessions.some(chat => chat.id === 'cached-a')).toBe(true)
})
})
@@ -297,7 +300,7 @@ 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 blocked = new Set<string>()
const deliveredA = deferred<void>()
const pendingB = deferred<SessionsListResult>()
clerum.chat.getIndex.mockResolvedValue(localIndex([]))
@@ -311,8 +314,9 @@ describe('late global catalog response', () => {
const controller = renderController({
selectedAgent: null,
agentNames: ['agent-a', 'agent-b'],
- onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAccessRevoked: agentRef => blocked.add(agentRef),
+ onHostAuthorityUncertain: agentRef => blocked.add(agentRef),
+ isHostAccessBlocked: agentRef => blocked.has(agentRef),
})
await deliveredA.promise
await waitFor(() =>
@@ -329,12 +333,12 @@ describe('late global catalog response', () => {
reason: 'background_refresh',
})
})
- expect(revoked.has('agent-a')).toBe(true)
+ expect(blocked.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')
+ expect(clerum.chat.delete).toHaveBeenCalledWith('agent-a', 'session-a', 1)
}
await act(async () => {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
index 6d01c34a3..f8d3da40c 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
@@ -38,9 +38,12 @@ function buildDeps(overrides: Partial<ReconcileChatDeps> = {}): ReconcileChatDep
attachLiveTask: vi.fn(async () => 'reconcile_rejoined' as const),
settleIdle: vi.fn(async () => 'fell_through_to_resend' as const),
revokeAccess: vi.fn(),
+ holdAccess: 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,
+ isConfirmedHostAccessRevoked: e =>
+ e instanceof Unauthorized && e.message === 'verified-host-403',
telemetry: vi.fn(),
networkRetryBackoffMs: [0, 0, 0],
...overrides,
@@ -100,7 +103,7 @@ describe('reconcileChat — precedence branches', () => {
expect(deps.fsm.getState(chatKey)).toBeDefined()
})
- it.each([401, 403])('%i revokes access and resets protected conversation state', async status => {
+ it.each([401, 403])('%i holds protected data pending renewed authority', async status => {
const deps = buildDeps({
loadSessionMessages: vi.fn(async () => {
throw new Unauthorized(String(status))
@@ -108,11 +111,26 @@ describe('reconcileChat — precedence branches', () => {
})
deps.fsm.dispatch(chatKey, { type: 'SEND_STARTED', taskId: 't1' })
const reconcile = createReconcileChat(deps)
- await reconcile(chatKey, { reason: 'user_refresh' })
- expect(deps.revokeAccess).toHaveBeenCalledWith(chatKey)
+ await expect(reconcile(chatKey, { reason: 'user_refresh' })).resolves.toBe(
+ 'authority_unverified'
+ )
+ expect(deps.holdAccess).toHaveBeenCalledWith(chatKey)
+ expect(deps.revokeAccess).not.toHaveBeenCalled()
expect(deps.fsm.getState(chatKey)).toBeUndefined()
})
+ it('revokes immediately for a verified Host denial', async () => {
+ const deps = buildDeps({
+ loadSessionMessages: vi.fn(async () => {
+ throw new Unauthorized('verified-host-403')
+ }),
+ })
+ const reconcile = createReconcileChat(deps)
+ await expect(reconcile(chatKey, { reason: 'user_refresh' })).resolves.toBe('revoked')
+ expect(deps.revokeAccess).toHaveBeenCalledWith(chatKey)
+ expect(deps.holdAccess).not.toHaveBeenCalled()
+ })
+
it('exhausted network retries → WENT_OFFLINE + offline outcome', async () => {
const load = vi.fn(async () => {
throw new NetErr('down')
@@ -276,7 +294,7 @@ describe('reconcileChat — single-flight', () => {
expect(deps.fsm.getState(chatKey)).toBeUndefined()
})
- it('revokes a Host when an old chat read returns 403 after selection moves to another chat', async () => {
+ it('holds a Host when an old chat read returns generic 403 after selection moves', async () => {
let rejectLoad: (reason: unknown) => void = () => {}
let firstChatSelected = true
const deps = buildDeps({
@@ -295,8 +313,8 @@ describe('reconcileChat — single-flight', () => {
firstChatSelected = false
rejectLoad(new Unauthorized('403 forbidden'))
- await expect(pending).resolves.toBe('revoked')
- expect(deps.revokeAccess).toHaveBeenCalledWith(chatKey)
+ await expect(pending).resolves.toBe('authority_unverified')
+ expect(deps.holdAccess).toHaveBeenCalledWith(chatKey)
})
it('ignores a late 403 after reset tears down the principal scope', async () => {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
index 34f2af9bc..036ed97cd 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx
@@ -159,7 +159,7 @@ describe('rename pending queue (spec 15 §2.5)', () => {
selectedAgent: 'agent-x',
agentNames: ['agent-x'],
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))
await act(async () => {
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.tsx
index 26513af6c..447885633 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
@@ -1027,7 +1027,8 @@ describe('switchToChat (unified, D.4)', () => {
)
const { result } = renderController({
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAuthorityUncertain: agentRef => revoked.add(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await settleMount()
await act(async () => {
@@ -1062,7 +1063,8 @@ describe('switchToChat (unified, D.4)', () => {
const controller = renderController({
currentTeamId: 'team-before',
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAuthorityUncertain: agentRef => revoked.add(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await settleMount()
await act(async () => {
@@ -1108,7 +1110,8 @@ describe('switchToChat (unified, D.4)', () => {
const controller = renderController({
currentTeamId: 'team-before',
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAuthorityUncertain: agentRef => revoked.add(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await settleMount()
await act(async () => {
@@ -1138,7 +1141,8 @@ describe('switchToChat (unified, D.4)', () => {
clerum.rpc.getTaskResult.mockRejectedValue(new Error(`${status} response`))
const { result } = renderController({
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAuthorityUncertain: agentRef => revoked.add(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await settleMount()
await act(async () => {
@@ -1178,7 +1182,8 @@ describe('switchToChat (unified, D.4)', () => {
const controller = renderController({
currentTeamId: 'team-before',
onHostAccessRevoked: agentRef => revoked.add(agentRef),
- isHostAccessRevoked: agentRef => revoked.has(agentRef),
+ onHostAuthorityUncertain: agentRef => revoked.add(agentRef),
+ isHostAccessBlocked: agentRef => revoked.has(agentRef),
})
await settleMount()
await act(async () => {
@@ -1206,7 +1211,7 @@ describe('switchToChat (unified, D.4)', () => {
await act(async () => {
await controller.result.current.handleDeleteChatForAgent('agent-x', 'late-result')
})
- expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', 'late-result')
+ expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', 'late-result', 1)
} else {
controller.rerender({ currentTeamId: 'team-after' })
}
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.tsx
index eda3cc67b..456dcb471 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
@@ -20,7 +20,10 @@ const revokedAgents = new Set<string>()
const onHostAccessRevoked = (agentRef: string) => {
revokedAgents.add(agentRef)
}
-const isHostAccessRevoked = (agentRef: string) => revokedAgents.has(agentRef)
+const onHostAuthorityUncertain = (agentRef: string) => {
+ revokedAgents.add(agentRef)
+}
+const isHostAccessBlocked = (agentRef: string) => revokedAgents.has(agentRef)
function getDraftInputValue(): string {
return (screen.getByTestId('draft-input') as HTMLInputElement).value
@@ -68,6 +71,7 @@ function installClerumHarness() {
return meta
}),
rename: vi.fn(async () => undefined),
+ getBindingGeneration: vi.fn(async () => 1),
delete: vi.fn(async (_agentRef: string, chatId: string) => {
deletedChatIds.add(chatId)
const index = chats.findIndex(chat => chat.id === chatId)
@@ -134,7 +138,8 @@ function AgentChatHarness() {
loadMenuData: true,
navItem: 'chat',
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
pushToast: vi.fn(),
pushNotification: vi.fn(),
agentDisplayName: (agentName: string) => agentName,
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.tsx
index d1d996dcf..a0aca4cf9 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
@@ -20,7 +20,8 @@ import type { TaskProgressStreamEvent } from '../../../../../src/types'
type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>
const onHostAccessRevoked = () => {}
-const isHostAccessRevoked = () => false
+const onHostAuthorityUncertain = () => {}
+const isHostAccessBlocked = () => false
function createChatMeta(chatId: string) {
const now = new Date().toISOString()
@@ -65,6 +66,7 @@ function installClerumHarness() {
return meta
}),
rename: vi.fn(async () => undefined),
+ getBindingGeneration: vi.fn(async () => 1),
delete: vi.fn(async () => undefined),
loadMessages: vi.fn(
async (_agentRef: string, chatId: string) => messagesByChat.get(chatId) || []
@@ -124,7 +126,8 @@ function AgentChatHarness() {
loadMenuData: true,
navItem: 'chat',
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
pushToast: vi.fn(),
pushNotification: vi.fn(),
agentDisplayName: (agentName: string) => agentName,
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx
index 8f000b5c6..d98ebe713 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
@@ -82,7 +82,8 @@ interface HarnessProps {
navItem: NavItem
}
const onHostAccessRevoked = () => {}
-const isHostAccessRevoked = () => false
+const onHostAuthorityUncertain = () => {}
+const isHostAccessBlocked = () => false
/** Both real hooks, mounted together under the task-tracker the chat controller needs. */
function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navItem }: HarnessProps) {
@@ -96,7 +97,8 @@ function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navIte
loadMenuData: true,
navItem,
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
...stableCallbacks,
})
}
diff --git a/desktop-app/ui/src/hooks/domain/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
index 9302de791..cbd395fe2 100644
--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts
+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
@@ -31,6 +31,7 @@ export type ReconcileOutcome =
| 'fell_through_to_resend'
| 'stale_drop'
| 'revoked'
+ | 'authority_unverified'
| 'offline'
| 'error'
| 'noop'
@@ -79,9 +80,11 @@ export interface ReconcileChatDeps {
) => Promise<ReconcileOutcome>
/** Hide protected data after an explicit authorization rejection. */
revokeAccess: (chatKey: string) => void
+ holdAccess: (chatKey: string) => void
isNetworkError: (err: unknown) => boolean
isHttp404: (err: unknown) => boolean
isAuthorizationError: (err: unknown) => boolean
+ isConfirmedHostAccessRevoked: (err: unknown) => boolean
telemetry: (event: string, data: Record<string, unknown>) => void
/** Guard: `false` aborts the reconcile mid-flight (chat switched away). */
isStillRelevant?: (chatKey: string) => boolean
@@ -225,9 +228,11 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
// 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)
+ const confirmed = deps.isConfirmedHostAccessRevoked(err)
+ if (confirmed) deps.revokeAccess(chatKey)
+ else deps.holdAccess(chatKey)
deps.fsm.dispatch(chatKey, { type: 'RESET' })
- outcome = 'revoked'
+ outcome = confirmed ? 'revoked' : 'authority_unverified'
} else if (!stillRelevant()) {
outcome = 'stale_drop'
return outcome
@@ -253,6 +258,7 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
// resurrect an empty entry, so skip the finalizer in that case.
if (
outcome !== 'revoked' &&
+ outcome !== 'authority_unverified' &&
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.ts
index 8b2590a99..119780a41 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -12,6 +12,7 @@ import {
} from '@lib/chatMessageAttachments'
import { truncateTitle } from '@lib/chatTitle'
import {
+ clearAllComposerDrafts,
getComposerDraft,
getComposerDraftRevision,
setComposerDraft,
@@ -359,7 +360,8 @@ interface UseAgentChatControllerParams {
) => Promise<void>
decideApprovalFromNotification: (target: AgentApprovalNotificationTarget) => Promise<void>
onHostAccessRevoked: (agentRef: string) => void
- isHostAccessRevoked: (agentRef: string) => boolean
+ onHostAuthorityUncertain: (agentRef: string) => void
+ isHostAccessBlocked: (agentRef: string) => boolean
}
export function useAgentChatController({
@@ -379,7 +381,8 @@ export function useAgentChatController({
openAgentConversationFromNotification,
decideApprovalFromNotification,
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
}: UseAgentChatControllerParams) {
const chatStore = useChatStore()
const authenticatedScope = `${currentUserId ?? 'unknown-user'}:${currentTeamId}`
@@ -409,9 +412,15 @@ 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 hideHostAccessRef = useRef<
+ ((agentRef: string, kind: 'revoked' | 'uncertain') => void) | null
+ >(null)
const onCatalogHostAccessRevoked = useCallback(
- (agentRef: string) => revokeHostAccessRef.current!(agentRef),
+ (agentRef: string) => hideHostAccessRef.current!(agentRef, 'revoked'),
+ []
+ )
+ const onCatalogHostAuthorityUncertain = useCallback(
+ (agentRef: string) => hideHostAccessRef.current!(agentRef, 'uncertain'),
[]
)
const autoSelectedChatIdRef = useRef<string | null>(null)
@@ -427,8 +436,9 @@ export function useAgentChatController({
chatStore,
fsm,
host: chatListHostRef,
- isHostAccessRevoked,
+ isHostAccessBlocked,
onHostAccessRevoked: onCatalogHostAccessRevoked,
+ onHostAuthorityUncertain: onCatalogHostAuthorityUncertain,
})
const {
chatList,
@@ -526,6 +536,7 @@ export function useAgentChatController({
const scope = `${isAuthenticated}:${authenticatedScope}`
if (lastRetentionScope.current === scope) return
lastRetentionScope.current = scope
+ clearAllComposerDrafts()
sendScopeGeneration.current += 1
agentSendSetupOwnerRef.current = null
agentSendInFlightRef.current = false
@@ -575,6 +586,7 @@ export function useAgentChatController({
attachLiveTask: ReconcileChatDeps['attachLiveTask']
settleIdle: ReconcileChatDeps['settleIdle']
revokeAccess: ReconcileChatDeps['revokeAccess']
+ holdAccess: ReconcileChatDeps['holdAccess']
} | null>(null)
const reconcileChatRef = useRef<ReconcileChat | null>(null)
if (!reconcileChatRef.current) {
@@ -587,9 +599,11 @@ export function useAgentChatController({
settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>
reconcileBranchesRef.current!.settleIdle(chatKey, resp, epoch, hint, stillRelevant),
revokeAccess: chatKey => reconcileBranchesRef.current!.revokeAccess(chatKey),
+ holdAccess: chatKey => reconcileBranchesRef.current!.holdAccess(chatKey),
isNetworkError,
isHttp404,
isAuthorizationError,
+ isConfirmedHostAccessRevoked,
telemetry: (event, data) => console.log(`[telemetry] ${event}`, data),
})
}
@@ -830,6 +844,7 @@ export function useAgentChatController({
}, [])
const resetChat = useCallback(() => {
+ clearAllComposerDrafts()
setActivityByAgentMessage({})
setProgressByAgentMessage({})
resetComposerAttachments()
@@ -884,7 +899,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)) return
+ if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
const switchRequest = Symbol(`${agentRef}:${chatId}`)
activeChatSwitchRequestRef.current = switchRequest
const key = makeTaskKey(agentRef, chatId)
@@ -915,7 +930,7 @@ export function useAgentChatController({
setAgentError(null)
setFailedAgentSend(null)
await chatStore.setLastActive(agentRef, chatId)
- if (isHostAccessRevoked(agentRef) || isChatDeleted(agentRef, chatId)) return
+ if (isHostAccessBlocked(agentRef) || isChatDeleted(agentRef, chatId)) return
unfillableServerGapUpperBoundsRef.current.delete(key)
@@ -1002,7 +1017,7 @@ export function useAgentChatController({
},
[
currentTeamId,
- isHostAccessRevoked,
+ isHostAccessBlocked,
isChatDeleted,
dispatchSession,
tracker,
@@ -1049,14 +1064,14 @@ export function useAgentChatController({
async (chatId: string) => {
if (
!selectedAgent ||
- isHostAccessRevoked(selectedAgent) ||
+ isHostAccessBlocked(selectedAgent) ||
isChatDeleted(selectedAgent, chatId)
)
return
autoSelectedChatIdRef.current = null
await switchToChat(selectedAgent, chatId)
},
- [selectedAgent, isHostAccessRevoked, isChatDeleted, switchToChat]
+ [selectedAgent, isHostAccessBlocked, isChatDeleted, switchToChat]
)
const handleLoadOlderMessages = useCallback(async () => {
@@ -1167,9 +1182,12 @@ export function useAgentChatController({
isAuthorizationError(error) &&
requestScope === sendScopeGeneration.current &&
requestScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(requestAgent)
+ !isHostAccessBlocked(requestAgent)
) {
- revokeHostAccessRef.current!(requestAgent)
+ hideHostAccessRef.current!(
+ requestAgent,
+ isConfirmedHostAccessRevoked(error) ? 'revoked' : 'uncertain'
+ )
return
}
console.warn('[chat-history] failed to load older messages', {
@@ -1192,13 +1210,13 @@ export function useAgentChatController({
ignoredServerGapUpperBounds,
markServerGapUnfillable,
selectedAgent,
- isHostAccessRevoked,
+ isHostAccessBlocked,
tracker,
])
// Agent selection → load chats
useEffect(() => {
- if (!selectedAgent || isHostAccessRevoked(selectedAgent)) {
+ if (!selectedAgent || isHostAccessBlocked(selectedAgent)) {
autoSelectedChatIdRef.current = null
activeChatVisibilityRef.current = {
...activeChatVisibilityRef.current,
@@ -1256,7 +1274,7 @@ export function useAgentChatController({
setChatListLoading(true)
;(async () => {
const result = await loadChatList(selectedAgent)
- if (cancelled || isHostAccessRevoked(selectedAgent)) return
+ if (cancelled || isHostAccessBlocked(selectedAgent)) return
setChatListLoading(false)
if (!result) {
setChatMessagesLoading(false)
@@ -1320,7 +1338,7 @@ export function useAgentChatController({
return () => {
cancelled = true
}
- }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent, isHostAccessRevoked])
+ }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent, isHostAccessBlocked])
const mapComposerAttachmentsToHostRequest = (
attachments: ComposerImageAttachment[]
@@ -1495,7 +1513,7 @@ export function useAgentChatController({
const mayAppend = () =>
messageScope === sendScopeGeneration.current &&
messageScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(agentName) &&
+ !isHostAccessBlocked(agentName) &&
(!chatId || !isChatDeleted(agentName, chatId))
if (!mayAppend()) return
// Update the in-memory view FIRST (synchronously), then persist. For a
@@ -1525,7 +1543,7 @@ export function useAgentChatController({
// notification delivery is best-effort
}
},
- [bumpActivity, chatStore, pushAssistantReplyNotification, isHostAccessRevoked, isChatDeleted]
+ [bumpActivity, chatStore, pushAssistantReplyNotification, isHostAccessBlocked, isChatDeleted]
)
// ─── reconcileChat branch callbacks (§4.3) ───
@@ -1563,7 +1581,7 @@ export function useAgentChatController({
return v.selectedAgent === agentRef && v.activeChatId === chatId
}
const mayHydrate = () =>
- stillRelevant() && !isHostAccessRevoked(agentRef) && !isChatDeleted(agentRef, chatId)
+ stillRelevant() && !isHostAccessBlocked(agentRef) && !isChatDeleted(agentRef, chatId)
const cached = (await chatStore
.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
.catch(error => {
@@ -1680,7 +1698,7 @@ export function useAgentChatController({
},
[
tracker,
- isHostAccessRevoked,
+ isHostAccessBlocked,
isChatDeleted,
chatStore.loadMessages,
chatStore.createChat,
@@ -1847,8 +1865,8 @@ export function useAgentChatController({
[fsm, tracker, hydrateActiveChatFromServer, appendAssistantMessage]
)
- const revokeHostAccess = useCallback(
- (agentRef: string) => {
+ const hideHostAccess = useCallback(
+ (agentRef: string, kind: 'revoked' | 'uncertain') => {
for (const chatKey of Object.keys(fsm.getSnapshot())) {
if (parseTaskKey(chatKey).agentRef !== agentRef) continue
tracker.release(chatKey as TaskKey)
@@ -1888,7 +1906,8 @@ export function useAgentChatController({
setHasOlderMessages(false)
cancelOlderMessagesLoad()
}
- onHostAccessRevoked(agentRef)
+ if (kind === 'revoked') onHostAccessRevoked(agentRef)
+ else onHostAuthorityUncertain(agentRef)
},
[
tracker,
@@ -1899,11 +1918,20 @@ export function useAgentChatController({
resetComposerAttachments,
cancelOlderMessagesLoad,
onHostAccessRevoked,
+ onHostAuthorityUncertain,
]
)
+ const revokeHostAccess = useCallback(
+ (agentRef: string) => hideHostAccess(agentRef, 'revoked'),
+ [hideHostAccess]
+ )
+ const holdHostAccess = useCallback(
+ (agentRef: string) => hideHostAccess(agentRef, 'uncertain'),
+ [hideHostAccess]
+ )
useEffect(() => {
- revokeHostAccessRef.current = revokeHostAccess
- }, [revokeHostAccess])
+ hideHostAccessRef.current = hideHostAccess
+ }, [hideHostAccess])
const reconcileRevokeAccess = useCallback<ReconcileChatDeps['revokeAccess']>(
chatKey => {
@@ -1912,6 +1940,13 @@ export function useAgentChatController({
},
[revokeHostAccess]
)
+ const reconcileHoldAccess = useCallback<ReconcileChatDeps['holdAccess']>(
+ chatKey => {
+ const { agentRef } = parseTaskKey(chatKey)
+ holdHostAccess(agentRef)
+ },
+ [holdHostAccess]
+ )
useEffect(() => {
reconcileBranchesRef.current = {
@@ -2021,6 +2056,7 @@ export function useAgentChatController({
attachLiveTask: reconcileAttachLiveTask,
settleIdle: reconcileSettleIdle,
revokeAccess: reconcileRevokeAccess,
+ holdAccess: reconcileHoldAccess,
}
}, [
chatStore.loadSessionMessages,
@@ -2028,6 +2064,7 @@ export function useAgentChatController({
reconcileAttachLiveTask,
reconcileSettleIdle,
reconcileRevokeAccess,
+ reconcileHoldAccess,
])
// ─── Tracker callbacks + subscription (the post-D.3 fire & forget glue) ───
@@ -2040,11 +2077,22 @@ export function useAgentChatController({
const terminalStillAuthorized = () =>
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(agentRef) &&
+ !isHostAccessBlocked(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
+ if (result?.kind === 'error' && result.source === 'authority') {
+ if (
+ terminalScope === sendScopeGeneration.current &&
+ terminalScopeIdentity === currentAuthScopeRef.current &&
+ !isHostAccessBlocked(agentRef)
+ ) {
+ if (result.authority === 'revoked') revokeHostAccess(agentRef)
+ else holdHostAccess(agentRef)
+ }
+ return
+ }
// ── stream-recovery: a lost progress stream is NOT a task failure ──
// The task is durable server-side (D.1/T2.1), so before surfacing the scary
@@ -2133,7 +2181,7 @@ export function useAgentChatController({
const mayRecover = () =>
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(agentRef) &&
+ !isHostAccessBlocked(agentRef) &&
!isChatDeleted(agentRef, chatId)
let taskResult: Awaited<ReturnType<typeof window.clerum.rpc.getTaskResult>>
try {
@@ -2143,9 +2191,12 @@ export function useAgentChatController({
if (
terminalScope === sendScopeGeneration.current &&
terminalScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(agentRef)
+ !isHostAccessBlocked(agentRef)
) {
- revokeHostAccessRef.current!(agentRef)
+ hideHostAccessRef.current!(
+ agentRef,
+ isConfirmedHostAccessRevoked(error) ? 'revoked' : 'uncertain'
+ )
}
return true
}
@@ -2340,6 +2391,7 @@ export function useAgentChatController({
setIdle()
break
case 'revoked':
+ case 'authority_unverified':
// The authorization rejection hid the protected chat + reset the FSM.
dropActivity()
break
@@ -2490,8 +2542,10 @@ export function useAgentChatController({
updateMessageProgress,
updateMessageActivity,
reconcileChat,
- isHostAccessRevoked,
+ isHostAccessBlocked,
isChatDeleted,
+ revokeHostAccess,
+ holdHostAccess,
]
)
@@ -2642,7 +2696,7 @@ export function useAgentChatController({
const effectiveReferences = [...references]
if (
!selectedAgent ||
- isHostAccessRevoked(selectedAgent) ||
+ isHostAccessBlocked(selectedAgent) ||
(!trimmedContent && !effectiveAttachments.length && !effectiveReferences.length)
)
return
@@ -2695,7 +2749,7 @@ export function useAgentChatController({
const sendStillAuthorized = () =>
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(sendAgent) &&
+ !isHostAccessBlocked(sendAgent) &&
(!sendChatId || !isChatDeleted(sendAgent, sendChatId))
// Captured for the retention snapshot: the model this attempt actually
// asked for (issue #654), readable from the catch below.
@@ -3064,12 +3118,16 @@ export function useAgentChatController({
isAuthorizationError(error) &&
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(sendAgent)
+ !isHostAccessBlocked(sendAgent)
) {
- if (isConfirmedHostAccessRevoked(error) || !isHttp403(error)) {
+ if (isConfirmedHostAccessRevoked(error)) {
revokeHostAccess(sendAgent)
return
}
+ if (!isHttp403(error)) {
+ holdHostAccess(sendAgent)
+ return
+ }
try {
await chatStore.listSessions(sendAgent, { agent: sendAgent, limit: 1 }, { force: true })
} catch (readError) {
@@ -3077,9 +3135,10 @@ export function useAgentChatController({
isAuthorizationError(readError) &&
sendScope === sendScopeGeneration.current &&
sendScopeIdentity === currentAuthScopeRef.current &&
- !isHostAccessRevoked(sendAgent)
+ !isHostAccessBlocked(sendAgent)
) {
- revokeHostAccess(sendAgent)
+ if (isConfirmedHostAccessRevoked(readError)) revokeHostAccess(sendAgent)
+ else holdHostAccess(sendAgent)
return
}
}
@@ -3160,9 +3219,10 @@ export function useAgentChatController({
},
[
selectedAgent,
- isHostAccessRevoked,
+ isHostAccessBlocked,
isChatDeleted,
revokeHostAccess,
+ holdHostAccess,
activeChatId,
composerImageAttachments,
composerReferenceAttachments,
@@ -3364,7 +3424,7 @@ export function useAgentChatController({
isRemote?: boolean
} = {}
) => {
- if (isHostAccessRevoked(agentName) || (chatId && isChatDeleted(agentName, chatId))) return
+ if (isHostAccessBlocked(agentName) || (chatId && isChatDeleted(agentName, chatId))) return
if (options.selectLatest) {
writePendingSelection(agentName, { mode: 'latest', chatId: null })
return
@@ -3401,7 +3461,7 @@ export function useAgentChatController({
currentTeamId,
writePendingSelection,
upsertProvisionalEntry,
- isHostAccessRevoked,
+ isHostAccessBlocked,
isChatDeleted,
]
)
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 41f0bd2d5..24436ad28 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -101,8 +101,9 @@ interface UseChatListControllerParams {
chatStore: ReturnType<typeof useChatStore>
fsm: SessionFsmStore
host: MutableRefObject<ChatListControllerHost | null>
- isHostAccessRevoked: (agentRef: string) => boolean
+ isHostAccessBlocked: (agentRef: string) => boolean
onHostAccessRevoked: (agentRef: string) => void
+ onHostAuthorityUncertain: (agentRef: string) => void
}
function sortableTimestamp(value: string): number {
@@ -165,8 +166,9 @@ export function useChatListController({
chatStore,
fsm,
host,
- isHostAccessRevoked,
+ isHostAccessBlocked,
onHostAccessRevoked,
+ onHostAuthorityUncertain,
}: UseChatListControllerParams) {
// Per-agent list for the SELECTED agent (the sidebar's chat list).
const [chatList, setChatList] = useState<SidebarChatEntry[]>([])
@@ -186,6 +188,8 @@ export function useChatListController({
const deletedChatIdsByAgentRef = useRef(new Map<string, Set<string>>())
const requestGenerationRef = useRef(0)
const authorityScopeGenerationRef = useRef(0)
+ const currentAuthorityScopeRef = useRef(`${isAuthenticated}:${scopeKey}`)
+ currentAuthorityScopeRef.current = `${isAuthenticated}:${scopeKey}`
// 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
@@ -281,7 +285,7 @@ export function useChatListController({
const upsertLatestChatSession = useCallback(
(agentRef: string, chat: SidebarChatEntry) => {
if (
- isHostAccessRevoked(agentRef) ||
+ isHostAccessBlocked(agentRef) ||
deletedChatIdsByAgentRef.current.get(agentRef)?.has(chat.id)
)
return
@@ -294,7 +298,7 @@ export function useChatListController({
return next.sort(byUpdatedDesc)
})
},
- [isHostAccessRevoked]
+ [isHostAccessBlocked]
)
const hideAgent = useCallback((agentRef: string) => {
@@ -324,7 +328,7 @@ export function useChatListController({
if (
selectedAgentRef.current !== agentRef ||
requestGenerationRef.current !== requestGeneration ||
- isHostAccessRevoked(agentRef)
+ isHostAccessBlocked(agentRef)
) {
return { index, merged: [...index.chats].sort(byUpdatedDesc) }
}
@@ -346,16 +350,17 @@ export function useChatListController({
if (
isAuthorizationError(error) &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(agentRef)
+ !isHostAccessBlocked(agentRef)
) {
- onHostAccessRevoked(agentRef)
+ if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)
+ else onHostAuthorityUncertain(agentRef)
}
return
}
if (
selectedAgentRef.current !== agentRef ||
requestGenerationRef.current !== requestGeneration ||
- isHostAccessRevoked(agentRef)
+ isHostAccessBlocked(agentRef)
) {
if (
suppressionMarkerAtRequest !== undefined &&
@@ -388,7 +393,7 @@ export function useChatListController({
// "Remote ·" label, no isRemote branch; switchToChat's unified path
// hydrates them.
setChatList(previous => {
- if (isHostAccessRevoked(agentRef)) return []
+ if (isHostAccessBlocked(agentRef)) return []
const visibleSessions = serverSessions.filter(
session => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)
)
@@ -489,7 +494,7 @@ export function useChatListController({
chatStore.listSessions,
chatStore.reconcileServerSessions,
fsm,
- isHostAccessRevoked,
+ isHostAccessBlocked,
onHostAccessRevoked,
]
)
@@ -521,9 +526,10 @@ export function useChatListController({
if (
isAuthorizationError(error) &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(agentRef)
+ !isHostAccessBlocked(agentRef)
) {
- onHostAccessRevoked(agentRef)
+ if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)
+ else onHostAuthorityUncertain(agentRef)
return
}
if (
@@ -544,13 +550,13 @@ export function useChatListController({
const serverSessions = serverResult.items.filter(
s => s.agent === agentRef && !deletedChatIdsByAgentRef.current.get(agentRef)?.has(s.chatId)
)
- if (selectedAgentRef.current !== agentRef || isHostAccessRevoked(agentRef)) return
+ if (selectedAgentRef.current !== agentRef || isHostAccessBlocked(agentRef)) return
chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? null
setChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))
seedSessionSnapshots(fsm, agentRef, serverSessions)
setChatList(previous => {
- if (isHostAccessRevoked(agentRef)) return []
+ if (isHostAccessBlocked(agentRef)) return []
const visibleSessions = serverSessions.filter(
session => !deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)
)
@@ -612,7 +618,7 @@ export function useChatListController({
chatStore.listSessions,
chatStore.reconcileServerSessions,
fsm,
- isHostAccessRevoked,
+ isHostAccessBlocked,
onHostAccessRevoked,
])
@@ -835,8 +841,15 @@ export function useChatListController({
*/
const applyLocalTitleOnly = useCallback(
async (agentRef: string, chatId: string, newTitle: string) => {
- if (!agentRef) return
+ if (!agentRef || !isAuthenticated) return
const requestGeneration = requestGenerationRef.current
+ const authorityScopeGeneration = authorityScopeGenerationRef.current
+ const authorityScope = currentAuthorityScopeRef.current
+ const stillOwned = () =>
+ authorityScopeGenerationRef.current === authorityScopeGeneration &&
+ currentAuthorityScopeRef.current === authorityScope
+ const bindingGeneration = await chatStore.getBindingGeneration()
+ if (!stillOwned()) return
const updatedAt = new Date().toISOString()
await chatStore.renameChat(agentRef, chatId, newTitle)
if (requestGenerationRef.current !== requestGeneration) return
@@ -898,7 +911,7 @@ export function useChatListController({
if (
isConfirmedHostAccessRevoked(error) &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(entry.agentRef)
+ !isHostAccessBlocked(entry.agentRef)
) {
onHostAccessRevoked(entry.agentRef)
if (pendingRenamesRef.current.get(key) === entry) {
@@ -909,7 +922,7 @@ export function useChatListController({
if (
isAuthorizationError(error) &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(entry.agentRef)
+ !isHostAccessBlocked(entry.agentRef)
) {
try {
await chatStore.listSessions(
@@ -921,7 +934,7 @@ export function useChatListController({
if (
isAuthorizationError(readError) &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(entry.agentRef)
+ !isHostAccessBlocked(entry.agentRef)
) {
onHostAccessRevoked(entry.agentRef)
if (pendingRenamesRef.current.get(key) === entry) {
@@ -972,7 +985,7 @@ export function useChatListController({
entry.sending = false
}
},
- [chatStore, applyLocalTitleOnly, host, isHostAccessRevoked, onHostAccessRevoked]
+ [chatStore, applyLocalTitleOnly, host, isHostAccessBlocked, onHostAccessRevoked]
)
/**
@@ -1079,6 +1092,11 @@ export function useChatListController({
async (agentRef: string, chatId: string) => {
if (!agentRef) return
const requestGeneration = requestGenerationRef.current
+ const authorityScopeGeneration = authorityScopeGenerationRef.current
+ const authorityScope = currentAuthorityScopeRef.current
+ const stillOwned = () =>
+ authorityScopeGenerationRef.current === authorityScopeGeneration &&
+ currentAuthorityScopeRef.current === authorityScope
// Stop following any in-flight task for this chat first: ack tears down the
// SSE + connect/watchdog timers, so a later terminal can't fire onTerminal
// and resurrect the just-deleted chat file via appendAssistantMessage.
@@ -1088,7 +1106,10 @@ export function useChatListController({
// fire onTerminal and resurrect the just-deleted chat file. Dispatched
// FIRST (before the delete), preserving the ack-before-delete ordering.
host.current?.dispatchSession(deletedKey, { type: 'CHAT_DELETED' })
- await chatStore.deleteChat(agentRef, chatId)
+ const bindingGeneration = await chatStore.getBindingGeneration()
+ if (!stillOwned()) return
+ await chatStore.deleteChat(agentRef, chatId, bindingGeneration)
+ if (!stillOwned()) return
const deleted = deletedChatIdsByAgentRef.current.get(agentRef) ?? new Set<string>()
deleted.add(chatId)
deletedChatIdsByAgentRef.current.set(agentRef, deleted)
@@ -1117,7 +1138,7 @@ export function useChatListController({
}
}
},
- [chatList, chatStore, removeLatestChatSession, handleCreateChat, host]
+ [chatList, chatStore, removeLatestChatSession, handleCreateChat, host, isAuthenticated]
)
const handleDeleteChat = useCallback(
@@ -1175,7 +1196,7 @@ export function useChatListController({
.flatMap(group => group.entries)
.filter(
chat =>
- !isHostAccessRevoked(chat.agentRef) &&
+ !isHostAccessBlocked(chat.agentRef) &&
!deletedChatIdsByAgentRef.current.get(chat.agentRef)?.has(chat.id)
)
.sort(byUpdatedDesc)
@@ -1198,9 +1219,10 @@ export function useChatListController({
isAuthorizationError(error) &&
!cancelled &&
authorityScopeGenerationRef.current === authorityScopeGeneration &&
- !isHostAccessRevoked(agentRef)
+ !isHostAccessBlocked(agentRef)
) {
- onHostAccessRevoked(agentRef)
+ if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)
+ else onHostAuthorityUncertain(agentRef)
}
return { agentRef, sessions: [] as SessionsListResult['items'] }
}
@@ -1209,7 +1231,7 @@ export function useChatListController({
sessions: serverResult.items.filter(
session =>
session.agent === agentRef &&
- !isHostAccessRevoked(agentRef) &&
+ !isHostAccessBlocked(agentRef) &&
!deletedChatIdsByAgentRef.current.get(agentRef)?.has(session.chatId)
),
}
@@ -1217,7 +1239,7 @@ export function useChatListController({
)
if (cancelled) return
for (const group of sessionGroups) {
- if (isHostAccessRevoked(group.agentRef)) continue
+ if (isHostAccessBlocked(group.agentRef)) continue
seedSessionSnapshots(
fsm,
group.agentRef,
@@ -1229,7 +1251,7 @@ export function useChatListController({
setLatestChatSessions(previous => {
const serverByKey = new Map<string, SessionsListResult['items'][number]>()
for (const group of sessionGroups) {
- if (isHostAccessRevoked(group.agentRef)) continue
+ if (isHostAccessBlocked(group.agentRef)) continue
for (const session of group.sessions) {
if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))
continue
@@ -1241,7 +1263,7 @@ export function useChatListController({
const reconciled = previous
.filter(
item =>
- !isHostAccessRevoked(item.agentRef) &&
+ !isHostAccessBlocked(item.agentRef) &&
!deletedChatIdsByAgentRef.current.get(item.agentRef)?.has(item.id)
)
.map(item => {
@@ -1259,7 +1281,7 @@ export function useChatListController({
const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))
const remoteOnly: LatestSidebarChatEntry[] = []
for (const group of sessionGroups) {
- if (isHostAccessRevoked(group.agentRef)) continue
+ if (isHostAccessBlocked(group.agentRef)) continue
for (const session of group.sessions) {
if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))
continue
@@ -1291,7 +1313,7 @@ export function useChatListController({
flushPendingRenamesRef.current(
new Set(
sessionGroups.flatMap(group =>
- isHostAccessRevoked(group.agentRef)
+ isHostAccessBlocked(group.agentRef)
? []
: group.sessions
.filter(
@@ -1320,7 +1342,7 @@ export function useChatListController({
loadMenuData,
scopeKey,
fsm,
- isHostAccessRevoked,
+ isHostAccessBlocked,
onHostAccessRevoked,
])
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 14a0e3bc5..8fb63c1a5 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -306,22 +306,66 @@ 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),
+ const authorityScope = `${auth.isAuthenticated}:${authenticatedPrincipalIdentity ?? ''}:${currentTeamId}`
+ const authorityScopeRef = useRef(authorityScope)
+ authorityScopeRef.current = authorityScope
+ const hostAuthorityEpochRef = useRef(0)
+ const blockedHostsRef = useRef(
+ new Map<string, { kind: 'revoked' | 'uncertain'; epoch: number }>()
+ )
+ const [hostAuthorityRevision, setHostAuthorityRevision] = useState(0)
+ const selectedAgentRef = useRef(nav.selectedAgent)
+ selectedAgentRef.current = nav.selectedAgent
+ const isHostAccessBlocked = useCallback(
+ (agentRef: string) => blockedHostsRef.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)
+ blockedHostsRef.current.clear()
+ hostAuthorityEpochRef.current += 1
+ setHostAuthorityRevision(revision => revision + 1)
+ }, [authorityScope])
+ const blockHostAccess = useCallback(
+ (agentRef: string, kind: 'revoked' | 'uncertain') => {
+ const existing = blockedHostsRef.current.get(agentRef)
+ if (existing?.kind === 'revoked' && kind === 'uncertain') return
+ blockedHostsRef.current.set(agentRef, {
+ kind,
+ epoch: ++hostAuthorityEpochRef.current,
+ })
+ setHostAuthorityRevision(revision => revision + 1)
+ if (selectedAgentRef.current === agentRef) nav.setSelectedAgent(null)
void agentsData.refresh()
},
- [agentsData.refresh, nav.selectedAgent, nav.setSelectedAgent]
+ [agentsData.refresh, nav.setSelectedAgent]
+ )
+ const onHostAccessRevoked = useCallback(
+ (agentRef: string) => blockHostAccess(agentRef, 'revoked'),
+ [blockHostAccess]
+ )
+ const onHostAuthorityUncertain = useCallback(
+ (agentRef: string) => blockHostAccess(agentRef, 'uncertain'),
+ [blockHostAccess]
)
+ const verifyHostAccess = useCallback(async (agentRef: string): Promise<boolean> => {
+ const blocked = blockedHostsRef.current.get(agentRef)
+ if (!blocked) return true
+ const scope = authorityScopeRef.current
+ const epoch = blocked.epoch
+ try {
+ await window.clerum.rpc.listSessions(agentRef, undefined, { agent: agentRef, limit: 1 })
+ } catch {
+ return false
+ }
+ if (
+ authorityScopeRef.current !== scope ||
+ blockedHostsRef.current.get(agentRef)?.epoch !== epoch
+ )
+ return false
+ blockedHostsRef.current.delete(agentRef)
+ setHostAuthorityRevision(revision => revision + 1)
+ return true
+ }, [])
const chat = useAgentChatController({
selectedAgent: nav.selectedAgent,
agentNames: agentsData.agentNames,
@@ -339,7 +383,8 @@ export function useAppController() {
openAgentConversationFromNotification,
decideApprovalFromNotification,
onHostAccessRevoked,
- isHostAccessRevoked,
+ onHostAuthorityUncertain,
+ isHostAccessBlocked,
})
// §4.7.4: the ONE central approval-decision function, bound to the chat
@@ -617,7 +662,7 @@ export function useAppController() {
if (agentsData.accessCatalog && nav.selectedAgent) {
if (
!agentsData.agentNames.includes(nav.selectedAgent) ||
- isHostAccessRevoked(nav.selectedAgent)
+ isHostAccessBlocked(nav.selectedAgent)
) {
nav.setSelectedAgent(null)
}
@@ -628,7 +673,7 @@ export function useAppController() {
auth.isAuthenticated,
nav.selectedAgent,
nav.setSelectedAgent,
- isHostAccessRevoked,
+ isHostAccessBlocked,
])
const switchTeamForWorkspace = useCallback(
@@ -881,7 +926,7 @@ export function useAppController() {
])
// ─── Cross-domain: handleOpenAgentWorkspace ───
- const handleOpenAgentWorkspace = useCallback(
+ const openAgentWorkspace = useCallback(
(agentName: string, route: AgentWorkspaceRoute = AGENT_WORKSPACE_ROUTES.connectors) => {
if (!agentName) return
chat.setPendingChatSelection(agentName, null)
@@ -900,9 +945,25 @@ export function useAppController() {
nav.setSelectedAgentRoute,
]
)
+ const handleOpenAgentWorkspace = useCallback(
+ (agentName: string, route: AgentWorkspaceRoute = AGENT_WORKSPACE_ROUTES.connectors) => {
+ if (!agentName) return
+ if (!isHostAccessBlocked(agentName)) {
+ openAgentWorkspace(agentName, route)
+ return
+ }
+ const scope = authorityScopeRef.current
+ void verifyHostAccess(agentName).then(verified => {
+ if (verified && authorityScopeRef.current === scope) {
+ openAgentWorkspace(agentName, route)
+ }
+ })
+ },
+ [isHostAccessBlocked, openAgentWorkspace, verifyHostAccess]
+ )
// ─── Cross-domain: handleSelectChatAgent (Chat page agent picker) ───
- const handleSelectChatAgent = useCallback(
+ const selectChatAgent = useCallback(
(
agentName: string,
options: {
@@ -1003,6 +1064,22 @@ export function useAppController() {
nav.setSelectedAgentRoute,
]
)
+ const handleSelectChatAgent = useCallback(
+ (agentName: string, options: Parameters<typeof selectChatAgent>[1] = {}) => {
+ if (!agentName) return
+ if (!isHostAccessBlocked(agentName)) {
+ selectChatAgent(agentName, options)
+ return
+ }
+ const scope = authorityScopeRef.current
+ void verifyHostAccess(agentName).then(verified => {
+ if (verified && authorityScopeRef.current === scope) {
+ selectChatAgent(agentName, options)
+ }
+ })
+ },
+ [isHostAccessBlocked, selectChatAgent, verifyHostAccess]
+ )
// ─── Cross-domain: handleNavSelect (extended) ───
const handleNavSelect = useCallback(
@@ -1059,6 +1136,7 @@ export function useAppController() {
if (requiresTeamSwitch) {
await ensureTeamContext({ teamId: targetTeamId })
}
+ if (isHostAccessBlocked(targetAgent) && !(await verifyHostAccess(targetAgent))) return
if (stayInDrawer) {
// handleSelectChatAgent(keepNavItem) sets the active chat without
@@ -1112,6 +1190,8 @@ export function useAppController() {
ensureTeamContext,
fullSetStatus,
handleSelectChatAgent,
+ isHostAccessBlocked,
+ verifyHostAccess,
nav.activateChatTab,
nav.navItem,
nav.selectedAgent,
@@ -1358,6 +1438,8 @@ export function useAppController() {
// Navigation
navItem: nav.navItem,
selectedAgent: nav.selectedAgent,
+ isHostAccessBlocked,
+ hostAuthorityRevision,
selectedAgentRoute: nav.selectedAgentRoute,
setSelectedAgent: nav.setSelectedAgent,
handleNavSelect,
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index 4569da3cf..6c9373b91 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -68,8 +68,10 @@ export function useChatStore() {
window.clerum.chat.rename(agentRef, chatId, title),
[]
)
+ const getBindingGeneration = useCallback(() => window.clerum.chat.getBindingGeneration(), [])
const deleteChat = useCallback(
- (agentRef: string, chatId: string) => window.clerum.chat.delete(agentRef, chatId),
+ (agentRef: string, chatId: string, bindingGeneration: number) =>
+ window.clerum.chat.delete(agentRef, chatId, bindingGeneration),
[]
)
const loadMessages = useCallback(
@@ -244,6 +246,7 @@ export function useChatStore() {
listChats,
createChat,
renameChat,
+ getBindingGeneration,
deleteChat,
loadMessages,
appendMessages,
diff --git a/desktop-app/ui/src/lib/composerDraftStore.ts b/desktop-app/ui/src/lib/composerDraftStore.ts
index 8fce8e031..e0bf96f40 100644
--- a/desktop-app/ui/src/lib/composerDraftStore.ts
+++ b/desktop-app/ui/src/lib/composerDraftStore.ts
@@ -59,6 +59,15 @@ export function clearComposerDraftAfterSend(chatId: string | null): void {
if (chatId) clearComposerDraft(chatId)
}
+/** Drop drafts on logout or principal/team change and notify mounted composers. */
+export function clearAllComposerDrafts(): void {
+ for (const key of [...drafts.keys()]) {
+ drafts.delete(key)
+ revisions.set(key, ++revision)
+ emit(key)
+ }
+}
+
export function subscribeComposerDraft(chatId: string | null, listener: Listener): () => void {
const key = keyFor(chatId)
let listeners = listenersByKey.get(key)
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 961897acb..6c82a6548 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.352",
+ "version": "0.1.353",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.352",
+ "version": "0.1.353",
"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.json
index e0a845ff6..d69981a81 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.352",
+ "version": "0.1.353",
"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/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.ts
index b185932a9..1e7ca0f55 100644
--- a/host-context-controller/src/hostReconciler.test.ts
+++ b/host-context-controller/src/hostReconciler.test.ts
@@ -1420,9 +1420,7 @@ describe('HostReconciler Host inventory mutation authority', () => {
await releaseTokenProvision.promise
return { revision: 'stale-revision', scopeHash: 'stale-scope' }
})
- const ensureDeployment = vi
- .spyOn(reconciler as any, 'ensureDeployment')
- .mockResolvedValue(undefined)
+ const ensureDeployment = vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(true)
const pending = reconciler.reconcile(host)
await tokenProvisionStarted.promise
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index b84ae5337..9ab121fe1 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -3605,18 +3605,40 @@ export class HostReconciler {
private async ensureDeployment(
host: HostCRD,
mounts: ResolvedSfsMount[],
- runtimeTokenRevision: string,
+ runtimeTokenRevision: string | undefined,
lifecycle?: EffectiveHostLifecycle,
resolveStateBeforeMutation?: () => Promise<DeploymentMutationState>,
revalidate?: () => void
- ): Promise<void> {
- const buildDesiredDeployment = async (): Promise<k8s.V1Deployment> => {
+ ): Promise<boolean> {
+ let observedDeployment: k8s.V1Deployment | undefined
+ let holdingTemplate = false
+ let applied = true
+ const buildDesiredDeployment = async (): Promise<k8s.V1Deployment | null> => {
const state = resolveStateBeforeMutation ? await resolveStateBeforeMutation() : null
+ const effective = state?.lifecycle ?? lifecycle
+ holdingTemplate = effective?.suspensionBlocked === true
+ if (holdingTemplate) {
+ if (!observedDeployment) return null
+ const existing = observedDeployment
+ if (
+ !this.isHccOwnedHostResource(existing, host.name) ||
+ existing.metadata?.name !== host.name ||
+ existing.metadata?.namespace !== host.namespace ||
+ !existing.metadata?.uid ||
+ !existing.metadata?.resourceVersion ||
+ !existing.spec?.template?.spec
+ ) {
+ throw new Error(`Cannot preserve an unverified Deployment for Host "${host.name}"`)
+ }
+ // Preserve UID/resourceVersion and every applied field. Conflicts
+ // re-read this object before retrying; only replicas may change.
+ return { ...existing, spec: { ...existing.spec, replicas: 1 } }
+ }
return this.buildDeployment(
host,
mounts,
state?.runtimeTokenRevision ?? runtimeTokenRevision,
- state?.lifecycle ?? lifecycle,
+ effective,
state?.grokExecutionEnabled ?? this.hostDerivesGrokExecution(host)
)
}
@@ -3626,14 +3648,20 @@ export class HostReconciler {
}
await ensureResource({
mutationAllowed,
- read: () =>
- observeExistenceRead('Deployment', () =>
+ read: async () => {
+ observedDeployment = await observeExistenceRead('Deployment', () =>
this.appsApi.readNamespacedDeployment({ namespace: host.namespace, name: host.name })
- ),
+ )
+ return observedDeployment
+ },
create: async () => {
// The initial GET may outlive the lifecycle or token-scope observation.
const deployment = await buildDesiredDeployment()
revalidate?.()
+ if (!deployment) {
+ applied = false
+ return
+ }
return observeCreate('Deployment', () =>
this.appsApi.createNamespacedDeployment({ namespace: host.namespace, body: deployment })
)
@@ -3643,8 +3671,13 @@ export class HostReconciler {
replaceWithConflictRetry({
description: `Deployment "${host.name}"`,
logPrefix: '[HostReconciler]',
- resolveBody: buildDesiredDeployment,
- mergeExisting: preserveHostDeploymentAnnotations,
+ resolveBody: async () => {
+ const desired = await buildDesiredDeployment()
+ if (!desired) throw new Error('Deployment disappeared during preservation')
+ return desired
+ },
+ mergeExisting: (desired, existing) =>
+ holdingTemplate ? desired : preserveHostDeploymentAnnotations(desired, existing),
isUpToDate: deploymentMatchesDesired,
mutationAllowed,
read,
@@ -3656,6 +3689,7 @@ export class HostReconciler {
}),
}),
})
+ return applied
}
private async deleteRuntimeResources(name: string, namespace: string): Promise<void> {
@@ -4686,6 +4720,32 @@ export class HostReconciler {
})
}
+ const holdAppliedRuntime = async (): Promise<void> => {
+ const applied = await this.ensureDeployment(
+ host,
+ mounts,
+ undefined,
+ lifecycle.effective,
+ undefined,
+ revalidateHostMutationBoundary
+ )
+ revalidateHostMutationBoundary()
+ this.lifecycle.markHostNotSuspended(host.name)
+ const ready = applied && (await this.checkDeploymentReady(host.name, host.namespace))
+ revalidateHostMutationBoundary()
+ this.setStatus(host.name, {
+ deployed: applied,
+ ready,
+ message: applied
+ ? 'CommunicationChannel inventory unavailable; preserving applied runtime with one replica'
+ : 'Waiting for CommunicationChannel inventory before creating runtime',
+ })
+ }
+ if (lifecycle.effective.suspensionBlocked) {
+ await holdAppliedRuntime()
+ return
+ }
+
revalidateHostMutationBoundary()
await this.ensurePvc(host, revalidateHostMutationBoundary)
revalidateHostMutationBoundary()
@@ -4755,6 +4815,11 @@ export class HostReconciler {
}
revalidateHostMutationBoundary()
+ if (lifecycle.effective.suspensionBlocked) {
+ await holdAppliedRuntime()
+ return
+ }
+
// Bootstrap captures the scope contract used for issuance. The Deployment
// guard below compares that contract with the live channel cache after this
// potentially slow I/O and before every create/replace attempt.
@@ -4813,10 +4878,25 @@ export class HostReconciler {
const resolveDeploymentState = async (): Promise<DeploymentMutationState> => {
for (let attempt = 1; attempt <= 3; attempt++) {
revalidateHostMutationBoundary()
- await resolveDeploymentLifecycle()
+ const beforeScope = await resolveDeploymentLifecycle()
+ if (beforeScope.suspensionBlocked) {
+ return {
+ lifecycle: beforeScope,
+ runtimeTokenRevision: runtimeTokenProvision.revision,
+ grokExecutionEnabled: this.hostDerivesGrokExecution(host),
+ }
+ }
await ensureCurrentRuntimeTokenScope()
const effective = await resolveDeploymentLifecycle()
const currentScopeHash = this.runtimeScopeHashFor(host, await this.frontsOAuthServer(host))
+ // The OAuth lookup can await I/O after the last lifecycle observation.
+ // Retry assessment rather than committing a now-obsolete mode.
+ if (
+ this.lifecycle.enforceCommunicationChannelPolicyBeforeDeployment(host.name, lifecycle) !==
+ lifecycle
+ ) {
+ continue
+ }
if (runtimeTokenProvision.scopeHash === currentScopeHash) {
revalidateHostMutationBoundary()
return {
@@ -4837,7 +4917,7 @@ export class HostReconciler {
}
revalidateHostMutationBoundary()
- await this.ensureDeployment(
+ const deploymentApplied = await this.ensureDeployment(
host,
mounts,
runtimeTokenProvision.revision,
@@ -4847,6 +4927,15 @@ export class HostReconciler {
)
revalidateHostMutationBoundary()
+ if (!deploymentApplied) {
+ this.setStatus(host.name, {
+ deployed: false,
+ ready: false,
+ message: 'Waiting for CommunicationChannel inventory before creating runtime',
+ })
+ return
+ }
+
const suspended = lifecycle.effective.stateless && lifecycle.effective.state === 'suspended'
if (suspended) {
this.lifecycle.recordSuspendedApplied(host.name)
diff --git a/host-context-controller/src/statelessLifecycle.types.ts b/host-context-controller/src/statelessLifecycle.types.ts
index ffeeb016a..f63a6a5ed 100644
--- a/host-context-controller/src/statelessLifecycle.types.ts
+++ b/host-context-controller/src/statelessLifecycle.types.ts
@@ -9,12 +9,13 @@ 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 confirmed
- * incompatibility applies. Cache uncertainty keeps the stateless runtime
- * identity but blocks suspension until channel authority returns.
+ * incompatibility applies. Cache uncertainty blocks suspension and template
+ * selection; `stateless` then describes the request, not the applied mode.
*/
export interface EffectiveHostLifecycle {
stateless: boolean
state: HostLifecycleState
+ /** Unknown channel authority: preserve the entire applied Deployment template. */
suspensionBlocked?: boolean
}
diff --git a/host-context-controller/src/statelessLifecycleExecutor.ts b/host-context-controller/src/statelessLifecycleExecutor.ts
index 1551fbc10..a6e8292b4 100644
--- a/host-context-controller/src/statelessLifecycleExecutor.ts
+++ b/host-context-controller/src/statelessLifecycleExecutor.ts
@@ -11,6 +11,7 @@ import { config } from './config'
import { isHeartbeatManagedLifecycleReason } from './constants'
import type { ResolvedSfsMount } from './hostReconciler'
import { SFS_LABEL, SFS_NAMESPACE_LABEL, WFC_APP_LABEL } from './k8s/sharedFileSystemFactory'
+import { hccLogger } from './logger'
import {
STATELESS_PULL_POLICY_REJECTED_CONDITION_TYPE,
pullPolicyNotApplicableCondition,
@@ -25,6 +26,7 @@ import { HostCRD, HostCondition, HostCrdStatus, HostLifecycleStatus } from './ty
import { getErrorCode } from './utils'
// ─── Stateless lifecycle (Stage 2) ─────────────────────────────────────────
+const log = hccLogger.child({ module: 'stateless-lifecycle' })
const GROUP = 'clerum.io'
const VERSION = 'v1alpha1'
const PLURAL_HOSTS = 'hosts'
@@ -185,7 +187,7 @@ export class StatelessLifecycleExecutor {
return
}
StatelessLifecycleExecutor.singleReplicaInvariantWarned = true
- console.warn(
+ log.warn(
'[HostReconciler] Stateless lifecycle status writes assume HCC runs replicas:1 WITHOUT leader election. serializeByHost orders writers within this process; the resourceVersion precondition + 409-retry closes the cross-writer window — but neither elects a leader. Running >1 replica risks two controllers racing (safe against corruption, but can livelock).'
)
}
@@ -217,7 +219,8 @@ export class StatelessLifecycleExecutor {
if (host.spec.lifecycle?.stateless !== true) {
return { stateless: false, state: 'active' }
}
- const hasCommunicationChannels = this.countCommunicationChannels(host.name) > 0
+ const hasCommunicationChannels =
+ this.isCommunicationChannelCacheSynced() && this.countCommunicationChannels(host.name) > 0
if (host.spec.desktop !== undefined || hasCommunicationChannels) {
return { stateless: false, state: 'active' }
}
@@ -233,7 +236,10 @@ export class StatelessLifecycleExecutor {
} {
const reasons: string[] = []
const messages: string[] = []
- const ccCount = this.countCommunicationChannels(hostName)
+ // A retained positive entry is no more authoritative than an empty cache.
+ const ccCount = this.isCommunicationChannelCacheSynced()
+ ? this.countCommunicationChannels(hostName)
+ : 0
if (ccCount > 0) {
// Addendum 6 (operator visibility): the rejection message names both the
// associated channel count AND the recovery action, because control-ui
@@ -350,7 +356,7 @@ export class StatelessLifecycleExecutor {
}
}
- /** Unknown channel inventory blocks suspension without changing the runtime template. */
+ /** Unknown channel inventory requires preserving the applied Deployment. */
private holdActiveDuringChannelCacheRecovery(
wakeHandledGeneration: number
): HostLifecycleAssessment {
@@ -374,8 +380,8 @@ export class StatelessLifecycleExecutor {
/**
* Close the interval between the initial lifecycle assessment and the
* Deployment write. Reconciliation performs several Kubernetes operations
- * in between; if the CommunicationChannel watch ends, retain the stateless
- * template but hold the Host active. A confirmed channel still applies the
+ * in between; if the CommunicationChannel watch ends, retain the applied
+ * template, whose mode may be stateful. A confirmed channel still applies the
* established incompatible-mode policy.
*
* This synchronous cache check adds no Kubernetes API calls to steady state.
@@ -385,6 +391,14 @@ export class StatelessLifecycleExecutor {
assessment: HostLifecycleAssessment
): HostLifecycleAssessment {
if (!assessment.effective.stateless) {
+ // Independent desktop/SFS incompatibilities retain their policy. A
+ // channel-only rejection cannot choose a runtime after authority is lost.
+ if (
+ !this.isCommunicationChannelCacheSynced() &&
+ assessment.condition.reason === ACTIVE_COMMUNICATION_CHANNELS_REASON
+ ) {
+ return this.holdActiveDuringChannelCacheRecovery(assessment.lifecycle.wakeHandledGeneration)
+ }
return assessment
}
@@ -441,9 +455,9 @@ export class StatelessLifecycleExecutor {
}
}
} catch (err) {
- console.warn(
+ log.warn(
`[HostReconciler] Could not resolve wfc node placement for SFS "${m.namespace}/${m.name}" (host "${host.name}"); skipping the co-location rejection check:`,
- err
+ { err }
)
return null
}
@@ -650,9 +664,9 @@ export class StatelessLifecycleExecutor {
} catch (err) {
// Best-effort: a status-write failure (including 409-retry exhaustion)
// is logged, not thrown — status writes must not block reconciliation.
- console.error(
+ log.error(
`[HostReconciler] Failed to write lifecycle status for "${host.name}" (${getErrorCode(err) ?? 'no code'}):`,
- err
+ { err }
)
return false
}
@@ -803,7 +817,7 @@ export class StatelessLifecycleExecutor {
// newer evidence. A fresh `suspended` returns as a SILENT idempotent
// no-op: the drained-report retry path relies on exactly that.
if (freshLifecycle?.state !== 'suspended') {
- console.log(
+ log.info(
`[HostReconciler] Suspend of stateless Host "${host.name}" skipped — fresh state "${freshLifecycle?.state ?? 'active'}" is not draining (drain decision overturned)`
)
}
@@ -827,7 +841,7 @@ export class StatelessLifecycleExecutor {
// with no reviver.
const freshHandled = freshLifecycle.wakeHandledGeneration ?? 0
if (freshHandled > entryWakeHandledGeneration) {
- console.log(
+ log.info(
`[StatelessSuspend] host=${host.name} phase=drained_report_stale reason=wake_handled_since entryGeneration=${entryWakeHandledGeneration} freshGeneration=${freshHandled} ts=${this.now().getTime()}`
)
return { skip: true }
@@ -839,7 +853,7 @@ export class StatelessLifecycleExecutor {
// suspended state that must immediately be overturned.
const freshRequested = this.wakeRequestedGeneration(fresh)
if (freshRequested > freshHandled) {
- console.log(
+ log.info(
`[StatelessSuspend] host=${host.name} phase=drained_report_stale reason=wake_pending requestedGeneration=${freshRequested} handledGeneration=${freshHandled} ts=${this.now().getTime()}`
)
return { skip: true }
@@ -886,7 +900,7 @@ export class StatelessLifecycleExecutor {
}
this.lastWrittenLifecycleStatus.delete(host.name)
this.logSuspendedApplied(host.name)
- console.log(
+ log.info(
`[HostReconciler] Suspending stateless Host "${host.name}" (reason: ${reason}) — reconciling to replicas=0`
)
// L2: call reconcileCore (not the serialized reconcile) — this method
@@ -1073,7 +1087,7 @@ export class StatelessLifecycleExecutor {
// evidence.
const freshHandled = freshLifecycle?.wakeHandledGeneration ?? 0
if (freshHandled > entryWakeHandledGeneration) {
- console.log(
+ log.info(
`[StatelessSuspend] host=${host.name} phase=draining_write_stale reason=wake_handled_since entryGeneration=${entryWakeHandledGeneration} freshGeneration=${freshHandled} ts=${this.now().getTime()}`
)
return { skip: true }
@@ -1082,7 +1096,7 @@ export class StatelessLifecycleExecutor {
// by definition ("pending wake wins") — never fence over it.
const freshRequested = this.wakeRequestedGeneration(fresh)
if (freshRequested > freshHandled) {
- console.log(
+ log.info(
`[StatelessSuspend] host=${host.name} phase=draining_write_stale reason=wake_pending requestedGeneration=${freshRequested} handledGeneration=${freshHandled} ts=${this.now().getTime()}`
)
return { skip: true }
@@ -1104,7 +1118,7 @@ export class StatelessLifecycleExecutor {
target.status = writtenStatus
})
this.lastWrittenLifecycleStatus.delete(host.name)
- console.log(
+ log.info(
`[HostReconciler] Marked stateless Host "${host.name}" draining — control-api now answers {drain:true} from Host.status`
)
}
@@ -1169,7 +1183,7 @@ export class StatelessLifecycleExecutor {
revalidate
)
if ('skipped' in result || writtenStatus === undefined) {
- console.log(
+ log.info(
`[StatelessLifecycle] host=${host.name} cancel-drain skipped — fresh state "${skippedNotDraining ?? 'active'}" is not draining`
)
return
@@ -1178,7 +1192,7 @@ export class StatelessLifecycleExecutor {
target.status = writtenStatus
})
this.lastWrittenLifecycleStatus.delete(host.name)
- console.log(
+ log.info(
`[StatelessLifecycle] host=${host.name} cancel-drain: activity evidence while draining — reverting status to active`
)
}
@@ -1219,7 +1233,7 @@ export class StatelessLifecycleExecutor {
if (Number.isNaN(parsed)) {
if (this.malformedWakeAnnotationLogged.get(host.name) !== raw) {
this.malformedWakeAnnotationLogged.set(host.name, raw)
- console.error(
+ log.error(
`[HostReconciler] Malformed ${WAKE_REQUESTED_ANNOTATION} annotation on Host "${host.name}": ${JSON.stringify(
raw
)} is not an integer; treating it as no wake intent`
@@ -1277,9 +1291,9 @@ export class StatelessLifecycleExecutor {
try {
initialFresh = await this.readFreshHost(host)
} catch (err) {
- console.error(
+ log.error(
`[HostReconciler] Wake fast-path fresh Host read failed for "${host.name}" (${getErrorCode(err) ?? 'no code'}):`,
- err
+ { err }
)
return false
}
@@ -1300,12 +1314,12 @@ export class StatelessLifecycleExecutor {
}
const currentState = initialFresh.status?.lifecycle?.state ?? 'active'
- console.log(
+ log.info(
`[HostReconciler] Wake fast-path for "${host.name}": generation ${freshWakeRequested} > handled ${freshWakeHandled} while ${currentState}`
)
// Stage 6 (W2): machine-parseable wake-phase timestamps for the
// wake-budget script. One line per phase, correlated by generation.
- console.log(
+ log.info(
`[StatelessWake] host=${host.name} generation=${freshWakeRequested} phase=wake_observed ts=${this.now().getTime()}`
)
@@ -1366,9 +1380,9 @@ export class StatelessLifecycleExecutor {
// lost — the annotation is durable and the drained-pre-scale guard in
// reconcile() re-checks it before any replicas:0 apply, so a pending
// wake can never be raced away by the suspension.
- console.error(
+ log.error(
`[HostReconciler] Wake fast-path status write failed for "${host.name}" (${getErrorCode(err) ?? 'no code'}):`,
- err
+ { err }
)
return false
}
@@ -1381,7 +1395,7 @@ export class StatelessLifecycleExecutor {
target.annotations = latestFresh.annotations
target.status = reflectedStatus
})
- console.log(
+ log.info(
`[StatelessWake] host=${host.name} generation=${writtenLifecycle.wakeHandledGeneration} phase=status_flipped ts=${this.now().getTime()}`
)
@@ -1391,6 +1405,10 @@ export class StatelessLifecycleExecutor {
return false
}
+ // Cache recovery uses the full reconcile's owned, resource-version-fenced
+ // replica-only update. Do not send the unfenced wake scale patch here.
+ if (!this.isCommunicationChannelCacheSynced()) return false
+
// Minimal scale patch — NOT the full buildDeployment replace. It also
// starts the pod even when the heavy body aborts early (e.g. on a
// transient Secret read failure).
@@ -1403,8 +1421,8 @@ export class StatelessLifecycleExecutor {
],
}
)
- console.log(`[HostReconciler] Wake fast-path scaled Deployment "${host.name}" to replicas=1`)
- console.log(
+ log.info(`[HostReconciler] Wake fast-path scaled Deployment "${host.name}" to replicas=1`)
+ log.info(
`[StatelessWake] host=${host.name} generation=${writtenLifecycle.wakeHandledGeneration} phase=replicas_patched ts=${this.now().getTime()}`
)
this.markHostNotSuspended(host.name)
@@ -1414,7 +1432,7 @@ export class StatelessLifecycleExecutor {
if (getErrorCode(err) === 404) {
// Deployment missing (e.g. deleted while suspended): fall through —
// the full reconcile below builds it with replicas=1.
- console.log(
+ log.info(
`[HostReconciler] Wake fast-path: Deployment "${host.name}" not found; the full reconcile will create it`
)
return true
@@ -1437,29 +1455,27 @@ export class StatelessLifecycleExecutor {
namespace: host.namespace,
body: deployment,
})
- console.warn(
+ log.warn(
`[HostReconciler] Wake fast-path scale patch forbidden for "${host.name}"; used deployment update fallback`
)
- console.log(
- `[HostReconciler] Wake fast-path scaled Deployment "${host.name}" to replicas=1`
- )
- console.log(
+ log.info(`[HostReconciler] Wake fast-path scaled Deployment "${host.name}" to replicas=1`)
+ log.info(
`[StatelessWake] host=${host.name} generation=${writtenLifecycle.wakeHandledGeneration} phase=replicas_patched ts=${this.now().getTime()}`
)
this.markHostNotSuspended(host.name)
this.recordScaleTransition(host.name, 'up')
return true
} catch (fallbackErr) {
- console.error(
+ log.error(
`[HostReconciler] Wake fast-path deployment update fallback failed for "${host.name}":`,
- fallbackErr
+ { err: fallbackErr }
)
return true
}
}
// Surfaced loudly; ensureDeployment in this same reconcile pass
// replaces the Deployment with replicas=1, so nothing is masked.
- console.error(`[HostReconciler] Wake fast-path scale patch failed for "${host.name}":`, err)
+ log.error(`[HostReconciler] Wake fast-path scale patch failed for "${host.name}":`, { err })
return true
}
}
@@ -1473,7 +1489,7 @@ export class StatelessLifecycleExecutor {
private recordScaleTransition(hostName: string, direction: 'up' | 'down'): void {
const total = (this.scaleTransitionsByHost.get(hostName) ?? 0) + 1
this.scaleTransitionsByHost.set(hostName, total)
- console.log(
+ log.info(
`[StatelessMetric] scale_transition host=${hostName} direction=${direction} total=${total}`
)
}
@@ -1492,7 +1508,7 @@ export class StatelessLifecycleExecutor {
return
}
this.suspendedAppliedLoggedByHost.add(hostName)
- console.log(
+ log.info(
`[StatelessSuspend] host=${hostName} phase=suspended_applied ts=${this.now().getTime()}`
)
}
@@ -1591,7 +1607,7 @@ export class StatelessLifecycleExecutor {
// The CR changed under us (a concurrent lifecycle writer or an
// unrelated metadata write). Re-read fresh and re-evaluate the
// guard so a decision the racing writer just made is respected.
- console.warn(
+ log.warn(
`[HostReconciler] Status write for "${host.name}" hit 409 (stale resourceVersion); re-reading fresh and retrying (attempt ${attempt}/${maxAttempts})`
)
fresh = undefined
@@ -1778,16 +1794,16 @@ export class StatelessLifecycleExecutor {
// Fail loud and skip the scale-down this pass: a suspend derived from
// a possibly-stale cache must NOT strand a racing wake at replicas:0.
// The periodic resync re-runs this reconcile with a fresh cache.
- console.error(
+ log.error(
`[HostReconciler] Drained-pre-scale guard for "${host.name}": fresh Host read failed; skipping replicas=0 this pass (resync will retry):`,
- err
+ { err }
)
} else {
// Same posture in the mirror direction: never commit replicas from a
// possibly-stale cached state when the fresh read is unavailable.
- console.error(
+ log.error(
`[HostReconciler] Stateless replicas guard for "${host.name}": fresh Host read failed; skipping the Deployment scale this pass (resync will retry):`,
- err
+ { err }
)
}
return null
@@ -1797,7 +1813,7 @@ export class StatelessLifecycleExecutor {
const freshState = fresh.status?.lifecycle?.state ?? 'active'
if (freshWakeRequested > freshWakeHandled) {
if (cachedState === 'suspended') {
- console.log(
+ log.info(
`[HostReconciler] Drained-pre-scale guard for "${host.name}": aborting replicas=0 — fresh wake generation ${freshWakeRequested} > handled ${freshWakeHandled}`
)
// A wake is pending in the fresh read — run the wake transition
@@ -1826,7 +1842,7 @@ export class StatelessLifecycleExecutor {
if ((cachedState === 'suspended') === freshSuspended) {
return assessment
}
- console.log(
+ log.info(
`[HostReconciler] Stateless replicas guard for "${host.name}": cached lifecycle state "${cachedState}" disagrees with fresh "${freshState}" — deriving replicas from FRESH state`
)
// Reflect fresh onto the in-memory host (mirroring the wake fast-path's
diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.ts
index 98e47c660..a1d9c7853 100644
--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts
+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts
@@ -1076,7 +1076,7 @@ describe('HostReconciler.suspendHostFromHeartbeat', () => {
expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
expect(host.status?.lifecycle?.state).toBe('draining')
const staleLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=drained_report_stale'))
expect(staleLines).toEqual([
expect.stringMatching(
@@ -1117,7 +1117,7 @@ describe('HostReconciler.suspendHostFromHeartbeat', () => {
expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()
expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
const staleLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=drained_report_stale'))
expect(staleLines).toEqual([
expect.stringMatching(
@@ -1876,7 +1876,7 @@ describe('HostReconciler.markHostDrainingFromHeartbeat — AP-1 entry-epoch guar
expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()
expect(host.status?.lifecycle?.state).toBe('active')
const staleLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=draining_write_stale'))
expect(staleLines).toEqual([
expect.stringMatching(
@@ -1914,7 +1914,7 @@ describe('HostReconciler.markHostDrainingFromHeartbeat — AP-1 entry-epoch guar
expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()
const staleLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=draining_write_stale'))
expect(staleLines).toEqual([
expect.stringMatching(
@@ -2018,7 +2018,7 @@ describe('HostReconciler reconcile — stateless replicas derive from FRESH stat
// pod is never scaled to 0.
expect(hostDeploymentBody(appsApi, 'stateless-host').spec?.replicas).toBe(1)
const guardLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('disagrees with fresh'))
expect(guardLines).toEqual([
'[HostReconciler] Stateless replicas guard for "stateless-host": cached lifecycle state "suspended" disagrees with fresh "active" — deriving replicas from FRESH state',
diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.ts
index a92d82a45..6c894cebd 100644
--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts
+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts
@@ -195,6 +195,28 @@ function runtimeTokenProvision(host: HostCRD, hasChannelIngress = false) {
}
}
+/** Model persisted API state so a loss-of-authority test cannot invent a template. */
+function persistHostDeployment(appsApi: MockAppsApi, host: HostCRD, initial: k8s.V1Deployment) {
+ let live = structuredClone(initial)
+ live.metadata = {
+ ...live.metadata,
+ uid: live.metadata?.uid ?? 'deployment-uid',
+ resourceVersion: live.metadata?.resourceVersion ?? '73',
+ }
+ const read = appsApi.readNamespacedDeployment.getMockImplementation()!
+ appsApi.readNamespacedDeployment.mockImplementation(request =>
+ request.name === host.name ? Promise.resolve(structuredClone(live)) : read(request)
+ )
+ const replace = appsApi.replaceNamespacedDeployment.getMockImplementation()!
+ appsApi.replaceNamespacedDeployment.mockImplementation(async request => {
+ if (request.name !== host.name) return replace(request)
+ expect(request.body.metadata.resourceVersion).toBe(live.metadata!.resourceVersion)
+ live = structuredClone(request.body)
+ return live
+ })
+ return () => live
+}
+
/** The mcp-host Deployment body sent to the K8s API (excludes channel-reader). */
function hostDeploymentBody(appsApi: MockAppsApi, name: string): k8s.V1Deployment {
const calls = [
@@ -737,6 +759,246 @@ describe('HostReconciler stateless lifecycle — env injection', () => {
})
describe('HostReconciler stateless lifecycle — rejection matrix', () => {
+ it('preserves a rejected stateful runtime across cold channel LIST failure and recovery', async () => {
+ const host = makeStatelessHost()
+ const previous = createReconciler({ countCommunicationChannels: () => 1 })
+ previous.customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ vi.spyOn(previous.reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue(
+ runtimeTokenProvision(host, true)
+ )
+ await previous.reconciler.reconcile(host)
+ host.status = lifecycleStatusWrites(previous.customApi).at(-1)
+ expect(rejectedCondition(host.status!).reason).toBe('ActiveCommunicationChannels')
+ const applied = hostDeploymentBody(previous.appsApi, host.name)
+ applied.metadata = { ...applied.metadata, uid: 'deployment-uid', resourceVersion: '73' }
+ const baseline = JSON.stringify(applied.spec!.template)
+ expect(containerEnv(applied).some(entry => entry.name === 'CLERUM_STATELESS_LIFECYCLE')).toBe(
+ false
+ )
+ let synced = false
+ let channels = 0
+ const { reconciler, appsApi, customApi } = createReconciler({
+ countCommunicationChannels: () => channels,
+ isCommunicationChannelCacheSynced: () => synced,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const live = persistHostDeployment(appsApi, host, applied)
+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue(
+ runtimeTokenProvision(host, true)
+ )
+ await reconciler.reconcile(host)
+ expect(JSON.stringify(live().spec!.template)).toBe(baseline)
+ expect(live().spec!.replicas).toBe(1)
+ expect(
+ appsApi.replaceNamespacedDeployment.mock.calls.filter(([r]) => r.name === host.name)
+ ).toHaveLength(0)
+ host.status = lifecycleStatusWrites(customApi).at(-1)
+ synced = true
+ channels = 1
+ await reconciler.reconcile(host)
+ expect(JSON.stringify(live().spec!.template)).toBe(baseline)
+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(
+ 'ActiveCommunicationChannels'
+ )
+ })
+
+ it('does not use a stale positive channel cache to change an applied stateless template', async () => {
+ const host = makeStatelessHost()
+ const { reconciler, appsApi, customApi } = createReconciler({
+ countCommunicationChannels: () => 1,
+ isCommunicationChannelCacheSynced: () => false,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = createReconciler().reconciler.buildDeployment(host)
+ applied.metadata = { ...applied.metadata, uid: 'deployment-uid', resourceVersion: '74' }
+ const live = persistHostDeployment(appsApi, host, applied)
+ await reconciler.reconcile(host)
+ expect(live().spec!.template).toEqual(applied.spec!.template)
+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(
+ 'CommunicationChannelCacheUnsynced'
+ )
+ })
+
+ it('defers creating a missing Deployment until the channel inventory is authoritative', async () => {
+ let synced = false
+ const host = makeStatelessHost()
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => synced,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const read = appsApi.readNamespacedDeployment.getMockImplementation()!
+ appsApi.readNamespacedDeployment.mockImplementation(request =>
+ request.name === host.name ? Promise.reject({ code: 404 }) : read(request)
+ )
+ await reconciler.reconcile(host)
+ expect(
+ appsApi.createNamespacedDeployment.mock.calls.filter(
+ ([r]) => r.body.metadata.name === host.name
+ )
+ ).toHaveLength(0)
+ expect(reconciler.getStatus(host.name)).toMatchObject({ deployed: false, ready: false })
+ synced = true
+ await reconciler.reconcile(host)
+ expect(
+ appsApi.createNamespacedDeployment.mock.calls.filter(
+ ([r]) => r.body.metadata.name === host.name
+ )
+ ).toHaveLength(1)
+ })
+
+ it('re-reads the applied template after a scale conflict and preserves the fresh UID and revision', async () => {
+ const host = makeStatelessHost({ status: suspendedStatus() })
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => false,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = createReconciler().reconciler.buildDeployment(host)
+ let current = structuredClone(applied)
+ current.metadata = { ...current.metadata, uid: 'deployment-uid', resourceVersion: '41' }
+ const baseline = JSON.stringify(current.spec!.template)
+ appsApi.readNamespacedDeployment.mockImplementation(async () => structuredClone(current))
+ appsApi.replaceNamespacedDeployment.mockImplementation(async request => {
+ expect(request.body.metadata.uid).toBe('deployment-uid')
+ expect(request.body.metadata.resourceVersion).toBe(current.metadata!.resourceVersion)
+ expect(request.body.spec.template).toEqual(current.spec!.template)
+ if (current.metadata!.resourceVersion === '41') {
+ current.metadata!.resourceVersion = '42'
+ current.spec!.template.metadata!.annotations = { 'example.org/rollout': 'fresh' }
+ throw { code: 409 }
+ }
+ current = structuredClone(request.body)
+ return current
+ })
+ await reconciler.reconcile(host)
+ expect(appsApi.replaceNamespacedDeployment).toHaveBeenCalledTimes(2)
+ expect(current.spec!.replicas).toBe(1)
+ expect(JSON.stringify(applied.spec!.template)).toBe(baseline)
+ expect(current.spec!.template.metadata!.annotations).toEqual({ 'example.org/rollout': 'fresh' })
+ })
+
+ it.each(['foreign owner', 'missing UID', 'missing resourceVersion'])(
+ 'does not scale an unverified Deployment during cache loss: %s',
+ async invalid => {
+ const host = makeStatelessHost({ status: suspendedStatus() })
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => false,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = createReconciler().reconciler.buildDeployment(host)
+ applied.metadata = { ...applied.metadata, uid: 'deployment-uid', resourceVersion: '73' }
+ if (invalid === 'foreign owner') applied.metadata.labels!['clerum.io/host'] = 'another-host'
+ if (invalid === 'missing UID') delete applied.metadata.uid
+ if (invalid === 'missing resourceVersion') delete applied.metadata.resourceVersion
+ appsApi.readNamespacedDeployment.mockResolvedValue(applied)
+ await expect(reconciler.reconcile(host)).rejects.toThrow('unverified Deployment')
+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()
+ expect(appsApi.patchNamespacedDeployment).not.toHaveBeenCalled()
+ }
+ )
+
+ it('holds the existing template when channel authority is lost during runtime provisioning', async () => {
+ let synced = true
+ const host = makeStatelessHost({ status: suspendedStatus() })
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => synced,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = reconciler.buildDeployment(host)
+ applied.spec!.template.metadata!.annotations = { 'example.org/applied': 'keep-exactly' }
+ const live = persistHostDeployment(appsApi, host, applied)
+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockImplementation(async () => {
+ synced = false
+ return runtimeTokenProvision(host)
+ })
+ await reconciler.reconcile(host)
+ expect(live().spec!.replicas).toBe(1)
+ expect(live().spec!.template).toEqual(applied.spec!.template)
+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(
+ 'CommunicationChannelCacheUnsynced'
+ )
+ })
+
+ it('uses the fenced replica-only update for a pending wake during cache loss', async () => {
+ const host = makeStatelessHost({ status: suspendedStatus() })
+ host.annotations = { 'clerum.io/wake-requested': '1' }
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => false,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = createReconciler().reconciler.buildDeployment(host)
+ const live = persistHostDeployment(appsApi, host, applied)
+ await reconciler.reconcile(host)
+ expect(appsApi.patchNamespacedDeployment).not.toHaveBeenCalled()
+ expect(live().spec!.replicas).toBe(1)
+ expect(live().spec!.template).toEqual(applied.spec!.template)
+ })
+
+ it('does not apply a channel rejection after that inventory loses authority mid-reconcile', async () => {
+ let synced = true
+ const host = makeStatelessHost()
+ const { reconciler, appsApi, customApi, networkingApi } = createReconciler({
+ countCommunicationChannels: () => 1,
+ isCommunicationChannelCacheSynced: () => synced,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = createReconciler().reconciler.buildDeployment(host)
+ const live = persistHostDeployment(appsApi, host, applied)
+ const readPolicy = networkingApi.readNamespacedNetworkPolicy.getMockImplementation()!
+ networkingApi.readNamespacedNetworkPolicy.mockImplementation(async request => {
+ synced = false
+ return readPolicy(request)
+ })
+ await reconciler.reconcile(host)
+ expect(live().spec!.template).toEqual(applied.spec!.template)
+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(
+ 'CommunicationChannelCacheUnsynced'
+ )
+ })
+
+ it('preserves the template when authority is lost during the final asynchronous scope lookup', async () => {
+ let synced = true
+ let lookup = 0
+ const host = makeStatelessHost()
+ const { reconciler, appsApi, customApi } = createReconciler({
+ isCommunicationChannelCacheSynced: () => synced,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ const applied = reconciler.buildDeployment(host)
+ applied.spec!.template.metadata!.annotations = { 'example.org/applied': 'keep-exactly' }
+ const live = persistHostDeployment(appsApi, host, applied)
+ vi.spyOn(reconciler as any, 'provisionRuntimeTokenRevision').mockResolvedValue(
+ runtimeTokenProvision(host)
+ )
+ vi.spyOn(reconciler as any, 'frontsOAuthServer').mockImplementation(async () => {
+ if (++lookup === 2) synced = false
+ return false
+ })
+ await reconciler.reconcile(host)
+ expect(lookup).toBe(2)
+ expect(live().spec!.template).toEqual(applied.spec!.template)
+ expect(rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!).reason).toBe(
+ 'CommunicationChannelCacheUnsynced'
+ )
+ })
+
+ it('preserves an independently confirmed desktop rejection while the channel cache is unknown', async () => {
+ const host = makeStatelessHost({ spec: { desktop: { browser: true } } })
+ const { reconciler, appsApi, customApi } = createReconciler({
+ countCommunicationChannels: () => 1,
+ isCommunicationChannelCacheSynced: () => false,
+ })
+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
+ await reconciler.reconcile(host)
+ const condition = rejectedCondition(lifecycleStatusWrites(customApi).at(-1)!)
+ expect(condition.reason).toBe('DesktopEnabled')
+ expect(condition.status).toBe('True')
+ expect(
+ containerEnv(hostDeploymentBody(appsApi, host.name)).some(
+ entry => entry.name === 'CLERUM_STATELESS_LIFECYCLE'
+ )
+ ).toBe(false)
+ })
+
it('reconciles an active Host twice through cache loss without changing its session path or template', async () => {
let cacheSynced = true
const host = makeStatelessHost({
@@ -749,10 +1011,9 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
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'
- )
+ const live = persistHostDeployment(appsApi, host, hostDeploymentBody(appsApi, host.name))
+ const baseline = structuredClone(live().spec?.template)
+ expect(envValue(live(), 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')
for (let cycle = 1; cycle <= 2; cycle++) {
cacheSynced = false
@@ -763,7 +1024,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
appsApi.replaceNamespacedDeployment.mockClear()
await reconciler.reconcile(host)
- const deployment = hostDeploymentBody(appsApi, host.name)
+ const deployment = live()
expect(deployment.spec?.replicas).toBe(1)
expect(deployment.spec?.template).toEqual(baseline)
expect(envValue(deployment, 'CLERUM_SESSION_DB_DIR')).toBe('/var/lib/clerum/state')
@@ -776,7 +1037,13 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
'CommunicationChannelCacheUnsynced'
)
expect(lifecycleStatusWrites(customApi).at(-1)?.lifecycle?.state).toBe('active')
+ expect(
+ appsApi.replaceNamespacedDeployment.mock.calls.filter(([r]) => r.name === host.name)
+ ).toHaveLength(0)
cacheSynced = true
+ serverHost = host
+ await reconciler.reconcile(host)
+ expect(live().spec?.template).toEqual(baseline)
}
})
@@ -784,9 +1051,15 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
const { reconciler, appsApi, customApi } = createReconciler({
isCommunicationChannelCacheSynced: () => false,
})
- await reconciler.reconcile(makeStatelessHost({ status: suspendedStatus() }))
+ const host = makeStatelessHost({ status: suspendedStatus() })
+ const live = persistHostDeployment(
+ appsApi,
+ host,
+ createReconciler().reconciler.buildDeployment(host)
+ )
+ await reconciler.reconcile(host)
- const deployment = hostDeploymentBody(appsApi, 'stateless-host')
+ const deployment = live()
expect(deployment.spec?.replicas).toBe(1)
expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')
expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')
@@ -805,6 +1078,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
isCommunicationChannelCacheSynced: () => cacheSynced,
})
const host = makeStatelessHost({ status: suspendedStatus(4) })
+ const live = persistHostDeployment(appsApi, host, reconciler.buildDeployment(host))
customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
const readPolicy = networkingApi.readNamespacedNetworkPolicy.getMockImplementation()!
networkingApi.readNamespacedNetworkPolicy.mockImplementation(async request => {
@@ -818,12 +1092,8 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
await reconciler.reconcile(host)
expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalled()
- expect(provision).toHaveBeenCalledOnce()
- expect(provision).toHaveBeenCalledWith(
- host,
- expect.objectContaining({ targetSuspended: false })
- )
- const deployment = hostDeploymentBody(appsApi, host.name)
+ expect(provision).not.toHaveBeenCalled()
+ const deployment = live()
expect(deployment.spec?.replicas).toBe(1)
expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')
expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')
@@ -1100,7 +1370,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
expect(provision).toHaveBeenCalledOnce()
})
- it('does not repeat bootstrap provisioning for active cache loss without channels', async () => {
+ it('does not bootstrap new runtime credentials for active cache loss without channels', async () => {
let cacheSynced = true
const { reconciler, appsApi, customApi, networkingApi } = createReconciler({
isCommunicationChannelCacheSynced: () => cacheSynced,
@@ -1108,6 +1378,7 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
const host = makeStatelessHost({
status: { lifecycle: { state: 'active', wakeHandledGeneration: 1 } },
})
+ const live = persistHostDeployment(appsApi, host, reconciler.buildDeployment(host))
customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))
const readPolicy = networkingApi.readNamespacedNetworkPolicy.getMockImplementation()!
networkingApi.readNamespacedNetworkPolicy.mockImplementation(async request => {
@@ -1121,8 +1392,8 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {
await reconciler.reconcile(host)
expect(networkingApi.readNamespacedNetworkPolicy).toHaveBeenCalled()
- expect(provision).toHaveBeenCalledOnce()
- const deployment = hostDeploymentBody(appsApi, host.name)
+ expect(provision).not.toHaveBeenCalled()
+ const deployment = live()
expect(deployment.spec?.replicas).toBe(1)
expect(envValue(deployment, 'CLERUM_STATELESS_LIFECYCLE')).toBe('true')
expect(envValue(deployment, 'CLERUM_SESSION_STORE')).toBe('sqlite')
diff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.ts
index 3f7964cf1..1754a9d17 100644
--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts
+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts
@@ -217,7 +217,7 @@ describe('HostReconciler.reconcile — NP wiring', () => {
})
vi.spyOn(reconciler as any, 'ensurePvc').mockResolvedValue(undefined)
vi.spyOn(reconciler as any, 'ensureService').mockResolvedValue(undefined)
- vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(undefined)
+ vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(true)
vi.spyOn(reconciler as any, 'ensureDesktopNetworkPolicy').mockResolvedValue(undefined)
vi.spyOn(reconciler as any, 'reconcileChannelReaderDeployment').mockResolvedValue(undefined)
vi.spyOn(reconciler as any, 'checkDeploymentReady').mockResolvedValue(true)
@@ -230,7 +230,7 @@ describe('HostReconciler.reconcile — NP wiring', () => {
const ingressSpy = vi
.spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy')
.mockResolvedValue(undefined)
- const deploySpy = vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(undefined)
+ const deploySpy = vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(true)
const readySpy = vi.spyOn(reconciler as any, 'checkDeploymentReady').mockResolvedValue(true)
await reconciler.reconcile(HOST)
diff --git a/host-context-controller/test/hostReconciler.wake.test.ts b/host-context-controller/test/hostReconciler.wake.test.ts
index 4c8fcb062..93b8175b8 100644
--- a/host-context-controller/test/hostReconciler.wake.test.ts
+++ b/host-context-controller/test/hostReconciler.wake.test.ts
@@ -358,7 +358,7 @@ describe('HostReconciler wake fast-path — wake × state transition matrix', ()
)
expect(
logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.some(line => line.includes('phase=replicas_patched'))
).toBe(true)
} finally {
@@ -581,7 +581,7 @@ describe('HostReconciler wake fast-path — durability and restart behavior', ()
String(args[0]).includes('Malformed clerum.io/wake-requested')
)
expect(malformedLogs).toHaveLength(1)
- expect(String(malformedLogs[0][0])).toContain('"not-a-number"')
+ expect(JSON.parse(String(malformedLogs[0][0])).msg).toContain('"not-a-number"')
} finally {
errorSpy.mockRestore()
}
@@ -599,7 +599,7 @@ describe('HostReconciler wake fast-path — structured wake timestamps (Stage 6,
await reconciler.reconcile(makeWakeHost({ wakeRequested: '2', state: 'suspended' }))
const wakeLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.startsWith('[StatelessWake]'))
expect(wakeLines).toEqual([
expect.stringMatching(
@@ -628,7 +628,7 @@ describe('HostReconciler wake fast-path — structured wake timestamps (Stage 6,
makeWakeHost({ wakeRequested: '4', state: 'draining', wakeHandledGeneration: 1 })
)
- const lines = logSpy.mock.calls.map(args => String(args[0]))
+ const lines = logSpy.mock.calls.map(args => JSON.parse(String(args[0])).msg as string)
const phases = lines
.filter(line => line.startsWith('[StatelessWake]'))
.map(line => /phase=(\w+)/.exec(line)?.[1])
@@ -683,7 +683,7 @@ describe('HostReconciler — scale-transition counter (Stage 6 metric)', () => {
await reconciler.suspendHostFromHeartbeat(host, 'idle', 2)
const metricLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.startsWith('[StatelessMetric]'))
expect(metricLines).toEqual([
'[StatelessMetric] scale_transition host=stateless-host direction=up total=1',
@@ -691,7 +691,7 @@ describe('HostReconciler — scale-transition counter (Stage 6 metric)', () => {
])
const suspendLines = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.startsWith('[StatelessSuspend]'))
expect(suspendLines).toEqual([
expect.stringMatching(
@@ -720,7 +720,7 @@ describe('HostReconciler wake fast-path — AP-1 fresh re-decide at the commit p
expect(customApi.patchNamespacedCustomObjectStatus).not.toHaveBeenCalled()
expect(appsApi.patchNamespacedDeployment).not.toHaveBeenCalled()
- const lines = logSpy.mock.calls.map(args => String(args[0]))
+ const lines = logSpy.mock.calls.map(args => JSON.parse(String(args[0])).msg as string)
expect(lines.filter(line => line.startsWith('[StatelessWake]'))).toEqual([])
expect(lines.filter(line => line.includes('Wake fast-path for'))).toEqual([])
} finally {
@@ -786,7 +786,7 @@ describe('HostReconciler wake fast-path — AP-1 fresh re-decide at the commit p
expect(writes[0].lifecycle).toEqual({ state: 'active', wakeHandledGeneration: 5 })
expect(appsApi.patchNamespacedDeployment).toHaveBeenCalledTimes(1)
const phases = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.startsWith('[StatelessWake]'))
.map(line => /phase=(\w+)/.exec(line)?.[1])
expect(phases).toEqual(['wake_observed', 'status_flipped', 'replicas_patched'])
@@ -814,7 +814,7 @@ describe('HostReconciler wake fast-path — AP-1 fresh re-decide at the commit p
expect(writes.at(-1)?.lifecycle).toEqual({ state: 'active', wakeHandledGeneration: 2 })
expect(appsApi.patchNamespacedDeployment).toHaveBeenCalledTimes(1)
const flipped = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=status_flipped'))
expect(flipped).toHaveLength(1)
} finally {
@@ -839,7 +839,7 @@ describe('HostReconciler wake fast-path — AP-1 fresh re-decide at the commit p
expect(customApi.patchNamespacedCustomObjectStatus).toHaveBeenCalledTimes(1)
expect(appsApi.patchNamespacedDeployment).not.toHaveBeenCalled()
const flipped = logSpy.mock.calls
- .map(args => String(args[0]))
+ .map(args => JSON.parse(String(args[0])).msg as string)
.filter(line => line.includes('phase=status_flipped'))
expect(flipped).toEqual([])
} finally {