Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Codex gets the Switch skill as instructions; failed turns show their reason (#547)

Louis Amaudruzb1e70170d08a
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/types.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/types.ts
index 524b8f6a1..7db9fa60a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/types.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/types.ts
@@ -2,6 +2,8 @@ import type { Session } from '@shared/core/sessions/sessions';
export interface AgentRuntimeProvider {
startupStatus?(): { status: 'starting' | 'ready' | 'error'; message: string | null };
+ /** The session's host came up after all, so a failed start no longer stands. */
+ hostCameUp?(): void;
restart(session: Session): Promise<void>;
start(session: Session, isResuming?: boolean, initialPrompt?: string): Promise<void>;
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
index c325420c4..a6df2edc4 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/controller.ts
@@ -2,10 +2,10 @@ import type { ClientCommand } from '@switch-console/shared/session-v1';
import { z } from 'zod';
import { getAgentById } from '@main/core/agents/getAgentById';
import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';
-import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { connectionHealth } from './connection-health';
import { sharedAgentDiagnostics, sharedAgentLogs } from './diagnostics';
+import { sessionIssue, sessionStartupStatus } from './host-failures';
import { transcriptSource } from './host-journal';
import { placeSession } from './place-session';
import {
@@ -18,8 +18,8 @@ import { stopSharedSession } from './stop-shared-session';
import { closeTranscript, openTranscript } from './transcripts';
export const sdkHostController = createRPCController({
stop: (agentId: string, sessionId: string) => stopSharedSession(agentId, sessionId),
- startupStatus: (sessionId: string) =>
- sessionRuntimeManager.getAgent(sessionId)?.startupStatus?.() ?? null,
+ startupStatus: (sessionId: string) => sessionStartupStatus(sessionId),
+ sessionIssue: (sessionId: string) => sessionIssue(sessionId),
discoveryErrors: () => remoteSessionReconciler.errors(),
retryDiscovery: (agentId: string) => remoteSessionReconciler.refresh(agentId),
connectionHealth,
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/forget-session.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/forget-session.ts
new file mode 100644
index 000000000..921e33916
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/forget-session.ts
@@ -0,0 +1,41 @@
+import { rm } from 'node:fs/promises';
+import { sharedSessionRoot } from '@switch-console/agent-providers';
+import { getAgentLocation } from '@main/core/agents/agent-location';
+import { getAgentById } from '@main/core/agents/getAgentById';
+import { log } from '@main/lib/logger';
+import { localWatcherControl, stopLocalSession } from './local-host';
+import { withSidecar } from './sidecar-control';
+
+/**
+ * Tell the agent's room watcher that Console deleted one of its sessions.
+ *
+ * Without this the watcher keeps the session as its rooms' session and hands
+ * it their messages, which a deleted session never answers. The watcher takes
+ * its rooms off it, drops what was queued for it, stops its host and removes
+ * its state, so a room's next message starts a new session.
+ */
+export async function forgetSession(agentId: string, sessionId: string): Promise<void> {
+ const agent = await getAgentById(agentId);
+ if (!agent?.switchAgentId) return;
+ if (!(await getAgentLocation(agent)).sshHost) {
+ const watcher = localWatcherControl(agent.switchAgentId);
+ if (watcher.running) return watcher.forget(sessionId);
+ // No watcher running: nothing routes to the session now, and one started
+ // later finds no state behind the room's session and drops it.
+ await stopLocalSession(sessionId);
+ await rm(sharedSessionRoot(sessionId), { recursive: true, force: true });
+ return;
+ }
+ try {
+ await withSidecar(agentId, (client) => client.forget(sessionId));
+ } catch (error) {
+ log.warn(
+ 'The agent sidecar was not told about a deleted session; its rooms may still reach it until the sidecar restarts',
+ {
+ agentId,
+ sessionId,
+ error: String(error),
+ }
+ );
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.test.ts
new file mode 100644
index 000000000..0e61464bc
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.test.ts
@@ -0,0 +1,106 @@
+import type { ChildProcess } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import { sharedSessionRoot } from '@switch-console/agent-providers';
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ runtime: vi.fn(), emit: vi.fn() }));
+vi.mock('@main/lib/events', () => ({ events: { emit: mocks.emit } }));
+vi.mock('@main/core/sessions/session-runtime-manager', () => ({
+ sessionRuntimeManager: { getAgent: mocks.runtime },
+}));
+vi.mock('./local-host', async () => {
+ const { SessionLinks } = await import('@switch-console/agent-providers');
+ return { localSessionLinks: new SessionLinks() };
+});
+
+const { recordRemoteHostFailure, sessionIssue, sessionStartupStatus } =
+ await import('./host-failures');
+const { localSessionLinks } = await import('./local-host');
+
+beforeEach(() => {
+ mocks.runtime.mockReset();
+ mocks.emit.mockReset();
+ mocks.runtime.mockReturnValue(undefined);
+});
+
+it('shows a session the watcher started as failed once its local host stops on a failure', () => {
+ expect(sessionStartupStatus('local-session')).toBeNull();
+ const child = new EventEmitter();
+ localSessionLinks.attach(sharedSessionRoot('local-session'), child as unknown as ChildProcess);
+ child.emit('exit', 1, null);
+ expect(sessionStartupStatus('local-session')).toEqual({
+ status: 'error',
+ message: expect.stringMatching(/^Shared SDK host failed: /),
+ });
+ // Started again, it is no longer shown as failed.
+ localSessionLinks.attach(sharedSessionRoot('local-session'), new EventEmitter() as never);
+ expect(sessionStartupStatus('local-session')).toBeNull();
+});
+
+it('shows the failure the sidecar pushed for a remote session until a host comes up again', () => {
+ recordRemoteHostFailure('remote-session', 'Sign in on the execution machine with codex login.');
+ expect(sessionStartupStatus('remote-session')).toEqual({
+ status: 'error',
+ message: 'Shared SDK host failed: Sign in on the execution machine with codex login.',
+ });
+ recordRemoteHostFailure('remote-session', null);
+ expect(sessionStartupStatus('remote-session')).toBeNull();
+});
+
+it('leaves Console’s own start in charge while it runs', () => {
+ recordRemoteHostFailure('starting-session', 'An earlier failure.');
+ mocks.runtime.mockReturnValue({
+ startupStatus: () => ({ status: 'starting', message: 'Starting the session process…' }),
+ });
+ expect(sessionStartupStatus('starting-session')).toEqual({
+ status: 'starting',
+ message: 'Starting the session process…',
+ });
+ mocks.runtime.mockReturnValue({ startupStatus: () => ({ status: 'ready', message: null }) });
+ expect(sessionStartupStatus('starting-session')).toEqual({
+ status: 'error',
+ message: 'Shared SDK host failed: An earlier failure.',
+ });
+});
+
+it('tells the sidebar when a session it asked about fails or comes back', () => {
+ expect(sessionIssue('watched-session')).toBeNull();
+ const child = new EventEmitter();
+ localSessionLinks.attach(sharedSessionRoot('watched-session'), child as unknown as ChildProcess);
+ child.emit('exit', 1, null);
+ expect(mocks.emit).toHaveBeenCalledWith(
+ expect.anything(),
+ { sessionId: 'watched-session' },
+ 'watched-session'
+ );
+ expect(sessionIssue('watched-session')).toMatch(/^Shared SDK host failed: /);
+
+ mocks.emit.mockReset();
+ recordRemoteHostFailure('remote-watched', 'Not signed in.');
+ recordRemoteHostFailure('remote-watched', 'Not signed in.');
+ expect(mocks.emit).toHaveBeenCalledTimes(1);
+ expect(sessionIssue('remote-watched')).toMatch(/Not signed in\.$/);
+});
+
+it("drops a failed start once the room watcher brings the session's host up", () => {
+ let error: string | null = 'Shared SDK host failed: Sign in first.';
+ mocks.runtime.mockReturnValue({
+ startupStatus: () => ({ status: error ? 'error' : 'ready', message: error }),
+ hostCameUp: () => {
+ error = null;
+ },
+ });
+ expect(sessionIssue('restarted-session')).toMatch(/Sign in first\.$/);
+ const child = new EventEmitter();
+ localSessionLinks.attach(
+ sharedSessionRoot('restarted-session'),
+ child as unknown as ChildProcess
+ );
+ child.emit('message', { kind: 'ready' });
+ expect(sessionIssue('restarted-session')).toBeNull();
+ expect(mocks.emit).toHaveBeenCalledWith(
+ expect.anything(),
+ { sessionId: 'restarted-session' },
+ 'restarted-session'
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.ts
new file mode 100644
index 000000000..0c3413e22
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-failures.ts
@@ -0,0 +1,89 @@
+import { sharedSessionRoot } from '@switch-console/agent-providers';
+import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';
+import { events } from '@main/lib/events';
+import { sessionIssueChangedChannel } from '@shared/core/sessions/sessionEvents';
+import { localSessionLinks } from './local-host';
+
+/**
+ * Why each remote session's host last stopped on a failure, as the agent's
+ * sidecar pushed it to Console while the session was open here. A local
+ * session's is held by Console's own end of the host's pipe.
+ */
+const remote = new Map<string, string>();
+
+/** Session ids by state root, for telling the renderer about a local host's failure. */
+const sessionsByRoot = new Map<string, string>();
+
+/** Tell every window that this session's health may have changed. */
+export function announceSessionIssue(sessionId: string): void {
+ events.emit(sessionIssueChangedChannel, { sessionId }, sessionId);
+}
+
+let listening = false;
+
+/** Start announcing local host failures and recoveries, once the sidebar asks. */
+function listenForLocalHosts(): void {
+ if (listening) return;
+ listening = true;
+ localSessionLinks.onFailure((root) => {
+ const sessionId = sessionsByRoot.get(root);
+ if (sessionId) announceSessionIssue(sessionId);
+ });
+ localSessionLinks.onReady((root) => {
+ const sessionId = sessionsByRoot.get(root);
+ if (sessionId) hostCameUp(sessionId);
+ });
+}
+
+/**
+ * The session's host is up, so neither an earlier host failure nor Console's
+ * own failed start stands: the room watcher can start a host Console could not.
+ */
+function hostCameUp(sessionId: string): void {
+ sessionRuntimeManager.getAgent(sessionId)?.hostCameUp?.();
+ announceSessionIssue(sessionId);
+}
+
+/** The sidecar said the session's host failed (a message) or came up again (null). */
+export function recordRemoteHostFailure(sessionId: string, failure: string | null): void {
+ if (failure === null) {
+ remote.delete(sessionId);
+ hostCameUp(sessionId);
+ return;
+ }
+ if (remote.get(sessionId) === failure) return;
+ remote.set(sessionId, failure);
+ announceSessionIssue(sessionId);
+}
+
+/** Why the session's host last stopped on a failure, or null if it has not since it last started. */
+export function hostFailure(sessionId: string): string | null {
+ return localSessionLinks.failure(sharedSessionRoot(sessionId)) ?? remote.get(sessionId) ?? null;
+}
+
+/**
+ * Where the session's startup is, as the open session view shows it: Console's
+ * own start while it runs or once it failed, and otherwise a failure the
+ * session's host recorded — which is also how a session the room watcher
+ * started, and Console did not, shows that it could not start.
+ */
+export function sessionStartupStatus(
+ sessionId: string
+): { status: 'starting' | 'ready' | 'error'; message: string | null } | null {
+ const started = sessionRuntimeManager.getAgent(sessionId)?.startupStatus?.() ?? null;
+ if (started && started.status !== 'ready') return started;
+ const failure = hostFailure(sessionId);
+ if (failure !== null) return { status: 'error', message: `Shared SDK host failed: ${failure}` };
+ return started;
+}
+
+/**
+ * What is wrong with a session right now, in a sentence, or null: its start
+ * failed or its host stopped on a failure. The sidebar marks such a session.
+ */
+export function sessionIssue(sessionId: string): string | null {
+ listenForLocalHosts();
+ sessionsByRoot.set(sharedSessionRoot(sessionId), sessionId);
+ const status = sessionStartupStatus(sessionId);
+ return status?.status === 'error' ? (status.message ?? 'The session failed.') : null;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.test.ts
index d086a06f7..c0f2c8830 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.test.ts
@@ -7,9 +7,13 @@ const mocks = vi.hoisted(() => ({
running: true,
hydrate: vi.fn(async () => {}),
}));
-const { Unavailable } = vi.hoisted(() => ({ Unavailable: class extends Error {} }));
+const { Unavailable, Failed } = vi.hoisted(() => ({
+ Unavailable: class extends Error {},
+ Failed: class extends Error {},
+}));
vi.mock('@switch-console/agent-providers', () => ({
SessionUnavailableError: Unavailable,
+ SessionHostFailedError: Failed,
sharedSessionRoot: (id: string) => `/roots/${id}`,
liveSupervisor: async () => (mocks.running ? { build: 'b' } : null),
}));
@@ -127,3 +131,11 @@ it('starts a parked session again and then sends the command', async () => {
expect(mocks.hydrate).toHaveBeenCalledWith('session');
expect(mocks.local.request).toHaveBeenCalledTimes(2);
});
+
+it('starts a session whose host failed again when the user sends it something', async () => {
+ mocks.local.request
+ .mockRejectedValueOnce(new Failed('Sign in on the execution machine with claude auth login.'))
+ .mockResolvedValueOnce(applied);
+ expect(await submitSessionCommand('agent', command)).toEqual(applied);
+ expect(mocks.hydrate).toHaveBeenCalledWith('session');
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.ts
index f0072f758..285c3c9a9 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/session-commands.ts
@@ -1,5 +1,6 @@
import {
liveSupervisor,
+ SessionHostFailedError,
SessionUnavailableError,
sharedSessionRoot,
type SessionRequest,
@@ -78,7 +79,10 @@ export async function submitSessionCommand(
try {
return commandStatusSchema.parse(await askHost(agentId, command.sessionId, request));
} catch (error) {
- if (!(error instanceof SessionUnavailableError)) throw error;
+ // A host that failed is started again too: sending it something is the
+ // user asking for it, and whatever stopped it may have been fixed.
+ if (!(error instanceof SessionUnavailableError || error instanceof SessionHostFailedError))
+ throw error;
}
try {
await hydrateSession(command.sessionId);
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
index 8a8a27d73..d4ecaf2cf 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.initial-prompt.test.ts
@@ -1,3 +1,4 @@
+import { SessionHostFailedError } from '@switch-console/agent-providers';
import { beforeEach, expect, it, vi } from 'vitest';
import type { LocationTransport } from '@main/core/locations/location-transport';
import type { Session } from '@shared/core/sessions/sessions';
@@ -292,6 +293,23 @@ it('keeps a background authentication failure visible without sending the first
await expect(agent.stop()).resolves.toBeUndefined();
});
+it('fails as soon as the host stops on a recorded failure, without waiting to poll for it', async () => {
+ mocks.snapshot.mockRejectedValue(
+ new SessionHostFailedError('Sign in on the execution machine with claude auth login.')
+ );
+ const agent = runtime();
+ const started = Date.now();
+ await expect(agent.start(session, false, 'Say hello')).rejects.toThrow(
+ 'Shared SDK host failed: Sign in on the execution machine with claude auth login.'
+ );
+ expect(Date.now() - started).toBeLessThan(1000);
+ expect(agent.startupStatus()).toEqual({
+ status: 'error',
+ message: 'Shared SDK host failed: Sign in on the execution machine with claude auth login.',
+ });
+ expect(mocks.submit).not.toHaveBeenCalled();
+});
+
it('still rejects deployment failures before a host connects', async () => {
mocks.runHost.mockRejectedValueOnce(new Error('Could not deploy host.'));
const agent = runtime();
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
index 3ecb01950..dafc9809d 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-agent-runtime.ts
@@ -5,6 +5,7 @@ import {
} from './session-commands';
import { stopSharedSession } from './stop-shared-session';
export { stopSharedSession } from './stop-shared-session';
+import { announceSessionIssue, recordRemoteHostFailure } from './host-failures';
import { reconcileInitialPrompt } from './initial-prompt';
import { stopLegacySidecar } from './legacy-sidecar';
import { readLocalHostFailure, startLocalSession } from './local-host';
@@ -15,6 +16,7 @@ import { randomUUID } from 'node:crypto';
import { join, posix } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import {
+ SessionHostFailedError,
sharedConfigSchema,
sharedSessionRoot,
type SharedHostConfig,
@@ -88,9 +90,19 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
}
) {}
+ hostCameUp(): void {
+ if (!this.starting) this.setStartupError(null);
+ }
+
+ private setStartupError(error: string | null): void {
+ if (this.startupError === error) return;
+ this.startupError = error;
+ announceSessionIssue(this.params.sessionId);
+ }
+
async start(session: Session, isResuming?: boolean, initialPrompt?: string): Promise<void> {
if (this.starting) return this.opened ?? this.starting;
- this.startupError = null;
+ this.setStartupError(null);
let connected!: () => void;
let failed!: (error: unknown) => void;
this.opened = new Promise<void>((resolve, reject) => {
@@ -100,7 +112,7 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
this.starting = this.open(session, initialPrompt, isResuming ?? false, false, connected);
void this.starting
.then(connected, (error: unknown) => {
- this.startupError = error instanceof Error ? error.message : String(error);
+ this.setStartupError(error instanceof Error ? error.message : String(error));
log.error('Background session startup failed', {
sessionId: session.id,
error: this.startupError,
@@ -133,6 +145,7 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
const previousEpoch = restart ? await journalEpoch(session.agentId, session.id) : null;
let root: string;
let readFailure: () => Promise<unknown>;
+ recordRemoteHostFailure(session.id, null);
this.startupStage = restart
? 'Stopping the previous process and starting its replacement…'
: 'Starting the session process…';
@@ -216,6 +229,8 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
)
break;
} catch (error) {
+ if (error instanceof SessionHostFailedError)
+ throw new Error(`Shared SDK host failed: ${error.failure}`);
if (Date.now() + 500 >= deadline) throw error;
// No journal yet is the host not having started, which is the wait itself.
const notYet = error instanceof JournalUnavailableError;
@@ -323,12 +338,12 @@ export class SharedAgentRuntime implements AgentRuntimeProvider {
async restart(session: Session): Promise<void> {
await this.resolveWorkspace();
if (this.starting) await this.starting;
- this.startupError = null;
+ this.setStartupError(null);
this.starting = this.open(session, undefined, true, true, () => {});
try {
await this.starting;
} catch (error) {
- this.startupError = error instanceof Error ? error.message : String(error);
+ this.setStartupError(error instanceof Error ? error.message : String(error));
throw error;
} finally {
this.starting = null;
@@ -475,13 +490,11 @@ export async function buildSharedHostConfig(
}
: {}),
codexConfig: profile?.files.map((file) => file.content).join('\n') ?? '',
- // Codex and OpenCode load the skill as a file; the others take it as
- // system context.
- skill: provider === 'codex' || provider === 'opencode' ? SWITCH_SKILL_FILE : '',
- context: [
- provider === 'codex' || provider === 'opencode' ? '' : SWITCH_SKILL_CONTEXT,
- specialization.instructions,
- ]
+ // OpenCode loads the skill as a file through its own skill tool; the
+ // others take it as system context. Codex has no skill tool, so a skill
+ // file would be read with a shell command that needs approval.
+ skill: provider === 'opencode' ? SWITCH_SKILL_FILE : '',
+ context: [provider === 'opencode' ? '' : SWITCH_SKILL_CONTEXT, specialization.instructions]
.filter(Boolean)
.join('\n\n'),
},
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.test.ts
index 63b6c47b9..21d4d2087 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.test.ts
@@ -9,9 +9,13 @@ const mocks = vi.hoisted(() => ({
sshHost: null as string | null,
hydrate: vi.fn(async () => {}),
}));
-const { Unavailable } = vi.hoisted(() => ({ Unavailable: class extends Error {} }));
+const { Unavailable, HostFailed } = vi.hoisted(() => ({
+ Unavailable: class extends Error {},
+ HostFailed: class extends Error {},
+}));
vi.mock('@switch-console/agent-providers', () => ({
SessionUnavailableError: Unavailable,
+ SessionHostFailedError: HostFailed,
sharedSessionRoot: (id: string) => `/roots/${id}`,
liveSupervisor: async () => ({ build: 'b' }),
}));
@@ -141,3 +145,11 @@ it('fails when the host cannot say whether the stop happened', async () => {
mocks.local.request.mockImplementation(host({}, [[receipt('unknown')]]));
await expect(stopSharedSession('agent', 'session-1')).rejects.toThrow('Stop unknown.');
});
+
+it('treats a session whose host failed to start as having nothing to stop', async () => {
+ mocks.local.request.mockRejectedValue(new HostFailed('Sign in with claude auth login.'));
+ await expect(stopSharedSession('agent', 'session')).resolves.toBeUndefined();
+ expect(mocks.local.request.mock.calls.every(([, request]) => request.type !== 'command')).toBe(
+ true
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.ts
index e77934db2..152a4d0ea 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/stop-shared-session.ts
@@ -1,4 +1,5 @@
import { setTimeout as delay } from 'node:timers/promises';
+import { SessionHostFailedError } from '@switch-console/agent-providers';
import { JournalUnavailableError } from './host-journal';
import {
CommandNotRecordedError,
@@ -11,15 +12,16 @@ import { currentSnapshot } from './transcripts';
* Ask a session's host to stop, and wait until it says it has.
*
* The stop goes straight to the host (Console's child, or the agent sidecar's
- * over SSH). A session no host is running, or whose host is offline or already
- * stopped, has nothing to stop and returns without sending anything.
+ * over SSH). A session no host is running, whose host failed to start, or
+ * whose host is offline or already stopped, has nothing to stop and returns
+ * without sending anything.
*/
export async function stopSharedSession(agentId: string, sessionId: string): Promise<void> {
let snapshot;
try {
snapshot = await currentSnapshot(agentId, sessionId);
} catch (error) {
- if (error instanceof JournalUnavailableError) return;
+ if (error instanceof JournalUnavailableError || error instanceof SessionHostFailedError) return;
throw error;
}
if (snapshot.session.status === 'stopped' || snapshot.session.connectivity !== 'online') return;
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts
index f2e033d12..74a1da3bd 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/transcripts.ts
@@ -1,6 +1,10 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
-import { SessionUnavailableError, sharedSessionRoot } from '@switch-console/agent-providers';
+import {
+ SessionHostFailedError,
+ SessionUnavailableError,
+ sharedSessionRoot,
+} from '@switch-console/agent-providers';
import { snapshotSchema, type ServerEvent, type Snapshot } from '@switch-console/shared/session-v1';
import { getAgentLocation } from '@main/core/agents/agent-location';
import { getAgentById } from '@main/core/agents/getAgentById';
@@ -10,6 +14,7 @@ import {
sessionTranscriptEventChannel,
sessionTranscriptResetChannel,
} from '@shared/core/sessions/sessionEvents';
+import { recordRemoteHostFailure } from './host-failures';
import { hostJournals, JournalTail, JournalUnavailableError } from './host-journal';
import { localSessionLinks } from './local-host';
import { syncSdkSessionActivity } from './session-activity';
@@ -90,7 +95,8 @@ async function recordedSnapshot(agentId: string, sessionId: string, local: boole
try {
return await currentSnapshot(agentId, sessionId);
} catch (error) {
- if (!(error instanceof JournalUnavailableError)) throw error;
+ if (!(error instanceof JournalUnavailableError || error instanceof SessionHostFailedError))
+ throw error;
}
return local
? localJournalSnapshot(sharedSessionRoot(sessionId))
@@ -111,8 +117,10 @@ export async function openTranscript(agentId: string, sessionId: string): Promis
forward(sessionId, event)
)
: await withSidecar(agentId, async (client) => {
- const unsubscribe = await client.subscribe(sessionId, (event) =>
- forward(sessionId, event)
+ const unsubscribe = await client.subscribe(
+ sessionId,
+ (event) => forward(sessionId, event),
+ (failure) => recordRemoteHostFailure(sessionId, failure)
);
// Events recorded while the connection is down never arrive, so the
// windows showing the session reload it rather than carry on with a gap.
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.test.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.test.ts
index 96ec1c5a5..08aee0c69 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.test.ts
@@ -5,11 +5,13 @@ const mocks = vi.hoisted(() => ({
deleteWhere: vi.fn(),
selectLimit: vi.fn(),
stopSaved: vi.fn(),
+ forget: vi.fn(),
teardownSession: vi.fn(),
viewStateDel: vi.fn(),
}));
vi.mock('@main/core/sdk-host/stop-saved-session', () => ({ stopSavedSession: mocks.stopSaved }));
+vi.mock('@main/core/sdk-host/forget-session', () => ({ forgetSession: mocks.forget }));
vi.mock('@main/db/client', () => ({
db: {
select: () => ({
@@ -57,6 +59,8 @@ describe('deleteSession', () => {
await deleteSession('session-1');
expect(mocks.teardownSession).toHaveBeenCalledWith('session-1', 'detach');
expect(mocks.deleteWhere).toHaveBeenCalledTimes(1);
+ // The agent's room watcher stops routing its rooms to the deleted session.
+ expect(mocks.forget).toHaveBeenCalledWith('agent-1', 'session-1');
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.ts
index 3f10c94f3..617b181bc 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/deleteSession.ts
@@ -1,4 +1,5 @@
import { eq } from 'drizzle-orm';
+import { forgetSession } from '@main/core/sdk-host/forget-session';
import { stopSavedSession } from '@main/core/sdk-host/stop-saved-session';
import { tombstoneSession } from '@main/core/sessions/deleted-sessions';
import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';
@@ -10,6 +11,7 @@ export async function deleteSession(sessionId: string): Promise<void> {
const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId)).limit(1);
if (!session) return;
await stopSavedSession(sessionId, session.agentId);
+ await forgetSession(session.agentId, sessionId);
const teardownResult = await sessionRuntimeManager.teardownSession(sessionId, 'detach');
if (!teardownResult.success) throw new Error(teardownResult.error.message);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section.tsx
new file mode 100644
index 000000000..d90dde503
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section.tsx
@@ -0,0 +1,40 @@
+import { useQuery } from '@tanstack/react-query';
+import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';
+import { rpc } from '@renderer/lib/ipc';
+import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';
+
+/**
+ * Whether the agent's provider CLI is signed in on the machine its sessions
+ * run on. A session cannot start without it, and that otherwise only shows
+ * once somebody addresses the agent and the start fails.
+ */
+export function ProviderSignInSettingsSection({
+ locationId,
+ agentId,
+}: {
+ locationId: string;
+ agentId: string | undefined;
+}) {
+ const { data: agents } = useQuery({
+ queryKey: ['location-agents', locationId],
+ queryFn: () => rpc.agents.getAgents(locationId),
+ });
+ const { data: locations } = useQuery({
+ queryKey: ['locations'],
+ queryFn: () => rpc.locations.getLocations(),
+ });
+ const agent = (agents ?? []).find((a) => a.id === agentId);
+ const location = (locations ?? []).find((l) => l.id === locationId);
+ if (!agent || !location) return null;
+ return (
+ <Field>
+ <FieldLabel>Provider sign-in</FieldLabel>
+ {/* An empty directory shares the Add Agent check's result for the same machine. */}
+ <ProviderConnectionStatus providerId={agent.providerId} sshHost={location.sshHost} dir="" />
+ <FieldDescription className="text-foreground-muted">
+ The agent&apos;s sessions start only when its provider CLI is signed in on the machine they
+ run on.
+ </FieldDescription>
+ </Field>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
index edbcc4a48..bdd7c521c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
@@ -6,6 +6,7 @@ import { AddressingPolicySettingsSection } from '@renderer/features/locations/co
import { AgentAdvancedSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section';
import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';
import { AutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-session-settings-section';
+import { ProviderSignInSettingsSection } from '@renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section';
import {
asMounted,
getLocationStore,
@@ -44,6 +45,7 @@ export const SettingsPanel = observer(function SettingsPanel() {
<AgentInstructionsSection locationId={locationId} agentId={agentId} />
<section className="flex flex-col gap-6">
<SectionLabel>General</SectionLabel>
+ <ProviderSignInSettingsSection locationId={locationId} agentId={agentId} />
<AutoSessionSettingsSection locationId={locationId} agentId={agentId} />
<AutoApproveSettingsSection locationId={locationId} agentId={agentId} />
<AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/setup-rows.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/setup-rows.tsx
index 6c62e556a..c24132056 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/setup-rows.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/setup-rows.tsx
@@ -55,6 +55,7 @@ function Row({
icon,
name,
subtitle,
+ status,
progress,
badge,
highlighted,
@@ -64,6 +65,8 @@ function Row({
icon: React.ReactNode;
name: string;
subtitle?: string | null;
+ /** A status line beside the subtitle, such as the CLI's sign-in state. */
+ status?: React.ReactNode;
/** What the running command last printed. Takes the subtitle's place while it runs. */
progress?: string | null;
badge: BadgeSpec;
@@ -92,7 +95,14 @@ function Row({
{progress ? (
<span className="truncate font-mono text-[11px] text-foreground-muted">{progress}</span>
) : (
- subtitle && <span className="truncate text-xs text-foreground-muted">{subtitle}</span>
+ (subtitle || status) && (
+ <span className="flex min-w-0 items-center gap-2">
+ {subtitle && (
+ <span className="truncate text-xs text-foreground-muted">{subtitle}</span>
+ )}
+ {status}
+ </span>
+ )
)}
</span>
</button>
@@ -325,6 +335,7 @@ export function AgentTypeRowItem({
onUpdate,
onRecheck,
onOpen,
+ signIn,
}: {
row: AgentTypeRow;
/** The step the plan says is in flight. */
@@ -342,12 +353,15 @@ export function AgentTypeRowItem({
onUpdate: (stepId: string) => void;
onRecheck: (stepId: string) => void;
onOpen: () => void;
+ /** Whether the CLI is signed in on this host, when that can be asked. */
+ signIn?: React.ReactNode;
}) {
return (
<Row
icon={<AgentIcon id={row.agentId} size={16} />}
name={row.name}
subtitle={versionSubtitle(row.cli)}
+ status={signIn}
progress={activityFor(row.cli.id)}
badge={stepBadge(row.cli)}
highlighted={currentStepId === row.cli.id}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.test.ts b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.test.ts
index af2d4ff57..9404fc37f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.test.ts
@@ -8,6 +8,7 @@ import {
canUpdate,
dependenciesMet,
groupPlanSteps,
+ needsFirstCheck,
outcomeLabel,
stepBadge,
versionSubtitle,
@@ -350,3 +351,12 @@ describe('versionSubtitle', () => {
).toBeNull();
});
});
+
+describe('needsFirstCheck', () => {
+ it('asks for a first look while any step has never been observed', () => {
+ const observed = step({ id: 'git', state: 'satisfied', outcome: 'satisfied' });
+ expect(needsFirstCheck(plan([observed, step({ id: 'node' })]))).toBe(true);
+ expect(needsFirstCheck(plan([observed]))).toBe(false);
+ expect(needsFirstCheck(null)).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.ts b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.ts
index 5614c2425..8a0b69a6d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/setup/step-presentation.ts
@@ -211,3 +211,8 @@ export function groupPlanSteps(plan: HostSetupPlan | null): GroupedPlan {
return { prerequisites, agentTypes };
}
+
+/** Whether any step has never been observed on the host, so the page should look once on its own. */
+export function needsFirstCheck(plan: HostSetupPlan | null): boolean {
+ return plan?.steps.some((step) => step.outcome === null) ?? false;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
index cfc2ed1a4..271f4b5d3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/remote-hosts/views/remote-host-view.tsx
@@ -20,15 +20,20 @@
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, RefreshCw } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useEffect, useMemo, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
import { PageHeader } from '@renderer/lib/components/page-header';
+import { ProviderConnectionStatus } from '@renderer/lib/components/provider-connection-status';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { Button } from '@renderer/lib/ui/button';
import { Spinner } from '@renderer/lib/ui/spinner';
import { StatusBadge } from '@renderer/lib/ui/status-badge';
+import {
+ AGENT_PROVIDER_IDS,
+ asAgentProviderId,
+} from '@shared/core/providers/agent-provider-registry';
import { deriveHostStatus } from '@shared/core/remote-hosts/host-status';
import { isHostBlocked } from '@shared/core/remote-hosts/reachability';
import { switchServersStore } from '../../switch-servers/switch-servers-store';
@@ -44,7 +49,7 @@ import {
PrerequisiteRow,
SectionLabel,
} from '../setup/setup-rows';
-import { groupPlanSteps } from '../setup/step-presentation';
+import { groupPlanSteps, needsFirstCheck } from '../setup/step-presentation';
import {
useHostSetupPlan,
useInstallSetupStep,
@@ -104,6 +109,19 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
startPrepare();
}, [blocked, plan.isLoading, startPrepare]);
+ // A step nobody has looked at yet has no state worth showing: probe the
+ // host once when the page opens with any, rather than leaving every row
+ // blank until someone presses Re-check. Steps already observed keep their
+ // last result; re-checking those stays a deliberate click.
+ const { mutate: startRecheck } = recheck;
+ const autoChecked = useRef(false);
+ const unobserved = needsFirstCheck(plan.data ?? null);
+ useEffect(() => {
+ if (autoChecked.current || blocked || !prepare.isSuccess || !unobserved) return;
+ autoChecked.current = true;
+ startRecheck();
+ }, [blocked, prepare.isSuccess, unobserved, startRecheck]);
+
// Resolve the Switch server for this host: prefer a managed server on this
// host, then the active server, then the first available. Read the
// observables outside useMemo so MobX tracks them and React sees them change.
@@ -279,6 +297,19 @@ export const RemoteHostMainPanel = observer(function RemoteHostMainPanel() {
onUpdate={(stepId) => updateStep.mutate(stepId)}
onRecheck={(stepId) => recheckStep.mutate(stepId)}
onOpen={() => setSheetTarget({ kind: 'agent-type', row })}
+ signIn={
+ // Installed is not usable: a session also needs
+ // the CLI signed in on this host.
+ !blocked &&
+ (AGENT_PROVIDER_IDS as readonly string[]).includes(row.agentId) ? (
+ <ProviderConnectionStatus
+ providerId={asAgentProviderId(row.agentId)}
+ sshHost={sshHost}
+ dir=""
+ compact
+ />
+ ) : null
+ }
/>
</div>
))}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
index d229f9169..db229f148 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/agent-item.tsx
@@ -15,6 +15,7 @@ import {
import { AgentConnectionIndicator } from '@renderer/features/switch-rooms/connection-health';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { ProviderIssueIndicator } from '@renderer/lib/components/provider-issue-indicator';
import { resetAgentErrorText } from '@renderer/lib/errors/reset-agent-error';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -154,6 +155,14 @@ export const SidebarAgentItem = observer(function SidebarAgentItem({
Shared with the room-grouped rows so the two trees cannot
disagree about the same agent (CHOO-1682/1809). */}
<HostTroubleIndicator sshHost={sshHost} agentId={agent.providerId ?? null} />
+ {agent.providerId && (
+ <ProviderIssueIndicator
+ providerId={agent.providerId}
+ sshHost={sshHost}
+ hostReachable={!hostUnreachable}
+ onOpen={open}
+ />
+ )}
{locationViewKind(location) === 'ready' &&
hasSessionError(agent.locationId) &&
(hasDiscardableSessionError(agent.locationId) ? (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
index ec2802abc..43c7a5ca2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-agent-row.tsx
@@ -1,11 +1,13 @@
import { Bot, ChevronRight, DoorOpen, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { getLocationStore } from '@renderer/features/locations/stores/location-selectors';
+import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { HostTroubleIndicator } from '@renderer/features/remote-hosts/host-trouble-indicator';
import { AgentConnectionIndicator } from '@renderer/features/switch-rooms/connection-health';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { AgentIcon } from '@renderer/lib/components/agent-icon';
+import { ProviderIssueIndicator } from '@renderer/lib/components/provider-issue-indicator';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { useToast } from '@renderer/lib/hooks/use-toast';
import { rpc } from '@renderer/lib/ipc';
@@ -140,6 +142,16 @@ export const RoomAgentRow = observer(function RoomAgentRow({
sshHost={location.data?.sshHost ?? null}
agentId={agent.providerId ?? null}
/>
+ {agent.providerId && (
+ <ProviderIssueIndicator
+ providerId={agent.providerId}
+ sshHost={location.data?.sshHost ?? null}
+ hostReachable={!hostReachabilityStore.isBlocked(location.data?.sshHost ?? null)}
+ onOpen={() =>
+ navigate('location', { locationId: agent.locationId, agentName: agent.name })
+ }
+ />
+ )}
</span>
</SidebarMenuAction>
<AgentConnectionIndicator agent={agent} />
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-issue-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-issue-indicator.tsx
new file mode 100644
index 000000000..a86199132
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-issue-indicator.tsx
@@ -0,0 +1,44 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { TriangleAlert } from 'lucide-react';
+import { useEffect } from 'react';
+import { events, rpc } from '@renderer/lib/ipc';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import { sessionIssueChangedChannel } from '@shared/core/sessions/sessionEvents';
+
+export const sessionIssueQueryKey = (sessionId: string) => ['session-issue', sessionId];
+
+/**
+ * A warning on a session row whose start failed or whose host stopped on a
+ * failure, with the reason in its tooltip. Asked once, then refreshed only
+ * when main says the session's health changed, so a sidebar full of sessions
+ * does not poll.
+ */
+export function SessionIssueIndicator({ sessionId }: { sessionId: string }) {
+ const queryClient = useQueryClient();
+ const { data: issue } = useQuery({
+ queryKey: sessionIssueQueryKey(sessionId),
+ queryFn: () => rpc.sdkHost.sessionIssue(sessionId),
+ staleTime: Infinity,
+ });
+ useEffect(
+ () =>
+ events.on(
+ sessionIssueChangedChannel,
+ () => void queryClient.invalidateQueries({ queryKey: sessionIssueQueryKey(sessionId) }),
+ sessionId
+ ),
+ [sessionId, queryClient]
+ );
+ if (!issue) return null;
+ return (
+ <Tooltip>
+ <TooltipTrigger>
+ <TriangleAlert
+ aria-label={`Session problem: ${issue}`}
+ className="h-3.5 w-3.5 shrink-0 text-foreground-destructive"
+ />
+ </TooltipTrigger>
+ <TooltipContent>{issue}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx
index 0f7507215..137351f5d 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/session-item.tsx
@@ -8,6 +8,7 @@ import {
getSessionStore,
} from '@renderer/features/sessions/stores/session-selectors';
import { useSessionActionProps } from '@renderer/features/sessions/use-session-actions';
+import { SessionIssueIndicator } from '@renderer/features/sidebar/session-issue-indicator';
import { SessionSidebarTrailingSlot } from '@renderer/features/sidebar/session-sidebar-agent-status';
import { SessionRoomConnection } from '@renderer/features/switch-rooms/session-room-connection';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -89,6 +90,7 @@ export const SidebarSessionItem = observer(function SidebarSessionItem({
{sessionName}
</span>
</SidebarMenuAction>
+ <SessionIssueIndicator sessionId={sessionId} />
{'agentId' in session.data && (
<SessionRoomConnection compact sessionId={sessionId} agentId={session.data.agentId} />
)}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
index 45fb91b3b..03d2ef148 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx
@@ -12,6 +12,44 @@ const loginCommands: Record<AgentProviderId, string> = {
opencode: 'opencode auth login',
};
+/**
+ * Whether a provider's CLI is installed and signed in on a machine. One check
+ * per provider, machine and directory, shared by every component that asks:
+ * the Add Agent tiles, an agent's settings and the sidebar all read the same
+ * cached answer.
+ */
+export function useProviderReadiness(
+ providerId: AgentProviderId,
+ sshHost: string | null,
+ dir: string,
+ enabled: boolean
+) {
+ return useQuery({
+ queryKey: ['provider-readiness', providerId, sshHost, dir],
+ queryFn: () => rpc.agents.providerReadiness({ providerId, sshHost, dir }),
+ // Signing in is not something that changes minute to minute, and this is
+ // rendered once per provider tile and once per agent row — so a short
+ // window turned opening a page into a burst of probes, each of which
+ // starts a provider process on the execution machine.
+ staleTime: 5 * 60_000,
+ retry: false,
+ enabled,
+ });
+}
+
+/** What is wrong with a provider on a machine, in a few words, or null when nothing is known to be. */
+export function providerProblem(
+ data: { installed: boolean | null; status: string } | undefined
+): string | null {
+ if (!data) return null;
+ if (data.installed === false) return 'CLI not installed';
+ if (data.status === 'unauthenticated') return 'Not signed in';
+ if (data.status === 'unconfigured') return 'No backend configured';
+ return null;
+}
+
+export { loginCommands };
+
export function ProviderConnectionStatus({
providerId,
sshHost,
@@ -23,16 +61,7 @@ export function ProviderConnectionStatus({
dir: string;
compact?: boolean;
}) {
- const query = useQuery({
- queryKey: ['provider-readiness', providerId, sshHost, dir],
- queryFn: () => rpc.agents.providerReadiness({ providerId, sshHost, dir }),
- // Signing in is not something that changes minute to minute, and this
- // component is rendered once per provider tile and once per agent row —
- // so a short window turned opening a page into a burst of probes, each of
- // which starts a provider process on the execution machine.
- staleTime: 5 * 60_000,
- retry: false,
- });
+ const query = useProviderReadiness(providerId, sshHost, dir, true);
const copy = useMutation({
mutationFn: () => navigator.clipboard.writeText(loginCommands[providerId]),
});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts
new file mode 100644
index 000000000..dd6d546c7
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.test.ts
@@ -0,0 +1,59 @@
+import React from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const readiness = vi.hoisted(() => ({ data: undefined as unknown, enabled: [] as boolean[] }));
+vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+vi.mock('./provider-connection-status', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useProviderReadiness: (_p: string, _h: string | null, _d: string, enabled: boolean) => {
+ readiness.enabled.push(enabled);
+ return { data: readiness.data };
+ },
+}));
+
+const { ProviderIssueIndicator } = await import('./provider-issue-indicator');
+const { providerProblem } = await import('./provider-connection-status');
+
+const render = (hostReachable = true) =>
+ renderToStaticMarkup(
+ React.createElement(ProviderIssueIndicator, {
+ providerId: 'claude',
+ sshHost: 'box',
+ hostReachable,
+ onOpen: () => {},
+ })
+ );
+
+beforeEach(() => {
+ readiness.data = undefined;
+ readiness.enabled.length = 0;
+});
+
+it('warns when the provider is not signed in or not installed', () => {
+ readiness.data = { installed: true, status: 'unauthenticated', message: null };
+ expect(render()).toContain('Not signed in on box');
+ readiness.data = { installed: false, status: 'unknown', message: null };
+ expect(render()).toContain('CLI not installed on box');
+});
+
+it('shows nothing when the provider is ready or the check could not tell', () => {
+ readiness.data = { installed: true, status: 'authenticated', message: null };
+ expect(render()).toBe('');
+ readiness.data = { installed: true, status: 'unknown', message: 'Could not tell' };
+ expect(render()).toBe('');
+ readiness.data = undefined;
+ expect(render()).toBe('');
+});
+
+it('does not probe a host already known to be unreachable', () => {
+ render(false);
+ expect(readiness.enabled).toEqual([false]);
+});
+
+it('names the problem only for states that stop a session', () => {
+ expect(providerProblem({ installed: true, status: 'unconfigured' })).toBe(
+ 'No backend configured'
+ );
+ expect(providerProblem({ installed: null, status: 'unknown' })).toBeNull();
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx
new file mode 100644
index 000000000..f455a21a8
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-issue-indicator.tsx
@@ -0,0 +1,56 @@
+import { CircleAlert } from 'lucide-react';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
+import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { loginCommands, providerProblem, useProviderReadiness } from './provider-connection-status';
+
+/**
+ * A warning beside an agent whose provider cannot run on the agent's machine:
+ * the CLI is missing, or not signed in. Nothing when it is ready, or when the
+ * check could not tell. An unknown is not a fault worth a warning.
+ */
+export function ProviderIssueIndicator({
+ providerId,
+ sshHost,
+ hostReachable,
+ onOpen,
+}: {
+ providerId: AgentProviderId;
+ sshHost: string | null;
+ /** A host already known to be down is not probed; its own indicator says so. */
+ hostReachable: boolean;
+ onOpen: () => void;
+}) {
+ const { data } = useProviderReadiness(providerId, sshHost, '', hostReachable);
+ const problem = providerProblem(data);
+ if (!problem) return null;
+ const name = getProvider(providerId)?.name ?? providerId;
+ const where = sshHost ? `on ${sshHost}` : 'on this computer';
+ const fix =
+ data?.installed === false
+ ? `Install the ${name} CLI ${where}.`
+ : data?.status === 'unauthenticated'
+ ? `Run \`${loginCommands[providerId]}\` ${where}.`
+ : data?.message;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label={`${name}: ${problem} ${where}. Open agent settings`}
+ className="inline-flex shrink-0 items-center text-foreground-warning"
+ onClick={(event) => {
+ event.stopPropagation();
+ onOpen();
+ }}
+ >
+ <CircleAlert className="h-3.5 w-3.5" />
+ </button>
+ }
+ />
+ <TooltipContent>
+ {name}: {problem.toLowerCase()} {where}. {fix}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/shared/core/sessions/sessionEvents.ts b/console/apps/switch-console-desktop/src/shared/core/sessions/sessionEvents.ts
index 7d52de5c0..d518e38d5 100644
--- a/console/apps/switch-console-desktop/src/shared/core/sessions/sessionEvents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/sessions/sessionEvents.ts
@@ -99,3 +99,11 @@ export const sessionTranscriptResetChannel = defineEvent<{
sessionId: string;
reason: string;
}>('session:transcript-reset');
+
+/**
+ * Something about a session's health changed: its host failed, came back, or
+ * its start failed. The topic is the session id; ask for the current state.
+ */
+export const sessionIssueChangedChannel = defineEvent<{ sessionId: string }>(
+ 'session:issue-changed'
+);
diff --git a/console/packages/agent-providers/src/claude/claude-adapter.test.ts b/console/packages/agent-providers/src/claude/claude-adapter.test.ts
index 8b8e2da34..6e653964f 100644
--- a/console/packages/agent-providers/src/claude/claude-adapter.test.ts
+++ b/console/packages/agent-providers/src/claude/claude-adapter.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { ProviderSessionStartInput, RuntimeMode } from '../adapter';
+import { ProviderConversationUnavailableError } from '../adapter';
import { EventRecorder } from '../testing/event-recorder';
import { ClaudeAdapter, installShadowedWarningFilter } from './claude-adapter';
import type { FakeSdk } from './fake-sdk';
@@ -55,7 +56,11 @@ describe('ClaudeAdapter session lifecycle', () => {
'accepts the first message after initialization without a conversation init event: %j',
async (resume) => {
const sdk = createFakeSdk(false);
- const adapter = new ClaudeAdapter({ query: sdk.query, claudeExecutablePath: '/bin/claude' });
+ const adapter = new ClaudeAdapter({
+ query: sdk.query,
+ claudeExecutablePath: '/bin/claude',
+ savedConversationExists: async () => true,
+ });
const recorder = new EventRecorder(adapter);
await adapter.startSession(startInput({ resume }));
await recorder.waitFor('session.state.changed', (event) => event.status === 'ready', 1_000);
@@ -282,9 +287,25 @@ describe('ClaudeAdapter session lifecycle', () => {
expect(seen).toEqual(['SOMETHING_ELSE']);
});
+ it('refuses to resume a conversation Claude never saved', async () => {
+ const sdk = createFakeSdk();
+ const adapter = new ClaudeAdapter({
+ query: sdk.query,
+ claudeExecutablePath: '/bin/claude',
+ savedConversationExists: async () => false,
+ });
+ await expect(
+ adapter.startSession(startInput({ resume: { nativeSessionId: 'never-saved' } }))
+ ).rejects.toBeInstanceOf(ProviderConversationUnavailableError);
+ });
+
it('resumes a native session instead of picking a new id', async () => {
const sdk = createFakeSdk();
- const adapter = new ClaudeAdapter({ query: sdk.query, claudeExecutablePath: '/bin/claude' });
+ const adapter = new ClaudeAdapter({
+ query: sdk.query,
+ claudeExecutablePath: '/bin/claude',
+ savedConversationExists: async (id) => id === 'earlier',
+ });
const session = await adapter.startSession(
startInput({ resume: { nativeSessionId: 'earlier' } })
);
diff --git a/console/packages/agent-providers/src/claude/claude-adapter.ts b/console/packages/agent-providers/src/claude/claude-adapter.ts
index 4a819bc12..ac2aec635 100644
--- a/console/packages/agent-providers/src/claude/claude-adapter.ts
+++ b/console/packages/agent-providers/src/claude/claude-adapter.ts
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import { accessSync, constants } from 'node:fs';
-import { readFile } from 'node:fs/promises';
+import { access, readdir, readFile } from 'node:fs/promises';
+import { homedir } from 'node:os';
import { delimiter, join } from 'node:path';
import { query as sdkQuery } from '@anthropic-ai/claude-agent-sdk';
import type {
@@ -25,7 +26,11 @@ import type {
ProviderSessionStartInput,
ProviderTurnStartResult,
} from '../adapter';
-import { ProviderSessionError, ProviderUnavailableError } from '../adapter';
+import {
+ ProviderConversationUnavailableError,
+ ProviderSessionError,
+ ProviderUnavailableError,
+} from '../adapter';
import type {
ApprovalDecision,
ApprovalOption,
@@ -124,6 +129,41 @@ export interface ClaudeAdapterOptions {
logger?: ClaudeAdapterLogger;
/** Test seam: a scripted stand-in for the SDK's `query()`. */
query?: typeof sdkQuery;
+ /** Test seam: whether Claude Code has a saved conversation with this id. */
+ savedConversationExists?: (
+ nativeSessionId: string,
+ env: Record<string, string>
+ ) => Promise<boolean>;
+}
+
+/**
+ * Whether Claude Code saved a conversation with this id. Claude writes a
+ * conversation only once a turn has run in it, under its config directory's
+ * `projects/<directory>/<id>.jsonl`; an id that was handed out but never used
+ * has no file, and resuming it fails with "No conversation found".
+ */
+async function claudeConversationSaved(
+ nativeSessionId: string,
+ env: Record<string, string>
+): Promise<boolean> {
+ const configDir = env.CLAUDE_CONFIG_DIR || join(env.HOME || homedir(), '.claude');
+ let projects: string[];
+ try {
+ projects = await readdir(join(configDir, 'projects'));
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
+ throw error;
+ }
+ for (const project of projects) {
+ try {
+ await access(join(configDir, 'projects', project, `${nativeSessionId}.jsonl`));
+ return true;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;
+ }
+ }
+ return false;
}
type EventBody<T extends ProviderRuntimeEvent = ProviderRuntimeEvent> =
@@ -289,11 +329,15 @@ export class ClaudeAdapter implements ProviderAdapter {
private readonly executablePath: string | undefined;
private readonly logger: ClaudeAdapterLogger | undefined;
private readonly queryFn: typeof sdkQuery;
+ private readonly savedConversationExists: NonNullable<
+ ClaudeAdapterOptions['savedConversationExists']
+ >;
constructor(options: ClaudeAdapterOptions = {}) {
this.executablePath = options.claudeExecutablePath;
this.logger = options.logger;
this.queryFn = options.query ?? sdkQuery;
+ this.savedConversationExists = options.savedConversationExists ?? claudeConversationSaved;
}
subscribe(listener: (event: ProviderRuntimeEvent) => void): () => void {
@@ -327,6 +371,12 @@ export class ClaudeAdapter implements ProviderAdapter {
const executable = resolveClaudeExecutable(this.executablePath, input.env);
const nativeSessionId = input.resume?.nativeSessionId ?? randomUUID();
+ if (input.resume && !(await this.savedConversationExists(nativeSessionId, input.env)))
+ throw new ProviderConversationUnavailableError(
+ PROVIDER,
+ input.sessionId,
+ `Claude Code has no saved conversation ${nativeSessionId} to resume.`
+ );
filterShadowedWarningOnce();
diff --git a/console/packages/agent-providers/src/codex/home.test.ts b/console/packages/agent-providers/src/codex/home.test.ts
index 8ee843b24..ff317aa1a 100644
--- a/console/packages/agent-providers/src/codex/home.test.ts
+++ b/console/packages/agent-providers/src/codex/home.test.ts
@@ -22,15 +22,16 @@ it('isolates config, preserves rollouts and refreshed auth on resume, and protec
sessionId: '../session',
sourceHome,
config: 'model = "test-model"',
- skill: 'Switch workflow',
};
const home = await prepareCodexSessionHome(input);
expect(parse(await readFile(join(home, 'config.toml'), 'utf8'))).toEqual({
model: 'test-model',
model_reasoning_effort: 'high',
});
- expect(await readFile(join(home, 'skills/switch/SKILL.md'), 'utf8')).toBe(input.skill);
- expect(await readdir(home)).toEqual(['auth.json', 'config.toml', 'skills']);
+ expect((await readdir(home)).filter((name) => name !== 'skills')).toEqual([
+ 'auth.json',
+ 'config.toml',
+ ]);
if (process.platform !== 'win32')
expect((await stat(join(home, 'auth.json'))).mode & 0o777).toBe(0o600);
await writeFile(join(home, 'auth.json'), 'refreshed-fixture');
@@ -53,7 +54,32 @@ it('allows native environment or keychain authentication when no login file exis
sessionId: 'session',
sourceHome: join(root, 'missing'),
config: '',
- skill: '',
})
).resolves.toEqual(expect.any(String));
});
+
+it('removes a Switch skill file an earlier build left in the session home', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'codex-home-test-'));
+ roots.push(root);
+ const input = { root, sessionId: 'session', sourceHome: join(root, 'missing'), config: '' };
+ const home = await prepareCodexSessionHome(input);
+ await mkdir(join(home, 'skills/switch'), { recursive: true });
+ await writeFile(join(home, 'skills/switch/SKILL.md'), 'old copy');
+ await prepareCodexSessionHome(input);
+ await expect(stat(join(home, 'skills/switch'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('links the user’s own Codex skills into a session home that has no skills folder yet', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'codex-home-test-'));
+ roots.push(root);
+ const sourceHome = join(root, 'source');
+ await mkdir(join(sourceHome, 'skills', '.system'), { recursive: true });
+ await writeFile(join(sourceHome, 'skills', '.system', 'SKILL.md'), 'system skill');
+ const home = await prepareCodexSessionHome({
+ root: join(root, 'sessions'),
+ sessionId: 'session',
+ sourceHome,
+ config: '',
+ });
+ expect(await readFile(join(home, 'skills', '.system', 'SKILL.md'), 'utf8')).toBe('system skill');
+});
diff --git a/console/packages/agent-providers/src/codex/home.ts b/console/packages/agent-providers/src/codex/home.ts
index ab9befe8f..0c9461fcf 100644
--- a/console/packages/agent-providers/src/codex/home.ts
+++ b/console/packages/agent-providers/src/codex/home.ts
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto';
-import { chmod, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
+import { chmod, copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { parse, stringify } from 'smol-toml';
import { linkHomeAsset, linkSkills, optionalText } from '../host/provider-home';
@@ -10,7 +10,6 @@ export async function prepareCodexSessionHome(input: {
sessionId: string;
sourceHome: string;
config: string;
- skill: string;
}): Promise<string> {
const key = createHash('sha256').update(input.sessionId).digest('hex');
const home = join(input.root, key);
@@ -43,9 +42,9 @@ export async function prepareCodexSessionHome(input: {
await writeFile(join(home, 'config.toml'), stringify(config), { mode: 0o600 });
for (const name of ['AGENTS.md', 'rules', 'plugins', 'hooks.json'])
await linkHomeAsset(join(input.sourceHome, name), join(home, name));
- const skillDir = join(home, 'skills', 'switch');
- await mkdir(skillDir, { recursive: true });
- await writeFile(join(skillDir, 'SKILL.md'), input.skill);
+ // Earlier builds wrote the Switch skill here; it now arrives as developer
+ // instructions, and a leftover copy would only be read again by shell.
+ await rm(join(home, 'skills', 'switch'), { recursive: true, force: true });
await linkSkills(join(input.sourceHome, 'skills'), join(home, 'skills'));
return home;
}
diff --git a/console/packages/agent-providers/src/host/control.test.ts b/console/packages/agent-providers/src/host/control.test.ts
index 114a3fcd7..7dbf249ca 100644
--- a/console/packages/agent-providers/src/host/control.test.ts
+++ b/console/packages/agent-providers/src/host/control.test.ts
@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, expect, it, vi } from 'vitest';
import { CONTROL_FILE, ControlClient, serveControl } from './control';
-import { SessionLinks } from './session-channel';
+import { SessionHostFailedError, SessionLinks } from './session-channel';
import { WatcherControl } from './watcher-tools';
const paths = vi.hoisted(() => ({ base: '' }));
@@ -81,7 +81,11 @@ it('relays requests to a session host and its events back', async () => {
expect(await console.request('session', { type: 'snapshot' })).toBe('snapshot');
const heard: number[] = [];
- const unsubscribe = await console.subscribe('session', (pushed) => heard.push(pushed.sequence));
+ const unsubscribe = await console.subscribe(
+ 'session',
+ (pushed) => heard.push(pushed.sequence),
+ () => {}
+ );
child.emit('message', { kind: 'event', event: event(1) });
await vi.waitFor(() => expect(heard).toEqual([1]));
unsubscribe();
@@ -97,6 +101,58 @@ it('relays requests to a session host and its events back', async () => {
await expect(readFile(join(base, CONTROL_FILE))).rejects.toMatchObject({ code: 'ENOENT' });
});
+it('passes on why a session host failed, to a waiting request and to subscribers', async () => {
+ const { base, links, stop, serving, client } = await started();
+ const sessionRoot = join(base, 'session');
+ await mkdir(join(sessionRoot, 'supervisor'), { recursive: true });
+ await writeFile(join(sessionRoot, 'running'), 'yes');
+ const child = host();
+ links.attach(sessionRoot, child as unknown as ChildProcess);
+
+ const console = client();
+ await console.ready;
+ const failures: (string | null)[] = [];
+ const unsubscribe = await console.subscribe(
+ 'session',
+ () => {},
+ (failure) => failures.push(failure)
+ );
+ expect(failures).toEqual([null]);
+ const request = console.request('session', { type: 'snapshot' });
+ const refused = expect(request).rejects.toBeInstanceOf(SessionHostFailedError);
+ await writeFile(
+ join(sessionRoot, 'supervisor', 'failure.json'),
+ JSON.stringify({ message: 'Sign in on the execution machine with claude auth login.' })
+ );
+ child.emit('exit', 1, null);
+ await refused;
+ await vi.waitFor(() =>
+ expect(failures).toEqual([null, 'Sign in on the execution machine with claude auth login.'])
+ );
+ unsubscribe();
+
+ // A subscriber arriving after the failure hears it too.
+ const late: (string | null)[] = [];
+ const unsubscribeLate = await console.subscribe(
+ 'session',
+ () => {},
+ (failure) => late.push(failure)
+ );
+ expect(late).toEqual(['Sign in on the execution machine with claude auth login.']);
+ // And hears it cleared once a host comes up again.
+ const next = host();
+ links.attach(sessionRoot, next as unknown as ChildProcess);
+ next.emit('message', { kind: 'ready' });
+ await vi.waitFor(() =>
+ expect(late).toEqual(['Sign in on the execution machine with claude auth login.', null])
+ );
+ unsubscribeLate();
+
+ console.close();
+ stop.abort();
+ await serving;
+});
+
it('answers at once for a session nothing is running', async () => {
const { stop, serving, client } = await started();
const console = client();
@@ -125,7 +181,10 @@ it('moves a room to a session through the watcher, and says why when it cannot',
previous: null,
displaced: 'other',
}));
- const unbind = watcher.bind(placed);
+ const forgot = vi.fn(async () => {});
+ const unbind = watcher.bind({ place: placed, forget: forgot });
+ await console.forget('gone');
+ expect(forgot).toHaveBeenCalledWith('gone');
expect(await console.place('session', 'room')).toEqual({
sessionId: 'session',
roomId: 'room',
diff --git a/console/packages/agent-providers/src/host/control.ts b/console/packages/agent-providers/src/host/control.ts
index c5cc72f74..94854d5c5 100644
--- a/console/packages/agent-providers/src/host/control.ts
+++ b/console/packages/agent-providers/src/host/control.ts
@@ -7,6 +7,7 @@ import { serverEventSchema, type ServerEvent } from '@switch-console/shared/sess
import { z } from 'zod';
import { liveSupervisor, sharedSessionRoot } from './launch';
import {
+ SessionHostFailedError,
sessionRequestSchema,
SessionUnavailableError,
type SessionLinks,
@@ -45,6 +46,10 @@ const clientMessageSchema = z.union([
id: z.number().int(),
place: z.object({ sessionId: z.string().min(1), roomId: z.string().min(1) }),
}),
+ z.object({
+ id: z.number().int(),
+ forget: z.string().min(1),
+ }),
/** The room watcher's connection state and placements, as it holds them now. */
z.object({ id: z.number().int(), health: z.literal(true) }),
/** Start or stop pushing `{health}` to this connection whenever the watcher's changes. */
@@ -127,6 +132,7 @@ export async function serveControl(
ok: false,
error: error instanceof Error ? error.message : String(error),
unavailable: error instanceof SessionUnavailableError,
+ ...(error instanceof SessionHostFailedError ? { failure: error.failure } : {}),
})
);
if ('request' in parsed) {
@@ -139,18 +145,32 @@ export async function serveControl(
);
} else if ('subscribe' in parsed) {
const sessionId = parsed.subscribe;
- if (!subscriptions.has(sessionId))
- subscriptions.set(
- sessionId,
- links.subscribe(sharedSessionRoot(sessionId), (event) => send({ sessionId, event }))
- );
- void reply(Promise.resolve(null));
+ const sessionRoot = sharedSessionRoot(sessionId);
+ if (!subscriptions.has(sessionId)) {
+ const offEvents = links.subscribe(sessionRoot, (event) => send({ sessionId, event }));
+ const offFailure = links.onFailure((failed, failure) => {
+ if (failed === sessionRoot) send({ sessionId, failure });
+ });
+ // A host that comes up again has put its failure behind it.
+ const offReady = links.onReady((ready) => {
+ if (ready === sessionRoot) send({ sessionId, failure: null });
+ });
+ subscriptions.set(sessionId, () => {
+ offEvents();
+ offFailure();
+ offReady();
+ });
+ }
+ // Answered with the failure already recorded, so a subscriber that
+ // arrives after the host stopped still hears why.
+ void reply(Promise.resolve({ failure: links.failure(sessionRoot) }));
} else if ('unsubscribe' in parsed) {
subscriptions.get(parsed.unsubscribe)?.();
subscriptions.delete(parsed.unsubscribe);
void reply(Promise.resolve(null));
} else if ('place' in parsed)
void reply(watcher.place(parsed.place.sessionId, parsed.place.roomId));
+ else if ('forget' in parsed) void reply(watcher.forget(parsed.forget));
else if ('health' in parsed) void reply(Promise.resolve(watcher.health()));
else if ('watchHealth' in parsed) {
if (parsed.watchHealth) unwatchHealth ??= watcher.onHealth((health) => send({ health }));
@@ -194,8 +214,10 @@ const serverMessageSchema = z.union([
value: z.unknown().optional(),
error: z.string().optional(),
unavailable: z.boolean().optional(),
+ failure: z.string().optional(),
}),
z.object({ sessionId: z.string(), event: serverEventSchema }),
+ z.object({ sessionId: z.string(), failure: z.string().nullable() }),
z.object({ health: watcherHealthSchema }),
]);
@@ -222,6 +244,7 @@ export class ControlClient {
{ resolve: (value: unknown) => void; reject: (error: Error) => void }
>();
private readonly listeners = new Map<string, Set<(event: ServerEvent) => void>>();
+ private readonly failureListeners = new Map<string, Set<(failure: string | null) => void>>();
private readonly healthListeners = new Set<(health: WatcherHealth) => void>();
private readonly closeListeners = new Set<(error: Error) => void>();
private closed: Error | null = null;
@@ -256,6 +279,9 @@ export class ControlClient {
if ('authenticated' in data) authenticate();
else if ('event' in data)
for (const listener of this.listeners.get(data.sessionId) ?? []) listener(data.event);
+ else if ('sessionId' in data)
+ for (const listener of this.failureListeners.get(data.sessionId) ?? [])
+ listener(data.failure);
else if ('health' in data) for (const listener of this.healthListeners) listener(data.health);
else {
const pending = this.pending.get(data.id);
@@ -263,6 +289,8 @@ export class ControlClient {
this.pending.delete(data.id);
const message = data.error ?? 'The sidecar refused the request.';
if (data.ok) pending.resolve(data.value);
+ else if (data.failure !== undefined)
+ pending.reject(new SessionHostFailedError(data.failure));
else if (data.unavailable) pending.reject(new SessionUnavailableError(message));
else pending.reject(new Error(message));
}
@@ -296,6 +324,11 @@ export class ControlClient {
return placeOutcomeSchema.parse(await this.call({ place: { sessionId, roomId } }));
}
+ /** Tell the sidecar's room watcher a session was deleted. */
+ async forget(sessionId: string): Promise<void> {
+ await this.call({ forget: sessionId });
+ }
+
/** The sidecar's room watcher: its connection state and placements. */
async health(): Promise<WatcherHealth> {
return watcherHealthSchema.parse(await this.call({ health: true }));
@@ -332,16 +365,38 @@ export class ControlClient {
return () => this.closeListeners.delete(listener);
}
- async subscribe(sessionId: string, listener: (event: ServerEvent) => void): Promise<() => void> {
+ /**
+ * Hear every event the session's host records, and `onFailure` with why it
+ * stopped each time it stops on a failure, and with null when a host comes
+ * up again. The first subscriber also hears the failure standing when it
+ * subscribed, null if there is none.
+ */
+ async subscribe(
+ sessionId: string,
+ listener: (event: ServerEvent) => void,
+ onFailure: (failure: string | null) => void
+ ): Promise<() => void> {
let set = this.listeners.get(sessionId);
+ let failures = this.failureListeners.get(sessionId);
+ if (!failures) {
+ failures = new Set();
+ this.failureListeners.set(sessionId, failures);
+ }
+ failures.add(onFailure);
if (!set) {
set = new Set();
this.listeners.set(sessionId, set);
- await this.call({ subscribe: sessionId });
+ const answer = z
+ .object({ failure: z.string().nullable() })
+ .nullable()
+ .parse(await this.call({ subscribe: sessionId }));
+ onFailure(answer?.failure ?? null);
}
set.add(listener);
return () => {
set.delete(listener);
+ failures.delete(onFailure);
+ if (!failures.size) this.failureListeners.delete(sessionId);
if (set.size) return;
this.listeners.delete(sessionId);
if (!this.closed) void this.call({ unsubscribe: sessionId }).catch(() => {});
diff --git a/console/packages/agent-providers/src/host/launch.ts b/console/packages/agent-providers/src/host/launch.ts
index bd3657a0f..05fb598b6 100644
--- a/console/packages/agent-providers/src/host/launch.ts
+++ b/console/packages/agent-providers/src/host/launch.ts
@@ -205,6 +205,7 @@ async function launch(input: LaunchInput): Promise<{ created: boolean }> {
if (running.build === input.supervision.build) return { created };
await input.supervision.stop(input.root);
}
+ input.supervision.links?.clearFailure(input.root);
await unlink(join(input.root, 'supervisor', 'failure.json')).catch(
(error: NodeJS.ErrnoException) => {
if (error.code !== 'ENOENT') throw error;
diff --git a/console/packages/agent-providers/src/host/provider-home.ts b/console/packages/agent-providers/src/host/provider-home.ts
index 5c8abc97a..02baf7f0a 100644
--- a/console/packages/agent-providers/src/host/provider-home.ts
+++ b/console/packages/agent-providers/src/host/provider-home.ts
@@ -1,4 +1,4 @@
-import { lstat, readdir, readFile, symlink } from 'node:fs/promises';
+import { lstat, mkdir, readFile, readdir, symlink } from 'node:fs/promises';
import { join } from 'node:path';
export async function optionalText(path: string): Promise<string | null> {
@@ -39,6 +39,7 @@ export async function linkSkills(source: string, destination: string): Promise<v
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
throw error;
}
+ await mkdir(destination, { recursive: true });
for (const entry of entries) {
if (entry === 'switch') continue;
await linkHomeAsset(join(source, entry), join(destination, entry));
diff --git a/console/packages/agent-providers/src/host/session-channel.test.ts b/console/packages/agent-providers/src/host/session-channel.test.ts
index 941ad5f6a..b2a3f4ae5 100644
--- a/console/packages/agent-providers/src/host/session-channel.test.ts
+++ b/console/packages/agent-providers/src/host/session-channel.test.ts
@@ -1,7 +1,15 @@
import type { ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { afterEach, expect, it, vi } from 'vitest';
-import { connectParent, SessionLinks, SessionUnavailableError } from './session-channel';
+import {
+ connectParent,
+ SessionHostFailedError,
+ SessionLinks,
+ SessionUnavailableError,
+} from './session-channel';
/** A child process as far as the parent's end can tell: messages both ways, and an exit. */
function fakeChild() {
@@ -54,11 +62,61 @@ it('refuses when no host comes, and when the host goes before answering', async
child.emit('message', { kind: 'ready' });
const answer = links.request('root', { type: 'snapshot' }, 1000);
await vi.waitFor(() => expect(child.sent).toHaveLength(1));
- child.emit('exit', 1, null);
+ child.emit('exit', null, 'SIGKILL');
await expect(answer).rejects.toThrow('stopped before it answered');
expect(links.ready('root')).toBe(false);
});
+it('refuses a waiting request as soon as the host stops on a failure it recorded', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'session-channel-'));
+ try {
+ await mkdir(join(root, 'supervisor'));
+ const links = new SessionLinks();
+ const failures: string[] = [];
+ links.onFailure((failed, failure) => failures.push(`${failed === root}:${failure}`));
+ const child = fakeChild();
+ links.attach(root, child as unknown as ChildProcess);
+ const started = Date.now();
+ const answer = links.request(root, { type: 'snapshot' }, 60000);
+ await writeFile(
+ join(root, 'supervisor', 'failure.json'),
+ JSON.stringify({ message: 'Sign in on the execution machine with claude auth login.' })
+ );
+ child.emit('exit', 1, null);
+ await expect(answer).rejects.toThrow(SessionHostFailedError);
+ await expect(answer).rejects.toMatchObject({
+ failure: 'Sign in on the execution machine with claude auth login.',
+ });
+ expect(Date.now() - started).toBeLessThan(5000);
+ expect(failures).toEqual(['true:Sign in on the execution machine with claude auth login.']);
+ // Asked again, it is refused at once rather than after the wait.
+ await expect(links.request(root, { type: 'snapshot' }, 60000)).rejects.toThrow(
+ SessionHostFailedError
+ );
+ expect(links.failure(root)).toBe('Sign in on the execution machine with claude auth login.');
+
+ // Cleared once something starts it again, and by the next host.
+ links.clearFailure(root);
+ expect(links.failure(root)).toBeNull();
+ const again = fakeChild();
+ links.attach(root, again as unknown as ChildProcess);
+ again.emit('exit', 3, null);
+ expect(links.failure(root)).toBe('Sign in on the execution machine with claude auth login.');
+ links.attach(root, fakeChild() as unknown as ChildProcess);
+ expect(links.failure(root)).toBeNull();
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+it('says why when a failed host left no record of it', () => {
+ const links = new SessionLinks();
+ const child = fakeChild();
+ links.attach('/nonexistent-session-root', child as unknown as ChildProcess);
+ child.emit('exit', 2, null);
+ expect(links.failure('/nonexistent-session-root')).toBe('The session host exited with code 2.');
+});
+
it('passes a refusal on as an error, and every pushed event to subscribers', async () => {
const links = new SessionLinks();
const heard: number[] = [];
diff --git a/console/packages/agent-providers/src/host/session-channel.ts b/console/packages/agent-providers/src/host/session-channel.ts
index b2670fdb0..28c9d50c4 100644
--- a/console/packages/agent-providers/src/host/session-channel.ts
+++ b/console/packages/agent-providers/src/host/session-channel.ts
@@ -1,6 +1,9 @@
import type { ChildProcess } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
import { serverEventSchema, type ServerEvent } from '@switch-console/shared/session-v1';
import { z } from 'zod';
+import { LEASE_EXPIRED_EXIT_CODE } from './exit-codes';
/**
* The pipe between a session host and the process that started it.
@@ -111,6 +114,37 @@ export class SessionUnavailableError extends Error {
}
}
+/**
+ * Raised when a session host stopped on a failure it recorded, and nothing has
+ * started it again since. Starting it again without changing anything would
+ * fail the same way, so the caller decides whether to.
+ */
+export class SessionHostFailedError extends Error {
+ constructor(readonly failure: string) {
+ super(`The session host failed: ${failure}`);
+ this.name = 'SessionHostFailedError';
+ }
+}
+
+/**
+ * Why the host at this root stopped, from the `supervisor/failure.json` it
+ * writes before exiting on an error; a plain account of the exit when it
+ * wrote none.
+ */
+function recordedFailure(root: string, code: number): string {
+ try {
+ const recorded = z
+ .object({ message: z.string().min(1) })
+ .safeParse(JSON.parse(readFileSync(join(root, 'supervisor', 'failure.json'), 'utf8')));
+ if (recorded.success) return recorded.data.message;
+ console.warn(`The failure the session host at ${root} recorded is unreadable.`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')
+ console.warn(`Could not read why the session host at ${root} failed: ${String(error)}`);
+ }
+ return `The session host exited with code ${code}.`;
+}
+
type Pending = {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
@@ -121,6 +155,8 @@ type Link = {
child: ChildProcess | null;
ready: boolean;
identity: HostIdentity | null;
+ /** Why the last host here stopped on an error, until another is started. */
+ failure: string | null;
nextId: number;
pending: Map<number, Pending>;
waiting: (() => void)[];
@@ -135,6 +171,8 @@ export class SessionLinks {
private readonly links = new Map<string, Link>();
private readonly answerers = new Map<string, AskHandler>();
private readonly exitListeners = new Set<(root: string, identity: HostIdentity | null) => void>();
+ private readonly readyListeners = new Set<(root: string) => void>();
+ private readonly failureListeners = new Set<(root: string, failure: string) => void>();
private link(root: string): Link {
let link = this.links.get(root);
@@ -143,6 +181,7 @@ export class SessionLinks {
child: null,
ready: false,
identity: null,
+ failure: null,
nextId: 0,
pending: new Map(),
waiting: [],
@@ -159,6 +198,7 @@ export class SessionLinks {
link.child = child;
link.ready = false;
link.identity = null;
+ link.failure = null;
child.on('message', (raw) => {
const parsed = fromChildSchema.safeParse(raw);
if (!parsed.success) {
@@ -169,6 +209,7 @@ export class SessionLinks {
if (message.kind === 'ready') {
link.ready = true;
for (const wake of link.waiting.splice(0)) wake();
+ for (const listener of this.readyListeners) listener(root);
} else if (message.kind === 'event') {
for (const subscriber of link.subscribers) subscriber(message.event);
} else if (message.kind === 'identity') {
@@ -194,18 +235,30 @@ export class SessionLinks {
else pending.reject(new Error(message.error ?? 'The session host refused the request.'));
}
});
- child.once('exit', () => {
+ child.once('exit', (code) => {
if (link.child !== child) return;
const identity = link.identity;
link.child = null;
link.ready = false;
link.identity = null;
+ // A non-zero exit other than a lapsed lease is one the supervisor does
+ // not recover from: the host has already written why.
+ if (code !== null && code !== 0 && code !== LEASE_EXPIRED_EXIT_CODE)
+ link.failure = recordedFailure(root, code);
+ const failure = link.failure;
for (const [id, pending] of link.pending) {
clearTimeout(pending.timer);
- pending.reject(new SessionUnavailableError('The session host stopped before it answered.'));
+ pending.reject(
+ failure !== null
+ ? new SessionHostFailedError(failure)
+ : new SessionUnavailableError('The session host stopped before it answered.')
+ );
link.pending.delete(id);
}
+ // A request waiting for this host to come up learns now that it will not.
+ for (const wake of link.waiting.splice(0)) wake();
for (const listener of this.exitListeners) listener(root, identity);
+ if (failure !== null) for (const listener of this.failureListeners) listener(root, failure);
});
}
@@ -249,6 +302,29 @@ export class SessionLinks {
return () => this.exitListeners.delete(listener);
}
+ /** Hear each host say it is ready for requests. */
+ onReady(listener: (root: string) => void): () => void {
+ this.readyListeners.add(listener);
+ return () => this.readyListeners.delete(listener);
+ }
+
+ /** Hear each host stop on a failure, with the failure it recorded. */
+ onFailure(listener: (root: string, failure: string) => void): () => void {
+ this.failureListeners.add(listener);
+ return () => this.failureListeners.delete(listener);
+ }
+
+ /** Why the last host at this root stopped on an error, or null if it did not. */
+ failure(root: string): string | null {
+ return this.links.get(root)?.failure ?? null;
+ }
+
+ /** Forgets a recorded failure: something is about to start the host again. */
+ clearFailure(root: string): void {
+ const link = this.links.get(root);
+ if (link) link.failure = null;
+ }
+
/** Whether a host is running at this root and ready for requests. */
ready(root: string): boolean {
return this.links.get(root)?.ready === true;
@@ -256,12 +332,14 @@ export class SessionLinks {
/**
* Ask the host, waiting up to `timeoutMs` for one to be ready if it is
- * still starting. Refused with `SessionUnavailableError` when none comes.
+ * still starting. Refused with `SessionUnavailableError` when none comes,
+ * and with `SessionHostFailedError` as soon as the host stops on a failure.
*/
async request(root: string, request: SessionRequest, timeoutMs: number): Promise<unknown> {
const link = this.link(root);
const deadline = Date.now() + timeoutMs;
while (!link.ready || !link.child) {
+ if (link.failure !== null) throw new SessionHostFailedError(link.failure);
const remaining = deadline - Date.now();
if (remaining <= 0) throw new SessionUnavailableError('The session host is not running.');
await new Promise<void>((resolve) => {
diff --git a/console/packages/agent-providers/src/host/session-host.test.ts b/console/packages/agent-providers/src/host/session-host.test.ts
index 6ec6d8e6f..5152c62d4 100644
--- a/console/packages/agent-providers/src/host/session-host.test.ts
+++ b/console/packages/agent-providers/src/host/session-host.test.ts
@@ -363,8 +363,14 @@ it('resets into a new epoch and native conversation while retaining history', as
const { host, adapter, emit, root } = await start('claude');
await host.command(message('old-turn'));
await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
+ // Completed only after the provider reported the turn started, or its late
+ // start would put the turn back to running.
+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
emit({ type: 'turn.completed', turnId: 'old-turn', outcome: 'completed', usage: [] });
await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ // The turn reads completed a moment before the session reads ready again,
+ // and a reset is refused until it does.
+ await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
vi.mocked(adapter.startSession).mockImplementationOnce(async () => {
emit({ type: 'session.state.changed', status: 'ready' });
return { provider: 'claude', sessionId: 'session', nativeSessionId: 'fresh-native' };
@@ -524,6 +530,25 @@ it('resumes an ordinary interrupted session without a reset decision', async ()
await vi.waitFor(() => expect(resumed.snapshot().session.status).toBe('ready'));
});
+it('starts a new conversation on its own when the saved one is gone and never answered', async () => {
+ const { host, root } = await start('claude');
+ await host.shutdown();
+ const next = setup('claude');
+ vi.mocked(next.adapter.startSession).mockRejectedValueOnce(
+ new ProviderConversationUnavailableError('claude', 'session', 'No saved conversation')
+ );
+ const restarted = await HostedSession.start(root, next.config, next.adapter);
+ hosts.push(restarted);
+ expect(restarted.resetDecisionPending).toBe(false);
+ expect(next.adapter.startSession).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(next.adapter.startSession).mock.calls[1][0].resume).toBeUndefined();
+ await vi.waitFor(() =>
+ expect(restarted.replay(0).events.map((e) => e.body)).toContainEqual(
+ expect.objectContaining({ code: 'CONVERSATION_STARTED_FRESH' })
+ )
+ );
+});
+
it('validates native model choices and persists a confirmed choice across restart', async () => {
const root = await mkdtemp(join(tmpdir(), 'sdk-model-test-'));
roots.push(root);
@@ -733,7 +758,16 @@ it('rejects unsupported native compaction without faulting the session', async (
});
it('requires an explicit fresh reset when the provider cannot resume the saved conversation', async () => {
- const { host, root } = await start('codex');
+ const { host, adapter, emit, root } = await start('codex');
+ // The provider has answered, so the lost conversation held something.
+ await host.command(message('answered'));
+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('running'));
+ // Completed only after the provider reported the turn started, or its late
+ // start would put the turn back to running.
+ await vi.waitFor(() => expect(adapter.sendTurn).toHaveBeenCalledOnce());
+ emit({ type: 'turn.completed', turnId: 'answered', outcome: 'completed', usage: [] });
+ await vi.waitFor(() => expect(host.snapshot().turns[0]?.status).toBe('completed'));
+ await vi.waitFor(() => expect(host.snapshot().session.status).toBe('ready'));
await host.shutdown();
const next = setup('codex');
vi.mocked(next.adapter.startSession).mockRejectedValueOnce(
diff --git a/console/packages/agent-providers/src/host/session-host.ts b/console/packages/agent-providers/src/host/session-host.ts
index 43db3526c..d81318bc3 100644
--- a/console/packages/agent-providers/src/host/session-host.ts
+++ b/console/packages/agent-providers/src/host/session-host.ts
@@ -120,6 +120,7 @@ export class HostedSession {
items: [],
requests: [],
commandStatuses: [],
+ notices: [],
nextPageToken: null,
};
// Replay old history before announcing the recovered generation.
@@ -285,8 +286,24 @@ export class HostedSession {
.catch((error: unknown) => host.fail(error));
return host;
} catch (error) {
- if (error instanceof ProviderConversationUnavailableError && host.nativeId) {
+ if (
+ error instanceof ProviderConversationUnavailableError &&
+ (host.nativeId || config.input.resume)
+ ) {
await host.eventSerial;
+ // Nothing the provider said is lost when it never answered (a session
+ // whose turns all failed while its CLI was signed out, say): start a
+ // new conversation rather than ask.
+ if (!host.providerAnswered()) {
+ try {
+ await host.startFresh();
+ return host;
+ } catch (fresh) {
+ await host.fail(fresh);
+ await host.shutdown();
+ throw fresh;
+ }
+ }
await host.awaitResetDecision('NATIVE_CONVERSATION_UNAVAILABLE', error.message);
return host;
}
@@ -296,6 +313,42 @@ export class HostedSession {
}
}
+ /** Whether the provider has ever answered in this session. */
+ private providerAnswered(): boolean {
+ const snapshot = this.replica.snapshot();
+ return (
+ snapshot.items.some((item) => item.kind === 'assistant-message') ||
+ snapshot.turns.some((turn) => turn.status === 'completed')
+ );
+ }
+
+ /** Start a new provider conversation in place of one that cannot be resumed. */
+ private async startFresh(): Promise<void> {
+ const { resume: _resume, ...fresh } = this.config.input;
+ const native = await this.startProvider(fresh);
+ await this.inbox.append({ type: 'native', nativeSessionId: native.nativeSessionId });
+ this.nativeId = native.nativeSessionId;
+ await this.eventSerial;
+ void this.refreshModels()
+ .catch(async (error: unknown) => {
+ if (this.shuttingDown) return;
+ await this.publish({
+ type: 'notice',
+ level: 'warning',
+ code: 'MODEL_CATALOG_UNAVAILABLE',
+ message: `Could not load provider models: ${String(error)}`,
+ });
+ })
+ .catch((error: unknown) => this.fail(error));
+ await this.publish({
+ type: 'notice',
+ level: 'info',
+ code: 'CONVERSATION_STARTED_FRESH',
+ message:
+ 'Started a new provider conversation: the earlier one was never saved by the provider, so there was nothing to resume.',
+ });
+ }
+
private async startProvider(input: ProviderSessionStartInput) {
const [authentication, provider] = await Promise.allSettled([
Promise.resolve().then(() => this.config.authenticate?.()),
diff --git a/console/packages/agent-providers/src/host/shared-config.test.ts b/console/packages/agent-providers/src/host/shared-config.test.ts
index 0888c26f8..2eb6224cf 100644
--- a/console/packages/agent-providers/src/host/shared-config.test.ts
+++ b/console/packages/agent-providers/src/host/shared-config.test.ts
@@ -88,3 +88,69 @@ it('gives the provider the host’s own MCP server and no Switch identity', asyn
await rm(root, { recursive: true, force: true });
}
});
+
+it('gives Codex the Switch skill as instructions, like the other providers', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-config-test-'));
+ try {
+ const credentialsPath = join(root, 'credentials.json');
+ await writeFile(
+ credentialsPath,
+ JSON.stringify({
+ env: {
+ SWITCH_API_ENDPOINT: 'https://switch.test',
+ SWITCH_API_TOKEN: 'agent-token',
+ SWITCH_AGENT_ID: 'agent',
+ },
+ })
+ );
+ const config = sharedConfigSchema.parse({
+ session: {
+ sessionId: 'session',
+ agentId: 'agent',
+ hostId: 'host',
+ epoch: 'epoch',
+ provider: 'codex',
+ status: 'starting',
+ connectivity: 'online',
+ pendingRequestIds: [],
+ capabilities: {
+ input: 'queue',
+ approvals: true,
+ questions: true,
+ interrupt: true,
+ reset: false,
+ compact: false,
+ modelChange: false,
+ attachmentMimeTypes: [],
+ },
+ },
+ start: {
+ provider: 'codex',
+ input: {
+ sessionId: 'session',
+ cwd: root,
+ runtimeMode: 'approval-required',
+ env: { CONFIGURED: 'yes', CODEX_HOME: join(root, 'codex-source') },
+ mcpServers: {},
+ },
+ },
+ roomConnection: { connectionId: 'controller' },
+ execution: {
+ credentialsPath,
+ inheritEnv: [],
+ codexConfig: '',
+ skill: '',
+ context: 'Switch skill text',
+ },
+ });
+ const runtime = {
+ transport: 'http' as const,
+ url: 'http://127.0.0.1:4321/mcp',
+ headers: { Authorization: 'Bearer per-session' },
+ };
+ const prepared = await prepareSharedConfig(root, config, runtime);
+ expect(prepared.input.systemContext).toBe('Switch skill text');
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/console/packages/agent-providers/src/host/shared-config.ts b/console/packages/agent-providers/src/host/shared-config.ts
index 3a65a9b0d..5e38fc236 100644
--- a/console/packages/agent-providers/src/host/shared-config.ts
+++ b/console/packages/agent-providers/src/host/shared-config.ts
@@ -88,9 +88,8 @@ export async function prepareSharedConfig(
sessionId: config.session.sessionId,
sourceHome: input.env.CODEX_HOME || join(homedir(), '.codex'),
config: execution.codexConfig,
- skill: execution.skill,
});
- if (config.start.provider !== 'codex') input.systemContext = execution.context;
+ input.systemContext = execution.context;
}
input.mcpServers.switch = runtime;
if (!agentApiUrl || !token)
diff --git a/console/packages/agent-providers/src/host/shared-watcher.test.ts b/console/packages/agent-providers/src/host/shared-watcher.test.ts
index c02da43fa..c2dfe1ee6 100644
--- a/console/packages/agent-providers/src/host/shared-watcher.test.ts
+++ b/console/packages/agent-providers/src/host/shared-watcher.test.ts
@@ -1,12 +1,13 @@
import type { ChildProcess } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
-import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type * as runtime from '@sandboxaq/switch-agent-runtime';
import type { AgentBridgeEvent, SwitchEventStreamDeps } from '@sandboxaq/switch-agent-runtime';
import { afterEach, expect, it, vi } from 'vitest';
+import type { Handoff } from './handoff';
import { ensureSharedProcess, type Supervision } from './launch';
import { type SessionRequest, SessionLinks } from './session-channel';
import { sharedConfigSchema } from './shared-config';
@@ -88,6 +89,11 @@ function sessionHosts() {
links,
requests,
drop: false,
+ /**
+ * When set, each host started fails before it is ready, recording this
+ * as why — what a host whose provider CLI is not signed in does.
+ */
+ fail: null as string | null,
supervision: {
build: 'build',
start: async () => {},
@@ -108,13 +114,23 @@ function sessionHosts() {
const { id, request } = message as { id: number; request: SessionRequest };
requests.push({ root, request });
setImmediate(() => {
- if (hosts.drop) child.emit('exit', 1, null);
+ if (hosts.drop) child.emit('exit', null, 'SIGKILL');
else child.emit('message', { kind: 'reply', id, ok: true, value: null });
});
return true;
};
children.set(root, child);
links.attach(root, child as unknown as ChildProcess);
+ const failure = hosts.fail;
+ if (failure !== null) {
+ await mkdir(join(root, 'supervisor'), { recursive: true });
+ await writeFile(
+ join(root, 'supervisor', 'failure.json'),
+ JSON.stringify({ message: failure })
+ );
+ setImmediate(() => child.emit('exit', 1, null));
+ return { created: true };
+ }
child.emit('message', { kind: 'ready' });
return { created: true };
},
@@ -1196,6 +1212,38 @@ it('gives a room a new session once the one serving it has been stopped', async
]);
});
+it('forgets a session Console deleted, so its room starts a new one', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-deleted-owner-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const owner = await existing(root, config);
+ await assignTo(root, config, 1, 'room', owner.sessionId);
+ const hosts = sessionHosts();
+ const control = new WatcherControl();
+
+ const abort = new AbortController();
+ const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, control);
+ try {
+ await eventually(() => streams.length === 1);
+ await control.forget(owner.sessionId);
+ await expect(stat(owner.sessionRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ await streams[0]!.onEvent!(addressed(2, 'room'));
+ await eventually(() => settled(root));
+ } finally {
+ abort.abort();
+ await run;
+ }
+ const sessions = (await SharedWatchAssignments.open(root)).sessions();
+ const fresh = sessions.at(-1)!.session.sessionId;
+ expect(fresh).not.toBe(owner.sessionId);
+ expect(hosts.to(owner.sessionRoot)).toEqual([]);
+ expect(published.at(-1)).toEqual({ [fresh]: 'room' });
+ expect(hosts.to(join(root, fresh))).toMatchObject([
+ { type: 'room', handoff: { messageId: 'message-2' } },
+ ]);
+});
+
it('passes an approval answer to the session it is for, and only that one', async () => {
const root = await mkdtemp(join(tmpdir(), 'shared-watch-approvals-'));
roots.push(root);
@@ -1399,3 +1447,139 @@ it('reports a room connection that is turned off, and a watcher that failed', as
expect(control.health().state).toBe('not-running');
expect(control.health().detail).toContain('credentials.json');
});
+
+/** Answers the Switch operations the watcher calls as a session, recording each. */
+function switchOperations(answers: { owner: string | null; refuseTargeted?: boolean }) {
+ const calls: { name: string; body: Record<string, unknown>; session: string | null }[] = [];
+ vi.stubGlobal('fetch', async (url: string, init: RequestInit = {}) => {
+ const name = String(url).split('/ops/')[1] ?? '';
+ const headers = init.headers as Record<string, string>;
+ calls.push({
+ name,
+ body: JSON.parse(String(init.body ?? '{}')),
+ session: headers['X-Switch-Session-Id'] ?? null,
+ });
+ if (name === 'get_agent_detail')
+ return new Response(JSON.stringify({ result: { owner_name: answers.owner } }));
+ if (name === 'send_targeted_message' && answers.refuseTargeted)
+ return new Response('Targets not in room: ada', { status: 400 });
+ return new Response(JSON.stringify({ result: { event_id: 'posted' } }));
+ });
+ return calls;
+}
+
+const SIGN_IN = 'Sign in on the execution machine with claude auth login.';
+
+it('stops starting a session whose host failed, keeps its message, and tells its owner once', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-failed-start-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const hosts = sessionHosts();
+ hosts.fail = SIGN_IN;
+ const calls = switchOperations({ owner: 'ada' });
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const abort = new AbortController();
+ const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());
+ try {
+ await eventually(() => streams.length === 1);
+ const first = addressed(1, 'room');
+ (first.payload as { thread_id?: string }).thread_id = 'thread-root';
+ const started = Date.now();
+ await streams[0]!.onEvent!(first);
+ await eventually(() => calls.some((call) => call.name === 'send_targeted_message'));
+ // Told at once rather than after the wait for a host to come up.
+ expect(Date.now() - started).toBeLessThan(5000);
+ const sessionId = placementsOf(published).room!;
+ expect(calls.map((call) => call.name)).toEqual(['get_agent_detail', 'send_targeted_message']);
+ expect(calls[1]).toEqual({
+ name: 'send_targeted_message',
+ session: sessionId,
+ body: {
+ body: `I couldn't start a session, and it needs you to fix it: ${SIGN_IN} Then address me again.`,
+ target_names: ['ada'],
+ thread_id: 'thread-root',
+ },
+ });
+ // No retry loop: nothing starts the host again on its own.
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(vi.mocked(ensureSharedProcess)).toHaveBeenCalledTimes(1);
+ expect(error.mock.calls.some((call) => String(call[0]).includes(SIGN_IN))).toBe(true);
+
+ // A later message tries once more, and that message is answered too.
+ await streams[0]!.onEvent!(addressed(2, 'room'));
+ await eventually(() => vi.mocked(ensureSharedProcess).mock.calls.length === 2);
+ await eventually(
+ () => calls.filter((call) => call.name === 'send_targeted_message').length === 2
+ );
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ expect(vi.mocked(ensureSharedProcess)).toHaveBeenCalledTimes(2);
+ expect(calls.filter((call) => call.name === 'send_targeted_message')).toHaveLength(2);
+
+ // Both messages are still owed.
+ expect((await SharedWatchAssignments.open(root)).pending().map((e) => e.messageId)).toEqual([
+ 'message-1',
+ 'message-2',
+ ]);
+
+ // Started from Console once it is fixed: the waiting messages go to it.
+ hosts.fail = null;
+ await hosts.start(join(root, sessionId));
+ await eventually(() => settled(root));
+ expect(
+ hosts.to(join(root, sessionId)).map((request) => (request as { handoff: Handoff }).handoff)
+ ).toMatchObject([{ messageId: 'message-1' }, { messageId: 'message-2' }]);
+ } finally {
+ abort.abort();
+ await run;
+ }
+});
+
+it('tells the room without addressing anyone when the owner cannot be addressed, and survives a refused post', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-failed-owner-'));
+ roots.push(root);
+ paths.root = root;
+ const config = await spawning(root);
+ const hosts = sessionHosts();
+ hosts.fail = SIGN_IN;
+ const calls = switchOperations({ owner: 'ada', refuseTargeted: true });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const abort = new AbortController();
+ const run = runSharedWatcher(root, config, abort.signal, hosts.supervision, new WatcherControl());
+ try {
+ await eventually(() => streams.length === 1);
+ await streams[0]!.onEvent!(addressed(1, 'room'));
+ await eventually(() => calls.some((call) => call.name === 'post_message'));
+ expect(calls.find((call) => call.name === 'post_message')!.body).toEqual({
+ body: `I couldn't start a session, and my owner (ada) needs to fix it: ${SIGN_IN} Then address me again.`,
+ });
+ expect(warn.mock.calls.some((call) => String(call[0]).includes('Targets not in room'))).toBe(
+ true
+ );
+
+ // A different failure is news, and a post Switch refuses is logged, not fatal.
+ hosts.fail = 'The provider executable is missing.';
+ vi.stubGlobal('fetch', async () => new Response('down', { status: 503 }));
+ await streams[0]!.onEvent!(addressed(2, 'room'));
+ await eventually(() =>
+ error.mock.calls.some((call) =>
+ String(call[0]).includes('Could not tell room room that session')
+ )
+ );
+ expect(streams).toHaveLength(1);
+ } finally {
+ abort.abort();
+ await run;
+ }
+});
+
+/** The last placements map the watcher stated to Switch, room → session. */
+function placementsOf(maps: Record<string, string>[]): Record<string, string> {
+ return Object.fromEntries(
+ Object.entries(maps.at(-1) ?? {}).map(([session, room]) => [room, session])
+ );
+}
diff --git a/console/packages/agent-providers/src/host/shared-watcher.ts b/console/packages/agent-providers/src/host/shared-watcher.ts
index 19eb9e965..9c52379ed 100644
--- a/console/packages/agent-providers/src/host/shared-watcher.ts
+++ b/console/packages/agent-providers/src/host/shared-watcher.ts
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from 'node:crypto';
-import { mkdir, readdir, readFile } from 'node:fs/promises';
+import { mkdir, readdir, readFile, rm } from 'node:fs/promises';
import { join } from 'node:path';
import {
EVICTION_HEARTBEAT_LAPSED,
@@ -20,11 +20,16 @@ import {
import { releaseOwner, replaceOwner, withOwnershipLock } from './ownership-lock';
import { SessionPlacements } from './placements';
import { roomInputId } from './room-inbox';
-import { type SessionRequest, SessionUnavailableError } from './session-channel';
+import {
+ SessionHostFailedError,
+ type SessionRequest,
+ SessionUnavailableError,
+} from './session-channel';
import { readSharedCredentials, sharedConfigSchema, type SharedHostConfig } from './shared-config';
import { readTakenOver, recordTakenOver } from './taken-over';
import { awaitWatchChange, readWatchFlags } from './watch-flags';
import {
+ announceStartFailure,
type PlaceOutcome,
sessionToolAnswerer,
type WatcherControl,
@@ -119,6 +124,14 @@ const HOST_START_MS = 120000;
/** How often a room still waiting for an owner says so again. */
const HELD_DISCLOSURE_MS = 30000;
+/** The thread a room message was posted in, or null for a top-level one. */
+function threadOf(event: unknown): string | null {
+ const parsed = z
+ .object({ payload: z.object({ thread_id: z.string().min(1).nullish() }) })
+ .safeParse(event);
+ return parsed.success ? (parsed.data.payload.thread_id ?? null) : null;
+}
+
function sessionIdFor(agentId: string, roomId: string, messageId: string): string {
const bytes = createHash('sha256')
.update(JSON.stringify([agentId, roomId, messageId]))
@@ -556,6 +569,21 @@ export async function runSharedWatcher(
unbind.push(
links.answer(agentId, sessionToolAnswerer({ identity, connectionId, placements, publish }))
);
+ // A host coming up — started from Console after it failed, say — takes
+ // the messages that waited for it.
+ unbind.push(
+ links.onReady((readyRoot) => {
+ for (const [sessionId, entry] of pumps) {
+ if (sharedSessionRoot(sessionId) !== readyRoot) continue;
+ if (entry.failed === null) continue;
+ console.warn(
+ `Session ${sessionId} is running again; handing it the ${entry.queue.length} room message(s) that waited for it.`
+ );
+ entry.failed = null;
+ pump(entry.config);
+ }
+ })
+ );
unbind.push(
links.onExit((_root, exited) => {
if (!exited || exited.agentId !== agentId) return;
@@ -612,17 +640,55 @@ export async function runSharedWatcher(
return false;
}
};
+ /**
+ * The room messages already answered with a start failure: each message
+ * that runs into it is answered once, however often the host is retried.
+ */
+ const announced = new Set<string>();
+ const announce = async (config: SharedHostConfig, event: Handoff, failure: string) => {
+ const sessionId = config.session.sessionId;
+ const key = `${sessionId}:${event.roomId}:${event.messageId}`;
+ if (announced.has(key)) return;
+ announced.add(key);
+ try {
+ // Switch answers the call from where it holds the session placed.
+ await publish();
+ await announceStartFailure({
+ identity,
+ connectionId,
+ session: config.session,
+ root: sharedSessionRoot(sessionId),
+ cwd: config.start.input.cwd,
+ threadId: threadOf(event.event),
+ failure,
+ });
+ } catch (error) {
+ console.error(
+ `Could not tell room ${event.roomId} that session ${sessionId} failed to start (${failure}): ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ }
+ };
/**
* Per session, the messages handed to it and not yet acknowledged, sent
* down the IPC pipe one at a time and in order. Each is parked in the
* journal first and released on the host's acknowledgement, so one this
* controller dies holding is routed again when it restarts.
+ *
+ * `failed` is set when the host stopped on a failure it recorded: the
+ * messages stay queued and the host is not started again until something
+ * changes — another room message for it, or its host coming up because
+ * somebody started it from Console.
*/
- const pumps = new Map<string, { queue: Handoff[]; running: boolean }>();
+ const pumps = new Map<
+ string,
+ { queue: Handoff[]; running: boolean; failed: string | null; config: SharedHostConfig }
+ >();
const pump = (config: SharedHostConfig) => {
const sessionId = config.session.sessionId;
const entry = pumps.get(sessionId)!;
- if (entry.running) return;
+ if (entry.running || entry.failed !== null) return;
entry.running = true;
void (async () => {
const sessionRoot = sharedSessionRoot(sessionId);
@@ -638,6 +704,15 @@ export async function runSharedWatcher(
pending = pending.then(() => assignments.released(event));
await pending;
} catch (error) {
+ if (error instanceof SessionHostFailedError) {
+ entry.failed = error.failure;
+ console.error(
+ `Session ${sessionId} could not start: ${error.failure} Its ${entry.queue.length} room message(s) stay queued; it is started again when the room next addresses the agent or the session is restarted from Console.`
+ );
+ // Answer the newest message: it is the one somebody just sent.
+ void announce(config, entry.queue.at(-1) ?? event, error.failure);
+ break;
+ }
if (!(error instanceof SessionUnavailableError)) throw error;
// Not running, or it stopped before it answered: start it again
// and hand the message over once it is back.
@@ -664,10 +739,20 @@ export async function runSharedWatcher(
const sessionId = config.session.sessionId;
const sessionRoot = sharedSessionRoot(sessionId);
if (!waiting) await assignments.park(event, false);
- const entry = pumps.get(sessionId) ?? { queue: [], running: false };
+ const entry = pumps.get(sessionId) ?? { queue: [], running: false, failed: null, config };
pumps.set(sessionId, entry);
- if (!entry.queue.some((queuedEvent) => queuedEvent.messageId === event.messageId))
- entry.queue.push(event);
+ entry.config = config;
+ const fresh = !entry.queue.some((queuedEvent) => queuedEvent.messageId === event.messageId);
+ if (fresh) entry.queue.push(event);
+ // A host that failed to start is tried once more for each new message,
+ // since whatever stopped it may have been fixed since.
+ if (entry.failed !== null) {
+ if (!fresh) return true;
+ console.warn(
+ `Room ${event.roomId} addressed the agent again; starting session ${sessionId} again after it failed (${entry.failed}).`
+ );
+ entry.failed = null;
+ }
if (!links.ready(sessionRoot)) await launch(config);
pump(config);
return true;
@@ -895,26 +980,44 @@ export async function runSharedWatcher(
const started = stream;
started.start();
unbind.push(
- control.bind(async (sessionId, roomId): Promise<PlaceOutcome> => {
- if (!(await sessionConfig(sessionId)))
- throw new Error(`Session ${sessionId} is not one of this agent's sessions here.`);
- if (await stopped(sessionId))
- throw new Error(`Session ${sessionId} was stopped; start it before moving a room to it.`);
- const before = placements.snapshot();
- const moved = await placements.place(sessionId, roomId);
- try {
- await publish();
- } catch (error) {
- await placements.restore(before);
- throw new Error(
- `Switch refused to move room ${roomId} to session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
- );
- }
- if (moved.displaced)
+ control.bind({
+ forget: async (sessionId) => {
+ const entry = pumps.get(sessionId);
+ if (entry) {
+ entry.queue.length = 0;
+ pumps.delete(sessionId);
+ }
+ if (await placements.unplace(sessionId)) publishQuietly();
+ const sessionRoot = sharedSessionRoot(sessionId);
+ await supervision.stop(sessionRoot);
+ await rm(sessionRoot, { recursive: true, force: true });
console.warn(
- `Room ${roomId} moved from session ${moved.displaced} to session ${sessionId}.`
+ `Session ${sessionId} was deleted; its rooms start a new session next time.`
);
- return { sessionId, roomId, ...moved };
+ },
+ place: async (sessionId, roomId): Promise<PlaceOutcome> => {
+ if (!(await sessionConfig(sessionId)))
+ throw new Error(`Session ${sessionId} is not one of this agent's sessions here.`);
+ if (await stopped(sessionId))
+ throw new Error(
+ `Session ${sessionId} was stopped; start it before moving a room to it.`
+ );
+ const before = placements.snapshot();
+ const moved = await placements.place(sessionId, roomId);
+ try {
+ await publish();
+ } catch (error) {
+ await placements.restore(before);
+ throw new Error(
+ `Switch refused to move room ${roomId} to session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
+ );
+ }
+ if (moved.displaced)
+ console.warn(
+ `Room ${roomId} moved from session ${moved.displaced} to session ${sessionId}.`
+ );
+ return { sessionId, roomId, ...moved };
+ },
})
);
// Queued behind the events rather than run beside them: the decision it
diff --git a/console/packages/agent-providers/src/host/watcher-tools.ts b/console/packages/agent-providers/src/host/watcher-tools.ts
index a8d6476a2..0a47bb65c 100644
--- a/console/packages/agent-providers/src/host/watcher-tools.ts
+++ b/console/packages/agent-providers/src/host/watcher-tools.ts
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import {
type CallerContext,
+ callOperation,
loadOperations,
SESSION_SELECTOR_HEADERS,
SwitchToolCatalog,
@@ -129,6 +130,76 @@ export function sessionToolAnswerer(deps: {
};
}
+function resultText(result: ToolResult): string {
+ return result.content.map((part) => part.text).join('\n');
+}
+
+/**
+ * Tells a room that the session started to answer it could not start, and
+ * why: as the agent, in the thread the message came from, and addressed to
+ * the agent's owner, who is the one able to fix what stopped it (a provider
+ * CLI that is not signed in, say). Raises when the room could not be told.
+ *
+ * The call is made as the session, so Switch must already know the room is
+ * placed with it.
+ */
+export async function announceStartFailure(input: {
+ identity: SwitchIdentity;
+ connectionId: string;
+ session: { sessionId: string; hostId: string; epoch: string };
+ root: string;
+ cwd: string;
+ threadId: string | null;
+ failure: string;
+}): Promise<void> {
+ const ctx: CallerContext = {
+ identity: input.identity,
+ connectionId: input.connectionId,
+ selector: {
+ [SESSION_SELECTOR_HEADERS.sessionId]: input.session.sessionId,
+ [SESSION_SELECTOR_HEADERS.hostId]: input.session.hostId,
+ [SESSION_SELECTOR_HEADERS.epoch]: input.session.epoch,
+ },
+ room: null,
+ mediaDir: join(input.root, 'media'),
+ cwd: input.cwd,
+ deadConnection: (operation) =>
+ `Switch refused ${operation}: this agent's connection (${input.connectionId}) had lapsed.`,
+ };
+ const thread = input.threadId ? { thread_id: input.threadId } : {};
+ const detail = await callOperation(ctx, 'get_agent_detail', {
+ agent_id: input.identity.agentId,
+ });
+ const owner = detail.isError ? null : detail.structuredContent?.owner_name;
+ if (typeof owner === 'string' && owner) {
+ const targeted = await callOperation(ctx, 'send_targeted_message', {
+ body: `I couldn't start a session, and it needs you to fix it: ${input.failure} Then address me again.`,
+ target_names: [owner],
+ ...thread,
+ });
+ if (!targeted.isError) return;
+ console.warn(
+ `Could not address this agent's owner (${owner}) about session ${input.session.sessionId} failing to start: ${resultText(targeted)}. Telling the room without addressing them.`
+ );
+ const posted = await callOperation(ctx, 'post_message', {
+ body: `I couldn't start a session, and my owner (${owner}) needs to fix it: ${input.failure} Then address me again.`,
+ ...thread,
+ });
+ if (posted.isError) throw new Error(resultText(posted));
+ return;
+ }
+ console.warn(
+ `Could not find this agent's owner to tell about session ${input.session.sessionId} failing to start${
+ detail.isError ? ` (${resultText(detail)})` : ''
+ }. Telling the room without addressing them.`
+ );
+ const posted = await callOperation(ctx, 'post_message', {
+ body: `I couldn't start a session, and my owner needs to fix it: ${input.failure} Then address me again.`,
+ ...thread,
+ });
+ if (posted.isError) throw new Error(resultText(posted));
+}
+
/** What moving a room to a session did. */
export type PlaceOutcome = {
sessionId: string;
@@ -173,6 +244,12 @@ export const watcherHealthSchema = z.object({
});
export type WatcherHealth = z.infer<typeof watcherHealthSchema>;
+/** What a running watcher answers for, through its control. */
+export type WatcherHandlers = {
+ place: (sessionId: string, roomId: string) => Promise<PlaceOutcome>;
+ forget: (sessionId: string) => Promise<void>;
+};
+
/**
* Reaches a running watcher from outside it: Console's "Reconnect to room",
* locally by a direct call and remotely through the sidecar's control port;
@@ -180,7 +257,7 @@ export type WatcherHealth = z.infer<typeof watcherHealthSchema>;
* keeps current here.
*/
export class WatcherControl {
- private placer: ((sessionId: string, roomId: string) => Promise<PlaceOutcome>) | null = null;
+ private handlers: WatcherHandlers | null = null;
private current: WatcherHealth = {
state: 'not-running',
detail: null,
@@ -190,23 +267,40 @@ export class WatcherControl {
private readonly healthListeners = new Set<(health: WatcherHealth) => void>();
/** Called by the watcher while it runs; the returned function unbinds it. */
- bind(placer: (sessionId: string, roomId: string) => Promise<PlaceOutcome>): () => void {
- if (this.placer) throw new Error('A room watcher is already bound to this control.');
- this.placer = placer;
+ bind(handlers: WatcherHandlers): () => void {
+ if (this.handlers) throw new Error('A room watcher is already bound to this control.');
+ this.handlers = handlers;
return () => {
- if (this.placer === placer) this.placer = null;
+ if (this.handlers === handlers) this.handlers = null;
};
}
+ /** Whether a watcher is running behind this control. */
+ get running(): boolean {
+ return this.handlers !== null;
+ }
+
+ /**
+ * Forget a session Console deleted: stop its host, take its rooms off it,
+ * drop what was queued for it and remove its state, so the room's next
+ * message starts a new session rather than reaching the deleted one.
+ * Refused when no watcher is running.
+ */
+ forget(sessionId: string): Promise<void> {
+ if (!this.handlers)
+ return Promise.reject(new Error("The agent's room watcher is not running."));
+ return this.handlers.forget(sessionId);
+ }
+
/** Move a room's messages to this session. Refused when no watcher is running. */
place(sessionId: string, roomId: string): Promise<PlaceOutcome> {
- if (!this.placer)
+ if (!this.handlers)
return Promise.reject(
new Error(
"The agent's room watcher is not running, so no session can be moved to a room. Turn the agent's room connection on first."
)
);
- return this.placer(sessionId, roomId);
+ return this.handlers.place(sessionId, roomId);
}
health(): WatcherHealth {
diff --git a/console/packages/agent-providers/src/index.ts b/console/packages/agent-providers/src/index.ts
index e187b9694..cd009fbb5 100644
--- a/console/packages/agent-providers/src/index.ts
+++ b/console/packages/agent-providers/src/index.ts
@@ -64,7 +64,12 @@ export {
watchFlagsSchema,
} from './host/watch-flags';
export { superviseSharedHost } from './host/supervisor';
-export { SessionLinks, SessionUnavailableError, type SessionRequest } from './host/session-channel';
+export {
+ SessionHostFailedError,
+ SessionLinks,
+ SessionUnavailableError,
+ type SessionRequest,
+} from './host/session-channel';
export {
WatcherControl,
type PlaceOutcome,
diff --git a/console/packages/shared/src/session-v1/contract.ts b/console/packages/shared/src/session-v1/contract.ts
index 1f5dd0d04..680c85042 100644
--- a/console/packages/shared/src/session-v1/contract.ts
+++ b/console/packages/shared/src/session-v1/contract.ts
@@ -190,5 +190,14 @@ export type Snapshot = {
decidedBy: { actorId: Id; surface: Surface; commandId: Id } | null;
})[];
commandStatuses: Extract<ServerBody, { type: 'command.status' }>[];
+ /** Recent notices (the newest ones only), each placed after the item it followed. */
+ notices: SnapshotNotice[];
nextPageToken: string | null;
};
+
+export type SnapshotNotice = {
+ level: 'info' | 'warning' | 'error';
+ code: string;
+ message: string;
+ afterItemId: Id | null;
+};
diff --git a/console/packages/shared/src/session-v1/replica.ts b/console/packages/shared/src/session-v1/replica.ts
index ac337a5d9..b5fdf10e7 100644
--- a/console/packages/shared/src/session-v1/replica.ts
+++ b/console/packages/shared/src/session-v1/replica.ts
@@ -1,15 +1,15 @@
import { isDeepEqual } from '../deep-equal';
-import type { ServerEvent, Snapshot } from './contract';
+import type { Snapshot, SnapshotNotice } from './contract';
import { commandStatusSchema, serverEventSchema, snapshotSchema } from './validation';
-export type TranscriptNotice = Extract<ServerEvent['body'], { type: 'notice' }> & {
- afterItemId: string | null;
-};
+export type TranscriptNotice = SnapshotNotice;
+
+/** How many recent notices a snapshot carries, so a reopened view still shows why a turn failed. */
+const SNAPSHOT_NOTICES = 50;
/** The server already filters this projection for the viewer. Sequence gaps are valid. */
export class SessionReplica {
private value: Snapshot;
- readonly notices: TranscriptNotice[] = [];
constructor(input: unknown) {
this.value = snapshotSchema.parse(input);
@@ -21,6 +21,10 @@ export class SessionReplica {
return structuredClone(this.value);
}
+ get notices(): TranscriptNotice[] {
+ return this.value.notices;
+ }
+
apply(input: unknown): boolean {
const event = serverEventSchema.parse(input);
if (event.sessionId !== this.value.session.sessionId)
@@ -91,7 +95,14 @@ export class SessionReplica {
case 'command.result':
break; // Only the server confirms shared command status.
case 'notice':
- this.notices.push({ ...body, afterItemId: this.value.items.at(-1)?.itemId ?? null });
+ this.value.notices.push({
+ level: body.level,
+ code: body.code,
+ message: body.message,
+ afterItemId: this.value.items.at(-1)?.itemId ?? null,
+ });
+ if (this.value.notices.length > SNAPSHOT_NOTICES)
+ this.value.notices.splice(0, this.value.notices.length - SNAPSHOT_NOTICES);
break;
}
this.value.session.pendingRequestIds = this.value.requests
diff --git a/console/packages/shared/src/session-v1/session-v1.test.ts b/console/packages/shared/src/session-v1/session-v1.test.ts
index cf727338c..7dafc8ed2 100644
--- a/console/packages/shared/src/session-v1/session-v1.test.ts
+++ b/console/packages/shared/src/session-v1/session-v1.test.ts
@@ -489,6 +489,34 @@ it('keeps a model notice anchored before messages that arrive later', () => {
expect(replica.notices[0].afterItemId).toBe('assistant');
});
+it('carries notices in the snapshot, so a view opened later still sees why a turn failed', () => {
+ const replica = new SessionReplica(initial());
+ const sequence = replica.snapshot().throughSequence;
+ replica.apply(
+ event(sequence + 1, {
+ type: 'notice',
+ level: 'error',
+ code: 'PROVIDER_NOTICE',
+ message: 'Model not found: example/model.',
+ })
+ );
+ const reopened = new SessionReplica(replica.snapshot());
+ expect(reopened.notices).toEqual([
+ expect.objectContaining({ level: 'error', message: 'Model not found: example/model.' }),
+ ]);
+});
+
+it('keeps only the newest notices in a snapshot', () => {
+ const replica = new SessionReplica(initial());
+ const sequence = replica.snapshot().throughSequence;
+ for (let index = 1; index <= 60; index++)
+ replica.apply(
+ event(sequence + index, { type: 'notice', level: 'info', code: 'N', message: `n${index}` })
+ );
+ expect(replica.snapshot().notices).toHaveLength(50);
+ expect(replica.snapshot().notices.at(-1)?.message).toBe('n60');
+});
+
it.each(['gemini', 'antigravity', 'future-provider'])(
'preserves %s provider names in stored snapshots',
(provider) => {
diff --git a/console/packages/shared/src/session-v1/validation.ts b/console/packages/shared/src/session-v1/validation.ts
index 80eb05e32..9654aea3f 100644
--- a/console/packages/shared/src/session-v1/validation.ts
+++ b/console/packages/shared/src/session-v1/validation.ts
@@ -206,6 +206,16 @@ export const snapshotSchema: z.ZodType<Snapshot> = z.object({
})
),
commandStatuses: z.array(commandStatusSchema),
+ notices: z
+ .array(
+ z.strictObject({
+ level: z.enum(['info', 'warning', 'error']),
+ code: id,
+ message: z.string(),
+ afterItemId: id.nullable(),
+ })
+ )
+ .default([]),
nextPageToken: id.nullable(),
});
export const commandSchema: z.ZodType<Command> = z.strictObject({