The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep the approval-mode chip on the active profile mode (#142565)
Austin Pickett47b23fa04853
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/branch-approval-owner.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions/branch-approval-owner.test.tsxnew file mode 100644index 00000000000..896bf7cc412--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/branch-approval-owner.test.tsx@@ -0,0 +1,182 @@+// Branching a chat another profile owns must not let that profile's runtime+// overwrite the ACTIVE profile's approval chip: forkBranch passes the branch's+// owner (the parent row's route) to applyRuntimeInfo, which only reconciles the+// chip when the owner is the active gateway.+import { cleanup, render, waitFor } from '@testing-library/react'+import type { MutableRefObject } from 'react'+import { useEffect } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { type SessionInfo } from '@/hermes'+import { $approvalModes, approvalModeForProfile, reconcileApprovalModeForProfile } from '@/store/approval-mode'+import { requestGatewayForAgent } from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'+import { setMessages, setSelectedStoredSessionId, setSessions } from '@/store/session'+import { $sessionTiles } from '@/store/session-states'++import type { ClientSessionState } from '../../../types'++import { useSessionActions } from './index'++vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ deleteSession: vi.fn(),+ getSession: vi.fn(),+ getAllSessionMessages: vi.fn(),+ getLatestSessionMessages: vi.fn(),+ listAllProfileSessions: vi.fn(),+ setApiRequestProfile: vi.fn(),+ setSessionArchived: vi.fn()+}))++vi.mock('@/store/profile', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureGatewayAgent: vi.fn().mockResolvedValue(undefined),+ ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)+}))++vi.mock('@/store/gateway', async importOriginal => {+ const original = await importOriginal<Record<string, unknown>>()++ return {+ ...original,+ // Default-preserving spy: tests that route by the active source override it.+ activeGatewayConnectionId: vi.fn(original.activeGatewayConnectionId as () => null | string),+ requestGatewayForAgent: vi.fn(),+ requestGatewayForProfile: vi.fn(),+ retainGatewayForAgent: vi.fn(async () => () => undefined)+ }+})++vi.mock('@/components/pane-shell/tree/store', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ noteActiveTreeGroup: vi.fn(),+ revealTreePane: vi.fn()+}))++function storedSession(overrides: Partial<SessionInfo> = {}): SessionInfo {+ return {+ ended_at: null,+ id: 'stored-1',+ input_tokens: 0,+ is_active: false,+ last_active: 1,+ message_count: 0,+ model: null,+ output_tokens: 0,+ preview: null,+ source: 'desktop',+ started_at: 1,+ title: 'stored',+ tool_call_count: 0,+ ...overrides+ }+}++function BranchHarness({+ activeSessionId = null,+ navigate = vi.fn(),+ onCurrentReady,+ onReady,+ requestGateway,+ selectedStoredSessionId = null+}: {+ activeSessionId?: string | null+ navigate?: ReturnType<typeof vi.fn>+ onCurrentReady?: (branchCurrentSession: (messageId?: string) => Promise<boolean>) => void+ onReady: (branchStoredSession: (storedSessionId: string, sessionProfile?: string | null) => Promise<boolean>) => void+ requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>+ selectedStoredSessionId?: string | null+}) {+ const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })+ const activeSessionIdRef = ref<string | null>(activeSessionId)+ const selectedStoredSessionIdRef = ref<string | null>(selectedStoredSessionId)++ const actions = useSessionActions({+ activeSessionId,+ activeSessionIdRef,+ busyRef: ref(false),+ creatingSessionRef: ref(false),+ ensureSessionState: () => ({}) as ClientSessionState,+ getRouteToken: () => 'token',+ getRoutedStoredSessionId: () => null,+ navigate: navigate as never,+ requestGateway,+ resetViewSync: vi.fn(),+ routedSessionId: null,+ runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),+ selectedStoredSessionId,+ selectedStoredSessionIdRef,+ sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),+ syncSessionStateToView: vi.fn(),+ updateSessionState: () => ({}) as ClientSessionState+ })++ useEffect(() => {+ onReady(actions.branchStoredSession)+ onCurrentReady?.(actions.branchCurrentSession)+ }, [actions.branchCurrentSession, actions.branchStoredSession, onCurrentReady, onReady])++ return null+}++describe('forkBranch approval-chip owner scoping', () => {+ beforeEach(() => {+ $approvalModes.set({})+ })++ afterEach(() => {+ cleanup()+ setSessions([])+ $sessionTiles.set([])+ setSelectedStoredSessionId(null)+ vi.restoreAllMocks()+ })++ it("keeps the active profile's approval chip when branching a chat another profile owns", async () => {+ // All-profiles view: the open chat lives on `bot` while the gateway (and+ // the status-bar chip keyed by its name) stays on `default`.+ $activeGatewayProfile.set('default')+ reconcileApprovalModeForProfile('default', 'manual')+ setSessions([storedSession({ connection_id: 'local', id: 'stored-parent', message_count: 4, profile: 'bot' })])+ setMessages([{ id: 'tail-user', role: 'user', parts: [{ type: 'text', text: 'question' }] }])++ vi.mocked(requestGatewayForAgent).mockImplementation((async (+ _connectionId: string,+ _profile: string,+ method: string+ ) =>+ method === 'session.branch_whole'+ ? {+ session_id: 'branch-runtime',+ stored_session_id: 'branch-stored',+ title: 'Branch',+ message_count: 4,+ messages_omitted: true,+ // A live parent's branch carries the full runtime info: the bot+ // profile's own approvals.mode.+ info: { approval_mode: 'off' }+ }+ : {}) as never)++ let branchCurrentSession: ((messageId?: string) => Promise<boolean>) | null = null+ render(+ <BranchHarness+ activeSessionId="live-parent"+ onCurrentReady={branch => (branchCurrentSession = branch)}+ onReady={() => undefined}+ requestGateway={vi.fn(async () => ({}) as never)}+ selectedStoredSessionId="stored-parent"+ />+ )+ await waitFor(() => expect(branchCurrentSession).not.toBeNull())++ try {+ await expect(branchCurrentSession!()).resolves.toBe(true)+ } finally {+ vi.mocked(requestGatewayForAgent).mockReset()+ }++ expect(approvalModeForProfile('default')).toBe('manual')+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex e3351708a44..440381ae486 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -171,6 +171,7 @@ import {rememberResolvedResumeOwner,resolveResumeOwner} from './resume-owner'+import { backgroundRuntimeOptions, runtimeOwner } from './runtime-owner'import { createGatewaySession, desktopSessionCreateParams } from './session-create-request'import {createPersistedDisplayTranscriptProvenance,@@ -819,7 +820,7 @@ export function useSessionActions({const runtimeStartedAt = Date.now()setSessionStartedAt(runtimeStartedAt)const yoloArmed = $yoloActive.get()- const runtimeInfo = applyRuntimeInfo(created.info)+ const runtimeInfo = applyRuntimeInfo(created.info, { owner: runtimeOwner(capturedRoute, capturedProfile) })updateSessionState(created.session_id,@@ -1175,7 +1176,7 @@ export function useSessionActions({// so the right rail kept showing the previous session's tree when a// Project "+" created a session while the main chat was occupied// (#76696). Split/side tiles deliberately stay isolated.- const runtimeInfo = applyRuntimeInfo(created.info, { foreground: false })+ const runtimeInfo = applyRuntimeInfo(created.info, backgroundRuntimeOptions(capturedRoute, requestedProfile))updateSessionState(created.session_id, state => (runtimeInfo ? { ...state, ...runtimeInfo } : state), stored)openSessionTile(stored, dir, options?.anchor, options?.before, workspaceScope)@@ -1617,7 +1618,7 @@ export function useSessionActions({? Boolean(settlePendingClarifyToolCall(cachedViewState.messages, {}, false).streamId): false- const runtimeInfo = applyRuntimeInfo(activated.info)+ const runtimeInfo = applyRuntimeInfo(activated.info, { owner: sessionOwner })// `omit_messages` means the response carries NO transcript, not// an empty one — the cache is the base and the live projection is@@ -2321,7 +2322,7 @@ export function useSessionActions({const clarifyAuthoritativelyAbsent =pendingClarifyState.authoritativeAbsent && !$clarifyRequests.get()[resumed.session_id]- const runtimeInfo = applyRuntimeInfo(resumed.info)+ const runtimeInfo = applyRuntimeInfo(resumed.info, { owner: sessionOwner })patchSessionWorkspace(storedSessionId, runtimeInfo?.cwd)@@ -2394,9 +2395,7 @@ export function useSessionActions({streamId: resumedRunning ? inFlightRecovery.streamId : null,turnStartedAt: resumedRunning ? (inFlightRecovery.turnStartedAt ?? resumedTurnStartedAt) : null}- : {- turnStartedAt: resumedRunning && resumedTurnStartedAt !== null ? resumedTurnStartedAt : null- }),+ : { turnStartedAt: resumedRunning && resumedTurnStartedAt !== null ? resumedTurnStartedAt : null }),...livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection),...(clearedClarifyProjection? {@@ -2814,7 +2813,7 @@ export function useSessionActions({routedSessionId)- const runtimeInfo = applyRuntimeInfo(branched.info, { foreground: false })+ const runtimeInfo = applyRuntimeInfo(branched.info, backgroundRuntimeOptions(ownerRoute, profile))patchSessionWorkspace(routedSessionId, runtimeInfo?.cwd)if (runtimeInfo) {diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.test.tsnew file mode 100644index 00000000000..5e10a97fbb7--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.test.ts@@ -0,0 +1,46 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $approvalModes, approvalModeForProfile } from '@/store/approval-mode'+import * as gateway from '@/store/gateway'+import { $activeGatewayProfile } from '@/store/profile'++import { applyRuntimeInfo } from './utils'++describe('applyRuntimeInfo approval mode owner scoping', () => {+ beforeEach(() => {+ $approvalModes.set({})+ $activeGatewayProfile.set('work')+ })++ it('never lets another backend runtime set the active profile approval chip', () => {+ applyRuntimeInfo({ approval_mode: 'manual' })++ // A bot tile, a branch of a bot chat, an All-profiles resume, and a+ // same-named profile on another connection all report THEIR config.+ applyRuntimeInfo({ approval_mode: 'off' }, { foreground: false, owner: { connectionId: 'local', profile: 'bot' } })+ applyRuntimeInfo({ approval_mode: 'off' }, { owner: 'bot' })+ applyRuntimeInfo({ approval_mode: 'off' }, { owner: { connectionId: 'ssh-box', profile: 'work' } })++ expect(approvalModeForProfile('work')).toBe('manual')++ applyRuntimeInfo({ approval_mode: 'off' }, { owner: { connectionId: 'local', profile: 'work' } })++ expect(approvalModeForProfile('work')).toBe('off')++ applyRuntimeInfo({ approval_mode: 'manual' })+ // The active socket is (ssh-box, work); a bare 'work' owner dialled the local profile door.+ const primary = vi.spyOn(gateway, 'isActivePrimary').mockReturnValue(false)+ const connection = vi.spyOn(gateway, 'activeGatewayConnectionId').mockReturnValue('ssh-box')++ try {+ applyRuntimeInfo({ approval_mode: 'off' }, { owner: 'work' })+ expect(approvalModeForProfile('work')).toBe('manual')++ applyRuntimeInfo({ approval_mode: 'off' }, { owner: { connectionId: 'ssh-box', profile: 'work' } })+ expect(approvalModeForProfile('work')).toBe('off')+ } finally {+ primary.mockRestore()+ connection.mockRestore()+ }+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.tsnew file mode 100644index 00000000000..d9482892418--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/runtime-owner.ts@@ -0,0 +1,62 @@+// Runtime-info ownership for applyRuntimeInfo: the status-bar approval chip+// is keyed by the ACTIVE profile's name, so only the active gateway's runtime+// may reconcile it. This mirrors the session.info event rule, except that a+// missing connection id counts as `local` here (that rule keys on+// registryBackendScopeKey, where the two differ); for the chip they are one gateway.+// Another profile's `approvals.mode` written under the active name shows+// "Manual" on a profile that auto-approves, or the reverse.+import { reconcileApprovalModeForProfile } from '@/store/approval-mode'+import { activeGatewayConnectionId, isActivePrimary } from '@/store/gateway'+import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'+import type { SessionOwnerRoute, SessionOwnerScope } from '@/store/session-request-router'+import type { SessionRuntimeInfo } from '@/types/hermes'++function ownerIsActiveGateway(owner: SessionOwnerScope): boolean {+ if (!owner) {+ return true+ }++ const activeProfile = normalizeProfileKey($activeGatewayProfile.get())++ if (typeof owner === 'string') {+ // A bare profile dials the profile door (the primary, or a connection-less+ // pool socket), so it is the active gateway only while that door is active,+ // never while a registry connection serving a same-named profile is.+ return normalizeProfileKey(owner) === activeProfile && (isActivePrimary() || activeGatewayConnectionId() === null)+ }++ return (+ normalizeProfileKey(owner.profile) === activeProfile &&+ (owner.connectionId?.trim() || 'local') === (activeGatewayConnectionId() ?? 'local')+ )+}++/** Reconcile `info`'s approval mode into the active profile's chip, but only+ * when `owner` is the active gateway — a runtime another backend produced+ * (a bot tile, a branch of a bot chat, an All-profiles resume) reports its+ * OWN config and must not repaint the active profile's chip. */+export function reconcileOwnerApprovalMode(info: SessionRuntimeInfo, owner: SessionOwnerScope): void {+ if (info.approval_mode === undefined || !ownerIsActiveGateway(owner)) {+ return+ }++ reconcileApprovalModeForProfile($activeGatewayProfile.get(), info.approval_mode)+}++/** applyRuntimeInfo options for a runtime that must NOT publish into the main+ * pane's composer (a session tile, a background branch): the owner is the+ * create's route when the caller dialled one, else its profile. */+export function backgroundRuntimeOptions(+ route: null | SessionOwnerRoute | undefined,+ profile: null | string | undefined+): { foreground: false; owner: SessionOwnerScope } {+ return { foreground: false, owner: runtimeOwner(route, profile) }+}++/** The owner of a create's runtime: the dialled route, else its profile. */+export function runtimeOwner(+ route: null | SessionOwnerRoute | undefined,+ profile: null | string | undefined+): SessionOwnerScope {+ return route ?? profile+}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex c77ff0cfd89..b6b3ea122ed 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -15,7 +15,6 @@ import { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-imaimport { parseErrorSurface } from '@/lib/error-surface'import { isMessagingSource, normalizeSessionSource } from '@/lib/session-source'import { isLiveTailReplyId } from '@/lib/spoken-reply'-import { reconcileApprovalModeForProfile } from '@/store/approval-mode'import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'import { pendingSnapshotFence, reconcilePendingSubmissions } from '@/store/pending-submissions'import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'@@ -75,6 +74,7 @@ import {persistedTurnsEquivalent,transcriptRowIds} from './pending-turn-identity'+import { reconcileOwnerApprovalMode } from './runtime-owner'export { goneSessionVerdict, isSessionGoneError, resolveResumedBusy } from './resume-verdicts'@@ -2370,6 +2370,8 @@ interface ApplyRuntimeInfoOptions {* per-session state is unaffected.*/foreground?: boolean+ /** The backend that produced `info` when it is not the ambient gateway. */+ owner?: SessionOwnerScope}/** Mirror a session's runtime state into the composer atoms the MAIN pane@@ -2426,7 +2428,7 @@ function publishRuntimeToComposer(state: SessionRuntimeStatePatch): void {}/** Session-independent side effects of one runtime info snapshot. */-function reportRuntimeInfoAppState(info: SessionRuntimeInfo): void {+function reportRuntimeInfoAppState(info: SessionRuntimeInfo, owner: SessionOwnerScope): void {if (info.stored_session_id) {reconcilePendingSubmissions(info.stored_session_id, info.pending_submissions,pendingSnapshotFence(info.replay_epoch, info.last_sequence))@@ -2436,9 +2438,7 @@ function reportRuntimeInfoAppState(info: SessionRuntimeInfo): void {// reports backend skew and credential warnings just as usefully.reportBackendContract(info.desktop_contract, info.desktop_protocol)- if (info.approval_mode !== undefined) {- reconcileApprovalModeForProfile($activeGatewayProfile.get(), info.approval_mode)- }+ reconcileOwnerApprovalMode(info, owner)requestDesktopOnboardingForCredentialWarning(info.credential_warning)@@ -2447,13 +2447,13 @@ function reportRuntimeInfoAppState(info: SessionRuntimeInfo): void {export function applyRuntimeInfo(info: SessionRuntimeInfo | undefined,- { foreground = true }: ApplyRuntimeInfoOptions = {}+ { foreground = true, owner }: ApplyRuntimeInfoOptions = {}): SessionRuntimeStatePatch | null {if (!info) {return null}- reportRuntimeInfoAppState(info)+ reportRuntimeInfoAppState(info, owner)const sessionState: SessionRuntimeStatePatch = {}diff --git a/apps/desktop/src/app/shell/approval-mode-menu.test.tsx b/apps/desktop/src/app/shell/approval-mode-menu.test.tsxindex bf6a888b952..73dac990eec 100644--- a/apps/desktop/src/app/shell/approval-mode-menu.test.tsx+++ b/apps/desktop/src/app/shell/approval-mode-menu.test.tsx@@ -19,13 +19,15 @@ afterEach(() => {})function Harness({+ gatewayState = 'open',profile = 'default',requestGateway}: {+ gatewayState?: stringprofile?: stringrequestGateway: (method: string, params?: Record<string, unknown>) => Promise<unknown>}) {- const item = useApprovalModeStatusbarItem(profile, requestGateway)+ const item = useApprovalModeStatusbarItem(profile, requestGateway, gatewayState)return (<MemoryRouter>@@ -53,4 +55,28 @@ describe('approval mode statusbar item', () => {expect(screen.getByRole('button', { name: /manual/i })).toBeTruthy()})})++ it('syncs once the gateway opens instead of sitting on the pre-sync default', async () => {+ // Boot order: the shell (and this chip) mount while the socket is still+ // connecting, so the sync must wait for 'open' — and then actually run.+ // A sync attempted while connecting rejects ("Hermes gateway+ // unavailable") and, swallowed, would leave the chip on its optimistic+ // 'smart' default for the whole session even though the configured mode+ // is 'off'.+ const requestGateway = vi.fn(async () => ({ value: 'off' }))++ const { rerender } = render(+ <Harness gatewayState="connecting" profile="boot" requestGateway={requestGateway} />+ )++ expect(requestGateway).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: /smart/i })).toBeTruthy()++ rerender(<Harness gatewayState="open" profile="boot" requestGateway={requestGateway} />)++ await waitFor(() => {+ expect(requestGateway).toHaveBeenCalledWith('config.get', { key: 'approvals.mode', profile: 'boot' })+ expect(screen.getByRole('button', { name: /off/i })).toBeTruthy()+ })+ })})diff --git a/apps/desktop/src/app/shell/approval-mode-menu.tsx b/apps/desktop/src/app/shell/approval-mode-menu.tsxindex 4d6b0b1a26f..01ae447c87c 100644--- a/apps/desktop/src/app/shell/approval-mode-menu.tsx+++ b/apps/desktop/src/app/shell/approval-mode-menu.tsx@@ -18,7 +18,11 @@ import {syncApprovalModeForProfile} from '@/store/approval-mode'-export function useApprovalModeStatusbarItem(profile: string, requestGateway: ApprovalModeRequester): StatusbarItem {+export function useApprovalModeStatusbarItem(+ profile: string,+ requestGateway: ApprovalModeRequester,+ gatewayState: string+): StatusbarItem {const { t } = useI18n()const copy = t.shell.approvalModeconst modes = useStore($approvalModes)@@ -39,8 +43,18 @@ export function useApprovalModeStatusbarItem(profile: string, requestGateway: Ap)useEffect(() => {+ // The shell (and this chip) mount before the gateway socket opens at+ // boot, and a sync issued that early rejects with "Hermes gateway+ // unavailable" — the swallow below then leaves the chip on its+ // optimistic 'smart' default until some later session event reconciles+ // it. Gate on the open socket and re-run when it opens (or a reconnect+ // lands), the same way useStatusSnapshot does.+ if (gatewayState !== 'open') {+ return+ }+void syncApprovalModeForProfile(requestGateway, profile).catch(() => undefined)- }, [profile, requestGateway])+ }, [gatewayState, profile, requestGateway])return {className: mode === 'off' ? 'bg-(--chrome-action-hover) text-foreground' : undefined,diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsxindex ca3ce5deb2b..f8bfa0a16c6 100644--- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx+++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx@@ -352,7 +352,7 @@ export function useStatusbarItems({[activeGatewayProfile])- const approvalModeItem = useApprovalModeStatusbarItem(activeGatewayProfile, requestApprovalModeGateway)+ const approvalModeItem = useApprovalModeStatusbarItem(activeGatewayProfile, requestApprovalModeGateway, gatewayState)const systemResourcesItem = useSystemResourcesStatusbarItem()const gatewayMenuContent = useMemo(