Skip to content

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

fix(console): detect or clear the prompt that stalls a session before it starts (CHOO-2213) (#257)

Louis Amaudruz9c18b3e3c760
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts
index f29090a45..f27a297f9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/agent-hook-service.ts
@@ -1,5 +1,6 @@
import type { IDisposable, IInitializable } from '@switch-console/shared';
import { eq } from 'drizzle-orm';
+import { sessionStartupWatch } from '@main/core/agent-runtime/desktop-session-startup-watch';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { saveProviderSessionId } from '@main/core/sessions/operations/save-provider-session-id';
import { setProviderSessionId } from '@main/core/sessions/operations/set-provider-session-id';
@@ -92,6 +93,11 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
return;
}
+ // Any hook at all proves the CLI is past its startup prompts and running,
+ // so this is deliberately not narrowed to the session-start event: a
+ // provider that varies its startup payload should not read as stalled.
+ sessionStartupWatch.markStarted(raw.ptyId);
+
if (parsed.kind === 'ignore') return;
if (parsed.kind === 'session') {
@@ -129,6 +135,28 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
async initialize(): Promise<void> {
await this.server.start(async (raw) => this.handleRawHook(raw, { startLocalPoller: true }));
+ // A session that never reported itself up is stopped on something only a
+ // human can answer. Raise it as attention-needed rather than leaving a
+ // pane that looks like every healthy session and does nothing.
+ sessionStartupWatch.onStall(({ sessionId, providerId }) => {
+ const event: AgentEvent = {
+ type: 'notification',
+ source: 'hook',
+ providerId,
+ sessionId,
+ timestamp: Date.now(),
+ payload: {
+ notificationType: 'startup_prompt',
+ title: 'Session did not start',
+ message:
+ 'It never reported that it started, so it is most likely waiting on a prompt from the CLI — a workspace-trust or permissions confirmation. Open its terminal to answer it.',
+ },
+ };
+ const appFocused = isAppFocused();
+ void maybeShowNotification(event, appFocused);
+ this.emitAgentEvent(event, appFocused);
+ });
+
sessionHooks.on('session:input-submitted', ({ sessionId, providerId }) => {
// Only synthesise a 'start' event when the plugin does not supply its own
// start hook (e.g. UserPromptSubmit). Providers with start-capable hooks
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts
index 4521d178b..f909aab85 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.test.ts
@@ -8,6 +8,8 @@ const mockMkdir = vi.hoisted(() => vi.fn());
const mockRename = vi.hoisted(() => vi.fn());
const mockRm = vi.hoisted(() => vi.fn());
const mockWarn = vi.hoisted(() => vi.fn());
+// Trust keys are the resolved path; identity here keeps the fixtures literal.
+const mockRealpath = vi.hoisted(() => vi.fn(async (p: string) => p));
vi.mock('node:fs', () => ({
promises: {
@@ -16,6 +18,7 @@ vi.mock('node:fs', () => ({
mkdir: mockMkdir,
rename: mockRename,
rm: mockRm,
+ realpath: mockRealpath,
},
}));
@@ -32,10 +35,15 @@ vi.mock('@main/lib/logger', () => ({
},
}));
+function renamedTo(): string[] {
+ return mockRename.mock.calls.map(([, target]) => String(target));
+}
+
function makeService(overrides: { autoTrustWorktrees?: boolean } = {}): ClaudeTrustService {
return new ClaudeTrustService({
getSessionSettings: () =>
Promise.resolve({ autoTrustWorktrees: overrides.autoTrustWorktrees ?? true }),
+ log: { warn: mockWarn },
});
}
@@ -53,7 +61,7 @@ describe('ClaudeTrustService', () => {
const service = makeService();
await service.maybeAutoTrustLocal({
- providerId: 'codex',
+ providerId: 'opencode',
cwd: '/tmp/worktree',
homedir: '/home/local-user',
});
@@ -86,7 +94,55 @@ describe('ClaudeTrustService', () => {
});
expect(mockReadFile).toHaveBeenCalledWith('/home/local-user/.claude.json', 'utf8');
- expect(mockWriteFile).toHaveBeenCalledTimes(1);
+ expect(renamedTo()).toContain('/home/local-user/.claude.json');
+ });
+
+ it('accepts the bypass-permissions warning only when auto-approve forced the launch', async () => {
+ const service = makeService();
+
+ await service.maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/tmp/worktree',
+ homedir: '/home/local-user',
+ });
+
+ expect(renamedTo()).not.toContain('/tmp/worktree/.claude/settings.local.json');
+
+ vi.clearAllMocks();
+ mockReadFile.mockRejectedValue(Object.assign(new Error('not found'), { code: 'ENOENT' }));
+
+ await service.maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/tmp/worktree',
+ homedir: '/home/local-user',
+ force: true,
+ });
+
+ const settingsWrite = mockWriteFile.mock.calls.find(([tmpPath]) =>
+ String(tmpPath).startsWith('/tmp/worktree/.claude/settings.local.json.')
+ );
+ expect(settingsWrite).toBeDefined();
+ expect(JSON.parse(String(settingsWrite?.[1]))).toEqual({
+ skipDangerousModePermissionPrompt: true,
+ });
+ });
+
+ it('leaves Claude settings alone when the bypass warning is already accepted', async () => {
+ const service = makeService();
+ mockReadFile.mockImplementation(async (target: string) =>
+ String(target).endsWith('.claude/settings.local.json')
+ ? JSON.stringify({ skipDangerousModePermissionPrompt: true, model: 'opus' })
+ : null
+ );
+
+ await service.maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/tmp/worktree',
+ homedir: '/home/local-user',
+ force: true,
+ });
+
+ expect(renamedTo()).not.toContain('/tmp/worktree/.claude/settings.local.json');
});
it('writes local config atomically when missing', async () => {
@@ -111,10 +167,47 @@ describe('ClaudeTrustService', () => {
expect(renameTo).toBe('/home/local-user/.claude.json');
const written = JSON.parse(String(content));
- expect(written.locations[path.resolve(relPath)]).toEqual({
+ expect(written.projects[path.resolve(relPath)]).toEqual({
hasTrustDialogAccepted: true,
- hasCompletedLocationOnboarding: true,
+ hasCompletedProjectOnboarding: true,
+ });
+ });
+
+ it('keys trust to the resolved directory, not the symlink used to reach it', async () => {
+ const service = makeService();
+ mockRealpath.mockImplementation(async (p: string) =>
+ p === '/link/to/worktree' ? '/real/worktree' : p
+ );
+
+ await service.maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/link/to/worktree',
+ homedir: '/home/local-user',
});
+
+ // A process asks the kernel where it is and gets the real path back, so a
+ // CLI comparing its cwd against a trust entry never sees the link.
+ const written = JSON.parse(String(mockWriteFile.mock.calls[0][1]));
+ expect(Object.keys(written.projects)).toEqual(['/real/worktree']);
+ });
+
+ it('leaves the global first-run setup wizard for the user to answer', async () => {
+ const service = makeService();
+
+ await service.maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/tmp/worktree',
+ homedir: '/home/local-user',
+ force: true,
+ });
+
+ const claudeJson = mockWriteFile.mock.calls.find(([tmpPath]) =>
+ String(tmpPath).startsWith('/home/local-user/.claude.json.')
+ );
+ // That wizard is where a fresh install is told to connect an account.
+ // Skipping it would trade a prompt that says what is missing for a session
+ // that fails later without saying anything.
+ expect(JSON.parse(String(claudeJson?.[1]))).not.toHaveProperty('hasCompletedOnboarding');
});
it('adds Copilot trusted folders', async () => {
@@ -158,10 +251,10 @@ describe('ClaudeTrustService', () => {
const trustedPath = '/already/trusted';
mockReadFile.mockResolvedValue(
JSON.stringify({
- locations: {
+ projects: {
[trustedPath]: {
hasTrustDialogAccepted: true,
- hasCompletedLocationOnboarding: true,
+ hasCompletedProjectOnboarding: true,
},
},
})
@@ -237,13 +330,13 @@ describe('ClaudeTrustService', () => {
expect(mockWriteFile).toHaveBeenCalledTimes(2);
const secondWriteContent = JSON.parse(String(mockWriteFile.mock.calls[1][1]));
- expect(secondWriteContent.locations[path.resolve('/worktree/a')]).toEqual({
+ expect(secondWriteContent.projects[path.resolve('/worktree/a')]).toEqual({
hasTrustDialogAccepted: true,
- hasCompletedLocationOnboarding: true,
+ hasCompletedProjectOnboarding: true,
});
- expect(secondWriteContent.locations[path.resolve('/worktree/b')]).toEqual({
+ expect(secondWriteContent.projects[path.resolve('/worktree/b')]).toEqual({
hasTrustDialogAccepted: true,
- hasCompletedLocationOnboarding: true,
+ hasCompletedProjectOnboarding: true,
});
});
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.ts
index 7c3aac742..996b45dea 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/claude-trust-service.ts
@@ -1,23 +1,24 @@
-import { randomUUID } from 'node:crypto';
-import { promises as fs } from 'node:fs';
import path from 'node:path';
-import { appSettingsService } from '@main/core/settings/settings-service';
-import { log } from '@main/lib/logger';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import {
+ canonicalTrustPath,
+ configWriteLock,
+ isPlainObject,
+ readLocalConfig,
+ type TrustLogger,
+ type TrustServiceDeps,
+ writeLocalConfigAtomic,
+} from './trust-config-io';
const CLAUDE_PROVIDER_ID: AgentProviderId = 'claude';
const COPILOT_PROVIDER_ID: AgentProviderId = 'copilot';
const CLAUDE_CONFIG_NAME = '.claude.json';
+const CLAUDE_LOCAL_SETTINGS_NAME = '.claude/settings.local.json';
+const CLAUDE_SKIP_BYPASS_PROMPT_KEY = 'skipDangerousModePermissionPrompt';
const COPILOT_CONFIG_NAME = '.copilot/config.json';
export class ClaudeTrustService {
- private readonly configLocks = new Map<string, Promise<void>>();
-
- constructor(
- private readonly deps: {
- getSessionSettings: () => Promise<{ autoTrustWorktrees: boolean }>;
- }
- ) {}
+ constructor(private readonly deps: TrustServiceDeps) {}
async maybeAutoTrustLocal({
providerId,
@@ -31,11 +32,15 @@ export class ClaudeTrustService {
force?: boolean;
}): Promise<void> {
if (!cwd) return;
+ if (providerId !== CLAUDE_PROVIDER_ID && providerId !== COPILOT_PROVIDER_ID) return;
+ const normalizedPath = await canonicalTrustPath(cwd);
+ if (providerId === CLAUDE_PROVIDER_ID && force) {
+ await this.acceptBypassPermissionsMode(normalizedPath);
+ }
const trustConfig = await this.getTrustConfig(providerId, force);
if (!trustConfig) return;
- const normalizedPath = path.resolve(cwd);
const configPath = path.join(homedir, trustConfig.configName);
- await this.withLock(configPath, () =>
+ await configWriteLock.run(configPath, () =>
this.ensureTrusted(normalizedPath, {
readConfig: () => readLocalConfig(configPath),
writeConfig: (content) => writeLocalConfigAtomic(configPath, content),
@@ -44,6 +49,48 @@ export class ClaudeTrustService {
);
}
+ /**
+ * Records acceptance of Claude Code's bypass-permissions warning, the last
+ * prompt between a `--dangerously-skip-permissions` launch and a live
+ * session.
+ *
+ * Only reached when the agent's own auto-approve toggle is on, which is where
+ * the user accepted that risk; Switch Console does not decide it for them.
+ * The warning's default answer is "No, exit", so a detached session left to
+ * answer it does not merely stall — the first stray keypress kills it.
+ *
+ * Written per working directory, not to the user's global settings: one
+ * agent's toggle must not quietly waive the warning for every other agent,
+ * or for Claude Code run by hand outside Switch Console. Verified against
+ * 2.1.234 that `settings.local.json` is the narrowest scope that works —
+ * the shared, committable `settings.json` beside it does not clear the
+ * prompt at all, which is the right call on Claude Code's part and the
+ * reason not to reach for it.
+ */
+ private async acceptBypassPermissionsMode(worktreePath: string): Promise<void> {
+ const settingsPath = path.join(worktreePath, CLAUDE_LOCAL_SETTINGS_NAME);
+ await configWriteLock.run(settingsPath, async () => {
+ try {
+ const settings = parseConfig(
+ await readLocalConfig(settingsPath),
+ 'Claude settings',
+ this.deps.log
+ );
+ if (!settings) return;
+ if (settings[CLAUDE_SKIP_BYPASS_PROMPT_KEY] === true) return;
+ await writeLocalConfigAtomic(
+ settingsPath,
+ JSON.stringify({ ...settings, [CLAUDE_SKIP_BYPASS_PROMPT_KEY]: true }, null, 2) + '\n'
+ );
+ } catch (error: unknown) {
+ this.deps.log.warn('ClaudeTrustService: failed to accept bypass-permissions mode', {
+ settingsPath,
+ error: String(error),
+ });
+ }
+ });
+ }
+
private async getTrustConfig(
providerId: AgentProviderId,
force: boolean
@@ -65,17 +112,10 @@ export class ClaudeTrustService {
return {
configName: CLAUDE_CONFIG_NAME,
parseWarningName: 'Claude',
- withTrustedPath: withClaudeTrustedLocation,
+ withTrustedPath: withClaudeTrustedProject,
};
}
- private withLock(configPath: string, fn: () => Promise<void>): Promise<void> {
- const prev = this.configLocks.get(configPath) ?? Promise.resolve();
- const next = prev.then(fn, fn);
- this.configLocks.set(configPath, next);
- return next;
- }
-
private async ensureTrusted(
normalizedPath: string,
io: {
@@ -86,13 +126,13 @@ export class ClaudeTrustService {
): Promise<void> {
try {
const rawConfig = await io.readConfig();
- const config = parseConfig(rawConfig, io.trustConfig.parseWarningName);
+ const config = parseConfig(rawConfig, io.trustConfig.parseWarningName, this.deps.log);
if (!config) return;
const nextConfig = io.trustConfig.withTrustedPath(config, normalizedPath);
if (!nextConfig) return;
await io.writeConfig(JSON.stringify(nextConfig, null, 2) + '\n');
} catch (error: unknown) {
- log.warn('ClaudeTrustService: failed to auto-trust worktree', {
+ this.deps.log.warn('ClaudeTrustService: failed to auto-trust worktree', {
path: normalizedPath,
error: String(error),
});
@@ -100,10 +140,6 @@ export class ClaudeTrustService {
}
}
-export const claudeTrustService = new ClaudeTrustService({
- getSessionSettings: () => appSettingsService.get('sessions'),
-});
-
type TrustConfig = {
configName: string;
parseWarningName: string;
@@ -113,7 +149,11 @@ type TrustConfig = {
) => Record<string, unknown> | null;
};
-function parseConfig(raw: string | null, warningName: string): Record<string, unknown> | null {
+function parseConfig(
+ raw: string | null,
+ warningName: string,
+ log: TrustLogger
+): Record<string, unknown> | null {
if (!raw || raw.trim() === '') return {};
try {
@@ -129,26 +169,43 @@ function parseConfig(raw: string | null, warningName: string): Record<string, un
}
}
-function withClaudeTrustedLocation(
+/**
+ * Clears "is this a project you trust?" for one directory.
+ *
+ * Deliberately does NOT mark Claude Code's global first-run setup as complete,
+ * though doing so would clear another startup prompt. That wizard is where a
+ * new install is told to connect an account, and skipping it would replace a
+ * prompt that says what is missing with a session that fails later for no
+ * visible reason. A session held up by it is reported as stalled instead —
+ * which is the honest answer, because setup really is needed.
+ *
+ * `projects` and the two flags under it are Claude Code's names for its own
+ * config, not Switch Console's. They track whatever Claude Code calls them and
+ * must not be renamed to follow our vocabulary — CHOO-1426 renamed them
+ * alongside our own project→location refactor, which silently disabled
+ * auto-trust for every Claude session while the (equally renamed) test kept
+ * passing.
+ */
+function withClaudeTrustedProject(
config: Record<string, unknown>,
worktreePath: string
): Record<string, unknown> | null {
- const locations = isPlainObject(config.locations) ? config.locations : {};
- const existing = isPlainObject(locations[worktreePath]) ? locations[worktreePath] : {};
+ const projects = isPlainObject(config.projects) ? config.projects : {};
+ const existing = isPlainObject(projects[worktreePath]) ? projects[worktreePath] : {};
const alreadyTrusted =
existing['hasTrustDialogAccepted'] === true &&
- existing['hasCompletedLocationOnboarding'] === true;
+ existing['hasCompletedProjectOnboarding'] === true;
if (alreadyTrusted) return null;
return {
...config,
- locations: {
- ...locations,
+ projects: {
+ ...projects,
[worktreePath]: {
...existing,
hasTrustDialogAccepted: true,
- hasCompletedLocationOnboarding: true,
+ hasCompletedProjectOnboarding: true,
},
},
};
@@ -166,34 +223,3 @@ function withCopilotTrustedFolder(
trustedFolders: [...trustedFolders, worktreePath],
};
}
-
-async function readLocalConfig(configPath: string): Promise<string | null> {
- try {
- return await fs.readFile(configPath, 'utf8');
- } catch (error: unknown) {
- if (isNodeNotFound(error)) return null;
- throw error;
- }
-}
-
-async function writeLocalConfigAtomic(configPath: string, content: string): Promise<void> {
- const tmpPath = `${configPath}.${randomUUID()}.tmp`;
- try {
- await fs.mkdir(path.dirname(configPath), { recursive: true });
- await fs.writeFile(tmpPath, content, 'utf8');
- await fs.rename(tmpPath, configPath);
- } catch (error: unknown) {
- try {
- await fs.rm(tmpPath, { force: true });
- } catch {}
- throw error;
- }
-}
-
-function isNodeNotFound(error: unknown): boolean {
- return (error as NodeJS.ErrnoException)?.code === 'ENOENT';
-}
-
-function isPlainObject(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value);
-}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.test.ts
new file mode 100644
index 000000000..aa02046f6
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.test.ts
@@ -0,0 +1,168 @@
+import path from 'node:path';
+import * as toml from 'smol-toml';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CodexTrustService } from './codex-trust-service';
+
+const mockReadFile = vi.hoisted(() => vi.fn());
+const mockWriteFile = vi.hoisted(() => vi.fn());
+const mockMkdir = vi.hoisted(() => vi.fn());
+const mockRename = vi.hoisted(() => vi.fn());
+const mockRm = vi.hoisted(() => vi.fn());
+const mockWarn = vi.hoisted(() => vi.fn());
+// Trust keys are the resolved path; identity here keeps the fixtures literal.
+const mockRealpath = vi.hoisted(() => vi.fn(async (p: string) => p));
+
+vi.mock('node:fs', () => ({
+ promises: {
+ readFile: mockReadFile,
+ writeFile: mockWriteFile,
+ mkdir: mockMkdir,
+ rename: mockRename,
+ rm: mockRm,
+ realpath: mockRealpath,
+ },
+}));
+
+vi.mock('@main/core/settings/settings-service', () => ({
+ appSettingsService: { get: vi.fn() },
+}));
+
+vi.mock('@main/lib/logger', () => ({
+ log: { warn: mockWarn, info: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+const CONFIG_PATH = '/home/local-user/.codex/config.toml';
+
+function makeService(overrides: { autoTrustWorktrees?: boolean } = {}): CodexTrustService {
+ return new CodexTrustService({
+ getSessionSettings: () =>
+ Promise.resolve({ autoTrustWorktrees: overrides.autoTrustWorktrees ?? true }),
+ log: { warn: mockWarn },
+ });
+}
+
+function writtenConfig(): string {
+ expect(mockRename.mock.calls.map(([, target]) => String(target))).toContain(CONFIG_PATH);
+ return String(mockWriteFile.mock.calls[0][1]);
+}
+
+async function trust(service: CodexTrustService, cwd: string, force?: boolean): Promise<void> {
+ await service.maybeAutoTrustLocal({
+ providerId: 'codex',
+ cwd,
+ homedir: '/home/local-user',
+ ...(force === undefined ? {} : { force }),
+ });
+}
+
+describe('CodexTrustService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockReadFile.mockRejectedValue(Object.assign(new Error('not found'), { code: 'ENOENT' }));
+ mockWriteFile.mockResolvedValue(undefined);
+ mockMkdir.mockResolvedValue(undefined);
+ mockRename.mockResolvedValue(undefined);
+ mockRm.mockResolvedValue(undefined);
+ });
+
+ it('ignores providers other than Codex', async () => {
+ await trust(makeService(), '/tmp/worktree');
+ await makeService().maybeAutoTrustLocal({
+ providerId: 'claude',
+ cwd: '/tmp/worktree',
+ homedir: '/home/local-user',
+ });
+
+ expect(mockWriteFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips when auto-trust is disabled, and writes anyway when forced', async () => {
+ await trust(makeService({ autoTrustWorktrees: false }), '/tmp/worktree');
+ expect(mockWriteFile).not.toHaveBeenCalled();
+
+ await trust(makeService({ autoTrustWorktrees: false }), '/tmp/worktree', true);
+ expect(toml.parse(writtenConfig())).toEqual({
+ projects: { '/tmp/worktree': { trust_level: 'trusted' } },
+ });
+ });
+
+ it('writes the resolved absolute path, never an ancestor', async () => {
+ await trust(makeService(), './relative/worktree');
+
+ const parsed = toml.parse(writtenConfig()) as { projects: Record<string, unknown> };
+ expect(Object.keys(parsed.projects)).toEqual([path.resolve('./relative/worktree')]);
+ });
+
+ it('appends to an existing config without disturbing what is already there', async () => {
+ const existing = [
+ '# my own notes',
+ 'model = "gpt-5.6-sol"',
+ '',
+ '[projects."/other/repo"]',
+ 'trust_level = "trusted"',
+ '',
+ ].join('\n');
+ mockReadFile.mockResolvedValue(existing);
+
+ await trust(makeService(), '/tmp/worktree');
+
+ const content = writtenConfig();
+ expect(content).toContain('# my own notes');
+ expect(content).toContain('model = "gpt-5.6-sol"');
+ expect(toml.parse(content)).toEqual({
+ model: 'gpt-5.6-sol',
+ projects: {
+ '/other/repo': { trust_level: 'trusted' },
+ '/tmp/worktree': { trust_level: 'trusted' },
+ },
+ });
+ });
+
+ it('is idempotent once the directory is trusted', async () => {
+ mockReadFile.mockResolvedValue('[projects."/tmp/worktree"]\ntrust_level = "trusted"\n');
+
+ await trust(makeService(), '/tmp/worktree');
+
+ expect(mockWriteFile).not.toHaveBeenCalled();
+ });
+
+ it('never flips a directory the user marked untrusted', async () => {
+ mockReadFile.mockResolvedValue('[projects."/tmp/worktree"]\ntrust_level = "untrusted"\n');
+
+ await trust(makeService(), '/tmp/worktree');
+
+ expect(mockWriteFile).not.toHaveBeenCalled();
+ });
+
+ it('refuses to edit a corrupt config and says so', async () => {
+ mockReadFile.mockResolvedValue('[projects."/tmp/worktree"\n= = =');
+
+ await trust(makeService(), '/tmp/worktree');
+
+ expect(mockWriteFile).not.toHaveBeenCalled();
+ expect(mockWarn).toHaveBeenCalledWith(
+ 'CodexTrustService: refusing to edit corrupt Codex config',
+ expect.objectContaining({ error: expect.any(String) })
+ );
+ });
+
+ it('refuses to append when the project is declared without a trust level', async () => {
+ mockReadFile.mockResolvedValue('[projects."/tmp/worktree"]\nsomething_else = 1\n');
+
+ await trust(makeService(), '/tmp/worktree');
+
+ expect(mockWriteFile).not.toHaveBeenCalled();
+ expect(mockWarn).toHaveBeenCalledWith(
+ 'CodexTrustService: Codex config already declares this project without a trust level',
+ { path: '/tmp/worktree' }
+ );
+ });
+
+ it('escapes paths that would otherwise break the TOML key', async () => {
+ const awkward = '/tmp/we"ird\\path';
+ await trust(makeService(), awkward);
+
+ const parsed = toml.parse(writtenConfig()) as { projects: Record<string, unknown> };
+ expect(parsed.projects[path.resolve(awkward)]).toEqual({ trust_level: 'trusted' });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.ts
new file mode 100644
index 000000000..b1c7da0d8
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/codex-trust-service.ts
@@ -0,0 +1,118 @@
+import path from 'node:path';
+import * as toml from 'smol-toml';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import {
+ canonicalTrustPath,
+ configWriteLock,
+ isPlainObject,
+ readLocalConfig,
+ type TrustLogger,
+ type TrustServiceDeps,
+ writeLocalConfigAtomic,
+} from './trust-config-io';
+
+const CODEX_PROVIDER_ID: AgentProviderId = 'codex';
+const CODEX_CONFIG_NAME = '.codex/config.toml';
+
+/**
+ * Marks a directory trusted for Codex, clearing the "do you trust this
+ * workspace?" prompt it raises in the TUI before a session starts.
+ *
+ * Codex reads this only from `~/.codex/config.toml` — verified against 0.146.0
+ * that the equivalent `-c projects."<path>".trust_level` override on argv does
+ * not clear the prompt, so there is no way to keep the setting out of the
+ * user's own config. Trust is also keyed on the exact path: a directory under
+ * an already-trusted parent is still untrusted, so this writes the session's
+ * own working directory and never an ancestor.
+ */
+export class CodexTrustService {
+ constructor(private readonly deps: TrustServiceDeps) {}
+
+ async maybeAutoTrustLocal({
+ providerId,
+ cwd,
+ homedir,
+ force = false,
+ }: {
+ providerId: AgentProviderId;
+ cwd?: string;
+ homedir: string;
+ force?: boolean;
+ }): Promise<void> {
+ if (!cwd) return;
+ if (providerId !== CODEX_PROVIDER_ID) return;
+ if (!force) {
+ const { autoTrustWorktrees } = await this.deps.getSessionSettings();
+ if (!autoTrustWorktrees) return;
+ }
+
+ const normalizedPath = await canonicalTrustPath(cwd);
+ const configPath = path.join(homedir, CODEX_CONFIG_NAME);
+ await configWriteLock.run(configPath, async () => {
+ try {
+ const raw = (await readLocalConfig(configPath)) ?? '';
+ const next = withCodexTrustedProject(raw, normalizedPath, this.deps.log);
+ if (next === null) return;
+ await writeLocalConfigAtomic(configPath, next);
+ } catch (error: unknown) {
+ this.deps.log.warn('CodexTrustService: failed to auto-trust worktree', {
+ path: normalizedPath,
+ configPath,
+ error: String(error),
+ });
+ }
+ });
+ }
+}
+
+/**
+ * Returns the config text with `<worktreePath>` trusted, or null to leave the
+ * file alone.
+ *
+ * The new table is appended to the existing text rather than round-tripped
+ * through the parser: `config.toml` is the user's file, hand-edited and
+ * commented, and re-serialising it would silently drop all of that on a write
+ * they did not ask for.
+ */
+export function withCodexTrustedProject(
+ raw: string,
+ worktreePath: string,
+ log: TrustLogger
+): string | null {
+ let config: Record<string, unknown>;
+ try {
+ config = toml.parse(raw) as Record<string, unknown>;
+ } catch (error: unknown) {
+ log.warn('CodexTrustService: refusing to edit corrupt Codex config', {
+ error: String(error),
+ });
+ return null;
+ }
+
+ const projects = config.projects;
+ if (projects !== undefined && !isPlainObject(projects)) {
+ log.warn('CodexTrustService: refusing to edit non-table `projects` in Codex config');
+ return null;
+ }
+
+ const existing = projects?.[worktreePath];
+ if (isPlainObject(existing)) {
+ // Leave an explicit "untrusted" alone: the user set it, and quietly
+ // flipping it is the one thing a trust setting must never do.
+ if (existing.trust_level !== undefined) return null;
+ // A table without a trust level cannot be appended to a second time
+ // without a duplicate-table error, and rewriting it in place means
+ // re-serialising the file.
+ log.warn(
+ 'CodexTrustService: Codex config already declares this project without a trust level',
+ {
+ path: worktreePath,
+ }
+ );
+ return null;
+ }
+
+ const section = `[projects.${JSON.stringify(worktreePath)}]\ntrust_level = "trusted"\n`;
+ if (raw.trim() === '') return section;
+ return `${raw.replace(/\n*$/, '')}\n\n${section}`;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.test.ts
index 3981efeff..7d53637c9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.test.ts
@@ -5,10 +5,13 @@ const mockAccess = vi.hoisted(() => vi.fn());
const mockMkdir = vi.hoisted(() => vi.fn());
const mockWriteFile = vi.hoisted(() => vi.fn());
const mockWarn = vi.hoisted(() => vi.fn());
+// Trust keys are the resolved path; identity here keeps the fixtures literal.
+const mockRealpath = vi.hoisted(() => vi.fn(async (p: string) => p));
vi.mock('node:fs', () => ({
promises: {
access: mockAccess,
+ realpath: mockRealpath,
mkdir: mockMkdir,
writeFile: mockWriteFile,
},
@@ -35,6 +38,7 @@ function makeService(overrides: { autoTrustWorktrees?: boolean } = {}): CursorTr
return new CursorTrustService({
getSessionSettings: () =>
Promise.resolve({ autoTrustWorktrees: overrides.autoTrustWorktrees ?? true }),
+ log: { warn: mockWarn },
});
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.ts
index ca136b842..5ebf63ebd 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/cursor-trust-service.ts
@@ -1,8 +1,7 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
-import { appSettingsService } from '@main/core/settings/settings-service';
-import { log } from '@main/lib/logger';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { canonicalTrustPath, type TrustServiceDeps } from './trust-config-io';
const CURSOR_PROVIDER_ID: AgentProviderId = 'cursor';
const CURSOR_DATA_DIR_NAME = '.cursor';
@@ -10,11 +9,7 @@ const CURSOR_PROJECTS_DIR_NAME = 'projects';
const CURSOR_TRUST_MARKER_NAME = '.workspace-trusted';
export class CursorTrustService {
- constructor(
- private readonly deps: {
- getSessionSettings: () => Promise<{ autoTrustWorktrees: boolean }>;
- }
- ) {}
+ constructor(private readonly deps: TrustServiceDeps) {}
async maybeAutoTrustLocal({
providerId,
@@ -30,7 +25,7 @@ export class CursorTrustService {
if (!cwd) return;
if (!(await this.shouldAutoTrust(providerId, force))) return;
- const workspacePath = path.resolve(cwd);
+ const workspacePath = await canonicalTrustPath(cwd);
const dataDir = path.join(homedir, CURSOR_DATA_DIR_NAME);
const markerPath = path.join(
cursorLocationDir(workspacePath, dataDir, path),
@@ -63,7 +58,7 @@ export class CursorTrustService {
await io.write(JSON.stringify(createTrustMarker(workspacePath), null, 2) + '\n');
} catch (error: unknown) {
- log.warn('CursorTrustService: failed to auto-trust worktree', {
+ this.deps.log.warn('CursorTrustService: failed to auto-trust worktree', {
path: workspacePath,
markerPath,
error: String(error),
@@ -72,10 +67,6 @@ export class CursorTrustService {
}
}
-export const cursorTrustService = new CursorTrustService({
- getSessionSettings: () => appSettingsService.get('sessions'),
-});
-
function createTrustMarker(workspacePath: string): Record<string, string> {
return {
trustedAt: new Date().toISOString(),
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust-service.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust-service.ts
index 8d6f16ced..f6da67459 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust-service.ts
@@ -1,26 +1,11 @@
-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-import { claudeTrustService } from './claude-trust-service';
-import { cursorTrustService } from './cursor-trust-service';
+import { appSettingsService } from '@main/core/settings/settings-service';
+import { log } from '@main/lib/logger';
+import { createDirTrustService } from './dir-trust';
-type DirTrustLocalArgs = {
- providerId: AgentProviderId;
- cwd?: string;
- homedir: string;
- force?: boolean;
-};
+export { createDirTrustService, DirTrustService } from './dir-trust';
-type DirTrustProvider = {
- maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void>;
-};
-
-export class DirTrustService {
- constructor(private readonly providers: readonly DirTrustProvider[]) {}
-
- async maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void> {
- for (const provider of this.providers) {
- await provider.maybeAutoTrustLocal(args);
- }
- }
-}
-
-export const dirTrustService = new DirTrustService([claudeTrustService, cursorTrustService]);
+/** The trust writers for this machine, for sessions the desktop starts here. */
+export const dirTrustService = createDirTrustService({
+ getSessionSettings: () => appSettingsService.get('sessions'),
+ log,
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust.ts
new file mode 100644
index 000000000..c674d8ced
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/dir-trust.ts
@@ -0,0 +1,45 @@
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { ClaudeTrustService } from './claude-trust-service';
+import { CodexTrustService } from './codex-trust-service';
+import { CursorTrustService } from './cursor-trust-service';
+import type { TrustServiceDeps } from './trust-config-io';
+
+export type DirTrustLocalArgs = {
+ providerId: AgentProviderId;
+ cwd?: string;
+ homedir: string;
+ force?: boolean;
+};
+
+type DirTrustProvider = {
+ maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void>;
+};
+
+export class DirTrustService {
+ constructor(private readonly providers: readonly DirTrustProvider[]) {}
+
+ async maybeAutoTrustLocal(args: DirTrustLocalArgs): Promise<void> {
+ for (const provider of this.providers) {
+ await provider.maybeAutoTrustLocal(args);
+ }
+ }
+}
+
+/**
+ * Build the trust writers for one machine.
+ *
+ * Takes its settings and logger rather than reaching for the app's, because a
+ * remote session's prompts have to be cleared on the VM it runs on: the sidecar
+ * builds the same set with its own logger and the setting carried in its launch
+ * spec. Writing them here would only clear the prompts on the wrong computer.
+ *
+ * Kept apart from the desktop's own instance so importing this does not drag
+ * the Electron-bound settings service and file logger into the sidecar bundle.
+ */
+export function createDirTrustService(deps: TrustServiceDeps): DirTrustService {
+ return new DirTrustService([
+ new ClaudeTrustService(deps),
+ new CodexTrustService(deps),
+ new CursorTrustService(deps),
+ ]);
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-hooks/trust-config-io.ts b/console/apps/switch-console-desktop/src/main/core/agent-hooks/trust-config-io.ts
new file mode 100644
index 000000000..960ad0f0b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-hooks/trust-config-io.ts
@@ -0,0 +1,94 @@
+import { randomUUID } from 'node:crypto';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+/**
+ * The logging surface the trust writers need.
+ *
+ * Injected rather than imported so they can run in the sidecar bundle, which
+ * must not pull in the Electron-bound main-process file logger — the same
+ * reason the hook-event parser takes its logger as a parameter. The sidecar
+ * writes these same files on the VM before it spawns a session there.
+ */
+export interface TrustLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
+
+export interface TrustServiceDeps {
+ getSessionSettings: () => Promise<{ autoTrustWorktrees: boolean }>;
+ log: TrustLogger;
+}
+
+/**
+ * The path an agent CLI will recognise as its own working directory.
+ *
+ * Symlinks have to be resolved, not just relative segments: a process asks the
+ * kernel where it is and gets the real path back, so a CLI comparing its cwd
+ * against a trust entry never sees the link. Verified against Claude Code
+ * 2.1.234 and codex-cli 0.146.0 — running in a symlinked directory, an entry
+ * written under the link is ignored and the prompt appears, while the same
+ * entry under the resolved path clears it.
+ *
+ * Falls back to the unresolved path only when the directory does not exist
+ * yet, which is not a case a session can be launched into anyway.
+ */
+export async function canonicalTrustPath(cwd: string): Promise<string> {
+ const resolved = path.resolve(cwd);
+ try {
+ return await fs.realpath(resolved);
+ } catch (error: unknown) {
+ if (isNodeNotFound(error)) return resolved;
+ throw error;
+ }
+}
+
+export async function readLocalConfig(configPath: string): Promise<string | null> {
+ try {
+ return await fs.readFile(configPath, 'utf8');
+ } catch (error: unknown) {
+ if (isNodeNotFound(error)) return null;
+ throw error;
+ }
+}
+
+export async function writeLocalConfigAtomic(configPath: string, content: string): Promise<void> {
+ const tmpPath = `${configPath}.${randomUUID()}.tmp`;
+ try {
+ await fs.mkdir(path.dirname(configPath), { recursive: true });
+ await fs.writeFile(tmpPath, content, 'utf8');
+ await fs.rename(tmpPath, configPath);
+ } catch (error: unknown) {
+ try {
+ await fs.rm(tmpPath, { force: true });
+ } catch {}
+ throw error;
+ }
+}
+
+export function isNodeNotFound(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT';
+}
+
+export function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/**
+ * Serialises writes to one config file across the trust services.
+ *
+ * The agent CLIs' config files are shared between providers and between
+ * concurrently starting sessions, and every write is read-modify-write over
+ * the whole document, so two unserialised spawns lose one of the two entries.
+ */
+class ConfigWriteLock {
+ private readonly locks = new Map<string, Promise<void>>();
+
+ run(configPath: string, fn: () => Promise<void>): Promise<void> {
+ const prev = this.locks.get(configPath) ?? Promise.resolve();
+ const next = prev.then(fn, fn);
+ this.locks.set(configPath, next);
+ return next;
+ }
+}
+
+export const configWriteLock = new ConfigWriteLock();
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/desktop-session-startup-watch.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/desktop-session-startup-watch.ts
new file mode 100644
index 000000000..365b2b6e5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/desktop-session-startup-watch.ts
@@ -0,0 +1,12 @@
+import { log } from '@main/lib/logger';
+import { SessionStartupWatch, STARTUP_SIGNAL_TIMEOUT_MS } from './session-startup-watch';
+
+/**
+ * The watch over sessions this desktop spawned itself.
+ *
+ * Separate from the class so the sidecar can import the class without this
+ * module's Electron-bound logger coming with it. A remote session is watched by
+ * the sidecar that spawned it, on its own instance — the two processes see
+ * different sessions and neither should be told about the other's.
+ */
+export const sessionStartupWatch = new SessionStartupWatch(STARTUP_SIGNAL_TIMEOUT_MS, log);
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
index 53da2b1eb..42e51d336 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
@@ -69,6 +69,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -81,6 +82,68 @@ describe('scheduleInitialPromptInjection', () => {
expect(write).toHaveBeenCalledExactlyOnceWith('\x1b[200~Fix the bug \x1b[201~\r');
});
+ it('stays shut while the session has not reported that it started', async () => {
+ const { pty, write, emitData } = makePty();
+ let reportStarted: (started: boolean) => void = () => {};
+ scheduleInitialPromptInjection({
+ pty,
+ session: makeSession('hermes'),
+ initialPrompt: 'Fix the bug',
+ isResuming: false,
+ awaitStartupSignal: () => new Promise<boolean>((resolve) => (reportStarted = resolve)),
+ onOpenForInjection,
+ });
+
+ // A pane parked on a startup prompt looks exactly like this: output, then
+ // quiet, then quiet for as long as you care to wait.
+ emitData('Do you trust this folder?');
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(write).not.toHaveBeenCalled();
+ expect(onOpenForInjection).not.toHaveBeenCalled();
+
+ reportStarted(true);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(write).toHaveBeenCalledExactlyOnceWith('\x1b[200~Fix the bug \x1b[201~\r');
+ expect(onOpenForInjection).toHaveBeenCalledOnce();
+ });
+
+ it('still waits for the pane to settle once the session reports', async () => {
+ const { pty, write, emitData } = makePty();
+ scheduleInitialPromptInjection({
+ pty,
+ session: makeSession('hermes'),
+ initialPrompt: 'Fix the bug',
+ isResuming: false,
+ awaitStartupSignal: () => Promise.resolve(true),
+ onOpenForInjection,
+ });
+
+ await vi.advanceTimersByTimeAsync(0);
+ emitData('painting the TUI');
+ await vi.advanceTimersByTimeAsync(200);
+ expect(write).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(900);
+ expect(write).toHaveBeenCalledExactlyOnceWith('\x1b[200~Fix the bug \x1b[201~\r');
+ });
+
+ it('never opens the pane when the pty dies before reporting', async () => {
+ const { pty, write, emitExit } = makePty();
+ scheduleInitialPromptInjection({
+ pty,
+ session: makeSession('hermes'),
+ initialPrompt: 'Fix the bug',
+ isResuming: false,
+ awaitStartupSignal: () => Promise.resolve(false),
+ onOpenForInjection,
+ });
+
+ emitExit();
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(write).not.toHaveBeenCalled();
+ expect(onOpenForInjection).not.toHaveBeenCalled();
+ });
+
it('falls back to a max wait when no output ever arrives', () => {
const { pty, write } = makePty();
scheduleInitialPromptInjection({
@@ -88,6 +151,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -102,6 +166,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: 'line one\nline two',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -117,6 +182,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('opencode'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -132,6 +198,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('grok'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -147,6 +214,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('claude'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -162,6 +230,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: true,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -177,6 +246,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: ' ',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -192,6 +262,7 @@ describe('scheduleInitialPromptInjection', () => {
session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -228,6 +299,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('hermes'),
initialPrompt: 'connect to switch room r-1',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -244,6 +316,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('hermes'),
initialPrompt: 'connect to switch room r-1',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -270,6 +343,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('claude'),
initialPrompt: 'connect to switch room r-1',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -293,6 +367,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('hermes'),
initialPrompt: undefined,
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -311,6 +386,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: true,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -330,6 +406,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('claude'),
initialPrompt: 'connect to switch room r-1',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
@@ -345,6 +422,7 @@ describe('the gate on typing into a starting session', () => {
session: makeSession('claude'),
initialPrompt: 'connect to switch room r-1',
isResuming: false,
+ awaitStartupSignal: null,
onOpenForInjection,
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
index 1a70a27ae..5a56c1b0f 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
@@ -25,6 +25,18 @@ export function scheduleInitialPromptInjection(args: {
session: Session;
initialPrompt: string | undefined;
isResuming: boolean;
+ /**
+ * Resolves true once the provider reports its session is really up, or false
+ * if the pty exits first. Null for providers that cannot report it.
+ *
+ * "The TUI went quiet" cannot tell a ready pane from one parked on a
+ * first-run trust or permission prompt — both stop producing output and wait
+ * — so where a real signal exists it replaces the guess rather than racing
+ * it. A session that never reports stays shut, which is the point: its pane
+ * may be showing a security prompt whose default answer is "No, exit", and
+ * typing a room message into that answers it.
+ */
+ awaitStartupSignal: (() => Promise<boolean>) | null;
/**
* Called once the pane is ready to be typed into and the session's own
* opening prompt (if it had one to type) is in. Room messages wait on this:
@@ -46,6 +58,10 @@ export function scheduleInitialPromptInjection(args: {
let done = false;
let sawAnyOutput = false;
let quietTimer: ReturnType<typeof setTimeout> | null = null;
+ // Both must hold before anything is typed: the session has reported itself
+ // up (or cannot report at all), and the pane has stopped painting.
+ let startupReported = args.awaitStartupSignal === null;
+ let settled = false;
const open = (reason: string) => {
log.info('AgentRuntime: session open for injected prompts', {
@@ -58,8 +74,13 @@ export function scheduleInitialPromptInjection(args: {
args.onOpenForInjection();
};
+ const settle = () => {
+ settled = true;
+ if (startupReported) ready();
+ };
+
const ready = () => {
- if (done) return;
+ if (done || !settled || !startupReported) return;
done = true;
if (quietTimer) clearTimeout(quietTimer);
clearTimeout(maxWaitTimer);
@@ -102,25 +123,34 @@ export function scheduleInitialPromptInjection(args: {
}
};
- const maxWaitTimer = setTimeout(ready, MAX_WAIT_MS);
+ const maxWaitTimer = setTimeout(settle, MAX_WAIT_MS);
+
+ if (args.awaitStartupSignal) {
+ void args.awaitStartupSignal().then((reported) => {
+ if (!reported) return;
+ startupReported = true;
+ ready();
+ });
+ }
args.pty.onData(() => {
if (done) return;
sawAnyOutput = true;
if (quietTimer) clearTimeout(quietTimer);
- quietTimer = setTimeout(ready, QUIET_PERIOD_MS);
+ quietTimer = setTimeout(settle, QUIET_PERIOD_MS);
});
args.pty.onExit(() => {
- const settled = done;
+ const opened = done;
done = true;
if (quietTimer) clearTimeout(quietTimer);
clearTimeout(maxWaitTimer);
- if (!settled && promptToType !== null) {
+ if (!opened && promptToType !== null) {
log.warn('AgentRuntime: PTY exited before initial prompt could be injected', {
providerId: args.session.providerId,
sessionId: args.session.id,
sawAnyOutput,
+ startupReported,
});
}
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
index 1b083826e..a9a07f08b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
@@ -34,6 +34,7 @@ import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makePtyId } from '@shared/core/pty/ptyId';
import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
import type { Session } from '@shared/core/sessions/sessions';
+import { sessionStartupWatch } from '../desktop-session-startup-watch';
import { scheduleInitialPromptInjection } from './keystroke-injection';
import { resolveAgentExecutable } from './resolve-agent-executable';
@@ -273,6 +274,16 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
sessionId: ptySessionId,
});
+ const reportsSessionStart =
+ plugin.capabilities.hooks.kind !== 'none' && plugin.capabilities.hooks.reportsSessionStart;
+ if (reportsSessionStart) {
+ sessionStartupWatch.begin({
+ ptyId,
+ sessionId: this.sessionId,
+ providerId: session.providerId,
+ });
+ }
+
const pty = spawnLocalPty({
id: ptySessionId,
command: resolved.command,
@@ -284,6 +295,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
});
pty.onExit((info) => {
+ sessionStartupWatch.end(ptyId);
const decision = this.supervisor.handleExit(pty);
if (decision.kind === 'stale') return;
const replacementSize = ptySessionRegistry.getLastSize(ptySessionId) ?? spawnSize;
@@ -332,6 +344,13 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {
session,
initialPrompt,
isResuming: agentSession.isResuming,
+ // Where the provider can say when its session is really up, wait for
+ // that instead of guessing from terminal output: the pane may be
+ // sitting on a startup prompt, which goes quiet exactly like a session
+ // that is ready.
+ awaitStartupSignal: reportsSessionStart
+ ? () => sessionStartupWatch.waitForStart(ptyId)
+ : null,
onOpenForInjection: () => ptySessionRegistry.markOpenForInjection(ptySessionId),
});
// If this session was connected to a Switch room before an app restart,
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
index f1717f2dc..a81efcb6f 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
@@ -21,6 +21,8 @@ const SPEC: AgentLaunchSpec = {
cwd: '/home/dev/repo',
providerId: 'claude',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
};
/** This client install's deployer identity, as minted once and persisted locally. */
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
index 9c2560af5..ecc066bab 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
@@ -30,6 +30,10 @@ const resolveSshCommand = vi.hoisted(() => vi.fn(() => 'remote-cmd'));
const deployAndLaunch = vi.hoisted(() => vi.fn(async () => ({ port: 9999, token: 'sidecar-tok' })));
const sidecarStop = vi.hoisted(() => vi.fn(async () => {}));
+vi.mock('@main/core/settings/settings-service', () => ({
+ appSettingsService: { get: vi.fn(async () => ({ autoTrustWorktrees: true })) },
+}));
+
vi.mock('./resolve-sidecar-bundle', () => ({
resolveSidecarBundlePath: vi.fn(() => '/local/dist-sidecar/sidecar.mjs'),
}));
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index 7fa57ffa3..e6defbc77 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -909,6 +909,22 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime
session,
initialPrompt,
isResuming: agentSession.isResuming,
+ // A remote session's startup signal does reach Switch Console — the
+ // sidecar installs the same hooks on the VM and relays their events
+ // back through `handleRawHook`, under the same deterministic ptyId.
+ // What is missing is a safe moment to start waiting for it. This
+ // method runs again on every re-attach, where the agent has been up
+ // for hours and will not report a start a second time; an idle one
+ // emits no hooks at all, so a watch armed here would call a healthy
+ // session stalled. `reattaching` cannot rule that out either, since it
+ // is process-local and reads false after an app restart.
+ //
+ // The signal belongs where the session is actually spawned, which for
+ // a remote host is the sidecar — and that is also where the startup
+ // prompts would have to be cleared, since this runtime writes no trust
+ // entries on the far side. Both are left to that work rather than
+ // approximated from here.
+ awaitStartupSignal: null,
onOpenForInjection: () => ptySessionRegistry.markOpenForInjection(ptySessionId),
});
} catch (error) {
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.test.ts
new file mode 100644
index 000000000..dca427028
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SessionStartupWatch, type StartupStall } from './session-startup-watch';
+
+const TIMEOUT_MS = 45_000;
+
+function makeWatch(): { watch: SessionStartupWatch; stalls: StartupStall[] } {
+ const watch = new SessionStartupWatch(TIMEOUT_MS, { warn: vi.fn(), error: vi.fn() });
+ const stalls: StartupStall[] = [];
+ watch.onStall((stall) => stalls.push(stall));
+ return { watch, stalls };
+}
+
+function begin(watch: SessionStartupWatch): void {
+ watch.begin({ ptyId: 'pty-1', sessionId: 'session-1', providerId: 'claude' });
+}
+
+describe('SessionStartupWatch', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('reports a stall when the session never says it started', () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+
+ vi.advanceTimersByTime(TIMEOUT_MS - 1);
+ expect(stalls).toEqual([]);
+
+ vi.advanceTimersByTime(1);
+ expect(stalls).toEqual([{ sessionId: 'session-1', providerId: 'claude' }]);
+ });
+
+ it('stays quiet for a session that reports in time', () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+
+ watch.markStarted('pty-1');
+ vi.advanceTimersByTime(TIMEOUT_MS * 2);
+
+ expect(stalls).toEqual([]);
+ });
+
+ it('reports a stall once, not on every later hook', () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+
+ vi.advanceTimersByTime(TIMEOUT_MS);
+ watch.markStarted('pty-1');
+ watch.markStarted('pty-1');
+ vi.advanceTimersByTime(TIMEOUT_MS);
+
+ expect(stalls).toHaveLength(1);
+ });
+
+ it('opens the pane for a session that reports late, after it was called stalled', async () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+ const started = watch.waitForStart('pty-1');
+
+ vi.advanceTimersByTime(TIMEOUT_MS);
+ expect(stalls).toHaveLength(1);
+
+ watch.markStarted('pty-1');
+ await expect(started).resolves.toBe(true);
+ });
+
+ it('resolves false when the pty exits without ever reporting', async () => {
+ const { watch } = makeWatch();
+ begin(watch);
+ const started = watch.waitForStart('pty-1');
+
+ watch.end('pty-1');
+
+ await expect(started).resolves.toBe(false);
+ });
+
+ it('does not report a stall after the pty is gone', () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+
+ watch.end('pty-1');
+ vi.advanceTimersByTime(TIMEOUT_MS * 2);
+
+ expect(stalls).toEqual([]);
+ });
+
+ it('resolves false for a pty it was never asked to watch', async () => {
+ const { watch } = makeWatch();
+ await expect(watch.waitForStart('pty-unknown')).resolves.toBe(false);
+ });
+
+ it('restarts the wait when a pty id is reused by a respawn', () => {
+ const { watch, stalls } = makeWatch();
+ begin(watch);
+ watch.markStarted('pty-1');
+
+ begin(watch);
+ vi.advanceTimersByTime(TIMEOUT_MS);
+
+ expect(stalls).toHaveLength(1);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.ts
new file mode 100644
index 000000000..dfa891cc2
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/session-startup-watch.ts
@@ -0,0 +1,163 @@
+/**
+ * How long a spawned session may go without reporting that it is up before
+ * Switch Console treats it as stalled.
+ *
+ * Short on purpose: the notice exists so the person who asked stops waiting on
+ * an answer that is not coming, and a notice that arrives a minute late has
+ * already failed at that. The CLIs report as soon as their session exists,
+ * before the first turn, so this is the gap between spawning a process and it
+ * being ready to be spoken to — not the time to do any work.
+ *
+ * The cost of being wrong is asymmetric and mild in this direction: a slow
+ * start that reports at five seconds gets one notice it did not need, and the
+ * pane opens the moment the report lands either way. A stall never resolves
+ * itself, so the only thing a longer wait buys is a later notice.
+ */
+export const STARTUP_SIGNAL_TIMEOUT_MS = 6_000;
+
+export type StartupStall = {
+ sessionId: string;
+ providerId: string;
+};
+
+/**
+ * The logging surface this needs, injected rather than imported so the watch
+ * can run in the sidecar bundle — which must not pull in the Electron-bound
+ * main-process file logger, and which is where a remote session's startup is
+ * actually observed.
+ */
+export interface StartupWatchLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+ error(message: string, meta?: Record<string, unknown>): void;
+}
+
+type Watch = {
+ sessionId: string;
+ providerId: string;
+ started: boolean;
+ timer: ReturnType<typeof setTimeout>;
+ settle: ((started: boolean) => void)[];
+};
+
+/**
+ * Tracks whether a spawned session ever reported that it was really running.
+ *
+ * The gap this closes: a CLI that stops on a first-run prompt — workspace
+ * trust, setup, a bypass warning — has spawned, is alive, and will never
+ * answer. Nothing about the process says so, and the terminal cannot be asked
+ * without pattern-matching the text of a security prompt, which fails silently
+ * and wrongly the moment the wording changes. A hook the CLI fires when its
+ * session comes up says it directly: it arrives when the session is running
+ * and not at all when it is parked.
+ *
+ * Only for providers that declare `reportsSessionStart`. Everywhere else there
+ * is no signal to wait on, and inventing one from terminal output is the thing
+ * this exists to avoid.
+ */
+export class SessionStartupWatch {
+ private readonly watches = new Map<string, Watch>();
+ private readonly stallHandlers = new Set<(stall: StartupStall) => void>();
+
+ constructor(
+ private readonly timeoutMs: number,
+ private readonly log: StartupWatchLogger
+ ) {}
+
+ /** Subscribe to sessions that never reported a start. Returns an unsubscribe. */
+ onStall(handler: (stall: StartupStall) => void): () => void {
+ this.stallHandlers.add(handler);
+ return () => this.stallHandlers.delete(handler);
+ }
+
+ begin(args: { ptyId: string; sessionId: string; providerId: string }): void {
+ this.end(args.ptyId);
+ const timer = setTimeout(() => this.reportStall(args.ptyId), this.timeoutMs);
+ // The wait outlives the timeout: a session that is merely slow still
+ // reports eventually, and its pane should open when it does.
+ timer.unref?.();
+ this.watches.set(args.ptyId, {
+ sessionId: args.sessionId,
+ providerId: args.providerId,
+ started: false,
+ timer,
+ settle: [],
+ });
+ }
+
+ /**
+ * A hook fired for this pty, so the CLI is past its startup prompts and
+ * running. Any hook proves it, not only the session-start one.
+ */
+ markStarted(ptyId: string): void {
+ const watch = this.watches.get(ptyId);
+ if (!watch || watch.started) return;
+ watch.started = true;
+ clearTimeout(watch.timer);
+ this.settleAll(watch, true);
+ }
+
+ /** The pty is gone; nothing is coming. */
+ end(ptyId: string): void {
+ const watch = this.watches.get(ptyId);
+ if (!watch) return;
+ this.watches.delete(ptyId);
+ clearTimeout(watch.timer);
+ this.settleAll(watch, watch.started);
+ }
+
+ /**
+ * Resolves true once the session reports it is up, or false if the pty exits
+ * first. Deliberately has no timeout of its own: a stall is worth reporting
+ * but is not proof the session is dead, and typing into a pane that may still
+ * be showing a security prompt is the failure this is here to prevent.
+ */
+ waitForStart(ptyId: string): Promise<boolean> {
+ const watch = this.watches.get(ptyId);
+ if (!watch) return Promise.resolve(false);
+ if (watch.started) return Promise.resolve(true);
+ return new Promise<boolean>((resolve) => watch.settle.push(resolve));
+ }
+
+ /**
+ * True when this pty is being watched and has not reported yet — the window
+ * in which its pane may still be showing a startup prompt, so nothing should
+ * be typed into it.
+ *
+ * A pty with no watch is not blocked. Only a spawn arms one, so an adopted or
+ * already-running session must not be held mute waiting for a report that was
+ * never expected of it.
+ */
+ blocksInjection(ptyId: string): boolean {
+ const watch = this.watches.get(ptyId);
+ return watch !== undefined && !watch.started;
+ }
+
+ private settleAll(watch: Watch, started: boolean): void {
+ const waiters = watch.settle.splice(0);
+ for (const resolve of waiters) resolve(started);
+ }
+
+ private reportStall(ptyId: string): void {
+ const watch = this.watches.get(ptyId);
+ if (!watch || watch.started) return;
+
+ this.log.error('AgentRuntime: session never reported that it started', {
+ event: 'switch_session_startup_stalled',
+ sessionId: watch.sessionId,
+ providerId: watch.providerId,
+ waitedMs: this.timeoutMs,
+ });
+
+ const stall: StartupStall = { sessionId: watch.sessionId, providerId: watch.providerId };
+ for (const handler of this.stallHandlers) {
+ try {
+ handler(stall);
+ } catch (error) {
+ this.log.warn('AgentRuntime: startup-stall handler failed', {
+ sessionId: watch.sessionId,
+ error: String(error),
+ });
+ }
+ }
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
index c8b28eecb..f4b49792a 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
@@ -32,6 +32,10 @@ vi.mock('@main/core/providers/plugin-registry', () => ({
vi.mock('@main/core/agent-runtime/impl/resolve-agent-executable', () => ({
resolveAgentExecutable: vi.fn(async () => '/usr/bin/claude'),
}));
+vi.mock('@main/core/settings/settings-service', () => ({
+ appSettingsService: { get: vi.fn(async () => ({ autoTrustWorktrees: true })) },
+}));
+
vi.mock('@main/core/settings/provider-settings-service', () => ({
providerOverrideSettings: { getItem: vi.fn(async () => undefined) },
}));
@@ -49,6 +53,8 @@ const baseParams = {
providerId: 'claude',
remoteRepoDir: '/home/agent/repo',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
agentName: null,
credsSlug: 'hoot',
ctx: {} as never,
@@ -239,6 +245,8 @@ describe('generateAgentLaunchSpec against real provider command builders', () =>
cwd: '/home/agent/repo',
providerId: 'codex',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
},
{
sessionId: 's1',
@@ -264,6 +272,8 @@ describe('generateAgentLaunchSpec against real provider command builders', () =>
cwd: '/home/agent/repo',
providerId: 'claude',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
},
{
sessionId: 's1',
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts
index 42822ece2..595d2f1ac 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts
@@ -5,6 +5,7 @@ import { hostDependencyStore } from '@main/core/dependencies/host-dependency-sto
import type { IExecutionContext } from '@main/core/execution-context/types';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';
+import { appSettingsService } from '@main/core/settings/settings-service';
import {
type AgentLaunchSpec,
INITIAL_PROMPT_PLACEHOLDER,
@@ -117,5 +118,9 @@ export async function generateAgentLaunchSpec(params: {
})),
providerId,
deeplinkScheme,
+ autoApprove,
+ // Read here rather than passed in: it is one global app setting, not a
+ // per-call decision, and the sidecar has no way to reach it.
+ autoTrustWorktrees: (await appSettingsService.get('sessions')).autoTrustWorktrees,
};
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
index 8e3cbb331..5ee20ea58 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
@@ -1,6 +1,8 @@
import { randomUUID } from 'node:crypto';
import path from 'node:path';
import { type AgentBridgeEvent, SwitchEventStream } from '@sandboxaq/switch-agent-runtime';
+import { sessionStartupWatch } from '@main/core/agent-runtime/desktop-session-startup-watch';
+import { STARTUP_SIGNAL_TIMEOUT_MS } from '@main/core/agent-runtime/session-startup-watch';
import { getRemoteAgentLocation } from '@main/core/agents/agent-location';
import { getAgentById } from '@main/core/agents/getAgentById';
import {
@@ -42,6 +44,12 @@ function spawnTurnOf(event: AgentBridgeEvent): SpawnTurn | null {
const SPAWN_MAX_ATTEMPTS = 3;
const SPAWN_RETRY_DELAY_MS = 2000;
+
+/**
+ * How long a spawn stays eligible for a startup-stall notice. Comfortably past
+ * STARTUP_SIGNAL_TIMEOUT_MS, which is when the verdict actually lands.
+ */
+const SPAWN_STALL_WATCH_TTL_MS = STARTUP_SIGNAL_TIMEOUT_MS + 30_000;
// How long a room stays "spawn in flight" before the guard is cleared.
//
// This covers the window the server cannot: it learns a session exists only
@@ -118,6 +126,42 @@ async function roomNameFor(localAgentId: string, roomId: string): Promise<string
}
}
+/**
+ * The name of whoever addressed the agent, so a notice can reach them rather
+ * than just appear in the channel. Null for a command or a join, which nobody
+ * is waiting on an answer to.
+ */
+function requesterNameOf(event: AgentBridgeEvent): string | null {
+ if (event.type !== 'message') return null;
+ const name = (event.payload as { sender_name?: string }).sender_name;
+ return name?.trim() ? name.trim() : null;
+}
+
+/**
+ * Address a room notice to the person waiting on it.
+ *
+ * The `@name` is deliberate: Switch re-parses it, so the notice reaches them
+ * wherever they are instead of scrolling past in a channel they may not be
+ * looking at. That is the whole point of a notice saying nobody is coming.
+ */
+function addressedTo(requesterName: string | null, body: string): string {
+ return requesterName ? `${body} (FYI @${requesterName})` : body;
+}
+
+/**
+ * What the room is told when a session never came up.
+ *
+ * Says only why, and carries no link: the "Open in Switch Console" link and the
+ * mention of the agent's owner come from the session's runtime state, which
+ * switch-core renders into a clickable line. A `switchdash://` URL written into
+ * a message body is never rewritten and arrives as dead text.
+ */
+const STARTUP_STALL_NOTICE =
+ 'My session seems to be blocked on something and never started — most likely a prompt only a human can answer.';
+
+const SPAWN_FAILED_NOTICE =
+ "I tried to start a session to handle this but couldn't — my operator may need to start one manually.";
+
/** Post a message to a room on the agent's behalf (used for the spawn-failure
* notice). Best-effort; throws on non-OK so the caller can log. */
async function postRoomMessage(
@@ -149,10 +193,26 @@ async function postRoomMessage(
class AutoSessionWatcher {
private readonly watchers = new Map<string, AgentWatcher>();
private roomChangeUnsub: (() => void) | null = null;
+ private startupStallUnsub: (() => void) | null = null;
+ /**
+ * Rooms whose waiting message is riding on a session this watcher spawned,
+ * so a session that never starts can be reported to the people waiting on
+ * it. Sessions spawned any other way have no room to answer to.
+ */
+ private readonly spawnedForRoom = new Map<
+ string,
+ {
+ roomId: string;
+ creds: SwitchAgentCredentials;
+ requesterName: string | null;
+ expiry: ReturnType<typeof setTimeout>;
+ }
+ >();
/** Start watchers for every agent and subagent currently mirrored as auto_session. */
async initialize(): Promise<void> {
this.subscribeToRoomConnections();
+ this.subscribeToStartupStalls();
const ids = await listAutoSessionAgentIds();
for (const agentId of ids) {
// Self-heal stale mirror entries: an agent deleted by a build that did not
@@ -216,6 +276,65 @@ class AutoSessionWatcher {
});
}
+ /**
+ * A session spawned to answer a room never reported that it started, so the
+ * message that triggered it is going unanswered and the room has been told
+ * one is coming. Say so there instead of leaving the human waiting on a
+ * session that looks alive.
+ *
+ * The in-flight guard is cleared too, so the next message can try again
+ * rather than being suppressed by a spawn that went nowhere.
+ */
+ private rememberSpawn(
+ sessionId: string,
+ roomId: string,
+ creds: SwitchAgentCredentials,
+ requesterName: string | null
+ ): void {
+ this.forgetSpawn(sessionId);
+ // Only the stall verdict is of interest, and it lands within the watch's
+ // own timeout; past that the entry is dead weight on a session that came up
+ // fine.
+ const expiry = setTimeout(() => this.forgetSpawn(sessionId), SPAWN_STALL_WATCH_TTL_MS);
+ expiry.unref?.();
+ this.spawnedForRoom.set(sessionId, { roomId, creds, requesterName, expiry });
+ }
+
+ private forgetSpawn(sessionId: string): void {
+ const spawned = this.spawnedForRoom.get(sessionId);
+ if (!spawned) return;
+ clearTimeout(spawned.expiry);
+ this.spawnedForRoom.delete(sessionId);
+ }
+
+ private subscribeToStartupStalls(): void {
+ if (this.startupStallUnsub) return;
+ this.startupStallUnsub = sessionStartupWatch.onStall(({ sessionId, providerId }) => {
+ const spawned = this.spawnedForRoom.get(sessionId);
+ if (!spawned) return;
+ this.forgetSpawn(sessionId);
+
+ for (const watcher of this.watchers.values()) {
+ if (watcher.creds.agentId === spawned.creds.agentId) {
+ this.clearInFlight(watcher, spawned.roomId);
+ }
+ }
+
+ log.error('AutoSessionWatcher: spawned session never started', {
+ roomId: spawned.roomId,
+ sessionId,
+ providerId,
+ });
+
+ void postRoomMessage(spawned.creds, spawned.roomId, STARTUP_STALL_NOTICE).catch((error) => {
+ log.warn('AutoSessionWatcher: failed to post startup-stall notice', {
+ roomId: spawned.roomId,
+ error: String(error),
+ });
+ });
+ });
+ }
+
private clearInFlight(watcher: AgentWatcher, roomId: string): void {
const timer = watcher.inFlight.get(roomId);
if (timer) clearTimeout(timer);
@@ -355,6 +474,9 @@ class AutoSessionWatcher {
dispose(): void {
this.roomChangeUnsub?.();
this.roomChangeUnsub = null;
+ this.startupStallUnsub?.();
+ this.startupStallUnsub = null;
+ for (const sessionId of [...this.spawnedForRoom.keys()]) this.forgetSpawn(sessionId);
for (const id of [...this.watchers.keys()]) this.stopForAgent(id);
}
@@ -514,7 +636,7 @@ class AutoSessionWatcher {
const timer = setTimeout(() => watcher.inFlight.delete(roomId), INFLIGHT_TTL_MS);
watcher.inFlight.set(roomId, timer);
- void this.spawnForRoom(watcher, roomId, triggerLine).catch((error) => {
+ void this.spawnForRoom(watcher, roomId, triggerLine, requesterNameOf(event)).catch((error) => {
log.warn('AutoSessionWatcher: spawn failed', {
localAgentId: watcher.localAgentId,
roomId,
@@ -526,7 +648,8 @@ class AutoSessionWatcher {
private async spawnForRoom(
watcher: AgentWatcher,
roomId: string,
- triggerLine: string | null
+ triggerLine: string | null,
+ requesterName: string | null
): Promise<void> {
// Bypass permissions only if this agent is configured to. Auto-started
// local sessions run with no operator watching, but the default is off —
@@ -569,6 +692,7 @@ class AutoSessionWatcher {
roomId,
sessionId: result.data.session.id,
});
+ this.rememberSpawn(result.data.session.id, roomId, watcher.creds, requesterName);
// createSession provisions the runtime inline but emits only
// session:created — not session:provisioned. Without the latter an
// open renderer leaves the session stuck "Setting up session…"
@@ -605,7 +729,7 @@ class AutoSessionWatcher {
await postRoomMessage(
watcher.creds,
roomId,
- "I tried to start a session to handle this but couldn't — my operator may need to start one manually."
+ addressedTo(requesterName, SPAWN_FAILED_NOTICE)
).catch((error) => {
log.warn('AutoSessionWatcher: failed to post spawn-failure notice', {
roomId,
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts
index e747ac920..e5a8b8810 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/room-connection.ts
@@ -4,6 +4,7 @@ import { SwitchEventStream } from '@sandboxaq/switch-agent-runtime';
import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';
import type { InjectionSink } from './injection-sink';
import type { SessionControl } from './session-control';
+import { buildSessionDeeplink } from './session-deeplink';
import {
formatEventForInjection,
formatAttachmentAnnotation,
@@ -501,15 +502,13 @@ export class RoomConnection {
* it verbatim. Resolution is by room, so `server`/`agent` are advisory.
*/
private sessionDeeplink(): string {
- const params = new URLSearchParams({
- server: this.creds.apiEndpoint,
- agent: this.creds.agentId,
- room: this.roomId ?? '',
- // The shared session id resolves to the exact session on any client
- // (a client that only adopted the session has no room mapping to match on).
- session: this.sessionId,
+ return buildSessionDeeplink({
+ scheme: this.deeplinkScheme,
+ apiEndpoint: this.creds.apiEndpoint,
+ agentId: this.creds.agentId,
+ roomId: this.roomId,
+ sessionId: this.sessionId,
});
- return `${this.deeplinkScheme}://session?${params.toString()}`;
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-deeplink.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-deeplink.ts
new file mode 100644
index 000000000..a183d8366
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/session-deeplink.ts
@@ -0,0 +1,26 @@
+/**
+ * The `<scheme>://session?…` link that opens one session in Switch Console.
+ *
+ * Switch Console owns this shape — switch-core relays it verbatim, and rewrites
+ * it into an https redirect for platforms that will not linkify a custom
+ * scheme, so a link posted into a room is clickable wherever the room is
+ * bridged.
+ *
+ * Resolution is by session id, which resolves on any client; `server` and
+ * `agent` are advisory, and `room` is empty for a session attending none.
+ */
+export function buildSessionDeeplink(args: {
+ scheme: string;
+ apiEndpoint: string;
+ agentId: string;
+ roomId: string | null;
+ sessionId: string;
+}): string {
+ const params = new URLSearchParams({
+ server: args.apiEndpoint,
+ agent: args.agentId,
+ room: args.roomId ?? '',
+ session: args.sessionId,
+ });
+ return `${args.scheme}://session?${params.toString()}`;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx
index e1912aad7..a7e201a9a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/SessionSettingsRows.tsx
@@ -42,7 +42,7 @@ export const AutoTrustWorktreesRow: React.FC = () => {
Auto-trust worktree directories
<InfoTooltip
label="More info about auto-trust worktrees"
- content="Applies to Claude Code and GitHub Copilot. Writes trust entries before launching."
+ content="Applies to Claude Code, Codex, Cursor and GitHub Copilot. Writes trust entries before launching."
/>
</div>
}
diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts
index ddff2443b..88706cf09 100644
--- a/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/providers/agent-provider-registry.ts
@@ -34,6 +34,18 @@ export const AGENT_PROVIDER_IDS = [
export type AgentProviderId = (typeof AGENT_PROVIDER_IDS)[number];
+/**
+ * Narrow a provider id that arrived as an opaque string — from a database row
+ * or a launch spec read off disk — to a registered one.
+ *
+ * Throws rather than passing it through: every consumer dispatches on this
+ * value, so an unregistered id silently selects no behaviour at all.
+ */
+export function asAgentProviderId(value: string): AgentProviderId {
+ if ((AGENT_PROVIDER_IDS as readonly string[]).includes(value)) return value as AgentProviderId;
+ throw new Error(`unknown agent provider '${value}'`);
+}
+
export type AgentProviderDefinition = {
id: AgentProviderId;
name: string;
diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/agentEvents.ts b/console/apps/switch-console-desktop/src/shared/core/providers/agentEvents.ts
index efb0f0cbe..faa48a855 100644
--- a/console/apps/switch-console-desktop/src/shared/core/providers/agentEvents.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/providers/agentEvents.ts
@@ -8,12 +8,19 @@ export type NotificationType =
| 'permission_prompt'
| 'idle_prompt'
| 'auth_success'
- | 'elicitation_dialog';
+ | 'elicitation_dialog'
+ /**
+ * The session never reported that it started. Raised by Switch Console
+ * itself, not by the agent — a CLI stopped on its own first-run prompt has
+ * nothing to send. See session-startup-watch.
+ */
+ | 'startup_prompt';
export const ATTENTION_NOTIFICATION_TYPES: ReadonlySet<NotificationType> = new Set([
'permission_prompt',
'idle_prompt',
'elicitation_dialog',
+ 'startup_prompt',
]);
export function isAttentionNotification(nt: NotificationType | undefined): nt is NotificationType {
diff --git a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts
index 76db41ff8..4c320c29c 100644
--- a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts
@@ -21,6 +21,8 @@ function spec(overrides: Partial<AgentLaunchSpec> = {}): AgentLaunchSpec {
cwd: '/home/agent/repo',
providerId: 'claude',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
...overrides,
};
}
diff --git a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts
index 297b47255..cc0199c90 100644
--- a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts
@@ -44,6 +44,18 @@ export interface AgentLaunchSpec {
launchFiles?: AgentLaunchFile[];
providerId: string;
deeplinkScheme: string;
+ /**
+ * The agent's bypass-permissions setting, already reflected in {@link args}.
+ * Repeated here because clearing the confirmation the bypass flag provokes is
+ * a separate act from passing the flag, and the sidecar performs it on the VM.
+ */
+ autoApprove: boolean;
+ /**
+ * Switch Console's "auto-trust worktree directories" setting, carried to the
+ * VM because that is where the trust entries have to be written and the
+ * sidecar cannot read the desktop's settings.
+ */
+ autoTrustWorktrees: boolean;
}
/** Argv token Switch Console emits in place of the fresh session's session id. */
diff --git a/console/apps/switch-console-desktop/src/sidecar/index.ts b/console/apps/switch-console-desktop/src/sidecar/index.ts
index f929f5da2..368bdd844 100644
--- a/console/apps/switch-console-desktop/src/sidecar/index.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/index.ts
@@ -5,6 +5,10 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { HookEventLog, HookServer } from '@main/core/agent-hooks/hook-server';
+import {
+ SessionStartupWatch,
+ STARTUP_SIGNAL_TIMEOUT_MS,
+} from '@main/core/agent-runtime/session-startup-watch';
import { agentSettingsPath } from '@main/core/agents/switch-settings-paths';
import {
readSwitchAgentCredentials,
@@ -13,8 +17,13 @@ import {
import { createTmuxRun } from '@main/core/switch-rooms/tmux-injection-sink';
import { type AgentLaunchSpec } from './agent-launch-spec';
import { atomicWriteFile } from './atomic-file';
-import { NotificationWatcher, type WatcherLogger } from './notification-watcher';
-import { InProcessSessionSpawner } from './session-spawner';
+import {
+ NotificationWatcher,
+ postRoomMessage,
+ STARTUP_STALL_NOTICE,
+ type WatcherLogger,
+} from './notification-watcher';
+import { clearStartupPromptsFor, InProcessSessionSpawner } from './session-spawner';
import { createSidecarLogger, requireEnv } from './sidecar-logger';
import {
LEGACY_LAUNCH_SPEC_REL_PATH,
@@ -78,7 +87,11 @@ async function hashOwnBundle(log: WatcherLogger): Promise<string | null> {
}
}
-async function readLaunchSpec(repoDir: string, specRelPath: string): Promise<AgentLaunchSpec> {
+async function readLaunchSpec(
+ repoDir: string,
+ specRelPath: string,
+ log: { warn: (message: string, meta?: Record<string, unknown>) => void }
+): Promise<AgentLaunchSpec> {
const specPath = path.join(repoDir, specRelPath);
let raw: string;
try {
@@ -90,6 +103,16 @@ async function readLaunchSpec(repoDir: string, specRelPath: string): Promise<Age
if (!spec.command || !Array.isArray(spec.args) || !spec.cwd || !spec.providerId) {
throw new Error(`sidecar: launch spec at ${specPath} is missing required fields`);
}
+ // A spec written by an older Switch Console carries neither flag. Both decide
+ // whether to waive a prompt on the user's behalf, so an absent one reads as
+ // "do not" — and says so, because the visible effect is sessions stalling on
+ // prompts this sidecar could otherwise have cleared.
+ for (const key of ['autoApprove', 'autoTrustWorktrees'] as const) {
+ if (typeof spec[key] !== 'boolean') {
+ log.warn(`sidecar: launch spec predates ${key}; treating it as off`, { specPath });
+ spec[key] = false;
+ }
+ }
return spec;
}
@@ -122,7 +145,7 @@ async function main(): Promise<void> {
const watchEnabledRel = credsSlug
? sidecarWatchEnabledRelPath(credsSlug)
: LEGACY_WATCH_ENABLED_REL_PATH;
- const launchSpec = await readLaunchSpec(repoDir, launchSpecRel);
+ const launchSpec = await readLaunchSpec(repoDir, launchSpecRel, log);
// Pane-liveness cache: a background poll marks each active/pending tmux target
// live or dead so injection defers (rather than fails) when a pane is briefly
@@ -163,6 +186,11 @@ async function main(): Promise<void> {
log,
});
+ // Owned here and shared with both halves: the spawner arms it for a session
+ // it starts, the runtime clears it when that session's first hook arrives and
+ // consults it before typing into the pane.
+ const startupWatch = new SessionStartupWatch(STARTUP_SIGNAL_TIMEOUT_MS, log);
+
const runtime = new SidecarRuntime({
creds,
deeplinkScheme,
@@ -171,6 +199,32 @@ async function main(): Promise<void> {
log,
createConnection: defaultRoomConnectionFactory,
registry: store,
+ startupWatch,
+ });
+
+ // A session that never reported itself up is stopped on something only a
+ // human can answer, and on a VM nobody is looking at that terminal. Say so in
+ // the room the session was started to answer — the same courtesy the watcher
+ // already extends when a spawn fails outright, for the case where the spawn
+ // succeeded and the session did not.
+ //
+ // The launched entry is deliberately left in place: the stuck pane is alive,
+ // so dropping it would let the next message spawn a second session on top of
+ // the first rather than surfacing the one that needs attention.
+ startupWatch.onStall(({ sessionId, providerId }) => {
+ const roomId = spawner?.roomIdForSession(sessionId);
+ if (!roomId) return;
+ log.error('sidecar: spawned session never reported that it started', {
+ sessionId,
+ providerId,
+ roomId,
+ });
+ // The state report is what carries the deeplink and names the owner; the
+ // message only says why. Both, because the report's wording is generic.
+ runtime.reportStartupStalled(sessionId);
+ void postRoomMessage(creds, roomId, STARTUP_STALL_NOTICE).catch((error) => {
+ log.warn('sidecar: failed to post startup-stall notice', { roomId, error: String(error) });
+ });
});
// Bring each restored session's room connection back up. The agent is still
@@ -289,6 +343,7 @@ async function main(): Promise<void> {
},
isPaneLive,
log,
+ startupWatch,
});
// The sidecar always serves session injection; the notification watcher only
@@ -314,7 +369,7 @@ async function main(): Promise<void> {
const refreshLaunchSpec = async (): Promise<void> => {
let spec: AgentLaunchSpec;
try {
- spec = await readLaunchSpec(repoDir, launchSpecRel);
+ spec = await readLaunchSpec(repoDir, launchSpecRel, log);
} catch (error) {
log.warn('sidecar: failed to re-read launch spec; keeping current', {
error: String(error),
@@ -368,6 +423,12 @@ async function main(): Promise<void> {
// Hash our OWN bytes rather than echoing the hash we were launched with: the
// launcher can skip an upload it believes is redundant and be wrong, and a
// sidecar that advertises a build it is not running is undetectable.
+ // Before this sidecar reports ready — which is the signal Switch Console
+ // waits on before opening a session's pane over SSH — clear the CLI prompts
+ // that would stop that pane before it starts. A desktop-started session never
+ // passes through the spawner, so this is the only point that covers it.
+ await clearStartupPromptsFor(launchSpec, log);
+
const bundleHash = await hashOwnBundle(log);
const readyLine = `${JSON.stringify({
event: 'ready',
diff --git a/console/apps/switch-console-desktop/src/sidecar/notification-watcher.test.ts b/console/apps/switch-console-desktop/src/sidecar/notification-watcher.test.ts
index 56dcbcac8..8cb4375ef 100644
--- a/console/apps/switch-console-desktop/src/sidecar/notification-watcher.test.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/notification-watcher.test.ts
@@ -27,10 +27,17 @@ afterEach(() => {
// spawnForRoom / handleNotification are private; reach them to test the spawn
// decision in isolation from the long-poll loop.
-function handle(watcher: NotificationWatcher, roomId: string, sequence?: number): void {
+function handle(
+ watcher: NotificationWatcher,
+ roomId: string,
+ sequence?: number,
+ requesterName: string | null = null
+): void {
(
- watcher as unknown as { handleNotification: (r: string, s?: number) => void }
- ).handleNotification(roomId, sequence);
+ watcher as unknown as {
+ handleNotification: (r: string, who: string | null, s?: number) => void;
+ }
+ ).handleNotification(roomId, requesterName, sequence);
}
describe('NotificationWatcher spawn decision', () => {
@@ -49,7 +56,7 @@ describe('NotificationWatcher spawn decision', () => {
const spawner = makeSpawner();
handle(makeWatcher(spawner), 'room-x');
await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));
- expect(spawner.launch).toHaveBeenCalledWith('room-x', undefined);
+ expect(spawner.launch).toHaveBeenCalledWith('room-x', null, undefined);
});
// The watcher consumed the triggering event to decide to spawn, so the
@@ -59,14 +66,14 @@ describe('NotificationWatcher spawn decision', () => {
const spawner = makeSpawner();
handle(makeWatcher(spawner), 'room-x', 42);
await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));
- expect(spawner.launch).toHaveBeenCalledWith('room-x', 41);
+ expect(spawner.launch).toHaveBeenCalledWith('room-x', null, 41);
});
it('does not rewind past the start of the stream', async () => {
const spawner = makeSpawner();
handle(makeWatcher(spawner), 'room-x', 0);
await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));
- expect(spawner.launch).toHaveBeenCalledWith('room-x', 0);
+ expect(spawner.launch).toHaveBeenCalledWith('room-x', null, 0);
});
it('does not launch when a live session already attends the room', async () => {
@@ -130,6 +137,23 @@ describe('NotificationWatcher spawn decision', () => {
expect(String(url)).toContain('/agents/switch-agent-1/message');
expect(String((init as RequestInit).body)).toContain('start a session');
}, 10_000);
+
+ // A notice nobody is pinged by scrolls past in a channel the person who asked
+ // may not be watching, which defeats the point of saying nobody is coming.
+ it('addresses the spawn-failure notice to whoever asked', async () => {
+ const launch = vi.fn(async () => {
+ throw new Error('boom');
+ });
+ const fetchMock = vi.fn(
+ async (_url: string | URL, _init?: RequestInit) => new Response(null, { status: 200 })
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ handle(makeWatcher(makeSpawner({ launch })), 'room-x', undefined, 'louis.amaudruz');
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled(), { timeout: 8000 });
+ const [, init] = fetchMock.mock.calls.at(-1)!;
+ expect(String((init as RequestInit).body)).toContain('@louis.amaudruz');
+ }, 10_000);
});
describe('NotificationWatcher watch gate', () => {
diff --git a/console/apps/switch-console-desktop/src/sidecar/notification-watcher.ts b/console/apps/switch-console-desktop/src/sidecar/notification-watcher.ts
index 923e8152c..97d74b8ae 100644
--- a/console/apps/switch-console-desktop/src/sidecar/notification-watcher.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/notification-watcher.ts
@@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { SwitchEventStream } from '@sandboxaq/switch-agent-runtime';
+import { type AgentBridgeEvent, SwitchEventStream } from '@sandboxaq/switch-agent-runtime';
import type { SwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';
// How often the auto_session gate is re-read, so toggling it takes effect
@@ -61,11 +61,49 @@ export interface SessionSpawner {
* how it knows to spawn — so a session opening at head comes up having
* missed the very message it exists to answer.
*/
- launch(roomId: string, startCursor?: number): Promise<void>;
+ launch(roomId: string, requesterName: string | null, startCursor?: number): Promise<void>;
}
-/** Post a message to a room on the agent's behalf (the spawn-failure notice). Throws on non-OK. */
-async function postRoomMessage(
+/**
+ * The name of whoever addressed the agent, so a notice can reach them rather
+ * than just appear in the channel. Null for a command or a join, which nobody
+ * is waiting on an answer to.
+ */
+export function requesterNameOf(event: AgentBridgeEvent): string | null {
+ if (event.type !== 'message') return null;
+ const name = (event.payload as { sender_name?: string }).sender_name;
+ return name?.trim() ? name.trim() : null;
+}
+
+/**
+ * Address a room notice to the person waiting on it.
+ *
+ * The `@name` is deliberate: Switch re-parses it, so the notice reaches them
+ * wherever they are instead of scrolling past in a channel they may not be
+ * looking at. That is the whole point of a notice saying nobody is coming.
+ */
+export function addressedTo(requesterName: string | null, body: string): string {
+ return requesterName ? `${body} (FYI @${requesterName})` : body;
+}
+
+/**
+ * What the room is told when a session never came up.
+ *
+ * Says only why, and carries no link: the "Open in Switch Console" link and the
+ * mention of the agent's owner come from the session's runtime state, which
+ * switch-core renders into a clickable line. A `switchdash://` URL written into
+ * a message body is never rewritten and arrives as dead text.
+ */
+export const STARTUP_STALL_NOTICE =
+ 'My session seems to be blocked on something and never started — most likely a prompt only a human can answer.';
+
+/**
+ * Post a message to a room on the agent's behalf. Throws on non-OK.
+ *
+ * Used for the two notices this VM owes a room it cannot serve: a spawn that
+ * failed outright, and one that succeeded into a session which never started.
+ */
+export async function postRoomMessage(
creds: SwitchAgentCredentials,
roomId: string,
content: string
@@ -168,7 +206,9 @@ export class NotificationWatcher {
// Same promise as Switch Console's watcher: this process will spawn.
spawnCapable: true,
onEvent: (event) => {
- if (event.room_id) this.handleNotification(event.room_id, event.sequence);
+ if (event.room_id) {
+ this.handleNotification(event.room_id, requesterNameOf(event), event.sequence);
+ }
},
onGap: (info) => {
log.warn('NotificationWatcher: gap — may have missed a spawn trigger', {
@@ -200,7 +240,11 @@ export class NotificationWatcher {
}
/** Decide whether to spawn for a notified room, with a per-room in-flight guard. */
- private handleNotification(roomId: string, sequence?: number): void {
+ private handleNotification(
+ roomId: string,
+ requesterName: string | null,
+ sequence?: number
+ ): void {
if (this.inFlight.has(roomId)) {
this.deps.log.info(
'NotificationWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',
@@ -217,7 +261,7 @@ export class NotificationWatcher {
// claims — where a gap is the bug this exists to prevent.
const startCursor = sequence === undefined ? undefined : Math.max(sequence - 1, 0);
- void this.spawnForRoom(roomId, startCursor).catch((error) => {
+ void this.spawnForRoom(roomId, requesterName, startCursor).catch((error) => {
this.deps.log.warn('NotificationWatcher: spawn failed', { roomId, error: String(error) });
});
}
@@ -232,7 +276,11 @@ export class NotificationWatcher {
this.clearInFlight(roomId);
}
- private async spawnForRoom(roomId: string, startCursor?: number): Promise<void> {
+ private async spawnForRoom(
+ roomId: string,
+ requesterName: string | null,
+ startCursor?: number
+ ): Promise<void> {
const { spawner, creds, log } = this.deps;
// A session this watcher started is already attending the room — its own
@@ -246,7 +294,7 @@ export class NotificationWatcher {
for (let attempt = 1; attempt <= SPAWN_MAX_ATTEMPTS; attempt += 1) {
if (this.abort.signal.aborted) return;
try {
- await spawner.launch(roomId, startCursor);
+ await spawner.launch(roomId, requesterName, startCursor);
// Half of a hand-off logged at both ends, so a session that comes up
// without its triggering message can be diagnosed from the log alone:
// this says where the session should start reading, and the runtime's
@@ -278,7 +326,10 @@ export class NotificationWatcher {
await postRoomMessage(
creds,
roomId,
- "I tried to start a session to handle this but couldn't — my operator may need to start one manually."
+ addressedTo(
+ requesterName,
+ "I tried to start a session to handle this but couldn't — my operator may need to start one manually."
+ )
).catch((error) => {
log.warn('NotificationWatcher: failed to post spawn-failure notice', {
roomId,
diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
index 278933531..ff389ef27 100644
--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.test.ts
@@ -3,6 +3,8 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parse as parseTOML } from 'smol-toml';
import { afterAll, describe, expect, it, vi } from 'vitest';
+import { SessionStartupWatch } from '@main/core/agent-runtime/session-startup-watch';
+import { makePtyId } from '@shared/core/pty/ptyId';
import {
type AgentLaunchSpec,
INITIAL_PROMPT_PLACEHOLDER,
@@ -48,6 +50,8 @@ const SPEC: AgentLaunchSpec = {
cwd: CWD,
providerId: 'claude',
deeplinkScheme: 'switchdash',
+ autoApprove: false,
+ autoTrustWorktrees: true,
};
function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {
@@ -69,6 +73,7 @@ function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {
SWITCH_AGENT_ID: 'agent-1',
},
isPaneLive: () => true,
+ startupWatch: new SessionStartupWatch(45_000, { warn: vi.fn(), error: vi.fn() }),
log: silentLog,
exec,
...over,
@@ -79,7 +84,7 @@ function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {
describe('InProcessSessionSpawner.launch', () => {
it('launches the agent tmux session wired to the local hook server', async () => {
const { spawner, calls } = makeSpawner();
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const launch = calls.find((c) => c.args[0] === 'new-session');
expect(launch).toBeDefined();
@@ -113,7 +118,7 @@ describe('InProcessSessionSpawner.launch', () => {
},
});
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const inner = calls.find((c) => c.args[0] === 'new-session')!.args.at(-1)!;
const names = (parseTOML(profile) as { mcp_servers: Record<string, { env_vars: string[] }> })
@@ -132,7 +137,7 @@ describe('InProcessSessionSpawner.launch', () => {
it("writes a global-scope provider's hooks under the home before the pane starts", async () => {
const { spawner, calls } = makeSpawner({ spec: { ...SPEC, providerId: 'codex' } });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const config = JSON.parse(await readFile(join(HOME, '.codex/hooks.json'), 'utf8')) as {
hooks: Record<string, unknown[]>;
@@ -150,7 +155,7 @@ describe('InProcessSessionSpawner.launch', () => {
it("writes a workspace-scoped provider's hooks under the session's working dir", async () => {
const { spawner } = makeSpawner();
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
expect(await readFile(join(CWD, '.claude/settings.local.json'), 'utf8')).toContain('hooks');
});
@@ -163,7 +168,7 @@ describe('InProcessSessionSpawner.launch', () => {
it("installs a plugin-delivered provider's hooks under the session's working dir", async () => {
const { spawner, calls } = makeSpawner({ spec: { ...SPEC, providerId: 'opencode' } });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const dropped = await readFile(
join(CWD, '.opencode/plugins/switchdash-notifications.js'),
@@ -182,7 +187,7 @@ describe('InProcessSessionSpawner.launch', () => {
};
try {
const { spawner, calls } = makeSpawner();
- await expect(spawner.launch('room-x')).rejects.toThrow(/no hook root for scope/);
+ await expect(spawner.launch('room-x', null)).rejects.toThrow(/no hook root for scope/);
expect(calls.find((c) => c.args[0] === 'new-session')).toBeUndefined();
} finally {
pluginOverride.current = null;
@@ -191,13 +196,13 @@ describe('InProcessSessionSpawner.launch', () => {
it('reports a launched-but-not-yet-connected room live while its pane is up', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
await expect(spawner.isRoomLive('room-x')).resolves.toBe(true);
});
it('treats a launched room whose pane died as not live', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => false });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
await expect(spawner.isRoomLive('room-x')).resolves.toBe(false);
});
@@ -216,7 +221,7 @@ describe('InProcessSessionSpawner.launch', () => {
describe('InProcessSessionSpawner.spawnedSessions', () => {
it('reports a launched session with its minted session id while its pane is live', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const spawned = spawner.spawnedSessions();
expect(spawned).toHaveLength(1);
expect(spawned[0]!.roomId).toBe('room-x');
@@ -225,7 +230,7 @@ describe('InProcessSessionSpawner.spawnedSessions', () => {
it('omits a launched session whose pane has died (no ghost row)', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => false });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
expect(spawner.spawnedSessions()).toEqual([]);
});
});
@@ -238,7 +243,7 @@ describe('InProcessSessionSpawner.setSpec', () => {
command: '/usr/bin/other-cli',
args: ['--session-id', SESSION_ID_PLACEHOLDER, '--no-skip', INITIAL_PROMPT_PLACEHOLDER],
});
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const inner = calls.find((c) => c.args[0] === 'new-session')!.args.at(-1)!;
expect(inner).toContain('/usr/bin/other-cli');
@@ -250,7 +255,7 @@ describe('InProcessSessionSpawner.setSpec', () => {
describe('InProcessSessionSpawner.roomIdForSession', () => {
it('returns the room a launched session was started for, or null', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const sessionId = spawner.spawnedSessions()[0]!.sessionId;
expect(spawner.roomIdForSession(sessionId)).toBe('room-x');
@@ -261,7 +266,7 @@ describe('InProcessSessionSpawner.roomIdForSession', () => {
describe('InProcessSessionSpawner.drop', () => {
it('forgets a launched session by its session id', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
const convId = spawner.spawnedSessions()[0]!.sessionId;
spawner.drop(convId);
@@ -273,7 +278,7 @@ describe('InProcessSessionSpawner.drop', () => {
it('is a no-op for an unknown session id', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
- await spawner.launch('room-x');
+ await spawner.launch('room-x', null);
spawner.drop('not-a-real-conv');
@@ -291,7 +296,7 @@ describe('InProcessSessionSpawner.drop', () => {
};
const { spawner } = makeSpawner({ isPaneLive: () => true, runtime });
- await spawner.launch('room-a');
+ await spawner.launch('room-a', null);
const sessionId = spawner.spawnedSessions()[0]!.sessionId;
// Connects to the room it was started for: still covered.
@@ -305,3 +310,77 @@ describe('InProcessSessionSpawner.drop', () => {
await expect(spawner.isRoomLive('room-a')).resolves.toBe(false);
});
});
+
+describe('InProcessSessionSpawner startup prompts', () => {
+ /** A cwd of its own, so one test's trust entry is not another's. */
+ async function freshCwd(): Promise<string> {
+ return mkdtemp(join(tmpdir(), 'session-spawner-trust-'));
+ }
+
+ async function claudeConfig(): Promise<Record<string, unknown>> {
+ return JSON.parse(await readFile(join(HOME, '.claude.json'), 'utf8'));
+ }
+
+ it('trusts the working directory on this VM before spawning into it', async () => {
+ const cwd = await freshCwd();
+ const { spawner } = makeSpawner({ spec: { ...SPEC, cwd } });
+
+ await spawner.launch('room-trust', null);
+
+ // The desktop cannot do this: the file belongs to the machine the session
+ // runs on, and that is this one.
+ expect(((await claudeConfig()).projects as Record<string, unknown>)[cwd]).toEqual({
+ hasTrustDialogAccepted: true,
+ hasCompletedProjectOnboarding: true,
+ });
+ });
+
+ it('honours the auto-trust setting carried in the launch spec', async () => {
+ const cwd = await freshCwd();
+ const { spawner } = makeSpawner({
+ spec: { ...SPEC, cwd, autoTrustWorktrees: false },
+ });
+
+ await spawner.launch('room-untrusted', null);
+
+ expect((await claudeConfig()).projects).not.toHaveProperty(cwd);
+ });
+
+ it('accepts the bypass warning only for an agent launched with auto-approve', async () => {
+ // Shares a file with the installed hooks, so read the key rather than the
+ // file's existence — and check the hooks survived the merge.
+ const localSettings = async (cwd: string): Promise<Record<string, unknown>> =>
+ JSON.parse(await readFile(join(cwd, '.claude/settings.local.json'), 'utf8'));
+
+ const plain = await freshCwd();
+ await makeSpawner({ spec: { ...SPEC, cwd: plain } }).spawner.launch('room-plain', null);
+ expect(await localSettings(plain)).not.toHaveProperty('skipDangerousModePermissionPrompt');
+
+ const bypassing = await freshCwd();
+ await makeSpawner({
+ spec: { ...SPEC, cwd: bypassing, autoApprove: true },
+ }).spawner.launch('room-bypass', null);
+
+ // Scoped to this agent's directory, not the VM's global Claude settings —
+ // one agent's toggle must not waive the warning for every other session on
+ // the host.
+ const accepted = await localSettings(bypassing);
+ expect(accepted.skipDangerousModePermissionPrompt).toBe(true);
+ expect(accepted.hooks).toBeDefined();
+ });
+
+ it('starts watching for the session to report that it is up', async () => {
+ const cwd = await freshCwd();
+ const startupWatch = new SessionStartupWatch(45_000, { warn: vi.fn(), error: vi.fn() });
+ const { spawner } = makeSpawner({ spec: { ...SPEC, cwd }, startupWatch });
+
+ await spawner.launch('room-watch', null);
+
+ const ptyId = makePtyId('claude', spawner.spawnedSessions()[0].sessionId);
+ // Nothing may be typed into the pane yet: it could be showing a prompt.
+ expect(startupWatch.blocksInjection(ptyId)).toBe(true);
+
+ startupWatch.markStarted(ptyId);
+ expect(startupWatch.blocksInjection(ptyId)).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
index 602321f33..0b82db9a9 100644
--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts
@@ -4,9 +4,12 @@ import { mkdir } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { promisify } from 'node:util';
+import { createDirTrustService } from '@main/core/agent-hooks/dir-trust';
+import type { SessionStartupWatch } from '@main/core/agent-runtime/session-startup-watch';
import { createPluginFs } from '@main/core/providers/plugin-fs';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { quoteShellArg } from '@main/utils/shellEscape';
+import { asAgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';
import { asPtyProviderId, makePtyId } from '@shared/core/pty/ptyId';
import {
@@ -20,6 +23,44 @@ import { makeAgentTmuxSessionName } from './vm-tmux';
const execFileAsync = promisify(execFile);
+/**
+ * Answer the CLI's own first-run prompts for a spec's directory — workspace
+ * trust, and the confirmation a bypass-permissions launch provokes.
+ *
+ * Has to happen on this machine: the entries go in config files belonging to
+ * the host the session runs on, and writing them on the desktop only clears the
+ * prompts on the wrong computer.
+ *
+ * Run at sidecar startup as well as per spawn, because a session started from
+ * Switch Console over SSH never passes through the spawner — the desktop opens
+ * the pane itself. The sidecar is launched before that pane exists, so doing it
+ * at boot is what covers both ways a session reaches this host.
+ *
+ * Best-effort by design (the writers log and continue): an unwritable config is
+ * not a reason to refuse a session that may well come up fine, and the startup
+ * watch reports it if it does not.
+ */
+export async function clearStartupPromptsFor(
+ spec: AgentLaunchSpec,
+ log: WatcherLogger
+): Promise<void> {
+ await createDirTrustService({
+ getSessionSettings: async () => ({ autoTrustWorktrees: spec.autoTrustWorktrees }),
+ log,
+ }).maybeAutoTrustLocal({
+ providerId: asAgentProviderId(spec.providerId),
+ cwd: spec.cwd,
+ homedir: homedir(),
+ force: spec.autoApprove,
+ });
+}
+
+/** Whether this provider fires a hook when its session comes up. */
+function reportsSessionStart(providerId: string): boolean {
+ const hooks = getPlugin(providerId).capabilities.hooks;
+ return hooks.kind !== 'none' && hooks.reportsSessionStart;
+}
+
/** The runtime slice the spawner needs to tell whether a room is already served. */
export interface RoomLivenessSource {
hasLiveRoom(roomId: string): boolean;
@@ -55,6 +96,8 @@ export interface InProcessSessionSpawnerDeps {
/** Whether a given tmux target is currently live (poller-backed cache). */
isPaneLive: (tmuxTarget: string) => boolean;
log: WatcherLogger;
+ /** Shared with the runtime, which receives the sessions' reports. */
+ startupWatch: SessionStartupWatch;
/** Run a command on the VM. Injected so tests can drive it without a real host. */
exec?: (command: string, args: string[]) => Promise<{ stdout: string; stderr: string }>;
}
@@ -71,7 +114,10 @@ export class InProcessSessionSpawner implements SessionSpawner {
args: string[]
) => Promise<{ stdout: string; stderr: string }>;
/** Room id → the session we launched for it (its minted id + tmux target). */
- private readonly launched = new Map<string, { sessionId: string; tmuxTarget: string }>();
+ private readonly launched = new Map<
+ string,
+ { sessionId: string; tmuxTarget: string; requesterName: string | null }
+ >();
/** The live launch recipe. Seeded from deps, replaceable via `setSpec` so a
* bypass-permissions toggle takes effect without restarting the sidecar. */
private spec: AgentLaunchSpec;
@@ -115,10 +161,21 @@ export class InProcessSessionSpawner implements SessionSpawner {
}
}
- /** The room a launched (not-yet-connected) session was started for, or null. */
+ /** The room a launched session was started for, or null if we did not start it. */
roomIdForSession(sessionId: string): string | null {
+ return this.launchedFor(sessionId)?.roomId ?? null;
+ }
+
+ /**
+ * The room a launched session was started for and who is waiting on it, so a
+ * session that never comes up can be reported to the person rather than only
+ * into the channel. Null if this sidecar did not start it.
+ */
+ launchedFor(sessionId: string): { roomId: string; requesterName: string | null } | null {
for (const [roomId, session] of this.launched) {
- if (session.sessionId === sessionId) return roomId;
+ if (session.sessionId === sessionId) {
+ return { roomId, requesterName: session.requesterName };
+ }
}
return null;
}
@@ -156,7 +213,7 @@ export class InProcessSessionSpawner implements SessionSpawner {
return false;
}
- async launch(roomId: string, startCursor?: number): Promise<void> {
+ async launch(roomId: string, requesterName: string | null, startCursor?: number): Promise<void> {
const { hookPort, hookToken, endpointFile, log } = this.deps;
const spec = this.spec;
const sessionId = randomUUID();
@@ -170,13 +227,15 @@ export class InProcessSessionSpawner implements SessionSpawner {
const connectionId =
this.deps.openConnectionFor?.(sessionId, spec.providerId, roomId, startCursor) ?? null;
+ // The spec is JSON off the host's disk, so its provider id is only a
+ // string until something checks it.
+ const ptyId = makePtyId(asPtyProviderId(spec.providerId), sessionId);
+
const hookEnv = {
...this.deps.switchEnv,
...buildAgentHookEnv({
port: hookPort,
- // The spec is JSON off the host's disk, so its provider id is only a
- // string until something checks it.
- ptyId: makePtyId(asPtyProviderId(spec.providerId), sessionId),
+ ptyId,
token: hookToken,
endpointFile,
}),
@@ -191,8 +250,15 @@ export class InProcessSessionSpawner implements SessionSpawner {
await this.writeLaunchFiles();
await this.installHooks();
+ await this.clearStartupPrompts();
+ // Armed only for a session this sidecar is spawning right now, so an
+ // adopted or already-running pane is never held mute waiting for a report
+ // that was never expected of it.
+ if (reportsSessionStart(spec.providerId)) {
+ this.deps.startupWatch.begin({ ptyId, sessionId, providerId: spec.providerId });
+ }
await this.startDetachedTmux(tmuxTarget, spec.cwd, command.env, command.command, command.args);
- this.launched.set(roomId, { sessionId, tmuxTarget });
+ this.launched.set(roomId, { sessionId, tmuxTarget, requesterName });
log.info('InProcessSessionSpawner: launched session for room', {
roomId,
sessionId,
@@ -216,6 +282,10 @@ export class InProcessSessionSpawner implements SessionSpawner {
}
}
+ private async clearStartupPrompts(): Promise<void> {
+ await clearStartupPromptsFor(this.spec, this.deps.log);
+ }
+
/**
* Install the provider's agent hooks on this VM before spawning, mirroring
* what the desktop does for a session it starts itself. The pane is launched
diff --git a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts
index 6ab903858..bb8102cf9 100644
--- a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { RawHookRequest } from '@main/core/agent-hooks/hook-server';
+import { SessionStartupWatch } from '@main/core/agent-runtime/session-startup-watch';
import type { RoomConnectionDeps } from '@main/core/switch-rooms/room-connection';
import { makePtyId } from '@shared/core/pty/ptyId';
import {
@@ -60,6 +61,11 @@ function fakeRegistry(): SessionRegistry & { entries: () => SidecarSessionEntry[
};
}
+/** A watch nothing has armed — every session reads as "not being watched". */
+function makeStartupWatch(): SessionStartupWatch {
+ return new SessionStartupWatch(45_000, { warn: vi.fn(), error: vi.fn() });
+}
+
function makeRuntime() {
const created: Array<{ deps: RoomConnectionDeps; conn: ManagedConnection }> = [];
const factory: RoomConnectionFactory = (deps) => {
@@ -76,6 +82,7 @@ function makeRuntime() {
log: silentLog,
createConnection: factory,
registry,
+ startupWatch: makeStartupWatch(),
});
return { runtime, created, registry };
}
@@ -287,6 +294,7 @@ describe('SidecarRuntime (multi-session)', () => {
log: silentLog,
createConnection: factory,
registry: fakeRegistry(),
+ startupWatch: makeStartupWatch(),
});
await runtime.handleHook(switchRoomHook('room-1', PTY_A));
expect(runtime.connectedSessions()).toHaveLength(1);
@@ -372,3 +380,69 @@ describe('SidecarRuntime (multi-session)', () => {
expect(runtime.connectedSessions()).toHaveLength(1);
});
});
+
+describe('SidecarRuntime startup gate', () => {
+ /** Build a runtime whose watch is already armed for one spawned session. */
+ function armed() {
+ const created: Array<{ deps: RoomConnectionDeps; conn: ManagedConnection }> = [];
+ const startupWatch = new SessionStartupWatch(45_000, { warn: vi.fn(), error: vi.fn() });
+ const runtime = new SidecarRuntime({
+ creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },
+ deeplinkScheme: 'switchdash',
+ tmuxRun: vi.fn(),
+ isPaneLive: () => true,
+ log: silentLog,
+ createConnection: (deps) => {
+ const conn = fakeConnection();
+ created.push({ deps, conn });
+ return conn;
+ },
+ registry: fakeRegistry(),
+ startupWatch,
+ });
+ const ptyId = makePtyId('codex', 'session-a');
+ startupWatch.begin({ ptyId, sessionId: 'session-a', providerId: 'codex' });
+ runtime.ensureForSession('session-a', 'codex', 'room-1');
+ return { runtime, sink: created[0].deps.sink, ptyId };
+ }
+
+ it('holds the pane shut until the spawned session reports that it started', () => {
+ const { sink } = armed();
+
+ // The pane is live, but a live pane is not a ready session: it may be
+ // showing a trust prompt, and a room message typed there answers it.
+ expect(sink.acquire()).toBeNull();
+ });
+
+ it('opens the pane as soon as any hook arrives from it', async () => {
+ const { runtime, sink, ptyId } = armed();
+
+ await runtime.handleHook({ ptyId, type: 'stop', body: '{}' });
+
+ expect(sink.acquire()).not.toBeNull();
+ });
+
+ it('never gates a session it did not spawn', () => {
+ const created: Array<{ deps: RoomConnectionDeps; conn: ManagedConnection }> = [];
+ const runtime = new SidecarRuntime({
+ creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },
+ deeplinkScheme: 'switchdash',
+ tmuxRun: vi.fn(),
+ isPaneLive: () => true,
+ log: silentLog,
+ createConnection: (deps) => {
+ const conn = fakeConnection();
+ created.push({ deps, conn });
+ return conn;
+ },
+ registry: fakeRegistry(),
+ startupWatch: makeStartupWatch(),
+ });
+
+ runtime.ensureForSession('session-adopted', 'codex', 'room-1');
+
+ // An adopted or already-running pane will never announce a start, so
+ // waiting for one would leave it mute for the rest of its life.
+ expect(created[0].deps.sink.acquire()).not.toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts
index ea6814fef..7d639d59e 100644
--- a/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/sidecar-runtime.ts
@@ -4,6 +4,7 @@ import { deriveAgentStatus } from '@main/core/agent-hooks/derive-agent-status';
import type { ContextResolver, ParsedHookEvent } from '@main/core/agent-hooks/event-enricher';
import { parseHookEvent } from '@main/core/agent-hooks/event-enricher';
import type { RawHookRequest } from '@main/core/agent-hooks/hook-server';
+import type { SessionStartupWatch } from '@main/core/agent-runtime/session-startup-watch';
import { PluginPromptInjector } from '@main/core/switch-rooms/plugin-prompt-injector';
import {
RoomConnection,
@@ -14,7 +15,7 @@ import {
import { sessionConnectionId } from '@main/core/switch-rooms/session-connection-id';
import { resolveSessionControl } from '@main/core/switch-rooms/session-control';
import { type TmuxRun, TmuxInjectionSink } from '@main/core/switch-rooms/tmux-injection-sink';
-import { parsePtyId } from '@shared/core/pty/ptyId';
+import { asPtyProviderId, makePtyId, parsePtyId } from '@shared/core/pty/ptyId';
import { makeAgentTmuxSessionName } from './vm-tmux';
/** A live per-room connection — the slice of RoomConnection the runtime drives. */
@@ -47,6 +48,14 @@ export interface SidecarRuntimeDeps {
* file so ownership survives a restart, rather than being rebuilt only as
* each session happens to post its next hook. */
registry: SessionRegistry;
+ /**
+ * Tracks which spawned sessions have reported that they are really running.
+ *
+ * Shared with the spawner, which arms it: the spawner knows a session is new,
+ * and this runtime is where the report arrives and where the pane is written
+ * to, so both halves need the same view.
+ */
+ startupWatch: SessionStartupWatch;
}
/** The slice of the durable state store the runtime needs. */
@@ -129,6 +138,12 @@ export class SidecarRuntime {
/** Handle one raw hook callback from an agent CLI. Never throws. */
async handleHook(raw: RawHookRequest): Promise<void> {
+ // Any hook at all proves the CLI is past its startup prompts and running,
+ // so this is not narrowed to the session-start event: it is also the point
+ // where the pane stops being a place a security prompt might be showing,
+ // and room messages held back for that reason are released.
+ this.deps.startupWatch.markStarted(raw.ptyId);
+
// Every hook posted to THIS sidecar comes from a session it owns (the
// session's hook env points here), so record its session id. This is
// how `/sessions` scopes the VM-wide tmux enumeration to this agent's own
@@ -258,8 +273,17 @@ export class SidecarRuntime {
connectionId,
startCursor,
sessionId,
- sink: new TmuxInjectionSink(tmuxTarget, this.deps.tmuxRun, () =>
- this.deps.isPaneLive(tmuxTarget)
+ // A live pane is not a ready session. Until one this sidecar spawned
+ // reports itself up, its pane may be showing a first-run trust or
+ // permissions prompt, and a room message typed there answers it — on
+ // Claude Code's bypass warning the default answer is "No, exit". A
+ // session with no watch (adopted, or already running) is not gated.
+ sink: new TmuxInjectionSink(
+ tmuxTarget,
+ this.deps.tmuxRun,
+ () =>
+ this.deps.isPaneLive(tmuxTarget) &&
+ !this.deps.startupWatch.blocksInjection(makePtyId(asPtyProviderId(providerId), sessionId))
),
injector: new PluginPromptInjector(providerId),
control: resolveSessionControl(providerId),
@@ -331,6 +355,24 @@ export class SidecarRuntime {
* poll + renew heartbeat that keeps the agent marked live) and forget it, so
* `/sessions` no longer reports it. Called when Switch Console deletes the session.
*/
+ /**
+ * Report a spawned session as waiting on a human because it never started.
+ *
+ * Goes through the session's runtime state rather than a posted message: the
+ * state report carries the session deeplink, and switch-core turns that into
+ * the clickable "Open in Switch Console" line addressed to the agent's owner.
+ * A `switchdash://` URL written into a message body gets no such treatment —
+ * only `deeplink_url` on the report is rewritten — so it arrives as dead text.
+ *
+ * No-op for a session with no connection yet, which is the common case when a
+ * pane dies before its first `connect_to_room`.
+ */
+ reportStartupStalled(sessionId: string): void {
+ this.sessions
+ .get(sessionId)
+ ?.connection.onAgentStatusChange('awaiting-input', 'startup_prompt');
+ }
+
stopSession(sessionId: string): void {
const session = this.sessions.get(sessionId);
if (!session) return;
diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts b/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts
index d6694f23d..e62c27b5a 100644
--- a/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts
+++ b/console/packages/core/src/agents/plugins/capabilities/hooks-types.ts
@@ -39,7 +39,8 @@ export type NotificationType =
| 'permission_prompt'
| 'idle_prompt'
| 'auth_success'
- | 'elicitation_dialog';
+ | 'elicitation_dialog'
+ | 'startup_prompt';
/**
* Normalised hook event produced by a plugin's parseHookEvent method.
diff --git a/console/packages/core/src/agents/plugins/capabilities/hooks.ts b/console/packages/core/src/agents/plugins/capabilities/hooks.ts
index 2d8c42305..fa0838fd9 100644
--- a/console/packages/core/src/agents/plugins/capabilities/hooks.ts
+++ b/console/packages/core/src/agents/plugins/capabilities/hooks.ts
@@ -56,6 +56,15 @@ export const hooksCapability = definePluginCapability<IHooksBehavior>()(
'subagent-done',
])
),
+ /**
+ * Whether the agent fires a hook when its session comes up, before any
+ * turn. That signal is what tells Switch Console a spawned session is
+ * really running rather than parked on a first-run prompt it has nobody
+ * to answer; without it a stalled session is indistinguishable from a
+ * working one. Only set this where the hook has been observed firing on
+ * a real spawn.
+ */
+ reportsSessionStart: z.boolean(),
}),
z.object({
kind: z.literal('plugin'),
@@ -73,6 +82,15 @@ export const hooksCapability = definePluginCapability<IHooksBehavior>()(
'subagent-done',
])
),
+ /**
+ * Whether the agent fires a hook when its session comes up, before any
+ * turn. That signal is what tells Switch Console a spawned session is
+ * really running rather than parked on a first-run prompt it has nobody
+ * to answer; without it a stalled session is indistinguishable from a
+ * working one. Only set this where the hook has been observed firing on
+ * a real spawn.
+ */
+ reportsSessionStart: z.boolean(),
}),
z.object({ kind: z.literal('none') }),
])
diff --git a/console/packages/plugins/src/agents/impl/amp/index.ts b/console/packages/plugins/src/agents/impl/amp/index.ts
index a198935e3..77c2b2eef 100644
--- a/console/packages/plugins/src/agents/impl/amp/index.ts
+++ b/console/packages/plugins/src/agents/impl/amp/index.ts
@@ -29,6 +29,7 @@ export const plugin = definePlugin(
kind: 'plugin',
scope: 'workspace',
supportedEvents: ['start', 'stop'],
+ reportsSessionStart: false,
},
hostDependency: npmDependency({
id: 'amp',
diff --git a/console/packages/plugins/src/agents/impl/claude/hooks.ts b/console/packages/plugins/src/agents/impl/claude/hooks.ts
index b7c3c28ff..6afbe0ef2 100644
--- a/console/packages/plugins/src/agents/impl/claude/hooks.ts
+++ b/console/packages/plugins/src/agents/impl/claude/hooks.ts
@@ -151,6 +151,13 @@ function parseClaudeHookEvent(
export function buildClaudeHookConfig() {
return {
...buildNestedJsonHookConfig(CLAUDE_SETTINGS_PATH, [
+ // Fires once the session is up, before any turn. Until this arrives a
+ // spawned session may still be parked on a startup prompt (trust,
+ // first-run setup, the bypass warning) with nobody to answer it, and
+ // UserPromptSubmit cannot tell the difference — it never fires either
+ // way. Also captures the provider session id at start rather than at the
+ // first prompt.
+ { hookKey: 'SessionStart', command: makeStdinHookCommand('session-start') },
{ hookKey: 'UserPromptSubmit', command: makeStdinHookCommand('start') },
{ hookKey: 'Notification', command: makeStdinHookCommand('notification') },
{ hookKey: 'Stop', command: makeStdinHookCommand('stop') },
diff --git a/console/packages/plugins/src/agents/impl/claude/index.ts b/console/packages/plugins/src/agents/impl/claude/index.ts
index 3fb5bb248..b9af0d483 100644
--- a/console/packages/plugins/src/agents/impl/claude/index.ts
+++ b/console/packages/plugins/src/agents/impl/claude/index.ts
@@ -28,6 +28,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: [
+ 'session',
'start',
'notification',
'stop',
@@ -37,6 +38,7 @@ export const plugin = definePlugin(
'subagent',
'subagent-done',
],
+ reportsSessionStart: true,
},
hostDependency: {
id: 'claude',
diff --git a/console/packages/plugins/src/agents/impl/codex/index.ts b/console/packages/plugins/src/agents/impl/codex/index.ts
index df5fe5c77..b267ccde3 100644
--- a/console/packages/plugins/src/agents/impl/codex/index.ts
+++ b/console/packages/plugins/src/agents/impl/codex/index.ts
@@ -91,6 +91,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'global',
supportedEvents: ['notification', 'stop', 'session', 'tool-use', 'tool-done'],
+ reportsSessionStart: true,
},
hostDependency: codexHostDependency(),
mcp: {
diff --git a/console/packages/plugins/src/agents/impl/copilot/index.ts b/console/packages/plugins/src/agents/impl/copilot/index.ts
index e8835ba71..abbe54e08 100644
--- a/console/packages/plugins/src/agents/impl/copilot/index.ts
+++ b/console/packages/plugins/src/agents/impl/copilot/index.ts
@@ -26,6 +26,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['stop', 'session', 'notification'],
+ reportsSessionStart: false,
},
hostDependency: npmDependency({ id: 'copilot', package: '@github/copilot' }),
mcp: {
diff --git a/console/packages/plugins/src/agents/impl/devin/index.ts b/console/packages/plugins/src/agents/impl/devin/index.ts
index d31f49701..838e81d17 100644
--- a/console/packages/plugins/src/agents/impl/devin/index.ts
+++ b/console/packages/plugins/src/agents/impl/devin/index.ts
@@ -22,6 +22,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['stop', 'notification'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'devin',
diff --git a/console/packages/plugins/src/agents/impl/droid/index.ts b/console/packages/plugins/src/agents/impl/droid/index.ts
index d9967bcbb..798500d3b 100644
--- a/console/packages/plugins/src/agents/impl/droid/index.ts
+++ b/console/packages/plugins/src/agents/impl/droid/index.ts
@@ -21,6 +21,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['notification', 'stop', 'session'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'droid',
diff --git a/console/packages/plugins/src/agents/impl/grok/index.ts b/console/packages/plugins/src/agents/impl/grok/index.ts
index f926df87e..ed3d4dcf9 100644
--- a/console/packages/plugins/src/agents/impl/grok/index.ts
+++ b/console/packages/plugins/src/agents/impl/grok/index.ts
@@ -22,6 +22,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'global',
supportedEvents: ['notification', 'stop', 'session', 'start'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'grok',
diff --git a/console/packages/plugins/src/agents/impl/kilocode/index.ts b/console/packages/plugins/src/agents/impl/kilocode/index.ts
index 694c068d1..e8513a9c5 100644
--- a/console/packages/plugins/src/agents/impl/kilocode/index.ts
+++ b/console/packages/plugins/src/agents/impl/kilocode/index.ts
@@ -28,6 +28,7 @@ export const plugin = definePlugin(
kind: 'plugin',
scope: 'workspace',
supportedEvents: ['notification', 'stop', 'session'],
+ reportsSessionStart: false,
},
hostDependency: npmDependency({
id: 'kilocode',
diff --git a/console/packages/plugins/src/agents/impl/kimi/index.ts b/console/packages/plugins/src/agents/impl/kimi/index.ts
index b33f95c50..cc22c40f9 100644
--- a/console/packages/plugins/src/agents/impl/kimi/index.ts
+++ b/console/packages/plugins/src/agents/impl/kimi/index.ts
@@ -53,6 +53,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'global',
supportedEvents: ['notification', 'stop', 'session', 'start'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'kimi',
diff --git a/console/packages/plugins/src/agents/impl/kiro/index.ts b/console/packages/plugins/src/agents/impl/kiro/index.ts
index 65268de3e..58087f551 100644
--- a/console/packages/plugins/src/agents/impl/kiro/index.ts
+++ b/console/packages/plugins/src/agents/impl/kiro/index.ts
@@ -22,6 +22,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['session', 'start', 'stop'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'kiro',
diff --git a/console/packages/plugins/src/agents/impl/mistral/index.ts b/console/packages/plugins/src/agents/impl/mistral/index.ts
index ece32ba51..af3fb46d8 100644
--- a/console/packages/plugins/src/agents/impl/mistral/index.ts
+++ b/console/packages/plugins/src/agents/impl/mistral/index.ts
@@ -22,6 +22,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['notification', 'stop'],
+ reportsSessionStart: false,
},
hostDependency: {
id: 'mistral',
diff --git a/console/packages/plugins/src/agents/impl/opencode/index.ts b/console/packages/plugins/src/agents/impl/opencode/index.ts
index 8c128f773..99df9c2a9 100644
--- a/console/packages/plugins/src/agents/impl/opencode/index.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/index.ts
@@ -76,6 +76,7 @@ export const plugin = definePlugin(
// No 'notification': the plugin reports real turn boundaries now, so
// nothing sends the idle_prompt that used to stand in for them.
supportedEvents: ['start', 'stop', 'session', 'tool-use', 'tool-done'],
+ reportsSessionStart: false,
},
hostDependency: OPENCODE_HOST_DEPENDENCY,
mcp: {
diff --git a/console/packages/plugins/src/agents/impl/pi/index.ts b/console/packages/plugins/src/agents/impl/pi/index.ts
index fa2af3bba..023d56ca0 100644
--- a/console/packages/plugins/src/agents/impl/pi/index.ts
+++ b/console/packages/plugins/src/agents/impl/pi/index.ts
@@ -28,6 +28,7 @@ export const plugin = definePlugin(
kind: 'plugin',
scope: 'workspace',
supportedEvents: ['stop'],
+ reportsSessionStart: false,
},
hostDependency: npmDependency({
id: 'pi',
diff --git a/console/packages/plugins/src/agents/impl/qwen/index.ts b/console/packages/plugins/src/agents/impl/qwen/index.ts
index 641951108..380031324 100644
--- a/console/packages/plugins/src/agents/impl/qwen/index.ts
+++ b/console/packages/plugins/src/agents/impl/qwen/index.ts
@@ -26,6 +26,7 @@ export const plugin = definePlugin(
kind: 'config',
scope: 'workspace',
supportedEvents: ['notification', 'stop'],
+ reportsSessionStart: false,
},
hostDependency: npmDependency({ id: 'qwen', package: '@qwen-code/qwen-code' }),
mcp: {