Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): surface session API errors, and stop deferring sidecar upgrades (#356)
Louis Amaudruz6bba5cd75625
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.tsindex f27a297f9..be78b58be 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts@@ -21,7 +21,7 @@ import {sessionChangedChannel,} from '@shared/core/sessions/sessionEvents';import { dbContextResolver } from './db-context-resolver';-import { deriveAgentStatus } from './derive-agent-status';+import { deriveAgentStatus, deriveErrorDetail } from './derive-agent-status';import { parseHookEvent } from './event-enricher';import { HookServer, type RawHookRequest } from './hook-server';import { isAppFocused, maybeShowNotification } from './notification';@@ -34,7 +34,7 @@ function determineSoundEvent(event: AgentEvent,status: AgentStatus): 'needs_attention' | 'session_complete' | undefined {- if (status === 'awaiting-input') return 'needs_attention';+ if (status === 'awaiting-input' || status === 'error') return 'needs_attention';if (status === 'completed' && event.type === 'stop') return 'session_complete';return undefined;}@@ -210,7 +210,12 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo// ipcMain), so an in-process emit never reaches an in-process listener — the// poller would otherwise never observe a turn finishing and would release// its gate only via the 60s fallback.- switchNotificationPoller.onAgentStatusChange(event.sessionId, status, notificationType);+ switchNotificationPoller.onAgentStatusChange(+ event.sessionId,+ status,+ notificationType,+ deriveErrorDetail(event)+ );await db.update(sessions)diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.test.tsindex 256eca967..848b7aa15 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';import type { AgentEvent } from '@shared/core/providers/agentEvents';-import { deriveAgentStatus } from './derive-agent-status';+import { deriveAgentStatus, deriveErrorDetail } from './derive-agent-status';function event(partial: Partial<AgentEvent> & Pick<AgentEvent, 'type'>): AgentEvent {return {@@ -33,3 +33,21 @@ describe('deriveAgentStatus', () => {expect(deriveAgentStatus(event({ type: 'notification', payload: {} }))).toBeNull();});});++describe('deriveErrorDetail', () => {+ it('returns the error message for an error event', () => {+ expect(+ deriveErrorDetail(+ event({ type: 'error', payload: { message: 'authentication_failed — token expired' } })+ )+ ).toBe('authentication_failed — token expired');+ });++ it('returns undefined for an error with no message and for other events', () => {+ expect(deriveErrorDetail(event({ type: 'error', payload: { message: ' ' } }))).toBeUndefined();+ expect(deriveErrorDetail(event({ type: 'error', payload: {} }))).toBeUndefined();+ expect(+ deriveErrorDetail(event({ type: 'stop', payload: { message: 'done' } }))+ ).toBeUndefined();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.tsindex ce06d5208..46f301970 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/derive-agent-status.ts@@ -20,3 +20,15 @@ export function deriveAgentStatus(event: AgentEvent): AgentStatus | null {}return null;}++/**+ * The reason line for an `error` event, for surfacing on the bridged channel+ * beside the session deeplink. Undefined for every other event, and for an+ * error the provider reported without any detail. Pure, for the same reason+ * `deriveAgentStatus` is.+ */+export function deriveErrorDetail(event: AgentEvent): string | undefined {+ if (event.type !== 'error') return undefined;+ const message = event.payload.message?.trim();+ return message ? message : undefined;+}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.tsindex a81efcb6f..016d40738 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts@@ -383,19 +383,53 @@ describe('RemoteSidecarLauncher versioning', () => {expect(await makeLauncher(host).probeExisting()).toEqual(ENDPOINT);});- it('defers an available upgrade while the sidecar has live sessions', async () => {+ it('takes an upgrade within the major even while sessions are live', async () => {+ // Live sessions used to hold this back, which left the busiest hosts — the+ // ones most likely to need the fix — on a stale build indefinitely. The+ // restart costs a few seconds of room injection: panes are separate tmux+ // sessions, agents re-read the endpoint file, and the durable state+ // re-adopts each pane's room on boot.const { host, calls } = makeHost({existingSidecar: true,readyHash: 'hash-old',liveSessions: 2,});+ await makeLauncher(host).deployAndLaunch();++ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);+ });++ it('defers a MAJOR upgrade while the sidecar has live sessions', async () => {+ // A major is where the durable state schema may move, and a sidecar refuses+ // to read state written by a newer one — so a major taken under live+ // sessions risks stranding the sessions it was meant to carry.+ const { host, calls } = makeHost({+ existingSidecar: true,+ readyHash: 'hash-old',+ readyVersion: '0.9',+ liveSessions: 2,+ });+const endpoint = await makeLauncher(host).deployAndLaunch();expect(endpoint).toEqual(ENDPOINT);expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(false);});+ it('takes a major upgrade once the sidecar is idle', async () => {+ const { host, calls } = makeHost({+ existingSidecar: true,+ readyHash: 'hash-old',+ readyVersion: '0.9',+ liveSessions: 0,+ });++ await makeLauncher(host).deployAndLaunch();++ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);+ });+it('takes the upgrade once the sidecar is idle', async () => {const { host, calls } = makeHost({existingSidecar: true,diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.tsindex 53182fb44..07ce46f22 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts@@ -17,6 +17,7 @@ import {} from '../../../../sidecar/sidecar-paths';import {compareSidecarVersions,+ isMajorUpgrade,MIN_SUPPORTED_SIDECAR_MAJOR,SIDECAR_CLIENT_MAJOR,SIDECAR_VERSION,@@ -632,10 +633,18 @@ export class RemoteSidecarLauncher {* it would be a downgrade.* - same version, another install's build → reattach; neither of us can claim* to be the upgrade, so whoever got there first keeps it.- * - different build, no live sessions → upgrade, since nothing is disturbed.- * - different build, live sessions → reattach and record that an upgrade is- * pending, rather than interrupting work in flight for a build difference.- * The next launch with an idle sidecar picks it up.+ * - different build within the same major → upgrade, live sessions or not.+ * A restart costs a few seconds of room injection and nothing else: agent+ * panes are separate tmux sessions, running agents re-read the port and+ * token from the endpoint file, and the durable state re-adopts each pane's+ * room on boot. Waiting for an idle sidecar instead meant a busy host — the+ * one being used, and so the one most likely to hit whatever the upgrade+ * fixes — could sit on a stale build indefinitely.+ * - a major bump with live sessions → reattach and record that an upgrade is+ * pending. A major is where the durable state schema may move, and a+ * sidecar refuses to read state written by a newer one, so taking it under+ * live sessions risks stranding them. The next launch with an idle sidecar+ * picks it up, or the operator's Restart takes it deliberately.*/private async decideExisting(localHash: string): Promise<SidecarEndpoint | null> {const ready = await this.readRunning();@@ -694,21 +703,27 @@ export class RemoteSidecarLauncher {return this.toEndpoint(ready);}- const liveSessions = await this.runningSessionCount();- if (liveSessions > 0) {- this.log.warn(- 'RemoteSidecarLauncher: sidecar upgrade pending — deferring while sessions run',- {- sidecarTmuxName: this.sidecarTmuxName,- runningHash: ready.hash,- localHash,- liveSessions,- }- );- return this.toEndpoint(ready);+ if (isMajorUpgrade(ready.version, SIDECAR_VERSION)) {+ const liveSessions = await this.runningSessionCount();+ if (liveSessions > 0) {+ this.log.warn(+ 'RemoteSidecarLauncher: major sidecar upgrade pending — deferring while sessions run',+ {+ sidecarTmuxName: this.sidecarTmuxName,+ runningVersion: ready.version,+ clientVersion: SIDECAR_VERSION,+ runningHash: ready.hash,+ localHash,+ liveSessions,+ }+ );+ return this.toEndpoint(ready);+ }}- this.log.debug('RemoteSidecarLauncher: upgrading idle sidecar to the current bundle', {+ this.log.debug('RemoteSidecarLauncher: upgrading sidecar to the current bundle', {sidecarTmuxName: this.sidecarTmuxName,+ runningVersion: ready.version,+ clientVersion: SIDECAR_VERSION,runningHash: ready.hash,localHash,});diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.tsindex 20ede005d..bd748a423 100644--- a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts@@ -43,8 +43,17 @@ describe('verdictFor', () => {expect(verdict({ hash: 'other', version: '1.6' })).toBe('upgrade-available');});- it('upgrade-pending when a different build is running but busy', () => {- expect(verdict({ hash: 'other', liveSessions: 3 })).toBe('upgrade-pending');+ it('upgrade-available when a busy sidecar is only a build behind', () => {+ // Live sessions survive the restart, so they no longer hold an upgrade back.+ expect(verdict({ hash: 'other', liveSessions: 3 })).toBe('upgrade-available');+ });++ it('upgrade-pending when a busy sidecar is a MAJOR behind', () => {+ expect(verdict({ hash: 'other', version: '0.9', liveSessions: 3 })).toBe('upgrade-pending');+ });++ it('upgrade-available for a major bump once the sidecar is idle', () => {+ expect(verdict({ hash: 'other', version: '0.9', liveSessions: 0 })).toBe('upgrade-available');});it('newer-on-host rather than offering a downgrade', () => {diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.tsindex 768d2b9e6..b496161f7 100644--- a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts@@ -1,6 +1,6 @@import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import type { SidecarVerdict } from '@shared/events/sidecarEvents';-import { compareSidecarVersions } from '../../../sidecar/sidecar-version';+import { compareSidecarVersions, isMajorUpgrade } from '../../../sidecar/sidecar-version';/** What this client ships, and who it is — the other half of the comparison. */export interface SidecarClientBuild {@@ -37,5 +37,12 @@ export function verdictFor(status: SidecarRunStatus, client: SidecarClientBuild)if (order === 0 && status.deployerId !== null && status.deployerId !== client.deployerId) {return 'other-install';}- return status.liveSessions > 0 ? 'upgrade-pending' : 'upgrade-available';+ // Live sessions no longer hold an upgrade back on their own — the launcher+ // takes one through a restart, which costs a few seconds of room injection.+ // Only a major bump waits for an idle sidecar, because that is where the+ // durable state schema may move.+ if (status.liveSessions > 0 && isMajorUpgrade(status.version, client.version)) {+ return 'upgrade-pending';+ }+ return 'upgrade-available';}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.tsindex ebcf6ff59..d40fd01df 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.test.ts@@ -669,6 +669,61 @@ describe('RoomConnection', () => {conn.stop();});+ it('reports an error as awaiting-input carrying the reason', async () => {+ const target: InjectionTarget = { write: vi.fn() };+ const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);+ await flush();++ conn.onAgentStatusChange('error', undefined, 'authentication_failed — expired');+ await flush();++ expect(runtimeStates(fetchMock)).toContain('awaiting-input');+ expect(runtimeDetails(fetchMock)).toContain('authentication_failed — expired');+ conn.stop();+ });++ it('does not ping again for the idle prompt that follows an error', async () => {+ // Claude reports its ready prompt as one more request for input seconds+ // after the failure. Passed on, that is a second reasonless ping that+ // buries the one naming the error.+ const target: InjectionTarget = { write: vi.fn() };+ const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);+ await flush();++ conn.onAgentStatusChange('error', undefined, 'server_error — upstream 503');+ await flush();+ conn.onAgentStatusChange('awaiting-input', 'idle_prompt');+ await flush();++ const awaiting = fetchMock.mock.calls+ .filter((c) => String(c[0]).includes('/runtime-state'))+ .map((c) => JSON.parse((c[1] as RequestInit).body as string))+ .filter((b) => b.state === 'awaiting-input');+ expect(awaiting).toHaveLength(1);+ expect(awaiting[0].detail).toBe('server_error — upstream 503');+ conn.stop();+ });++ it('pings again for a genuine request for input once work has resumed', async () => {+ const target: InjectionTarget = { write: vi.fn() };+ const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);+ await flush();++ conn.onAgentStatusChange('error', undefined, 'rate_limit');+ await flush();+ conn.onAgentStatusChange('working');+ await flush();+ conn.onAgentStatusChange('awaiting-input', 'permission_prompt');+ await flush();++ const awaiting = fetchMock.mock.calls+ .filter((c) => String(c[0]).includes('/runtime-state'))+ .map((c) => JSON.parse((c[1] as RequestInit).body as string))+ .filter((b) => b.state === 'awaiting-input');+ expect(awaiting).toHaveLength(2);+ conn.stop();+ });+it('stops posting after stop()', async () => {const target: InjectionTarget = { write: vi.fn() };const { conn, fetchMock } = connect({ acquire: () => target }, [messageEvent(true)]);diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.tsindex 526e1a895..f31f8ddd1 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts@@ -280,6 +280,9 @@ export class RoomConnection {private busy = false;/** Last runtime state we pushed to the bridge, to avoid redundant calls. */private runtimeState: RuntimeState = 'idle';+ /** Why the current `awaiting-input` was reported, when it was an error. Null+ * for an ordinary request for input, and cleared as soon as work resumes. */+ private awaitingReason: string | null = null;/*** True while the session is handling a turn kicked off by an addressed room* message. Only then does runtime state surface to the room — local TUI work@@ -836,7 +839,11 @@ export class RoomConnection {* room while a room-triggered turn is active — local TUI work must not show* "working on it" in the bridged channel, nor ping the operator.*/- onAgentStatusChange(status: AgentStatus, notificationType?: NotificationType): void {+ onAgentStatusChange(+ status: AgentStatus,+ notificationType?: NotificationType,+ detail?: string+ ): void {if (this.stopped) return;if (toRuntimeState(status) === 'awaiting-input') {this.log.debug('RoomConnection: status -> awaiting-input', {@@ -850,7 +857,7 @@ export class RoomConnection {}if (this.roomTurnActive) {const next = toRuntimeState(status);- this.setRuntimeState(next);+ this.setRuntimeState(next, detail);if (next === 'idle') {this.roomTurnActive = false;this.currentThreadId = null;@@ -875,13 +882,27 @@ export class RoomConnection {this.tryFlush();}- private setRuntimeState(state: RuntimeState): void {+ private setRuntimeState(state: RuntimeState, detail?: string): void {// `awaiting-input` always re-surfaces: each report is a fresh request for// operator input (Claude emits one per notification, not on a timer), so it// must ping again even when the previous state was already awaiting-input —// e.g. a follow-up prompt with no intervening `working` event we observed.// `working`/`idle` stay deduped: one "working on it…" / one clear is enough.if (state !== 'awaiting-input' && this.runtimeState === state) return;+ // The exception to that: a session that just died on an error goes quiet at+ // its prompt, and Claude reports the idle prompt as one more request for+ // input. Reported as-is that is a second, reasonless ping seconds after the+ // one naming the failure — it reads as a new request and buries the reason.+ // The turn is still the errored one until work resumes, so say nothing more+ // until it does.+ if (state === 'awaiting-input' && this.awaitingReason !== null && !detail) {+ this.log.debug('RoomConnection: awaiting-input with no reason follows an error — skipping', {+ roomId: this.roomId,+ reason: this.awaitingReason,+ });+ return;+ }+ this.awaitingReason = state === 'awaiting-input' ? (detail ?? null) : null;const wasWorking = this.runtimeState === 'working';this.runtimeState = state;// A fresh state clears the activity line: a new "working" turn starts from@@ -900,7 +921,7 @@ export class RoomConnection {return;}this.stopActivityTicker();- void this.postRuntimeState(state, this.currentThreadId).catch((error) => {+ void this.postRuntimeState(state, this.currentThreadId, {}, detail).catch((error) => {if (this.abort.signal.aborted) return;this.log.warn('RoomConnection: failed to set runtime state', {roomId: this.roomId,diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.tsindex 124e0fd96..278e7ce92 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/switch-notification-poller.ts@@ -333,11 +333,12 @@ class SwitchNotificationPoller {onAgentStatusChange(sessionId: string,status: AgentStatus,- notificationType?: NotificationType+ notificationType?: NotificationType,+ detail?: string): void {const connection = this.connections.get(sessionId);if (!connection) return;- connection.onAgentStatusChange(status, notificationType);+ connection.onAgentStatusChange(status, notificationType, detail);}/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsxindex a62becd03..472b7ede4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx@@ -162,9 +162,9 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {{data.verdict === 'other-install' &&'Another Switch Console install on this host deployed the running sidecar, from the same release as yours. Neither build is newer, so this one leaves it alone rather than the two of you replacing it in turn. Use Restart to run your build instead — the other install will then leave yours alone.'}{data.verdict === 'upgrade-pending' &&- `An update is ready but held back because ${data.liveSessions} session${+ `A major update is ready but held back because ${data.liveSessions} session${data.liveSessions === 1 ? ' is' : 's are'- } running. It applies next time the sidecar is idle — or use Restart to apply it now (running sessions reconnect automatically).`}+ } running — a major version can change the state format those sessions are recorded in. It applies next time the sidecar is idle — or use Restart to apply it now (running sessions reconnect automatically).`}</p><Buttondiff --git a/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts b/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.tsindex 15de528eb..933df4584 100644--- a/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts+++ b/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts@@ -6,10 +6,13 @@ import { defineEvent } from '@shared/lib/ipc/events';** - `not-running` — no sidecar is up on the host.* - `up-to-date` — the host runs this client's exact build.- * - `upgrade-available` — a different build is running and can be replaced now- * (the sidecar is idle).- * - `upgrade-pending` — a different build is running but has live sessions, so- * the upgrade is deferred until it is idle rather than interrupting work.+ * - `upgrade-available` — a different build is running and can be replaced now.+ * Live sessions do not hold this back: they survive the restart, losing only+ * a few seconds of room injection.+ * - `upgrade-pending` — a build one MAJOR ahead is ready but the sidecar has+ * live sessions, so it is deferred until idle. A major is where the durable+ * state schema may move, and a sidecar refuses to read state written by a+ * newer one, so taking it under live sessions risks stranding them.* - `newer-on-host` — a newer Switch Console deployed the running sidecar. There is* nothing to offer: replacing it would be a downgrade, and on a shared host* two installs doing that to each other never converges.diff --git a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.tsindex e5b593fd7..0db590abe 100644--- a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts+++ b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts@@ -219,10 +219,33 @@ describe('SidecarRuntime (multi-session)', () => {await runtime.handleHook(switchRoomHook('room-2', PTY_B));await runtime.handleHook(statusHook('start', PTY_A));- expect(created[0].conn.onAgentStatusChange).toHaveBeenCalledWith('working', undefined);+ expect(created[0].conn.onAgentStatusChange).toHaveBeenCalledWith(+ 'working',+ undefined,+ undefined+ );expect(created[1].conn.onAgentStatusChange).not.toHaveBeenCalled();});+ it('forwards the failure reason with an error status', async () => {+ const { runtime, created } = makeRuntime();+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));+ await runtime.handleHook({+ ptyId: PTY_A,+ type: 'stop-failure',+ body: JSON.stringify({+ error_type: 'authentication_failed',+ error_message: 'credentials have expired',+ }),+ });++ expect(created[0].conn.onAgentStatusChange).toHaveBeenCalledWith(+ 'error',+ undefined,+ 'authentication_failed — credentials have expired'+ );+ });+it('reports a room live only while its pane is up', async () => {const { runtime } = makeRuntime();await runtime.handleHook(switchRoomHook('room-1', PTY_A));diff --git a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.tsindex 34c2764a8..64a81a780 100644--- a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts+++ b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts@@ -1,6 +1,6 @@import * as os from 'node:os';import * as path from 'node:path';-import { deriveAgentStatus } from '@main/core/agent-hooks/derive-agent-status';+import { deriveAgentStatus, deriveErrorDetail } from '@main/core/agent-hooks/derive-agent-status';import type { ContextResolver, ParsedHookEvent } from '@main/core/agent-hooks/event-enricher';import { parseHookEvent } from '@main/core/agent-hooks/event-enricher';import type { RawHookRequest } from '@main/core/agent-hooks/hook-server';@@ -24,7 +24,8 @@ export interface ManagedConnection {stop(): void;onAgentStatusChange(status: Parameters<RoomConnection['onAgentStatusChange']>[0],- notificationType?: Parameters<RoomConnection['onAgentStatusChange']>[1]+ notificationType?: Parameters<RoomConnection['onAgentStatusChange']>[1],+ detail?: Parameters<RoomConnection['onAgentStatusChange']>[2]): void;reportActivity(detail: string): void;/** The connection id this session's tool calls are expected to arrive on. */@@ -183,7 +184,11 @@ export class SidecarRuntime {parsed.event.type === 'notification' ? parsed.event.payload.notificationType : undefined;// Route to the session the event came from — not every connection.const session = this.sessions.get(parsed.event.sessionId);- session?.connection.onAgentStatusChange(status, notificationType);+ session?.connection.onAgentStatusChange(+ status,+ notificationType,+ deriveErrorDetail(parsed.event)+ );return;}diff --git a/console/apps/switch-console-desktop/src/sidecar/sidecar-version.ts b/console/apps/switch-console-desktop/src/sidecar/sidecar-version.tsindex 164b0c021..2d3fb7a50 100644--- a/console/apps/switch-console-desktop/src/sidecar/sidecar-version.ts+++ b/console/apps/switch-console-desktop/src/sidecar/sidecar-version.ts@@ -62,6 +62,23 @@ export function sidecarMajor(version: string | null): number {return Number.isFinite(major) ? major : 0;}+/**+ * Whether replacing a sidecar on `runningVersion` with this build crosses a+ * major — the one upgrade that waits for the sidecar to go idle rather than+ * taking live sessions through a restart.+ *+ * A major is where the durable state schema may move, and a sidecar refuses to+ * read state written by a newer one, so a half-taken major upgrade can strand+ * the sessions it was meant to carry. Everything below a major is a few seconds+ * of lost room injection, which is not worth deferring for.+ *+ * The launcher's deploy policy and the settings panel's verdict both ask this,+ * so they cannot drift into offering an Update that does nothing.+ */+export function isMajorUpgrade(runningVersion: string | null, clientVersion: string): boolean {+ return sidecarMajor(clientVersion) > sidecarMajor(runningVersion);+}+/*** A version as numbers; a missing or unparseable part reads as 0.*diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts b/console/packages/core/src/agents/plugins/capabilities/hooks-types.tsindex e62c27b5a..8112bdbbb 100644--- a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts+++ b/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts@@ -1,6 +1,7 @@export const HOOK_EVENTS = ['notification','stop',+ 'stop-failure','session','start','tool-use',diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks.ts b/console/packages/core/src/agents/plugins/capabilities/hooks.tsindex fa0838fd9..0252cfa8c 100644--- a/console/packages/core/src/agents/plugins/capabilities/hooks.ts+++ b/console/packages/core/src/agents/plugins/capabilities/hooks.ts@@ -1,6 +1,7 @@import z from 'zod';import { definePluginCapability } from '../../../lib/plugins/capability';import type { PluginFs } from '../../runtime/fs';+import { HOOK_EVENTS } from './hooks-types';import type { CanonicalHookEvent, HookCommandOptions, HookRegistration } from './hooks-types';export type { HookRegistration };@@ -43,19 +44,7 @@ export const hooksCapability = definePluginCapability<IHooksBehavior>()(z.object({kind: z.literal('config'),scope: z.enum(['global', 'workspace']),- supportedEvents: z.array(- z.enum([- 'notification',- 'stop',- 'session',- 'start',- 'tool-use',- 'tool-done',- 'tool-use-failure',- 'subagent',- 'subagent-done',- ])- ),+ supportedEvents: z.array(z.enum(HOOK_EVENTS)),/*** Whether the agent fires a hook when its session comes up, before any* turn. That signal is what tells Switch Console a spawned session is@@ -69,19 +58,7 @@ export const hooksCapability = definePluginCapability<IHooksBehavior>()(z.object({kind: z.literal('plugin'),scope: z.enum(['global', 'workspace']),- supportedEvents: z.array(- z.enum([- 'notification',- 'stop',- 'session',- 'start',- 'tool-use',- 'tool-done',- 'tool-use-failure',- 'subagent',- 'subagent-done',- ])- ),+ supportedEvents: z.array(z.enum(HOOK_EVENTS)),/*** Whether the agent fires a hook when its session comes up, before any* turn. That signal is what tells Switch Console a spawned session isdiff --git a/console/packages/core/src/agents/plugins/helpers/parse-hook-event.test.ts b/console/packages/core/src/agents/plugins/helpers/parse-hook-event.test.tsnew file mode 100644index 000000000..eae984e51--- /dev/null+++ b/console/packages/core/src/agents/plugins/helpers/parse-hook-event.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';+import { defaultHookEventParser } from './parse-hook-event';++describe('defaultHookEventParser', () => {+ it('maps stop-failure to an error carrying the reason', () => {+ expect(+ defaultHookEventParser('stop-failure', {+ error_type: 'authentication_failed',+ error_message: 'Vertex AI\n credentials have expired',+ })+ ).toEqual({+ kind: 'status',+ type: 'error',+ title: 'authentication_failed',+ message: 'authentication_failed — Vertex AI credentials have expired',+ });+ });++ it('never surfaces an empty error when the provider omits a half', () => {+ expect(defaultHookEventParser('stop-failure', { error_type: 'rate_limit' })).toMatchObject({+ message: 'rate_limit',+ });+ expect(defaultHookEventParser('stop-failure', { error_message: 'upstream 503' })).toMatchObject(+ { message: 'upstream 503' }+ );+ expect(defaultHookEventParser('stop-failure', {})).toMatchObject({+ type: 'error',+ message: 'the turn ended on an error',+ });+ });+});diff --git a/console/packages/core/src/agents/plugins/helpers/parse-hook-event.ts b/console/packages/core/src/agents/plugins/helpers/parse-hook-event.tsindex 4c294140d..ba8e8075d 100644--- a/console/packages/core/src/agents/plugins/helpers/parse-hook-event.ts+++ b/console/packages/core/src/agents/plugins/helpers/parse-hook-event.ts@@ -13,6 +13,20 @@ function asNotificationType(value: unknown): NotificationType | undefined {: undefined;}+/**+ * The human-readable reason a turn died, from a stop-failure body: the provider+ * stamps an `error_type` (`authentication_failed`, `rate_limit`, `billing_error`,+ * `server_error`, …) alongside a message. Either may be absent, so fall back to+ * a generic phrase rather than surfacing an empty error.+ */+function stopFailureDetail(body: Record<string, unknown>): string {+ const type = typeof body.error_type === 'string' ? body.error_type.trim() : '';+ const raw = typeof body.error_message === 'string' ? body.error_message.trim() : '';+ const message = raw.replace(/\s+/g, ' ').slice(0, 300);+ if (type && message) return `${type} — ${message}`;+ return type || message || 'the turn ended on an error';+}+/** Extract the first non-empty string from a list of candidates. */export function extractProviderSessionId(body: Record<string, unknown>): string | undefined {const candidates = [@@ -50,6 +64,15 @@ export function defaultHookEventParser(return { kind: 'ignore' };}+ if (eventType === 'stop-failure') {+ return {+ kind: 'status',+ type: 'error',+ title: typeof body.error_type === 'string' ? body.error_type : undefined,+ message: stopFailureDetail(body),+ };+ }+if (eventType === 'start' || eventType === 'stop' || eventType === 'error') {const rawLam = body.last_assistant_message ?? body.lastAssistantMessage;return {diff --git a/console/packages/plugins/src/agents/impl/claude/hooks.test.ts b/console/packages/plugins/src/agents/impl/claude/hooks.test.tsindex aee873ca9..363977ec8 100644--- a/console/packages/plugins/src/agents/impl/claude/hooks.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/hooks.test.ts@@ -164,6 +164,38 @@ describe('buildClaudeHookConfig', () => {});});+ it('registers StopFailure, whose parse is delegated to the generic parser', async () => {+ const fs = createMemoryFs();+ await buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' });++ const settings = JSON.parse((await fs.read(CLAUDE_SETTINGS_PATH))!) as {+ hooks: Record<string, NestedHookEntry[]>;+ };+ expect(settings.hooks.StopFailure).toHaveLength(1);++ const { parseHookEvent } = buildClaudeHookConfig();+ expect(+ parseHookEvent('stop-failure', {+ error_type: 'authentication_failed',+ error_message: 'Vertex AI\n credentials have expired',+ })+ ).toEqual({+ kind: 'status',+ type: 'error',+ title: 'authentication_failed',+ message: 'authentication_failed — Vertex AI credentials have expired',+ });++ // Either half may be missing; never surface an empty error.+ expect(parseHookEvent('stop-failure', { error_type: 'rate_limit' })).toMatchObject({+ message: 'rate_limit',+ });+ expect(parseHookEvent('stop-failure', {})).toMatchObject({+ type: 'error',+ message: 'the turn ended on an error',+ });+ });+it('leaves matcher-less hooks (Stop) without a matcher field', async () => {const fs = createMemoryFs();await buildClaudeHookConfig().writeHooks(fs, [], { platform: 'linux' });diff --git a/console/packages/plugins/src/agents/impl/claude/hooks.ts b/console/packages/plugins/src/agents/impl/claude/hooks.tsindex 6afbe0ef2..8ed9896f7 100644--- a/console/packages/plugins/src/agents/impl/claude/hooks.ts+++ b/console/packages/plugins/src/agents/impl/claude/hooks.ts@@ -161,6 +161,11 @@ export function buildClaudeHookConfig() {{ hookKey: 'UserPromptSubmit', command: makeStdinHookCommand('start') },{ hookKey: 'Notification', command: makeStdinHookCommand('notification') },{ hookKey: 'Stop', command: makeStdinHookCommand('stop') },+ // A turn that died on an API error (expired credentials, quota, provider+ // outage) fires StopFailure instead of Stop. Without it such a session is+ // indistinguishable from one that finished cleanly, and the operator sees+ // silence rather than a reason.+ { hookKey: 'StopFailure', command: makeStdinHookCommand('stop-failure') },// Switch room detection: report the room a session connects to so// Switch Console can surface membership and drive notification injection.{diff --git a/console/packages/plugins/src/agents/impl/claude/index.ts b/console/packages/plugins/src/agents/impl/claude/index.tsindex b9af0d483..e80cdb438 100644--- a/console/packages/plugins/src/agents/impl/claude/index.ts+++ b/console/packages/plugins/src/agents/impl/claude/index.ts@@ -32,6 +32,7 @@ export const plugin = definePlugin('start','notification','stop',+ 'stop-failure','tool-use','tool-done','tool-use-failure',diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex f5c5e24e8..47f2629f9 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -484,7 +484,12 @@ class CollaborationAdapter(ABC):elif state == "awaiting-input":await self.send_typing(channel_id, agent_name, True)await self._ping_operator(- channel_id, agent_name, mention_handle, thread_root_id, deeplink_url+ channel_id,+ agent_name,+ mention_handle,+ thread_root_id,+ deeplink_url,+ detail,)else:await self.send_typing(channel_id, agent_name, False)@@ -581,8 +586,14 @@ class CollaborationAdapter(ABC):mention_handle: str | None,thread_root_id: str | None,deeplink_url: str | None = None,+ detail: str | None = None,) -> str | None:- """Post a message nudging the operator that the agent needs input.+ """Post a message nudging the operator that the agent needs attention.++ ``detail``, when set, is the reason the session stalled — an API or auth+ failure the agent cannot recover from on its own. It replaces the+ generic "needs your input" wording so the operator knows what is wrong+ before clicking through.`mention_handle` is the agent owner's account on this platform, or Nonewhen there is nobody to reach — no owner, or an owner who has not said@@ -592,11 +603,14 @@ class CollaborationAdapter(ABC):Returns the posted message ref so callers that can remove it (Slack,Mattermost) track it for cleanup when the turn ends."""+ reason = detail.strip() if detail and detail.strip() else ""+ need = f"hit an error: {reason}" if reason else "needs your input"+ lead = "⚠️ " if reason else ""if mention_handle:- text = f"@{mention_handle} **{agent_name}** needs your input."+ text = f"@{mention_handle} {lead}**{agent_name}** {need}."else:text = (- f"**{agent_name}** needs your input — but nobody here is linked "+ f"{lead}**{agent_name}** {need} — but nobody here is linked "f"to its owner, so this pings no one. Link your "f"{self.platform_name} account in Switch Console to be notified.")diff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex f794c625c..0285b23ee 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -652,7 +652,12 @@ class DiscordAdapter(CollaborationAdapter):)elif state == "awaiting-input":ref = await self._ping_operator(- channel_id, agent_name, mention_handle, thread_root_id, deeplink_url+ channel_id,+ agent_name,+ mention_handle,+ thread_root_id,+ deeplink_url,+ detail,)if ref is not None:self._input_pings.setdefault(key, []).append(ref)diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.pyindex cf9875071..f415c0dc6 100644--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py@@ -565,7 +565,12 @@ class MattermostAdapter(CollaborationAdapter):await self._post_typing(channel_id, agent_name, trigger_thread_root_id)elif state == "awaiting-input":ref = await self._ping_operator(- channel_id, agent_name, mention_handle, thread_root_id, deeplink_url+ channel_id,+ agent_name,+ mention_handle,+ thread_root_id,+ deeplink_url,+ detail,)if ref is not None:self._input_pings.setdefault(key, []).append(ref)diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex 326145513..3c3b7bde3 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -786,7 +786,12 @@ class SlackAdapter(CollaborationAdapter):elif state == "awaiting-input":# Leave the working indicator up; add a ping and track it.ref = await self._ping_operator(- channel_id, agent_name, mention_handle, thread_root_id, deeplink_url+ channel_id,+ agent_name,+ mention_handle,+ thread_root_id,+ deeplink_url,+ detail,)if ref is not None:self._input_pings.setdefault(key, []).append(ref)@@ -977,12 +982,16 @@ class SlackAdapter(CollaborationAdapter):else:self._session_owner.pop(key, None)+ # A detail on `awaiting-input` is the reason a turn died, not a step the+ # agent is taking. Streamed unmarked it reads as progress — a spinner+ # over "the turn ended on an error" — so it is flagged as the stall it is.+ step_detail = f"⚠️ {detail}" if state == "awaiting-input" and detail else detailawait self._drive_stream(channel_id,thread_ts,agent_name,working=working,- detail=detail,+ detail=step_detail,deeplink_url=deeplink_url,)diff --git a/core/switch_core/bridges/collaboration/teams/adapter.py b/core/switch_core/bridges/collaboration/teams/adapter.pyindex e832ed35f..463316cc3 100644--- a/core/switch_core/bridges/collaboration/teams/adapter.py+++ b/core/switch_core/bridges/collaboration/teams/adapter.py@@ -1021,7 +1021,12 @@ class TeamsAdapter(CollaborationAdapter):)elif state == "awaiting-input":ref = await self._ping_operator(- channel_id, agent_name, mention_handle, thread_root_id, deeplink_url+ channel_id,+ agent_name,+ mention_handle,+ thread_root_id,+ deeplink_url,+ detail,)if ref is not None:self._input_pings.setdefault(key, []).append(ref)diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 15ad9641f..9c1503941 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -673,6 +673,54 @@ def test_runtime_state_detail_edits_message_in_place() -> None:assert adapter._working_msg[("C123", "agent-bot")].message_ref == "C123:999.9"+def test_runtime_state_awaiting_input_pings_operator() -> None:+ adapter = _adapter()+ fake = _FakeWebClient()+ adapter._web_client = fake # type: ignore[assignment]++ _run(+ adapter.apply_runtime_state(+ "C123",+ "agent-bot",+ "awaiting-input",+ mention_handle="louis",+ thread_root_id=None,+ deeplink_url="https://gw.example/deeplink/session?x=1",+ )+ )++ assert len(fake.calls) == 1+ assert "needs your input" in fake.calls[0]["text"]+ assert "gw.example/deeplink/session" in fake.calls[0]["text"]+++def test_runtime_state_awaiting_input_with_detail_names_the_error() -> None:+ # A stalled session (expired credentials, quota, provider outage) reports+ # awaiting-input with the reason — the ping must say what broke, not the+ # generic "needs your input", and still carry the session link.+ adapter = _adapter()+ fake = _FakeWebClient()+ adapter._web_client = fake # type: ignore[assignment]++ _run(+ adapter.apply_runtime_state(+ "C123",+ "agent-bot",+ "awaiting-input",+ mention_handle="louis",+ thread_root_id=None,+ deeplink_url="https://gw.example/deeplink/session?x=1",+ detail="authentication_failed — credentials have expired",+ )+ )++ assert len(fake.calls) == 1+ text = fake.calls[0]["text"]+ assert "hit an error: authentication_failed — credentials have expired" in text+ assert "needs your input" not in text+ assert "gw.example/deeplink/session" in text++def test_runtime_state_idle_clears_working_message() -> None:adapter = _adapter()fake = _FakeWebClient()diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.py b/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.pyindex c72c17626..dbf0220be 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.py@@ -259,6 +259,31 @@ def test_the_same_activity_is_not_sent_twice() -> None:assert len(_chunks(client)) == 1+def test_a_stalled_turn_is_flagged_rather_than_shown_as_progress() -> None:+ """A detail on `awaiting-input` is why the turn died, not a step the agent+ is taking. Unmarked it reads as work in progress."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading the codebase"))+ _run(_state(adapter, "awaiting-input", detail="authentication_failed — expired"))++ assert [c["title"] for c in _chunks(client)] == [+ "reading the codebase",+ "⚠️ authentication_failed — expired",+ ]+++def test_an_ordinary_request_for_input_is_not_flagged() -> None:+ """Only a reason gets the warning mark — a plain request for input keeps+ the generic step it has always had."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading the codebase"))+ _run(_state(adapter, "awaiting-input"))++ assert [c["title"] for c in _chunks(client)] == ["reading the codebase", "Working"]++def test_switch_markup_is_stripped_from_a_step() -> None:"""A card's title is plain text, so markup arrives as literal underscoresand backticks — which is exactly how it looked in the pilot."""