Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Merge origin/main into the remote-host onboarding rewrite (CHOO-1809)

switch-worker-louis-remote94b90d9b4bea
diff --cc core/uv.lock
index 44a6dddc6,862b7f2f5..33a3bede3
--- a/core/uv.lock
+++ b/core/uv.lock
@@@ -2433,7 -2433,7 +2433,7 @@@ wheels =
[[package]]
name = "switch-core"
- version = "0.9.0"
-version = "0.10.0"
++version = "0.11.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts
index 5eded504b,b4742840c..95b5e9668
--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/controller.ts
@@@ -52,7 -47,7 +52,7 @@@ export type RemoteDependencyView =
/**
* GitHub CLI auth status. Present only on the `gh` dependency once its binary
* is available — `gh` being installed is not enough to use it, it must also be
-- * authenticated (`gh auth status`).
++ * authenticated and hold the `read:packages` scope.
*/
ghAuth?: GhAuthStatus;
};
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/gh-auth.ts
index 61a444403,000000000..67e564b0c
mode 100644,000000..100644
--- 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.ts
@@@ -1,37 -1,0 +1,95 @@@
+/**
+ * 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.
++ * `gh` being on PATH is not enough to use it — it must also be logged in with a
++ * token that can read GitHub Packages, 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';
++import {
++ GH_AUTH_STATUS_ARGS,
++ type GhAuthState,
++ parseGhAuthStatus,
++ READ_PACKAGES_SCOPE,
++} from '@shared/core/npm-registry';
+
- export type GhAuthStatus = { authenticated: boolean; account: string | null };
++export type GhAuthStatus = {
++ authenticated: boolean;
++ account: string | null;
++ /**
++ * Whether the token can read GitHub Packages.
++ *
++ * Authenticated is not sufficient: `gh auth login` requests `gist`,
++ * `read:org`, `repo` and `workflow`, and not `read:packages`. Sessions on
++ * this host fetch their MCP runtime from GitHub Packages, so without it they
++ * start with no tools and the registry's `403 … does not match expected
++ * scopes` is the only clue — reported nowhere near the host that caused it.
++ */
++ canReadPackages: boolean;
++ /** Why the credential is unusable, when it is. Null when it is fine. */
++ detail: 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+)/;
++const NOT_LOGGED_IN: GhAuthStatus = {
++ authenticated: false,
++ account: null,
++ canReadPackages: false,
++ detail: 'Not logged in to GitHub on this host.',
++};
++
++function statusFrom(state: GhAuthState): GhAuthStatus {
++ switch (state.status) {
++ case 'ok':
++ return { authenticated: true, account: state.login, canReadPackages: true, detail: null };
++ case 'missing-scope':
++ return {
++ authenticated: true,
++ account: state.login,
++ canReadPackages: false,
++ detail: `The GitHub token is missing the ${READ_PACKAGES_SCOPE} scope.`,
++ };
++ case 'invalid':
++ return { ...NOT_LOGGED_IN, detail: state.detail };
++ case 'unknown':
++ // The check did not apply — do not invent a fault the host may not have.
++ return { authenticated: true, account: null, canReadPackages: true, detail: null };
++ }
++}
+
+/**
- * 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.
++ * What `gh` on a remote host will do with the credentials it currently has.
++ *
++ * A non-zero exit (which SshExecutionContext throws on) means `gh` is missing
++ * or has no login at all. A transport failure propagates rather than being read
++ * as "not logged in" — a dead connection is not evidence about the login state.
++ *
++ * `--json` exits zero even when the token is rejected, so an unusable
++ * credential arrives as a parsed `invalid` rather than as a throw, and is
++ * reported as not authenticated: a token the API refuses is no better than
++ * none, and saying "authenticated" of it sends the user looking elsewhere.
+ */
+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 };
++ const { stdout } = await ctx.exec('gh', GH_AUTH_STATUS_ARGS);
++ return statusFrom(parseGhAuthStatus(stdout));
+ } catch (error) {
+ if (isTransportFailure(error)) throw error;
- return { authenticated: false, account: null };
++ // Older gh versions reject `--json` and exit non-zero with nothing useful
++ // to parse; they land here alongside a genuinely logged-out host. The
++ // sign-in flow that follows is the right answer for both.
++ const stdout = (error as { stdout?: string } | undefined)?.stdout;
++ if (stdout) {
++ const state = parseGhAuthStatus(stdout);
++ if (state.status !== 'unknown') return statusFrom(state);
++ }
++ return NOT_LOGGED_IN;
+ }
+}
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.test.ts
index c2505f90f,000000000..6f3a0982d
mode 100644,000000..100644
--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.test.ts
@@@ -1,404 -1,0 +1,444 @@@
+import { describe, expect, it, vi } from 'vitest';
+import type { HostSetupPlan, HostSetupStep } from '@shared/core/remote-hosts/setup';
+import {
+ HostSetupAbortedError,
+ HostSetupRunner,
+ type StepCheckResult,
+ type StepInstallResult,
+} from './host-setup-runner';
+
+function step(id: string, patch: Partial<HostSetupStep> = {}): HostSetupStep {
+ return {
+ id,
+ kind: 'core-dependency',
+ name: id,
+ state: 'pending',
+ outcome: null,
+ version: null,
+ error: null,
+ output: null,
+ optional: false,
+ dependsOn: [],
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ ...patch,
+ };
+}
+
+function plan(steps: HostSetupStep[]): HostSetupPlan {
+ return {
+ sshHost: 'dev-vm',
+ status: 'idle',
+ steps,
+ currentStepId: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ };
+}
+
+type Harness = {
+ checks: Record<string, StepCheckResult[]>;
+ installs: Record<string, StepInstallResult>;
+ canInstall?: (id: string) => boolean;
+ reachable?: boolean;
+};
+
+class Unreachable extends Error {}
+
+function makeRunner(harness: Harness) {
+ const saved: HostSetupPlan[] = [];
+ const published: HostSetupPlan[] = [];
+ const installOrder: string[] = [];
+ const inFlight = { count: 0, max: 0 };
+
+ const runner = new HostSetupRunner({
+ sshHost: 'dev-vm',
+ load: async () => null,
+ save: async (p) => void saved.push(structuredClone(p)),
+ publish: (p) => published.push(structuredClone(p)),
+ check: async (s) => {
+ const queue = harness.checks[s.id] ?? [{ outcome: 'satisfied' }];
+ return queue.length > 1 ? queue.shift()! : queue[0]!;
+ },
+ install: async (s) => {
+ installOrder.push(s.id);
+ inFlight.count += 1;
+ inFlight.max = Math.max(inFlight.max, inFlight.count);
+ await Promise.resolve();
+ inFlight.count -= 1;
+ return harness.installs[s.id] ?? { ok: true };
+ },
+ canInstall: (s) => harness.canInstall?.(s.id) ?? true,
+ requireReachable: () => {
+ if (harness.reachable === false) throw new Unreachable('host down');
+ },
+ now: () => new Date('2026-02-02T00:00:00.000Z'),
+ });
+
+ return { runner, saved, published, installOrder, inFlight };
+}
+
+const stateOf = (p: HostSetupPlan, id: string) => p.steps.find((s) => s.id === id)!.state;
+
+describe('HostSetupRunner', () => {
+ it('marks already-satisfied steps satisfied without installing', async () => {
+ const { runner, installOrder } = makeRunner({
+ checks: { git: [{ outcome: 'satisfied', version: '2.43.0' }] },
+ installs: {},
+ });
+
+ const result = await runner.run(plan([step('git')]));
+
+ expect(result.status).toBe('complete');
+ expect(stateOf(result, 'git')).toBe('satisfied');
+ expect(installOrder).toEqual([]);
+ });
+
+ it('installs a missing dependency and verifies it afterwards', async () => {
+ const { runner, installOrder } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }, { outcome: 'satisfied', version: '22.0.0' }] },
+ installs: { node: { ok: true } },
+ });
+
+ const result = await runner.run(plan([step('node')]));
+
+ expect(installOrder).toEqual(['node']);
+ expect(stateOf(result, 'node')).toBe('satisfied');
+ expect(result.steps[0]!.version).toBe('22.0.0');
+ expect(result.status).toBe('complete');
+ });
+
+ it('fails the step when an install reports success but verification disagrees', async () => {
+ // The installer's exit code is a claim; only the re-check is evidence.
+ const { runner } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }, { outcome: 'missing' }] },
+ installs: { node: { ok: true } },
+ });
+
+ const result = await runner.run(plan([step('node')]));
+
+ expect(stateOf(result, 'node')).toBe('failed');
+ expect(result.steps[0]!.error).toContain('still reports "missing" after installing');
+ expect(result.status).toBe('halted');
+ });
+
+ it('installs strictly one at a time, in plan order', async () => {
+ const { runner, installOrder, inFlight } = makeRunner({
+ checks: {
+ git: [{ outcome: 'missing' }, { outcome: 'satisfied' }],
+ node: [{ outcome: 'missing' }, { outcome: 'satisfied' }],
+ tmux: [{ outcome: 'missing' }, { outcome: 'satisfied' }],
+ },
+ installs: {},
+ });
+
+ await runner.run(plan([step('git'), step('node'), step('tmux')]));
+
+ expect(installOrder).toEqual(['git', 'node', 'tmux']);
+ expect(inFlight.max).toBe(1);
+ });
+
+ it('halts on failure, keeps earlier progress, and blocks later steps', async () => {
+ const { runner, installOrder } = makeRunner({
+ checks: {
+ git: [{ outcome: 'satisfied' }],
+ node: [{ outcome: 'missing' }],
+ tmux: [{ outcome: 'missing' }],
+ },
+ installs: { node: { ok: false, error: 'apt-get failed', output: 'E: Unable to locate' } },
+ });
+
+ const result = await runner.run(plan([step('git'), step('node'), step('tmux')]));
+
+ expect(result.status).toBe('halted');
+ expect(stateOf(result, 'git')).toBe('satisfied'); // step 1 is not discarded
+ expect(stateOf(result, 'node')).toBe('failed');
+ expect(stateOf(result, 'tmux')).toBe('blocked'); // never attempted, and says so
+ expect(installOrder).toEqual(['node']); // stopped; tmux was not installed
+ expect(result.currentStepId).toBe('node');
+ });
+
+ it('preserves the failing step error and command output', async () => {
+ const { runner } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }] },
+ installs: { node: { ok: false, error: 'permission denied', output: 'sudo: no tty' } },
+ });
+
+ const result = await runner.run(plan([step('node')]));
+
+ expect(result.steps[0]!.error).toBe('permission denied');
+ expect(result.steps[0]!.output).toBe('sudo: no tty');
+ });
+
+ it('resumes from the failed step without redoing satisfied ones', async () => {
+ // Each runner gets its own check queues — sharing them would let the first
+ // run consume the second's answers and hide whether resume really re-probes.
+ const first = makeRunner({
+ checks: { git: [{ outcome: 'satisfied' }], node: [{ outcome: 'missing' }] },
+ installs: { node: { ok: false, error: 'transient' } },
+ });
+ const halted = await first.runner.run(plan([step('git'), step('node')]));
+ expect(halted.status).toBe('halted');
+
+ // Resume with the persisted plan, exactly as a restart would. node is still
+ // missing, so it must be re-attempted; git is satisfied and must not be.
+ const second = makeRunner({
+ checks: {
+ git: [{ outcome: 'satisfied' }],
+ node: [{ outcome: 'missing' }, { outcome: 'satisfied' }],
+ },
+ installs: { node: { ok: true } },
+ });
+ const resumed = await second.runner.run(halted);
+
+ expect(resumed.status).toBe('complete');
+ expect(second.installOrder).toEqual(['node']); // git was not re-installed
+ });
+
+ it('records unknown — never missing — when a probe throws', async () => {
+ const runner = new HostSetupRunner({
+ sshHost: 'dev-vm',
+ load: async () => null,
+ save: async () => {},
+ publish: () => {},
+ check: async () => {
+ throw new Error('ssh channel closed');
+ },
+ install: async () => ({ ok: true }),
+ canInstall: () => true,
+ requireReachable: () => {},
+ now: () => new Date('2026-02-02T00:00:00.000Z'),
+ });
+
+ const result = await runner.run(plan([step('docker')]));
+
+ expect(result.steps[0]!.outcome).toBe('unknown');
+ expect(result.steps[0]!.state).toBe('failed');
+ expect(result.steps[0]!.error).toContain('ssh channel closed');
+ });
+
+ it('never reports an unverifiable step as satisfied', async () => {
+ const { runner } = makeRunner({
+ checks: { docker: [{ outcome: 'unknown', error: 'could not tell' }] },
+ installs: {},
+ });
+
+ const result = await runner.run(plan([step('docker')]));
+
+ expect(stateOf(result, 'docker')).not.toBe('satisfied');
+ expect(result.status).toBe('halted');
+ });
+
+ it('does not try to install a dependency that is installed but not running', async () => {
+ const { runner, installOrder } = makeRunner({
+ checks: { docker: [{ outcome: 'not-running' }] },
+ installs: {},
+ });
+
+ const result = await runner.run(plan([step('docker')]));
+
+ expect(installOrder).toEqual([]);
+ expect(result.steps[0]!.error).toContain('not running');
+ });
+
+ it('reports "no install command" rather than silently stalling', async () => {
+ const { runner } = makeRunner({
+ checks: { docker: [{ outcome: 'missing' }] },
+ installs: {},
+ canInstall: () => false,
+ });
+
+ const result = await runner.run(plan([step('docker')]));
+
+ expect(result.steps[0]!.state).toBe('failed');
+ expect(result.steps[0]!.error).toContain('no install command');
+ });
+
+ it('continues past a failed optional step', async () => {
+ const { runner } = makeRunner({
+ checks: { gh: [{ outcome: 'missing' }], node: [{ outcome: 'satisfied' }] },
+ installs: { gh: { ok: false, error: 'nope' } },
+ });
+
+ const result = await runner.run(plan([step('gh', { optional: true }), step('node')]));
+
+ expect(stateOf(result, 'gh')).toBe('failed');
+ expect(stateOf(result, 'node')).toBe('satisfied');
+ expect(result.status).toBe('complete'); // optional failure does not block the host
+ });
+
+ it('skipping unblocks the rest of the plan but is not satisfied', async () => {
+ const { runner } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }], tmux: [{ outcome: 'satisfied' }] },
+ installs: { node: { ok: false, error: 'nope' } },
+ });
+
+ const halted = await runner.run(plan([step('node'), step('tmux')]));
+ expect(stateOf(halted, 'tmux')).toBe('blocked');
+
+ const skipped = await runner.skip(halted, 'node');
+
+ expect(stateOf(skipped, 'node')).toBe('skipped');
+ expect(stateOf(skipped, 'tmux')).toBe('pending'); // unblocked
+ expect(skipped.steps.find((s) => s.id === 'node')!.outcome).not.toBe('satisfied');
+ });
+
+ it('aborts as unreachable instead of blaming a dependency', async () => {
+ const { runner, installOrder } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }] },
+ installs: {},
+ reachable: false,
+ });
+
+ await expect(runner.run(plan([step('node')]))).rejects.toBeInstanceOf(HostSetupAbortedError);
+ expect(installOrder).toEqual([]);
+ });
+
+ it('persists and publishes every transition', async () => {
+ const { runner, saved, published } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }, { outcome: 'satisfied' }] },
+ installs: { node: { ok: true } },
+ });
+
+ await runner.run(plan([step('node')]));
+
+ // running → checking → observed → installing → checking → satisfied → complete
+ expect(saved.length).toBeGreaterThanOrEqual(6);
+ expect(published.length).toBe(saved.length);
+ expect(saved.at(-1)!.status).toBe('complete');
+ });
+
+ it('refuses a second concurrent run for the same host', async () => {
+ const { runner } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }, { outcome: 'satisfied' }] },
+ installs: { node: { ok: true } },
+ });
+ const p = plan([step('node')]);
+
+ const first = runner.run(p);
+ await expect(runner.run(p)).rejects.toThrow('already in progress');
+ await first;
+ });
+
+ it('stops mid-run when the host drops', async () => {
+ const harness: Harness = {
+ checks: { git: [{ outcome: 'satisfied' }], node: [{ outcome: 'missing' }] },
+ installs: {},
+ };
+ const reachable = { value: true };
+ const runner = new HostSetupRunner({
+ sshHost: 'dev-vm',
+ load: async () => null,
+ save: async () => {},
+ publish: () => {},
+ check: async (s) => harness.checks[s.id]![0]!,
+ install: async () => ({ ok: true }),
+ canInstall: () => true,
+ requireReachable: () => {
+ if (!reachable.value) throw new Unreachable('dropped');
+ reachable.value = false; // drops after the first step
+ },
+ now: () => new Date('2026-02-02T00:00:00.000Z'),
+ });
+
+ await expect(runner.run(plan([step('git'), step('node')]))).rejects.toBeInstanceOf(
+ HostSetupAbortedError
+ );
+ });
+
+ it('clears a previous error when a step is retried', async () => {
+ const { runner } = makeRunner({
+ checks: { node: [{ outcome: 'missing' }, { outcome: 'satisfied' }] },
+ installs: { node: { ok: true } },
+ });
+ const failed = plan([
+ step('node', { state: 'failed', error: 'old failure', output: 'old output' }),
+ ]);
+
+ const result = await runner.run(failed);
+
+ expect(stateOf(result, 'node')).toBe('satisfied');
+ expect(result.steps[0]!.error).toBeNull();
+ expect(result.steps[0]!.output).toBeNull();
+ });
+});
+
+describe('plan helpers', () => {
+ it('treats a skipped required step as outstanding, not done', async () => {
+ const { isPlanComplete } = await import('@shared/core/remote-hosts/setup');
+ expect(isPlanComplete(plan([step('node', { state: 'skipped' })]))).toBe(false);
+ });
+
+ it('ignores optional steps when deciding completeness', async () => {
+ const { isPlanComplete } = await import('@shared/core/remote-hosts/setup');
+ expect(
+ isPlanComplete(
+ plan([
+ step('node', { state: 'satisfied' }),
+ step('gh', { optional: true, state: 'failed' }),
+ ])
+ )
+ ).toBe(true);
+ });
+});
+
++describe('gh-auth steps', () => {
++ const ghStep = (patch: Partial<HostSetupStep> = {}) =>
++ step('gh:auth', { kind: 'gh-auth', name: 'GitHub CLI login', optional: true, ...patch });
++
++ it('tells the user to sign in rather than reporting a missing install command', async () => {
++ const { runner, installOrder } = makeRunner({
++ checks: { 'gh:auth': [{ outcome: 'missing' }] },
++ installs: {},
++ canInstall: () => false,
++ });
++
++ const result = await runner.run(plan([ghStep()]));
++
++ expect(installOrder).toEqual([]);
++ expect(result.steps[0]!.error).toMatch(/Use Sign in to start it/);
++ });
++
++ it('leads with why a login that already exists is still not enough', async () => {
++ const { runner } = makeRunner({
++ checks: {
++ 'gh:auth': [
++ {
++ outcome: 'missing',
++ error: 'The GitHub token is missing the read:packages scope.',
++ },
++ ],
++ },
++ installs: {},
++ canInstall: () => false,
++ });
++
++ const result = await runner.run(plan([ghStep()]));
++
++ expect(result.steps[0]!.state).toBe('failed');
++ expect(result.steps[0]!.error).toMatch(
++ /^The GitHub token is missing the read:packages scope\./
++ );
++ });
++});
++
+describe('runner determinism', () => {
+ it('does not mutate the plan it was given', async () => {
+ const { runner } = makeRunner({ checks: { git: [{ outcome: 'satisfied' }] }, installs: {} });
+ const original = plan([step('git')]);
+ const snapshot = structuredClone(original);
+
+ await runner.run(original);
+
+ expect(original).toEqual(snapshot);
+ });
+
+ it('stamps updatedAt on every changed step', async () => {
+ const { runner } = makeRunner({ checks: { git: [{ outcome: 'satisfied' }] }, installs: {} });
+ vi.useFakeTimers();
+
+ const result = await runner.run(plan([step('git')]));
+
+ expect(result.steps[0]!.updatedAt).toBe('2026-02-02T00:00:00.000Z');
+ vi.useRealTimers();
+ });
+});
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.ts
index 7bd70395f,000000000..d7d69ef54
mode 100644,000000..100644
--- a/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-runner.ts
@@@ -1,293 -1,0 +1,296 @@@
+/**
+ * Sequential, resumable setup runner for a remote host (CHOO-1809).
+ *
+ * Runs a host's setup plan one step at a time, persisting after every
+ * transition so a run survives the app closing mid-install. Three rules drive
+ * the design:
+ *
+ * 1. **One step in flight.** Dependencies install one after another, in order,
+ * never concurrently — the old page fired every probe and install
+ * independently and left the user to guess the sequence.
+ * 2. **Halt on failure, hold position.** A failed required step stops the run.
+ * Steps already satisfied stay satisfied, the failure keeps its error and
+ * command output, and untried steps become `blocked` rather than being
+ * discarded. Resuming re-attempts the failure; it does not start over.
+ * 3. **Reachability is not a dependency verdict.** The reachability gate is
+ * consulted before any probing, and an unreachable host aborts the run as
+ * *unreachable* instead of reporting every prerequisite as missing.
+ *
+ * Verification is explicit: after an install we re-check rather than assuming
+ * the installer worked. A step is only `satisfied` on the strength of a fresh
+ * observation.
+ */
+
+import {
+ isInstallableOutcome,
+ isPlanComplete,
+ type DependencyCheckOutcome,
+ type HostSetupPlan,
+ type HostSetupStep,
+ type HostSetupStepState,
+} from '@shared/core/remote-hosts/setup';
+
+/** What a probe observed for one step. */
+export type StepCheckResult = {
+ outcome: DependencyCheckOutcome;
+ version?: string | null;
+ /** Set when the outcome is `unknown` — why we could not tell. */
+ error?: string;
+};
+
+/** Outcome of installing one step. */
+export type StepInstallResult = { ok: true } | { ok: false; error: string; output?: string | null };
+
+export type HostSetupRunnerDeps = {
+ sshHost: string;
+ /** Load the persisted plan. Null when the host has never been set up. */
+ load: (sshHost: string) => Promise<HostSetupPlan | null>;
+ save: (plan: HostSetupPlan) => Promise<void>;
+ /** Push the plan to the renderer on every transition. */
+ publish: (plan: HostSetupPlan) => void;
+ check: (step: HostSetupStep) => Promise<StepCheckResult>;
+ install: (step: HostSetupStep) => Promise<StepInstallResult>;
+ /** Whether this step can be installed by switchdash at all on this host. */
+ canInstall: (step: HostSetupStep) => boolean;
+ /**
+ * Throws when the host is not reachable. Wired to the central reachability
+ * service (CHOO-1682/1780) — this runner never forms its own verdict.
+ */
+ requireReachable: (sshHost: string) => void;
+ now?: () => Date;
+};
+
+/** Raised when a run is abandoned because the host itself is not reachable. */
+export class HostSetupAbortedError extends Error {
+ constructor(
+ message: string,
+ readonly cause: unknown
+ ) {
+ super(message);
+ this.name = 'HostSetupAbortedError';
+ }
+}
+
+export class HostSetupRunner {
+ private running = false;
+
+ constructor(private readonly deps: HostSetupRunnerDeps) {}
+
+ private now(): string {
+ return (this.deps.now?.() ?? new Date()).toISOString();
+ }
+
+ /**
+ * Run (or resume) the plan. Returns as soon as the plan completes or halts.
+ * Concurrent calls are rejected rather than interleaved — two runs against
+ * one host would break the one-at-a-time guarantee.
+ */
+ async run(plan: HostSetupPlan): Promise<HostSetupPlan> {
+ if (this.running) {
+ throw new Error(`A setup run is already in progress for ${this.deps.sshHost}`);
+ }
+ this.running = true;
+ try {
+ return await this.drive(plan);
+ } finally {
+ this.running = false;
+ }
+ }
+
+ private async drive(initial: HostSetupPlan): Promise<HostSetupPlan> {
+ let plan = await this.transition(initial, { status: 'running' });
+
+ for (const step of plan.steps) {
+ if (step.state === 'satisfied' || step.state === 'skipped') continue;
+
+ // Gate on reachability before every step, not just at the start: a host
+ // can drop mid-run, and continuing would attribute the loss of the
+ // transport to whichever dependency happened to be next in line.
+ try {
+ this.deps.requireReachable(this.deps.sshHost);
+ } catch (error) {
+ plan = await this.transition(plan, { status: 'halted' });
+ throw new HostSetupAbortedError(
+ `Setup for ${this.deps.sshHost} stopped: the host became unreachable.`,
+ error
+ );
+ }
+
+ plan = await this.runStep(plan, step.id);
+ const current = findStep(plan, step.id);
+
+ if (current.state === 'failed' && !current.optional) {
+ return await this.haltAfter(plan, step.id);
+ }
+ }
+
+ return await this.transition(plan, {
+ status: isPlanComplete(plan) ? 'complete' : 'halted',
+ currentStepId: null,
+ });
+ }
+
+ /**
+ * Check one step, install it if that is both needed and possible, then
+ * re-check to verify. Never marks a step satisfied on the strength of an
+ * installer's exit code alone.
+ */
+ async runStep(plan: HostSetupPlan, stepId: string): Promise<HostSetupPlan> {
+ let next = await this.patchStep(plan, stepId, {
+ state: 'checking',
+ error: null,
+ output: null,
+ });
+ next = await this.transition(next, { currentStepId: stepId });
+
+ const checked = await this.observe(next, stepId);
+ const step = findStep(checked, stepId);
+
+ if (step.outcome === 'satisfied') return checked;
+
+ // Nothing we can do automatically — surface the real outcome rather than
+ // pretending an install would help. `not-running` and `unknown` land here.
+ if (!isInstallableOutcome(step.outcome) || !this.deps.canInstall(step)) {
+ return await this.patchStep(checked, stepId, {
+ state: 'failed',
+ error: describeUnactionable(step),
+ });
+ }
+
+ const installing = await this.patchStep(checked, stepId, { state: 'installing' });
+ const result = await this.deps.install(findStep(installing, stepId));
+
+ if (!result.ok) {
+ return await this.patchStep(installing, stepId, {
+ state: 'failed',
+ error: result.error,
+ output: result.output ?? null,
+ });
+ }
+
+ // Verify. An installer reporting success is a claim, not an observation.
+ const verifying = await this.patchStep(installing, stepId, { state: 'checking' });
+ const verified = await this.observe(verifying, stepId);
+ const after = findStep(verified, stepId);
+
+ if (after.outcome === 'satisfied') return verified;
+
+ return await this.patchStep(verified, stepId, {
+ state: 'failed',
+ error:
+ after.outcome === 'unknown'
+ ? `${after.name} was installed but could not be verified afterwards.`
+ : `${after.name} still reports "${after.outcome}" after installing.`,
+ });
+ }
+
+ /** Probe one step and record what was actually observed. */
+ private async observe(plan: HostSetupPlan, stepId: string): Promise<HostSetupPlan> {
+ let result: StepCheckResult;
+ try {
+ result = await this.deps.check(findStep(plan, stepId));
+ } catch (error) {
+ // A probe that throws tells us nothing about the dependency — record
+ // `unknown`, never `missing`.
+ result = {
+ outcome: 'unknown',
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
+ return await this.patchStep(plan, stepId, {
+ outcome: result.outcome,
+ version: result.version ?? null,
+ state: result.outcome === 'satisfied' ? 'satisfied' : 'checking',
+ error: result.error ?? null,
+ });
+ }
+
+ /** Mark the plan halted and block everything downstream of the failure. */
+ private async haltAfter(plan: HostSetupPlan, failedStepId: string): Promise<HostSetupPlan> {
+ const failedIndex = plan.steps.findIndex((s) => s.id === failedStepId);
+ const steps = plan.steps.map((step, index) =>
+ index > failedIndex && (step.state === 'pending' || step.state === 'blocked')
+ ? { ...step, state: 'blocked' as HostSetupStepState, updatedAt: this.now() }
+ : step
+ );
+ return await this.commit({
+ ...plan,
+ steps,
+ status: 'halted',
+ currentStepId: failedStepId,
+ });
+ }
+
+ /**
+ * Move past a step the user has chosen not to fix. Unblocks the rest of the
+ * plan so the run can continue, but is never reported as satisfied.
+ */
+ async skip(plan: HostSetupPlan, stepId: string): Promise<HostSetupPlan> {
+ const skipped = await this.patchStep(plan, stepId, {
+ state: 'skipped',
+ error: null,
+ output: null,
+ });
+ const steps = skipped.steps.map((step) =>
+ step.state === 'blocked' ? { ...step, state: 'pending' as HostSetupStepState } : step
+ );
+ return await this.commit({ ...skipped, steps, status: 'idle' });
+ }
+
+ private async patchStep(
+ plan: HostSetupPlan,
+ stepId: string,
+ patch: Partial<Omit<HostSetupStep, 'id'>>
+ ): Promise<HostSetupPlan> {
+ const steps = plan.steps.map((step) =>
+ step.id === stepId ? { ...step, ...patch, updatedAt: this.now() } : step
+ );
+ return await this.commit({ ...plan, steps });
+ }
+
+ private async transition(
+ plan: HostSetupPlan,
+ patch: Partial<Pick<HostSetupPlan, 'status' | 'currentStepId'>>
+ ): Promise<HostSetupPlan> {
+ return await this.commit({ ...plan, ...patch });
+ }
+
+ /** Persist then publish. Every visible state change goes through here. */
+ private async commit(plan: HostSetupPlan): Promise<HostSetupPlan> {
+ const next = { ...plan, updatedAt: this.now() };
+ await this.deps.save(next);
+ this.deps.publish(next);
+ return next;
+ }
+}
+
+function findStep(plan: HostSetupPlan, stepId: string): HostSetupStep {
+ const step = plan.steps.find((s) => s.id === stepId);
+ if (!step) throw new Error(`Setup step ${stepId} is not part of the plan for ${plan.sshHost}`);
+ return step;
+}
+
+/** Why a step cannot be advanced automatically — stated in terms of what we saw. */
+function describeUnactionable(step: HostSetupStep): string {
+ // Not a failure of ours to fix: signing in to GitHub is a device flow the
+ // user drives in a terminal. Say what they need to do rather than reporting
- // it as a missing install command.
++ // it as a missing install command. A login that exists but lacks a scope
++ // says so first — "sign in" reads as wrong advice to someone already signed
++ // in, and re-running the flow is nonetheless the fix.
+ if (step.kind === 'gh-auth') {
- return 'Signing in to GitHub needs a one-time code you enter yourself. Use Sign in to start it.';
++ const prefix = step.error ? `${step.error} ` : '';
++ return `${prefix}Signing in to GitHub needs a one-time code you enter yourself. Use Sign in to start it.`;
+ }
+
+ switch (step.outcome) {
+ case 'not-running':
+ return `${step.name} is installed but not running. Start it on the host, then retry.`;
+ case 'unknown':
+ return step.error ?? `Could not determine whether ${step.name} is available.`;
+ case 'wrong-version':
+ return `${step.name} is installed but too old, and switchdash has no upgrade command for this host.`;
+ default:
+ return `${step.name} is not installed, and switchdash has no install command for this host.`;
+ }
+}
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/host-setup-service.ts
index 2e289edb4,000000000..863862721
mode 100644,000000..100644
--- 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.ts
@@@ -1,220 -1,0 +1,192 @@@
+/**
+ * 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 type { HostDependencyManager } from '@switchdash/core/deps/runtime';
+import { CORE_DEPENDENCIES } from '@main/core/dependencies/core-dependencies';
+import {
+ getRemoteDependencyManager,
+ remoteDependencyDescriptor,
+} from '@main/core/dependencies/remote-dependency-manager';
+import { getRemoteSwitchSetupService } from '@main/core/switch-setup/remote-switch-setup';
+import { events } from '@main/lib/events';
+import { log } from '@main/lib/logger';
+import {
+ hostSetupPlanEventChannel,
- type DependencyCheckOutcome,
+ type HostSetupPlan,
+ type HostSetupStep,
+} from '@shared/core/remote-hosts/setup';
+import { probeGhAuthStatus } from '../gh-auth';
+import { hostReachabilityService } from '../production-host-reachability';
+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 };
- }
++import { outcomeForDependency, outcomeForGhAuth } from './step-outcomes';
+
+/** 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' };
++ return outcomeForGhAuth(await probeGhAuthStatus(sshHost));
+ }
+
+ 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 --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/step-outcomes.test.ts
index 000000000,000000000..7387a7c7e
new file mode 100644
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/step-outcomes.test.ts
@@@ -1,0 -1,0 +1,72 @@@
++import { describe, expect, it } from 'vitest';
++import type { GhAuthStatus } from '../gh-auth';
++import { outcomeForDependency, outcomeForGhAuth } from './step-outcomes';
++
++function ghStatus(overrides: Partial<GhAuthStatus>): GhAuthStatus {
++ return {
++ authenticated: true,
++ account: 'octocat',
++ canReadPackages: true,
++ detail: null,
++ ...overrides,
++ };
++}
++
++describe('outcomeForGhAuth', () => {
++ it('is satisfied only when the login can also read packages', () => {
++ expect(outcomeForGhAuth(ghStatus({}))).toEqual({ outcome: 'satisfied', version: 'octocat' });
++ });
++
++ it('does not accept a login that lacks read:packages, and says why', () => {
++ const result = outcomeForGhAuth(
++ ghStatus({
++ canReadPackages: false,
++ detail: 'The GitHub token is missing the read:packages scope.',
++ })
++ );
++
++ expect(result.outcome).toBe('missing');
++ expect(result.error).toMatch(/read:packages/);
++ });
++
++ it('reports a host with no login at all as missing', () => {
++ const result = outcomeForGhAuth(
++ ghStatus({
++ authenticated: false,
++ account: null,
++ canReadPackages: false,
++ detail: 'Not logged in.',
++ })
++ );
++
++ expect(result).toEqual({ outcome: 'missing', error: 'Not logged in.' });
++ });
++});
++
++describe('outcomeForDependency', () => {
++ it('reports an available dependency as satisfied with its version', () => {
++ expect(outcomeForDependency({ status: 'available', version: '2.44.0' }, false)).toEqual({
++ outcome: 'satisfied',
++ version: '2.44.0',
++ });
++ });
++
++ it('reports an absent dependency as missing', () => {
++ expect(outcomeForDependency({ status: 'missing', version: null }, false)).toEqual({
++ outcome: 'missing',
++ version: null,
++ });
++ });
++
++ it('recovers "too old" from the manager collapsing it into an error', () => {
++ expect(
++ outcomeForDependency({ status: 'error', version: '16.0.0', error: 'needs >= 20' }, true)
++ ).toEqual({ outcome: 'wrong-version', version: '16.0.0', error: 'needs >= 20' });
++ });
++
++ it('reports an undetermined probe as unknown rather than guessing missing', () => {
++ expect(
++ outcomeForDependency({ status: 'error', version: null, error: 'channel closed' }, true)
++ ).toEqual({ outcome: 'unknown', version: null, error: 'channel closed' });
++ });
++});
diff --cc dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/step-outcomes.ts
index 000000000,000000000..9e3466bca
new file mode 100644
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/remote-hosts/setup/step-outcomes.ts
@@@ -1,0 -1,0 +1,53 @@@
++/**
++ * Turning a raw probe into an observation (CHOO-1809).
++ *
++ * Kept apart from the service that does the probing so the rules can be read
++ * and tested on their own — the service reaches SSH, the database and the
++ * dependency managers, and none of that is needed to say what a given
++ * observation means.
++ */
++
++import type { DependencyCheckOutcome } from '@shared/core/remote-hosts/setup';
++import type { GhAuthStatus } from '../gh-auth';
++import type { StepCheckResult } from './host-setup-runner';
++
++/**
++ * 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 };
++}
++
++/**
++ * Translate a probed GitHub login into an observation.
++ *
++ * Being logged in is not the same as being usable: without `read:packages`
++ * every session this host starts fetches its MCP runtime from GitHub Packages
++ * and gets a 403 several layers below anything that mentions `gh` (CHOO-1873).
++ * Reporting that login as satisfied is the stale-green bug in another coat, so
++ * the step stays outstanding and carries the reason.
++ */
++export function outcomeForGhAuth(status: GhAuthStatus): StepCheckResult {
++ if (status.authenticated && status.canReadPackages) {
++ return { outcome: 'satisfied', version: status.account };
++ }
++ return { outcome: 'missing', error: status.detail ?? undefined };
++}
diff --cc dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/setup/setup-steps.tsx
index 328d036b2,000000000..704db565b
mode 100644,000000..100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/setup/setup-steps.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/remote-hosts/setup/setup-steps.tsx
@@@ -1,178 -1,0 +1,171 @@@
+/**
+ * The visible setup sequence for one host (CHOO-1809).
+ *
+ * Every step renders its own state, its own error and its own command output.
+ * The previous page showed a bare "Install failed" — and, when the failure came
+ * back as a Result rather than a thrown error, showed nothing at all.
+ */
+
- import {
- CheckCircle2,
- ChevronRight,
- Circle,
- Loader2,
- MinusCircle,
- XCircle,
- } from 'lucide-react';
++import { CheckCircle2, ChevronRight, Circle, Loader2, MinusCircle, XCircle } from 'lucide-react';
+import { useState } from 'react';
+import { Button } from '@renderer/lib/ui/button';
+import { cn } from '@renderer/utils/utils';
+import type { HostSetupStep } from '@shared/core/remote-hosts/setup';
+import { canSkip, stepStatusLabel, stepTone, type StepTone } from './step-presentation';
+
+const TONE_TEXT: Record<StepTone, string> = {
+ done: 'text-green-500',
+ busy: 'text-amber-500',
+ failed: 'text-destructive',
+ skipped: 'text-foreground-muted',
+ waiting: 'text-foreground-muted',
+ idle: 'text-foreground-muted',
+};
+
+function StepIcon({ tone }: { tone: StepTone }) {
+ const className = cn('size-4 shrink-0', TONE_TEXT[tone]);
+ switch (tone) {
+ case 'done':
+ return <CheckCircle2 className={className} />;
+ case 'busy':
+ return <Loader2 className={cn(className, 'animate-spin')} />;
+ case 'failed':
+ return <XCircle className={className} />;
+ case 'skipped':
+ return <MinusCircle className={className} />;
+ case 'waiting':
+ return <Circle className={className} />;
+ case 'idle':
+ return <Circle className={className} />;
+ }
+}
+
+/**
+ * A failed step's raw command output, collapsed by default. Hidden behind a
+ * disclosure rather than dropped: it is usually the only thing that explains
+ * *why* an install failed, but it is long enough to bury the rest of the page.
+ */
+function FailureOutput({ output }: { output: string }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <div className="flex flex-col gap-1">
+ <button
+ type="button"
+ className="flex w-fit items-center gap-1 text-xs text-foreground-muted hover:text-foreground"
+ onClick={() => setOpen((prev) => !prev)}
+ >
+ <ChevronRight className={cn('size-3 transition-transform', open && 'rotate-90')} />
+ {open ? 'Hide output' : 'Show output'}
+ </button>
+ {open && (
+ <pre className="bg-background-subtle max-h-48 overflow-auto rounded-md p-2 text-xs whitespace-pre-wrap">
+ {output}
+ </pre>
+ )}
+ </div>
+ );
+}
+
+export function SetupStepRow({
+ step,
+ isCurrent,
+ onSkip,
+ skipping,
+ onAuthenticate,
+}: {
+ step: HostSetupStep;
+ isCurrent: boolean;
+ onSkip: () => void;
+ skipping: boolean;
+ /** Starts the interactive GitHub sign-in. Only meaningful for the gh-auth step. */
+ onAuthenticate: () => void;
+}) {
+ const tone = stepTone(step);
+
+ return (
+ <li
+ className={cn(
+ 'flex flex-col gap-2 rounded-md border px-3 py-2',
+ isCurrent ? 'border-amber-500/50' : 'border-border',
+ tone === 'failed' && 'border-destructive/50'
+ )}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-start gap-2">
+ <span className="pt-0.5">
+ <StepIcon tone={tone} />
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="flex items-center gap-2 text-sm">
+ {step.name}
+ {step.optional && (
+ <span className="rounded-sm border border-border px-1 text-[10px] text-foreground-muted">
+ optional
+ </span>
+ )}
+ </span>
+ <span className={cn('text-xs', TONE_TEXT[tone])}>{stepStatusLabel(step)}</span>
+ </span>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ {step.kind === 'gh-auth' && step.state !== 'satisfied' && (
+ <Button size="sm" onClick={onAuthenticate}>
+ Sign in
+ </Button>
+ )}
+ {canSkip(step) && (
+ <Button size="sm" variant="ghost" disabled={skipping} onClick={onSkip}>
+ {skipping ? 'Skipping…' : 'Skip'}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {step.state === 'failed' && step.error && (
+ <p className="text-destructive pl-6 text-xs">{step.error}</p>
+ )}
+ {step.state === 'failed' && step.output && (
+ <div className="pl-6">
+ <FailureOutput output={step.output} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+export function SetupStepList({
+ steps,
+ currentStepId,
+ onSkip,
+ skippingStepId,
+ onAuthenticate,
+}: {
+ steps: HostSetupStep[];
+ currentStepId: string | null;
+ onSkip: (stepId: string) => void;
+ skippingStepId: string | null;
+ onAuthenticate: () => void;
+}) {
+ if (steps.length === 0) {
+ return (
+ <p className="text-sm text-foreground-muted">
+ No setup steps yet — prepare the host to work out what it needs.
+ </p>
+ );
+ }
+
+ return (
+ <ol className="flex flex-col gap-2">
+ {steps.map((step) => (
+ <SetupStepRow
+ key={step.id}
+ step={step}
+ isCurrent={step.id === currentStepId}
+ onSkip={() => onSkip(step.id)}
+ skipping={skippingStepId === step.id}
+ onAuthenticate={onAuthenticate}
+ />
+ ))}
+ </ol>
+ );
+}