Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc,desktop): contain scoped deletions and truthful runtime holds
Alfredo Lopez7b7718290b66
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 3846e5165..9a240542e 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -528,6 +528,9 @@ jobs:- name: Test HCC watch-churn readiness gate contractrun: bash scripts/tests/test-hcc-watch-churn-readiness-gate.sh+ - name: Test HCC stateless cache-containment gate contract+ run: bash scripts/tests/test-hcc-stateless-cache-containment.sh+- name: HCC policy lifecycle and restoration contractsrun: |bash scripts/tests/test-hcc-watch-churn-empty-fleet.shdiff --git a/Makefile b/Makefileindex 820c05904..21f5e46f5 100644--- a/Makefile+++ b/Makefile@@ -783,6 +783,19 @@ minikube-t2-hcc-watch-recovery: ## Certify PR A recovery omission, runtime repai@bash scripts/tests/test-hcc-watch-pr-a.sh@E2E_HCC_PR_A=1 $(MAKE) minikube-t2-hcc-networkpolicy-lifecycle+.PHONY: minikube-t2-hcc-stateless-cache-containment+minikube-t2-hcc-stateless-cache-containment: ## Opt-in branch-owned T2 cache-containment journey; requires matching profile/context and refreshed user-facing forwards+ @bash scripts/tests/test-hcc-stateless-cache-containment.sh+ @context='$(CONTROL_API_REAL_PG_CONTEXT)'; \+ [ -n "$$context" ] || { echo 'Set CONTROL_API_REAL_PG_CONTEXT to the verified branch-owned context' >&2; exit 1; }; \+ [ "$(MINIKUBE_PROFILE)" = "$$context" ] || { echo 'MINIKUBE_PROFILE and CONTROL_API_REAL_PG_CONTEXT must select the same branch-owned profile/context' >&2; exit 1; }; \+ printf '%s\n' "$$context" | grep -Eq '^clerum-[a-z0-9][a-z0-9-]*-[0-9a-f]{8}$$' || { echo 'The selected context must be generated and branch-scoped' >&2; exit 1; }+ @E2E_HCC_WATCH_FAULT_INJECTION=1 \+ T2_GATE_ID=minikube-t2 \+ T2_HEALTHCHECK_COMMAND='KUBECONTEXT="$$T2_CONTEXT" MINIKUBE_PROFILE="$$T2_PROFILE" E2E_BRANCH_PROFILE_ENV="$$T2_PROFILE_ENV" E2E_PROFILE_PORTS_ENV="$$T2_PORTS_ENV" E2E_EXPECTED_PRE_GATE_GATE=minikube-t2 bash scripts/e2e/e2e-hcc-stateless-cache-containment.sh' \+ T2_HEALTHCHECK_TIMEOUT_SECONDS=900 T2_HEALTHCHECK_KILL_GRACE_SECONDS=300 \+ $(MAKE) minikube-t2+.PHONY: minikube-t2-runtimeminikube-t2-runtime: ## Exact-head T2 after T0 and T1 already passed on this HEAD and profile@T2_RUN_T0=false T2_RUN_T1=false \diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 5d6875a2b..d19c2e9e8 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -8,10 +8,17 @@ import type { ChatMessage } from '../types.js'let tempDir: stringlet store: ChatStore+const TEAM_A_SCOPE = {+ environmentKey: 'env-a',+ userId: 'user-a',+ teamId: 'team-a',+} as const+const TEAM_B_SCOPE = { ...TEAM_A_SCOPE, teamId: 'team-b' } as constbeforeEach(async () => {tempDir = await fs.mkdtemp(join(tmpdir(), 'chatstore-test-'))store = new ChatStore(tempDir)+ store.setAuthorityScope(TEAM_A_SCOPE)})afterEach(async () => {@@ -181,13 +188,16 @@ describe('deleteChat', () => {it('persists a confirmed deletion across a new store instance', async () => {await store.createChat('agent-1', 'deleted-session')await store.createChat('agent-1', 'kept-session')- await store.deleteChat('agent-1', 'deleted-session')+ await store.deleteChat('agent-1', 'deleted-session', TEAM_A_SCOPE)const restartedStore = new ChatStore(tempDir)expect((await restartedStore.listChats('agent-1')).map(chat => chat.id)).toEqual(['kept-session',])- expect((await restartedStore.getIndex('agent-1')).deletedChatIds).toContain('deleted-session')+ expect((await restartedStore.getIndex('agent-1')).deletedChatTombstones).toContainEqual({+ chatId: 'deleted-session',+ authorityScope: TEAM_A_SCOPE,+ })})it('does not recreate a deleted transcript from queued or restarted writes', async () => {@@ -206,7 +216,7 @@ describe('deleteChat', () => {// Invocation order is the per-chat serialization order: both writes must// observe the tombstone published by the preceding confirmed delete.- const deletion = store.deleteChat(agentRef, chatId)+ const deletion = store.deleteChat(agentRef, chatId, TEAM_A_SCOPE)const queuedAppend = store.appendMessages(agentRef, chatId, [message])const queuedReplace = store.replaceMessages(agentRef, chatId, [message])await Promise.all([deletion, queuedAppend, queuedReplace])@@ -219,7 +229,10 @@ describe('deleteChat', () => {)expect(await restartedStore.loadMessages(agentRef, chatId)).toEqual([])expect(await restartedStore.listChats(agentRef)).toEqual([])- expect((await restartedStore.getIndex(agentRef)).deletedChatIds).toContain(chatId)+ expect((await restartedStore.getIndex(agentRef)).deletedChatTombstones).toContainEqual({+ chatId,+ authorityScope: TEAM_A_SCOPE,+ })await expect(fs.access(chatCacheDir(chatId))).rejects.toThrow()})@@ -228,7 +241,7 @@ describe('deleteChat', () => {await store.saveMessages('agent-1', 'del-1', [{ id: 'm1', role: 'user', content: 'hello', timestamp: Date.now() },])- await store.deleteChat('agent-1', 'del-1')+ await store.deleteChat('agent-1', 'del-1', TEAM_A_SCOPE)const chats = await store.listChats('agent-1')expect(chats).toHaveLength(0)@@ -239,10 +252,79 @@ describe('deleteChat', () => {it('clears lastActiveChatId when deleting active chat', async () => {await store.createChat('agent-1', 'active-1')await store.setLastActiveChatId('agent-1', 'active-1')- await store.deleteChat('agent-1', 'active-1')+ await store.deleteChat('agent-1', 'active-1', TEAM_A_SCOPE)const lastActive = await store.getLastActiveChatId('agent-1')expect(lastActive).toBeNull()})++ it('keeps new tombstones scoped to the full authority identity', async () => {+ await store.createChat('agent-1', 'team-owned-chat')+ await store.deleteChat('agent-1', 'team-owned-chat', TEAM_A_SCOPE)++ const teamBStore = new ChatStore(tempDir)+ teamBStore.setAuthorityScope(TEAM_B_SCOPE)+ await expect(teamBStore.createChat('agent-1', 'team-owned-chat')).resolves.toMatchObject({+ id: 'team-owned-chat',+ })+ await expect(store.createChat('agent-1', 'team-owned-chat')).rejects.toThrow(+ 'Chat was deleted locally'+ )+ })++ it('retains legacy tombstone reads without carrying them into a new team', async () => {+ await fs.mkdir(agentPath(), { recursive: true })+ await fs.writeFile(+ agentPath('index.json'),+ JSON.stringify({+ version: 2,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ deletedChatIds: ['legacy-chat', 'legacy-unscoped-only'],+ })+ )+ const teamBStore = new ChatStore(tempDir)+ teamBStore.setAuthorityScope(TEAM_B_SCOPE)+ expect((await teamBStore.getIndex('agent-1')).deletedChatIds).toContain('legacy-chat')+ await expect(teamBStore.createChat('agent-1', 'legacy-chat')).resolves.toMatchObject({+ id: 'legacy-chat',+ })++ const unscopedStore = new ChatStore(tempDir)+ unscopedStore.setAuthorityScope({ ...TEAM_A_SCOPE, teamId: null })+ await expect(unscopedStore.createChat('agent-1', 'legacy-unscoped-only')).rejects.toThrow(+ 'Chat was deleted locally'+ )+ })++ it('keeps cleanup queued after a failure and retries it only in the owning scope', async () => {+ await store.createChat('agent-1', 'retry-cleanup')+ await store.saveMessages('agent-1', 'retry-cleanup', [+ { id: 'message', role: 'user', content: 'private', timestamp: 1 },+ ])+ const cleanupReadError = Object.assign(new Error('permission denied'), { code: 'EACCES' })+ vi.spyOn(fs, 'readdir').mockRejectedValueOnce(cleanupReadError)++ await expect(store.deleteChat('agent-1', 'retry-cleanup', TEAM_A_SCOPE)).resolves.toEqual({+ cleanupPending: true,+ })+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toContainEqual({+ chatId: 'retry-cleanup',+ authorityScope: TEAM_A_SCOPE,+ })+ await expect(fs.access(chatCacheDir('retry-cleanup'))).resolves.toBeUndefined()++ store.setAuthorityScope(TEAM_B_SCOPE)+ await expect(store.retryPendingDeleteCleanups(TEAM_A_SCOPE)).rejects.toThrow(+ 'Chat deletion authority scope changed'+ )+ await expect(fs.access(chatCacheDir('retry-cleanup'))).resolves.toBeUndefined()++ store.setAuthorityScope(TEAM_A_SCOPE)+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE)+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toEqual([])+ await expect(fs.access(chatCacheDir('retry-cleanup'))).rejects.toThrow()+ })})// ── messages ─────────────────────────────────────────────────────────────────@@ -288,6 +370,7 @@ describe('messages', () => {pageSize: 3,maxLocalSyncedMessages: Number.POSITIVE_INFINITY,})+ pagedStore.setAuthorityScope(TEAM_A_SCOPE)await pagedStore.createChat('agent-1', 'paged-1')const msgs = Array.from({ length: 10 }, (_, i) => ({id: `m${i}`,@@ -318,6 +401,7 @@ describe('messages', () => {pageSize: 2,maxLocalSyncedMessages: Number.POSITIVE_INFINITY,})+ pagedStore.setAuthorityScope(TEAM_A_SCOPE)await pagedStore.createChat('agent-1', 'append-pages')await pagedStore.saveMessages('agent-1', 'append-pages', [{ id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },@@ -708,6 +792,7 @@ describe('messages', () => {pageSize: 2,maxLocalSyncedMessages: Number.POSITIVE_INFINITY,})+ pagedStore.setAuthorityScope(TEAM_A_SCOPE)await pagedStore.createChat('agent-1', 'delete-siblings')await pagedStore.saveMessages('agent-1', 'delete-siblings', [{ id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },@@ -718,7 +803,7 @@ describe('messages', () => {[{ id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 1 }])- await pagedStore.deleteChat('agent-1', 'delete-siblings')+ await pagedStore.deleteChat('agent-1', 'delete-siblings', TEAM_A_SCOPE)expect(await pagedStore.loadMessages('agent-1', 'delete-siblings')).toEqual([])await expect(@@ -1894,7 +1979,7 @@ describe('corrupt/missing files', () => {await fs.writeFile(join(corruptDir, `${encodedChatId}-${legacyUuid}.json`), '{}')await fs.writeFile(join(corruptDir, `${otherEncodedChatId}-${legacyUuid}.json`), '{}')- await store.deleteChat('agent-1', chatId)+ await store.deleteChat('agent-1', chatId, TEAM_A_SCOPE)await expect(fs.access(join(corruptDir, encodedChatId))).rejects.toMatchObject({code: 'ENOENT',diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 49980d5ea..f4a64765e 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -42,6 +42,7 @@ import {AccessCatalog,AgentWithMcpServers,ApprovalDecisionResult,+ ChatAuthorityScope,ContextBreakdownResult,DependencyHealth,DesktopAppInfo,@@ -1008,9 +1009,26 @@ export class AppService {private async bindCurrentChatStore(userId: string): Promise<void> {await bindChatStoreForUser(userId, getActiveEnvKey(), {legacyEnvKeys: getActiveLegacyEnvKeys(),+ teamId: this.me?.id === userId ? this.me.teamId : null,})}+ getChatDeletionFenceAuthority(): {+ authorityScope: ChatAuthorityScope+ sessionGeneration: number+ } {+ this.requireSessionToken()+ if (!this.me) throw new Error('Not authenticated')+ return {+ authorityScope: {+ environmentKey: getActiveEnvKey(),+ userId: this.me.id,+ teamId: String(this.me.teamId || '').trim() || null,+ },+ sessionGeneration: this.sessionGeneration,+ }+ }+private async commitSessionToken(token: string,options: { refreshMe?: boolean } = {}@@ -1393,7 +1411,10 @@ export class AppService {if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }}- await bindChatStoreForUser(restoredMe.id, envKey, { legacyEnvKeys })+ await bindChatStoreForUser(restoredMe.id, envKey, {+ legacyEnvKeys,+ teamId: restoredMe.teamId,+ })if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {if (this.me) {await this.bindCurrentChatStore(this.me.id)diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 58d560118..cf12f6535 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -4,6 +4,9 @@ import { dirname, join } from 'node:path'import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.js'import { assertSafeFilesystemSegment } from './pathSafety.js'import type {+ ChatAuthorityScope,+ ChatDeleteResult,+ ChatDeleteTombstone,ChatFile,ChatIndex,ChatMessage,@@ -69,6 +72,32 @@ function isPositiveSafeInteger(value: unknown): value is number {return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1}+function isChatAuthorityScope(value: unknown): value is ChatAuthorityScope {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false+ const scope = value as Record<string, unknown>+ return (+ typeof scope.environmentKey === 'string' &&+ scope.environmentKey.length > 0 &&+ typeof scope.userId === 'string' &&+ scope.userId.length > 0 &&+ (scope.teamId === null || typeof scope.teamId === 'string')+ )+}++function isChatDeleteTombstone(value: unknown): value is ChatDeleteTombstone {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false+ const tombstone = value as Record<string, unknown>+ return typeof tombstone.chatId === 'string' && isChatAuthorityScope(tombstone.authorityScope)+}++function sameChatAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {+ return (+ left.environmentKey === right.environmentKey &&+ left.userId === right.userId &&+ left.teamId === right.teamId+ )+}+function normalizePositiveInteger(value: number | undefined, fallback: number): number {if (value === undefined) return fallbackif (!Number.isFinite(value)) return fallback@@ -169,7 +198,16 @@ function parseChatIndex(raw: string): ChatIndex {!Array.isArray(candidate.chats) ||(candidate.deletedChatIds !== undefined &&(!Array.isArray(candidate.deletedChatIds) ||- !candidate.deletedChatIds.every((id: unknown) => typeof id === 'string')))+ !candidate.deletedChatIds.every((id: unknown) => typeof id === 'string'))) ||+ (candidate.deletedChatTombstones !== undefined &&+ (!Array.isArray(candidate.deletedChatTombstones) ||+ !candidate.deletedChatTombstones.every(isChatDeleteTombstone))) ||+ (candidate.pendingChatCleanup !== undefined &&+ (!Array.isArray(candidate.pendingChatCleanup) ||+ !candidate.pendingChatCleanup.every(isChatDeleteTombstone))) ||+ (candidate.pendingCleanupChatIds !== undefined &&+ (!Array.isArray(candidate.pendingCleanupChatIds) ||+ !candidate.pendingCleanupChatIds.every((id: unknown) => typeof id === 'string')))) {throw new Error('Invalid chat index')}@@ -293,6 +331,7 @@ function emptyIndex(): ChatIndex {export class ChatStore {private readonly pageSize: numberprivate readonly maxLocalSyncedMessages: number+ private authorityScope: ChatAuthorityScope | null = nullconstructor(private readonly baseDir: string,@@ -302,6 +341,38 @@ export class ChatStore {this.maxLocalSyncedMessages = normalizeMaxLocalSyncedMessages(options.maxLocalSyncedMessages)}+ setAuthorityScope(scope: ChatAuthorityScope): void {+ this.authorityScope = Object.freeze({ ...scope })+ }++ getAuthorityScope(): ChatAuthorityScope | null {+ return this.authorityScope ? { ...this.authorityScope } : null+ }++ private requireAuthorityScope(expected?: ChatAuthorityScope): ChatAuthorityScope {+ const current = this.authorityScope+ if (!current || (expected && !sameChatAuthorityScope(current, expected))) {+ throw new Error('Chat deletion authority scope changed')+ }+ return current+ }++ private isDeletedInScope(index: ChatIndex, chatId: string, scope = this.authorityScope): boolean {+ if (+ index.deletedChatTombstones?.some(+ tombstone =>+ tombstone.chatId === chatId &&+ (!scope || sameChatAuthorityScope(tombstone.authorityScope, scope))+ )+ ) {+ return true+ }+ // Legacy entries were global inside an env/user store. Retain that behavior+ // for the unscoped legacy account and for stores used without authority+ // context, but never carry an unknowable old-team deletion into a new team.+ return Boolean(index.deletedChatIds?.includes(chatId) && (!scope || scope.teamId === null))+ }+/*** Index read-modify-write sequences are serialized per agent because every* chat shares one `index.json`. Paged transcript operations use a separate@@ -1522,11 +1593,11 @@ export class ChatStore {async createChat(agentRef: string, chatId: string): Promise<ChatMetadata> {return this.serializeIndex(agentRef, async () => {const index = await this.getIndex(agentRef)- const existing = index.chats.find(c => c.id === chatId)- if (existing) return existing- if (index.deletedChatIds?.includes(chatId)) {+ if (this.isDeletedInScope(index, chatId)) {throw new Error('Chat was deleted locally')}+ const existing = index.chats.find(c => c.id === chatId)+ if (existing) return existingconst now = new Date().toISOString()const meta: ChatMetadata = {@@ -1553,38 +1624,174 @@ export class ChatStore {})}- async deleteChat(agentRef: string, chatId: string): Promise<void> {- return this.serializeChat(agentRef, chatId, async () => {+ async deleteChat(+ agentRef: string,+ chatId: string,+ authorityScope: ChatAuthorityScope+ ): Promise<ChatDeleteResult> {+ const scope = this.requireAuthorityScope(authorityScope)+ const tombstone: ChatDeleteTombstone = { chatId, authorityScope: { ...scope } }+ await this.serializeChat(agentRef, chatId, async () => {+ this.requireAuthorityScope(scope)await this.serializeIndex(agentRef, async () => {+ this.requireAuthorityScope(scope)const index = await this.getIndex(agentRef)index.chats = index.chats.filter(c => c.id !== chatId)- if (!index.deletedChatIds?.includes(chatId)) {- index.deletedChatIds = [...(index.deletedChatIds ?? []), chatId]+ index.deletedChatTombstones = index.deletedChatTombstones ?? []+ if (+ !index.deletedChatTombstones.some(+ existing =>+ existing.chatId === chatId && sameChatAuthorityScope(existing.authorityScope, scope)+ )+ ) {+ index.deletedChatTombstones.push(tombstone)}- if (index.lastActiveChatId === chatId) {- index.lastActiveChatId = null+ index.pendingChatCleanup = index.pendingChatCleanup ?? []+ if (+ !index.pendingChatCleanup.some(+ existing =>+ existing.chatId === chatId && sameChatAuthorityScope(existing.authorityScope, scope)+ )+ ) {+ index.pendingChatCleanup.push(tombstone)}+ if (index.lastActiveChatId === chatId) index.lastActiveChatId = nullawait this.saveIndex(agentRef, index)})- await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })- const corruptLegacyDir = join(this.agentDir(agentRef), '.corrupt')- await fs.rm(join(corruptLegacyDir, encodedChatId(chatId)), { recursive: true, force: true })- const corruptLegacyEntries = await fs.readdir(corruptLegacyDir).catch(() => [])- await Promise.all(- corruptLegacyEntries- .filter(name => legacyCorruptFileBelongsToChat(name, chatId))- .map(name => fs.rm(join(corruptLegacyDir, name), { force: true }))- )- await fs.rm(`${this.chatFilePath(agentRef, chatId)}.tmp`, { force: true })- await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })- await fs.rm(`${this.chatCompatibilitySignaturePath(agentRef, chatId)}.tmp`, { force: true })- await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })- await this.removePagedChatSnapshotSiblings(agentRef, chatId)const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)this.cleanedSnapshotSiblingKeys.delete(cacheKey)this.compatibilityCheckedKeys.delete(cacheKey)this.dropCompatibilityWindow(cacheKey)})++ const cleaned = await this.finishPendingDeleteCleanup(agentRef, tombstone)+ return { cleanupPending: !cleaned }+ }++ private async removeChatArtifacts(+ agentRef: string,+ chatId: string,+ authorityScope: ChatAuthorityScope+ ): Promise<boolean> {+ const corruptLegacyDir = join(this.agentDir(agentRef), '.corrupt')+ let corruptLegacyEntries: string[]+ try {+ corruptLegacyEntries = await fs.readdir(corruptLegacyDir)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') corruptLegacyEntries = []+ else return false+ }+ if (!this.authorityScope || !sameChatAuthorityScope(this.authorityScope, authorityScope)) {+ return false+ }+ const paths = [+ { path: this.chatFilePath(agentRef, chatId), recursive: false },+ { path: join(corruptLegacyDir, encodedChatId(chatId)), recursive: true },+ ...corruptLegacyEntries+ .filter(name => legacyCorruptFileBelongsToChat(name, chatId))+ .map(name => ({ path: join(corruptLegacyDir, name), recursive: false })),+ { path: `${this.chatFilePath(agentRef, chatId)}.tmp`, recursive: false },+ { path: this.chatCompatibilitySignaturePath(agentRef, chatId), recursive: false },+ { path: `${this.chatCompatibilitySignaturePath(agentRef, chatId)}.tmp`, recursive: false },+ { path: this.chatDirPath(agentRef, chatId), recursive: true },+ ]+ let allRemoved = true+ for (const target of paths) {+ if (!this.authorityScope || !sameChatAuthorityScope(this.authorityScope, authorityScope)) {+ return false+ }+ try {+ await fs.rm(target.path, { recursive: target.recursive, force: true })+ } catch {+ allRemoved = false+ }+ }+ if (!this.authorityScope || !sameChatAuthorityScope(this.authorityScope, authorityScope)) {+ return false+ }+ try {+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)+ } catch {+ allRemoved = false+ }+ return (+ allRemoved &&+ Boolean(this.authorityScope && sameChatAuthorityScope(this.authorityScope, authorityScope))+ )+ }++ private async finishPendingDeleteCleanup(+ agentRef: string,+ tombstone: ChatDeleteTombstone+ ): Promise<boolean> {+ if (+ !this.authorityScope ||+ !sameChatAuthorityScope(this.authorityScope, tombstone.authorityScope)+ ) {+ return false+ }+ let artifactsRemoved = false+ try {+ artifactsRemoved = await this.removeChatArtifacts(+ agentRef,+ tombstone.chatId,+ tombstone.authorityScope+ )+ } catch {+ return false+ }+ if (+ !artifactsRemoved ||+ !this.authorityScope ||+ !sameChatAuthorityScope(this.authorityScope, tombstone.authorityScope)+ ) {+ return false+ }+ try {+ await this.serializeIndex(agentRef, async () => {+ this.requireAuthorityScope(tombstone.authorityScope)+ const index = await this.getIndex(agentRef)+ index.pendingChatCleanup = (index.pendingChatCleanup ?? []).filter(+ existing =>+ existing.chatId !== tombstone.chatId ||+ !sameChatAuthorityScope(existing.authorityScope, tombstone.authorityScope)+ )+ await this.saveIndex(agentRef, index)+ })+ return true+ } catch {+ return false+ }+ }++ async retryPendingDeleteCleanups(authorityScope: ChatAuthorityScope): Promise<void> {+ const scope = this.requireAuthorityScope(authorityScope)+ let entries+ try {+ entries = await fs.readdir(this.baseDir, { withFileTypes: true })+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw error+ }+ for (const entry of entries) {+ if (!entry.isDirectory()) continue+ let agentRef = entry.name+ try {+ const index = await this.getIndex(agentRef)+ const pending = (index.pendingChatCleanup ?? []).filter(item =>+ sameChatAuthorityScope(item.authorityScope, scope)+ )+ for (const tombstone of pending) {+ if (!this.authorityScope || !sameChatAuthorityScope(this.authorityScope, scope)) return+ await this.serializeChat(agentRef, tombstone.chatId, () =>+ this.finishPendingDeleteCleanup(agentRef, tombstone)+ )+ }+ } catch {+ // An unrelated or unreadable agent index must not prevent other durable+ // cleanup entries from being retried on the next authorized read.+ }+ }}async loadMessages(@@ -1650,7 +1857,7 @@ export class ChatStore {): Promise<void> {return this.serializeChat(agentRef, chatId, async () => {const index = await this.getIndex(agentRef)- if (index.deletedChatIds?.includes(chatId)) return+ if (this.isDeletedInScope(index, chatId)) returnconst indexedCount = options.preserveExistingTotals? await this.indexedMessageCount(agentRef, chatId): undefined@@ -1684,7 +1891,7 @@ export class ChatStore {): Promise<void> {await this.serializeChat(agentRef, chatId, async () => {const index = await this.getIndex(agentRef)- if (index.deletedChatIds?.includes(chatId)) return+ if (this.isDeletedInScope(index, chatId)) returnconst existingMeta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)const existingMessages = existingMeta? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta)@@ -1726,7 +1933,7 @@ export class ChatStore {): Promise<void> {return this.serializeChat(agentRef, chatId, async () => {const indexBeforeAppend = await this.getIndex(agentRef)- if (indexBeforeAppend.deletedChatIds?.includes(chatId)) return+ if (this.isDeletedInScope(indexBeforeAppend, chatId)) returnconst existing =(await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??(await this.writePagedChatUnlocked(agentRef, chatId, []))diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex bea661689..67c52a491 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'import { join } from 'node:path'import { ChatStore } from './chatStore.js'import { assertSafeFilesystemSegment } from './pathSafety.js'+import type { ChatAuthorityScope } from './types.js'/*** Keep the shared catalog at v2 so pre-paging desktop builds can read the@@ -49,7 +50,7 @@ const PRE_ENV_MIGRATION_MARKER = '.env-scoped'export async function bindChatStoreForUser(userId: string,envKey: string,- options: { legacyEnvKeys?: readonly string[] } = {}+ options: { legacyEnvKeys?: readonly string[]; teamId?: string | null } = {}): Promise<void> {assertSafeFilesystemSegment('userId', userId)assertSafeFilesystemSegment('envKey', envKey)@@ -60,9 +61,23 @@ export async function bindChatStoreForUser(// refreshes re-call this with an unchanged `me.id`; tearing the store down// just to rebuild it opens a window where every concurrent chat IPC fails// with "Not authenticated" (seen as an empty "Latest sessions" at boot).- if (activeChatStore && activeUserId === userId && activeEnvKey === envKey) return+ const authorityScope: ChatAuthorityScope = {+ environmentKey: envKey,+ userId,+ teamId: String(options.teamId || '').trim() || null,+ }+ if (activeChatStore && activeUserId === userId && activeEnvKey === envKey) {+ activeChatStore.setAuthorityScope(authorityScope)+ return+ }const bindKey = `${envKey}::${userId}`- if (bindInFlight?.key === bindKey) return bindInFlight.promise+ if (bindInFlight?.key === bindKey) {+ await bindInFlight.promise+ if (activeChatStore && activeUserId === userId && activeEnvKey === envKey) {+ activeChatStore.setAuthorityScope(authorityScope)+ }+ return+ }const generation = ++bindingGenerationconst promise = (async () => {@@ -84,6 +99,7 @@ export async function bindChatStoreForUser(await sweepExpiredCorruptQuarantines(userDir)if (generation !== bindingGeneration) returnactiveChatStore = new ChatStore(userDir)+ activeChatStore.setAuthorityScope(authorityScope)activeUserId = userIdactiveEnvKey = envKey})()diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 1c458d896..38d15fd58 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -26,6 +26,8 @@ import {PLUGIN_SDK_REQUEST_CHANNEL,} from './pluginSdkProtocol.js'import {+ type ChatAuthorityScope,+ type ChatDeleteFence,DesktopRuntimeConfig,HostActivityStreamEvent,HostMessageRequest,@@ -38,6 +40,54 @@ function sanitizeString(input: unknown): string {return String(input || '').trim()}+function sanitizeChatAuthorityScope(input: unknown): ChatAuthorityScope {+ if (!input || typeof input !== 'object' || Array.isArray(input)) {+ throw new Error('Invalid chat deletion authority scope')+ }+ const value = input as Record<string, unknown>+ const environmentKey = sanitizeString(value.environmentKey)+ const userId = sanitizeString(value.userId)+ const teamId = value.teamId === null ? null : sanitizeString(value.teamId)+ if (!environmentKey || !userId || (value.teamId !== null && !teamId)) {+ throw new Error('Invalid chat deletion authority scope')+ }+ return { environmentKey, userId, teamId }+}++function sameChatAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {+ return (+ left.environmentKey === right.environmentKey &&+ left.userId === right.userId &&+ left.teamId === right.teamId+ )+}++function sanitizeChatDeleteFence(input: unknown): ChatDeleteFence {+ if (!input || typeof input !== 'object' || Array.isArray(input)) {+ throw new Error('Scoped chat deletion is required')+ }+ const value = input as Record<string, unknown>+ const bindingGeneration = value.bindingGeneration+ const sessionGeneration = value.sessionGeneration+ if (+ value.version !== 1 ||+ typeof bindingGeneration !== 'number' ||+ !Number.isSafeInteger(bindingGeneration) ||+ bindingGeneration < 1 ||+ typeof sessionGeneration !== 'number' ||+ !Number.isSafeInteger(sessionGeneration) ||+ sessionGeneration < 0+ ) {+ throw new Error('Invalid chat deletion fence')+ }+ return {+ version: 1,+ authorityScope: sanitizeChatAuthorityScope(value.authorityScope),+ bindingGeneration,+ sessionGeneration,+ }+}+/*** Sanitize a bulk subject-key array (grant/share to many subjects in one call).* Fails loud on a non-array or empty payload rather than silently no-op'ing — an@@ -1429,13 +1479,31 @@ export function registerIpcHandlers(service: AppService): void {return getChatStoreBindingGeneration()})+ ipcMain.handle(+ 'chat:captureDeleteFence',+ (event, payload: { expectedAuthorityScope?: unknown }) => {+ assertTrustedSender(event)+ const expectedAuthorityScope = sanitizeChatAuthorityScope(payload?.expectedAuthorityScope)+ const authority = service.getChatDeletionFenceAuthority()+ if (!sameChatAuthorityScope(expectedAuthorityScope, authority.authorityScope)) {+ throw new Error('Chat deletion authority scope changed before confirmation')+ }+ return {+ version: 1,+ authorityScope: authority.authorityScope,+ bindingGeneration: getChatStoreBindingGeneration(),+ sessionGeneration: authority.sessionGeneration,+ } satisfies ChatDeleteFence+ }+ )+ipcMain.handle('chat:delete',async (event,payload: {version?: number- bindingGeneration?: number+ fence?: unknownagentRef: stringchatId: string}@@ -1444,9 +1512,17 @@ export function registerIpcHandlers(service: AppService): void {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)+ if (payload?.version !== 3) throw new Error('Scoped chat deletion is required')+ const fence = sanitizeChatDeleteFence(payload.fence)+ const authority = service.getChatDeletionFenceAuthority()+ if (+ !sameChatAuthorityScope(fence.authorityScope, authority.authorityScope) ||+ fence.sessionGeneration !== authority.sessionGeneration+ ) {+ throw new Error('Chat deletion authority changed before confirmation')+ }+ const store = requireChatStoreForBindingGeneration(fence.bindingGeneration)+ await store.deleteChat(agentRef, chatId, fence.authorityScope)})@@ -1598,7 +1674,10 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)const agentRef = sanitizeString(payload?.agentRef)if (!agentRef) throw new Error('agentRef is required')- return requireChatStore().getIndex(agentRef)+ const store = requireChatStore()+ const authority = service.getChatDeletionFenceAuthority()+ await store.retryPendingDeleteCleanups(authority.authorityScope)+ return store.getIndex(agentRef)})ipcMain.handle('chat:dismissOnboarding', async (event, payload: { agentRef: string }) => {diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 595a67196..ced4b55f9 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -581,8 +581,10 @@ const clerum = Object.freeze({rename: (agentRef: string, chatId: string, title: string) =>ipcRenderer.invoke('chat:rename', { agentRef, chatId, title }),getBindingGeneration: () => ipcRenderer.invoke('chat:bindingGeneration'),- delete: (agentRef: string, chatId: string, bindingGeneration: number) =>- ipcRenderer.invoke('chat:delete', { version: 2, agentRef, chatId, bindingGeneration }),+ captureDeleteFence: (expectedAuthorityScope: import('./types.js').ChatAuthorityScope) =>+ ipcRenderer.invoke('chat:captureDeleteFence', { expectedAuthorityScope }),+ delete: (agentRef: string, chatId: string, fence: import('./types.js').ChatDeleteFence) =>+ ipcRenderer.invoke('chat:delete', { version: 3, agentRef, chatId, fence }),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.tsindex f7b3c2486..5dbd6480a 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -8,6 +8,9 @@ import {AccessCatalog,AgentWithMcpServers,ApprovalDecisionResult,+ ChatAuthorityScope,+ ChatDeleteFence,+ ChatDeleteResult,ChatIndex,ChatMessage,ChatMetadata,@@ -697,7 +700,12 @@ declare global {create: (agentRef: string, chatId: string) => Promise<ChatMetadata>rename: (agentRef: string, chatId: string, title: string) => Promise<void>getBindingGeneration: () => Promise<number>- delete: (agentRef: string, chatId: string, bindingGeneration: number) => Promise<void>+ captureDeleteFence: (expectedAuthorityScope: ChatAuthorityScope) => Promise<ChatDeleteFence>+ delete: (+ agentRef: string,+ chatId: string,+ fence: ChatDeleteFence+ ) => Promise<ChatDeleteResult>loadMessages: (agentRef: string,chatId: string,diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 6c4120219..263e0d3fc 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -908,15 +908,40 @@ export interface ChatMetadata {lastTerminalAt?: string}+/** The authority identity that owns a local chat deletion. */+export interface ChatAuthorityScope {+ environmentKey: string+ userId: string+ teamId: string | null+}++/** Main-issued fence captured when a delete is queued and rechecked on confirm. */+export interface ChatDeleteFence {+ version: 1+ authorityScope: ChatAuthorityScope+ bindingGeneration: number+ sessionGeneration: number+}++/** Durable tombstone and cleanup identity for one scoped local deletion. */+export interface ChatDeleteTombstone {+ chatId: string+ authorityScope: ChatAuthorityScope+}+export interface ChatIndex {/** v2 remains readable by pre-paging builds; v3 is accepted and normalized for compatibility. */version: 1 | 2 | 3lastActiveChatId: string | nullonboardingDismissed: booleanchats: ChatMetadata[]- /** Optional for older indexes. User-confirmed local deletions stay hidden from remote lists. */+ /** Legacy tombstones from pre-scoped versions; retained for read compatibility. */deletedChatIds?: string[]- /** Logical deletions whose on-disk cache cleanup must be retried. */+ /** New deletions are isolated to their complete authority identity. */+ deletedChatTombstones?: ChatDeleteTombstone[]+ /** Durable artifact-cleanup work, retried only in the owning authority scope. */+ pendingChatCleanup?: ChatDeleteTombstone[]+ /** Legacy pending cleanup field, read for compatibility with intermediate builds. */pendingCleanupChatIds?: string[]}diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex 439240e23..8072118e3 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -1,6 +1,13 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'import path from 'node:path'+import {+ __setChatStoreBaseDirForTests,+ bindChatStoreForUser,+ getChatStoreBindingGeneration,+ requireChatStore,+ unbindChatStore,+} from '../src/chatStoreBinding.js'import { registerIpcHandlers, sanitizeChatLoadWindow } from '../src/ipc.js'import type { HostStatusStreamEvent } from '../src/types.js'@@ -104,6 +111,7 @@ describe('ipc host status stream handlers', () => {listArtifacts: vi.fn(),downloadArtifact: vi.fn(),listSessions: vi.fn(),+ getChatDeletionFenceAuthority: vi.fn(),loadSessionMessages: vi.fn(),renameSession: vi.fn(),listWorkflowRuns: vi.fn(),@@ -132,6 +140,12 @@ describe('ipc host status stream handlers', () => {vi.clearAllMocks()await fs.rm(testState.downloadsDir, { recursive: true, force: true })await fs.mkdir(testState.downloadsDir, { recursive: true })+ unbindChatStore()+ __setChatStoreBaseDirForTests(path.join(testState.downloadsDir, 'chat-cache'))+ service.getChatDeletionFenceAuthority.mockReturnValue({+ authorityScope: { environmentKey: 'env-1', userId: 'user-1', teamId: 'team-a' },+ sessionGeneration: 7,+ })service.stopHostStatusStream.mockReturnValue(true)registerIpcHandlers(service as never)})@@ -145,6 +159,54 @@ describe('ipc host status stream handlers', () => {).rejects.toThrow('Scoped chat deletion is required')})+ it('captures and rechecks the main-owned authority and binding fence', async () => {+ await bindChatStoreForUser('user-1', 'env-1', { teamId: 'team-a' })+ const { event } = makeTrustedEvent()+ const capture = testState.handlers.get('chat:captureDeleteFence')+ const remove = testState.handlers.get('chat:delete')+ const expectedAuthorityScope = {+ environmentKey: 'env-1',+ userId: 'user-1',+ teamId: 'team-a',+ }+ const fence = await Promise.resolve(capture?.(event, { expectedAuthorityScope }))+ expect(fence).toMatchObject({+ version: 1,+ authorityScope: expectedAuthorityScope,+ bindingGeneration: getChatStoreBindingGeneration(),+ sessionGeneration: 7,+ })++ // Returning to the same team does not revive the old confirmation: the+ // auth/session epoch changed during the intervening team switch.+ service.getChatDeletionFenceAuthority.mockReturnValue({+ authorityScope: expectedAuthorityScope,+ sessionGeneration: 9,+ })+ await expect(+ Promise.resolve(remove?.(event, { version: 3, agentRef: 'agent-x', chatId: 'c1', fence }))+ ).rejects.toThrow('Chat deletion authority changed before confirmation')+ })++ it('persists a scoped tombstone before returning from the fenced delete IPC', async () => {+ await bindChatStoreForUser('user-1', 'env-1', { teamId: 'team-a' })+ const { event } = makeTrustedEvent()+ const capture = testState.handlers.get('chat:captureDeleteFence')+ const remove = testState.handlers.get('chat:delete')+ const authorityScope = {+ environmentKey: 'env-1',+ userId: 'user-1',+ teamId: 'team-a',+ }+ const fence = await Promise.resolve(+ capture?.(event, { expectedAuthorityScope: authorityScope })+ )+ await Promise.resolve(remove?.(event, { version: 3, agentRef: 'agent-x', chatId: 'c1', fence }))+ const index = await requireChatStore().getIndex('agent-x')+ expect(index.deletedChatTombstones).toContainEqual({ chatId: 'c1', authorityScope })+ expect(index.pendingChatCleanup).toEqual([])+ })+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/components/SidebarNav/index.tsx b/desktop-app/ui/src/components/SidebarNav/index.tsxindex 3df859e8a..377043697 100644--- a/desktop-app/ui/src/components/SidebarNav/index.tsx+++ b/desktop-app/ui/src/components/SidebarNav/index.tsx@@ -1,5 +1,8 @@import React, { useEffect, useMemo, useRef, useState } from 'react'-import { useAgentChatActionsContext } from '@contexts/AgentChatActionsContext'+import {+ type QueuedChatDelete,+ useAgentChatActionsContext,+} from '@contexts/AgentChatActionsContext'import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'import { useAuthContext } from '@contexts/AuthContext'import { useChatListContext } from '@contexts/ChatListContext'@@ -53,6 +56,7 @@ export function SidebarNav({const { activeChatId, latestChatSessions, latestChatSessionsLoading, sessionStateByChatKey } =useChatListContext()const {+ captureChatDeleteFence,handleRenameChatForAgent: onRenameChatForAgent,handleDeleteChatForAgent: onDeleteChatForAgent,} = useAgentChatActionsContext()@@ -71,6 +75,7 @@ export function SidebarNav({agentRef: stringchatId: stringtitle: string+ deletion: QueuedChatDelete} | null>(null)const lastToggleRequestIdRef = useRef(0)const desktopAppInfo = useDesktopAppInfo()@@ -88,6 +93,24 @@ export function SidebarNav({[onSettingsMenuOpenChange])+ const requestDeleteSession = React.useCallback(+ async (session: { agentRef: string; id: string; title: string }) => {+ setSessionMenuId(null)+ try {+ const deletion = await captureChatDeleteFence(session.agentRef)+ setPendingDeleteSession({+ agentRef: session.agentRef,+ chatId: session.id,+ title: session.title,+ deletion,+ })+ } catch {+ // captureChatDeleteFence reports the failure through the shared chat toast.+ }+ },+ [captureChatDeleteFence, pushToast]+ )+useClickOutside(settingsMenuRef, settingsMenuOpen, () => {updateSettingsMenuOpen(false)})@@ -503,14 +526,7 @@ export function SidebarNav({role="menuitem"color="danger"className="danger"- onClick={() => {- setSessionMenuId(null)- setPendingDeleteSession({- agentRef: session.agentRef,- chatId: session.id,- title: session.title,- })- }}+ onClick={() => void requestDeleteSession(session)}>Delete</MenuItem>@@ -749,7 +765,11 @@ export function SidebarNav({tone="danger"onCancel={() => setPendingDeleteSession(null)}onConfirm={() => {- void onDeleteChatForAgent(pendingDeleteSession.agentRef, pendingDeleteSession.chatId)+ void onDeleteChatForAgent(+ pendingDeleteSession.agentRef,+ pendingDeleteSession.chatId,+ pendingDeleteSession.deletion+ )setPendingDeleteSession(null)}}/>diff --git a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsxindex 38ac26727..eda9d1839 100644--- a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx+++ b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx@@ -24,6 +24,9 @@ vi.mock('@contexts/ChatListContext', () => ({}))vi.mock('@contexts/AgentChatActionsContext', () => ({useAgentChatActionsContext: () => ({+ captureChatDeleteFence: vi.fn(async () => {+ throw new Error('no delete target')+ }),handleRenameChatForAgent: vi.fn(),handleDeleteChatForAgent: vi.fn(),}),diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsxindex c272bc721..67a5b75f4 100644--- a/desktop-app/ui/src/components/agents/ChatThread.tsx+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx@@ -7,7 +7,10 @@ import {useRef,useState,} from 'react'-import { useAgentChatActionsContext } from '@contexts/AgentChatActionsContext'+import {+ type QueuedChatDelete,+ useAgentChatActionsContext,+} from '@contexts/AgentChatActionsContext'import { useChatListContext } from '@contexts/ChatListContext'import { useChatThreadStateContext } from '@contexts/ChatThreadStateContext'import { useMcpRuntimeContext } from '@contexts/McpRuntimeContext'@@ -239,6 +242,7 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: CchatEndRef,handleSelectChat: onSelectChat,handleRenameChat: onRenameChat,+ captureChatDeleteFence,handleDeleteChat: onDeleteChat,} = useAgentChatActionsContext()const { cancelTask: onCancelTask } = useMcpRuntimeContext()@@ -249,8 +253,10 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: Cconst [renamingSessionId, setRenamingSessionId] = useState<string | null>(null)const [sessionRenameValue, setSessionRenameValue] = useState('')const [pendingDeleteSession, setPendingDeleteSession] = useState<{+ agentRef: stringid: stringtitle: string+ deletion: QueuedChatDelete} | null>(null)const dedicatedSessionsRef = useRef<HTMLDivElement | null>(null)const sessionRenameInputRef = useRef<HTMLInputElement | null>(null)@@ -406,16 +412,29 @@ export function ChatThread({ showAgentLabel = false, onScrollPositionChange }: CcancelSessionRename()}, [cancelSessionRename, onRenameChat, renamingSessionId, sessionRenameValue])- const deleteSession = useCallback((chatId: string, chatTitle: string) => {- setSessionMenuChatId(null)- setPendingDeleteSession({ id: chatId, title: chatTitle })- }, [])+ const deleteSession = useCallback(+ async (chatId: string, chatTitle: string) => {+ setSessionMenuChatId(null)+ if (!selectedAgent) return+ try {+ const deletion = await captureChatDeleteFence(selectedAgent)+ setPendingDeleteSession({ agentRef: selectedAgent, id: chatId, title: chatTitle, deletion })+ } catch {+ // Capture reports the scope/authority failure through the normal chat toast path.+ }+ },+ [captureChatDeleteFence, selectedAgent]+ )const confirmDeleteSession = useCallback(() => {if (!pendingDeleteSession) return- void onDeleteChat(pendingDeleteSession.id)+ if (selectedAgent !== pendingDeleteSession.agentRef) {+ setPendingDeleteSession(null)+ return+ }+ void onDeleteChat(pendingDeleteSession.id, pendingDeleteSession.deletion)setPendingDeleteSession(null)- }, [onDeleteChat, pendingDeleteSession])+ }, [onDeleteChat, pendingDeleteSession, selectedAgent])const handleCopyMessage = useCallback(async (messageKey: string, content: string) => {try {diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsxindex dd17760d7..191bd2fbe 100644--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx@@ -162,7 +162,7 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr// Per-chat draft from the module-scoped store. Typing only re-renders this// component (it's the sole subscriber); the value is restored automatically when// activeChatId changes and survives the inline→docked composer swap.- const [draft, setDraft] = useComposerDraft(activeChatId)+ const [draft, setDraft] = useComposerDraft(activeChatId, selectedAgent ?? undefined)const composerInputRef = useRef<HTMLTextAreaElement | null>(null)const composerInputWidthRef = useRef<number | null>(null)const composerFileInputRef = useRef<HTMLInputElement | null>(null)diff --git a/desktop-app/ui/src/components/agents/__tests__/ChatThread.renderSemantics.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ChatThread.renderSemantics.test.tsxindex 838dd7971..7305b9b1b 100644--- a/desktop-app/ui/src/components/agents/__tests__/ChatThread.renderSemantics.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ChatThread.renderSemantics.test.tsx@@ -16,6 +16,9 @@ const actionsValue = {chatEndRef: { current: null },handleSelectChat: vi.fn(),handleRenameChat: vi.fn(),+ captureChatDeleteFence: vi.fn(async () => {+ throw new Error('no delete target')+ }),handleDeleteChat: vi.fn(),}const runtimeValue = { cancelTask: vi.fn() }diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.connectFailure.test.tsx b/desktop-app/ui/src/components/agents/__tests__/chatThread.connectFailure.test.tsxindex c86386072..057320357 100644--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.connectFailure.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.connectFailure.test.tsx@@ -19,6 +19,9 @@ const actionsValue = {chatEndRef: { current: null },handleSelectChat: vi.fn(),handleRenameChat: vi.fn(),+ captureChatDeleteFence: vi.fn(async () => {+ throw new Error('no delete target')+ }),handleDeleteChat: vi.fn(),}const runtimeValue = { cancelTask: vi.fn() }diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsxindex 569adc9b3..0013f2e1c 100644--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx@@ -26,6 +26,9 @@ const actionsValue = {chatEndRef: { current: null },handleSelectChat: vi.fn(),handleRenameChat: vi.fn(),+ captureChatDeleteFence: vi.fn(async () => {+ throw new Error('no delete target')+ }),handleDeleteChat: vi.fn(),}const mcpRuntimeValue = { cancelTask: vi.fn() }diff --git a/desktop-app/ui/src/contexts/AgentChatActionsContext/index.ts b/desktop-app/ui/src/contexts/AgentChatActionsContext/index.tsindex 39d0cfe9d..50ee10b34 100644--- a/desktop-app/ui/src/contexts/AgentChatActionsContext/index.ts+++ b/desktop-app/ui/src/contexts/AgentChatActionsContext/index.ts@@ -1,3 +1,7 @@export { AgentChatActionsContext, AgentChatActionsProvider } from './context'export { useAgentChatActionsContext } from './useAgentChatActionsContext'-export type { AgentChatActionsContextValue, AgentChatActionsProviderProps } from './types'+export type {+ AgentChatActionsContextValue,+ AgentChatActionsProviderProps,+ QueuedChatDelete,+} from './types'diff --git a/desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts b/desktop-app/ui/src/contexts/AgentChatActionsContext/types.tsindex 81beab82a..be847729f 100644--- a/desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts+++ b/desktop-app/ui/src/contexts/AgentChatActionsContext/types.ts@@ -1,6 +1,13 @@import type { ReactNode, RefObject } from 'react'+import type { ChatDeleteFence } from '../../../../src/types'import type { ComposerImageAttachment, ComposerReferenceAttachment } from '../../uiTypes'+export interface QueuedChatDelete {+ agentRef: string+ fence: ChatDeleteFence+ hostAuthorityEpoch: number+}+/*** Stable, cross-cutting chat actions. These are `useCallback` handlers plus the* scroll ref — split out from chat state so action-only consumers (e.g. FleetBoard)@@ -12,8 +19,13 @@ export interface AgentChatActionsContextValue {handleCreateChat: () => Promise<void>handleRenameChat: (chatId: string, newTitle: string) => Promise<void>handleRenameChatForAgent: (agentRef: string, chatId: string, newTitle: string) => Promise<void>- handleDeleteChat: (chatId: string) => Promise<void>- handleDeleteChatForAgent: (agentRef: string, chatId: string) => Promise<void>+ captureChatDeleteFence: (agentRef: string) => Promise<QueuedChatDelete>+ handleDeleteChat: (chatId: string, deletion: QueuedChatDelete) => Promise<void>+ handleDeleteChatForAgent: (+ agentRef: string,+ chatId: string,+ deletion: QueuedChatDelete+ ) => Promise<void>handleSelectChat: (chatId: string) => Promise<void>clearComposerSendError: () => voidhandleAddComposerImageAttachments: (attachments: ComposerImageAttachment[]) => voiddiff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex 61005ad17..ca91cb722 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -7,6 +7,7 @@ import { useAgentChatController } from '../../useAgentChatController'const onHostAccessRevoked = () => {}const onHostAuthorityUncertain = () => {}const isHostAccessBlocked = () => false+const getHostAuthorityEpoch = () => 0type ControllerParams = Parameters<typeof useAgentChatController>[0]@@ -51,6 +52,7 @@ export function renderController(selectedAgent: 'agent-x',agentNames: ['agent-x'],currentTeamId: 'team-1',+ currentEnvironmentKey: 'env-test',currentTeamName: 'Team 1',isAuthenticated: true,loadMenuData: true,@@ -58,6 +60,7 @@ export function renderController(onHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,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.tsindex 44fd8435a..585983158 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/mockClerum.ts@@ -22,6 +22,7 @@ interface ChatMock {create: Fnrename: FngetBindingGeneration: Fn+ captureDeleteFence: Fndelete: FnloadMessages: FnappendMessages: Fn@@ -78,7 +79,13 @@ export function installMockClerum(): MockClerum {})),rename: vi.fn(async () => undefined),getBindingGeneration: vi.fn(async () => 1),- delete: vi.fn(async () => undefined),+ captureDeleteFence: vi.fn(async (authorityScope: unknown) => ({+ version: 1,+ authorityScope,+ bindingGeneration: 1,+ sessionGeneration: 1,+ })),+ delete: vi.fn(async () => ({ cleanupPending: false })),loadMessages: vi.fn(async () => []),appendMessages: vi.fn(async () => undefined),replaceMessages: 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.tsxindex e6751a145..20ef621e9 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@@ -59,13 +59,18 @@ describe('handleDeleteChat', () => {expect(result.current.sessionStateByChatKey[key]?.state).toBe('processing')await act(async () => {- await result.current.handleDeleteChat(chatId)+ const deletion = await result.current.captureChatDeleteFence('agent-x')+ await result.current.handleDeleteChat(chatId, deletion)})// 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, 1)+ expect(clerum.chat.delete).toHaveBeenCalledWith(+ 'agent-x',+ chatId,+ expect.objectContaining({ version: 1, bindingGeneration: 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.tsxindex 165d810e0..0c41cbcce 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatListTitleMerge.test.tsx@@ -51,6 +51,7 @@ function localIndex(chats: Array<{ id: string; title: string }>,deletedChatIds: string[] = []): ChatIndex {+ const authorityScope = { environmentKey: 'env-test', userId: 'unknown-user', teamId: 'team-1' }return {version: 1,lastActiveChatId: null,@@ -63,6 +64,7 @@ function localIndex(messageCount: 0,})),deletedChatIds,+ deletedChatTombstones: deletedChatIds.map(chatId => ({ chatId, authorityScope })),}}@@ -229,12 +231,14 @@ describe('revoked host catalog protection', () => {))- clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ clerum.rpc.loadSessionMessages.mockRejectedValue(+ new Error('403 forbidden: host_access_revoked')+ )await expect(controller.result.current.reconcileChat(makeTaskKey('agent-y', 'protected-y'), {reason: 'background_refresh',})- ).resolves.toBe('authority_unverified')+ ).resolves.toBe('revoked')expect(blocked.has('agent-y')).toBe(true)await waitFor(() =>expect(controller.result.current.latestChatSessions.some(s => s.id === 'protected-y')).toBe(@@ -296,6 +300,40 @@ describe('revoked host catalog protection', () => {})})+describe('host authority verification', () => {+ it('discards a pre-verification authorization denial after the host authority epoch advances', async () => {+ let hostAuthorityEpoch = 0+ const revoked = new Set<string>()+ const uncertain = new Set<string>()+ clerum.chat.getIndex.mockResolvedValue(localIndex([]))+ let rejectFirst!: (reason: unknown) => void+ let firstCatalogRead = true+ clerum.rpc.listSessions.mockImplementation(() => {+ if (!firstCatalogRead) return Promise.resolve(serverSessions([]))+ firstCatalogRead = false+ return new Promise((_resolve, reject) => {+ rejectFirst = reject+ })+ })++ const controller = renderController({+ selectedAgent: 'agent-x',+ agentNames: ['agent-x'],+ onHostAccessRevoked: agentRef => revoked.add(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked: agentRef => revoked.has(agentRef) || uncertain.has(agentRef),+ getHostAuthorityEpoch: () => hostAuthorityEpoch,+ })++ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())+ hostAuthorityEpoch += 1+ rejectFirst(new Error('403 stale'))+ await waitFor(() => expect(controller.result.current.latestChatSessionsLoading).toBe(false))+ expect(revoked.has('agent-x')).toBe(false)+ expect(uncertain.has('agent-x')).toBe(false)+ })+})+describe('late global catalog response', () => {it.each(['revocation', 'confirmed deletion'])('does not republish Host A after %s while Host B is pending',@@ -336,9 +374,14 @@ describe('late global catalog response', () => {expect(blocked.has('agent-a')).toBe(true)} else {await act(async () => {- await controller.result.current.handleDeleteChatForAgent('agent-a', 'session-a')+ const deletion = await controller.result.current.captureChatDeleteFence('agent-a')+ await controller.result.current.handleDeleteChatForAgent('agent-a', 'session-a', deletion)})- expect(clerum.chat.delete).toHaveBeenCalledWith('agent-a', 'session-a', 1)+ expect(clerum.chat.delete).toHaveBeenCalledWith(+ 'agent-a',+ 'session-a',+ expect.objectContaining({ version: 1, bindingGeneration: 1 })+ )}await act(async () => {diff --git a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsxindex 036ed97cd..183a1ffe3 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/renameSessionQueue.test.tsx@@ -14,7 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act, cleanup, waitFor } from '@testing-library/react'import { parseSessionsListResult } from '../../../../../src/rpcProxyClient'import type { ChatIndex } from '../../../../../src/types'-import { MAX_RENAME_SYNC_ATTEMPTS } from '../useChatListController'+import { MAX_RENAME_SYNC_ATTEMPTS, deletedChatIdsForScope } from '../useChatListController'import { renderController } from './__fixtures__/controllerHarness'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'@@ -53,6 +53,47 @@ function localIndex(chats: Array<{ id: string; title: string }>): ChatIndex {}}+describe('scoped deletion visibility', () => {+ it('filters tombstones by environment, user, and team while keeping legacy reads conservative', () => {+ const index: ChatIndex = {+ ...localIndex([]),+ deletedChatIds: ['legacy-delete'],+ deletedChatTombstones: [+ {+ chatId: 'team-a-delete',+ authorityScope: { environmentKey: 'env-1', userId: 'user-1', teamId: 'team-a' },+ },+ {+ chatId: 'other-environment-delete',+ authorityScope: { environmentKey: 'env-2', userId: 'user-1', teamId: 'team-a' },+ },+ ],+ }++ expect(+ deletedChatIdsForScope(index, {+ environmentKey: 'env-1',+ userId: 'user-1',+ teamId: 'team-a',+ })+ ).toEqual(['team-a-delete'])+ expect(+ deletedChatIdsForScope(index, {+ environmentKey: 'env-1',+ userId: 'user-1',+ teamId: 'team-b',+ })+ ).toEqual([])+ expect(+ deletedChatIdsForScope(index, {+ environmentKey: 'env-1',+ userId: 'user-1',+ teamId: null,+ })+ ).toEqual(['legacy-delete'])+ })+})+function titleInList(current: { chatList: Array<{ id: string; title: string }> }, id: string) {return current.chatList.find(c => c.id === id)?.title}@@ -124,29 +165,34 @@ describe('rename pending queue (spec 15 §2.5)', () => {renameError: 'Rename session failed (403): host_access_revoked',readStatus: null,shouldRevoke: true,+ shouldBeUncertain: false,},{label: 'operation-scope denial',renameError: 'Rename session failed (403)',readStatus: null,shouldRevoke: false,+ shouldBeUncertain: true,},{label: 'read also denied',renameError: 'Rename session failed (403)',readStatus: 403,- shouldRevoke: true,+ shouldRevoke: false,+ shouldBeUncertain: true,},{label: 'read unavailable',renameError: 'Rename session failed (403)',readStatus: 503,shouldRevoke: false,+ shouldBeUncertain: true,},])('$label applies the transcript authority decision',- async ({ renameError, readStatus, shouldRevoke }) => {+ async ({ renameError, readStatus, shouldRevoke, shouldBeUncertain }) => {const revoked = new Set<string>()+ const uncertain = new Set<string>()clerum.chat.getIndex.mockResolvedValue(localIndex([{ id: 'c1', title: 'old' }]))clerum.rpc.renameSession.mockRejectedValue(new Error(renameError))clerum.rpc.listSessions.mockImplementation(@@ -159,6 +205,7 @@ describe('rename pending queue (spec 15 §2.5)', () => {selectedAgent: 'agent-x',agentNames: ['agent-x'],onHostAccessRevoked: agentRef => revoked.add(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),isHostAccessBlocked: agentRef => revoked.has(agentRef),})await waitFor(() => expect(titleInList(result.current, 'c1')).toBe('old'))@@ -166,8 +213,9 @@ describe('rename pending queue (spec 15 §2.5)', () => {await result.current.handleRenameChatForAgent('agent-x', 'c1', 'new')})expect(revoked.has('agent-x')).toBe(shouldRevoke)+ expect(uncertain.has('agent-x')).toBe(shouldBeUncertain)if (shouldRevoke) expect(result.current.chatList).toEqual([])- else expect(titleInList(result.current, 'c1')).toBe('old')+ else expect(titleInList(result.current, 'c1')).toBe('new')})@@ -275,7 +323,7 @@ describe('rename pending queue (spec 15 §2.5)', () => {// Next poll reports c1 → the queue retries the 404'd rename.await act(async () => {- rerender({ agentNames: ['agent-x'] })+ rerender({ agentNames: ['agent-x', 'agent-y'] })})await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))// Still shows the rename (never clobbered by the server title).@@ -343,11 +391,11 @@ describe('rename pending queue — concurrency (spec 15 §2.5)', () => {// trick drives a retry in the 404 case — see the T5 test — so it does invoke// flushPendingRenames; here the in-flight guard must make it a no-op.)await act(async () => {- rerender({ agentNames: ['agent-x'] })+ rerender({ agentNames: ['agent-x', 'agent-y'] })await flushMicrotasks()})await act(async () => {- rerender({ agentNames: ['agent-x'] })+ rerender({ agentNames: ['agent-x', 'agent-y'] })await flushMicrotasks()})@@ -704,7 +752,7 @@ describe('rename pending queue — bounded retry (spec 15 §2.5 / R1-M1)', () =>reportedSessions([{ chatId: 'c1', title: 'server' }]))await act(async () => {- rerender({ agentNames: ['agent-x'] })+ rerender({ agentNames: ['agent-x', 'agent-y'] })await flushMicrotasks()})await waitFor(() => expect(clerum.rpc.renameSession).toHaveBeenCalledTimes(2))diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsxindex 447885633..142ef9c82 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@@ -999,6 +999,7 @@ describe('switchToChat (unified, D.4)', () => {'older-message HTTP %i applies the correct Host authority decision',async status => {const revoked = new Set<string>()+ const uncertain = new Set<string>()clerum.chat.loadMessages.mockImplementation(async (_agentRef, _chatId, _limit, offset) =>offset === undefined? [@@ -1027,8 +1028,8 @@ describe('switchToChat (unified, D.4)', () => {)const { result } = renderController({onHostAccessRevoked: agentRef => revoked.add(agentRef),- onHostAuthorityUncertain: agentRef => revoked.add(agentRef),- isHostAccessBlocked: agentRef => revoked.has(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked: agentRef => revoked.has(agentRef) || uncertain.has(agentRef),})await settleMount()await act(async () => {@@ -1041,12 +1042,14 @@ describe('switchToChat (unified, D.4)', () => {})if (status === 404) {expect(revoked.has('agent-x')).toBe(false)+ expect(uncertain.has('agent-x')).toBe(false)expect(result.current.activeChatId).toBe('older-authority')expect(result.current.chatMessages.map(message => message.content)).toEqual(['cached'])} else {- expect(revoked.has('agent-x')).toBe(true)- expect(result.current.activeChatId).toBeNull()- expect(result.current.chatMessages).toEqual([])+ expect(revoked.has('agent-x')).toBe(false)+ expect(uncertain.has('agent-x')).toBe(true)+ expect(result.current.activeChatId).toBe('older-authority')+ expect(result.current.chatMessages.map(message => message.content)).toEqual(['cached'])}})@@ -1131,6 +1134,7 @@ describe('switchToChat (unified, D.4)', () => {'durable task-result HTTP %i applies the correct Host authority decision',async status => {const revoked = new Set<string>()+ const uncertain = new Set<string>()clerum.chat.loadMessages.mockResolvedValue([])clerum.rpc.loadSessionMessages.mockResolvedValue({agent: 'agent-x',@@ -1141,8 +1145,8 @@ describe('switchToChat (unified, D.4)', () => {clerum.rpc.getTaskResult.mockRejectedValue(new Error(`${status} response`))const { result } = renderController({onHostAccessRevoked: agentRef => revoked.add(agentRef),- onHostAuthorityUncertain: agentRef => revoked.add(agentRef),- isHostAccessBlocked: agentRef => revoked.has(agentRef),+ onHostAuthorityUncertain: agentRef => uncertain.add(agentRef),+ isHostAccessBlocked: agentRef => revoked.has(agentRef) || uncertain.has(agentRef),})await settleMount()await act(async () => {@@ -1158,10 +1162,12 @@ describe('switchToChat (unified, D.4)', () => {expect(clerum.rpc.getTaskResult).toHaveBeenCalled()if (status === 404) {expect(revoked.has('agent-x')).toBe(false)+ expect(uncertain.has('agent-x')).toBe(false)expect(result.current.activeChatId).toBe('result-authority')} else {- expect(revoked.has('agent-x')).toBe(true)- expect(result.current.activeChatId).toBeNull()+ expect(revoked.has('agent-x')).toBe(false)+ expect(uncertain.has('agent-x')).toBe(true)+ expect(result.current.activeChatId).toBe('result-authority')}})@@ -1209,9 +1215,18 @@ describe('switchToChat (unified, D.4)', () => {expect(revoked.has('agent-x')).toBe(true)} else if (action === 'confirmed deletion') {await act(async () => {- await controller.result.current.handleDeleteChatForAgent('agent-x', 'late-result')+ const deletion = await controller.result.current.captureChatDeleteFence('agent-x')+ await controller.result.current.handleDeleteChatForAgent(+ 'agent-x',+ 'late-result',+ deletion+ )})- expect(clerum.chat.delete).toHaveBeenCalledWith('agent-x', 'late-result', 1)+ expect(clerum.chat.delete).toHaveBeenCalledWith(+ 'agent-x',+ 'late-result',+ expect.objectContaining({ version: 1, bindingGeneration: 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.tsxindex 456dcb471..78a6b3628 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@@ -17,13 +17,16 @@ import type { TaskProgressStreamEvent } from '../../../../../src/types'type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>const revokedAgents = new Set<string>()+const uncertainAgents = new Set<string>()const onHostAccessRevoked = (agentRef: string) => {revokedAgents.add(agentRef)}const onHostAuthorityUncertain = (agentRef: string) => {- revokedAgents.add(agentRef)+ uncertainAgents.add(agentRef)}-const isHostAccessBlocked = (agentRef: string) => revokedAgents.has(agentRef)+const isHostAccessBlocked = (agentRef: string) =>+ revokedAgents.has(agentRef) || uncertainAgents.has(agentRef)+const getHostAuthorityEpoch = () => 0function getDraftInputValue(): string {return (screen.getByTestId('draft-input') as HTMLInputElement).value@@ -72,11 +75,18 @@ function installClerumHarness() {}),rename: vi.fn(async () => undefined),getBindingGeneration: vi.fn(async () => 1),+ captureDeleteFence: vi.fn(async (authorityScope: unknown) => ({+ version: 1,+ authorityScope,+ bindingGeneration: 1,+ sessionGeneration: 1,+ })),delete: vi.fn(async (_agentRef: string, chatId: string) => {deletedChatIds.add(chatId)const index = chats.findIndex(chat => chat.id === chatId)if (index >= 0) chats.splice(index, 1)messagesByChat.delete(chatId)+ return { cleanupPending: false }}),loadMessages: vi.fn(async (_agentRef: string, chatId: string) => messagesByChat.get(chatId) || []@@ -133,6 +143,7 @@ function AgentChatHarness() {selectedAgent: 'trader',agentNames: ['trader'],currentTeamId: 'team-1',+ currentEnvironmentKey: 'env-test',currentTeamName: 'Team One',isAuthenticated: true,loadMenuData: true,@@ -140,6 +151,7 @@ function AgentChatHarness() {onHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,@@ -192,7 +204,14 @@ function AgentChatHarness() {>Select chat {chat.id}</button>- <button type="button" onClick={() => void vm.handleDeleteChatForAgent('trader', chat.id)}>+ <button+ type="button"+ onClick={() => {+ void vm+ .captureChatDeleteFence('trader')+ .then(deletion => vm.handleDeleteChatForAgent('trader', chat.id, deletion))+ }}+ >Delete chat {chat.id}</button></React.Fragment>@@ -205,6 +224,7 @@ describe('useAgentChatController (cross-chat, migrated)', () => {afterEach(() => {cleanup()vi.restoreAllMocks()+ uncertainAgents.clear()resetComposerDraftStore()revokedAgents.clear()delete (window as { clerum?: unknown }).clerum@@ -363,7 +383,7 @@ describe('useAgentChatController (cross-chat, migrated)', () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }))await waitFor(() => expect(invokeHostMessage).toHaveBeenCalledTimes(1))- loadSessionMessages.mockRejectedValue(new Error('403 forbidden'))+ loadSessionMessages.mockRejectedValue(new Error('403 forbidden: host_access_revoked'))fireEvent.click(screen.getByRole('button', { name: `Select chat ${chatId}` }))await waitFor(() => expect(revokedAgents.has('trader')).toBe(true))await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).toBe(''))@@ -379,29 +399,44 @@ describe('useAgentChatController (cross-chat, migrated)', () => {})it.each([- { label: '401', sendError: '401 unauthorized', readError: null, revoked: true },+ {+ label: '401',+ sendError: '401 unauthorized',+ readError: null,+ revoked: false,+ uncertain: true,+ },{label: 'exact Host-wide 403',sendError: '403 Forbidden: host_access_revoked',readError: '503 unavailable',revoked: true,+ uncertain: false,},{label: 'generic 403 with readable catalog',sendError: '403 missing send scope',readError: null,revoked: false,+ uncertain: false,},{label: 'generic 403 with denied catalog',sendError: '403 missing send scope',readError: '403 forbidden',- revoked: true,+ revoked: false,+ uncertain: true,+ },+ {+ label: '404',+ sendError: '404 transient',+ readError: null,+ revoked: false,+ uncertain: false,},- { label: '404', sendError: '404 transient', readError: null, revoked: false },])('send $label applies the transcript authority decision',- async ({ sendError, readError, revoked }) => {+ async ({ sendError, readError, revoked, uncertain }) => {const { invokeHostMessage, listSessions } = installClerumHarness()invokeHostMessage.mockRejectedValueOnce(new Error(sendError))render(@@ -416,6 +451,7 @@ describe('useAgentChatController (cross-chat, migrated)', () => {fireEvent.click(screen.getByRole('button', { name: 'Send message' }))await waitFor(() => expect(screen.getByTestId('send-state').textContent).toBe('settled'))expect(revokedAgents.has('trader')).toBe(revoked)+ expect(uncertainAgents.has('trader')).toBe(uncertain)if (revoked) {expect(screen.getByTestId('active-chat-id').textContent).toBe('')expect(screen.getByTestId('chat-message-count').textContent).toBe('0')diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsxindex a0aca4cf9..8f5638af5 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@@ -22,6 +22,7 @@ type ProgressHandler = (event: TaskProgressStreamEvent) => void | Promise<void>const onHostAccessRevoked = () => {}const onHostAuthorityUncertain = () => {}const isHostAccessBlocked = () => false+const getHostAuthorityEpoch = () => 0function createChatMeta(chatId: string) {const now = new Date().toISOString()@@ -67,7 +68,13 @@ function installClerumHarness() {}),rename: vi.fn(async () => undefined),getBindingGeneration: vi.fn(async () => 1),- delete: vi.fn(async () => undefined),+ captureDeleteFence: vi.fn(async (authorityScope: unknown) => ({+ version: 1,+ authorityScope,+ bindingGeneration: 1,+ sessionGeneration: 1,+ })),+ delete: vi.fn(async () => ({ cleanupPending: false })),loadMessages: vi.fn(async (_agentRef: string, chatId: string) => messagesByChat.get(chatId) || []),@@ -121,6 +128,7 @@ function AgentChatHarness() {selectedAgent: 'trader',agentNames: ['trader'],currentTeamId: 'team-1',+ currentEnvironmentKey: 'env-test',currentTeamName: 'Team One',isAuthenticated: true,loadMenuData: true,@@ -128,6 +136,7 @@ function AgentChatHarness() {onHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,pushToast: vi.fn(),pushNotification: vi.fn(),agentDisplayName: (agentName: string) => agentName,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsxindex d98ebe713..0e5e38bd6 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@@ -84,6 +84,7 @@ interface HarnessProps {const onHostAccessRevoked = () => {}const onHostAuthorityUncertain = () => {}const isHostAccessBlocked = () => false+const getHostAuthorityEpoch = () => 0/** Both real hooks, mounted together under the task-tracker the chat controller needs. */function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navItem }: HarnessProps) {@@ -92,6 +93,7 @@ function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navIteselectedAgent,agentNames,currentTeamId: 'team-1',+ currentEnvironmentKey: 'env-test',currentTeamName: 'Team 1',isAuthenticated,loadMenuData: true,@@ -99,6 +101,7 @@ function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navIteonHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,...stableCallbacks,})}diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 119780a41..a0d9dbc1a 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -13,6 +13,7 @@ import {import { truncateTitle } from '@lib/chatTitle'import {clearAllComposerDrafts,+ clearComposerDraft,getComposerDraft,getComposerDraftRevision,setComposerDraft,@@ -335,6 +336,7 @@ interface UseAgentChatControllerParams {agentNames: string[]currentUserId?: stringcurrentTeamId: string+ currentEnvironmentKey: stringcurrentTeamName: stringisAuthenticated: booleanloadMenuData: boolean@@ -362,6 +364,7 @@ interface UseAgentChatControllerParams {onHostAccessRevoked: (agentRef: string) => voidonHostAuthorityUncertain: (agentRef: string) => voidisHostAccessBlocked: (agentRef: string) => boolean+ getHostAuthorityEpoch: (agentRef: string) => number}export function useAgentChatController({@@ -369,6 +372,7 @@ export function useAgentChatController({agentNames,currentUserId,currentTeamId,+ currentEnvironmentKey,currentTeamName,isAuthenticated,loadMenuData,@@ -383,9 +387,20 @@ export function useAgentChatController({onHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,}: UseAgentChatControllerParams) {const chatStore = useChatStore()- const authenticatedScope = `${currentUserId ?? 'unknown-user'}:${currentTeamId}`+ const userScopeKey = currentUserId ?? 'unknown-user'+ const normalizedTeamId = String(currentTeamId || '').trim() || null+ const authorityScope = useMemo(+ () => ({+ environmentKey: currentEnvironmentKey,+ userId: userScopeKey,+ teamId: normalizedTeamId,+ }),+ [currentEnvironmentKey, normalizedTeamId, userScopeKey]+ )+ const authenticatedScope = `${currentEnvironmentKey}:${userScopeKey}:${normalizedTeamId ?? ''}`useEffect(() => {chatStore.setRemoteCacheScope(@@ -432,11 +447,13 @@ export function useAgentChatController({// User portion of the scope only (NOT the combined user:team scopeKey): the// pending-rename queue is per-user and must survive a team-switch (R1-H1).authUserKey: currentUserId ?? 'unknown-user',+ authorityScope,loadMenuData,chatStore,fsm,host: chatListHostRef,isHostAccessBlocked,+ getHostAuthorityEpoch,onHostAccessRevoked: onCatalogHostAccessRevoked,onHostAuthorityUncertain: onCatalogHostAuthorityUncertain,})@@ -1041,6 +1058,7 @@ export function useAgentChatController({handleRenameChat,handleRenameChatForAgent,applyLocalTitleOnly,+ captureChatDeleteFence,handleDeleteChat,handleDeleteChatForAgent,} = chatListCtl@@ -1888,23 +1906,25 @@ export function useAgentChatController({const { [agentRef]: _removed, ...remaining } = previousreturn remaining})- hideAgent(agentRef)- const view = activeChatVisibilityRef.current- if (agentSendSetupOwnerRef.current?.agentRef === agentRef) {- agentSendSetupOwnerRef.current = null- agentSendInFlightRef.current = false- setAgentSending(false)- }- if (view.selectedAgent === agentRef) {- chatStore.clearCachedRemoteData()- clearList()- resetComposerAttachments()- activeChatVisibilityRef.current = { ...view, selectedAgent: null, activeChatId: null }- setActiveChatId(null)- setChatMessages([])- setChatMessagesLoading(false)- setHasOlderMessages(false)- cancelOlderMessagesLoad()+ if (kind === 'revoked') {+ hideAgent(agentRef)+ const view = activeChatVisibilityRef.current+ if (agentSendSetupOwnerRef.current?.agentRef === agentRef) {+ agentSendSetupOwnerRef.current = null+ agentSendInFlightRef.current = false+ setAgentSending(false)+ }+ if (view.selectedAgent === agentRef) {+ chatStore.clearCachedRemoteData()+ clearList()+ resetComposerAttachments()+ activeChatVisibilityRef.current = { ...view, selectedAgent: null, activeChatId: null }+ setActiveChatId(null)+ setChatMessages([])+ setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ }}if (kind === 'revoked') onHostAccessRevoked(agentRef)else onHostAuthorityUncertain(agentRef)@@ -2689,7 +2709,8 @@ export function useAgentChatController({const sendScope = sendScopeGeneration.currentconst sendScopeIdentity = currentAuthScopeRef.currentconst originalDraftChat = activeChatVisibilityRef.current.activeChatId- const originalDraftRevision = getComposerDraftRevision(originalDraftChat)+ const originalDraftAgent = selectedAgent+ const originalDraftRevision = getComposerDraftRevision(originalDraftChat, originalDraftAgent)const originalAttachmentRevision = composerAttachmentRevisionRef.currentconst trimmedContent = content.trim()const effectiveAttachments = [...attachments]@@ -2903,9 +2924,10 @@ export function useAgentChatController({activeChatVisibilityRef.current.selectedAgent === sendAgent &&activeChatVisibilityRef.current.activeChatId === sendChatId &&composerAttachmentRevisionRef.current === originalAttachmentRevision &&- getComposerDraftRevision(originalDraftChat) === originalDraftRevision+ getComposerDraftRevision(originalDraftChat, originalDraftAgent) === originalDraftRevision) {clearComposerAfterSend(sendChatId)+ clearComposerDraft(null, sendAgent)}setAgentError(null)setFailedAgentSend(null)@@ -3319,14 +3341,14 @@ export function useAgentChatController({)returnif (- getComposerDraft(activeChatId) ||+ getComposerDraft(activeChatId, selectedAgent ?? undefined) ||composerImageAttachments.length ||composerReferenceAttachments.length) {pushToast('Keep or clear the current draft before recovering the earlier input.', 'error')return}- setComposerDraft(activeChatId, visibleFailure.content)+ setComposerDraft(activeChatId, visibleFailure.content, selectedAgent ?? undefined)handleAddComposerImageAttachments(visibleFailure.attachments.map(attachment => ({...attachment,@@ -3548,6 +3570,7 @@ export function useAgentChatController({handleRenameChat,handleRenameChatForAgent,applyLocalTitleOnly,+ captureChatDeleteFence,handleDeleteChat,handleDeleteChatForAgent,handleSelectChat,diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 24436ad28..dcbea1bb8 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -2,7 +2,13 @@ import { type MutableRefObject, useCallback, useEffect, useRef, useState } fromimport { makeTaskKey } from '@contexts/AgentTaskTrackerContext'import { agentChatPlaceholder, remotePlaceholder } from '@lib/chatTitle'import { type PendingRename, resolveSessionTitle } from '@lib/resolveSessionTitle'-import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'+import type {+ ChatAuthorityScope,+ ChatDeleteFence,+ ChatIndex,+ ChatMetadata,+ SessionsListResult,+} from '../../../../src/types'import { isAuthorizationError, isConfirmedHostAccessRevoked } from '../../lib/format'import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import type { useChatStore } from '../useChatStore'@@ -97,11 +103,13 @@ interface UseChatListControllerParams {* team-switch of the same user — see the teardown effect below.*/authUserKey: string+ authorityScope: ChatAuthorityScopeloadMenuData: booleanchatStore: ReturnType<typeof useChatStore>fsm: SessionFsmStorehost: MutableRefObject<ChatListControllerHost | null>isHostAccessBlocked: (agentRef: string) => boolean+ getHostAuthorityEpoch: (agentRef: string) => numberonHostAccessRevoked: (agentRef: string) => voidonHostAuthorityUncertain: (agentRef: string) => void}@@ -129,8 +137,9 @@ function isRecoverableCatalogCursorError(error: unknown): boolean {* error) is treated as a network failure.* - 'not-found' (404): session not materialized server-side yet → keep pending,* retry once it appears in listSessions. NOT an error; no rollback.- * - 'client-error' (other 4xx: 400 invalid title, 401/403 access): a genuine- * rejection → roll the optimistic title back and toast.+ * - 'client-error' (other 4xx, such as 400 invalid title): a genuine rejection+ * → roll the optimistic title back and toast. Authorization failures are+ * handled separately because a generic 401/403 does not prove revocation.* - 'network' (5xx / no status): transient → queue offline, retry on reconnect.*/function classifyRenameError(error: unknown): 'not-found' | 'client-error' | 'network' {@@ -138,6 +147,7 @@ function classifyRenameError(error: unknown): 'not-found' | 'client-error' | 'neconst match = message.match(/\((\d{3})\)/)const status = match ? Number(match[1]) : nullif (status === 404) return 'not-found'+ if (status === 401 || status === 403) return 'network'if (status !== null && status >= 400 && status < 500) return 'client-error'return 'network'}@@ -156,17 +166,37 @@ function knownServerMessageCount(session: SessionsListResult['items'][number]):return typeof count === 'number' && Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0}+function sameAuthorityScope(left: ChatAuthorityScope, right: ChatAuthorityScope): boolean {+ return (+ left.environmentKey === right.environmentKey &&+ left.userId === right.userId &&+ left.teamId === right.teamId+ )+}++export function deletedChatIdsForScope(index: ChatIndex, scope: ChatAuthorityScope): string[] {+ const scoped = (index.deletedChatTombstones ?? [])+ .filter(tombstone => sameAuthorityScope(tombstone.authorityScope, scope))+ .map(tombstone => tombstone.chatId)+ // Legacy IDs have no known team owner. Keep their historic behavior for the+ // unscoped account, but don't carry them into a different new team.+ const legacy = scope.teamId === null ? (index.deletedChatIds ?? []) : []+ return [...new Set([...legacy, ...scoped])]+}+export function useChatListController({selectedAgent,agentNames,isAuthenticated,scopeKey,authUserKey,+ authorityScope,loadMenuData,chatStore,fsm,host,isHostAccessBlocked,+ getHostAuthorityEpoch,onHostAccessRevoked,onHostAuthorityUncertain,}: UseChatListControllerParams) {@@ -188,6 +218,9 @@ export function useChatListController({const deletedChatIdsByAgentRef = useRef(new Map<string, Set<string>>())const requestGenerationRef = useRef(0)const authorityScopeGenerationRef = useRef(0)+ const agentNamesRef = useRef(agentNames)+ agentNamesRef.current = agentNames+ const agentNamesKey = agentNames.join('\n')const currentAuthorityScopeRef = useRef(`${isAuthenticated}:${scopeKey}`)currentAuthorityScopeRef.current = `${isAuthenticated}:${scopeKey}`@@ -319,6 +352,8 @@ export function useChatListController({requestGeneration: number): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {const authorityScopeGeneration = authorityScopeGenerationRef.current+ const authorityScopeAtRequest = currentAuthorityScopeRef.current+ const hostAuthorityEpoch = getHostAuthorityEpoch(agentRef)chatListNextCursorByAgentRef.current[agentRef] = nullif (selectedAgentRef.current === agentRef) {setChatListHasMoreRemoteSessions(false)@@ -326,14 +361,20 @@ export function useChatListController({}const index = await chatStore.getIndex(agentRef)if (- selectedAgentRef.current !== agentRef ||- requestGenerationRef.current !== requestGeneration ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||+ currentAuthorityScopeRef.current !== authorityScopeAtRequest ||isHostAccessBlocked(agentRef)+ ) {+ return { index, merged: [] }+ }+ if (+ selectedAgentRef.current !== agentRef ||+ requestGenerationRef.current !== requestGeneration) {return { index, merged: [...index.chats].sort(byUpdatedDesc) }}const deleted = deletedChatIdsByAgentRef.current.get(agentRef) ?? new Set<string>()- for (const chatId of index.deletedChatIds ?? []) deleted.add(chatId)+ for (const chatId of deletedChatIdsForScope(index, authorityScope)) deleted.add(chatId)deletedChatIdsByAgentRef.current.set(agentRef, deleted)const merged = index.chats.filter(chat => !deleted.has(chat.id)).sort(byUpdatedDesc)setChatList(merged)@@ -350,6 +391,8 @@ export function useChatListController({if (isAuthorizationError(error) &&authorityScopeGenerationRef.current === authorityScopeGeneration &&+ getHostAuthorityEpoch(agentRef) === hostAuthorityEpoch &&+ currentAuthorityScopeRef.current === authorityScopeAtRequest &&!isHostAccessBlocked(agentRef)) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)@@ -360,6 +403,8 @@ export function useChatListController({if (selectedAgentRef.current !== agentRef ||requestGenerationRef.current !== requestGeneration ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||+ currentAuthorityScopeRef.current !== authorityScopeAtRequest ||isHostAccessBlocked(agentRef)) {if (@@ -490,10 +535,12 @@ export function useChatListController({return { index, merged }},[+ authorityScope,chatStore.getIndex,chatStore.listSessions,chatStore.reconcileServerSessions,fsm,+ getHostAuthorityEpoch,isHostAccessBlocked,onHostAccessRevoked,]@@ -513,6 +560,8 @@ export function useChatListController({chatListLoadingMoreByAgentRef.current.add(agentRef)const requestGeneration = requestGenerationRef.currentconst authorityScopeGeneration = authorityScopeGenerationRef.current+ const authorityScopeAtRequest = currentAuthorityScopeRef.current+ const hostAuthorityEpoch = getHostAuthorityEpoch(agentRef)setChatListMoreLoading(true)try {let serverResult: SessionsListResult@@ -526,6 +575,8 @@ export function useChatListController({if (isAuthorizationError(error) &&authorityScopeGenerationRef.current === authorityScopeGeneration &&+ getHostAuthorityEpoch(agentRef) === hostAuthorityEpoch &&+ currentAuthorityScopeRef.current === authorityScopeAtRequest &&!isHostAccessBlocked(agentRef)) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)@@ -534,6 +585,8 @@ export function useChatListController({}if (requestGenerationRef.current === requestGeneration &&+ getHostAuthorityEpoch(agentRef) === hostAuthorityEpoch &&+ currentAuthorityScopeRef.current === authorityScopeAtRequest &&selectedAgentRef.current === agentRef) {if (isRecoverableCatalogCursorError(error)) {@@ -545,12 +598,25 @@ export function useChatListController({}return}- if (requestGenerationRef.current !== requestGeneration) return+ if (+ requestGenerationRef.current !== requestGeneration ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||+ currentAuthorityScopeRef.current !== authorityScopeAtRequest+ ) {+ return+ }const serverSessions = serverResult.items.filter(s => s.agent === agentRef && !deletedChatIdsByAgentRef.current.get(agentRef)?.has(s.chatId))- if (selectedAgentRef.current !== agentRef || isHostAccessBlocked(agentRef)) return+ if (+ selectedAgentRef.current !== agentRef ||+ isHostAccessBlocked(agentRef) ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpoch ||+ currentAuthorityScopeRef.current !== authorityScopeAtRequest+ ) {+ return+ }chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? nullsetChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))@@ -618,6 +684,7 @@ export function useChatListController({chatStore.listSessions,chatStore.reconcileServerSessions,fsm,+ getHostAuthorityEpoch,isHostAccessBlocked,onHostAccessRevoked,])@@ -844,10 +911,10 @@ export function useChatListController({if (!agentRef || !isAuthenticated) returnconst requestGeneration = requestGenerationRef.currentconst authorityScopeGeneration = authorityScopeGenerationRef.current- const authorityScope = currentAuthorityScopeRef.current+ const authorityScopeAtDelete = currentAuthorityScopeRef.currentconst stillOwned = () =>authorityScopeGenerationRef.current === authorityScopeGeneration &&- currentAuthorityScopeRef.current === authorityScope+ currentAuthorityScopeRef.current === authorityScopeAtDeleteconst bindingGeneration = await chatStore.getBindingGeneration()if (!stillOwned()) returnconst updatedAt = new Date().toISOString()@@ -900,6 +967,10 @@ export function useChatListController({if (pendingRenamesRef.current.get(key) !== entry) returnentry.sending = trueconst authorityScopeGeneration = authorityScopeGenerationRef.current+ const hostAuthorityEpoch = getHostAuthorityEpoch(entry.agentRef)+ const requestStillCurrent = () =>+ authorityScopeGenerationRef.current === authorityScopeGeneration &&+ getHostAuthorityEpoch(entry.agentRef) === hostAuthorityEpochtry {await chatStore.renameSession(entry.agentRef, entry.chatId, entry.title)// Only clear if this attempt still owns the key (a stale 200 must never@@ -910,7 +981,7 @@ export function useChatListController({} catch (error) {if (isConfirmedHostAccessRevoked(error) &&- authorityScopeGenerationRef.current === authorityScopeGeneration &&+ requestStillCurrent() &&!isHostAccessBlocked(entry.agentRef)) {onHostAccessRevoked(entry.agentRef)@@ -919,11 +990,8 @@ export function useChatListController({}return}- if (- isAuthorizationError(error) &&- authorityScopeGenerationRef.current === authorityScopeGeneration &&- !isHostAccessBlocked(entry.agentRef)- ) {+ if (isAuthorizationError(error)) {+ if (!requestStillCurrent() || isHostAccessBlocked(entry.agentRef)) returntry {await chatStore.listSessions(entry.agentRef,@@ -931,11 +999,8 @@ export function useChatListController({{ force: true })} catch (readError) {- if (- isAuthorizationError(readError) &&- authorityScopeGenerationRef.current === authorityScopeGeneration &&- !isHostAccessBlocked(entry.agentRef)- ) {+ if (!requestStillCurrent() || isHostAccessBlocked(entry.agentRef)) return+ if (isConfirmedHostAccessRevoked(readError)) {onHostAccessRevoked(entry.agentRef)if (pendingRenamesRef.current.get(key) === entry) {pendingRenamesRef.current.delete(key)@@ -943,6 +1008,19 @@ export function useChatListController({return}}+ if (!requestStillCurrent() || isHostAccessBlocked(entry.agentRef)) return+ // Only the structured host denial proves revocation. A generic 403+ // may be a stale/missing write capability, so block the host as+ // uncertain and retain the optimistic rename for a later retry.+ onHostAuthorityUncertain(entry.agentRef)+ if (pendingRenamesRef.current.get(key) === entry) {+ entry.state = 'offline'+ entry.failureCount += 1+ if (entry.failureCount >= MAX_RENAME_SYNC_ATTEMPTS) {+ entry.retriesExhausted = true+ }+ }+ return}// A newer rename superseded this one: leave the key entirely to it — no// rollback, no re-mark (FIX 2).@@ -985,7 +1063,15 @@ export function useChatListController({entry.sending = false}},- [chatStore, applyLocalTitleOnly, host, isHostAccessBlocked, onHostAccessRevoked]+ [+ chatStore,+ applyLocalTitleOnly,+ getHostAuthorityEpoch,+ host,+ isHostAccessBlocked,+ onHostAccessRevoked,+ onHostAuthorityUncertain,+ ])/**@@ -1002,6 +1088,7 @@ export function useChatListController({// FIX 1: skip a key with a PATCH already in flight (attemptRenameRpc// guards this too, but skipping avoids spawning a no-op).if (entry.sending) continue+ if (isHostAccessBlocked(entry.agentRef)) continue// R1-M1: skip an entry whose retry budget is spent — its optimistic title// stays, but it no longer PATCHes on polls/online. Only 'offline' entries// can ever reach this state (in-flight never counts toward the budget).@@ -1020,7 +1107,7 @@ export function useChatListController({await attemptRenameRpc(entry)}},- [attemptRenameRpc]+ [attemptRenameRpc, isHostAccessBlocked])/**@@ -1088,15 +1175,57 @@ export function useChatListController({}}, [flushPendingRenames])+ const captureChatDeleteFence = useCallback(+ async (+ agentRef: string+ ): Promise<{ agentRef: string; fence: ChatDeleteFence; hostAuthorityEpoch: number }> => {+ if (!agentRef || isHostAccessBlocked(agentRef)) {+ throw new Error('Chat deletion is unavailable while host access is blocked')+ }+ const hostAuthorityEpoch = getHostAuthorityEpoch(agentRef)+ try {+ const fence = await chatStore.captureDeleteFence(authorityScope)+ if (+ !sameAuthorityScope(fence.authorityScope, authorityScope) ||+ hostAuthorityEpoch !== getHostAuthorityEpoch(agentRef) ||+ isHostAccessBlocked(agentRef)+ ) {+ throw new Error('Chat deletion authority changed before confirmation')+ }+ return { agentRef, fence, hostAuthorityEpoch }+ } catch (error) {+ host.current?.pushToast('Could not confirm chat access. Please try again.', 'error')+ throw error+ }+ },+ [authorityScope, chatStore.captureDeleteFence, getHostAuthorityEpoch, host, isHostAccessBlocked]+ )+const handleDeleteChatForAgent = useCallback(- async (agentRef: string, chatId: string) => {+ async (+ agentRef: string,+ chatId: string,+ deletion: { agentRef: string; fence: ChatDeleteFence; hostAuthorityEpoch: number }+ ) => {if (!agentRef) return+ if (+ deletion.agentRef !== agentRef ||+ !sameAuthorityScope(deletion.fence.authorityScope, authorityScope) ||+ deletion.hostAuthorityEpoch !== getHostAuthorityEpoch(agentRef) ||+ isHostAccessBlocked(agentRef)+ ) {+ host.current?.pushToast(+ 'Delete cancelled because chat access changed. Please try again.',+ 'error'+ )+ return+ }const requestGeneration = requestGenerationRef.currentconst authorityScopeGeneration = authorityScopeGenerationRef.current- const authorityScope = currentAuthorityScopeRef.current+ const authorityScopeAtDelete = currentAuthorityScopeRef.currentconst stillOwned = () =>authorityScopeGenerationRef.current === authorityScopeGeneration &&- currentAuthorityScopeRef.current === authorityScope+ currentAuthorityScopeRef.current === authorityScopeAtDelete// 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.@@ -1106,9 +1235,13 @@ 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' })- const bindingGeneration = await chatStore.getBindingGeneration()- if (!stillOwned()) return- await chatStore.deleteChat(agentRef, chatId, bindingGeneration)+ let result: Awaited<ReturnType<typeof chatStore.deleteChat>>+ try {+ result = await chatStore.deleteChat(agentRef, chatId, deletion.fence)+ } catch {+ host.current?.pushToast('Could not delete the chat. Please try again.', 'error')+ return+ }if (!stillOwned()) returnconst deleted = deletedChatIdsByAgentRef.current.get(agentRef) ?? new Set<string>()deleted.add(chatId)@@ -1116,6 +1249,12 @@ export function useChatListController({chatStore.clearCachedRemoteData()host.current?.clearComposerDraft(chatId)removeLatestChatSession(agentRef, chatId)+ if (result.cleanupPending) {+ host.current?.pushToast(+ 'Chat removed. Local transcript cleanup will retry when this team is active.',+ 'info'+ )+ }if (requestGenerationRef.current !== requestGeneration) return// Post-await guards read the LIVE committed values (selectedAgentRef /// getActiveChatId), intentionally — if the user switched agent during the@@ -1138,14 +1277,25 @@ export function useChatListController({}}},- [chatList, chatStore, removeLatestChatSession, handleCreateChat, host, isAuthenticated]+ [+ authorityScope,+ chatList,+ chatStore,+ getHostAuthorityEpoch,+ isHostAccessBlocked,+ removeLatestChatSession,+ handleCreateChat,+ host,+ isAuthenticated,+ ])const handleDeleteChat = useCallback(- async (chatId: string) => {- const agentRef = selectedAgentRef.current- if (!agentRef) return- await handleDeleteChatForAgent(agentRef, chatId)+ async (+ chatId: string,+ deletion: { agentRef: string; fence: ChatDeleteFence; hostAuthorityEpoch: number }+ ) => {+ await handleDeleteChatForAgent(deletion.agentRef, chatId, deletion)},[handleDeleteChatForAgent])@@ -1153,7 +1303,8 @@ export function useChatListController({// ─── Cross-agent latest-sessions loader (seeds badges via SERVER_SNAPSHOT) ───useEffect(() => {- if (!isAuthenticated || !loadMenuData || !agentNames.length) {+ const requestedAgentNames = agentNamesRef.current+ if (!isAuthenticated || !loadMenuData || !requestedAgentNames.length) {setLatestChatSessions([])setLatestChatSessionsLoading(false)return@@ -1161,20 +1312,35 @@ export function useChatListController({let cancelled = falseconst authorityScopeGeneration = authorityScopeGenerationRef.current+ const authorityScopeAtRequest = currentAuthorityScopeRef.current+ const hostAuthorityEpochByAgent = new Map(+ requestedAgentNames.map(agentRef => [agentRef, getHostAuthorityEpoch(agentRef)])+ )setLatestChatSessionsLoading(true);(async () => {try {const localGroups = await Promise.all(- agentNames.map(async agentRef => {+ requestedAgentNames.map(async agentRef => {try {const index = await chatStore.getIndex(agentRef)+ if (+ currentAuthorityScopeRef.current !== authorityScopeAtRequest ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpochByAgent.get(agentRef) ||+ isHostAccessBlocked(agentRef)+ ) {+ return {+ agentRef,+ entries: [] as LatestSidebarChatEntry[],+ deletedChatIds: [] as string[],+ }+ }return {agentRef,entries: index.chats.map(chat => ({...chat,agentRef,})),- deletedChatIds: index.deletedChatIds ?? [],+ deletedChatIds: deletedChatIdsForScope(index, authorityScope),}} catch {return {@@ -1185,8 +1351,15 @@ export function useChatListController({}}))- if (cancelled) return+ if (cancelled || currentAuthorityScopeRef.current !== authorityScopeAtRequest) returnfor (const group of localGroups) {+ if (+ getHostAuthorityEpoch(group.agentRef) !==+ hostAuthorityEpochByAgent.get(group.agentRef) ||+ isHostAccessBlocked(group.agentRef)+ ) {+ continue+ }const deleted = deletedChatIdsByAgentRef.current.get(group.agentRef) ?? new Set<string>()for (const chatId of group.deletedChatIds) deleted.add(chatId)deletedChatIdsByAgentRef.current.set(group.agentRef, deleted)@@ -1204,7 +1377,7 @@ export function useChatListController({setLatestChatSessionsLoading(false)const sessionGroups = await Promise.all(- agentNames.map(async agentRef => {+ requestedAgentNames.map(async agentRef => {// This feeds only the cross-agent sidebar preview. Do not follow// cursors here; the selected-agent session list exposes explicit// on-demand pagination through `loadMoreChatSessions`.@@ -1219,6 +1392,8 @@ export function useChatListController({isAuthorizationError(error) &&!cancelled &&authorityScopeGenerationRef.current === authorityScopeGeneration &&+ currentAuthorityScopeRef.current === authorityScopeAtRequest &&+ getHostAuthorityEpoch(agentRef) === hostAuthorityEpochByAgent.get(agentRef) &&!isHostAccessBlocked(agentRef)) {if (isConfirmedHostAccessRevoked(error)) onHostAccessRevoked(agentRef)@@ -1226,6 +1401,13 @@ export function useChatListController({}return { agentRef, sessions: [] as SessionsListResult['items'] }}+ if (+ currentAuthorityScopeRef.current !== authorityScopeAtRequest ||+ getHostAuthorityEpoch(agentRef) !== hostAuthorityEpochByAgent.get(agentRef) ||+ isHostAccessBlocked(agentRef)+ ) {+ return { agentRef, sessions: [] as SessionsListResult['items'] }+ }return {agentRef,sessions: serverResult.items.filter(@@ -1237,9 +1419,14 @@ export function useChatListController({}}))- if (cancelled) return+ if (cancelled || currentAuthorityScopeRef.current !== authorityScopeAtRequest) returnfor (const group of sessionGroups) {- if (isHostAccessBlocked(group.agentRef)) continue+ if (+ getHostAuthorityEpoch(group.agentRef) !==+ hostAuthorityEpochByAgent.get(group.agentRef) ||+ isHostAccessBlocked(group.agentRef)+ )+ continueseedSessionSnapshots(fsm,group.agentRef,@@ -1251,7 +1438,12 @@ export function useChatListController({setLatestChatSessions(previous => {const serverByKey = new Map<string, SessionsListResult['items'][number]>()for (const group of sessionGroups) {- if (isHostAccessBlocked(group.agentRef)) continue+ if (+ getHostAuthorityEpoch(group.agentRef) !==+ hostAuthorityEpochByAgent.get(group.agentRef) ||+ isHostAccessBlocked(group.agentRef)+ )+ continuefor (const session of group.sessions) {if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))continue@@ -1263,6 +1455,8 @@ export function useChatListController({const reconciled = previous.filter(item =>+ getHostAuthorityEpoch(item.agentRef) ===+ hostAuthorityEpochByAgent.get(item.agentRef) &&!isHostAccessBlocked(item.agentRef) &&!deletedChatIdsByAgentRef.current.get(item.agentRef)?.has(item.id))@@ -1281,7 +1475,12 @@ export function useChatListController({const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))const remoteOnly: LatestSidebarChatEntry[] = []for (const group of sessionGroups) {- if (isHostAccessBlocked(group.agentRef)) continue+ if (+ getHostAuthorityEpoch(group.agentRef) !==+ hostAuthorityEpochByAgent.get(group.agentRef) ||+ isHostAccessBlocked(group.agentRef)+ )+ continuefor (const session of group.sessions) {if (deletedChatIdsByAgentRef.current.get(group.agentRef)?.has(session.chatId))continue@@ -1335,13 +1534,14 @@ export function useChatListController({cancelled = true}}, [- agentNames,+ agentNamesKey,chatStore.getIndex,chatStore.listSessions,isAuthenticated,loadMenuData,scopeKey,fsm,+ getHostAuthorityEpoch,isHostAccessBlocked,onHostAccessRevoked,])@@ -1360,6 +1560,7 @@ export function useChatListController({handleRenameChat,handleRenameChatForAgent,applyLocalTitleOnly,+ captureChatDeleteFence,handleDeleteChat,handleDeleteChatForAgent,// Loader + list-loading control (parent agent-selection effect).diff --git a/desktop-app/ui/src/hooks/useAgentChatActionsValue.ts b/desktop-app/ui/src/hooks/useAgentChatActionsValue.tsindex 739d9c2dc..49a6826ea 100644--- a/desktop-app/ui/src/hooks/useAgentChatActionsValue.ts+++ b/desktop-app/ui/src/hooks/useAgentChatActionsValue.ts@@ -18,6 +18,7 @@ export function useAgentChatActionsValue(vm: AppVm): AgentChatActionsContextValuconst handleCreateChat = useStableCallback(vm.handleCreateChat)const handleRenameChat = useStableCallback(vm.handleRenameChat)const handleRenameChatForAgent = useStableCallback(vm.handleRenameChatForAgent)+ const captureChatDeleteFence = useStableCallback(vm.captureChatDeleteFence)const handleDeleteChat = useStableCallback(vm.handleDeleteChat)const handleDeleteChatForAgent = useStableCallback(vm.handleDeleteChatForAgent)const handleSelectChat = useStableCallback(vm.handleSelectChat)@@ -47,6 +48,7 @@ export function useAgentChatActionsValue(vm: AppVm): AgentChatActionsContextValuhandleCreateChat,handleRenameChat,handleRenameChatForAgent,+ captureChatDeleteFence,handleDeleteChat,handleDeleteChatForAgent,handleSelectChat,@@ -67,6 +69,7 @@ export function useAgentChatActionsValue(vm: AppVm): AgentChatActionsContextValuhandleCreateChat,handleRenameChat,handleRenameChatForAgent,+ captureChatDeleteFence,handleDeleteChat,handleDeleteChatForAgent,handleSelectChat,diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 8fb63c1a5..d0da62f43 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -306,10 +306,12 @@ export function useAppController() {(agentName: string) => agentsData.agentDisplayByName[agentName] ?? agentName,[agentsData.agentDisplayByName])- const authorityScope = `${auth.isAuthenticated}:${authenticatedPrincipalIdentity ?? ''}:${currentTeamId}`+ const authorityScope = `${auth.runtimeConfigState?.envKey ?? ''}:${auth.isAuthenticated}:${authenticatedPrincipalIdentity ?? ''}:${currentTeamId}`const authorityScopeRef = useRef(authorityScope)authorityScopeRef.current = authorityScopeconst hostAuthorityEpochRef = useRef(0)+ const hostAuthorityEpochByAgentRef = useRef(new Map<string, number>())+ const navigationIntentEpochRef = useRef(0)const blockedHostsRef = useRef(new Map<string, { kind: 'revoked' | 'uncertain'; epoch: number }>())@@ -320,9 +322,15 @@ export function useAppController() {(agentRef: string) => blockedHostsRef.current.has(agentRef),[])+ const getHostAuthorityEpoch = useCallback(+ (agentRef: string) =>+ hostAuthorityEpochByAgentRef.current.get(agentRef) ?? hostAuthorityEpochRef.current,+ []+ )useEffect(() => {blockedHostsRef.current.clear()hostAuthorityEpochRef.current += 1+ hostAuthorityEpochByAgentRef.current.clear()setHostAuthorityRevision(revision => revision + 1)}, [authorityScope])const blockHostAccess = useCallback(@@ -333,6 +341,7 @@ export function useAppController() {kind,epoch: ++hostAuthorityEpochRef.current,})+ hostAuthorityEpochByAgentRef.current.set(agentRef, hostAuthorityEpochRef.current)setHostAuthorityRevision(revision => revision + 1)if (selectedAgentRef.current === agentRef) nav.setSelectedAgent(null)void agentsData.refresh()@@ -363,6 +372,7 @@ export function useAppController() {)return falseblockedHostsRef.current.delete(agentRef)+ hostAuthorityEpochByAgentRef.current.set(agentRef, ++hostAuthorityEpochRef.current)setHostAuthorityRevision(revision => revision + 1)return true}, [])@@ -371,6 +381,7 @@ export function useAppController() {agentNames: agentsData.agentNames,currentUserId: auth.me?.id,currentTeamId,+ currentEnvironmentKey: auth.runtimeConfigState?.envKey ?? '',currentTeamName,isAuthenticated: auth.isAuthenticated,loadMenuData: postPaintDataReady,@@ -385,6 +396,7 @@ export function useAppController() {onHostAccessRevoked,onHostAuthorityUncertain,isHostAccessBlocked,+ getHostAuthorityEpoch,})// §4.7.4: the ONE central approval-decision function, bound to the chat@@ -948,13 +960,18 @@ export function useAppController() {const handleOpenAgentWorkspace = useCallback((agentName: string, route: AgentWorkspaceRoute = AGENT_WORKSPACE_ROUTES.connectors) => {if (!agentName) return+ const navigationIntentEpoch = ++navigationIntentEpochRef.currentif (!isHostAccessBlocked(agentName)) {openAgentWorkspace(agentName, route)return}const scope = authorityScopeRef.currentvoid verifyHostAccess(agentName).then(verified => {- if (verified && authorityScopeRef.current === scope) {+ if (+ verified &&+ authorityScopeRef.current === scope &&+ navigationIntentEpochRef.current === navigationIntentEpoch+ ) {openAgentWorkspace(agentName, route)}})@@ -1067,13 +1084,18 @@ export function useAppController() {const handleSelectChatAgent = useCallback((agentName: string, options: Parameters<typeof selectChatAgent>[1] = {}) => {if (!agentName) return+ const navigationIntentEpoch = ++navigationIntentEpochRef.currentif (!isHostAccessBlocked(agentName)) {selectChatAgent(agentName, options)return}const scope = authorityScopeRef.currentvoid verifyHostAccess(agentName).then(verified => {- if (verified && authorityScopeRef.current === scope) {+ if (+ verified &&+ authorityScopeRef.current === scope &&+ navigationIntentEpochRef.current === navigationIntentEpoch+ ) {selectChatAgent(agentName, options)}})@@ -1523,6 +1545,7 @@ export function useAppController() {handleCreateChat: chat.handleCreateChat,handleRenameChat: chat.handleRenameChat,handleRenameChatForAgent: chat.handleRenameChatForAgent,+ captureChatDeleteFence: chat.captureChatDeleteFence,handleDeleteChat: chat.handleDeleteChat,handleDeleteChatForAgent: chat.handleDeleteChatForAgent,handleSelectChat: chat.handleSelectChat,diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 6c9373b91..765f70de2 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -1,5 +1,7 @@import { useCallback } from 'react'import type {+ ChatAuthorityScope,+ ChatDeleteFence,ChatMessage,ReplaceChatMessagesOptions,SessionMessagesQuery,@@ -69,9 +71,14 @@ export function useChatStore() {[])const getBindingGeneration = useCallback(() => window.clerum.chat.getBindingGeneration(), [])+ const captureDeleteFence = useCallback(+ (expectedAuthorityScope: ChatAuthorityScope) =>+ window.clerum.chat.captureDeleteFence(expectedAuthorityScope),+ []+ )const deleteChat = useCallback(- (agentRef: string, chatId: string, bindingGeneration: number) =>- window.clerum.chat.delete(agentRef, chatId, bindingGeneration),+ (agentRef: string, chatId: string, fence: ChatDeleteFence) =>+ window.clerum.chat.delete(agentRef, chatId, fence),[])const loadMessages = useCallback(@@ -247,6 +254,7 @@ export function useChatStore() {createChat,renameChat,getBindingGeneration,+ captureDeleteFence,deleteChat,loadMessages,appendMessages,diff --git a/desktop-app/ui/src/hooks/useComposerDraft.ts b/desktop-app/ui/src/hooks/useComposerDraft.tsindex dffeeaea5..f5973edb7 100644--- a/desktop-app/ui/src/hooks/useComposerDraft.ts+++ b/desktop-app/ui/src/hooks/useComposerDraft.ts@@ -11,13 +11,17 @@ import {* not. Returns a `[draft, setDraft]` pair scoped to `chatId`.*/export function useComposerDraft(- chatId: string | null+ chatId: string | null,+ agentRef?: string): readonly [string, (value: string) => void] {const subscribe = useCallback(- (listener: () => void) => subscribeComposerDraft(chatId, listener),- [chatId]+ (listener: () => void) => subscribeComposerDraft(chatId, listener, agentRef),+ [agentRef, chatId]+ )+ const draft = useSyncExternalStore(subscribe, () => getComposerDraft(chatId, agentRef))+ const setDraft = useCallback(+ (value: string) => setComposerDraft(chatId, value, agentRef),+ [agentRef, chatId])- const draft = useSyncExternalStore(subscribe, () => getComposerDraft(chatId))- const setDraft = useCallback((value: string) => setComposerDraft(chatId, value), [chatId])return [draft, setDraft] as const}diff --git a/desktop-app/ui/src/lib/__tests__/composerDraftStore.test.ts b/desktop-app/ui/src/lib/__tests__/composerDraftStore.test.tsindex b2ac9e175..5e9b0dcdd 100644--- a/desktop-app/ui/src/lib/__tests__/composerDraftStore.test.ts+++ b/desktop-app/ui/src/lib/__tests__/composerDraftStore.test.ts@@ -95,6 +95,21 @@ describe('composerDraftStore', () => {expect(getComposerDraft('chat-1')).toBe('')})+ it('isolates no-chat drafts by agent while preserving the legacy unscoped bucket', () => {+ setComposerDraft(null, 'agent-a draft', 'agent-a')+ setComposerDraft(null, 'agent-b draft', 'agent-b')+ setComposerDraft(null, 'legacy draft')++ expect(getComposerDraft(null, 'agent-a')).toBe('agent-a draft')+ expect(getComposerDraft(null, 'agent-b')).toBe('agent-b draft')+ expect(getComposerDraft(null)).toBe('legacy draft')++ clearComposerDraftAfterSend(null, 'agent-a')+ expect(getComposerDraft(null, 'agent-a')).toBe('')+ expect(getComposerDraft(null, 'agent-b')).toBe('agent-b draft')+ expect(getComposerDraft(null)).toBe('legacy draft')+ })+it('resetComposerDraftStore wipes all drafts and listeners', () => {const listener = vi.fn()subscribeComposerDraft('chat-1', listener)diff --git a/desktop-app/ui/src/lib/composerDraftStore.ts b/desktop-app/ui/src/lib/composerDraftStore.tsindex e0bf96f40..a75b38c07 100644--- a/desktop-app/ui/src/lib/composerDraftStore.ts+++ b/desktop-app/ui/src/lib/composerDraftStore.ts@@ -8,13 +8,7 @@type Listener = () => void-/**- * Draft key used while no chat is active yet (before the first send creates one).- * This bucket is shared, not per-agent: it assumes at most one "no active chat"- * composer is mounted at a time (true today — the inline composer renders only when- * `!activeChatId`). A future split-view that showed two no-chat composers at once- * would make them share this draft.- */+/** Legacy no-chat key retained for callers that do not yet provide an agent. */const NO_CHAT_DRAFT_KEY = '__no_chat__'const drafts = new Map<string, string>()@@ -22,8 +16,10 @@ let revision = 0const revisions = new Map<string, number>()const listenersByKey = new Map<string, Set<Listener>>()-function keyFor(chatId: string | null): string {- return chatId ?? NO_CHAT_DRAFT_KEY+function keyFor(chatId: string | null, agentRef?: string): string {+ if (chatId) return chatId+ const agent = agentRef?.trim()+ return agent ? `${NO_CHAT_DRAFT_KEY}:${agent}` : NO_CHAT_DRAFT_KEY}function emit(key: string): void {@@ -32,16 +28,16 @@ function emit(key: string): void {for (const listener of listeners) listener()}-export function getComposerDraftRevision(chatId: string | null): number {- return revisions.get(keyFor(chatId)) ?? 0+export function getComposerDraftRevision(chatId: string | null, agentRef?: string): number {+ return revisions.get(keyFor(chatId, agentRef)) ?? 0}-export function getComposerDraft(chatId: string | null): string {- return drafts.get(keyFor(chatId)) ?? ''+export function getComposerDraft(chatId: string | null, agentRef?: string): string {+ return drafts.get(keyFor(chatId, agentRef)) ?? ''}-export function setComposerDraft(chatId: string | null, value: string): void {- const key = keyFor(chatId)+export function setComposerDraft(chatId: string | null, value: string, agentRef?: string): void {+ const key = keyFor(chatId, agentRef)if ((drafts.get(key) ?? '') === value) returnrevisions.set(key, ++revision)if (value) drafts.set(key, value)@@ -49,13 +45,13 @@ export function setComposerDraft(chatId: string | null, value: string): void {emit(key)}-export function clearComposerDraft(chatId: string | null): void {- setComposerDraft(chatId, '')+export function clearComposerDraft(chatId: string | null, agentRef?: string): void {+ setComposerDraft(chatId, '', agentRef)}/** Clears the draft for a chat and the "no chat yet" bucket (used on send). */-export function clearComposerDraftAfterSend(chatId: string | null): void {- clearComposerDraft(null)+export function clearComposerDraftAfterSend(chatId: string | null, agentRef?: string): void {+ clearComposerDraft(null, agentRef)if (chatId) clearComposerDraft(chatId)}@@ -68,8 +64,12 @@ export function clearAllComposerDrafts(): void {}}-export function subscribeComposerDraft(chatId: string | null, listener: Listener): () => void {- const key = keyFor(chatId)+export function subscribeComposerDraft(+ chatId: string | null,+ listener: Listener,+ agentRef?: string+): () => void {+ const key = keyFor(chatId, agentRef)let listeners = listenersByKey.get(key)if (!listeners) {listeners = new Set()diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 6c82a6548..f0b4aa14b 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.353",+ "version": "0.1.354","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.353",+ "version": "0.1.354","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex d69981a81..6b87da092 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.353",+ "version": "0.1.354","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.rbacPvcReadFirst.test.ts b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.tsindex 75a2c3d9a..379060db4 100644--- a/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts+++ b/host-context-controller/src/hostReconciler.rbacPvcReadFirst.test.ts@@ -308,7 +308,7 @@ describe('Host read-first RBAC and PVC contracts', () => {},spec: { volumeName: 'bound-volume' },})- await (f.reconciler as any).ensurePvc(host)+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBe(true)expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()@@ -317,7 +317,7 @@ describe('Host read-first RBAC and PVC contracts', () => {it('updates an unbound Host PVC once with its observed resourceVersion', async () => {const f = fixture()- await (f.reconciler as any).ensurePvc(host)+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBe(true)expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()expect(f.core.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()@@ -327,6 +327,28 @@ describe('Host read-first RBAC and PVC contracts', () => {expect(await count('PersistentVolumeClaim', 'skipped')).toBe(1)})+ it('counts a Host PVC create race as successful after fresh read convergence', async () => {+ const f = fixture()+ f.core.readNamespacedPersistentVolumeClaim+ .mockRejectedValueOnce({ code: 404 })+ .mockResolvedValueOnce({+ metadata: {+ name: 'rbac-host-workspace',+ namespace: host.namespace,+ uid: 'pvc-uid',+ resourceVersion: '17',+ },+ })+ f.core.createNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code: 409 })++ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBe(true)++ expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledTimes(2)+ expect(f.core.createNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()+ expect(f.core.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()+ expect(await count('PersistentVolumeClaim', 'conflict')).toBe(1)+ })+it('propagates a Host PVC initial GET failure outside retained write catches', async () => {const f = fixture()const failure = { code: 403 }@@ -342,7 +364,7 @@ describe('Host read-first RBAC and PVC contracts', () => {const f = fixture()f.core.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code: 404 })f.core.createNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code: 503 })- await expect((f.reconciler as any).ensurePvc(host)).resolves.toBeUndefined()+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBe(false)expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.createNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.replaceNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()@@ -353,7 +375,7 @@ describe('Host read-first RBAC and PVC contracts', () => {it.each([409, 503])('retains Host PVC PUT%d without retrying or recording a skip', async code => {const f = fixture()f.core.replaceNamespacedPersistentVolumeClaim.mockRejectedValueOnce({ code })- await expect((f.reconciler as any).ensurePvc(host)).resolves.toBeUndefined()+ await expect((f.reconciler as any).ensurePvc(host)).resolves.toBe(false)expect(f.core.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.replaceNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()expect(f.core.createNamespacedPersistentVolumeClaim).not.toHaveBeenCalled()diff --git a/host-context-controller/src/hostReconciler.readFirst.test.ts b/host-context-controller/src/hostReconciler.readFirst.test.tsindex 01095d665..0601f9730 100644--- a/host-context-controller/src/hostReconciler.readFirst.test.ts+++ b/host-context-controller/src/hostReconciler.readFirst.test.ts@@ -214,7 +214,7 @@ describe('Host read-first Service and Deployment contracts', () => {const { core, reconciler } = fixture()core.readNamespacedService.mockRejectedValueOnce({ code: 404 })core.createNamespacedService.mockRejectedValueOnce({ code: 503 })- await expect((reconciler as any).ensureService(host)).resolves.toBeUndefined()+ await expect((reconciler as any).ensureService(host)).resolves.toBe(false)expect(core.readNamespacedService).toHaveBeenCalledOnce()expect(core.createNamespacedService).toHaveBeenCalledOnce()expect(core.replaceNamespacedService).not.toHaveBeenCalled()@@ -225,7 +225,7 @@ describe('Host read-first Service and Deployment contracts', () => {it('retains a Host Service convergence failure without recording a successful skip', async () => {const { core, reconciler } = fixture()core.replaceNamespacedService.mockRejectedValueOnce({ code: 503 })- await expect((reconciler as any).ensureService(host)).resolves.toBeUndefined()+ await expect((reconciler as any).ensureService(host)).resolves.toBe(false)expect(core.readNamespacedService).toHaveBeenCalledOnce()expect(core.createNamespacedService).not.toHaveBeenCalled()expect(core.replaceNamespacedService).toHaveBeenCalledOnce()@@ -238,7 +238,7 @@ describe('Host read-first Service and Deployment contracts', () => {const desired = (reconciler as any).buildService(host) as k8s.V1Servicecore.readNamespacedService.mockResolvedValue(asApiserverService(desired))core.createNamespacedService.mockRejectedValue({ code: 409 })- await (reconciler as any).ensureService(host)+ await expect((reconciler as any).ensureService(host)).resolves.toBe(true)expect(core.readNamespacedService).toHaveBeenCalledOnce()expect(core.createNamespacedService).not.toHaveBeenCalled()expect(core.replaceNamespacedService).not.toHaveBeenCalled()@@ -325,7 +325,7 @@ describe('Host read-first Service and Deployment contracts', () => {const { core, reconciler } = fixture()core.readNamespacedService.mockRejectedValueOnce({ code: 404 })core.createNamespacedService.mockRejectedValueOnce({ code: 409 })- await (reconciler as any).ensureService(host)+ await expect((reconciler as any).ensureService(host)).resolves.toBe(true)expect(core.readNamespacedService).toHaveBeenCalledTimes(2)expect(core.createNamespacedService).toHaveBeenCalledOnce()expect(core.replaceNamespacedService).toHaveBeenCalledOnce()diff --git a/host-context-controller/src/hostReconciler.test.ts b/host-context-controller/src/hostReconciler.test.tsindex 1e7ca0f55..f7a2e31c9 100644--- a/host-context-controller/src/hostReconciler.test.ts+++ b/host-context-controller/src/hostReconciler.test.ts@@ -1056,12 +1056,12 @@ describe('HostReconciler Host inventory mutation authority', () => {function stubPreDeploymentReconcileEffects(reconciler: HostReconciler): void {vi.spyOn(reconciler as any, 'validateHostSecret').mockResolvedValue({ ok: true })+ vi.spyOn(reconciler as any, 'ensurePvc').mockResolvedValue(true)+ vi.spyOn(reconciler as any, 'ensureService').mockResolvedValue(true)for (const method of ['ensureHostServiceAccount','ensureHostRole','ensureHostRoleBinding',- 'ensurePvc',- 'ensureService','ensureMcpHostIngressNetworkPolicy','ensureMcpHostGfsEgressNetworkPolicy','ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy',@@ -1071,7 +1071,7 @@ describe('HostReconciler Host inventory mutation authority', () => {'ensureChannelReaderEgressNetworkPolicy','ensureWorkflowApprovalReaderHostEgressNetworkPolicy',]) {- vi.spyOn(reconciler as any, method).mockResolvedValue(undefined)+ vi.spyOn(reconciler as any, method).mockResolvedValue('up_to_date')}}diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 9ab121fe1..7a28f3350 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -78,6 +78,7 @@ import {HostWorkflowControlSpec,} from './types'import {+ type ResourceApplyResult,applyNetworkPolicy,canonicalStringify,canonicalizeValue,@@ -382,6 +383,7 @@ const GFS_TOKEN_REFRESH_BEFORE_ANNOTATION = 'clerum.io/gfs-token-refresh-before'const GFS_TOKEN_EXPECTED_SUBJECT_ANNOTATION = 'clerum.io/gfs-token-expected-subject'const GFS_TOKEN_CAPABILITY_SET_HASH_ANNOTATION = 'clerum.io/gfs-token-capability-set-hash'const GFS_TOKEN_HOST_UID_ANNOTATION = 'clerum.io/gfs-token-host-uid'+const HOST_UID_ANNOTATION = 'clerum.io/host-uid'const GFS_TOKEN_HOST_GENERATION_ANNOTATION = 'clerum.io/gfs-token-host-generation'const RUNTIME_TOKEN_HOST_BINDING_HASH_ANNOTATION = 'clerum.io/runtime-token-host-binding-hash'const RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION = 'clerum.io/runtime-token-scope-hash'@@ -3182,6 +3184,7 @@ export class HostReconciler {name: host.name,namespace: host.namespace,labels,+ ...(host.uid ? { annotations: { [HOST_UID_ANNOTATION]: host.uid } } : {}),},spec: {// A suspended stateless Host scales to 0 on EVERY reconcile path@@ -3502,16 +3505,17 @@ export class HostReconciler {this.readinessTimers.set(name, timer)}- private async ensurePvc(host: HostCRD, revalidate?: () => void): Promise<void> {+ private async ensurePvc(host: HostCRD, revalidate?: () => void): Promise<boolean> {const pvc = this.buildPvc(host)const name = this.pvcName(host)+ let createFailed = falseconst mutationAllowed = () => {revalidate?.()return true}// Initial GET errors must propagate; retain only the established// non-throwing POST and convergence failures of this PVC writer.- await ensureResource({+ const result = await ensureResource({mutationAllowed,read: () =>observeExistenceRead('PersistentVolumeClaim', () =>@@ -3527,6 +3531,7 @@ export class HostReconciler {)} catch (error) {if (error != null && getErrorCode(error) === 409) throw error+ createFailed = truelog.error('Failed to create Host PVC', { host: host.name, err: error })}},@@ -3549,17 +3554,19 @@ export class HostReconciler {},onSkipped: () => createsTotal.inc({ kind: 'PersistentVolumeClaim', outcome: 'skipped' }),})+ return !createFailed && this.resourceApplySucceeded(result)}- private async ensureService(host: HostCRD, revalidate?: () => void): Promise<void> {+ private async ensureService(host: HostCRD, revalidate?: () => void): Promise<boolean> {const service = this.buildService(host)+ let createFailed = falseconst mutationAllowed = () => {revalidate?.()return true}// Initial read errors propagate. Only the existing POST/convergence paths// retain their historical non-throwing failures.- await ensureResource({+ const result = await ensureResource({mutationAllowed,read: () =>observeExistenceRead('Service', () =>@@ -3572,6 +3579,7 @@ export class HostReconciler {)} catch (error) {if (error != null && getErrorCode(error) === 409) throw error+ createFailed = truelog.error('Failed to create Host Service', { host: host.name, err: error })}},@@ -3600,6 +3608,11 @@ export class HostReconciler {}},})+ return !createFailed && this.resourceApplySucceeded(result)+ }++ private resourceApplySucceeded(result: ResourceApplyResult): boolean {+ return result === 'created' || result === 'replaced' || result === 'up_to_date'}private async ensureDeployment(@@ -3626,13 +3639,23 @@ export class HostReconciler {existing.metadata?.namespace !== host.namespace ||!existing.metadata?.uid ||!existing.metadata?.resourceVersion ||+ existing.metadata.deletionTimestamp ||!existing.spec?.template?.spec) {throw new Error(`Cannot preserve an unverified Deployment for Host "${host.name}"`)}+ const annotatedHostUid = existing.metadata.annotations?.[HOST_UID_ANNOTATION]+ const hostUidVerified = !!host.uid && annotatedHostUid === host.uid+ if (!hostUidVerified) {+ 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 } }+ // re-read this object before retrying; replicas is the only field that+ // may change. An unverified legacy object must never be scaled.+ return {+ ...existing,+ spec: { ...existing.spec, replicas: 1 },+ }}return this.buildDeployment(host,@@ -3646,7 +3669,7 @@ export class HostReconciler {revalidate?.()return true}- await ensureResource({+ const result = await ensureResource({mutationAllowed,read: async () => {observedDeployment = await observeExistenceRead('Deployment', () =>@@ -3689,7 +3712,7 @@ export class HostReconciler {}),}),})- return applied+ return applied && this.resourceApplySucceeded(result)}private async deleteRuntimeResources(name: string, namespace: string): Promise<void> {@@ -3856,9 +3879,11 @@ export class HostReconciler {}}- private async ensureDesktopNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureDesktopNetworkPolicy(+ host: HostCRD+ ): Promise<'not-required' | ResourceApplyResult> {const isDesktop = !!(host.spec.desktop?.browser || host.spec.desktop?.x11)- if (!isDesktop) return+ if (!isDesktop) return 'not-required'const policyName = `allow-rpc-proxy-desktop-${host.name}`const policy: k8s.V1NetworkPolicy = {@@ -3892,17 +3917,13 @@ export class HostReconciler {},}- try {- await applyNetworkPolicy(- this.networkingApi,- policyName,- host.namespace,- policy,- '[HostReconciler]'- )- } catch (error) {- log.error('Failed to ensure desktop NetworkPolicy', { policy: policyName, err: error })- }+ return applyNetworkPolicy(+ this.networkingApi,+ policyName,+ host.namespace,+ policy,+ '[HostReconciler]'+ )}/**@@ -3911,7 +3932,7 @@ export class HostReconciler {* egress. Desktop hosts also expose the desktop service port through the* same host-scoped egress boundary.*/- private async ensureRpcProxyHostEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureRpcProxyHostEgressNetworkPolicy(host: HostCRD): Promise<ResourceApplyResult> {const isDesktop = !!(host.spec.desktop?.browser || host.spec.desktop?.x11)const policyName = `rpc-proxy-${host.name}-egress-mcp-host`const ports: k8s.V1NetworkPolicyPort[] = [{ port: config.hostPort, protocol: 'TCP' }]@@ -3954,7 +3975,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,config.rpcProxyNamespace,@@ -3968,7 +3989,9 @@ export class HostReconciler {* its bound mcp-host on :8080. Provider approvals and verification continue* through mcp-host; channel-reader must not reach control-api gateways.*/- private async ensureChannelReaderEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureChannelReaderEgressNetworkPolicy(+ host: HostCRD+ ): Promise<ResourceApplyResult> {const policyName = `channel-reader-${host.name}-egress`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4013,7 +4036,7 @@ export class HostReconciler {// channel-reader security boundary. Route-level JWT auth is the other// half, so an NP apply error still MUST surface in HostRuntimeStatus// rather than be silently swallowed.- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,config.channelsNamespace,@@ -4027,7 +4050,9 @@ export class HostReconciler {* are verified by control-api against a CommunicationChannel, then forwarded* to that channel's bound Host for the authoritative provider-decision path.*/- private async ensureWorkflowApprovalReaderHostEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureWorkflowApprovalReaderHostEgressNetworkPolicy(+ host: HostCRD+ ): Promise<ResourceApplyResult> {const policyName = `workflow-approval-reader-${host.name}-egress-mcp-host`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4067,7 +4092,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,config.channelsNamespace,@@ -4081,7 +4106,7 @@ export class HostReconciler {* pod ingress on :8080 to ONLY accept connections from channel-reader-<host>* pods (label match).*/- private async ensureMcpHostIngressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureMcpHostIngressNetworkPolicy(host: HostCRD): Promise<ResourceApplyResult> {const policyName = `mcp-host-${host.name}-ingress-channel-reader`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4129,7 +4154,7 @@ export class HostReconciler {// channel-reader↔mcp-host security boundary. Route-level JWT auth is// the other half, so an apply error MUST surface in HostRuntimeStatus// rather than be silently swallowed.- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4145,7 +4170,7 @@ export class HostReconciler {*/private async ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy(host: HostCRD- ): Promise<void> {+ ): Promise<ResourceApplyResult> {const policyName = `mcp-host-${host.name}-ingress-workflow-approval-reader`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4187,7 +4212,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4201,7 +4226,9 @@ export class HostReconciler {* namespace-wide mcp-host ingress rule for rpc-proxy. Desktop hosts include* the desktop port, but only for the selected Host pod.*/- private async ensureRpcProxyMcpHostIngressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureRpcProxyMcpHostIngressNetworkPolicy(+ host: HostCRD+ ): Promise<ResourceApplyResult> {const isDesktop = !!(host.spec.desktop?.browser || host.spec.desktop?.x11)const policyName = `mcp-host-${host.name}-ingress-rpc-proxy`const ports: k8s.V1NetworkPolicyPort[] = [{ port: config.hostPort, protocol: 'TCP' }]@@ -4244,7 +4271,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4258,7 +4285,7 @@ export class HostReconciler {* NetworkPolicy only opens the required transport lane from the selected Host* pod to the governed GFS controller service.*/- private async ensureMcpHostGfsEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureMcpHostGfsEgressNetworkPolicy(host: HostCRD): Promise<ResourceApplyResult> {const target = { namespace: config.gfsNamespace, port: config.gfscPort }const policyName = `mcp-host-${host.name}-egress-gfs`const policy: k8s.V1NetworkPolicy = {@@ -4299,7 +4326,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4312,7 +4339,9 @@ export class HostReconciler {* Per-Host mcp-host egress to the static Codex LLM proxy runtime listener.* Derived from the same Codex projection that mints `llm:codex:execute`.*/- private async ensureMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureMcpHostCodexProxyEgressNetworkPolicy(+ host: HostCRD+ ): Promise<ResourceApplyResult> {const policyName = `mcp-host-${host.name}-egress-codex-proxy`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4352,7 +4381,7 @@ export class HostReconciler {},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4381,17 +4410,21 @@ export class HostReconciler {)}- private async reconcileMcpHostCodexProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async reconcileMcpHostCodexProxyEgressNetworkPolicy(+ host: HostCRD+ ): Promise<'not-required' | ResourceApplyResult> {const projection = this.projectCodexForHost(host)- if (projection.eligibility === 'uncertain') return+ if (projection.eligibility === 'uncertain') return 'not-required'if (projection.requiresCodexProxyEgress) {- await this.ensureMcpHostCodexProxyEgressNetworkPolicy(host)- return+ return this.ensureMcpHostCodexProxyEgressNetworkPolicy(host)}await this.deleteMcpHostCodexProxyEgressNetworkPolicy(host)+ return 'not-required'}- private async ensureMcpHostGrokProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async ensureMcpHostGrokProxyEgressNetworkPolicy(+ host: HostCRD+ ): Promise<ResourceApplyResult> {const policyName = `mcp-host-${host.name}-egress-grok-proxy`const policy: k8s.V1NetworkPolicy = {apiVersion: 'networking.k8s.io/v1',@@ -4430,7 +4463,7 @@ export class HostReconciler {],},}- await applyNetworkPolicy(+ return applyNetworkPolicy(this.networkingApi,policyName,host.namespace,@@ -4459,14 +4492,16 @@ export class HostReconciler {)}- private async reconcileMcpHostGrokProxyEgressNetworkPolicy(host: HostCRD): Promise<void> {+ private async reconcileMcpHostGrokProxyEgressNetworkPolicy(+ host: HostCRD+ ): Promise<'not-required' | ResourceApplyResult> {const projection = this.projectGrokForHost(host)- if (projection.eligibility === 'uncertain') return+ if (projection.eligibility === 'uncertain') return 'not-required'if (projection.requiresGrokProxyEgress) {- await this.ensureMcpHostGrokProxyEgressNetworkPolicy(host)- return+ return this.ensureMcpHostGrokProxyEgressNetworkPolicy(host)}await this.deleteMcpHostGrokProxyEgressNetworkPolicy(host)+ return 'not-required'}/**@@ -4720,6 +4755,30 @@ export class HostReconciler {})}+ let pvcApplied = true+ let serviceApplied = true+ const resourceErrors: unknown[] = []+ const resourceFailureMessages = new Map<'Host PVC' | 'Host Service', string>()+ const npFailures: string[] = []+ const ensureIndependentResource = async (+ kind: 'Host PVC' | 'Host Service',+ reconcile: () => Promise<boolean>+ ): Promise<boolean> => {+ try {+ return await reconcile()+ } catch (error) {+ if (isBenignSupersessionError(error)) throw error+ resourceErrors.push(error)+ const message = error instanceof Error ? error.message : String(error)+ resourceFailureMessages.set(kind, `${kind}: ${message}`)+ log.error('Failed to reconcile Host resource', {+ host: host.name,+ resource: kind,+ err: error,+ })+ return false+ }+ }const holdAppliedRuntime = async (): Promise<void> => {const applied = await this.ensureDeployment(host,@@ -4731,25 +4790,40 @@ export class HostReconciler {)revalidateHostMutationBoundary()this.lifecycle.markHostNotSuspended(host.name)- const ready = applied && (await this.checkDeploymentReady(host.name, host.namespace))+ const deploymentReady =+ applied && (await this.checkDeploymentReady(host.name, host.namespace))revalidateHostMutationBoundary()+ const ready = deploymentReady && pvcApplied && serviceApplied && npFailures.length === 0+ const failures = [+ ...(!pvcApplied+ ? [resourceFailureMessages.get('Host PVC') ?? 'Host PVC did not converge']+ : []),+ ...(!serviceApplied+ ? [resourceFailureMessages.get('Host Service') ?? 'Host Service did not converge']+ : []),+ ...npFailures,+ ]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',+ message: !applied+ ? 'Waiting for CommunicationChannel inventory before creating runtime'+ : failures.length > 0+ ? `degraded — Host runtime boundary incomplete while preserving applied runtime (${failures.join('; ')})`+ : deploymentReady+ ? 'CommunicationChannel inventory unavailable; preserving applied runtime with one replica'+ : 'CommunicationChannel inventory unavailable; preserved applied runtime is not Ready',})}- if (lifecycle.effective.suspensionBlocked) {- await holdAppliedRuntime()- return- }revalidateHostMutationBoundary()- await this.ensurePvc(host, revalidateHostMutationBoundary)+ pvcApplied = await ensureIndependentResource('Host PVC', () =>+ this.ensurePvc(host, revalidateHostMutationBoundary)+ )revalidateHostMutationBoundary()- await this.ensureService(host, revalidateHostMutationBoundary)+ serviceApplied = await ensureIndependentResource('Host Service', () =>+ this.ensureService(host, revalidateHostMutationBoundary)+ )// NetworkPolicies before Deployments. Calico/Cilium evaluate egress and// ingress against the policies that exist when the connection is opened,@@ -4762,45 +4836,54 @@ export class HostReconciler {// Route-level edge context and ownership checks remain the application// boundary. An NP apply failure means the network boundary is missing, so// surface it via HostRuntimeStatus instead of swallowing it.- const npFailures: string[] = []- try {- revalidateHostMutationBoundary()- await this.ensureMcpHostIngressNetworkPolicy(host)- revalidateHostMutationBoundary()- await this.ensureMcpHostGfsEgressNetworkPolicy(host)- revalidateHostMutationBoundary()- await this.reconcileMcpHostCodexProxyEgressNetworkPolicy(host)- revalidateHostMutationBoundary()- await this.reconcileMcpHostGrokProxyEgressNetworkPolicy(host)- // The mcp-host→llm-hooks egress policy is now owned by LlmHookReconciler- // (per-host, scoped to referenced hook pods — N1/N7); host-delete cleanup- // of `mcp-host-<host>-egress-llm-hooks` stays in deleteHostNetworkPolicies.- revalidateHostMutationBoundary()- await this.ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy(host)- } catch (err) {- log.error('Failed to ensure mcp-host NP', { host: host.name, err })- npFailures.push(`mcp-host NP: ${(err as Error).message}`)- }- try {- revalidateHostMutationBoundary()- await this.ensureRpcProxyMcpHostIngressNetworkPolicy(host)- revalidateHostMutationBoundary()- await this.ensureRpcProxyHostEgressNetworkPolicy(host)- } catch (err) {- log.error('Failed to ensure rpc-proxy host NP', { host: host.name, err })- npFailures.push(`rpc-proxy NP: ${(err as Error).message}`)+ const ensureNetworkPolicy = async (+ name: string,+ reconcile: () => Promise<'not-required' | ResourceApplyResult>+ ): Promise<void> => {+ try {+ revalidateHostMutationBoundary()+ const result = await reconcile()+ revalidateHostMutationBoundary()+ if (result !== 'not-required' && !this.resourceApplySucceeded(result)) {+ throw new Error(`apply did not converge (${result})`)+ }+ } catch (err) {+ log.error('Failed to ensure Host NetworkPolicy', { host: host.name, policy: name, err })+ npFailures.push(`${name}: ${err instanceof Error ? err.message : String(err)}`)+ }}+ await ensureNetworkPolicy('mcp-host ingress', () =>+ this.ensureMcpHostIngressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('mcp-host GFS egress', () =>+ this.ensureMcpHostGfsEgressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('mcp-host Codex proxy egress', () =>+ this.reconcileMcpHostCodexProxyEgressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('mcp-host Grok proxy egress', () =>+ this.reconcileMcpHostGrokProxyEgressNetworkPolicy(host)+ )+ // The mcp-host→llm-hooks egress policy is now owned by LlmHookReconciler+ // (per-host, scoped to referenced hook pods — N1/N7); host-delete cleanup+ // of `mcp-host-<host>-egress-llm-hooks` stays in deleteHostNetworkPolicies.+ await ensureNetworkPolicy('workflow approval reader ingress', () =>+ this.ensureWorkflowApprovalReaderMcpHostIngressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('rpc-proxy mcp-host ingress', () =>+ this.ensureRpcProxyMcpHostIngressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('rpc-proxy Host egress', () =>+ this.ensureRpcProxyHostEgressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('desktop ingress', () => this.ensureDesktopNetworkPolicy(host))+ await ensureNetworkPolicy('channel-reader egress', () =>+ this.ensureChannelReaderEgressNetworkPolicy(host)+ )+ await ensureNetworkPolicy('workflow approval reader egress', () =>+ this.ensureWorkflowApprovalReaderHostEgressNetworkPolicy(host)+ )revalidateHostMutationBoundary()- await this.ensureDesktopNetworkPolicy(host)- try {- revalidateHostMutationBoundary()- await this.ensureChannelReaderEgressNetworkPolicy(host)- revalidateHostMutationBoundary()- await this.ensureWorkflowApprovalReaderHostEgressNetworkPolicy(host)- } catch (err) {- log.error('Failed to ensure channels egress NP', { host: host.name, err })- npFailures.push(`egress NP: ${(err as Error).message}`)- }// Resolve policy once before bootstrap so token scopes and wake/suspend// decisions use the latest channel state already observed.@@ -4820,6 +4903,14 @@ export class HostReconciler {return}+ if (resourceErrors.length === 1) throw resourceErrors[0]+ if (resourceErrors.length > 1) {+ throw new AggregateError(+ resourceErrors,+ `Failed to reconcile Host resources for "${host.name}"`+ )+ }+// 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.diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.tsindex 6c894cebd..062806fa9 100644--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@ -380,7 +380,10 @@ describe('HostReconciler ensureDeployment — idempotent replacement', () => {uid: 'deployment-uid',generation: 7,creationTimestamp: new Date('2026-07-10T00:00:00Z'),- annotations: { 'deployment.kubernetes.io/revision': '7' },+ annotations: {+ ...deployment.metadata?.annotations,+ 'deployment.kubernetes.io/revision': '7',+ },}deployment.status = { readyReplicas: 1, availableReplicas: 1 }deployment.spec = {@@ -876,25 +879,114 @@ describe('HostReconciler stateless lifecycle — rejection matrix', () => {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.each([+ 'foreign owner',+ 'missing UID',+ 'missing resourceVersion',+ 'prior Host UID',+ 'unannotated legacy',+ ])('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+ if (invalid === 'prior Host UID') {+ applied.metadata.annotations = {+ ...applied.metadata.annotations,+ 'clerum.io/host-uid': 'prior-host-uid',+ }}- )+ if (invalid === 'unannotated legacy')+ delete applied.metadata.annotations?.['clerum.io/host-uid']+ appsApi.readNamespacedDeployment.mockResolvedValue(applied)+ await expect(reconciler.reconcile(host)).rejects.toThrow('unverified Deployment')+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()+ expect(appsApi.patchNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('never scales an unannotated legacy Deployment, even when created after the current Host', async () => {+ const host = makeStatelessHost({ status: suspendedStatus() })+ host.metadata = {+ ...host.metadata,+ creationTimestamp: new Date('2026-09-20T10:00:00Z'),+ }+ const { reconciler, appsApi } = createReconciler()+ const legacy = reconciler.buildDeployment(host)+ delete legacy.metadata?.annotations?.['clerum.io/host-uid']+ legacy.metadata = {+ ...legacy.metadata,+ uid: 'deployment-uid',+ resourceVersion: '73',+ creationTimestamp: new Date('2026-09-20T10:01:00Z'),+ }+ appsApi.readNamespacedDeployment.mockResolvedValue(legacy)++ await expect(+ (reconciler as any).ensureDeployment(host, [], undefined, {+ stateless: true,+ state: 'active',+ suspensionBlocked: true,+ })+ ).rejects.toThrow('unverified Deployment')+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()+ expect(appsApi.createNamespacedDeployment).not.toHaveBeenCalled()+ })++ it('converges the held runtime boundary and reports failures from PVC and policy reconciliation', async () => {+ const host = makeStatelessHost({ status: suspendedStatus() })+ const { reconciler, appsApi, coreApi, customApi } = createReconciler({+ isCommunicationChannelCacheSynced: () => false,+ })+ customApi.getNamespacedCustomObject.mockImplementation(async () => hostApiObject(host))+ const applied = reconciler.buildDeployment(host)+ applied.status = { readyReplicas: 1 }+ persistHostDeployment(appsApi, host, applied)++ coreApi.readNamespacedPersistentVolumeClaim.mockRejectedValueOnce(new Error('PVC read failed'))+ coreApi.readNamespacedService.mockRejectedValueOnce(new Error('Service read failed'))+ const ingress = vi+ .spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy')+ .mockRejectedValueOnce(new Error('ingress policy failed'))+ const gfsEgress = vi+ .spyOn(reconciler as any, 'ensureMcpHostGfsEgressNetworkPolicy')+ .mockResolvedValue(undefined)+ const codexEgress = vi+ .spyOn(reconciler as any, 'reconcileMcpHostCodexProxyEgressNetworkPolicy')+ .mockResolvedValue(undefined)++ await reconciler.reconcile(host)++ expect(coreApi.readNamespacedPersistentVolumeClaim).toHaveBeenCalledOnce()+ expect(coreApi.readNamespacedService).toHaveBeenCalledOnce()+ expect(ingress).toHaveBeenCalledOnce()+ expect(gfsEgress).toHaveBeenCalledOnce()+ expect(codexEgress).toHaveBeenCalledOnce()+ expect(reconciler.getStatus(host.name)).toMatchObject({+ deployed: true,+ ready: false,+ message: expect.stringContaining('Host runtime boundary incomplete'),+ })+ })++ it('does not report a Deployment applied when create conflict is followed by a missing read', async () => {+ const host = makeStatelessHost()+ const { reconciler, appsApi } = createReconciler()+ appsApi.readNamespacedDeployment+ .mockRejectedValueOnce({ code: 404 })+ .mockRejectedValueOnce({ code: 404 })+ appsApi.createNamespacedDeployment.mockRejectedValueOnce({ code: 409 })++ await expect((reconciler as any).ensureDeployment(host, [], 'runtime-revision')).resolves.toBe(+ false+ )+ expect(appsApi.replaceNamespacedDeployment).not.toHaveBeenCalled()+ })it('holds the existing template when channel authority is lost during runtime provisioning', async () => {let synced = truediff --git a/host-context-controller/test/hostReconciler.networkpolicy.test.ts b/host-context-controller/test/hostReconciler.networkpolicy.test.tsindex 1754a9d17..87f342f28 100644--- a/host-context-controller/test/hostReconciler.networkpolicy.test.ts+++ b/host-context-controller/test/hostReconciler.networkpolicy.test.ts@@ -215,10 +215,10 @@ describe('HostReconciler.reconcile — NP wiring', () => {revision: 'runtime-revision',scopeHash: (HostReconciler as any).runtimeTokenScopeHash(HOST, false),})- vi.spyOn(reconciler as any, 'ensurePvc').mockResolvedValue(undefined)- vi.spyOn(reconciler as any, 'ensureService').mockResolvedValue(undefined)+ vi.spyOn(reconciler as any, 'ensurePvc').mockResolvedValue(true)+ vi.spyOn(reconciler as any, 'ensureService').mockResolvedValue(true)vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(true)- vi.spyOn(reconciler as any, 'ensureDesktopNetworkPolicy').mockResolvedValue(undefined)+ vi.spyOn(reconciler as any, 'ensureDesktopNetworkPolicy').mockResolvedValue('up_to_date')vi.spyOn(reconciler as any, 'reconcileChannelReaderDeployment').mockResolvedValue(undefined)vi.spyOn(reconciler as any, 'checkDeploymentReady').mockResolvedValue(true)})@@ -229,7 +229,7 @@ describe('HostReconciler.reconcile — NP wiring', () => {// than racing the deny-all default.const ingressSpy = vi.spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy')- .mockResolvedValue(undefined)+ .mockResolvedValue('up_to_date')const deploySpy = vi.spyOn(reconciler as any, 'ensureDeployment').mockResolvedValue(true)const readySpy = vi.spyOn(reconciler as any, 'checkDeploymentReady').mockResolvedValue(true)@@ -246,7 +246,7 @@ describe('HostReconciler.reconcile — NP wiring', () => {it('calls ensureChannelReaderEgressNetworkPolicy before reconcileChannelReaderDeployment', async () => {const egressSpy = vi.spyOn(reconciler as any, 'ensureChannelReaderEgressNetworkPolicy')- .mockResolvedValue(undefined)+ .mockResolvedValue('up_to_date')const cReaderSpy = vi.spyOn(reconciler as any, 'reconcileChannelReaderDeployment').mockResolvedValue(undefined)@@ -266,7 +266,7 @@ describe('HostReconciler.reconcile — NP wiring', () => {new Error('rbac: networkpolicies.networking.k8s.io is forbidden'))vi.spyOn(reconciler as any, 'ensureChannelReaderEgressNetworkPolicy').mockResolvedValue(- undefined+ 'up_to_date')await reconciler.reconcile(HOST)@@ -278,11 +278,13 @@ describe('HostReconciler.reconcile — NP wiring', () => {expect(status!.deployed).toBe(true)expect(status!.ready).toBe(false)expect(status!.message).toMatch(/degraded/i)- expect(status!.message).toMatch(/mcp-host NP/)+ expect(status!.message).toMatch(+ /mcp-host ingress: rbac: networkpolicies\.networking\.k8s\.io is forbidden/+ )})it('surfaces egress NP apply failure in Host status as degraded', async () => {- vi.spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy').mockResolvedValue(undefined)+ vi.spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy').mockResolvedValue('up_to_date')vi.spyOn(reconciler as any, 'ensureChannelReaderEgressNetworkPolicy').mockRejectedValue(new Error('cluster connectivity failure'))@@ -296,7 +298,25 @@ describe('HostReconciler.reconcile — NP wiring', () => {expect(status!.deployed).toBe(true)expect(status!.ready).toBe(false)expect(status!.message).toMatch(/degraded/i)- expect(status!.message).toMatch(/egress NP/)+ expect(status!.message).toMatch(/channel-reader egress: cluster connectivity failure/)+ })++ it('surfaces a NetworkPolicy apply result of missing as degraded', async () => {+ vi.spyOn(reconciler as any, 'ensureMcpHostIngressNetworkPolicy').mockResolvedValue('missing')+ vi.spyOn(reconciler as any, 'ensureChannelReaderEgressNetworkPolicy').mockResolvedValue(+ 'up_to_date'+ )++ await reconciler.reconcile(HOST)++ const status = (reconciler as any).statusMap.get('chatllm') as+ | { deployed?: boolean; ready?: boolean; message?: string }+ | undefined+ expect(status).toMatchObject({+ deployed: true,+ ready: false,+ message: expect.stringContaining('mcp-host ingress: apply did not converge (missing)'),+ })})})diff --git a/scripts/e2e/_lib/hcc-watch-api-proxy.mjs b/scripts/e2e/_lib/hcc-watch-api-proxy.mjsindex c53ef402e..b69444f2d 100644--- a/scripts/e2e/_lib/hcc-watch-api-proxy.mjs+++ b/scripts/e2e/_lib/hcc-watch-api-proxy.mjs@@ -4,6 +4,11 @@ import https from 'node:https'import { createSecureContext } from 'node:tls'import { createBookmarkObservation } from './hcc-watch-bookmarks.mjs'+// Individual fixture commands remain one-minute bounded; a single continuous+// cache-loss observation has a two-minute ceiling even when renewed.+const MAX_CHANNEL_HOLD_WINDOW_MS = 60_000+const MAX_CHANNEL_HOLD_BUDGET_MS = 120_000+export function proxyUpstreamErrorRecord(error) {const codes = ['ECONNREFUSED',@@ -47,7 +52,11 @@ export function validateCommand(command, allowedPaths) {if (typeof command.pauseId !== 'string' || !/^[a-zA-Z0-9-]{1,80}$/.test(command.pauseId))throw new Error('invalid_pause_id')} else if (command.action === 'hold-channel') {- if (!Number.isInteger(command.durationMs) || command.durationMs < 1000 || command.durationMs > 60000)+ if (+ !Number.isInteger(command.durationMs) ||+ command.durationMs < 1000 ||+ command.durationMs > MAX_CHANNEL_HOLD_WINDOW_MS+ )throw new Error('invalid_channel_hold_duration')} else if (command.action !== 'release-channel' && command.action !== 'observe-bookmarks')throw new Error('invalid_control_action')@@ -95,7 +104,14 @@ export function createProxy({const held = channelHoldchannelHold = nullclearTimeout(held.timer)- writeRecord('channel-hold', { id: held.id, state: reason, rejected: held.rejected })+ writeRecord('channel-hold', {+ id: held.id,+ state: reason,+ cut: held.cut,+ rejected: held.rejected,+ renewals: held.renewals,+ deadlineAtMs: held.deadlineAtMs,+ })}const server = https.createServer({ key, cert }, (request, response) => {const url = new URL(request.url, 'https://fixture.invalid')@@ -209,22 +225,67 @@ export function createProxy({finishPause('released')acknowledge({ id: command.id, state: 'released' })} else if (command.action === 'hold-channel') {- if (!channelPath || channelHold) throw new Error('channel_hold_unavailable')- let count = 0- channelHold = {- id: command.id,- rejected: 0,- timer: setTimeout(() => finishChannelHold('expired'), command.durationMs),- }- for (const stream of streams) {- if (stream.watch && stream.request.method === 'GET' &&- new URL(stream.request.url, 'https://fixture.invalid').pathname === channelPath) {- stream.close()- count+++ if (!channelPath) throw new Error('channel_hold_unavailable')+ if (channelHold) {+ const now = Date.now()+ const budgetDeadlineMs = channelHold.startedAtMs + MAX_CHANNEL_HOLD_BUDGET_MS+ const deadlineAtMs = Math.min(now + command.durationMs, budgetDeadlineMs)+ if (deadlineAtMs <= now) throw new Error('channel_hold_budget_exhausted')+ clearTimeout(channelHold.timer)+ channelHold.id = command.id+ channelHold.deadlineAtMs = deadlineAtMs+ channelHold.renewals+++ channelHold.timer = setTimeout(+ () => finishChannelHold('expired'),+ deadlineAtMs - now,+ )+ writeRecord('channel-hold', {+ id: channelHold.id,+ state: 'held',+ cut: channelHold.cut,+ rejected: channelHold.rejected,+ renewals: channelHold.renewals,+ deadlineAtMs,+ })+ acknowledge({+ id: command.id,+ state: 'held',+ count: channelHold.cut,+ renewed: true,+ renewals: channelHold.renewals,+ deadlineAtMs,+ })+ } else {+ let count = 0+ const now = Date.now()+ const deadlineAtMs = now + command.durationMs+ channelHold = {+ id: command.id,+ startedAtMs: now,+ deadlineAtMs,+ cut: 0,+ rejected: 0,+ renewals: 0,+ timer: setTimeout(() => finishChannelHold('expired'), command.durationMs),+ }+ for (const stream of streams) {+ if (stream.watch && stream.request.method === 'GET' &&+ new URL(stream.request.url, 'https://fixture.invalid').pathname === channelPath) {+ stream.close()+ count+++ }}+ channelHold.cut = count+ writeRecord('channel-hold', {+ id: command.id,+ state: 'held',+ cut: count,+ rejected: 0,+ renewals: 0,+ deadlineAtMs,+ })+ acknowledge({ id: command.id, state: 'held', count, renewals: 0, deadlineAtMs })}- writeRecord('channel-hold', { id: command.id, state: 'held', cut: count, rejected: 0 })- acknowledge({ id: command.id, state: 'held', count })} else if (command.action === 'release-channel') {if (!channelHold) throw new Error('channel_hold_not_active')finishChannelHold('released')diff --git a/scripts/e2e/e2e-hcc-stateless-cache-containment.sh b/scripts/e2e/e2e-hcc-stateless-cache-containment.shindex ae46f512c..94837bad9 100755--- a/scripts/e2e/e2e-hcc-stateless-cache-containment.sh+++ b/scripts/e2e/e2e-hcc-stateless-cache-containment.sh@@ -42,6 +42,14 @@ require_safe_kube_contextdie 'provide E2E_BRANCH_PROFILE_ENV from the owned branch profile'[ -n "${E2E_PROFILE_PORTS_ENV:-}" ] && [ -r "$E2E_PROFILE_PORTS_ENV" ] ||die 'provide E2E_PROFILE_PORTS_ENV from the owned branch profile'+profile_port_value() {+ awk -F= -v key="$1" '$1 == key { sub(/^[^=]*=/, ""); print; exit }' "$E2E_PROFILE_PORTS_ENV"+}+CONTROL_API_BASE_URL="$(profile_port_value CONTROL_API_URL)"+CONTROL_UI_BASE_URL="$(profile_port_value CONTROL_UI_URL)"+EXTERNAL_REST_API_BASE_URL="$(profile_port_value EXTERNAL_REST_API_URL)"+RPC_PROXY_BASE_URL="$(profile_port_value RPC_PROXY_URL)"+export CONTROL_API_BASE_URL CONTROL_UI_BASE_URL EXTERNAL_REST_API_BASE_URL RPC_PROXY_BASE_URLrequire_branch_profile_urls "$E2E_KUBECONTEXT" "$E2E_PROFILE_PORTS_ENV" ||die 'profile URLs do not match the owned ports'kctl get nodes -o json | jq -e --arg c "$E2E_KUBECONTEXT" \@@ -67,6 +75,7 @@ HCC_GATE_FINALIZATION_FAILURE=''HCC_PATCHED=0 PROXY_CREATED=0 PROBE_CREATED=0 HCC_PR_A_TLS_CREATED=0HCC_UID='' HCC_RESTARTS=''ORIGINAL_REPLICAS=''+HCC_PR_A_CHANNEL_HOLD_ID=''cleanup() {local status=$? cleanup_failed=0 restore_ok=1@@ -135,9 +144,12 @@ login="$(curl -fsS -m 20 -X POST "${EXT_BASE}/api/v1/auth/password-login" \SESSION_TOKEN="$(jq -er '.token' <<<"$login")" || die 'login returned no token'mint_rpc_token() {local body+ # The existing messages route uses wakeAndHold when the stateless Host is+ # suspended. Keep wake capability on this user token so the baseline message+ # can take that supported Desktop-to-rpc-proxy path when it is needed.body="$(curl -fsS -m 20 -X POST "${EXT_BASE}/api/v1/rpc/token" \-H "Authorization: Bearer ${SESSION_TOKEN}" -H 'Content-Type: application/json' \- -d "$(jq -cn --arg host "$HOST_REF" '{hostRefs:[$host],scopes:["host:message:invoke","host:session:read","host:status:read","host:health:read"]}')")" || return 1+ -d "$(jq -cn --arg host "$HOST_REF" '{hostRefs:[$host],scopes:["host:message:invoke","host:session:read","host:status:read","host:health:read","host:wake:write"]}')")" || return 1RPC_TOKEN="$(jq -er '.token' <<<"$body")"}mint_rpc_token || die 'could not mint authorized RPC token'@@ -205,17 +217,50 @@ cache_held_active() {[ "$pod" = "$baseline_pod" ]}+channel_hold_is_active() {+ local expected_id=$1 pod+ pod="$(hcc_pr_a_proxy_pod)" || return 1+ kctl exec "pod/$pod" -n "$HCC_NS" -c proxy -- node -e \+ 'const fs=require("fs");try{const hold=JSON.parse(fs.readFileSync("/churn-ctl/channel-hold.json"));if(hold.id!==process.argv[1]||hold.state!=="held"||!Number.isFinite(hold.deadlineAtMs)||hold.deadlineAtMs<=Date.now())process.exit(1)}catch{process.exit(1)}' \+ "$expected_id" >/dev/null 2>&1+}++renew_channel_hold() {+ local cycle=$1+ hcc_pr_a_command hold-channel 60000 || die "cycle ${cycle}: channel-hold renewal command failed"+ HCC_PR_A_CHANNEL_HOLD_ID="$HCC_PR_A_COMMAND_ID"+ wait_until 5 'selective hold renewal acknowledgement' hcc_pr_a_ack held ||+ die "cycle ${cycle}: channel-hold renewal was not acknowledged"+ wait_until 5 'live selective hold after renewal' channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: renewed channel hold is not active"+}+for cycle in 1 2; dobefore="$(log_count 'CommunicationChannel watch ended;')"hcc_pr_a_command hold-channel 60000 || die "cycle ${cycle}: fault command failed"+ HCC_PR_A_CHANNEL_HOLD_ID="$HCC_PR_A_COMMAND_ID"wait_until 5 'selective hold acknowledgement' hcc_pr_a_ack held ||die "cycle ${cycle}: no live channel watch was cut"+ wait_until 5 'live selective hold' channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold is not active"wait_log_count 'CommunicationChannel watch ended;' "$((before + 1))" 20 ||die "cycle ${cycle}: HCC did not lose channel authority"wait_until 30 'reconciliation while channel cache is unsynced' cache_held_active ||die "cycle ${cycle}: active stateless Host did not converge during watch loss"+ channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold expired during cache reconciliation"+ renew_channel_hold "$cycle"+ channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold expired before session transcript read"session_visible || die "cycle ${cycle}: known session unavailable through rpc-proxy"+ channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold expired during session transcript read"+ renew_channel_hold "$cycle"+ channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold expired before session list read"session_listed || die "cycle ${cycle}: known session absent from authorized list"+ channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||+ die "cycle ${cycle}: channel hold expired during session list read"cache_held_active || die "cycle ${cycle}: template, SQLite path or pod identity changed"hcc_pr_a_command release-channel || die "cycle ${cycle}: release command failed"wait_until 5 'selective release acknowledgement' hcc_pr_a_ack released ||diff --git a/scripts/tests/hcc-watch-api-proxy.test.mjs b/scripts/tests/hcc-watch-api-proxy.test.mjsindex 898b6eab4..a4c705541 100644--- a/scripts/tests/hcc-watch-api-proxy.test.mjs+++ b/scripts/tests/hcc-watch-api-proxy.test.mjs@@ -91,11 +91,33 @@ test('channel hold cuts only its watch and keeps Host API requests available', {}))const held = await ack('hold-1', 'held')assert.equal(held.count, 1, 'live CommunicationChannel watch was cut')+ const initialHold = JSON.parse(readFileSync(join(controlDir, 'channel-hold.json'), 'utf8'))assert.equal(await get(channelPath), 503, 'channel LIST remains unavailable')assert.equal(await get('/apis/clerum.io/v1alpha1/namespaces/mcp-host/hosts/test'), 200)assert.equal(await get('/api/v1/namespaces/mcp-host/pods'), 200)assert.equal(seen.filter(path => path.startsWith(channelPath)).length, 1,'blocked channel retries never reached upstream')+ writeFileSync(join(controlDir, 'command.json'), JSON.stringify({+ id: 'hold-2', action: 'hold-channel', durationMs: 5000,+ }))+ const renewed = await ack('hold-2', 'held')+ assert.equal(renewed.count, 1, 'renewal retains the original watch-cut witness')+ assert.equal(renewed.renewed, true)+ assert.equal(renewed.renewals, 1)+ assert.ok(renewed.deadlineAtMs > initialHold.deadlineAtMs,+ 'renewal extends the live hold deadline without a timing sleep')+ const renewedHold = JSON.parse(readFileSync(join(controlDir, 'channel-hold.json'), 'utf8'))+ assert.deepEqual(renewedHold, {+ id: 'hold-2',+ state: 'held',+ cut: 1,+ rejected: 1,+ renewals: 1,+ deadlineAtMs: renewed.deadlineAtMs,+ })+ assert.equal(await get(channelPath), 503, 'channel LIST remains unavailable after renewal')+ assert.equal(seen.filter(path => path.startsWith(channelPath)).length, 1,+ 'renewed channel hold still blocks upstream channel requests')writeFileSync(join(controlDir, 'command.json'), JSON.stringify({id: 'release-1', action: 'release-channel',}))diff --git a/scripts/tests/test-hcc-stateless-cache-containment.sh b/scripts/tests/test-hcc-stateless-cache-containment.shindex 48dd5a994..e9ed9919c 100755--- a/scripts/tests/test-hcc-stateless-cache-containment.sh+++ b/scripts/tests/test-hcc-stateless-cache-containment.sh@@ -6,13 +6,17 @@ set -euo pipefailROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"GATE="${ROOT}/scripts/e2e/e2e-hcc-stateless-cache-containment.sh"PROXY="${ROOT}/scripts/e2e/_lib/hcc-watch-api-proxy.mjs"+PROXY_TEST="${ROOT}/scripts/tests/hcc-watch-api-proxy.test.mjs"HELPER="${ROOT}/scripts/e2e/_lib/hcc-watch-pr-a.sh"+MAKEFILE="${ROOT}/Makefile"+WORKFLOW="${ROOT}/.github/workflows/ci-public.yml"-bash -n "$GATE" "$HELPER"+bash -n "$GATE" "$HELPER" "$0"node --check "$PROXY"grep -Fq 'require_branch_owned_hcc_gate' "$GATE"grep -Fq 'E2E_BRANCH_PROFILE_ENV' "$GATE"grep -Fq 'E2E_PROFILE_PORTS_ENV' "$GATE"+grep -Fq 'profile_port_value CONTROL_API_URL' "$GATE"grep -Fq 'acquire_hcc_watch_gate_lock' "$GATE"# shellcheck disable=SC2016 # Match literal shell source.grep -Fq 'finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok"' "$GATE"@@ -30,9 +34,27 @@ grep -Fq '/sessions/${HOST_REF}/${THREAD_ID}/messages' "$GATE"grep -Fq '/sessions?agent=${HOST_REF}&limit=100' "$GATE"grep -Fq 'session_visible || die "cycle' "$GATE"grep -Fq 'session_listed || die "cycle' "$GATE"+grep -Fq '"host:wake:write"' "$GATE"+grep -Fq '/api/v1/rpc/hosts/${HOST_REF}/messages' "$GATE"+grep -Fq 'channel_hold_is_active' "$GATE"+[ "$(grep -Fc 'channel_hold_is_active "$HCC_PR_A_CHANNEL_HOLD_ID" ||' "$GATE")" -ge 6 ]+[ "$(grep -Fc 'hcc_pr_a_command hold-channel 60000' "$GATE")" -ge 2 ]+grep -Fq 'MAX_CHANNEL_HOLD_BUDGET_MS = 120_000' "$PROXY"+grep -Fq 'channelHold.renewals++' "$PROXY"+grep -Fq 'deadlineAtMs' "$PROXY"+grep -Fq "renewal extends the live hold deadline without a timing sleep" "$PROXY_TEST"+grep -Fq "renewed channel hold still blocks upstream channel requests" "$PROXY_TEST"grep -Fq 'HCC_PR_A_SELECTIVE_CHANNEL=1 hcc_pr_a_enable_proxy' "$GATE"grep -Fq 'response.writeHead(503' "$PROXY"grep -Fq 'url.pathname === channelPath' "$PROXY"+grep -Fq 'CONTROL_UI_BASE_URL="$(profile_port_value CONTROL_UI_URL)"' "$GATE"+grep -Fq 'minikube-t2-hcc-stateless-cache-containment' "$MAKEFILE"+grep -Fq 'T2_HEALTHCHECK_COMMAND=' "$MAKEFILE"+grep -Fq 'MINIKUBE_PROFILE="$$T2_PROFILE"' "$MAKEFILE"+grep -Fq 'T2_GATE_ID=minikube-t2' "$MAKEFILE"+grep -Fq 'MINIKUBE_PROFILE)" = "$$context"' "$MAKEFILE"+grep -Fq 'E2E_EXPECTED_PRE_GATE_GATE=minikube-t2' "$MAKEFILE"+grep -Fq 'bash scripts/tests/test-hcc-stateless-cache-containment.sh' "$WORKFLOW"if grep -Eq 'scale_proxy|kill .*HCC|kubectl .*delete pod' "$GATE"; thenecho 'Selective gate contains a broad API or pod fault' >&2exit 1