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): always auto-start sessions, read-only agent page, reliable startup (#592)

Louis Amaudruz06aae48a2221
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 210595e29..8b210c6ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1357,6 +1357,25 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Changed
+- **Every agent starts a session when it is addressed; the "Auto-create a
+ session on notify" setting is gone.** Its switch is removed from the agent
+ page and the create form, and new agents register as `auto_session`.
+- **Opening an agent's page only reads.** Reading the auto-session setting used
+ to re-launch the agent's controller as a side effect, which on a remote host
+ uploaded the sidecar bundle and replaced an outdated sidecar, and checking a
+ provider's sign-in or models uploaded the bundle too. The provider check now
+ uses the bundle already on the host, and says so when there is none. The
+ bundle is uploaded only when an agent is started, restarted or updated.
+
+#### Fixed
+- **Agents come up after Console starts without their page being opened.**
+ Console now brings each host's agents up side by side, so a slow or wedged
+ SSH connection holds back only that host, never local agents or other hosts,
+ and it keeps retrying an agent whose controller could not start, backing off
+ from 30 seconds to 5 minutes. Before, an agent that failed once stayed off
+ until its host reconnected or its page was opened.
+
### [0.37.3] - 2026-09-29
#### Changed
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
index 9ba1d1f1a..9373e7865 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts
@@ -5,6 +5,7 @@ import { locationManager } from '@main/core/locations/location-manager';
import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation, getLocationByHostDir } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
+import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
import { getServer } from '@main/core/switch-servers/servers-store';
import { agentTypeOf } from '@main/core/telemetry/agent-type';
import type { TelemetryAgentCreateFailure } from '@main/core/telemetry/events';
@@ -12,7 +13,6 @@ import { entryPointOf } from '@main/core/telemetry/narrow';
import { trackEvent } from '@main/core/telemetry/telemetry-service';
import { db } from '@main/db/client';
import { agents as agentsTable } from '@main/db/schema';
-import { log } from '@main/lib/logger';
import { agentAvatarUrlForName } from '@shared/core/agents/agent-avatar';
import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
@@ -36,7 +36,6 @@ import { acknowledgeDefinition } from './import-agent-config';
import { knownAgentTypeForProvider } from './known-agent-type';
import { registerAgentIdentity } from './register-agent-identity';
import { inspectRemoteDir } from './remote-dir';
-import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';
import { writeNeutralAgentSettingsFs } from './write-switch-settings';
export type AddAgentParams = {
@@ -60,7 +59,6 @@ export type AddAgentParams = {
/** The icon picked in the create form. Null means the form offered no
* choice, and the agent is registered with the avatar its name generates. */
iconUrl: string | null;
- autoSession: boolean;
autoApprove: boolean;
/** The agent's system prompt, provider-agnostic. Rendered into whatever the
* provider reads — a Claude Code subagent body, Codex's developer
@@ -261,7 +259,6 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
description: params.description,
displayName: params.displayName,
repoDir: params.dir,
- autoSession: params.autoSession,
agentType: knownAgentTypeForProvider(params.providerId),
iconUrl: params.iconUrl ?? agentAvatarUrlForName(params.name),
});
@@ -321,15 +318,9 @@ async function runAddAgent(params: AddAgentParams): Promise<AddAgentResult> {
providerConfig: params.providerConfig ?? null,
});
- // Seed the local auto_session mirror + watcher from the gateway profile so an
- // agent registered with auto_session on starts watching now, without an
- // off→on toggle. Best-effort: a gateway hiccup must not fail creation.
- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {
- log.warn('addAgent: failed to reconcile auto_session for new agent', {
- agentId: agent.id,
- error: String(error),
- });
- });
+ // Creating the agent is the ask for its controller. It does not fail
+ // creation when the controller cannot come up yet; it is retried.
+ await autoSessionWatcher.bringUp(agent.id, 'explicit');
await locationManager.openLocation(location);
agentEvents._emit('agent:created', agent, params.entryPoint);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts
index 5f359cb4c..f0e5a9694 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts
@@ -12,7 +12,6 @@ const ensureRemoteWatcher = vi.hoisted(() => vi.fn(async (_agentId: string) => {
const state = vi.hoisted(() => ({
providerId: 'codex',
providerConfig: null as unknown,
- autoSession: [] as string[],
files: new Map<string, string>(),
writes: [] as string[],
}));
@@ -56,9 +55,6 @@ vi.mock('./remote-watcher', () => ({
vi.mock('@main/lib/logger', () => ({
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));
-vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
- listAutoSessionAgentIds: async () => state.autoSession,
-}));
vi.mock('@main/core/providers/plugin-registry', () => ({
getPlugin: (id: string) => ({
behavior:
@@ -83,7 +79,6 @@ beforeEach(() => {
ensureRemoteWatcher.mockClear();
state.files.clear();
state.writes = [];
- state.autoSession = [];
state.providerId = 'codex';
state.providerConfig = null;
state.files.set(CONFIG_PATH, '{}\n');
@@ -214,21 +209,12 @@ describe('saving', () => {
// Claude Code gets its definition in the launch spec now, so an automatic
// session would otherwise start on the previous one.
state.providerId = 'claude';
- state.autoSession = ['agent-1'];
await setAgentSettings({ agentId: 'agent-1', settings: { model: 'opus' } });
expect(ensureRemoteWatcher).toHaveBeenCalledWith('agent-1');
expect(setAgentProviderConfig).not.toHaveBeenCalled();
});
-
- it('leaves the controller alone when automatic sessions are off', async () => {
- state.providerId = 'claude';
-
- await setAgentSettings({ agentId: 'agent-1', settings: { model: 'opus' } });
-
- expect(ensureRemoteWatcher).not.toHaveBeenCalled();
- });
});
describe('launching', () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
index c3ecd069d..eef9dfdb1 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts
@@ -1,6 +1,5 @@
import type { RepoAgentAttributes } from '@switch-console/core/agents/plugins';
import { getPlugin } from '@main/core/providers/plugin-registry';
-import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
import { providerConfigFromAttributes } from '@shared/core/agents/agent-provider-config';
import type { AgentConfigFile } from './agent-config-file';
import { writeAgentConfigFile, type AgentTemplateOrigin } from './agent-config-file';
@@ -109,6 +108,5 @@ async function propagateToLaunch(agentId: string, config: AgentConfigFile): Prom
return;
}
- if (!(await listAutoSessionAgentIds()).includes(agentId)) return;
await ensureRemoteWatcher(agentId);
}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts
new file mode 100644
index 000000000..f6a7cdd8b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ locate: vi.fn(),
+ deploy: vi.fn(),
+ exec: vi.fn(),
+ dispose: vi.fn(),
+}));
+
+vi.mock('@main/core/sdk-host/shared-host-deployment', () => ({
+ locateSharedHost: mocks.locate,
+ deploySharedHost: mocks.deploy,
+}));
+vi.mock('@main/core/agent-runtime/impl/resolve-agent-executable', () => ({
+ resolveAgentExecutable: async () => '/usr/bin/claude',
+}));
+vi.mock('@switch-console/core/deps/runtime', () => ({
+ resolveCommandPath: async () => '/usr/bin/claude',
+}));
+vi.mock('@main/core/providers/plugin-registry', () => ({
+ getPlugin: () => ({
+ metadata: { name: 'Claude Code' },
+ capabilities: { hostDependency: { binaryNames: ['claude'] } },
+ }),
+}));
+vi.mock('@main/core/dependencies/host-dependency-store', () => ({ hostDependencyStore: {} }));
+vi.mock('@main/core/dependencies/dependency-managers', () => ({
+ localDependencyManager: { get: () => undefined },
+}));
+vi.mock('@main/core/ssh/connect/connect-agent-ssh', () => ({ ensureSshConnected: vi.fn() }));
+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({
+ SshExecutionContext: class {
+ dispose = vi.fn();
+ },
+}));
+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn() } }));
+
+const { getProviderReadiness } = await import('./agent-model-catalogue');
+
+const remote = { providerId: 'claude' as const, sshHost: 'builder', dir: '/work' };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.exec.mockResolvedValue({
+ stdout: JSON.stringify({ status: 'authenticated', message: 'Signed in', models: [] }),
+ });
+});
+
+it('checks a host with the bundle already there, and never deploys one', async () => {
+ mocks.locate.mockResolvedValue({
+ ctx: { exec: mocks.exec, dispose: mocks.dispose },
+ entrypoint: '/home/me/.local/state/switch/sdk-host/shared-host-a.mjs',
+ });
+
+ const readiness = await getProviderReadiness(remote, true);
+
+ expect(readiness).toMatchObject({ installed: true, status: 'authenticated' });
+ expect(mocks.exec.mock.calls[0]?.[1]?.[0]).toBe(
+ '/home/me/.local/state/switch/sdk-host/shared-host-a.mjs'
+ );
+ expect(mocks.deploy).not.toHaveBeenCalled();
+ expect(mocks.dispose).toHaveBeenCalled();
+});
+
+it('says Switch is not set up on a host with no bundle, rather than deploying one', async () => {
+ mocks.locate.mockResolvedValue(null);
+
+ const readiness = await getProviderReadiness(remote, true);
+
+ expect(readiness).toMatchObject({ installed: true, status: 'unknown', models: [] });
+ expect(readiness.message).toContain('builder');
+ expect(mocks.deploy).not.toHaveBeenCalled();
+ expect(mocks.exec).not.toHaveBeenCalled();
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts
index 6b086dd1e..b27628b02 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts
@@ -11,7 +11,7 @@ import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-
import type { IExecutionContext } from '@main/core/execution-context/types';
import { locationTransport } from '@main/core/locations/location-transport';
import { getPlugin } from '@main/core/providers/plugin-registry';
-import { deploySharedHost } from '@main/core/sdk-host/shared-host-deployment';
+import { locateSharedHost } from '@main/core/sdk-host/shared-host-deployment';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
import { log } from '@main/lib/logger';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
@@ -171,7 +171,14 @@ export async function getProviderReadiness(
message: `${plugin.metadata.name} is not installed or its selected executable cannot be found.`,
models: [],
};
- const deployed = await deploySharedHost(transport, params.dir, 'provider-readiness', false);
+ const deployed = await locateSharedHost(transport, params.dir);
+ if (!deployed)
+ return {
+ installed: true,
+ status: 'unknown' as const,
+ message: `Switch is not set up on ${params.sshHost ?? 'this machine'} yet, so ${plugin.metadata.name} cannot be checked there. Start an agent on it, or press Update on one's Room watcher.`,
+ models: [],
+ };
try {
const { stdout } = await deployed.ctx.exec(
'node',
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
index e199ac243..bc7b30808 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.test.ts
@@ -108,8 +108,8 @@ vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () =>
vi.mock('@main/core/locations/location-manager', () => ({
locationManager: { openLocation: h.openLocation },
}));
-vi.mock('./setAgentAutoSession', () => ({
- reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),
+vi.mock('@main/core/switch-rooms/auto-session-watcher', () => ({
+ autoSessionWatcher: { bringUp: vi.fn(async () => {}) },
}));
vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));
vi.mock('./remote-watcher', () => ({ startRemoteDiscovery: vi.fn(async () => {}) }));
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
index 423b5c790..c094e007e 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/attach-configured-agents.ts
@@ -5,6 +5,7 @@ import { locationManager } from '@main/core/locations/location-manager';
import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
+import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
import { getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
@@ -19,7 +20,6 @@ import { resolveWorkspaceFsFor } from './agent-workspace-fs';
import { createAgent } from './createAgent';
import { discoverConfiguredAgents } from './discover-configured-agents';
import { importAgentConfig } from './import-agent-config';
-import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';
export type AttachConfiguredAgentsParams = {
sshHost: string | null;
@@ -170,12 +170,7 @@ export async function attachConfiguredAgents(
});
created.push(agent);
- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {
- log.warn('attachConfiguredAgents: failed to reconcile auto_session', {
- agentId: agent.id,
- error: String(error),
- });
- });
+ await autoSessionWatcher.bringUp(agent.id, 'explicit');
}
await locationManager.openLocation(location);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
index 952451f5c..cdfc29779 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
@@ -35,11 +35,6 @@ import type { RemoveLoadableAgentConfigParams } from './remove-loadable-agent-co
import { removeLoadableAgentConfig } from './remove-loadable-agent-config';
import { resetRemoteAgent } from './reset-remote-agent';
import { setAgentAutoApprove, type AgentAutoApproveParams } from './setAgentAutoApprove';
-import {
- getAgentAutoSession,
- setAgentAutoSession,
- type AgentAutoSessionParams,
-} from './setAgentAutoSession';
export const agentsController = createRPCController({
addAgent: (params: AddAgentParams) => addAgent(params),
@@ -98,10 +93,6 @@ export const agentsController = createRPCController({
resetRemoteAgent: (params: { agentId: string }) => resetRemoteAgent(params.agentId),
assignServer: (params: { agentId: string; serverId: string }): Promise<AgentVerifyResult> =>
assignAgentServer(params),
- setAgentAutoSession: (params: AgentAutoSessionParams): Promise<void> =>
- setAgentAutoSession(params),
setAgentAutoApprove: (params: AgentAutoApproveParams): Promise<void> =>
setAgentAutoApprove(params),
- getAgentAutoSession: (params: { agentId: string }): Promise<boolean> =>
- getAgentAutoSession(params),
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
index 7bd7851a5..72eff6d91 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/deleteAgent.ts
@@ -2,10 +2,7 @@ import { eq } from 'drizzle-orm';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { discardControllerState } from '@main/core/sdk-host/shared-watcher';
import { sessionHooks } from '@main/core/sessions/session-hooks';
-import {
- setAutoSessionAgent,
- setControllerStopped,
-} from '@main/core/switch-rooms/auto-session-store';
+import { setControllerStopped } from '@main/core/switch-rooms/auto-session-store';
import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
import {
deleteAgent as gatewayDeleteAgent,
@@ -180,8 +177,7 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promise
* only when `deleteInSwitch` is set (the opt-in "also delete in Switch").
* 2. The agent's running sessions (runtime + view-state), which previously
* only the location-delete path handled.
- * 3. Its local controller and the state that controller left behind, plus the
- * local auto_session mirror. The controller caches the agent's Switch
+ * 3. Its local controller and the state that controller left behind. The controller caches the agent's Switch
* credentials in memory, so without an explicit stop it keeps heartbeating
* and answering rooms for an agent that no longer exists. A controller on a
* remote host is stopped and discarded only for a full cleanup — see 4.
@@ -281,7 +277,6 @@ async function removeAgent(
await discardControllerState(agentId);
}
- await setAutoSessionAgent(agentId, false);
await setControllerStopped(agentId, false);
if (agent && location && removeFiles) {
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
index 41ced4b9c..3438387da 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.test.ts
@@ -68,8 +68,8 @@ vi.mock('./createAgent', () => ({
createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input })),
}));
vi.mock('./agent-events', () => ({ agentEvents: { _emit: h.emit } }));
-vi.mock('./setAgentAutoSession', () => ({
- reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),
+vi.mock('@main/core/switch-rooms/auto-session-watcher', () => ({
+ autoSessionWatcher: { bringUp: vi.fn(async () => {}) },
}));
vi.mock('./write-switch-settings', () => ({ writeAgentNeutralSettings: vi.fn(async () => {}) }));
vi.mock('./agent-workspace-fs', () => ({
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
index 17057180d..e6641f9b2 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/onboard-agent.ts
@@ -4,6 +4,7 @@ import { locationManager } from '@main/core/locations/location-manager';
import { checkIsValidDirectory } from '@main/core/locations/path-utils';
import { ensureLocation } from '@main/core/locations/store';
import { getPlugin } from '@main/core/providers/plugin-registry';
+import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
import { readSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credentials';
import { agentExistsOnServer, GatewayError } from '@main/core/switch-servers/gateway-client';
import { getServer } from '@main/core/switch-servers/servers-store';
@@ -25,7 +26,6 @@ import { createAgent } from './createAgent';
import { detectSwitchAgent } from './detect';
import { detectSwitchAgentRemote } from './detect-remote';
import { importAgentConfig } from './import-agent-config';
-import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';
import { writeAgentNeutralSettings } from './write-switch-settings';
/**
@@ -247,16 +247,9 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA
}
}
- // Seed the local auto_session mirror + start the watcher from the gateway
- // profile so an agent registered with auto_session on starts watching now,
- // without the operator toggling it off→on (CHOO-1185). Best-effort: a gateway
- // hiccup must not fail onboarding — the settings panel reconciles later.
- await reconcileAgentAutoSessionFromGateway(agent.id).catch((error) => {
- log.warn('onboardAgent: failed to reconcile auto_session for new agent', {
- agentId: agent.id,
- error: String(error),
- });
- });
+ // Creating the agent is the ask for its controller. It does not fail
+ // onboarding when the controller cannot come up yet; it is retried.
+ await autoSessionWatcher.bringUp(agent.id, 'explicit');
await locationManager.openLocation(location);
agentEvents._emit('agent:created', agent, ONBOARD_ENTRY_POINT);
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
index af9dbc2ad..930fe9e78 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/register-agent-identity.ts
@@ -7,7 +7,6 @@ export type RegisterAgentInput = {
name: string;
description: string;
repoDir: string;
- autoSession?: boolean;
/** Gateway known-agent type; derive from the provider via
* `knownAgentTypeForProvider`. Required — an omitted type would silently
* register the agent as Claude Code whatever it actually runs (CHOO-1436). */
@@ -30,10 +29,10 @@ export type RegisterAgentInput = {
* repository-defined agent (CHOO-1440). Shared by the local and remote create
* flows so the option mapping stays identical.
*
- * Channels are always enabled: Switch Console keeps the agent's session live (and
- * auto-spawns one on notify), so it is session-addressable regardless of the
- * underlying model provider — there is no user-facing "how do you run Claude"
- * choice.
+ * Channels are always enabled and the agent is always `auto_session`: Switch
+ * Console keeps the agent's connection and starts a session whenever it is
+ * addressed, whatever the underlying model provider — there is no user-facing
+ * "how do you run Claude" choice, and no opting out of automatic sessions.
*/
export async function registerAgentIdentity(
server: SwitchServer,
@@ -49,7 +48,7 @@ export async function registerAgentIdentity(
options: {
channels_enabled: true,
repo_dir: input.repoDir,
- ...(input.autoSession ? { auto_session: true } : {}),
+ auto_session: true,
},
});
return { kind: 'created', id: registered.id, apiKey: registered.apiKey };
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts
index eb0447e12..59d0c5979 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.test.ts
@@ -13,7 +13,6 @@ const updateAgent = vi.hoisted(() =>
})
);
const getRemoteAgentLocation = vi.hoisted(() => vi.fn());
-const listAutoSessionAgentIds = vi.hoisted(() => vi.fn(async (): Promise<string[]> => []));
const listStoppedControllerAgentIds = vi.hoisted(() => vi.fn(async (): Promise<string[]> => []));
const pushRemoteAutoApprove = vi.hoisted(() =>
vi.fn(async (_id: string) => void calls.push('push'))
@@ -29,7 +28,6 @@ vi.mock('./getAgentById', () => ({ getAgentById: async () => agentRow.current })
vi.mock('./updateAgent', () => ({ updateAgent }));
vi.mock('./agent-location', () => ({ getRemoteAgentLocation }));
vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
- listAutoSessionAgentIds,
listStoppedControllerAgentIds,
}));
vi.mock('./remote-watcher', () => ({ pushRemoteAutoApprove }));
@@ -46,7 +44,6 @@ describe('setAgentAutoApprove', () => {
calls.length = 0;
agentRow.current = { id: 'agent-1', switchAgentId: 'sw-1', autoApprove: false };
getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1' });
- listAutoSessionAgentIds.mockResolvedValue([]);
listStoppedControllerAgentIds.mockResolvedValue([]);
});
@@ -61,7 +58,6 @@ describe('setAgentAutoApprove', () => {
it('keeps the choice on the host, then the row, then rewrites a watcher that starts sessions', async () => {
// The choice first, so a racing watcher write takes the new value instead
// of putting the old one back.
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
@@ -71,7 +67,6 @@ describe('setAgentAutoApprove', () => {
it('says the watcher lags when the push does not reach the host, keeping the saved choice', async () => {
// The host's choice already holds the new value; rolling the row back
// would let the next watcher write silently undo it.
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
pushRemoteAutoApprove.mockRejectedValueOnce(new Error('host unreachable'));
await expect(setAgentAutoApprove({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
@@ -83,7 +78,6 @@ describe('setAgentAutoApprove', () => {
});
it('changes nothing when the host could not take the choice', async () => {
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
keepAutoApproveChoice.mockRejectedValueOnce(new Error('host unreachable'));
await expect(setAgentAutoApprove({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
@@ -96,22 +90,13 @@ describe('setAgentAutoApprove', () => {
it('writes only the row for an agent with no Switch identity, which has no watcher yet', async () => {
agentRow.current = { id: 'agent-1', switchAgentId: null, autoApprove: false };
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
expect(calls).toEqual(['row true']);
});
- it('keeps the choice on the host first for a watcher that starts no sessions', async () => {
- await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
-
- expect(recordAutoApproveOnHost).toHaveBeenCalledWith('agent-1', true);
- expect(calls).toEqual(['host true', 'row true']);
- });
-
it('keeps the choice on the host for a stopped watcher, which nothing rewrites until it starts', async () => {
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
listStoppedControllerAgentIds.mockResolvedValue(['agent-1']);
await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
@@ -121,6 +106,7 @@ describe('setAgentAutoApprove', () => {
});
it('leaves the row alone when the host could not keep the choice', async () => {
+ listStoppedControllerAgentIds.mockResolvedValue(['agent-1']);
recordAutoApproveOnHost.mockRejectedValueOnce(new Error('host unreachable'));
await expect(setAgentAutoApprove({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
@@ -140,7 +126,6 @@ describe('setAgentAutoApprove', () => {
});
it('says why the watcher lags when the push failed with something other than an Error', async () => {
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
pushRemoteAutoApprove.mockRejectedValueOnce('ssh closed');
await expect(setAgentAutoApprove({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts
index 2bf5f9f91..5dfa70fb1 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoApprove.ts
@@ -1,8 +1,5 @@
import { keepAutoApproveChoice, recordAutoApproveOnHost } from '@main/core/sdk-host/shared-watcher';
-import {
- listAutoSessionAgentIds,
- listStoppedControllerAgentIds,
-} from '@main/core/switch-rooms/auto-session-store';
+import { listStoppedControllerAgentIds } from '@main/core/switch-rooms/auto-session-store';
import { getRemoteAgentLocation } from './agent-location';
import { getAgentById } from './getAgentById';
import { pushRemoteAutoApprove } from './remote-watcher';
@@ -30,11 +27,7 @@ export async function setAgentAutoApprove(params: AgentAutoApproveParams): Promi
await setRow(params.enabled);
return;
}
- const [spawning, stopped] = await Promise.all([
- listAutoSessionAgentIds(),
- listStoppedControllerAgentIds(),
- ]);
- if (!spawning.includes(agent.id) || stopped.includes(agent.id)) {
+ if ((await listStoppedControllerAgentIds()).includes(agent.id)) {
await recordAutoApproveOnHost(agent.id, params.enabled);
await setRow(params.enabled);
return;
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts
deleted file mode 100644
index 9d06c2d91..000000000
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.test.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import { beforeEach, expect, it, vi } from 'vitest';
-
-const h = vi.hoisted(() => {
- const calls: string[] = [];
- const state: { agent: Record<string, unknown> | null; sshHost: string | null } = {
- agent: null,
- sshHost: null,
- };
- return {
- calls,
- state,
- setAutoSession: vi.fn(async () => void calls.push('gateway')),
- setAutoSessionAgent: vi.fn(async () => void calls.push('mirror')),
- reconcile: vi.fn(async () => void calls.push('controller')),
- ensureRemoteWatcher: vi.fn(async () => void calls.push('controller')),
- };
-});
-
-vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
- listAutoSessionAgentIds: vi.fn(async () => []),
- setAutoSessionAgent: h.setAutoSessionAgent,
-}));
-vi.mock('@main/core/switch-rooms/auto-session-watcher', () => ({
- autoSessionWatcher: { reconcile: h.reconcile },
-}));
-vi.mock('@main/core/switch-servers/gateway-client', () => ({
- fetchAgentOptions: vi.fn(),
- setAutoSession: h.setAutoSession,
- GatewayError: class GatewayError extends Error {},
-}));
-vi.mock('@main/core/switch-servers/servers-store', () => ({
- getServer: vi.fn(async () => ({ id: 'server-1' })),
-}));
-vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
-vi.mock('./agent-location', () => ({ getRemoteAgentLocation: async () => h.state.sshHost }));
-vi.mock('./getAgentById', () => ({ getAgentById: async () => h.state.agent }));
-vi.mock('./remote-watcher', () => ({ ensureRemoteWatcher: h.ensureRemoteWatcher }));
-
-import { setAgentAutoSession } from './setAgentAutoSession';
-
-beforeEach(() => {
- vi.clearAllMocks();
- h.calls.length = 0;
- h.state.sshHost = null;
- h.state.agent = { id: 'agent-1', serverId: 'server-1', switchAgentId: 'switch-1' };
-});
-
-it('makes the controller spawn-capable before claiming the profile that promises a session', async () => {
- await setAgentAutoSession({ agentId: 'agent-1', enabled: true });
-
- expect(h.calls).toEqual(['mirror', 'controller', 'gateway']);
-});
-
-it('gives up the promise before standing the controller down', async () => {
- await setAgentAutoSession({ agentId: 'agent-1', enabled: false });
-
- expect(h.calls).toEqual(['gateway', 'mirror', 'controller']);
-});
-
-it('leaves the profile alone when a remote controller cannot be told it may spawn', async () => {
- // The profile is what the server answers an addressed agent on: claiming
- // auto_session over a controller that never heard would promise a session
- // nothing is going to start, and an unreachable host leaves it promising.
- h.state.sshHost = 'host';
- h.ensureRemoteWatcher.mockRejectedValueOnce(new Error('Host unreachable'));
-
- await expect(setAgentAutoSession({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
- 'Host unreachable'
- );
- expect(h.setAutoSession).not.toHaveBeenCalled();
-});
-
-it('leaves a spawn-capable controller unclaimed when the profile cannot be set', async () => {
- // The other half-applied enable. The toggle did not take, and it says so, but
- // what is left over is a controller that would start a session under a
- // profile that does not promise one — the server asks the connection there,
- // so nothing is claimed that cannot be kept.
- h.setAutoSession.mockImplementationOnce(async () => {
- h.calls.push('gateway');
- throw new Error('Gateway unreachable');
- });
-
- await expect(setAgentAutoSession({ agentId: 'agent-1', enabled: true })).rejects.toThrow(
- 'Gateway unreachable'
- );
- expect(h.calls).toEqual(['mirror', 'controller', 'gateway']);
-});
-
-it('gives the promise up even when the controller cannot then be stood down', async () => {
- // Disabling, with the second step failing. The profile has already stopped
- // promising a session, so the leftover is a controller that may still start
- // one nobody was told to expect — the direction that does not lie to a room.
- h.state.sshHost = 'host';
- h.ensureRemoteWatcher.mockImplementationOnce(async () => {
- h.calls.push('controller');
- throw new Error('Host unreachable');
- });
-
- await expect(setAgentAutoSession({ agentId: 'agent-1', enabled: false })).rejects.toThrow(
- 'Host unreachable'
- );
- expect(h.setAutoSession).toHaveBeenCalledWith({ id: 'server-1' }, 'switch-1', false);
- expect(h.calls).toEqual(['gateway', 'mirror', 'controller']);
-});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts
deleted file mode 100644
index fc61c494d..000000000
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentAutoSession.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import {
- listAutoSessionAgentIds,
- setAutoSessionAgent,
-} from '@main/core/switch-rooms/auto-session-store';
-import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
-import {
- fetchAgentOptions,
- GatewayError,
- setAutoSession,
-} from '@main/core/switch-servers/gateway-client';
-import { getServer } from '@main/core/switch-servers/servers-store';
-import { log } from '@main/lib/logger';
-import type { Agent } from '@shared/core/agents/agents';
-import { getRemoteAgentLocation } from './agent-location';
-import { getAgentById } from './getAgentById';
-import { ensureRemoteWatcher } from './remote-watcher';
-
-export type AgentAutoSessionParams = { agentId: string; enabled: boolean };
-
-/**
- * Apply an agent's auto_session state to the LOCAL side only: mirror the flag
- * and tell the agent's controller whether it may start sessions. The controller
- * itself stays up either way — an agent linked to Switch holds its connection
- * because it exists, so turning automatic sessions off leaves it addressable
- * and answering that it has no session. A remote agent's controller runs on its
- * host, so that side is driven over the transport rather than in process. Does
- * NOT touch the gateway profile — callers that also mutate the gateway must do
- * so separately.
- */
-async function applyLocalAutoSessionState(agent: Agent, enabled: boolean): Promise<void> {
- await setAutoSessionAgent(agent.id, enabled);
- if ((await getRemoteAgentLocation(agent)) !== null) await ensureRemoteWatcher(agent.id);
- else await autoSessionWatcher.reconcile(agent.id);
-}
-
-/**
- * Toggle an agent's auto_session capability. Single write path: flips the
- * gateway profile (`connection_model` ⇄ `auto_session`) via the known-agent
- * options, mirrors the flag locally, and tells the controller whether it may
- * spawn. The local agent must be linked to a Switch server and have a Switch
- * agent id.
- *
- * The two writes are ordered by which half-applied state is honest, because
- * either one can fail and leave the other standing. `auto_session` is the
- * profile on which the server answers an addressed agent with "starting a
- * session", and it grants that on the strength of the profile rather than on
- * what the controller declared — so a profile that says `auto_session` while
- * the controller cannot spawn is a promise nothing will keep. Enabling
- * therefore makes the controller spawn-capable first and claims the profile
- * second; disabling gives the promise up first and stands the controller down
- * second. A failure at either step lands on `session_addressable`, where the
- * server asks the connection instead of the profile.
- */
-export async function setAgentAutoSession(params: AgentAutoSessionParams): Promise<void> {
- const agent = await getAgentById(params.agentId);
- if (!agent) throw new Error(`No agent with id ${params.agentId}`);
- if (!agent.serverId || !agent.switchAgentId) {
- throw new Error('Agent is not linked to a Switch server; cannot set auto_session.');
- }
- const server = await getServer(agent.serverId);
- if (!server) throw new Error(`No Switch server with id ${agent.serverId}`);
-
- if (params.enabled) {
- await applyLocalAutoSessionState(agent, true);
- await setAutoSession(server, agent.switchAgentId, true);
- return;
- }
- await setAutoSession(server, agent.switchAgentId, false);
- await applyLocalAutoSessionState(agent, false);
-}
-
-/**
- * Reconcile the local auto_session state (mirror + watcher / watch-enabled
- * marker file) from the gateway profile — the source of truth. Call this right
- * after an agent is created so a fresh agent registered with `auto_session: true`
- * starts watching immediately, without the operator having to toggle it off→on.
- * Returns whether auto_session is enabled. No-ops for agents not linked to a
- * Switch server.
- */
-export async function reconcileAgentAutoSessionFromGateway(agentId: string): Promise<boolean> {
- const agent = await getAgentById(agentId);
- if (!agent?.serverId || !agent.switchAgentId) return false;
- const server = await getServer(agent.serverId);
- if (!server) return false;
-
- const { connectionModel } = await fetchAgentOptions(server, agent.switchAgentId);
- const enabled = connectionModel === 'auto_session';
- await applyLocalAutoSessionState(agent, enabled);
- return enabled;
-}
-
-/**
- * Read whether the agent has auto_session enabled, reconciling the local mirror
- * (and the watcher) from the gateway profile — the source of truth. Falls back
- * to the local mirror if the gateway is unreachable / the session is expired,
- * so the UI can still render a value.
- */
-export async function getAgentAutoSession(params: { agentId: string }): Promise<boolean> {
- const agent = await getAgentById(params.agentId);
- if (!agent?.serverId || !agent.switchAgentId) return false;
-
- try {
- return await reconcileAgentAutoSessionFromGateway(params.agentId);
- } catch (error) {
- if (error instanceof GatewayError) {
- log.warn('setAgentAutoSession: could not read gateway profile; using local mirror', {
- agentId: params.agentId,
- error: error.message,
- });
- return (await listAutoSessionAgentIds()).includes(params.agentId);
- }
- throw error;
- }
-}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts
index a8a933a3a..d090302b9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts
@@ -15,7 +15,6 @@ const getAgentLocation = vi.fn(async (_agent: unknown) => ({
sshHost: null,
}));
const getRemoteAgentLocation = vi.fn();
-const listAutoSessionAgentIds = vi.fn();
const ensureRemoteWatcher = vi.fn(async (_id: string) => {});
const removeAgentLaunchProfile = vi.fn(
async (_agent: unknown, _location: unknown, _slug: string) => {}
@@ -34,9 +33,6 @@ vi.mock('./agent-location', () => ({
getAgentLocation: (a: unknown) => getAgentLocation(a),
getRemoteAgentLocation: (a: unknown) => getRemoteAgentLocation(a),
}));
-vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
- listAutoSessionAgentIds: () => listAutoSessionAgentIds(),
-}));
vi.mock('./remote-watcher', () => ({
ensureRemoteWatcher: (id: string) => ensureRemoteWatcher(id),
}));
@@ -60,7 +56,6 @@ describe('setAgentProviderConfig', () => {
getAgentById.mockResolvedValue({ id: 'agent-1', name: 'codex.yak', locationId: 'loc-1' });
getAgentLocation.mockClear();
getRemoteAgentLocation.mockReset();
- listAutoSessionAgentIds.mockReset();
ensureRemoteWatcher.mockClear();
removeAgentLaunchProfile.mockClear();
});
@@ -95,27 +90,16 @@ describe('setAgentProviderConfig', () => {
);
});
- it('re-pushes the spec to a remote agent whose watcher is running (auto_session on)', async () => {
+ it('re-pushes the spec to a remote agent’s watcher', async () => {
getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
expect(ensureRemoteWatcher).toHaveBeenCalledWith('agent-1');
});
- it('skips the re-push for a remote agent with auto_session off (nothing running to refresh)', async () => {
- getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
- listAutoSessionAgentIds.mockResolvedValue([]);
-
- await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
-
- expect(ensureRemoteWatcher).not.toHaveBeenCalled();
- });
-
it('surfaces an unreachable VM rather than reporting a save that only half landed', async () => {
getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
- listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
ensureRemoteWatcher.mockRejectedValueOnce(new Error('ssh: connect failed'));
await expect(setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG })).rejects.toThrow(
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts
index 34fccb749..6ae02e954 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts
@@ -1,4 +1,3 @@
-import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import { getAgentLocation, getRemoteAgentLocation } from './agent-location';
import { getAgentById } from './getAgentById';
@@ -29,9 +28,7 @@ export type AgentProviderConfigParams = {
* is specialized again under the same name and directory.
* - A remote agent bakes the specialization into its on-VM watcher's launch
* spec, so the watcher is re-ensured to rewrite it; the running sidecar
- * re-reads the spec and applies it to the next auto-started session. When
- * auto_session is off there is no watcher to refresh and the next
- * `ensureRemoteWatcher` picks the value up.
+ * re-reads the spec and applies it to the next auto-started session.
*
* The re-ensure is allowed to throw: if the VM is unreachable the change cannot
* reach auto-started sessions, and the caller should surface that rather than
@@ -53,6 +50,5 @@ export async function setAgentProviderConfig(params: AgentProviderConfigParams):
}
if ((await getRemoteAgentLocation(agent)) === null) return;
- if (!(await listAutoSessionAgentIds()).includes(agent.id)) return;
await ensureRemoteWatcher(agent.id);
}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.test.ts
new file mode 100644
index 000000000..bc9ef87f6
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.test.ts
@@ -0,0 +1,166 @@
+/**
+ * One session listing per host, not one per agent.
+ *
+ * This read used to run once per linked agent every 5 seconds, and each run
+ * read *every* session directory on the host to keep the few belonging to
+ * that agent. Twenty agents on a machine meant twenty SSH commands every five
+ * seconds, forever, down a connection that runs four at a time — for twenty
+ * near-identical answers. It was the largest standing cost of leaving Console
+ * open.
+ *
+ * So what these tests hold is a count: how many times the host is actually
+ * asked. Getting the sessions right matters too, but that was already true;
+ * the regression worth catching is the fan-out quietly coming back.
+ */
+
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ exec: vi.fn(),
+ agents: new Map<string, { id: string; switchAgentId: string; locationId: string }>(),
+ locations: new Map<string, { sshHost: string | null }>(),
+}));
+
+vi.mock('@main/core/agents/getAgentById', () => ({
+ getAgentById: async (id: string) => mocks.agents.get(id),
+}));
+vi.mock('@main/core/agents/agent-location', () => ({
+ getAgentLocation: async (agent: { locationId: string }) => mocks.locations.get(agent.locationId),
+}));
+vi.mock('@main/core/agents/connect-remote-agent', () => ({
+ connectRemoteAgent: async () => ({ ctx: { exec: mocks.exec } }),
+}));
+vi.mock('@main/core/execution-context/local-execution-context', () => ({
+ LocalExecutionContext: class {
+ exec = mocks.exec;
+ },
+}));
+
+const { clearHostSessionsCache, listHostSessions } = await import('./host-sessions');
+
+/** What the host script prints: every session on the machine, with its owner. */
+function hostReplies(entries: { agentId: string; sessionId: string }[]) {
+ mocks.exec.mockImplementation(async () => ({
+ stdout: JSON.stringify(
+ entries.map((e) => ({
+ agentId: e.agentId,
+ session: {
+ sessionId: e.sessionId,
+ agentId: e.agentId,
+ provider: 'claude',
+ hostId: 'host',
+ epoch: 'epoch',
+ status: 'running',
+ connectivity: 'online',
+ pendingRequestIds: [],
+ capabilities: {
+ input: 'queue',
+ approvals: false,
+ questions: false,
+ interrupt: false,
+ reset: false,
+ compact: false,
+ modelChange: false,
+ attachmentMimeTypes: [],
+ },
+ },
+ stopped: false,
+ room: null,
+ alive: true,
+ }))
+ ),
+ stderr: '',
+ exitCode: 0,
+ }));
+}
+
+function agentOn(id: string, switchAgentId: string, host: string | null) {
+ mocks.agents.set(id, { id, switchAgentId, locationId: `loc-${host ?? 'local'}` });
+ mocks.locations.set(`loc-${host ?? 'local'}`, { sshHost: host });
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.useRealTimers();
+ mocks.agents.clear();
+ mocks.locations.clear();
+ clearHostSessionsCache();
+});
+
+it('asks the host once when every agent on it lists at the same moment', async () => {
+ for (let i = 1; i <= 20; i++) agentOn(`a${i}`, `switch-a${i}`, 'vm-1');
+ hostReplies([{ agentId: 'switch-a7', sessionId: 's7' }]);
+
+ const results = await Promise.all(
+ Array.from({ length: 20 }, (_, i) => listHostSessions(`a${i + 1}`))
+ );
+
+ expect(mocks.exec).toHaveBeenCalledTimes(1);
+ expect(results[6].map((s) => s.sessionId)).toEqual(['s7']);
+});
+
+it('gives each agent only its own sessions', async () => {
+ agentOn('a1', 'switch-a1', 'vm-1');
+ agentOn('a2', 'switch-a2', 'vm-1');
+ hostReplies([
+ { agentId: 'switch-a1', sessionId: 'one' },
+ { agentId: 'switch-a2', sessionId: 'two' },
+ { agentId: 'switch-a1', sessionId: 'three' },
+ ]);
+
+ expect((await listHostSessions('a1')).map((s) => s.sessionId).sort()).toEqual(['one', 'three']);
+ expect((await listHostSessions('a2')).map((s) => s.sessionId)).toEqual(['two']);
+});
+
+it('reports an agent with nothing on the host as having no sessions', async () => {
+ // Not "unknown": the read covered every agent on the machine, so an absent
+ // agent is a statement rather than a gap.
+ agentOn('a1', 'switch-a1', 'vm-1');
+ hostReplies([{ agentId: 'someone-else', sessionId: 'x' }]);
+
+ expect(await listHostSessions('a1')).toEqual([]);
+});
+
+it('does not share one host’s answer with another host', async () => {
+ agentOn('a1', 'switch-a1', 'vm-1');
+ agentOn('a2', 'switch-a2', 'vm-2');
+ hostReplies([]);
+
+ await Promise.all([listHostSessions('a1'), listHostSessions('a2')]);
+
+ expect(mocks.exec).toHaveBeenCalledTimes(2);
+});
+
+it('keeps local agents separate from a remote host', async () => {
+ agentOn('local-1', 'switch-local', null);
+ agentOn('remote-1', 'switch-remote', 'vm-1');
+ hostReplies([]);
+
+ await Promise.all([listHostSessions('local-1'), listHostSessions('remote-1')]);
+
+ expect(mocks.exec).toHaveBeenCalledTimes(2);
+});
+
+it('retries after a failure instead of caching the rejection', async () => {
+ // A cached failure would leave every agent on the host wedged until the TTL
+ // expired, which is the opposite of what a shared read should do.
+ agentOn('a1', 'switch-a1', 'vm-1');
+ mocks.exec.mockRejectedValueOnce(new Error('connection lost'));
+
+ await expect(listHostSessions('a1')).rejects.toThrow('connection lost');
+
+ hostReplies([{ agentId: 'switch-a1', sessionId: 'back' }]);
+ expect((await listHostSessions('a1')).map((s) => s.sessionId)).toEqual(['back']);
+});
+
+it('reads again once the listing is stale', async () => {
+ vi.useFakeTimers();
+ agentOn('a1', 'switch-a1', 'vm-1');
+ hostReplies([]);
+
+ await listHostSessions('a1');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await listHostSessions('a1');
+
+ expect(mocks.exec).toHaveBeenCalledTimes(2);
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts
index 647949dda..0f1003f04 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-sessions.ts
@@ -5,6 +5,7 @@ import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
import { getAgentById } from '@main/core/agents/getAgentById';
import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';
import type { IExecutionContext } from '@main/core/execution-context/types';
+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
import { READ_JSON } from './remote-json';
import { IS_STATE_ROOT } from './state-roots';
@@ -15,12 +16,18 @@ import { IS_STATE_ROOT } from './state-roots';
* keeps its own, under the agent's host directory, and this is where Console
* finds them. One `node` run per call, locally or over the agent's SSH
* connection: the same script either way.
+ *
+ * It reports every session on the host with the agent that owns it, rather
+ * than filtering to one. Answering for a single agent always meant reading
+ * every session directory anyway — the filter only discarded the rest — so
+ * returning all of it costs nothing and lets one run serve every agent on
+ * the host.
*/
export const LIST_SCRIPT = String.raw`${READ_JSON}${IS_STATE_ROOT}
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
-const [agentId, baseArg] = process.argv.slice(1);
+const [, baseArg] = process.argv.slice(1);
const base = baseArg || path.join(os.homedir(), '.local', 'state', 'switch', 'sdk-sessions');
const lines = (file) => {
try {
@@ -45,19 +52,20 @@ for (const name of names) {
const root = path.join(base, name);
let config;
try { config = readJson(path.join(root, 'config.json')); } catch (e) { if (e.code === 'ENOENT') continue; throw e; }
- if (!config || !config.session || config.session.agentId !== agentId) continue;
+ if (!config || !config.session || !config.session.agentId) continue;
const upserts = lines(path.join(root, 'events.jsonl')).filter((e) => e && e.body && e.body.type === 'session.upsert');
const latest = upserts.length ? upserts[upserts.length - 1].body.session : null;
const stopped = lines(path.join(root, 'inbox.jsonl')).some((r) => r && r.type === 'stopped');
const handoffs = lines(path.join(root, 'handoff.jsonl'));
const room = handoffs.length ? handoffs[handoffs.length - 1].roomId : null;
- found.push({ session: latest ?? config.session, stopped, room, alive: alive(root) });
+ found.push({ agentId: config.session.agentId, session: latest ?? config.session, stopped, room, alive: alive(root) });
}
process.stdout.write(JSON.stringify(found));
`;
const listedSchema = z.array(
z.object({
+ agentId: z.string(),
session: z.unknown(),
stopped: z.boolean(),
room: z.string().nullable(),
@@ -67,35 +75,93 @@ const listedSchema = z.array(
async function agentContext(
agentId: string
-): Promise<{ ctx: IExecutionContext; switchAgentId: string }> {
+): Promise<{ ctx: IExecutionContext; switchAgentId: string; hostKey: string }> {
const agent = await getAgentById(agentId);
if (!agent?.switchAgentId) throw new Error('This agent is not linked to Switch.');
const location = await getAgentLocation(agent);
const ctx = location.sshHost
? (await connectRemoteAgent(agent)).ctx
: new LocalExecutionContext();
- return { ctx, switchAgentId: agent.switchAgentId };
+ return {
+ ctx,
+ switchAgentId: agent.switchAgentId,
+ // The pooled SSH connection is per host, so that is also the unit the
+ // read below is shared over. Everything local shares one key for the
+ // same reason: it is all one machine.
+ hostKey: location.sshHost ? sshConnectionIdForHost(location.sshHost) : 'local',
+ };
+}
+
+/**
+ * How long one host's session listing is reused for. Comfortably shorter than
+ * the discovery interval, so a normal round still reads fresh state, and long
+ * enough to cover a host's agents whose timers have drifted apart.
+ */
+export const HOST_SESSIONS_TTL_MS = 3000;
+
+const hostReads = new Map<string, { at: number; sessions: Promise<Map<string, Session[]>> }>();
+
+/** Drop every cached listing. For tests, and for "refresh now" paths. */
+export function clearHostSessionsCache(): void {
+ hostReads.clear();
+}
+
+/**
+ * Every session on one host, grouped by the Switch agent that owns it.
+ *
+ * Shared per host, because it used to be per agent and that was the single
+ * largest standing cost of running Console: each linked agent listed sessions
+ * every 5 seconds, and each listing read *all* of the host's session
+ * directories to keep the few that were its own. Twenty agents on a host
+ * meant twenty SSH commands every five seconds, forever, down a connection
+ * that runs four at a time — and the answers were near-identical.
+ *
+ * Now one command answers for all of them. Concurrent callers join the
+ * in-flight read rather than starting their own, which is what collapses the
+ * burst when a host's agents all tick together; the short TTL catches the
+ * stragglers whose timers have drifted.
+ *
+ * A failed read is not cached — the next caller retries rather than being
+ * handed a stale rejection.
+ */
+async function hostSessions(agentId: string): Promise<Map<string, Session[]>> {
+ const { ctx, hostKey } = await agentContext(agentId);
+ const cached = hostReads.get(hostKey);
+ if (cached && Date.now() - cached.at < HOST_SESSIONS_TTL_MS) return cached.sessions;
+
+ const read = (async () => {
+ const { stdout } = await ctx.exec('node', ['-e', LIST_SCRIPT, '', '']);
+ const byAgent = new Map<string, Session[]>();
+ for (const entry of listedSchema.parse(JSON.parse(stdout))) {
+ const parsed = sessionSchema.safeParse(entry.session);
+ if (!parsed.success) continue;
+ const list = byAgent.get(entry.agentId);
+ const session = {
+ ...parsed.data,
+ status: entry.stopped ? ('stopped' as const) : parsed.data.status,
+ connectivity: entry.alive ? ('online' as const) : ('offline' as const),
+ roomIds: entry.room ? [entry.room] : [],
+ retired: false,
+ };
+ if (list) list.push(session);
+ else byAgent.set(entry.agentId, [session]);
+ }
+ return byAgent;
+ })();
+ read.catch(() => hostReads.delete(hostKey));
+ hostReads.set(hostKey, { at: Date.now(), sessions: read });
+ return read;
}
/**
* Each session this agent has on its host, as its host last recorded it: the
* status it reported, whether its host is running now, and the room it was
* last handed a message in.
+ *
+ * An agent with no sessions gets an empty list, which is a fact about the
+ * host rather than a gap: the read covered every agent on it.
*/
export async function listHostSessions(agentId: string): Promise<Session[]> {
- const { ctx, switchAgentId } = await agentContext(agentId);
- const { stdout } = await ctx.exec('node', ['-e', LIST_SCRIPT, switchAgentId, '']);
- return listedSchema.parse(JSON.parse(stdout)).flatMap((entry) => {
- const parsed = sessionSchema.safeParse(entry.session);
- if (!parsed.success) return [];
- return [
- {
- ...parsed.data,
- status: entry.stopped ? 'stopped' : parsed.data.status,
- connectivity: entry.alive ? 'online' : 'offline',
- roomIds: entry.room ? [entry.room] : [],
- retired: false,
- },
- ];
- });
+ const { switchAgentId } = await agentContext(agentId);
+ return (await hostSessions(agentId)).get(switchAgentId) ?? [];
}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts
new file mode 100644
index 000000000..0ae2f8195
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.test.ts
@@ -0,0 +1,99 @@
+/**
+ * The skip check that lets a host's agents be brought up only when needed.
+ *
+ * Bringing one controller up is about a dozen SSH round trips whose usual
+ * outcome is nothing — the watcher is already running the right build. This
+ * decides that in advance, from one command per host.
+ *
+ * What these tests are really about is the asymmetry: wrongly deciding "needs
+ * work" costs a redundant bring-up, which is what happens today anyway.
+ * Wrongly deciding "current" leaves an agent off the air with nothing to
+ * notice. So every uncertain case has to fall on the safe side, and that is
+ * most of what is asserted here.
+ */
+
+import { expect, it, vi } from 'vitest';
+import { listHostWatchers, watcherIsCurrent, type HostWatcherStatus } from './host-watchers';
+
+const ENTRYPOINT = '/home/u/.local/state/switch/sdk-host/shared-host-abc123.mjs';
+const BUNDLE_FILE = 'shared-host-abc123.mjs';
+const want = { bundleFile: BUNDLE_FILE, enabled: true, spawn: true };
+
+function status(overrides: Partial<HostWatcherStatus> = {}): HostWatcherStatus {
+ return {
+ agentId: 'switch-a1',
+ root: '/home/u/.local/state/switch/sdk-watchers/hash',
+ running: true,
+ build: ENTRYPOINT,
+ enabled: true,
+ spawn: true,
+ stoodDown: false,
+ ...overrides,
+ };
+}
+
+it('skips a watcher that is running the right build with the right flags', () => {
+ expect(watcherIsCurrent(status(), want)).toBe(true);
+});
+
+it.each([
+ ['the agent is not on the host at all', undefined],
+ ['no supervisor is running', status({ running: false })],
+ ['it runs a different build', status({ build: '/…/shared-host-old.mjs' })],
+ ['its build is unknown', status({ build: null })],
+ ['it has no watch flags yet', status({ enabled: null, spawn: null })],
+ ['it is enabled but will not spawn', status({ spawn: false })],
+ ['it is disabled', status({ enabled: false })],
+ ['it stood down for another client', status({ stoodDown: true })],
+])('brings up when %s', (_case, given) => {
+ expect(watcherIsCurrent(given as HostWatcherStatus | undefined, want)).toBe(false);
+});
+
+it('does not skip when the flags we want differ from the ones it has', () => {
+ // The bring-up writes watch.json, so "running the right build" alone is not
+ // enough — skipping here would silently drop a change to what it may do.
+ expect(watcherIsCurrent(status(), { ...want, spawn: false })).toBe(false);
+});
+
+it('reads every watcher on the host in one command, keyed by agent', async () => {
+ const exec = vi.fn(async () => ({
+ stdout: JSON.stringify([
+ {
+ agentId: 'switch-a1',
+ root: '/r/1',
+ running: true,
+ build: ENTRYPOINT,
+ enabled: true,
+ spawn: true,
+ stoodDown: false,
+ },
+ {
+ agentId: 'switch-a2',
+ root: '/r/2',
+ running: false,
+ build: null,
+ enabled: null,
+ spawn: null,
+ stoodDown: false,
+ },
+ ]),
+ stderr: '',
+ exitCode: 0,
+ }));
+
+ const found = await listHostWatchers({ exec } as never);
+
+ expect(exec).toHaveBeenCalledTimes(1);
+ expect([...found.keys()].sort()).toEqual(['switch-a1', 'switch-a2']);
+ expect(watcherIsCurrent(found.get('switch-a1'), want)).toBe(true);
+ expect(watcherIsCurrent(found.get('switch-a2'), want)).toBe(false);
+});
+
+it('treats a host with no watchers as nothing to skip', async () => {
+ const exec = vi.fn(async () => ({ stdout: '[]', stderr: '', exitCode: 0 }));
+
+ const found = await listHostWatchers({ exec } as never);
+
+ expect(found.size).toBe(0);
+ expect(watcherIsCurrent(found.get('switch-a1'), want)).toBe(false);
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts
new file mode 100644
index 000000000..5aaa8a3d5
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/host-watchers.ts
@@ -0,0 +1,110 @@
+import { z } from 'zod';
+import type { IExecutionContext } from '@main/core/execution-context/types';
+import { READ_JSON } from './remote-json';
+
+/**
+ * What every watcher on one host is currently doing — one command, whatever
+ * the agent count.
+ *
+ * Bringing a controller up costs about a dozen SSH round trips, and its usual
+ * outcome is nothing at all: the watcher is already running the build we would
+ * have installed, so the launcher looks at it and leaves it alone. Opening
+ * Console on a host with twenty agents paid that cost twenty times to discover
+ * twenty times that there was nothing to do — and paid it again on every host
+ * reconnect, which on an unstable tunnel is constantly.
+ *
+ * This asks once instead. What it reports is exactly what the host-side
+ * launcher decides on (`liveSupervisor` in `agent-providers/host/launch.ts`):
+ * is a supervisor process alive, and which build does it say it is running.
+ * It also returns the watch flags, since the bring-up writes those too and a
+ * skip has to mean "nothing would have changed", not just "it is running".
+ *
+ * Deliberately only facts. It does not decide anything — see
+ * `watcherIsCurrent` for that, so the decision lives in one place and can be
+ * read without the script.
+ */
+export const WATCHER_STATUS_SCRIPT = String.raw`${READ_JSON}
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const [baseArg] = process.argv.slice(1);
+const base = baseArg || path.join(os.homedir(), '.local', 'state', 'switch', 'sdk-watchers');
+const alive = (pid) => {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+};
+let names = [];
+try { names = fs.readdirSync(base); } catch {}
+const found = [];
+for (const name of names) {
+ const root = path.join(base, name);
+ let config;
+ try { config = readJson(path.join(root, 'config.json')); } catch (e) { if (e.code === 'ENOENT') continue; throw e; }
+ if (!config || !config.session || !config.session.agentId) continue;
+ let owner = null;
+ try { owner = readJson(path.join(root, 'supervisor', 'owner.json')); } catch (e) { if (e.code !== 'ENOENT') throw e }
+ let watch = null;
+ try { watch = readJson(path.join(root, 'watch.json')); } catch (e) { if (e.code !== 'ENOENT') throw e }
+ let stoodDown = false;
+ try { fs.statSync(path.join(root, 'taken-over.json')); stoodDown = true; } catch (e) { if (e.code !== 'ENOENT') throw e }
+ found.push({
+ agentId: config.session.agentId,
+ root,
+ running: !!(owner && Number.isSafeInteger(owner.pid) && owner.pid > 0 && alive(owner.pid)),
+ build: owner && typeof owner.build === 'string' ? owner.build : null,
+ enabled: watch ? watch.enabled === true : null,
+ spawn: watch ? watch.spawn === true : null,
+ stoodDown,
+ });
+}
+process.stdout.write(JSON.stringify(found));
+`;
+
+const statusSchema = z.array(
+ z.object({
+ agentId: z.string(),
+ root: z.string(),
+ running: z.boolean(),
+ build: z.string().nullable(),
+ enabled: z.boolean().nullable(),
+ spawn: z.boolean().nullable(),
+ stoodDown: z.boolean(),
+ })
+);
+
+export type HostWatcherStatus = z.infer<typeof statusSchema>[number];
+
+/** Every watcher on the host this context reaches, keyed by Switch agent id. */
+export async function listHostWatchers(
+ ctx: IExecutionContext
+): Promise<Map<string, HostWatcherStatus>> {
+ const { stdout } = await ctx.exec('node', ['-e', WATCHER_STATUS_SCRIPT, '']);
+ return new Map(statusSchema.parse(JSON.parse(stdout)).map((entry) => [entry.agentId, entry]));
+}
+
+/**
+ * Whether bringing this watcher up would change anything.
+ *
+ * The bar is deliberately high, because the two ways of being wrong are not
+ * symmetric. Saying "needs work" when it does not costs a bring-up that ends
+ * in the launcher declining to restart anything — the behaviour we have
+ * today. Saying "current" when it is not leaves the agent off the air with
+ * nothing to notice, which is worse than the cost this exists to avoid. So
+ * anything unknown, absent or unexpected counts as needing work.
+ *
+ * The build is compared by *filename*. The host records the entrypoint path
+ * it launched, and that filename carries the bundle's content hash, so equal
+ * filenames mean equal code — without this side having to resolve the remote
+ * home directory first, which would cost the round trip this exists to save.
+ */
+export function watcherIsCurrent(
+ status: HostWatcherStatus | undefined,
+ want: { bundleFile: string; enabled: boolean; spawn: boolean }
+): boolean {
+ if (!status) return false;
+ // A watcher that stood down for another client is left alone by a restore,
+ // but its state is not ours to reason about: defer to the normal path.
+ if (status.stoodDown) return false;
+ if (!status.running) return false;
+ if (!status.build || status.build.split('/').pop() !== want.bundleFile) return false;
+ return status.enabled === want.enabled && status.spawn === want.spawn;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.test.ts
index 0f25ef093..793fdeeeb 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.test.ts
@@ -1,6 +1,10 @@
+import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { readFile, stat } from 'node:fs/promises';
-import { expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, readdir, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { promisify } from 'node:util';
+import { afterEach, expect, it, vi } from 'vitest';
import type { IExecutionContext } from '@main/core/execution-context/types';
vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({
resolveSharedHostBundlePath: vi.fn(),
@@ -24,7 +28,8 @@ vi.mock('@main/core/execution-context/ssh-execution-context', () => ({
}
},
}));
-const { resolveWatcherRoot, runSharedHostCommand } = await import('./shared-host-deployment');
+const { LOCATE_BUNDLE, resolveWatcherRoot, runSharedHostCommand } =
+ await import('./shared-host-deployment');
it.each([false, true])(
'keeps configuration out of launch arguments and cleans files on failure=%s',
async (fail) => {
@@ -73,3 +78,55 @@ it('finds a watcher’s state root on a host without deploying anything there',
'switch-agent-1',
]);
});
+
+const homes: string[] = [];
+afterEach(async () => {
+ for (const home of homes.splice(0)) await rm(home, { recursive: true, force: true });
+});
+
+async function hostWith(bundles: { name: string; ageMs: number }[]) {
+ const home = await mkdtemp(join(tmpdir(), 'locate-bundle-'));
+ homes.push(home);
+ const dir = join(home, '.local/state/switch/sdk-host');
+ await mkdir(dir, { recursive: true });
+ for (const bundle of bundles) {
+ await writeFile(join(dir, bundle.name), '');
+ const at = new Date(Date.now() - bundle.ageMs);
+ await utimes(join(dir, bundle.name), at, at);
+ }
+ return { home, dir };
+}
+
+async function locate(home: string, wanted: string) {
+ const { stdout } = await promisify(execFile)(process.execPath, ['-e', LOCATE_BUNDLE, wanted], {
+ env: { ...process.env, HOME: home },
+ });
+ return stdout.trim();
+}
+
+const bundle = (c: string) => `shared-host-${c.repeat(64)}.mjs`;
+
+it('finds this build’s bundle on a host without deploying one', async () => {
+ const { home, dir } = await hostWith([
+ { name: bundle('a'), ageMs: 0 },
+ { name: bundle('b'), ageMs: 60_000 },
+ ]);
+ expect(await locate(home, bundle('b'))).toBe(join(dir, bundle('b')));
+ expect((await readdir(dir)).sort()).toEqual([bundle('a'), bundle('b')]);
+});
+
+it('falls back to the newest bundle an earlier deployment left', async () => {
+ const { home, dir } = await hostWith([
+ { name: bundle('a'), ageMs: 120_000 },
+ { name: bundle('b'), ageMs: 1_000 },
+ { name: 'shared-host-not-a-bundle.mjs', ageMs: 0 },
+ ]);
+ expect(await locate(home, bundle('c'))).toBe(join(dir, bundle('b')));
+});
+
+it('reports a host with no bundle rather than deploying one', async () => {
+ const empty = await mkdtemp(join(tmpdir(), 'locate-bundle-'));
+ homes.push(empty);
+ expect(await locate(empty, bundle('c'))).toBe('');
+ await expect(stat(join(empty, '.local'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts
index 58b244486..c8d0d1477 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-host-deployment.ts
@@ -20,6 +20,51 @@ import { MAKE_LAUNCH_DIR, RESOLVE_STATE_ROOT, STALE_LAUNCH_MS } from './state-ro
const PRUNE_SUPERSEDED_BUNDLES =
"const fs=require('node:fs');const [dir,keep]=process.argv.slice(1);const running=require('node:child_process').execFileSync('ps',['-eo','args='],{encoding:'utf8'});for(const name of fs.readdirSync(dir)){if(name===keep||!/^shared-host-[a-f0-9]{64}\\.mjs$/.test(name)||running.includes(name))continue;fs.rmSync(dir+'/'+name,{force:true})}";
+/**
+ * Prints the path of a shared host bundle already on the host: this build's
+ * when it is there, otherwise the newest one an earlier deployment left, and
+ * nothing when there is none. Arguments: this build's bundle file name.
+ */
+export const LOCATE_BUNDLE = String.raw`
+const fs = require('node:fs'), path = require('node:path');
+const [wanted] = process.argv.slice(1);
+const dir = path.join(require('node:os').homedir(), '.local', 'state', 'switch', 'sdk-host');
+let names;
+try { names = fs.readdirSync(dir); }
+catch (e) { if (e.code === 'ENOENT') { console.log(''); process.exit(0); } throw e; }
+const bundles = names.filter((name) => /^shared-host-[a-f0-9]{64}\.mjs$/.test(name));
+if (bundles.includes(wanted)) console.log(path.join(dir, wanted));
+else if (!bundles.length) console.log('');
+else console.log(path.join(dir, bundles
+ .map((name) => ({ name, at: fs.statSync(path.join(dir, name)).mtimeMs }))
+ .sort((a, b) => b.at - a.at)[0].name));
+`;
+
+/**
+ * A shared host to run a one-off command with, without deploying one: this
+ * machine's own bundle, or a bundle already on the SSH host. Reading a host —
+ * what its provider offers, whether it is signed in — must not change what is
+ * installed there; only a launch, or somebody pressing Update, deploys. Null
+ * when the host has no bundle yet.
+ */
+export async function locateSharedHost(
+ transport: LocationTransport,
+ dir: string
+): Promise<{ ctx: IExecutionContext; entrypoint: string } | null> {
+ const bundle = resolveSharedHostBundlePath();
+ if (transport.kind !== 'ssh') return { ctx: new LocalExecutionContext(), entrypoint: bundle };
+ const hash = createHash('sha256')
+ .update(await readFile(bundle))
+ .digest('hex');
+ const proxy = await ensureSshConnected(transport.connectionId, transport.host);
+ const ctx = new SshExecutionContext(proxy, { root: dir });
+ const { stdout } = await ctx.exec('node', ['-e', LOCATE_BUNDLE, `shared-host-${hash}.mjs`]);
+ const entrypoint = stdout.trim();
+ if (entrypoint) return { ctx, entrypoint };
+ ctx.dispose();
+ return null;
+}
+
export async function deploySharedHost(
transport: LocationTransport,
sessionPath: string,
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts
index ccf6bc0a9..894f521fc 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.locality.test.ts
@@ -8,7 +8,6 @@ const mocks = vi.hoisted(() => ({
stopLocal: vi.fn(),
exec: vi.fn(),
stopped: vi.fn(),
- spawning: vi.fn(),
removeRoots: vi.fn(),
agentById: vi.fn(),
ssh: vi.fn(),
@@ -23,7 +22,6 @@ vi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: mocks.ser
vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
listStoppedControllerAgentIds: mocks.stopped,
- listAutoSessionAgentIds: mocks.spawning,
}));
vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: mocks.agentById }));
@@ -77,7 +75,6 @@ beforeEach(() => {
});
mocks.exec.mockResolvedValue({ stdout: '' });
mocks.stopped.mockResolvedValue([]);
- mocks.spawning.mockResolvedValue([]);
mocks.agentById.mockResolvedValue({
id: 'agent-1',
name: 'scout',
@@ -169,15 +166,11 @@ it('passes the spawn decision to a local watcher', async () => {
expect(mocks.startLocal.mock.calls[0][1]).toEqual({ intent: 'explicit', spawning: false });
});
-it.each([true, false])(
- 'connects an agent nobody stopped, spawning only when auto-start is %s',
- async (autoStart) => {
- mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });
- mocks.spawning.mockResolvedValue(autoStart ? ['agent-1'] : []);
- await applyControllerState('agent-1', 'restore', 'host');
- expect(mocks.startLocal.mock.calls[0][1]).toEqual({ intent: 'restore', spawning: autoStart });
- }
-);
+it('connects an agent nobody stopped, and lets it start sessions', async () => {
+ mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });
+ await applyControllerState('agent-1', 'restore', 'host');
+ expect(mocks.startLocal.mock.calls[0][1]).toEqual({ intent: 'restore', spawning: true });
+});
it('discards a local agent’s controller state inside Console', async () => {
mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });
@@ -207,10 +200,9 @@ it('has no controller state to discard for an agent never linked to Switch', asy
expect(mocks.location).not.toHaveBeenCalled();
});
-it('leaves a stopped controller off the air however auto-start is set', async () => {
+it('leaves a stopped controller off the air', async () => {
mocks.location.mockResolvedValue({ id: 'local', dir: '/work', sshHost: null });
mocks.stopped.mockResolvedValue(['agent-1']);
- mocks.spawning.mockResolvedValue(['agent-1']);
await applyControllerState('agent-1', 'restore', 'host');
expect(mocks.stopLocal).toHaveBeenCalledWith('switch-agent-1');
expect(mocks.startLocal).not.toHaveBeenCalled();
diff --git a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts
index d7565577d..12cfdeff3 100644
--- a/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sdk-host/shared-watcher.ts
@@ -9,10 +9,7 @@ import { resolveSessionEnv } from '@main/core/locations/location-runtime-factory
import { locationTransport, type LocationTransport } from '@main/core/locations/location-transport';
import { ensureServerSessionReady } from '@main/core/managed-switch-server/session-readiness';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
-import {
- listAutoSessionAgentIds,
- listStoppedControllerAgentIds,
-} from '@main/core/switch-rooms/auto-session-store';
+import { listStoppedControllerAgentIds } from '@main/core/switch-rooms/auto-session-store';
import { controllerConnectionId } from '@main/core/switch-rooms/session-connection-id';
import { getServer } from '@main/core/switch-servers/servers-store';
import { log } from '@main/lib/logger';
@@ -161,27 +158,21 @@ export async function recordAutoApproveOnHost(
export type ControllerState = { connected: boolean; spawning: boolean };
/**
- * Puts an agent's controller into the state its settings describe: connected
- * unless somebody stopped it, and spawning only if automatic sessions are on.
- * This is the read of those two settings — callers that are not themselves
- * deciding one of them should come through here rather than assemble a state.
+ * Puts an agent's controller into the state its settings describe: connected,
+ * and starting sessions when addressed, unless somebody stopped it. Callers
+ * that are not themselves stopping or starting it should come through here
+ * rather than assemble a state.
*/
export async function applyControllerState(
agentId: string,
intent: WatcherIntent,
autoApprove: AutoApproveSource
): Promise<void> {
- const [stopped, spawning] = await Promise.all([
- listStoppedControllerAgentIds(),
- listAutoSessionAgentIds(),
- ]);
- const connected = !stopped.includes(agentId);
- await configureSharedWatcherFor(
- agentId,
- { connected, spawning: connected && spawning.includes(agentId) },
- intent,
- { name: undefined, autoApprove }
- );
+ const connected = !(await listStoppedControllerAgentIds()).includes(agentId);
+ await configureSharedWatcherFor(agentId, { connected, spawning: connected }, intent, {
+ name: undefined,
+ autoApprove,
+ });
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.db.test.ts
index f0b0843cb..6e40c61fd 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.db.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.db.test.ts
@@ -14,10 +14,8 @@ vi.mock('@main/db/client', () => ({
}));
const {
- listAutoSessionAgentIds,
listAutoSessionSubagents,
listStoppedControllerAgentIds,
- setAutoSessionAgent,
setAutoSessionSubagent,
setControllerStopped,
} = await import('./auto-session-store');
@@ -43,12 +41,15 @@ it('keeps both agents stopped when two controllers are stopped at once', async (
expect((await listStoppedControllerAgentIds()).sort()).toEqual(['agent-1', 'agent-2']);
});
-it('does not put an agent back in the auto-session mirror because another was added', async () => {
- await setAutoSessionAgent('agent-1', true);
+it('does not put an agent back on the air because another was started', async () => {
+ await setControllerStopped('agent-1', true);
- await Promise.all([setAutoSessionAgent('agent-1', false), setAutoSessionAgent('agent-2', true)]);
+ await Promise.all([
+ setControllerStopped('agent-1', false),
+ setControllerStopped('agent-2', true),
+ ]);
- expect(await listAutoSessionAgentIds()).toEqual(['agent-2']);
+ expect(await listStoppedControllerAgentIds()).toEqual(['agent-2']);
});
it('keeps both subagents when two are enabled at once', async () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.ts
index d99439695..379c93841 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-store.ts
@@ -2,15 +2,6 @@ import { eq } from 'drizzle-orm';
import { db } from '@main/db/client';
import { appSettings } from '@main/db/schema';
-/**
- * Local mirror of which agents have `auto_session` enabled. The agent's gateway
- * profile (`connection_model === 'auto_session'`) is the source of truth; this
- * mirror lets the watcher start at boot using only the agent token (no gateway
- * JWT), and is reconciled from the gateway when the UI loads the agent. Stored
- * as a JSON array of local agent ids under a single appSettings key.
- */
-const KEY = 'auto_session_agents';
-
/**
* Agents whose controller someone stopped by hand. Every agent linked to Switch
* is given a controller at boot, so this is the only record that one of them
@@ -48,8 +39,7 @@ const inFlight = new Map<string, Promise<void>>();
* row, so changing one member is a read, an edit and a write with suspension
* points between them: two that overlap both read before either writes, and the
* later write drops the earlier's member. Overlapping is ordinary here —
- * removing an agent clears both agent keys, and tearing down a host removes its
- * agents together — and what is lost is durable, so an agent stopped by hand is
+ * tearing down a host removes its agents together — and what is lost is durable, so an agent stopped by hand is
* back on the air at the next boot.
*/
function serialize(key: string, mutate: () => Promise<void>): Promise<void> {
@@ -72,16 +62,6 @@ async function updateSet(key: string, agentId: string, member: boolean): Promise
});
}
-/** Local agent ids currently mirrored as auto_session-enabled. */
-export async function listAutoSessionAgentIds(): Promise<string[]> {
- return [...(await readSet(KEY))];
-}
-
-/** Add or remove an agent from the local auto_session mirror. */
-export async function setAutoSessionAgent(agentId: string, enabled: boolean): Promise<void> {
- await updateSet(KEY, agentId, enabled);
-}
-
/** Local agent ids whose controller is stopped until someone starts it again. */
export async function listStoppedControllerAgentIds(): Promise<string[]> {
return [...(await readSet(STOPPED_KEY))];
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
index fde1e8fa7..bf805ed23 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
type Change = { current: { sshHost: string; status: string } };
const mocks = vi.hoisted(() => {
const listeners: ((change: Change) => void)[] = [];
@@ -10,8 +10,6 @@ const mocks = vi.hoisted(() => {
dispose: vi.fn(async () => {}),
agents: vi.fn(),
agentById: vi.fn(),
- autoSessionIds: vi.fn(),
- setAutoSessionAgent: vi.fn(),
location: vi.fn(),
reachability: {
on(_event: string, listener: (change: Change) => void) {
@@ -35,20 +33,19 @@ vi.mock('@main/core/remote-hosts/production-host-reachability', () => ({
hostReachabilityService: mocks.reachability,
}));
vi.mock('./auto-session-store', () => ({
- listAutoSessionAgentIds: mocks.autoSessionIds,
listAutoSessionSubagents: async () => [],
- setAutoSessionAgent: mocks.setAutoSessionAgent,
setAutoSessionSubagent: vi.fn(),
}));
-vi.mock('@main/lib/logger', () => ({ log: { error: vi.fn() } }));
+vi.mock('./current-watchers', () => ({ currentWatchers: async () => new Set<string>() }));
+vi.mock('@main/lib/logger', () => ({ log: { error: vi.fn(), warn: vi.fn() } }));
vi.mock('@main/core/managed-switch-server/session-readiness', () => ({
onManagedServerUpgraded: (listener: (serverId: string) => void) => mocks.upgraded.push(listener),
}));
-const { autoSessionWatcher } = await import('./auto-session-watcher');
+const { autoSessionWatcher, HOST_SETTLE_MS, RETRY_FIRST_MS, RETRY_MAX_MS } =
+ await import('./auto-session-watcher');
beforeEach(() => {
vi.clearAllMocks();
- mocks.autoSessionIds.mockResolvedValue([]);
mocks.agentById.mockResolvedValue({ id: 'agent' });
mocks.agents.mockResolvedValue([
{ id: 'linked', switchAgentId: 'switch-1' },
@@ -57,6 +54,11 @@ beforeEach(() => {
mocks.location.mockResolvedValue({ sshHost: null });
});
+afterEach(async () => {
+ vi.useRealTimers();
+ await autoSessionWatcher.dispose();
+});
+
it('gives every Switch-linked agent a controller at boot, and only those', async () => {
await autoSessionWatcher.initialize();
expect(mocks.apply.mock.calls).toEqual([['linked', 'restore', 'host']]);
@@ -80,13 +82,6 @@ it('keeps sweeping when one agent’s controller cannot start', async () => {
expect(mocks.apply).toHaveBeenCalledWith('linked', 'restore', 'host');
});
-it('drops a deleted agent from the automatic-session mirror', async () => {
- mocks.autoSessionIds.mockResolvedValue(['gone']);
- mocks.agentById.mockResolvedValue(null);
- await autoSessionWatcher.initialize();
- expect(mocks.setAutoSessionAgent).toHaveBeenCalledWith('gone', false);
-});
-
it('starts a controller whose host was unreachable at boot, once the host comes back', async () => {
// The boot sweep runs once. Without this the agent is off the air until
// Console is restarted, however long the host has been back.
@@ -96,7 +91,12 @@ it('starts a controller whose host was unreachable at boot, once the host comes
await autoSessionWatcher.initialize();
expect(mocks.apply).toHaveBeenCalledTimes(1);
+ vi.useFakeTimers();
mocks.reachability.announce({ current: { sshHost: 'host', status: 'reachable' } });
+ // The sweep now waits for the host to hold still first, so a flapping
+ // tunnel cannot keep triggering it.
+ await vi.advanceTimersByTimeAsync(HOST_SETTLE_MS);
+ vi.useRealTimers();
await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledTimes(2));
// Still a restore: the host returning is not somebody asking for a connection
@@ -115,7 +115,12 @@ it('leaves agents on other hosts alone when one host comes back', async () => {
await autoSessionWatcher.initialize();
mocks.apply.mockClear();
+ vi.useFakeTimers();
mocks.reachability.announce({ current: { sshHost: 'host', status: 'reachable' } });
+ // The sweep now waits for the host to hold still first, so a flapping
+ // tunnel cannot keep triggering it.
+ await vi.advanceTimersByTimeAsync(HOST_SETTLE_MS);
+ vi.useRealTimers();
await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledTimes(1));
expect(mocks.apply).toHaveBeenCalledWith('here', 'restore', 'host');
@@ -137,10 +142,16 @@ it('sweeps again for a host that flaps while its recovery is still running', asy
});
await autoSessionWatcher.initialize();
+ vi.useFakeTimers();
mocks.reachability.announce({ current: { sshHost: 'host', status: 'reachable' } });
+ await vi.advanceTimersByTimeAsync(HOST_SETTLE_MS);
+ vi.useRealTimers();
await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledTimes(2));
+ vi.useFakeTimers();
mocks.reachability.announce({ current: { sshHost: 'host', status: 'unreachable' } });
mocks.reachability.announce({ current: { sshHost: 'host', status: 'reachable' } });
+ await vi.advanceTimersByTimeAsync(HOST_SETTLE_MS);
+ vi.useRealTimers();
arrive();
await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledTimes(3));
@@ -159,11 +170,6 @@ it('does nothing for a host that has only just gone away', async () => {
expect(mocks.apply).not.toHaveBeenCalled();
});
-it('applies the saved settings when asked to reconcile an agent', async () => {
- await autoSessionWatcher.reconcile('agent');
- expect(mocks.apply).toHaveBeenCalledWith('agent', 'explicit', 'host');
-});
-
it('stops everything it hosts when Console closes', async () => {
await autoSessionWatcher.dispose();
expect(mocks.dispose).toHaveBeenCalled();
@@ -202,3 +208,79 @@ it('starts the controllers of a server once an update they were refused for fini
await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledTimes(1));
expect(mocks.apply).toHaveBeenCalledWith('upgraded', 'restore', 'host');
});
+
+it('brings each host up side by side, so a stuck host holds back only its own agents', async () => {
+ mocks.agents.mockResolvedValue([
+ { id: 'stuck', switchAgentId: 'switch-1' },
+ { id: 'after-stuck', switchAgentId: 'switch-2' },
+ { id: 'local', switchAgentId: 'switch-3' },
+ ]);
+ mocks.location.mockImplementation(async (agent: { id: string }) => ({
+ sshHost: agent.id === 'local' ? null : 'wedged-host',
+ }));
+ let release: () => void = () => {};
+ mocks.apply.mockImplementation(async (agentId: string) => {
+ if (agentId === 'stuck')
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ });
+ const boot = autoSessionWatcher.initialize();
+
+ await vi.waitFor(() => expect(mocks.apply).toHaveBeenCalledWith('local', 'restore', 'host'));
+ // One host's agents still go in turn: they share its one SSH connection.
+ expect(mocks.apply).not.toHaveBeenCalledWith('after-stuck', 'restore', 'host');
+ release();
+ await boot;
+ expect(mocks.apply).toHaveBeenCalledWith('after-stuck', 'restore', 'host');
+});
+
+it('tries a controller that could not start again, backing off, until it comes up', async () => {
+ vi.useFakeTimers();
+ mocks.agents.mockResolvedValue([{ id: 'remote', switchAgentId: 'switch-1' }]);
+ mocks.agentById.mockResolvedValue({ id: 'remote', switchAgentId: 'switch-1' });
+ mocks.apply
+ .mockRejectedValueOnce(new Error('SSH exec channel open timed out'))
+ .mockRejectedValueOnce(new Error('SSH exec channel open timed out'))
+ .mockResolvedValue(undefined);
+ await autoSessionWatcher.initialize();
+ expect(mocks.apply).toHaveBeenCalledTimes(1);
+
+ await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS);
+ expect(mocks.apply).toHaveBeenCalledTimes(2);
+ // The second wait is twice the first.
+ await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS);
+ expect(mocks.apply).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS);
+ expect(mocks.apply).toHaveBeenCalledTimes(3);
+
+ // Up now, so nothing more is scheduled.
+ await vi.advanceTimersByTimeAsync(RETRY_MAX_MS * 2);
+ expect(mocks.apply).toHaveBeenCalledTimes(3);
+ expect(mocks.apply.mock.calls.every(([, intent]) => intent === 'restore')).toBe(true);
+});
+
+it('retries a new agent’s controller as a restore, whatever the first ask was', async () => {
+ vi.useFakeTimers();
+ mocks.agentById.mockResolvedValue({ id: 'new', switchAgentId: 'switch-1' });
+ mocks.apply.mockRejectedValueOnce(new Error('Host unreachable')).mockResolvedValue(undefined);
+
+ await autoSessionWatcher.bringUp('new', 'explicit');
+ await vi.advanceTimersByTimeAsync(RETRY_FIRST_MS);
+
+ expect(mocks.apply.mock.calls).toEqual([
+ ['new', 'explicit', 'host'],
+ ['new', 'restore', 'host'],
+ ]);
+});
+
+it('stops retrying for an agent that has been removed', async () => {
+ vi.useFakeTimers();
+ mocks.apply.mockRejectedValue(new Error('Host unreachable'));
+ await autoSessionWatcher.bringUp('gone', 'restore');
+ mocks.agentById.mockResolvedValue(null);
+
+ await vi.advanceTimersByTimeAsync(RETRY_MAX_MS * 4);
+
+ expect(mocks.apply).toHaveBeenCalledTimes(1);
+});
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 71565d0be..4d43c971b 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
@@ -4,39 +4,47 @@ import { getAgents } from '@main/core/agents/getAgents';
import { onManagedServerUpgraded } from '@main/core/managed-switch-server/session-readiness';
import type { HostReachabilityChange } from '@main/core/remote-hosts/host-reachability-service';
import { hostReachabilityService } from '@main/core/remote-hosts/production-host-reachability';
-import { disposeLocalHosts } from '@main/core/sdk-host/local-host';
+import { disposeLocalHosts, type WatcherIntent } from '@main/core/sdk-host/local-host';
import { applyControllerState, configureSharedWatcher } from '@main/core/sdk-host/shared-watcher';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
-import {
- listAutoSessionAgentIds,
- listAutoSessionSubagents,
- setAutoSessionAgent,
- setAutoSessionSubagent,
-} from './auto-session-store';
+import { listAutoSessionSubagents, setAutoSessionSubagent } from './auto-session-store';
+import { currentWatchers } from './current-watchers';
type Subagent = { parentAgentId: string; name: string };
+/**
+ * How long a host must stay reachable before its recovery sweep runs.
+ *
+ * A tunnel that drops and returns every 10–30 seconds — which is what an
+ * overloaded SSH tunnel does — announced every return, and each one started a
+ * full sweep over the host's agents. The sweep is the most expensive thing
+ * Console does to a host, so instability triggered the work most likely to
+ * make it worse. Waiting for the host to hold still first means a flap costs
+ * nothing, and a genuine recovery is delayed by a couple of seconds.
+ */
+export const HOST_SETTLE_MS = 3_000;
+/** The wait before trying again a controller that could not be brought up. */
+export const RETRY_FIRST_MS = 30_000;
+/** Retries back off by doubling, up to this. */
+export const RETRY_MAX_MS = 5 * 60_000;
+
class AutoSessionWatcher {
private watchingHosts = false;
private watchingUpgrades = false;
private readonly recovering = new Map<string, { again: boolean }>();
+ private readonly retries = new Map<string, ReturnType<typeof setTimeout>>();
+ private readonly settling = new Map<string, ReturnType<typeof setTimeout>>();
/**
- * Brings up a controller for every agent linked to Switch, whether or not it
- * may start sessions: an agent is reachable because it exists, and the
- * auto-start setting only decides what its controller does with a message it
- * is addressed in.
- *
- * Each server's agents are brought up on their own, because a controller
- * waits for its managed server to finish upgrading and that must not hold
- * back the agents of every other server.
+ * Brings up a controller for every agent linked to Switch. Each server's
+ * agents are brought up on their own, because a controller waits for its
+ * managed server to finish upgrading and that must not hold back the agents
+ * of every other server.
*/
async initialize(): Promise<void> {
this.watchHostRecovery();
this.watchServerUpgrades();
- for (const agentId of await listAutoSessionAgentIds())
- if (!(await getAgentById(agentId))) await setAutoSessionAgent(agentId, false);
const agents = await getAgents();
const subagents: Subagent[] = [];
for (const subagent of await listAutoSessionSubagents()) {
@@ -77,22 +85,40 @@ class AutoSessionWatcher {
}
}
+ /**
+ * Each host is asked once what its watchers are already doing, and only the
+ * agents that need something are brought up — usually none. A bring-up is
+ * about a dozen SSH round trips whose normal outcome is the launcher
+ * deciding to leave a healthy watcher alone, so twenty agents meant ~260
+ * round trips to discover twenty times that there was nothing to do. On a
+ * host that keeps reconnecting, that ran again on every recovery.
+ *
+ * Each host's agents are still brought up in turn, and the hosts side by side:
+ * a host whose connection is slow or wedged holds back only its own agents,
+ * never another host's or this machine's, and one host is not sent every
+ * agent's launch at once over its one connection.
+ *
+ * Restoring a controller an earlier run was already meant to be holding is
+ * not a decision to reclaim a connection something else has since taken: one
+ * that stood down stays down until someone asks for it by name.
+ */
private async startControllers(agents: Agent[], subagents: Subagent[]): Promise<void> {
+ const hosts = new Map<string, Agent[]>();
for (const agent of agents) {
if (!agent.switchAgentId) continue;
- try {
- // Restoring a controller an earlier run was already meant to be
- // holding, not a decision to reclaim a connection something else has
- // since taken: one that stood down stays down until someone asks for it
- // by name.
- await applyControllerState(agent.id, 'restore', 'host');
- } catch (error) {
- log.error('Shared SDK watcher could not start', {
- agentId: agent.id,
- error: String(error),
- });
- }
+ const location = await getAgentLocation(agent).catch(() => null);
+ const host = location?.sshHost ?? '';
+ hosts.set(host, [...(hosts.get(host) ?? []), agent]);
}
+ await Promise.all(
+ [...hosts.values()].map(async (members) => {
+ const current = await currentWatchers(members);
+ for (const agent of members) {
+ if (current.has(agent.id)) continue;
+ await this.bringUp(agent.id, 'restore');
+ }
+ })
+ );
for (const { parentAgentId, name } of subagents) {
try {
await this.startForSubagent(parentAgentId, name);
@@ -116,10 +142,30 @@ class AutoSessionWatcher {
if (this.watchingHosts) return;
this.watchingHosts = true;
hostReachabilityService.on('change', ({ current }: HostReachabilityChange) => {
- if (current.status === 'reachable') void this.restoreHost(current.sshHost);
+ if (current.status === 'reachable') this.scheduleRestore(current.sshHost);
+ // A host that has gone away again cancels the sweep it had not earned
+ // yet: the point of waiting is to not sweep a host that cannot hold a
+ // connection.
+ else clearTimeout(this.settling.get(current.sshHost));
});
}
+ /**
+ * Run the recovery sweep once the host has stayed reachable for
+ * `HOST_SETTLE_MS`, restarting that wait on every further announcement.
+ * A host flapping faster than that never sweeps, which is correct: there is
+ * nothing to restore onto a connection that keeps dying.
+ */
+ private scheduleRestore(sshHost: string): void {
+ clearTimeout(this.settling.get(sshHost));
+ const timer = setTimeout(() => {
+ this.settling.delete(sshHost);
+ void this.restoreHost(sshHost);
+ }, HOST_SETTLE_MS);
+ timer.unref();
+ this.settling.set(sshHost, timer);
+ }
+
private async restoreHost(sshHost: string): Promise<void> {
const running = this.recovering.get(sshHost);
// A host that goes away and returns while its sweep is still running has
@@ -148,21 +194,68 @@ class AutoSessionWatcher {
if (!agent.switchAgentId) continue;
const location = await getAgentLocation(agent).catch(() => null);
if (location?.sshHost !== sshHost) continue;
- try {
- // A host coming back is not somebody asking for a connection back, so
- // a controller that stood down after a takeover stays down and one
- // stopped by hand stays stopped.
- await applyControllerState(agent.id, 'restore', 'host');
- } catch (error) {
- log.error('Shared SDK watcher could not start after its host returned', {
- agentId: agent.id,
- error: String(error),
- });
- }
+ // A host coming back is not somebody asking for a connection back, so a
+ // controller that stood down after a takeover stays down and one stopped
+ // by hand stays stopped.
+ await this.bringUp(agent.id, 'restore');
}
}
+ /**
+ * Puts an agent's controller in the state its settings describe, and keeps
+ * trying until it gets there. A controller that cannot be brought up —
+ * its host unreachable, its connection wedged, its server mid-upgrade — is
+ * tried again after `RETRY_FIRST_MS`, doubling up to `RETRY_MAX_MS`, until
+ * it comes up or the agent is gone. Nothing else would try it again, so
+ * without this the agent stays off the air until something unrelated, such
+ * as a host reconnecting or Console restarting, happens to reapply it.
+ *
+ * Retries are restores whatever the first attempt was: only the first is
+ * somebody's request.
+ */
+ async bringUp(agentId: string, intent: WatcherIntent): Promise<void> {
+ this.cancelRetry(agentId);
+ try {
+ await applyControllerState(agentId, intent, 'host');
+ } catch (error) {
+ log.error('Shared SDK watcher could not start; will retry', {
+ agentId,
+ error: String(error),
+ });
+ this.scheduleRetry(agentId, 0);
+ }
+ }
+
+ private scheduleRetry(agentId: string, attempt: number): void {
+ const delay = Math.min(RETRY_FIRST_MS * 2 ** attempt, RETRY_MAX_MS);
+ const timer = setTimeout(() => {
+ if (this.retries.get(agentId) !== timer) return;
+ this.retries.delete(agentId);
+ void (async () => {
+ if (!(await getAgentById(agentId))?.switchAgentId) return;
+ try {
+ await applyControllerState(agentId, 'restore', 'host');
+ } catch (error) {
+ log.warn('Shared SDK watcher still could not start; will retry', {
+ agentId,
+ attempt: attempt + 1,
+ error: String(error),
+ });
+ if (!this.retries.has(agentId)) this.scheduleRetry(agentId, attempt + 1);
+ }
+ })();
+ }, delay);
+ timer.unref?.();
+ this.retries.set(agentId, timer);
+ }
+
+ private cancelRetry(agentId: string): void {
+ clearTimeout(this.retries.get(agentId));
+ this.retries.delete(agentId);
+ }
+
stopForAgent(agentId: string): Promise<void> {
+ this.cancelRetry(agentId);
return configureSharedWatcher(agentId, { connected: false, spawning: false }, 'restore');
}
startForSubagent(agentId: string, name: string): Promise<void> {
@@ -171,23 +264,11 @@ class AutoSessionWatcher {
stopForSubagent(agentId: string, name: string): Promise<void> {
return configureSharedWatcher(agentId, { connected: false, spawning: false }, 'restore', name);
}
- /**
- * Applies the saved auto-start setting. The controller stays connected either
- * way — only Stop, or deleting the agent, takes an agent's connection away.
- */
- reconcile(agentId: string): Promise<void> {
- return applyControllerState(agentId, 'explicit', 'host');
- }
- reconcileSubagent(agentId: string, name: string, enabled: boolean): Promise<void> {
- return configureSharedWatcher(
- agentId,
- { connected: enabled, spawning: enabled },
- 'explicit',
- name
- );
- }
/** Stops every locally hosted watcher and session, so none outlives Console. */
dispose(): Promise<void> {
+ for (const agentId of [...this.retries.keys()]) this.cancelRetry(agentId);
+ for (const timer of this.settling.values()) clearTimeout(timer);
+ this.settling.clear();
return disposeLocalHosts();
}
}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.test.ts
new file mode 100644
index 000000000..44fe3b04b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Deciding which agents a startup sweep can leave alone.
+ *
+ * The value is skipping work; the risk is skipping an agent that needed it,
+ * because nothing notices an agent that quietly never comes up. So the
+ * property under test is mostly the failure behaviour: anything unknown,
+ * broken or unreachable must produce an empty set, meaning "bring everyone
+ * up" — the behaviour we have today.
+ */
+
+import { expect, it, vi, beforeEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ location: vi.fn(),
+ connect: vi.fn(),
+ watchers: vi.fn(),
+ stopped: vi.fn(async () => [] as string[]),
+ bundlePath: vi.fn(() => '/local/shared-host.mjs'),
+ readFile: vi.fn(async () => Buffer.from('bundle-contents')),
+ debug: vi.fn(),
+}));
+
+vi.mock('node:fs/promises', () => ({ readFile: mocks.readFile }));
+vi.mock('@main/core/agent-runtime/impl/resolve-sidecar-bundle', () => ({
+ resolveSharedHostBundlePath: mocks.bundlePath,
+}));
+vi.mock('@main/core/agents/agent-location', () => ({ getAgentLocation: mocks.location }));
+vi.mock('@main/core/agents/connect-remote-agent', () => ({ connectRemoteAgent: mocks.connect }));
+vi.mock('@main/core/sdk-host/host-watchers', async () => {
+ const actual = await vi.importActual<object>('@main/core/sdk-host/host-watchers');
+ return { ...actual, listHostWatchers: mocks.watchers };
+});
+vi.mock('./auto-session-store', () => ({ listStoppedControllerAgentIds: mocks.stopped }));
+vi.mock('@main/lib/logger', () => ({ log: { debug: mocks.debug, error: vi.fn() } }));
+
+const { currentWatchers } = await import('./current-watchers');
+const { createHash } = await import('node:crypto');
+
+const BUNDLE_FILE = `shared-host-${createHash('sha256').update('bundle-contents').digest('hex')}.mjs`;
+
+const agents = [
+ { id: 'a1', switchAgentId: 'switch-a1', locationId: 'loc' },
+ { id: 'a2', switchAgentId: 'switch-a2', locationId: 'loc' },
+] as never[];
+
+function onHost(entries: Record<string, { running: boolean; build: string | null }>) {
+ mocks.watchers.mockResolvedValue(
+ new Map(
+ Object.entries(entries).map(([agentId, e]) => [
+ agentId,
+ {
+ agentId,
+ root: `/r/${agentId}`,
+ running: e.running,
+ build: e.build,
+ enabled: true,
+ spawn: true,
+ stoodDown: false,
+ },
+ ])
+ )
+ );
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.location.mockResolvedValue({ sshHost: 'vm-1' });
+ mocks.connect.mockResolvedValue({ ctx: { exec: vi.fn() } });
+ mocks.stopped.mockResolvedValue([]);
+ mocks.bundlePath.mockReturnValue('/local/shared-host.mjs');
+ mocks.readFile.mockResolvedValue(Buffer.from('bundle-contents'));
+});
+
+it('skips agents already running the bundle we would install', async () => {
+ onHost({
+ 'switch-a1': { running: true, build: `/remote/${BUNDLE_FILE}` },
+ 'switch-a2': { running: true, build: `/remote/${BUNDLE_FILE}` },
+ });
+
+ expect([...(await currentWatchers(agents))].sort()).toEqual(['a1', 'a2']);
+});
+
+it('brings up the ones on an older build, leaving the current one alone', async () => {
+ onHost({
+ 'switch-a1': { running: true, build: `/remote/${BUNDLE_FILE}` },
+ 'switch-a2': { running: true, build: '/remote/shared-host-older.mjs' },
+ });
+
+ expect([...(await currentWatchers(agents))]).toEqual(['a1']);
+});
+
+it('asks the host exactly once for the whole group', async () => {
+ onHost({});
+ await currentWatchers(agents);
+ expect(mocks.watchers).toHaveBeenCalledTimes(1);
+});
+
+it('does not skip an agent whose controller is meant to be stopped', async () => {
+ // Its watch flags would have to be rewritten, so the bring-up is not a
+ // no-op and skipping it would silently leave the old intent in place.
+ mocks.stopped.mockResolvedValue(['a2']);
+ onHost({
+ 'switch-a1': { running: true, build: `/remote/${BUNDLE_FILE}` },
+ 'switch-a2': { running: true, build: `/remote/${BUNDLE_FILE}` },
+ });
+
+ expect([...(await currentWatchers(agents))]).toEqual(['a1']);
+});
+
+it('skips nothing when the host cannot be reached', async () => {
+ mocks.connect.mockRejectedValue(new Error('host unreachable'));
+
+ expect(await currentWatchers(agents)).toEqual(new Set());
+});
+
+it('skips nothing when the status command fails', async () => {
+ mocks.watchers.mockRejectedValue(new Error('node: command not found'));
+
+ expect(await currentWatchers(agents)).toEqual(new Set());
+});
+
+it('skips nothing for local agents', async () => {
+ // No SSH connection to spare, so the check would cost more than it saves.
+ mocks.location.mockResolvedValue({ sshHost: null });
+
+ expect(await currentWatchers(agents)).toEqual(new Set());
+ expect(mocks.watchers).not.toHaveBeenCalled();
+});
+
+it('handles an empty group without touching the host', async () => {
+ expect(await currentWatchers([])).toEqual(new Set());
+ expect(mocks.connect).not.toHaveBeenCalled();
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.ts b/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.ts
new file mode 100644
index 000000000..eac94ba26
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-rooms/current-watchers.ts
@@ -0,0 +1,68 @@
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { resolveSharedHostBundlePath } from '@main/core/agent-runtime/impl/resolve-sidecar-bundle';
+import { getAgentLocation } from '@main/core/agents/agent-location';
+import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
+import { listHostWatchers, watcherIsCurrent } from '@main/core/sdk-host/host-watchers';
+import { log } from '@main/lib/logger';
+import type { Agent } from '@shared/core/agents/agents';
+import { listStoppedControllerAgentIds } from './auto-session-store';
+
+/**
+ * Which of these agents already have the watcher a bring-up would give them.
+ *
+ * One command for the whole host, answering for every agent on it, so the
+ * expensive per-agent path runs only where it would change something. On a
+ * settled host that is nobody, and the sweep costs one round trip instead of
+ * roughly thirteen per agent.
+ *
+ * Every agent must be on the same host — the caller has already grouped them,
+ * and the connection being shared per host is the whole point.
+ *
+ * **Returns agents to skip, never agents to act on.** If anything goes wrong
+ * — the host is unreachable, the script fails, the agents are local — the
+ * answer is the empty set and every agent takes the normal path. A wrong
+ * "skip" leaves an agent off the air with nothing to notice it; a wrong
+ * "bring up" costs round trips we are already paying today. Only one of those
+ * is worth risking, so the failure mode is deliberately the expensive one.
+ */
+export async function currentWatchers(members: Agent[]): Promise<Set<string>> {
+ const first = members[0];
+ if (!first) return new Set();
+
+ try {
+ const location = await getAgentLocation(first);
+ // Local agents are cheap to bring up — no SSH, no channel budget — so the
+ // check would cost more than it saves.
+ if (!location.sshHost) return new Set();
+
+ const { ctx } = await connectRemoteAgent(first);
+ const [statuses, stopped, bundle] = await Promise.all([
+ listHostWatchers(ctx),
+ listStoppedControllerAgentIds(),
+ readFile(resolveSharedHostBundlePath()),
+ ]);
+ const bundleFile = `shared-host-${createHash('sha256').update(bundle).digest('hex')}.mjs`;
+
+ const skip = new Set<string>();
+ for (const agent of members) {
+ if (!agent.switchAgentId) continue;
+ // `applyControllerState` derives both flags from the same bit, so this
+ // has to match it or a skip would hide a change of intent.
+ const connected = !stopped.includes(agent.id);
+ const status = statuses.get(agent.switchAgentId);
+ if (watcherIsCurrent(status, { bundleFile, enabled: connected, spawn: connected }))
+ skip.add(agent.id);
+ }
+ return skip;
+ } catch (error) {
+ // Not an error for the caller: it simply means nothing is skipped, and
+ // the bring-up that follows will report the real failure with its own
+ // context and retry policy.
+ log.debug?.('Could not read the host’s watchers; bringing every agent up', {
+ agentId: first.id,
+ error: String(error),
+ });
+ return new Set();
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 9c3c761ee..c5467bbd2 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -448,67 +448,6 @@ export async function fetchAgentRooms(
}));
}
-/** The agent's current known-agent options (the last validated payload) and
- * its derived connection model, from `GET /agents/{id}`. */
-export type RemoteAgentOptions = {
- options: Record<string, unknown>;
- connectionModel: string | null;
-};
-
-/**
- * Fetch the agent's current known-agent options and connection model. Returns
- * empty options for agents with no known-agent type. Used to read-modify-write
- * the options payload (the PATCH endpoint is a full replace, not a merge).
- */
-export async function fetchAgentOptions(
- server: SwitchServer,
- agentId: string
-): Promise<RemoteAgentOptions> {
- const res = await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}`, {
- authenticated: true,
- });
- const json = (await res.json()) as {
- known_agent_options?: Record<string, unknown> | null;
- connection_model?: string | null;
- };
- return {
- options: json.known_agent_options ?? {},
- connectionModel: json.connection_model ?? null,
- };
-}
-
-/**
- * Replace a known-agent's options (`PATCH /agents/{id}/options`). The gateway
- * re-derives the `integration_profile` from the new options, so this is the one
- * write path that keeps options and connection model in sync. The body must be
- * the FULL options payload — callers read current options first and merge.
- */
-export async function updateKnownAgentOptions(
- server: SwitchServer,
- agentId: string,
- options: Record<string, unknown>
-): Promise<void> {
- await gatewayFetch(server, `/agents/${encodeURIComponent(agentId)}/options`, {
- authenticated: true,
- method: 'PATCH',
- body: { options },
- });
-}
-
-/**
- * Toggle the agent's `auto_session` option, preserving all other options.
- * Read-modify-writes through `updateKnownAgentOptions` so the gateway rebuilds
- * the connection model (`auto_session` ⇄ `session_addressable`).
- */
-export async function setAutoSession(
- server: SwitchServer,
- agentId: string,
- enabled: boolean
-): Promise<void> {
- const { options } = await fetchAgentOptions(server, agentId);
- await updateKnownAgentOptions(server, agentId, { ...options, auto_session: enabled });
-}
-
/**
* Fetch an agent's scoped addressing policy (CHOO-1585) from `GET /agents/{id}`.
* Returns null when the agent is open (no policy set).
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
index 711f3b496..a2639a67b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx
@@ -374,7 +374,6 @@ export const AddAgentModal = observer(function AddAgentModal({
displayName: form.displayName.trim() || null,
instructions: form.instructions,
iconUrl: form.iconUrl,
- autoSession: form.autoSession,
autoApprove: form.autoApprove,
definitionAttributes: advancedAttributesRef.current,
providerConfig: launchProfileConfigRef.current,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
index 428feb0e5..7b179292a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx
@@ -148,28 +148,6 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({
/>
{settingsOpen && (
<FieldGroup className="pt-3">
- <Field>
- <label className="-mx-2 flex cursor-pointer items-start justify-between gap-3 rounded-md px-2 py-1.5 transition-colors hover:bg-[var(--sel-soft)]">
- <span className="flex flex-col gap-0.5">
- <span className="flex items-center gap-1.5 text-sm">
- Auto-create a session on notify
- <InfoTooltip
- label="More info about auto-creating a session"
- content="Switch Console watches this agent's Switch rooms and starts a session — connected to the room and ready to reply — whenever it's addressed with no session running."
- />
- </span>
- <span className="text-xs text-foreground-muted">
- Start a session when this agent is addressed.
- </span>
- </span>
- <Switch
- className="mt-0.5"
- checked={form.autoSession}
- onCheckedChange={(checked) => form.setAutoSession(checked)}
- />
- </label>
- </Field>
-
<Field>
<label className="-mx-2 flex cursor-pointer items-start justify-between gap-3 rounded-md px-2 py-1.5 transition-colors hover:bg-[var(--sel-soft)]">
<span className="flex flex-col gap-0.5">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
index 14501829f..88b3f3f54 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts
@@ -54,7 +54,6 @@ export function useConfigureAgentForm() {
// with none runs on its provider's defaults, and the description stands in
// where a provider needs a prompt.
const [instructions, setInstructions] = useState('');
- const [autoSession, setAutoSession] = useState(true);
const [autoApprove, setAutoApproveRaw] = useState(false);
const [autoApproveTouched, setAutoApproveTouched] = useState(false);
// Scoped addressing policy (CHOO-1585). null = open; a new agent starts
@@ -141,8 +140,6 @@ export function useConfigureAgentForm() {
setDescription,
instructions,
setInstructions,
- autoSession,
- setAutoSession,
autoApprove,
setAutoApprove,
suggestAutoApprove,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx
deleted file mode 100644
index 37661a7d0..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/auto-session-settings-section.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { useState } from 'react';
-import { InfoTooltip } from '@renderer/features/settings/components/InfoTooltip';
-import { rpc } from '@renderer/lib/ipc';
-import { Field, FieldDescription, FieldTitle } from '@renderer/lib/ui/field';
-import { Switch } from '@renderer/lib/ui/switch';
-import { log } from '@renderer/utils/logger';
-
-/**
- * Per-Switch-agent "auto-create session on notify" toggle. Unlike the rest of
- * the location settings form (persisted to .switchdash.json / DB on Save), this
- * flips the agent's gateway connection model immediately on toggle — there is
- * no local config to stage. Renders one row per Switch-linked agent in the
- * location; hidden entirely when the location has none.
- */
-export function AutoSessionSettingsSection({
- locationId,
- agentId,
-}: {
- locationId: string;
- /** Scope to a single agent (e.g. a subagent's own row); omit for every agent. */
- agentId?: string;
-}) {
- const { data: agents } = useQuery({
- queryKey: ['location-agents', locationId],
- queryFn: () => rpc.agents.getAgents(locationId),
- });
-
- const switchAgents = (agents ?? [])
- .filter((a) => a.serverId && a.switchAgentId)
- .filter((a) => !agentId || a.id === agentId);
- if (switchAgents.length === 0) return null;
- // The agent name only disambiguates when a location has more than one agent;
- // for the common single-agent case the section title already identifies it, so
- // the toggle sits inline with the title instead of in a redundant named row.
- const single = switchAgents.length === 1 ? switchAgents[0] : null;
-
- return (
- <Field>
- <div className="flex items-center justify-between gap-3">
- <FieldTitle>
- <span className="flex items-center gap-1.5">
- Auto-create a session on notify
- <InfoTooltip
- label="More info about auto-creating a session"
- content="Switch Console holds this agent's room connection either way. With this on it also starts a session — connected to the room and ready to reply — whenever the agent is addressed with none running; with it off the agent stays addressable and answers that it has no session."
- />
- </span>
- </FieldTitle>
- {single && <AutoSessionSwitch agentId={single.id} />}
- </div>
- <FieldDescription className="text-foreground-muted">
- Start a session when this agent is addressed.
- </FieldDescription>
- {!single && (
- <div className="flex flex-col gap-2">
- {switchAgents.map((agent) => (
- <div
- key={agent.id}
- className="flex items-center justify-between gap-3 rounded-md border border-border px-2 py-1.5"
- >
- <AgentLabel name={agent.name} />
- <AutoSessionSwitch agentId={agent.id} />
- </div>
- ))}
- </div>
- )}
- </Field>
- );
-}
-
-/** Renders an agent's Switch name — the stored one, which is what was
- * registered on the server. */
-function AgentLabel({ name }: { name: string }) {
- return <span className="truncate text-sm">{name}</span>;
-}
-
-function AutoSessionSwitch({ agentId }: { agentId: string }) {
- const queryClient = useQueryClient();
- const [pending, setPending] = useState(false);
-
- const { data: enabled, isLoading } = useQuery({
- queryKey: ['agent-auto-session', agentId],
- queryFn: () => rpc.agents.getAgentAutoSession({ agentId }),
- });
-
- const mutation = useMutation({
- mutationFn: (next: boolean) => rpc.agents.setAgentAutoSession({ agentId, enabled: next }),
- onMutate: (next) => {
- setPending(true);
- queryClient.setQueryData(['agent-auto-session', agentId], next);
- },
- onError: (error, next) => {
- // Revert the optimistic update on failure.
- queryClient.setQueryData(['agent-auto-session', agentId], !next);
- log.error('Failed to update auto_session for agent', { agentId, error });
- },
- onSettled: () => {
- setPending(false);
- void queryClient.invalidateQueries({ queryKey: ['agent-auto-session', agentId] });
- },
- });
-
- return (
- <Switch
- checked={enabled === true}
- disabled={isLoading || pending}
- onCheckedChange={(checked) => mutation.mutate(checked)}
- />
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
index d5a8c40f0..6a9e7164a 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
@@ -62,17 +62,16 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {
(deployed ? (
<p className="text-sm text-foreground-muted">
The sidecar is a background service on the SSH host that holds this agent’s room
- connection while Console is closed, and starts sessions for it when “Auto-create a
- session on notify” is on. Manage conversations in Sessions below. Update and Restart
- reload the service. Stop takes the agent off the air until you press Start; existing
- sessions continue running.
+ connection while Console is closed, and starts a session for it whenever it is
+ addressed. Manage conversations in Sessions below. Update and Restart reload the
+ service. Stop takes the agent off the air until you press Start; existing sessions
+ continue running.
</p>
) : (
<p className="text-sm text-foreground-muted">
Console holds this agent’s room connection itself, and starts a session when the agent
- is addressed with none running if “Auto-create a session on notify” is on. It runs
- inside Console, so quitting Console takes the agent off the air along with the sessions
- it started.
+ is addressed with none running. It runs inside Console, so quitting Console takes the
+ agent off the air along with the sessions it started.
</p>
))}
{query.isPending && <p className="text-sm">Checking the watcher…</p>}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
index bdd7c521c..3ff9eae57 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
@@ -5,7 +5,6 @@ import { SectionLabel } from '@renderer/features/locations/components/main-panel
import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';
import { AgentAdvancedSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section';
import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';
-import { AutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-session-settings-section';
import { ProviderSignInSettingsSection } from '@renderer/features/locations/components/settings-view/sections/provider-sign-in-settings-section';
import {
asMounted,
@@ -46,7 +45,6 @@ export const SettingsPanel = observer(function SettingsPanel() {
<section className="flex flex-col gap-6">
<SectionLabel>General</SectionLabel>
<ProviderSignInSettingsSection locationId={locationId} agentId={agentId} />
- <AutoSessionSettingsSection locationId={locationId} agentId={agentId} />
<AutoApproveSettingsSection locationId={locationId} agentId={agentId} />
<AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />
</section>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
index 15f65c9aa..5d46d8ccc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/templates/template-use-view.tsx
@@ -806,7 +806,6 @@ const TemplateUsePanel = observer(function TemplateUsePanel() {
? setup.displayName.trim()
: null,
iconUrl: null,
- autoSession: true,
// Nobody sits at a host's terminal to approve tool calls.
autoApprove: sshHost !== null,
instructions: slot.entry.instructions,