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): wire the setup runner to real hosts; fix host-removal leaks (CHOO-1809)
switch-worker-louis-remote570371fb024c
diff --git a/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts b/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.tsindex bdabc0d72..68391cc68 100644--- a/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts+++ b/dash/apps/switchdash-desktop/src/main/core/dependencies/remote-dependency-manager.ts@@ -62,6 +62,15 @@ async function buildRemoteDependencyManager(sshHost: string): Promise<HostDepend* alias. Cached so repeated probe/install calls reuse one manager (and one* pooled SSH connection) per host.*/+/**+ * Forget a host's cached manager. Called when a host is removed: the cache is+ * keyed by alias, so without this a re-onboarded alias would reuse a manager+ * bound to the previous connection and its stale probe results.+ */+export function evictRemoteDependencyManager(sshHost: string): void {+ managerCache.delete(sshHost);+}+export function getRemoteDependencyManager(sshHost: string): Promise<HostDependencyManager> {const existing = managerCache.get(sshHost);if (existing) return existing;diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.tsindex 85e4f16c5..3ded2787b 100644--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts@@ -9,6 +9,7 @@ import type {import { isTransportFailure } from '@switchdash/core/exec';import { detectSwitchAgentRemote } from '@main/core/agents/detect-remote';import {+ evictRemoteDependencyManager,getRemoteDependencyManager,remoteDependencyDescriptor,} from '@main/core/dependencies/remote-dependency-manager';@@ -27,10 +28,22 @@ import { hostBlockedReason, type HostReachability } from '@shared/core/remote-hoimport type { ConnectionState, SshHealthState } from '@shared/core/ssh/ssh';import { createRPCController } from '@shared/lib/ipc/rpc';import type { SwitchAgentConfig } from '@shared/switch-agents';+import type { HostSetupPlan } from '@shared/core/remote-hosts/setup';+import { probeGhAuthStatus, type GhAuthStatus } from './gh-auth';import { listSshConfigHosts } from './list-ssh-config-hosts';import { hostReachabilityService } from './production-host-reachability';+import { deletePersistedReachability } from './reachability-store';+import {+ discardSetupPlan,+ ensureSetupPlan,+ readSetupPlan,+ runSetup,+ skipSetupStep,+} from './setup/host-setup-service';import { listRemoteHosts, removeRemoteHost, upsertRemoteHost, type RemoteHost } from './store';+export type { GhAuthStatus };+/** A single dependency's status on a remote host, enriched for the UI. */export type RemoteDependencyView = {id: string;@@ -51,8 +64,6 @@ export type RemoteDependencyView = {ghAuth?: GhAuthStatus;};-export type GhAuthStatus = { authenticated: boolean; account: string | null };-export type TestConnectionResult = { ok: true } | { ok: false; message: string };/** Live status of a host's pooled SSH connection, for the connection badge. */@@ -69,28 +80,6 @@ function hostConnectionStatus(sshHost: string): HostConnectionStatus {};}-/** Matches the account line of `gh auth status` across gh versions ("account NAME" / "as NAME"). */-const GH_AUTH_ACCOUNT_RE = /Logged in to \S+ (?:account|as) (\S+)/;--/**- * Check whether `gh` is authenticated on a remote host via `gh auth status`.- * Exit 0 means authenticated; a non-zero exit (which SshExecutionContext- * throws on) means not logged in. A transport failure propagates — a dead- * connection is not evidence of a missing login.- */-async function probeGhAuth(sshHost: string): Promise<GhAuthStatus> {- const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);- const ctx = new SshExecutionContext(proxy);- try {- const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status']);- const account = GH_AUTH_ACCOUNT_RE.exec(`${stdout}\n${stderr}`)?.[1] ?? null;- return { authenticated: true, account };- } catch (error) {- if (isTransportFailure(error)) throw error;- return { authenticated: false, account: null };- }-}-/*** Ad-hoc reachability check. Routed through the reachability service rather* than connecting directly, so a manual "Test connection" and the background@@ -125,7 +114,7 @@ async function probeDeps(sshHost: string): Promise<RemoteDependencyView[]> {// auth when the binary is present (probing gh auth without gh would just fail).const gh = views.find((v) => v.id === 'gh');if (gh && gh.status === 'available') {- gh.ghAuth = await probeGhAuth(sshHost);+ gh.ghAuth = await probeGhAuthStatus(sshHost);}return views;@@ -286,7 +275,38 @@ export const remoteHostsController = createRPCController({return upsertRemoteHost({ sshHost: params.sshHost, name: params.name });},- removeHost: (sshHost: string): Promise<void> => removeRemoteHost(sshHost),+ /**+ * Remove a host and everything keyed to it. Previously only the row was+ * deleted, leaving an orphaned reachability record and a cached dependency+ * manager bound to the old connection — so re-adding the same alias resumed+ * against stale state.+ */+ removeHost: async (sshHost: string): Promise<void> => {+ await removeRemoteHost(sshHost);+ await discardSetupPlan(sshHost);+ await deletePersistedReachability(sshHost);+ evictRemoteDependencyManager(sshHost);+ },++ /** The host's persisted setup plan, or null if setup has never been run. */+ getSetupPlan: (sshHost: string): Promise<HostSetupPlan | null> => readSetupPlan(sshHost),++ /**+ * Build or refresh the plan without running it — what the host page loads on+ * open. Merges onto any persisted progress rather than discarding it.+ */+ prepareSetup: (sshHost: string): Promise<HostSetupPlan> => ensureSetupPlan(sshHost),++ /**+ * Run (or resume) setup. Steps are checked and installed one at a time and+ * the run halts at the first required failure, holding its position so it can+ * be resumed rather than restarted.+ */+ runSetup: (sshHost: string): Promise<HostSetupPlan> => runSetup(sshHost),++ /** Move past a step the user has chosen not to fix, unblocking the rest. */+ skipSetupStep: (params: { sshHost: string; stepId: string }): Promise<HostSetupPlan> =>+ skipSetupStep(params.sshHost, params.stepId),/*** Detect the Switch agent configured in a remote working directory (reads itsdiff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/gh-auth.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/gh-auth.tsnew file mode 100644index 000000000..61a444403--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/gh-auth.ts@@ -0,0 +1,37 @@+/**+ * GitHub CLI authentication on a remote host.+ *+ * `gh` being on PATH is not enough to use it — it must also be logged in, and+ * that login is an interactive device flow. Extracted from the remote-hosts+ * controller so the setup runner (CHOO-1809) can probe auth as its own step+ * rather than as a side effect of a dependency sweep.+ */++import { isTransportFailure } from '@switchdash/core/exec';+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import { sshConnectionIdForHost } from '@main/core/locations/location-transport';+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';++export type GhAuthStatus = { authenticated: boolean; account: string | null };++/** Matches the account line of `gh auth status` across gh versions ("account NAME" / "as NAME"). */+const GH_AUTH_ACCOUNT_RE = /Logged in to \S+ (?:account|as) (\S+)/;++/**+ * Whether `gh` is authenticated on a remote host. Exit 0 means authenticated; a+ * non-zero exit (which SshExecutionContext throws on) means not logged in. A+ * transport failure propagates rather than being read as "not logged in" — a+ * dead connection is not evidence about the login state.+ */+export async function probeGhAuthStatus(sshHost: string): Promise<GhAuthStatus> {+ const proxy = await ensureSshConnected(sshConnectionIdForHost(sshHost), sshHost);+ const ctx = new SshExecutionContext(proxy);+ try {+ const { stdout, stderr } = await ctx.exec('gh', ['auth', 'status']);+ const account = GH_AUTH_ACCOUNT_RE.exec(`${stdout}\n${stderr}`)?.[1] ?? null;+ return { authenticated: true, account };+ } catch (error) {+ if (isTransportFailure(error)) throw error;+ return { authenticated: false, account: null };+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-service.tsnew file mode 100644index 000000000..f55794c65--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts@@ -0,0 +1,220 @@+/**+ * Wires the setup runner to a real remote host (CHOO-1809).+ *+ * The runner is deliberately ignorant of SSH, dependency managers and plugin+ * registries — it only knows how to sequence steps. This module supplies the+ * `check` and `install` implementations for each step kind, and owns the+ * per-host lifecycle (build, resume, run, skip, discard).+ */++import { HostDependencyManager } from '@switchdash/core/deps/runtime';+import {+ getRemoteDependencyManager,+ remoteDependencyDescriptor,+} from '@main/core/dependencies/remote-dependency-manager';+import { CORE_DEPENDENCIES } from '@main/core/dependencies/core-dependencies';+import { getRemoteSwitchSetupService } from '@main/core/switch-setup/remote-switch-setup';+import { log } from '@main/lib/logger';+import {+ hostSetupPlanEventChannel,+ type DependencyCheckOutcome,+ type HostSetupPlan,+ type HostSetupStep,+} from '@shared/core/remote-hosts/setup';+import { events } from '@main/lib/events';+import { hostReachabilityService } from '../production-host-reachability';+import { probeGhAuthStatus } from '../gh-auth';+import { HostSetupRunner, type StepCheckResult, type StepInstallResult } from './host-setup-runner';+import {+ agentPluginStepId,+ buildSetupPlan,+ GH_AUTH_STEP_ID,+ reconcileInterruptedPlan,+} from './plan-builder';+import { deleteSetupPlan, getSetupPlan, saveSetupPlan } from './setup-plan-store';++/**+ * Translate a probed dependency into an observation.+ *+ * The dependency manager collapses "installed but below minVersion" into+ * `status: 'error'` with a message; we recover the distinction here, because+ * "too old" is actionable (upgrade) in a way that "we could not tell" is not.+ * Anything else reporting `error` is genuinely undetermined and must surface as+ * `unknown` rather than being guessed at.+ */+export function outcomeForDependency(+ state: { status: string; version: string | null; error?: string },+ hasMinVersion: boolean+): { outcome: DependencyCheckOutcome; version: string | null; error?: string } {+ if (state.status === 'available') {+ return { outcome: 'satisfied', version: state.version };+ }+ if (state.status === 'missing') {+ return { outcome: 'missing', version: null };+ }+ if (hasMinVersion && state.version) {+ return { outcome: 'wrong-version', version: state.version, error: state.error };+ }+ return { outcome: 'unknown', version: state.version, error: state.error };+}++/** Runners are per-host so two hosts can be set up at once, but a host only once. */+const runners = new Map<string, HostSetupRunner>();++async function plannableAgentTypes(sshHost: string) {+ const service = await getRemoteSwitchSetupService(sshHost);+ const statuses = await service.listAgentTypeStatuses();+ return statuses+ .filter((status) => status.supported)+ .map((status) => ({+ agentId: status.agentId,+ name: remoteDependencyDescriptor(status.agentId)?.name ?? status.agentId,+ }));+}++/**+ * Build or refresh a host's plan. Rebuilding merges onto whatever was+ * persisted, so progress is preserved when the known dependency set changes,+ * and any step interrupted by the app closing is reset to pending rather than+ * left claiming a state nobody verified.+ */+export async function ensureSetupPlan(sshHost: string): Promise<HostSetupPlan> {+ const existing = await getSetupPlan(sshHost);+ const now = new Date().toISOString();++ const plan = buildSetupPlan({+ sshHost,+ coreDependencies: CORE_DEPENDENCIES.map((dep) => ({ id: dep.id, name: dep.name })),+ agentTypes: await plannableAgentTypes(sshHost),+ existing: existing ? reconcileInterruptedPlan(existing, now) : null,+ now,+ });++ await saveSetupPlan(plan);+ events.emit(hostSetupPlanEventChannel, plan);+ return plan;+}++/** The persisted plan, without rebuilding it. Null when the host has never run setup. */+export async function readSetupPlan(sshHost: string): Promise<HostSetupPlan | null> {+ return await getSetupPlan(sshHost);+}++function stepAgentId(step: HostSetupStep): string {+ return step.kind === 'agent-plugin' ? step.id.replace(/:plugin$/, '') : step.id;+}++function runnerFor(sshHost: string, manager: HostDependencyManager): HostSetupRunner {+ const existing = runners.get(sshHost);+ if (existing) return existing;++ const runner = new HostSetupRunner({+ sshHost,+ load: (host) => getSetupPlan(host),+ save: (plan) => saveSetupPlan(plan),+ publish: (plan) => events.emit(hostSetupPlanEventChannel, plan),+ requireReachable: (host) => hostReachabilityService.requireReachable(host),+ canInstall: (step) => {+ // The gh device flow is interactive by nature — it needs a terminal the+ // user types into, so it can never be part of an unattended run.+ if (step.kind === 'gh-auth') return false;+ if (step.kind === 'agent-plugin') return true;+ return manager.getInstallOptions(step.id).length > 0;+ },+ check: (step) => checkStep(sshHost, manager, step),+ install: (step) => installStep(sshHost, manager, step),+ });++ runners.set(sshHost, runner);+ return runner;+}++async function checkStep(+ sshHost: string,+ manager: HostDependencyManager,+ step: HostSetupStep+): Promise<StepCheckResult> {+ if (step.kind === 'gh-auth') {+ const status = await probeGhAuthStatus(sshHost);+ return status.authenticated+ ? { outcome: 'satisfied', version: status.account }+ : { outcome: 'missing' };+ }++ if (step.kind === 'agent-plugin') {+ const service = await getRemoteSwitchSetupService(sshHost);+ const statuses = await service.listAgentTypeStatuses();+ const agentId = stepAgentId(step);+ const status = statuses.find((s) => s.agentId === agentId);+ if (!status) {+ return {+ outcome: 'unknown',+ error: `${agentId} is no longer a known agent type on this host.`,+ };+ }+ return status.installed+ ? { outcome: 'satisfied', version: status.installedVersion ?? null }+ : { outcome: 'missing' };+ }++ const state = await manager.probe(step.id);+ return outcomeForDependency(state, Boolean(remoteDependencyDescriptor(step.id)?.minVersion));+}++async function installStep(+ sshHost: string,+ manager: HostDependencyManager,+ step: HostSetupStep+): Promise<StepInstallResult> {+ if (step.kind === 'agent-plugin') {+ const service = await getRemoteSwitchSetupService(sshHost);+ const result = await service.install(stepAgentId(step));+ return result.success+ ? { ok: true }+ : { ok: false, error: result.message ?? `Could not install the Switch connector.` };+ }++ const result = await manager.install(step.id);+ if (result.success) return { ok: true };++ // Surface the installer's own words. The old page discarded these and+ // rendered a bare "Install failed" — or, for a Result-typed failure, nothing.+ const error = result.error as { message?: string; output?: string; type?: string };+ return {+ ok: false,+ error: error.message ?? error.type ?? 'Install failed.',+ output: error.output ?? null,+ };+}++/** Run (or resume) a host's setup. Returns the plan as it stands when the run stops. */+export async function runSetup(sshHost: string): Promise<HostSetupPlan> {+ const plan = await ensureSetupPlan(sshHost);+ const manager = await getRemoteDependencyManager(sshHost);+ try {+ return await runnerFor(sshHost, manager).run(plan);+ } catch (error) {+ log.warn('[HostSetup] run stopped', {+ event: 'host-setup-run-stopped',+ sshHost,+ error: String((error as Error)?.message ?? error),+ });+ throw error;+ }+}++/** Move past a step the user has chosen not to fix, unblocking the rest. */+export async function skipSetupStep(sshHost: string, stepId: string): Promise<HostSetupPlan> {+ const plan = await getSetupPlan(sshHost);+ if (!plan) throw new Error(`No setup plan exists for ${sshHost}`);+ const manager = await getRemoteDependencyManager(sshHost);+ return await runnerFor(sshHost, manager).skip(plan, stepId);+}++/** Drop a host's plan and its runner — called when the host is removed. */+export async function discardSetupPlan(sshHost: string): Promise<void> {+ runners.delete(sshHost);+ await deleteSetupPlan(sshHost);+}++export { agentPluginStepId, GH_AUTH_STEP_ID };diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.test.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.test.tsnew file mode 100644index 000000000..0db8057bd--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.test.ts@@ -0,0 +1,221 @@+import { describe, expect, it } from 'vitest';+import type { HostSetupPlan, HostSetupStep } from '@shared/core/remote-hosts/setup';+import {+ agentPluginStepId,+ buildSetupPlan,+ GH_AUTH_STEP_ID,+ reconcileInterruptedPlan,+} from './plan-builder';++const NOW = '2026-02-02T00:00:00.000Z';++const CORE = [+ { id: 'git', name: 'Git' },+ { id: 'node', name: 'Node.js' },+ { id: 'tmux', name: 'tmux' },+ { id: 'gh', name: 'GitHub CLI' },+];+const AGENTS = [{ agentId: 'claude-code', name: 'Claude Code' }];++function build(existing: HostSetupPlan | null = null) {+ return buildSetupPlan({+ sshHost: 'dev-vm',+ coreDependencies: CORE,+ agentTypes: AGENTS,+ existing,+ now: NOW,+ });+}++describe('buildSetupPlan', () => {+ it('orders core tools first, then gh login, then each agent CLI before its plugin', () => {+ expect(build().steps.map((s) => s.id)).toEqual([+ 'git',+ 'node',+ 'tmux',+ 'gh',+ GH_AUTH_STEP_ID,+ 'claude-code',+ agentPluginStepId('claude-code'),+ ]);+ });++ it('marks gh and its login optional so they cannot strand a host', () => {+ const plan = build();+ const optional = plan.steps.filter((s) => s.optional).map((s) => s.id);+ expect(optional).toEqual(['gh', GH_AUTH_STEP_ID]);+ });++ it('keeps the required core tools required', () => {+ const plan = build();+ for (const id of ['git', 'node', 'tmux']) {+ expect(plan.steps.find((s) => s.id === id)!.optional).toBe(false);+ }+ });++ it('declares that agent CLIs need node, since they install via npm', () => {+ const cli = build().steps.find((s) => s.id === 'claude-code')!;+ expect(cli.dependsOn).toContain('node');+ });++ it('declares that a plugin needs its own CLI', () => {+ const plugin = build().steps.find((s) => s.id === agentPluginStepId('claude-code'))!;+ expect(plugin.dependsOn).toEqual(['claude-code']);+ });++ it('starts every step pending with no outcome', () => {+ for (const step of build().steps) {+ expect(step.state).toBe('pending');+ expect(step.outcome).toBeNull();+ }+ });++ it('assigns the right kind to each step', () => {+ const kinds = Object.fromEntries(build().steps.map((s) => [s.id, s.kind]));+ expect(kinds.git).toBe('core-dependency');+ expect(kinds[GH_AUTH_STEP_ID]).toBe('gh-auth');+ expect(kinds['claude-code']).toBe('agent-cli');+ expect(kinds[agentPluginStepId('claude-code')]).toBe('agent-plugin');+ });+});++describe('buildSetupPlan — rebuilding onto an existing plan', () => {+ function existingPlan(steps: Partial<HostSetupStep>[]): HostSetupPlan {+ return {+ sshHost: 'dev-vm',+ status: 'halted',+ currentStepId: 'node',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ steps: steps.map((patch) => ({+ id: 'x',+ kind: 'core-dependency',+ name: 'x',+ state: 'pending',+ outcome: null,+ version: null,+ error: null,+ output: null,+ optional: false,+ dependsOn: [],+ updatedAt: '2026-01-01T00:00:00.000Z',+ ...patch,+ })) as HostSetupStep[],+ };+ }++ it('preserves progress rather than discarding it', () => {+ const plan = build(+ existingPlan([+ { id: 'git', state: 'satisfied', outcome: 'satisfied', version: '2.43.0' },+ { id: 'node', state: 'failed', outcome: 'missing', error: 'apt failed', output: 'E:' },+ ])+ );++ const git = plan.steps.find((s) => s.id === 'git')!;+ expect(git.state).toBe('satisfied');+ expect(git.version).toBe('2.43.0');++ const node = plan.steps.find((s) => s.id === 'node')!;+ expect(node.state).toBe('failed');+ expect(node.error).toBe('apt failed');+ expect(node.output).toBe('E:');+ });++ it('adds newly known steps as pending without touching the rest', () => {+ const plan = build(existingPlan([{ id: 'git', state: 'satisfied', outcome: 'satisfied' }]));++ expect(plan.steps.find((s) => s.id === 'git')!.state).toBe('satisfied');+ expect(plan.steps.find((s) => s.id === 'claude-code')!.state).toBe('pending');+ });++ it('drops steps that are no longer known', () => {+ const plan = build(existingPlan([{ id: 'retired-agent', state: 'satisfied' }]));+ expect(plan.steps.some((s) => s.id === 'retired-agent')).toBe(false);+ });++ it('keeps the original creation time and the halted status', () => {+ const plan = build(existingPlan([{ id: 'git', state: 'satisfied' }]));+ expect(plan.createdAt).toBe('2026-01-01T00:00:00.000Z');+ expect(plan.status).toBe('halted');+ expect(plan.currentStepId).toBe('node');+ });++ it('re-imposes canonical order even if the stored order differed', () => {+ const plan = build(+ existingPlan([+ { id: 'tmux', state: 'satisfied' },+ { id: 'git', state: 'satisfied' },+ ])+ );+ expect(plan.steps.map((s) => s.id).slice(0, 3)).toEqual(['git', 'node', 'tmux']);+ });+});++describe('reconcileInterruptedPlan', () => {+ function planWith(state: HostSetupStep['state'], status: HostSetupPlan['status']): HostSetupPlan {+ return {+ sshHost: 'dev-vm',+ status,+ currentStepId: 'node',+ createdAt: NOW,+ updatedAt: NOW,+ steps: [+ {+ id: 'git',+ kind: 'core-dependency',+ name: 'Git',+ state: 'satisfied',+ outcome: 'satisfied',+ version: '2.43.0',+ error: null,+ output: null,+ optional: false,+ dependsOn: [],+ updatedAt: NOW,+ },+ {+ id: 'node',+ kind: 'core-dependency',+ name: 'Node.js',+ state,+ outcome: null,+ version: null,+ error: null,+ output: null,+ optional: false,+ dependsOn: [],+ updatedAt: NOW,+ },+ ],+ };+ }++ it('resets a step the app died mid-install on — never to satisfied', () => {+ const reconciled = reconcileInterruptedPlan(planWith('installing', 'running'), NOW);+ const node = reconciled.steps.find((s) => s.id === 'node')!;+ expect(node.state).toBe('pending');+ expect(node.outcome).toBeNull();+ });++ it('resets a step interrupted mid-check', () => {+ const reconciled = reconcileInterruptedPlan(planWith('checking', 'running'), NOW);+ expect(reconciled.steps.find((s) => s.id === 'node')!.state).toBe('pending');+ });++ it('clears a stale running status so the plan is startable again', () => {+ expect(reconcileInterruptedPlan(planWith('installing', 'running'), NOW).status).toBe('idle');+ });++ it('leaves genuinely finished work alone', () => {+ const reconciled = reconcileInterruptedPlan(planWith('installing', 'running'), NOW);+ const git = reconciled.steps.find((s) => s.id === 'git')!;+ expect(git.state).toBe('satisfied');+ expect(git.version).toBe('2.43.0');+ });++ it('is a no-op for a cleanly halted plan', () => {+ const plan = planWith('failed', 'halted');+ expect(reconcileInterruptedPlan(plan, NOW)).toBe(plan);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.ts b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.tsnew file mode 100644index 000000000..548dbd117--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/plan-builder.ts@@ -0,0 +1,177 @@+/**+ * Builds a host's ordered setup plan (CHOO-1809).+ *+ * The order is the point. Onboarding used to present every prerequisite at once+ * and leave the user to infer the sequence — which mattered, because the agent+ * CLIs are installed with npm and therefore need Node first. Here the order is+ * declared once, in one place:+ *+ * 1. core host tools, in dependency order (git → node → tmux → …)+ * 2. gh, then its interactive login+ * 3. per agent type: its CLI, then the Switch connector plugin+ *+ * Rebuilding is **merge, not replace**. A plan is rebuilt whenever the set of+ * known dependencies changes (a new agent type ships, say), and discarding the+ * existing states would silently undo work the user already did. Steps that+ * survive a rebuild keep their state; steps that disappear are dropped.+ */++import {+ type HostSetupPlan,+ type HostSetupStep,+ type HostSetupStepKind,+} from '@shared/core/remote-hosts/setup';++/** A dependency switchdash knows how to check on the host. */+export type PlannableDependency = {+ id: string;+ name: string;+};++/** An agent type that can run under Switch, and therefore needs CLI + plugin. */+export type PlannableAgentType = {+ agentId: string;+ name: string;+};++export type BuildPlanInput = {+ sshHost: string;+ /** Core host tools, already in the order they should be installed. */+ coreDependencies: PlannableDependency[];+ /** Agent types worth offering — only those the Switch plugin supports. */+ agentTypes: PlannableAgentType[];+ /** Existing plan to merge onto, when one has been persisted. */+ existing: HostSetupPlan | null;+ now: string;+};++/** Step id for an agent type's Switch connector plugin. */+export function agentPluginStepId(agentId: string): string {+ return `${agentId}:plugin`;+}++/** Step id for the interactive `gh auth login`. */+export const GH_AUTH_STEP_ID = 'gh:auth';++function blankStep(+ id: string,+ kind: HostSetupStepKind,+ name: string,+ now: string,+ options: { optional?: boolean; dependsOn?: string[] } = {}+): HostSetupStep {+ return {+ id,+ kind,+ name,+ state: 'pending',+ outcome: null,+ version: null,+ error: null,+ output: null,+ optional: options.optional ?? false,+ dependsOn: options.dependsOn ?? [],+ updatedAt: now,+ };+}++export function buildSetupPlan(input: BuildPlanInput): HostSetupPlan {+ const { sshHost, coreDependencies, agentTypes, existing, now } = input;+ const steps: HostSetupStep[] = [];++ for (const dep of coreDependencies) {+ // gh is required-but-deferrable: agents commonly want it, but it needs an+ // interactive device-flow login that a user may reasonably postpone without+ // the host being unusable. Blocking onboarding on it strands the host.+ const optional = dep.id === 'gh';+ steps.push(blankStep(dep.id, 'core-dependency', dep.name, now, { optional }));++ if (dep.id === 'gh') {+ steps.push(+ blankStep(GH_AUTH_STEP_ID, 'gh-auth', 'GitHub CLI login', now, {+ optional: true,+ dependsOn: ['gh'],+ })+ );+ }+ }++ for (const agent of agentTypes) {+ steps.push(+ blankStep(agent.agentId, 'agent-cli', agent.name, now, {+ // The CLIs install via npm, so Node has to be in place first. Declared+ // rather than implied by list position.+ dependsOn: coreDependencies.some((d) => d.id === 'node') ? ['node'] : [],+ })+ );+ steps.push(+ blankStep(+ agentPluginStepId(agent.agentId),+ 'agent-plugin',+ `${agent.name} · Switch connector`,+ now,+ { dependsOn: [agent.agentId] }+ )+ );+ }++ return {+ sshHost,+ status: existing?.status ?? 'idle',+ steps: existing ? mergeSteps(steps, existing.steps) : steps,+ currentStepId: existing?.currentStepId ?? null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ };+}++/**+ * Carry prior progress onto a freshly built plan. The new plan defines which+ * steps exist and in what order; the old one contributes what we already know+ * about the steps that still exist.+ */+function mergeSteps(fresh: HostSetupStep[], previous: HostSetupStep[]): HostSetupStep[] {+ const byId = new Map(previous.map((step) => [step.id, step]));+ return fresh.map((step) => {+ const prior = byId.get(step.id);+ if (!prior) return step;+ return {+ ...step,+ state: prior.state,+ outcome: prior.outcome,+ version: prior.version,+ error: prior.error,+ output: prior.output,+ updatedAt: prior.updatedAt,+ };+ });+}++/**+ * Reset a plan's transient states so a resumed run re-observes rather than+ * trusting what a previous process was mid-way through. Anything left+ * `checking` or `installing` when the app died is of unknown truth — the one+ * thing it must not become is `satisfied`.+ */+export function reconcileInterruptedPlan(plan: HostSetupPlan, now: string): HostSetupPlan {+ const interrupted = plan.steps.some(+ (step) => step.state === 'checking' || step.state === 'installing'+ );+ if (!interrupted && plan.status !== 'running') return plan;++ return {+ ...plan,+ status: plan.status === 'running' ? 'idle' : plan.status,+ steps: plan.steps.map((step) =>+ step.state === 'checking' || step.state === 'installing'+ ? {+ ...step,+ state: 'pending',+ outcome: null,+ error: null,+ updatedAt: now,+ }+ : step+ ),+ };+}