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(switchdash): honor bypass toggle on remote + clear stale session guard (CHOO-1664) (#63)

Louis Amaudruz17801cd56e27
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
index 9ad935dac..28aea76c4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
@@ -21,15 +21,18 @@ export async function ensureAgentSidecar(params: {
/** Absolute remote repo dir; the agent's Switch creds + bundle live under it. */
repoDir: string;
deeplinkScheme: string;
+ /** The agent's bypass-permissions setting, baked into the auto-start launch spec. */
+ autoApprove: boolean;
ctx: IExecutionContext;
connectionId: string;
host: SidecarHost;
}): Promise<SidecarEndpoint> {
- const { providerId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;
+ const { providerId, repoDir, deeplinkScheme, autoApprove, ctx, connectionId, host } = params;
const launchSpec = await generateAgentLaunchSpec({
providerId,
remoteRepoDir: repoDir,
deeplinkScheme,
+ autoApprove,
ctx,
connectionId,
});
@@ -54,15 +57,19 @@ export async function probeAgentSidecar(params: {
providerId: string;
repoDir: string;
deeplinkScheme: string;
+ /** The agent's bypass-permissions setting. Probe never writes the spec, so this
+ * only shapes the (unused) config; pass the real value for consistency. */
+ autoApprove: boolean;
ctx: IExecutionContext;
connectionId: string;
host: SidecarHost;
}): Promise<SidecarEndpoint | null> {
- const { providerId, repoDir, deeplinkScheme, ctx, connectionId, host } = params;
+ const { providerId, repoDir, deeplinkScheme, autoApprove, ctx, connectionId, host } = params;
const launchSpec = await generateAgentLaunchSpec({
providerId,
remoteRepoDir: repoDir,
deeplinkScheme,
+ autoApprove,
ctx,
connectionId,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
index ae7af288c..3b2cbc7c5 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
@@ -55,6 +55,12 @@ vi.mock('@main/core/dependencies/host-dependency-store', () => ({
},
}));
+// Stubbed so importing the runtime doesn't pull in the DB client (no Electron
+// `app` in tests). launchSidecar reads the agent's autoApprove for the spec.
+vi.mock('@main/core/agents/getAgentById', () => ({
+ getAgentById: vi.fn(async () => ({ autoApprove: false })),
+}));
+
vi.mock('@main/core/providers/plugin-registry', () => ({
getPlugin: vi.fn((id: string) => ({
metadata: { id },
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index fd1004ba1..b59ebd34e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -3,6 +3,7 @@ import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';
import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';
import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';
import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
+import { getAgentById } from '@main/core/agents/getAgentById';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
import type { FileSystemProvider } from '@main/core/fs/types';
@@ -197,10 +198,14 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
// One agent-scoped sidecar serves every session on the VM (this one and any
// the sidecar's own watcher auto-starts) — ensure it is running and point
// this session's hooks at its shared hook server. Reattaches if already up.
+ // The launch spec governs the watcher's auto-started sessions, so it carries
+ // the agent's bypass-permissions setting (not this UI session's).
+ const agent = await getAgentById(session.agentId);
const endpoint = await ensureAgentSidecar({
providerId: session.providerId,
repoDir: this.sessionPath,
deeplinkScheme: DEEPLINK_SCHEME,
+ autoApprove: agent?.autoApprove ?? false,
ctx: this.ctx,
connectionId: this.connectionId,
host: this.createSidecarHost(),
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
index a3d628089..b214bec7e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts
@@ -10,6 +10,7 @@ import { getAgents } from './getAgents';
import { onboardAgent } from './onboard-agent';
import { renameAgent } from './renameAgent';
import { resetRemoteAgent } from './reset-remote-agent';
+import { setAgentAutoApprove, type AgentAutoApproveParams } from './setAgentAutoApprove';
import {
getAgentAutoSession,
setAgentAutoSession,
@@ -31,6 +32,8 @@ export const agentsController = createRPCController({
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/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
new file mode 100644
index 000000000..5a4ee7f89
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts
@@ -0,0 +1,43 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const buildCommand = vi.fn(() => ({ command: 'claude', args: ['--x'], env: { E: '1' } }));
+
+vi.mock('@main/core/providers/plugin-registry', () => ({
+ getPlugin: () => ({
+ behavior: { prompt: { buildCommand } },
+ capabilities: { hostDependency: { binaryNames: ['claude'] } },
+ }),
+}));
+vi.mock('@main/core/agent-runtime/impl/resolve-agent-executable', () => ({
+ resolveAgentExecutable: vi.fn(async () => '/usr/bin/claude'),
+}));
+vi.mock('@main/core/settings/provider-settings-service', () => ({
+ providerOverrideSettings: { getItem: vi.fn(async () => undefined) },
+}));
+vi.mock('@main/core/dependencies/host-dependency-store', () => ({ hostDependencyStore: {} }));
+
+import { generateAgentLaunchSpec } from './generate-agent-launch-spec';
+
+const baseParams = {
+ providerId: 'claude',
+ remoteRepoDir: '/home/agent/repo',
+ deeplinkScheme: 'switchdash',
+ ctx: {} as never,
+ connectionId: 'conn-1',
+};
+
+describe('generateAgentLaunchSpec', () => {
+ beforeEach(() => buildCommand.mockClear());
+
+ // The bug (CHOO-1664): autoApprove was hardcoded true, so the remote watcher's
+ // auto-started sessions always bypassed permissions regardless of the setting.
+ it('forwards autoApprove: true to the provider buildCommand', async () => {
+ await generateAgentLaunchSpec({ ...baseParams, autoApprove: true });
+ expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ autoApprove: true }));
+ });
+
+ it('forwards autoApprove: false (no longer hardcoded on)', async () => {
+ await generateAgentLaunchSpec({ ...baseParams, autoApprove: false });
+ expect(buildCommand).toHaveBeenCalledWith(expect.objectContaining({ autoApprove: false }));
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
index 3e9f3169c..d6bfb1b00 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
@@ -21,19 +21,21 @@ function parseExtraArgs(value: string | undefined): string[] {
* prompt). The VM watcher — which has no plugin registry — substitutes those
* tokens per spawn, so all provider knowledge stays here in switchdash.
*
- * Auto-started sessions always run with autoApprove: a headless VM session has
- * no operator to answer permission prompts, matching the local auto-session
- * watcher's `autoApprove: true`.
+ * `autoApprove` is the agent's per-agent bypass-permissions setting, baked into
+ * the spec's argv so the VM watcher's auto-started sessions honor it (CHOO-1664)
+ * — mirroring the local auto-session watcher, which reads the same setting.
*/
export async function generateAgentLaunchSpec(params: {
providerId: string;
/** Absolute remote working dir the agent runs in. */
remoteRepoDir: string;
deeplinkScheme: string;
+ /** The agent's bypass-permissions setting, applied to auto-started sessions. */
+ autoApprove: boolean;
ctx: IExecutionContext;
connectionId: string;
}): Promise<AgentLaunchSpec> {
- const { providerId, remoteRepoDir, deeplinkScheme, ctx, connectionId } = params;
+ const { providerId, remoteRepoDir, deeplinkScheme, autoApprove, ctx, connectionId } = params;
const plugin = getPlugin(providerId);
if (!plugin.behavior.prompt) {
throw new Error(
@@ -54,7 +56,7 @@ export async function generateAgentLaunchSpec(params: {
const agentCommand = plugin.behavior.prompt.buildCommand({
cli,
extraArgs: parseExtraArgs(providerConfig?.extraArgs),
- autoApprove: true,
+ autoApprove,
initialPrompt: INITIAL_PROMPT_PLACEHOLDER,
sessionId: SESSION_ID_PLACEHOLDER,
providerSessionId: undefined,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
index 71fb8ac46..7063e284f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts
@@ -355,6 +355,7 @@ class RemoteSessionReconciler {
providerId: agent.providerId,
repoDir: conn.remoteRepoDir,
deeplinkScheme: DEEPLINK_SCHEME,
+ autoApprove: agent.autoApprove,
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
index ee9fcc34c..ddeddaca0 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
@@ -113,6 +113,7 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {
providerId: agent.providerId,
repoDir: remoteRepoDir,
deeplinkScheme: DEEPLINK_SCHEME,
+ autoApprove: agent.autoApprove,
ctx,
connectionId,
host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
index 1e8df7079..b76792d56 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts
@@ -45,6 +45,7 @@ async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<s
providerId: agent.providerId,
repoDir: conn.remoteRepoDir,
deeplinkScheme: DEEPLINK_SCHEME,
+ autoApprove: agent.autoApprove,
ctx: conn.ctx,
connectionId: conn.connectionId,
host: conn.host,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.test.ts
new file mode 100644
index 000000000..189c1935e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const updateAgent = vi.fn(
+ async ({ agentId, autoApprove }): Promise<{ id: string; autoApprove?: boolean } | undefined> => ({
+ id: agentId,
+ autoApprove,
+ })
+);
+const getRemoteAgentLocation = vi.fn();
+const listAutoSessionAgentIds = vi.fn();
+const ensureRemoteWatcher = vi.fn(async (_id: string) => {});
+
+vi.mock('./updateAgent', () => ({ updateAgent: (p: unknown) => updateAgent(p) }));
+vi.mock('./agent-location', () => ({
+ 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),
+}));
+
+import { setAgentAutoApprove } from './setAgentAutoApprove';
+
+describe('setAgentAutoApprove', () => {
+ beforeEach(() => {
+ updateAgent.mockClear();
+ getRemoteAgentLocation.mockReset();
+ listAutoSessionAgentIds.mockReset();
+ ensureRemoteWatcher.mockClear();
+ });
+
+ it('writes the agent row and does not touch a local agent (read fresh at spawn)', async () => {
+ getRemoteAgentLocation.mockResolvedValue(null);
+
+ await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
+
+ expect(updateAgent).toHaveBeenCalledWith({ agentId: 'agent-1', autoApprove: true });
+ expect(ensureRemoteWatcher).not.toHaveBeenCalled();
+ });
+
+ it('re-pushes the spec to a remote agent whose watcher is running (auto_session on)', async () => {
+ getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1' });
+ listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
+
+ await setAgentAutoApprove({ agentId: 'agent-1', enabled: false });
+
+ 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' });
+ listAutoSessionAgentIds.mockResolvedValue([]);
+
+ await setAgentAutoApprove({ agentId: 'agent-1', enabled: true });
+
+ expect(ensureRemoteWatcher).not.toHaveBeenCalled();
+ });
+
+ it('throws when the agent does not exist', async () => {
+ updateAgent.mockResolvedValueOnce(undefined);
+
+ await expect(setAgentAutoApprove({ agentId: 'ghost', enabled: true })).rejects.toThrow(
+ /No agent with id ghost/
+ );
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.ts b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.ts
new file mode 100644
index 000000000..eb5038df4
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/setAgentAutoApprove.ts
@@ -0,0 +1,31 @@
+import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
+import { getRemoteAgentLocation } from './agent-location';
+import { ensureRemoteWatcher } from './remote-watcher';
+import { updateAgent } from './updateAgent';
+
+export type AgentAutoApproveParams = { agentId: string; enabled: boolean };
+
+/**
+ * Toggle an agent's per-agent bypass-permissions setting (CHOO-1664).
+ *
+ * Writes the agent row, then makes the change reach auto-started sessions:
+ * - Local agents need nothing extra — the in-process auto-session watcher reads
+ * `agent.autoApprove` fresh each time it spawns a session.
+ * - Remote agents bake the setting into the VM watcher's launch spec. When the
+ * agent's on-VM watcher is running (auto_session enabled), re-ensure the
+ * sidecar so the spec file is rewritten with the new value; the running sidecar
+ * re-reads it live and applies it to the next auto-started session without a
+ * restart. When auto_session is off there is no watcher to refresh — the next
+ * `ensureRemoteWatcher` (toggle-on / boot) picks up the current value.
+ *
+ * The re-ensure is allowed to throw: if the VM is unreachable the setting cannot
+ * take effect live, and the caller should surface that rather than pretend it did.
+ */
+export async function setAgentAutoApprove(params: AgentAutoApproveParams): Promise<void> {
+ const agent = await updateAgent({ agentId: params.agentId, autoApprove: params.enabled });
+ if (!agent) throw new Error(`No agent with id ${params.agentId}`);
+
+ if ((await getRemoteAgentLocation(agent)) === null) return;
+ if (!(await listAutoSessionAgentIds()).includes(agent.id)) return;
+ await ensureRemoteWatcher(agent.id);
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
index 184db82f5..65471b863 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.ts
@@ -369,7 +369,13 @@ class AutoSessionWatcher {
.getConnections()
.some((c) => c.roomId === roomId && c.agentId === watcher.creds.agentId);
if (hasLiveSession) return;
- if (watcher.inFlight.has(roomId)) return;
+ if (watcher.inFlight.has(roomId)) {
+ log.info(
+ 'AutoSessionWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',
+ { localAgentId: watcher.localAgentId, roomId }
+ );
+ return;
+ }
const timer = setTimeout(() => watcher.inFlight.delete(roomId), INFLIGHT_TTL_MS);
watcher.inFlight.set(roomId, timer);
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx
index 48fea441f..f12a10c0a 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/settings-view/sections/auto-approve-settings-section.tsx
@@ -9,8 +9,10 @@ import { log } from '@renderer/utils/logger';
* agent's CLI with its auto-approve flag (e.g. `--dangerously-skip-permissions`)
* — for every session, including automation-started ones (auto-session,
* remote reconcile). Defaults off for local agents and on for remote agents
- * (seeded at onboarding); this row is the source of truth thereafter. The
- * value lives on the agent row, so the toggle writes through `updateAgent`.
+ * (seeded at onboarding); this row is the source of truth thereafter. The value
+ * lives on the agent row; the toggle writes through `setAgentAutoApprove`, which
+ * also pushes the change to a remote agent's on-VM watcher so it takes effect
+ * live (CHOO-1664).
*/
export function AutoApproveSettingsSection({ locationId }: { locationId: string }) {
const { data: agents } = useQuery({
@@ -75,7 +77,7 @@ function AutoApproveSwitch({
const queryKey = ['location-agents', locationId];
const mutation = useMutation({
- mutationFn: (next: boolean) => rpc.agents.updateAgent({ agentId, autoApprove: next }),
+ mutationFn: (next: boolean) => rpc.agents.setAgentAutoApprove({ agentId, enabled: next }),
onError: (error) => {
log.error('Failed to update autoApprove for agent', { agentId, error });
void queryClient.invalidateQueries({ queryKey });
diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.ts
index 46c8094a6..57f2996ff 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts
@@ -110,9 +110,11 @@ async function main(): Promise<void> {
// Every raw hook the agents post is buffered so switchdash can replay it
// through its own hook path (room/status/session) while the UI is attached;
// the sidecar still handles it VM-locally for injection regardless.
- // Declared before the server so the /sessions provider can close over it; the
- // spawner is constructed once the server's port/token are known below.
+ // Declared before the server so the /sessions provider and disconnect handler
+ // can close over them; both are constructed once the server's port/token are
+ // known below.
let spawner: InProcessSessionSpawner | null = null;
+ let watcher: NotificationWatcher | null = null;
const eventLog = new HookEventLog();
const server = new HookServer(log);
@@ -153,8 +155,15 @@ async function main(): Promise<void> {
// the session everywhere instead of leaving a ghost row that re-attaches
// into a blank tmux session.
disconnectHandler: (sessionId, terminated) => {
+ // Resolve the session's room before teardown, then clear the watcher's
+ // in-flight guard for it — otherwise a delete during the boot window
+ // (before the session connects, so the connect hand-off never fired)
+ // leaves the room gated for up to INFLIGHT_TTL_MS and a near-immediate
+ // re-address is silently dropped (CHOO-1664).
+ const roomId = runtime.roomIdForSession(sessionId) ?? spawner?.roomIdForSession(sessionId);
runtime.stopSession(sessionId);
spawner?.drop(sessionId);
+ if (roomId) watcher?.clearRoom(roomId);
if (terminated) {
eventLog.append({
ptyId: '',
@@ -189,12 +198,38 @@ async function main(): Promise<void> {
watchEnabled = false;
}
};
- const watcher = new NotificationWatcher({
+
+ // Re-read the launch spec each poll and push it to the spawner, so a toggled
+ // setting (e.g. bypass-permissions, CHOO-1664) applies to the next auto-started
+ // session without restarting the sidecar — mirroring `watch-enabled`. A read or
+ // parse failure keeps the last good spec rather than crashing the poll.
+ let lastSpecJson = JSON.stringify(launchSpec);
+ const refreshLaunchSpec = async (): Promise<void> => {
+ let spec: AgentLaunchSpec;
+ try {
+ spec = await readLaunchSpec(repoDir);
+ } catch (error) {
+ log.warn('sidecar: failed to re-read launch spec; keeping current', {
+ error: String(error),
+ });
+ return;
+ }
+ const json = JSON.stringify(spec);
+ if (json === lastSpecJson) return;
+ lastSpecJson = json;
+ spawner?.setSpec(spec);
+ log.info('sidecar: launch spec changed — applied to spawner');
+ };
+ watcher = new NotificationWatcher({
creds,
spawner,
watchEnabled: () => watchEnabled,
log,
});
+ // Hand the per-room spawn guard off to the live-room check the moment a session
+ // connects — so a session torn down shortly after connecting does not leave the
+ // room gated until INFLIGHT_TTL_MS (mirrors the local AutoSessionWatcher).
+ runtime.onRoomConnected((roomId) => watcher?.clearRoom(roomId));
watcher.start();
const refreshLiveness = async (): Promise<void> => {
@@ -211,7 +246,7 @@ async function main(): Promise<void> {
for (const t of [...liveTargets]) if (!targets.has(t)) liveTargets.delete(t);
};
const refresh = async (): Promise<void> => {
- await Promise.all([refreshLiveness(), refreshWatchEnabled()]);
+ await Promise.all([refreshLiveness(), refreshWatchEnabled(), refreshLaunchSpec()]);
};
void refresh();
const paneTimer = setInterval(() => void refresh(), PANE_POLL_INTERVAL_MS);
@@ -230,7 +265,7 @@ async function main(): Promise<void> {
const shutdown = (): void => {
clearInterval(paneTimer);
- watcher.stop();
+ watcher?.stop();
runtime.stop();
server.stop();
process.exit(0);
diff --git a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
index d4b5e2c1b..6741fe514 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
@@ -66,6 +66,35 @@ describe('NotificationWatcher spawn decision', () => {
expect(spawner.launch).toHaveBeenCalledTimes(1);
});
+ it('logs at info when a notification is dropped because a spawn is in flight', async () => {
+ const spawner = makeSpawner();
+ const watcher = makeWatcher(spawner);
+ handle(watcher, 'room-x');
+ await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));
+ handle(watcher, 'room-x'); // suppressed by the in-flight guard
+ expect(spawner.launch).toHaveBeenCalledTimes(1);
+ expect(silentLog.info).toHaveBeenCalledWith(
+ expect.stringContaining('skipping duplicate spawn'),
+ { roomId: 'room-x' }
+ );
+ });
+
+ it('clearRoom releases the in-flight guard so the next notification spawns again', async () => {
+ const spawner = makeSpawner();
+ const watcher = makeWatcher(spawner);
+ handle(watcher, 'room-x');
+ await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(1));
+
+ // Without a clear, a re-notification is suppressed by the in-flight guard.
+ handle(watcher, 'room-x');
+ expect(spawner.launch).toHaveBeenCalledTimes(1);
+
+ // Handing the guard off (session connected, or deleted) lets the next one spawn.
+ watcher.clearRoom('room-x');
+ handle(watcher, 'room-x');
+ await vi.waitFor(() => expect(spawner.launch).toHaveBeenCalledTimes(2));
+ });
+
it('retries on launch failure then posts a spawn-failure notice', async () => {
const launch = vi.fn(async () => {
throw new Error('boom');
diff --git a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts
index f6dc85122..5951e2d18 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.ts
@@ -191,7 +191,13 @@ export class NotificationWatcher {
/** Decide whether to spawn for a notified room, with a per-room in-flight guard. */
private handleNotification(roomId: string): void {
- if (this.inFlight.has(roomId)) return;
+ if (this.inFlight.has(roomId)) {
+ this.deps.log.info(
+ 'NotificationWatcher: notification for room with a spawn already in flight — skipping duplicate spawn',
+ { roomId }
+ );
+ return;
+ }
const timer = setTimeout(() => this.inFlight.delete(roomId), INFLIGHT_TTL_MS);
this.inFlight.set(roomId, timer);
@@ -201,6 +207,16 @@ export class NotificationWatcher {
});
}
+ /**
+ * Clear the in-flight guard for a room, so the next notification spawns a fresh
+ * session immediately. Called when a session actually connects to the room (the
+ * live-room check takes over the guard from here — mirrors the local
+ * AutoSessionWatcher) and when a session is deleted before it ever connected.
+ */
+ clearRoom(roomId: string): void {
+ this.clearInFlight(roomId);
+ }
+
private async spawnForRoom(roomId: string): Promise<void> {
const { spawner, creds, log } = this.deps;
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
index dc523f07a..1f20b6bef 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
@@ -100,6 +100,34 @@ describe('InProcessSessionSpawner.spawnedSessions', () => {
});
});
+describe('InProcessSessionSpawner.setSpec', () => {
+ it('applies a swapped launch spec to the next launch (live toggle, no restart)', async () => {
+ const { spawner, calls } = makeSpawner();
+ spawner.setSpec({
+ ...SPEC,
+ command: '/usr/bin/other-cli',
+ args: ['--session-id', SESSION_ID_PLACEHOLDER, '--no-skip', INITIAL_PROMPT_PLACEHOLDER],
+ });
+ await spawner.launch('room-x');
+
+ const inner = calls.find((c) => c.args[0] === 'new-session')!.args.at(-1)!;
+ expect(inner).toContain('/usr/bin/other-cli');
+ expect(inner).toContain('--no-skip');
+ expect(inner).not.toContain('--dangerously-skip-permissions');
+ });
+});
+
+describe('InProcessSessionSpawner.roomIdForSession', () => {
+ it('returns the room a launched session was started for, or null', async () => {
+ const { spawner } = makeSpawner({ isPaneLive: () => true });
+ await spawner.launch('room-x');
+ const sessionId = spawner.spawnedSessions()[0]!.sessionId;
+
+ expect(spawner.roomIdForSession(sessionId)).toBe('room-x');
+ expect(spawner.roomIdForSession('unknown-session')).toBeNull();
+ });
+});
+
describe('InProcessSessionSpawner.drop', () => {
it('forgets a launched session by its session id', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
index 18cddf577..5658b4fdb 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
@@ -41,9 +41,22 @@ export class InProcessSessionSpawner implements SessionSpawner {
) => Promise<{ stdout: string; stderr: string }>;
/** Room id → the session we launched for it (its minted id + tmux target). */
private readonly launched = new Map<string, { sessionId: string; tmuxTarget: string }>();
+ /** The live launch recipe. Seeded from deps, replaceable via `setSpec` so a
+ * bypass-permissions toggle takes effect without restarting the sidecar. */
+ private spec: AgentLaunchSpec;
constructor(private readonly deps: InProcessSessionSpawnerDeps) {
this.exec = deps.exec ?? ((command, args) => execFileAsync(command, args));
+ this.spec = deps.spec;
+ }
+
+ /**
+ * Swap the launch recipe (the entrypoint re-reads the spec file each poll and
+ * pushes it here), so a toggled setting — e.g. bypass-permissions — applies to
+ * the next auto-started session without restarting the sidecar.
+ */
+ setSpec(spec: AgentLaunchSpec): void {
+ this.spec = spec;
}
/**
@@ -64,6 +77,14 @@ export class InProcessSessionSpawner implements SessionSpawner {
}
}
+ /** The room a launched (not-yet-connected) session was started for, or null. */
+ roomIdForSession(sessionId: string): string | null {
+ for (const [roomId, session] of this.launched) {
+ if (session.sessionId === sessionId) return roomId;
+ }
+ return null;
+ }
+
/** tmux targets of launched sessions, for the entrypoint's pane-liveness poll. */
pendingTmuxTargets(): string[] {
return [...this.launched.values()].map((s) => s.tmuxTarget);
@@ -98,7 +119,8 @@ export class InProcessSessionSpawner implements SessionSpawner {
}
async launch(roomId: string): Promise<void> {
- const { spec, hookPort, hookToken, log } = this.deps;
+ const { hookPort, hookToken, log } = this.deps;
+ const spec = this.spec;
const sessionId = randomUUID();
const tmuxTarget = makeAgentTmuxSessionName(sessionId);
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
index 3bd0ad1f2..554bbaf60 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -160,6 +160,35 @@ describe('SidecarRuntime (multi-session)', () => {
expect(runtime.connectedSessions()).toEqual([]);
});
+ it('notifies the room-connected listener when a session connects to a room', async () => {
+ const { runtime } = makeRuntime();
+ const connected: string[] = [];
+ runtime.onRoomConnected((roomId) => connected.push(roomId));
+
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+
+ expect(connected).toEqual(['room-1']);
+ });
+
+ it('notifies the listener again on a repeat connect (idempotent guard hand-off)', async () => {
+ const { runtime } = makeRuntime();
+ const connected: string[] = [];
+ runtime.onRoomConnected((roomId) => connected.push(roomId));
+
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+
+ expect(connected).toEqual(['room-1', 'room-1']);
+ });
+
+ it('roomIdForSession returns the attended room, or null when unknown', async () => {
+ const { runtime } = makeRuntime();
+ await runtime.handleHook(switchRoomHook('room-1', PTY_A));
+
+ expect(runtime.roomIdForSession('session-a')).toBe('room-1');
+ expect(runtime.roomIdForSession('session-unknown')).toBeNull();
+ });
+
it('stops all connections on stop()', async () => {
const { runtime, created } = makeRuntime();
await runtime.handleHook(switchRoomHook('room-1', PTY_A));
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index 7cdb9c719..bcc8f3581 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -66,6 +66,10 @@ export class SidecarRuntime {
* sessions it owns, used to scope the VM-wide tmux enumeration in `/sessions`. */
private readonly seen = new Set<string>();
private readonly resolveContext: ContextResolver;
+ /** Notified when a session connects to a room, so the notification watcher can
+ * hand its per-room in-flight guard off to the live-room check (mirrors the
+ * local AutoSessionWatcher's room-connection subscription). */
+ private roomConnectedListener: ((roomId: string) => void) | null = null;
constructor(private readonly deps: SidecarRuntimeDeps) {
this.resolveContext = async (ptyId) => {
@@ -79,6 +83,11 @@ export class SidecarRuntime {
};
}
+ /** Register the room-connected listener (the notification watcher's guard hand-off). */
+ onRoomConnected(listener: (roomId: string) => void): void {
+ this.roomConnectedListener = listener;
+ }
+
/** Handle one raw hook callback from an agent CLI. Never throws. */
async handleHook(raw: RawHookRequest): Promise<void> {
// Every hook posted to THIS sidecar comes from a session it owns (the
@@ -133,8 +142,12 @@ export class SidecarRuntime {
): void {
const existing = this.sessions.get(sessionId);
// A repeat connect to the same room by the same session is a no-op so the
- // in-flight queue and renew loop are preserved.
- if (existing && existing.roomId === roomId) return;
+ // in-flight queue and renew loop are preserved — but still hand off the
+ // watcher's spawn guard (idempotent), since a session is attending the room.
+ if (existing && existing.roomId === roomId) {
+ this.roomConnectedListener?.(roomId);
+ return;
+ }
// A session re-targeting to a new room supersedes ITS OWN prior room only —
// other sessions' connections are untouched (mirrors each session's
// connect_to_room re-targeting independently).
@@ -162,6 +175,12 @@ export class SidecarRuntime {
this.sessions.set(sessionId, { connection, roomId, tmuxTarget });
this.deps.log.debug('SidecarRuntime: room connected', { sessionId, roomId, roomName });
connection.start();
+ this.roomConnectedListener?.(roomId);
+ }
+
+ /** The room a session is currently attending, or null if it has none. */
+ roomIdForSession(sessionId: string): string | null {
+ return this.sessions.get(sessionId)?.roomId ?? null;
}
/**