Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): reset a remote agent — kill & reset all its tmux sessions (CHOO-1656) (#58)
Louis Amaudruz34972ebdea2f
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts b/dash/apps/switchdash-desktop/src/main/core/agents/controller.tsindex 0aec5e382..a3d628089 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/controller.ts@@ -9,6 +9,7 @@ import { getAgentById } from './getAgentById';import { getAgents } from './getAgents';import { onboardAgent } from './onboard-agent';import { renameAgent } from './renameAgent';+import { resetRemoteAgent } from './reset-remote-agent';import {getAgentAutoSession,setAgentAutoSession,@@ -24,6 +25,7 @@ export const agentsController = createRPCController({renameAgent: (params: RenameAgentParams) => renameAgent(params),deleteAgent: (params: { agentId: string } & DeleteAgentOptions) =>deleteAgent(params.agentId, { deleteInSwitch: params.deleteInSwitch }),+ resetRemoteAgent: (params: { agentId: string }) => resetRemoteAgent(params.agentId),updateAgent: (params: UpdateAgentParams) => updateAgent(params),assignServer: (params: { agentId: string; serverId: string }): Promise<AgentVerifyResult> =>assignAgentServer(params),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.tsnew file mode 100644index 000000000..3a3f96c63--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent-tmux.ts@@ -0,0 +1,29 @@+import { agentSidecarTmuxName } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import { exactTmuxTarget, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';+import { quoteShellArg } from '@main/utils/shellEscape';++/**+ * The tmux session names to kill when resetting an agent: one per agent session+ * id plus the agent's sidecar session. Deduplicated by name.+ */+export function resetTmuxTargets(sessionIds: string[], remoteRepoDir: string): string[] {+ return [+ ...new Set([...sessionIds.map(makeAgentTmuxSessionName), agentSidecarTmuxName(remoteRepoDir)]),+ ];+}++/**+ * A `sh -c` script that kills each named tmux session on the remote host, failing+ * loud. Each target is killed only if it exists (`has-session` guards the+ * `kill-session`), so an already-gone session — or a host with no tmux server at+ * all — is a no-op, while a real `kill-session` failure aborts the whole script+ * (`set -e`). Returns null when there is nothing to kill.+ */+export function buildKillTmuxScript(sessionNames: string[]): string | null {+ if (sessionNames.length === 0) return null;+ const lines = sessionNames.map((name) => {+ const target = quoteShellArg(exactTmuxTarget(name));+ return `if tmux has-session -t ${target} 2>/dev/null; then tmux kill-session -t ${target}; fi`;+ });+ return ['set -e', ...lines].join('\n');+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.tsnew file mode 100644index 000000000..f1122aac8--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';+import { agentSidecarTmuxName } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import { exactTmuxTarget, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';+import { buildKillTmuxScript, resetTmuxTargets } from './reset-remote-agent-tmux';++const REPO = '/home/dev/repo';++describe('resetTmuxTargets', () => {+ it('kills every agent session plus the sidecar', () => {+ const targets = resetTmuxTargets(['s1', 's2'], REPO);+ expect(targets).toContain(makeAgentTmuxSessionName('s1'));+ expect(targets).toContain(makeAgentTmuxSessionName('s2'));+ expect(targets).toContain(agentSidecarTmuxName(REPO));+ expect(targets).toHaveLength(3);+ });++ it('kills the sidecar even when the agent has no sessions', () => {+ expect(resetTmuxTargets([], REPO)).toEqual([agentSidecarTmuxName(REPO)]);+ });++ it('deduplicates repeated session ids', () => {+ const targets = resetTmuxTargets(['s1', 's1'], REPO);+ expect(targets).toEqual([makeAgentTmuxSessionName('s1'), agentSidecarTmuxName(REPO)]);+ });+});++describe('buildKillTmuxScript', () => {+ it('returns null when there is nothing to kill', () => {+ expect(buildKillTmuxScript([])).toBeNull();+ });++ it('fails loud (set -e) and guards each kill behind has-session', () => {+ const script = buildKillTmuxScript(['alpha', 'beta']);+ expect(script).not.toBeNull();+ const lines = script!.split('\n');+ expect(lines[0]).toBe('set -e');+ expect(lines).toHaveLength(3);+ for (const name of ['alpha', 'beta']) {+ const line = lines.find((l) => l.includes(name));+ expect(line).toBeDefined();+ // Each target is killed only if it exists, so an already-gone session is a+ // no-op rather than an error.+ expect(line).toContain('tmux has-session -t');+ expect(line).toContain('tmux kill-session -t');+ }+ });++ it('uses exact-match tmux targets so a name never prefix-matches its sidecar', () => {+ const name = makeAgentTmuxSessionName('s1');+ const script = buildKillTmuxScript([name]);+ // exactTmuxTarget prefixes '=', forcing an exact session-name match.+ expect(script).toContain(exactTmuxTarget(name));+ expect(exactTmuxTarget(name).startsWith('=')).toBe(true);+ });+});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.tsnew file mode 100644index 000000000..1e8df7079--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/reset-remote-agent.ts@@ -0,0 +1,165 @@+import { eq } from 'drizzle-orm';+import { DEEPLINK_SCHEME } from '@main/app/deeplinks';+import { probeAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';+import {+ type SidecarEndpoint,+ type SidecarHost,+ writeWatchEnabled,+} from '@main/core/agent-runtime/impl/remote-sidecar-launcher';+import { httpGetJsonOverChannel } from '@main/core/agent-runtime/impl/sidecar-http';+import { sessionRuntimeManager } from '@main/core/sessions/session-runtime-manager';+import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';+import { viewStateService } from '@main/core/view-state/view-state-service';+import { db } from '@main/db/client';+import { sessions } from '@main/db/schema';+import { events } from '@main/lib/events';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';+import { getRemoteAgentLocation } from './agent-location';+import { connectRemoteAgent } from './connect-remote-agent';+import { getAgentById } from './getAgentById';+import { remoteSessionReconciler } from './remote-session-reconciler';+import { ensureRemoteWatcher, startRemoteDiscovery } from './remote-watcher';+import { buildKillTmuxScript, resetTmuxTargets } from './reset-remote-agent-tmux';++const SESSIONS_REQUEST_TIMEOUT_MS = 10_000;++interface SidecarSessionsResponse {+ sessions: Array<{ sessionId: string; roomId: string | null }>;+}++type RemoteConn = Awaited<ReturnType<typeof connectRemoteAgent>>;++/**+ * The live session ids the on-VM sidecar is running, or an empty list. Best+ * effort: the sidecar is about to be killed anyway, so a dead/unreachable+ * sidecar contributes nothing rather than aborting the reset — the DB rows still+ * cover the sessions this client knows about. Real teardown errors surface later,+ * when the tmux sessions are actually killed.+ */+async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<string[]> {+ let endpoint: SidecarEndpoint | null;+ try {+ endpoint = await probeAgentSidecar({+ providerId: agent.providerId,+ repoDir: conn.remoteRepoDir,+ deeplinkScheme: DEEPLINK_SCHEME,+ ctx: conn.ctx,+ connectionId: conn.connectionId,+ host: conn.host,+ });+ } catch (error) {+ log.warn('resetRemoteAgent: failed to probe sidecar for sessions', {+ agentId: agent.id,+ error: String(error),+ });+ return [];+ }+ if (!endpoint) return [];++ const channel = await conn.proxy.forwardOut(endpoint.port);+ try {+ const response = await httpGetJsonOverChannel<SidecarSessionsResponse>(channel, {+ port: endpoint.port,+ token: endpoint.token,+ path: '/sessions',+ timeoutMs: SESSIONS_REQUEST_TIMEOUT_MS,+ });+ return (response.sessions ?? []).map((s) => s.sessionId);+ } catch (error) {+ log.warn('resetRemoteAgent: failed to read sidecar /sessions', {+ agentId: agent.id,+ error: String(error),+ });+ return [];+ } finally {+ channel.destroy();+ }+}++/**+ * Kill the given tmux sessions on the remote host, failing loud: a real+ * `kill-session` failure or a broken SSH transport rejects the exec rather than+ * being swallowed. This is the "fail loud on remote teardown errors" the reset+ * must guarantee.+ */+async function killTmuxSessions(host: SidecarHost, sessionNames: string[]): Promise<void> {+ const script = buildKillTmuxScript(sessionNames);+ if (!script) return;+ await host.exec('sh', ['-c', script]);+}++/**+ * Drop a session's local footprint after its remote tmux pane is gone: tear down+ * its runtime, delete its row, clear its view-state + room badge, and tell the+ * renderer to remove it. Mirrors the remote-driven delete in+ * {@link remoteSessionReconciler}, so a wiped session does not linger as a ghost+ * row in any open window.+ */+async function removeLocalSession(sessionId: string): Promise<void> {+ await sessionRuntimeManager.teardownSession(sessionId).catch((error) => {+ log.warn('resetRemoteAgent: failed to teardown session runtime', {+ sessionId,+ error: String(error),+ });+ });+ switchRoomService.clearSession(sessionId);+ const deleted = await db.delete(sessions).where(eq(sessions.id, sessionId));+ await viewStateService.del(`session:${sessionId}`);+ if (deleted.changes === 0) return;+ events.emit(sessionDeletedChannel, { sessionId });+}++/**+ * Reset a remote agent: kill every one of its tmux sessions on the remote host —+ * the sidecar/watcher session and every agent (Claude Code) session — then bring+ * the agent back up fresh so it can start clean (CHOO-1656).+ *+ * The kill scope is the union of the sessions switchdash has rows for and the+ * sessions the VM sidecar reports live, so it covers sessions this client never+ * opened while staying scoped to THIS agent's sidecar (host + repo dir) rather+ * than sweeping every switchdash session on a shared host.+ *+ * Fails loud: a real remote teardown error (a `kill-session` that fails, a+ * broken SSH transport) propagates instead of being swallowed. Remote-only —+ * throws for a local agent.+ */+export async function resetRemoteAgent(agentId: string): Promise<void> {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error(`No agent with id ${agentId}`);+ const location = await getRemoteAgentLocation(agent);+ if (!location) {+ throw new Error(`Agent ${agentId} is not remote, so it cannot be reset.`);+ }++ // Stop this client's discovery loop before killing anything so a reconcile tick+ // cannot re-adopt a session from a stale snapshot mid-reset.+ remoteSessionReconciler.stop(agentId);++ const conn = await connectRemoteAgent(agent);++ // Silence the VM watcher first so it cannot auto-start a fresh session between+ // the /sessions snapshot and the kill (whose pane we would then miss).+ await writeWatchEnabled(conn.host, false);++ const dbSessionIds = (+ await db.select({ id: sessions.id }).from(sessions).where(eq(sessions.agentId, agentId))+ ).map((r) => r.id);+ const sidecarSessionIds = await fetchSidecarSessionIds(agent, conn);+ const sessionIds = [...new Set([...dbSessionIds, ...sidecarSessionIds])];++ await killTmuxSessions(conn.host, resetTmuxTargets(sessionIds, conn.remoteRepoDir));+ log.info('resetRemoteAgent: killed remote tmux sessions', {+ agentId,+ sessions: sessionIds.length,+ });++ await Promise.all(dbSessionIds.map((id) => removeLocalSession(id)));++ // Bring the agent back up fresh, the same way switchdash does at boot: re-ensure+ // the sidecar + watcher (when auto_session is on) and restart session discovery.+ await ensureRemoteWatcher(agentId);+ await startRemoteDiscovery(agentId);+ log.info('resetRemoteAgent: reset complete', { agentId });+}diff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.tsindex 6cf000bbc..74797a354 100644--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts@@ -1,6 +1,7 @@import { CommandPaletteModal } from '@renderer/features/command-palette/command-palette-modal';import { AddAgentModal } from '@renderer/features/locations/components/add-agent-modal/add-agent-modal';import { DeleteAgentModal } from '@renderer/features/locations/components/delete-agent-modal';+import { ResetAgentModal } from '@renderer/features/locations/components/reset-agent-modal';import { CreateSessionModal } from '@renderer/features/sessions/create-session-modal/create-session-modal';import { DeleteSessionModal } from '@renderer/features/sessions/delete-session-modal';import { RenameSessionModal } from '@renderer/features/sessions/rename-session-modal';@@ -36,6 +37,7 @@ export const modalRegistry = {addAgentModal: createModal(AddAgentModal),confirmActionModal: createModal(ConfirmActionDialog, { size: 'xs' }),deleteAgentModal: createModal(DeleteAgentModal, { size: 'sm' }),+ resetAgentModal: createModal(ResetAgentModal, { size: 'sm' }),confirmExternalLinkModal: createModal(ExternalLinkChoiceDialog, { size: 'sm' }),unsavedChangesModal: createModal(UnsavedChangesDialog, { size: 'xs' }),feedbackModal: createModal(FeedbackModal),diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/reset-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/reset-agent-modal.tsxnew file mode 100644index 000000000..5b7413e96--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/reset-agent-modal.tsx@@ -0,0 +1,49 @@+import { TriangleAlert } from 'lucide-react';+import type { BaseModalProps } from '@renderer/lib/modal/modal-provider';+import { Button } from '@renderer/lib/ui/button';+import { ConfirmButton } from '@renderer/lib/ui/confirm-button';+import {+ DialogContentArea,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@renderer/lib/ui/dialog';++export type ResetAgentModalArgs = {+ /** Display name for the agent (its Switch name, falling back to the location). */+ agentLabel: string;+};++type Props = BaseModalProps<void> & ResetAgentModalArgs;++export function ResetAgentModal({ agentLabel, onSuccess, onClose }: Props) {+ return (+ <>+ <DialogHeader showCloseButton={false}>+ <DialogTitle>Reset agent</DialogTitle>+ </DialogHeader>+ <DialogContentArea className="flex flex-col gap-4 pt-0">+ <p className="text-sm text-foreground-muted">+ <span className="font-medium text-foreground">{agentLabel}</span> will be reset.+ switchdash kills all of its remote sessions — the watcher and every running session — then+ restarts it fresh.+ </p>++ <div className="border-destructive/30 bg-destructive/10 flex items-start gap-2.5 rounded-md border p-3 text-sm">+ <TriangleAlert className="mt-0.5 size-4 shrink-0 text-foreground-destructive" />+ <span className="text-foreground-muted">+ Any in-progress work in those sessions will be lost. This can’t be undone.+ </span>+ </div>+ </DialogContentArea>+ <DialogFooter>+ <Button variant="outline" onClick={onClose}>+ Cancel+ </Button>+ <ConfirmButton variant="destructive" onClick={() => onSuccess()}>+ Reset+ </ConfirmButton>+ </DialogFooter>+ </>+ );+}diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsxindex 5341b69d6..6ba76b3f2 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx@@ -6,6 +6,7 @@ import {Loader2,Plus,RefreshCw,+ RotateCcw,Server,Trash2,TriangleAlert,@@ -25,6 +26,7 @@ import {import { hasSessionError } from '@renderer/features/sessions/stores/session-selectors';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { AgentIcon } from '@renderer/lib/components/agent-icon';+import { useToast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import {useNavigate,@@ -67,8 +69,9 @@ export const SidebarLocationItem = observer(function SidebarLocationItem({const { params: locationParams } = useParams('location');const { params: sessionParams } = useParams('session');const showCreateSessionModal = useShowModal('sessionModal');- const showAssignServerModal = useShowModal('assignServerModal');+ const showConfirmReset = useShowModal('resetAgentModal');const confirmDeleteAgent = useConfirmDeleteAgent();+ const { toastPromise } = useToast();// Resolve the agent's Switch identity so the "go to" button can open its// detail page in the gateway web app (parallel to a room's "go to" button).@@ -308,10 +311,26 @@ export const SidebarLocationItem = observer(function SidebarLocationItem({</SidebarMenuRow></ContextMenuTrigger><ContextMenuContent>- <ContextMenuItem onClick={() => showAssignServerModal({ locationId })}>- <Server className="size-4" />- Assign server- </ContextMenuItem>+ {location.data?.sshHost != null && agent && (+ <ContextMenuItem+ onClick={() => {+ showConfirmReset({+ agentLabel: locationLabel,+ onSuccess: () => {+ void toastPromise(rpc.agents.resetRemoteAgent({ agentId: agent.id }), {+ loading: `Resetting ${locationLabel}…`,+ success: `${locationLabel} was reset`,+ error: (error) =>+ `Failed to reset agent: ${error instanceof Error ? error.message : String(error)}`,+ });+ },+ });+ }}+ >+ <RotateCcw className="size-4" />+ Reset agent+ </ContextMenuItem>+ )}<ContextMenuItemvariant="destructive"onClick={() => {diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-toast.ts b/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-toast.tsindex 1905de9c9..8e4c8b1d8 100644--- a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-toast.ts+++ b/dash/apps/switchdash-desktop/src/renderer/lib/hooks/use-toast.ts@@ -27,8 +27,25 @@ function toast({ title, description, variant, action, icon }: Toast) {return sonnerToast(title ?? '', options);}+/**+ * Show a single toast that tracks a promise: a loading state while it runs, then+ * a success or error state when it settles. Use for actions with a noticeable+ * delay (e.g. a remote reset) so the user gets "working…" then "done" feedback+ * from one toast rather than a click with no acknowledgement.+ */+function toastPromise<T>(+ promise: Promise<T>,+ messages: { loading: string; success: string; error: (error: unknown) => string }+) {+ return sonnerToast.promise(promise, {+ loading: messages.loading,+ success: messages.success,+ error: (error: unknown) => messages.error(error),+ });+}+function useToast() {- return { toast };+ return { toast, toastPromise };}-export { toast, useToast };+export { toast, toastPromise, useToast };