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): reap sidecars orphaned by a change of tmux name (CHOO-1425) (#80)

Louis Amaudruzb7f862b3a737
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
index ac97ff2b5..1f66cd52b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import { describe, expect, it, vi } from 'vitest';
import type { AgentLaunchSpec } from '../../../../sidecar/agent-launch-spec';
import { SIDECAR_BUNDLE_REL_PATH } from '../../../../sidecar/sidecar-paths';
@@ -6,6 +7,7 @@ import {
agentSidecarTmuxName,
killSidecarSession,
reapOrphanedSidecars,
+ reapStaleAgentSidecars,
RemoteSidecarLauncher,
type SidecarHost,
type SidecarLaunchConfig,
@@ -454,6 +456,95 @@ describe('killSidecarSession', () => {
});
});
+describe('reapStaleAgentSidecars', () => {
+ const REPO = '/home/dev/repo';
+ /** What a pre-CHOO-1440 client named this agent's sidecar: hash(repoDir) alone. */
+ const legacyName = `switchdash-sidecar-${createHash('sha256').update(REPO).digest('hex').slice(0, 16)}`;
+ const current = agentSidecarTmuxName(REPO, 'agent-a');
+ const sibling = agentSidecarTmuxName(REPO, 'agent-b');
+ const renamedFrom = agentSidecarTmuxName(REPO, 'agent-a-old');
+ const otherDir = agentSidecarTmuxName('/home/dev/other', 'agent-z');
+
+ function reaperHost(sessions: Array<[name: string, path: string]>) {
+ const calls: ExecCall[] = [];
+ const host: SidecarHost = {
+ async exec(command, args) {
+ calls.push({ command, args });
+ if (command === 'tmux' && args[0] === 'list-sessions') {
+ return { stdout: sessions.map(([n, p]) => `${n}\t${p}`).join('\n'), stderr: '' };
+ }
+ return { stdout: '', stderr: '' };
+ },
+ async putFile() {},
+ };
+ const kills = (): string[] =>
+ calls
+ .filter((c) => c.command === 'tmux' && c.args[0] === 'kill-session')
+ .map((c) => c.args[2]!);
+ return { host, kills };
+ }
+
+ it('kills leftover generations in the dir, sparing siblings and other dirs', async () => {
+ const { host, kills } = reaperHost([
+ [current, REPO],
+ [legacyName, REPO], // pre-CHOO-1440 naming — same agent, unreachable name
+ [renamedFrom, REPO], // the name this agent ran under before it was renamed
+ [sibling, REPO], // a co-located agent's own sidecar
+ [otherDir, '/home/dev/other'], // an agent this client knows nothing about
+ ['switchdash-abc123', REPO], // an agent pane, not a sidecar
+ ]);
+
+ await reapStaleAgentSidecars(host, REPO, [current, sibling], noopLog);
+
+ expect(kills()).toEqual([`=${legacyName}`, `=${renamedFrom}`]);
+ });
+
+ it('kills nothing when every sidecar in the dir is claimed', async () => {
+ const { host, kills } = reaperHost([
+ [current, REPO],
+ [sibling, REPO],
+ ]);
+ await reapStaleAgentSidecars(host, REPO, [current, sibling], noopLog);
+ expect(kills()).toEqual([]);
+ });
+
+ it('refuses to reap when no expected name is supplied', async () => {
+ const { host, kills } = reaperHost([[current, REPO]]);
+ await reapStaleAgentSidecars(host, REPO, [], noopLog);
+ expect(kills()).toEqual([]);
+ });
+
+ it('is a no-op when the host has no tmux server', async () => {
+ const host: SidecarHost = {
+ async exec() {
+ throw new Error('no server running');
+ },
+ async putFile() {},
+ };
+ await expect(reapStaleAgentSidecars(host, REPO, [current], noopLog)).resolves.toBeUndefined();
+ });
+
+ it('keeps reaping after one kill fails', async () => {
+ const calls: ExecCall[] = [];
+ const host: SidecarHost = {
+ async exec(command, args) {
+ calls.push({ command, args });
+ if (command === 'tmux' && args[0] === 'list-sessions') {
+ return { stdout: `${legacyName}\t${REPO}\n${renamedFrom}\t${REPO}`, stderr: '' };
+ }
+ if (args[2] === `=${legacyName}`) throw new Error('kill failed');
+ return { stdout: '', stderr: '' };
+ },
+ async putFile() {},
+ };
+ await reapStaleAgentSidecars(host, REPO, [current], noopLog);
+ expect(calls.filter((c) => c.args[0] === 'kill-session').map((c) => c.args[2])).toEqual([
+ `=${legacyName}`,
+ `=${renamedFrom}`,
+ ]);
+ });
+});
+
describe('reapOrphanedSidecars', () => {
function reaperHost(sessions: string[], aliveAgents: string[]) {
const calls: ExecCall[] = [];
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
index fbe9e8bed..f392a7e2a 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
@@ -41,6 +41,7 @@ import {
*/
const SIDECAR_TMUX_SUFFIX = '-sidecar';
+const AGENT_SIDECAR_TMUX_PREFIX = 'switchdash-sidecar-';
const READY_POLL_INTERVAL_MS = 250;
const READY_MAX_ATTEMPTS = 80; // ~20s
const DEPLOY_LOCK_POLL_MS = 500;
@@ -172,7 +173,7 @@ const defaultSleep = (ms: number): Promise<void> =>
*/
export function agentSidecarTmuxName(repoDir: string, slug: string): string {
const hash = createHash('sha256').update(`${repoDir}\0${slug}`).digest('hex').slice(0, 16);
- return `switchdash-sidecar-${hash}`;
+ return `${AGENT_SIDECAR_TMUX_PREFIX}${hash}`;
}
async function sha256File(path: string): Promise<string> {
@@ -716,6 +717,108 @@ export async function killSidecarSession(
}
}
+/** One entry of `tmux list-sessions`: the session's name and its working dir. */
+export interface HostTmuxSession {
+ name: string;
+ /** `#{session_path}` — for an agent-scoped sidecar, the repo dir it was
+ * launched with (`new-session -c`). */
+ path: string;
+}
+
+function parseTmuxSessions(stdout: string): HostTmuxSession[] {
+ return stdout
+ .split('\n')
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line) => {
+ const tab = line.indexOf('\t');
+ return tab === -1
+ ? { name: line, path: '' }
+ : { name: line.slice(0, tab), path: line.slice(tab + 1) };
+ });
+}
+
+/**
+ * Agent-scoped sidecars running in `repoDir` that no live agent claims — the
+ * stale generations to reap. See {@link reapStaleAgentSidecars}.
+ *
+ * Scoped to `repoDir` on purpose: a sidecar for some other directory belongs to
+ * an agent this caller knows nothing about (another client's, another user's),
+ * and killing it would be strictly destructive.
+ */
+export function staleAgentSidecarNames(
+ sessions: readonly HostTmuxSession[],
+ repoDir: string,
+ expectedNames: readonly string[]
+): string[] {
+ const expected = new Set(expectedNames);
+ return sessions
+ .filter((s) => s.name.startsWith(AGENT_SIDECAR_TMUX_PREFIX))
+ .filter((s) => s.path === repoDir)
+ .filter((s) => !expected.has(s.name))
+ .map((s) => s.name);
+}
+
+/**
+ * Kill agent-scoped sidecars in `repoDir` whose name no agent at that directory
+ * currently maps to.
+ *
+ * A sidecar's identity is a hash of `(repoDir, creds slug)` and every other code
+ * path asks tmux exactly one question — does a session with *this* name exist —
+ * so the moment either input changes, the running sidecar becomes unreachable
+ * rather than replaced: the next launch starts a second one beside it and
+ * nothing ever looks at the first again. Both inputs have changed in shipped
+ * releases (the slug joined the hash in CHOO-1440; the storage migration
+ * rewrote agent names), and a plain rename does it too. The orphans are not
+ * merely untidy — each keeps polling its Switch rooms and renewing, so the agent
+ * appears live from a process no client can see, stop, or upgrade.
+ *
+ * `expectedNames` must cover every agent at `repoDir` — siblings sharing a
+ * directory each run their own sidecar by design (CHOO-1440).
+ *
+ * Best-effort by design: this is opportunistic cleanup alongside a launch, and
+ * a host that cannot be enumerated is not a reason to fail the launch. Anything
+ * actually reaped is logged as a warning rather than passing silently.
+ */
+export async function reapStaleAgentSidecars(
+ host: SidecarHost,
+ repoDir: string,
+ expectedNames: readonly string[],
+ log: SidecarLauncherLogger
+): Promise<void> {
+ if (expectedNames.length === 0) {
+ // Reaping against an empty expected-set would kill the directory's live
+ // sidecar. A caller with no agents to name has nothing to reconcile.
+ log.warn('reapStaleAgentSidecars: refusing to reap with no expected sidecars', { repoDir });
+ return;
+ }
+
+ let sessions: HostTmuxSession[];
+ try {
+ const { stdout } = await host.exec('tmux', [
+ 'list-sessions',
+ '-F',
+ '#{session_name}\t#{session_path}',
+ ]);
+ sessions = parseTmuxSessions(stdout);
+ } catch {
+ return; // no tmux server / no sessions
+ }
+
+ for (const name of staleAgentSidecarNames(sessions, repoDir, expectedNames)) {
+ try {
+ await host.exec('tmux', ['kill-session', '-t', exactTmuxTarget(name)]);
+ log.warn('reapStaleAgentSidecars: killed a sidecar no agent claims', { name, repoDir });
+ } catch (error) {
+ log.warn('reapStaleAgentSidecars: failed to kill stale sidecar', {
+ name,
+ repoDir,
+ error: String(error),
+ });
+ }
+ }
+}
+
/**
* Reap LEGACY per-session sidecars — those named `<agentTmux>-sidecar`, one per
* session — whose agent pane is gone: they are still polling Switch with nowhere
@@ -726,8 +829,9 @@ export async function killSidecarSession(
* to outlive every pane: with no live session the notification watcher is the
* thing that starts one when the agent is next addressed, so reaping them for
* having no panes would quietly disable auto-start. An agent-scoped sidecar is
- * torn down explicitly instead, via `killSidecarSession`, when the agent or host
- * goes away.
+ * torn down explicitly instead — via `killSidecarSession` when its agent is
+ * renamed or deleted, and via `reapStaleAgentSidecars` when it is a leftover
+ * generation of an agent that is still around.
*
* Best-effort: a missing tmux server (no sessions at all) is a no-op, not an error.
*/
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 3b2cbc7c5..33bbb67d9 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
@@ -23,6 +23,10 @@ vi.mock('./resolve-sidecar-bundle', () => ({
resolveSidecarBundlePath: vi.fn(() => '/local/dist-sidecar/sidecar.mjs'),
}));
+vi.mock('@main/core/agents/reap-stale-sidecars', () => ({
+ reapStaleSidecarsForAgent: vi.fn(async () => {}),
+}));
+
vi.mock('./remote-sidecar-launcher', () => ({
RemoteSidecarLauncher: vi.fn(function () {
return { deployAndLaunch, stop: sidecarStop };
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 b82287f67..5d08a0c66 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
@@ -4,6 +4,7 @@ import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-s
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 { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';
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';
@@ -201,6 +202,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
// 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 host = this.createSidecarHost();
const endpoint = await ensureAgentSidecar({
providerId: session.providerId,
repoDir: this.sessionPath,
@@ -210,8 +212,11 @@ export class SshAgentRuntime implements AgentRuntimeProvider {
agentName: agent?.name ?? session.agentName ?? null,
ctx: this.ctx,
connectionId: this.connectionId,
- host: this.createSidecarHost(),
+ host,
});
+ // Drop any sidecar left in this directory by an earlier generation of the
+ // agent's name — it is still polling Switch and no other path can see it.
+ if (agent) await reapStaleSidecarsForAgent(agent, host, this.sessionPath);
this.sidecarEndpoint = endpoint;
this.startRelay(endpoint);
return endpoint;
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
index 9b4881c84..7271289f4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/deleteAgent.ts
@@ -1,4 +1,8 @@
import { eq } from 'drizzle-orm';
+import {
+ agentSidecarTmuxName,
+ killSidecarSession,
+} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { setAutoSessionAgent } from '@main/core/switch-rooms/auto-session-store';
import { autoSessionWatcher } from '@main/core/switch-rooms/auto-session-watcher';
@@ -14,6 +18,7 @@ import { sessionRuntimeManager } from '../sessions/session-runtime-manager';
import { agentEvents } from './agent-events';
import { getAgentLocation } from './agent-location';
import { resolveWorkspaceFsFor } from './agent-workspace-fs';
+import { connectRemoteAgent } from './connect-remote-agent';
import { getAgentById } from './getAgentById';
import { stopRemoteWatcher } from './remote-watcher';
import { removeSwitchCredentials } from './remove-switch-settings';
@@ -81,6 +86,32 @@ async function removeProvisionedFiles(agent: Agent, location: Location): Promise
}
}
+/**
+ * Kill the agent's own sidecar on its VM. `stopRemoteWatcher` only flips the
+ * watch flag — the process stays up, holding this agent's Switch room
+ * connections and renewing them, for an agent that is about to stop existing.
+ * Nothing would ever address that sidecar again: its tmux name is derived from
+ * the agent row being deleted. Scoped to this agent's name, so a sibling sharing
+ * the directory keeps its own (CHOO-1440).
+ *
+ * Best-effort: an unreachable host must not block removing the agent locally.
+ */
+async function killRemoteSidecar(agent: Agent): Promise<void> {
+ try {
+ const { host, remoteRepoDir } = await connectRemoteAgent(agent);
+ await killSidecarSession(
+ host,
+ agentSidecarTmuxName(remoteRepoDir, agent.name ?? agent.id),
+ log
+ );
+ } catch (error) {
+ log.warn('deleteAgent: failed to kill the remote sidecar', {
+ agentId: agent.id,
+ error: String(error),
+ });
+ }
+}
+
/**
* Delete an agent — the one real delete entry point (the sidebar's Remove
* Agent routes here). Tears down everything a bare row delete would leak:
@@ -126,6 +157,7 @@ export async function deleteAgent(agentId: string, options: DeleteAgentOptions):
await stopRemoteWatcher(agentId).catch((error) => {
log.warn('deleteAgent: failed to stop remote watcher', { agentId, error: String(error) });
});
+ if (agent) await killRemoteSidecar(agent);
} else {
autoSessionWatcher.stopForAgent(agentId);
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts
new file mode 100644
index 000000000..1a24ce80b
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reap-stale-sidecars.ts
@@ -0,0 +1,53 @@
+import {
+ agentSidecarTmuxName,
+ reapStaleAgentSidecars,
+ type SidecarHost,
+} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
+import { log } from '@main/lib/logger';
+import type { Agent } from '@shared/core/agents/agents';
+import { getAgents } from './getAgents';
+
+/**
+ * The sidecar tmux names that are legitimately running in an agent's directory:
+ * one per agent switchdash has at that location, since siblings sharing a
+ * directory each run their own sidecar (CHOO-1440).
+ *
+ * `agent` is always included, even if the location query somehow misses its row
+ * — reaping must never be able to kill the sidecar of the very agent it was
+ * invoked for.
+ */
+async function expectedSidecarNames(agent: Agent, repoDir: string): Promise<string[]> {
+ const siblings = await getAgents(agent.locationId);
+ const slugs = new Set([agent.name ?? agent.id, ...siblings.map((a) => a.name ?? a.id)]);
+ return [...slugs].map((slug) => agentSidecarTmuxName(repoDir, slug));
+}
+
+/**
+ * Kill the sidecars left behind in this agent's directory by an earlier
+ * generation of its name — an agent rename, or a release that changed how the
+ * sidecar's tmux name is derived. See {@link reapStaleAgentSidecars} for why
+ * those survive: nothing else on the host ever looks at a sidecar whose name is
+ * not the one it just computed.
+ *
+ * Call this from paths that ensure a sidecar, not from read-only probes: it is
+ * reconciliation, and a status read should not mutate the host.
+ *
+ * Best-effort — logged, never thrown. The caller is launching an agent; failing
+ * that because a leftover process could not be enumerated would trade a cosmetic
+ * problem for a real one.
+ */
+export async function reapStaleSidecarsForAgent(
+ agent: Agent,
+ host: SidecarHost,
+ repoDir: string
+): Promise<void> {
+ try {
+ await reapStaleAgentSidecars(host, repoDir, await expectedSidecarNames(agent, repoDir), log);
+ } catch (error) {
+ log.warn('reapStaleSidecarsForAgent: failed to reconcile sidecars', {
+ agentId: agent.id,
+ repoDir,
+ error: String(error),
+ });
+ }
+}
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 9274b8fe2..278a1675b 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
@@ -7,6 +7,7 @@ import { getRemoteAgentLocation } from './agent-location';
import { connectRemoteAgent } from './connect-remote-agent';
import { getAgentById } from './getAgentById';
import { getAgents } from './getAgents';
+import { reapStaleSidecarsForAgent } from './reap-stale-sidecars';
import { remoteSessionReconciler } from './remote-session-reconciler';
/**
@@ -121,6 +122,7 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {
host,
});
await writeWatchEnabled(host, agent.name ?? agent.id, true);
+ await reapStaleSidecarsForAgent(agent, host, remoteRepoDir);
log.info('ensureRemoteWatcher: sidecar deployed + watching', {
agentId,
switchAgentId: agent.switchAgentId,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
index 40e22ec29..f14360005 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/renameAgent.ts
@@ -1,15 +1,60 @@
import { eq, sql } from 'drizzle-orm';
+import {
+ agentSidecarTmuxName,
+ killSidecarSession,
+} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
import { db } from '@main/db/client';
import { agents } from '@main/db/schema';
+import { log } from '@main/lib/logger';
import type { Agent, RenameAgentParams } from '@shared/core/agents/agents';
+import { getRemoteAgentLocation } from './agent-location';
+import { connectRemoteAgent } from './connect-remote-agent';
+import { getAgentById } from './getAgentById';
+import { ensureRemoteWatcher } from './remote-watcher';
import { mapAgentRowToAgent } from './utils';
+/**
+ * Tear down the remote sidecar the agent ran under its previous name, then bring
+ * one back up under the new one.
+ *
+ * A sidecar's tmux name is a hash of `(repo dir, creds slug)` and the slug is the
+ * agent's name, so a rename makes the running sidecar unreachable to every code
+ * path rather than renaming it: left alone it keeps polling the agent's Switch
+ * rooms forever while the next launch starts a second one beside it.
+ *
+ * Best-effort — a rename must not fail because the VM is unreachable. The
+ * leftover is then reaped by `reapStaleSidecarsForAgent` on the next launch.
+ */
+async function moveSidecarToNewName(previous: Agent, renamed: Agent): Promise<void> {
+ try {
+ const location = await getRemoteAgentLocation(previous);
+ if (!location) return;
+ const { host, remoteRepoDir } = await connectRemoteAgent(previous);
+ await killSidecarSession(
+ host,
+ agentSidecarTmuxName(remoteRepoDir, previous.name ?? previous.id),
+ log
+ );
+ await ensureRemoteWatcher(renamed.id);
+ } catch (error) {
+ log.warn('renameAgent: failed to move the sidecar to the new name', {
+ agentId: previous.id,
+ error: String(error),
+ });
+ }
+}
+
export async function renameAgent(params: RenameAgentParams): Promise<Agent | undefined> {
+ const previous = await getAgentById(params.agentId);
const [row] = await db
.update(agents)
.set({ name: params.newName, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(eq(agents.id, params.agentId))
.returning();
if (!row) return undefined;
- return mapAgentRowToAgent(row);
+ const renamed = mapAgentRowToAgent(row);
+ if (previous && previous.name !== renamed.name) {
+ await moveSidecarToNewName(previous, renamed);
+ }
+ return renamed;
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
index fad8f317e..bf8301450 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sidecar/controller.ts
@@ -10,6 +10,7 @@ import {
import { getRemoteAgentLocation } from '@main/core/agents/agent-location';
import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';
import { getAgentById } from '@main/core/agents/getAgentById';
+import { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
import type { Agent } from '@shared/core/agents/agents';
@@ -89,7 +90,9 @@ export const sidecarController = createRPCController({
*/
upgrade: async (agentId: string): Promise<AgentSidecarStatus> => {
const { agent } = await requireRemoteAgent(agentId);
- await ensureAgentSidecar(await paramsForAgent(agent));
+ const params = await paramsForAgent(agent);
+ await ensureAgentSidecar(params);
+ await reapStaleSidecarsForAgent(agent, params.host, params.repoDir);
return readAndBroadcast(agentId);
},
@@ -100,7 +103,9 @@ export const sidecarController = createRPCController({
*/
restart: async (agentId: string): Promise<AgentSidecarStatus> => {
const { agent } = await requireRemoteAgent(agentId);
- await restartAgentSidecar(await paramsForAgent(agent));
+ const params = await paramsForAgent(agent);
+ await restartAgentSidecar(params);
+ await reapStaleSidecarsForAgent(agent, params.host, params.repoDir);
return readAndBroadcast(agentId);
},