Skip to content

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

feat(switchdash): local-server mode — run a managed Switch stack via Docker (CHOO-1428)

Louis Amaudruzef9dfc8d7768
diff --git a/.env.example b/.env.example
index b6cce1039..8e3a78c83 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,16 @@
SWITCH_REGISTRY=ghcr.io
SWITCH_IMAGE_NAMESPACE=sandbox-quantum
SWITCH_VERSION=latest
+# Host ports each service publishes. Defaults match the values baked in before
+# these knobs existed; override any that clash with something already running on
+# your machine (switchdash's local-server mode picks free ports automatically).
+GATEWAY_HOST_PORT=3000
+API_HOST_PORT=8000
+MATTERMOST_HOST_PORT=8065
+POSTGRES_HOST_PORT=5432
+# Host interface the published ports bind to. Defaults to all interfaces; set to
+# 127.0.0.1 to keep the stack reachable only from this machine.
+SWITCH_BIND_ADDR=0.0.0.0
# ── Switch database (docker compose) ──────────────────────────────────────────
DB_HOST=localhost
diff --git a/dash/apps/switchdash-desktop/drizzle/0037_curvy_madame_masque.sql b/dash/apps/switchdash-desktop/drizzle/0037_curvy_madame_masque.sql
new file mode 100644
index 000000000..f20c4e2da
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/0037_curvy_madame_masque.sql
@@ -0,0 +1 @@
+ALTER TABLE `switch_servers` ADD `managed` integer DEFAULT false NOT NULL;
\ No newline at end of file
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/0037_snapshot.json b/dash/apps/switchdash-desktop/drizzle/meta/0037_snapshot.json
new file mode 100644
index 000000000..d28470604
--- /dev/null
+++ b/dash/apps/switchdash-desktop/drizzle/meta/0037_snapshot.json
@@ -0,0 +1,678 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "97250cdb-a224-488f-9f38-73595cc25ba1",
+ "prevId": "57e3dc0d-71bf-4223-8960-3f284d9ef932",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "switch_agent_id": {
+ "name": "switch_agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "api_endpoint": {
+ "name": "api_endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_agents_location_id": {
+ "name": "idx_agents_location_id",
+ "columns": ["location_id"],
+ "isUnique": false
+ },
+ "idx_agents_server_id": {
+ "name": "idx_agents_server_id",
+ "columns": ["server_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "agents_location_id_locations_id_fk": {
+ "name": "agents_location_id_locations_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agents_server_id_switch_servers_id_fk": {
+ "name": "agents_server_id_switch_servers_id_fk",
+ "tableFrom": "agents",
+ "tableTo": "switch_servers",
+ "columnsFrom": ["server_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "app_secrets": {
+ "name": "app_secrets",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret": {
+ "name": "secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_app_secrets_key": {
+ "name": "idx_app_secrets_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "app_settings": {
+ "name": "app_settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_app_settings_key": {
+ "name": "idx_app_settings_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "kv": {
+ "name": "kv",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_kv_key": {
+ "name": "idx_kv_key",
+ "columns": ["key"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "location_settings": {
+ "name": "location_settings",
+ "columns": {
+ "location_id": {
+ "name": "location_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "base_settings_json": {
+ "name": "base_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "shareable_settings_json": {
+ "name": "shareable_settings_json",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "legacy_config_migrated_at": {
+ "name": "legacy_config_migrated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "location_settings_location_id_locations_id_fk": {
+ "name": "location_settings_location_id_locations_id_fk",
+ "tableFrom": "location_settings",
+ "tableTo": "locations",
+ "columnsFrom": ["location_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "locations": {
+ "name": "locations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "dir": {
+ "name": "dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_locations_host_dir": {
+ "name": "idx_locations_host_dir",
+ "columns": ["ssh_host", "dir"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "messages": {
+ "name": "messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sender": {
+ "name": "sender",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "idx_messages_session_id": {
+ "name": "idx_messages_session_id",
+ "columns": ["session_id"],
+ "isUnique": false
+ },
+ "idx_messages_timestamp": {
+ "name": "idx_messages_timestamp",
+ "columns": ["timestamp"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messages_session_id_sessions_id_fk": {
+ "name": "messages_session_id_sessions_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "sessions",
+ "columnsFrom": ["session_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "remote_hosts": {
+ "name": "remote_hosts",
+ "columns": {
+ "ssh_host": {
+ "name": "ssh_host",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "config": {
+ "name": "config",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shell_id": {
+ "name": "shell_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_session_id": {
+ "name": "agent_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status": {
+ "name": "agent_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_status_seen": {
+ "name": "agent_status_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "is_initial_session": {
+ "name": "is_initial_session",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "is_pinned": {
+ "name": "is_pinned",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_interacted_at": {
+ "name": "last_interacted_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status_changed_at": {
+ "name": "status_changed_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_sessions_agent_id": {
+ "name": "idx_sessions_agent_id",
+ "columns": ["agent_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": ["agent_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "switch_servers": {
+ "name": "switch_servers",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gateway_url": {
+ "name": "gateway_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "api_url": {
+ "name": "api_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "managed": {
+ "name": "managed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "CURRENT_TIMESTAMP"
+ }
+ },
+ "indexes": {
+ "idx_switch_servers_gateway_url": {
+ "name": "idx_switch_servers_gateway_url",
+ "columns": ["gateway_url"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ }
+ },
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
index fe13b0ab2..3a537df8e 100644
--- a/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
+++ b/dash/apps/switchdash-desktop/drizzle/meta/_journal.json
@@ -260,6 +260,13 @@
"when": 1784451483886,
"tag": "0036_rename_workspace_provider_setting",
"breakpoints": true
+ },
+ {
+ "idx": 37,
+ "version": "6",
+ "when": 1784456381313,
+ "tag": "0037_curvy_madame_masque",
+ "breakpoints": true
}
]
}
diff --git a/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs b/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs
new file mode 100644
index 000000000..e94f5878c
--- /dev/null
+++ b/dash/apps/switchdash-desktop/scripts/sync-standalone-compose.mjs
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+/**
+ * Sync the bundled standalone compose from the repo's source of truth.
+ *
+ * node scripts/sync-standalone-compose.mjs
+ *
+ * Copies deploy/local/standalone-docker-compose.yml (the file the switch-release
+ * workflow publishes to GHCR as `standalone-compose:<version>`) into
+ * src/main/core/local-switch-server/resources/, re-adding the "bundled copy"
+ * header. Run this when bumping COMPATIBLE_SWITCH_VERSION so the bundled compose
+ * stays in lockstep with the pinned switch-core release. It reads the repo file
+ * directly rather than pulling the OCI artifact so it works offline and before a
+ * release exists; the two are identical by construction.
+ */
+import { readFileSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(here, '../../../..');
+const source = resolve(repoRoot, 'deploy/local/standalone-docker-compose.yml');
+const dest = resolve(
+ here,
+ '../src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml'
+);
+
+const header = `# BUNDLED COPY — do not hand-edit. This is the standalone compose published to
+# GHCR as \`standalone-compose:<version>\` by the switch-release workflow, pinned
+# to COMPATIBLE_SWITCH_VERSION (src/shared/app-identity.ts) and bundled into the
+# app so local-server mode needs no runtime OCI puller. Re-sync it from the
+# repo's deploy/local/standalone-docker-compose.yml when bumping the pin
+# (scripts/sync-standalone-compose.mjs).
+#
+`;
+
+const body = readFileSync(source, 'utf8');
+writeFileSync(dest, header + body, 'utf8');
+console.log(`Synced ${source}\n -> ${dest}`);
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/bundled-compose.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/bundled-compose.ts
new file mode 100644
index 000000000..c1fbfac71
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/bundled-compose.ts
@@ -0,0 +1,21 @@
+import { mkdir, writeFile } from 'node:fs/promises';
+import { dirname } from 'node:path';
+import { composeFilePath } from './paths';
+import composeYaml from './resources/standalone-docker-compose.pinned.yml?raw';
+
+/** The standalone compose bundled into the app (pinned to
+ * COMPATIBLE_SWITCH_VERSION), inlined at build time. */
+export function bundledComposeYaml(): string {
+ return composeYaml;
+}
+
+/** Write the bundled compose to disk so `docker compose -f <path>` can run it,
+ * returning the path. Docker cannot read a file inside the packaged app bundle,
+ * so it is materialised into the user-data dir on every start (cheap, and keeps
+ * the on-disk copy in lockstep with the app version). */
+export async function materialiseComposeFile(): Promise<string> {
+ const path = composeFilePath();
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, composeYaml, 'utf8');
+ return path;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/compose.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/compose.ts
new file mode 100644
index 000000000..733c4f905
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/compose.ts
@@ -0,0 +1,115 @@
+import { execFile, spawn } from 'node:child_process';
+import { promisify } from 'node:util';
+import { log } from '@main/lib/logger';
+import { LOCAL_SERVER_PROFILES, LOCAL_SERVER_PROJECT_NAME } from './constants';
+import { DOCKER_EXECUTABLE } from './docker';
+import { composeFilePath, envFilePath, localServerDir } from './paths';
+
+const execFileAsync = promisify(execFile);
+
+/** Pulls can take minutes on a cold machine; give compose a generous ceiling. */
+const COMPOSE_TIMEOUT_MS = 20 * 60 * 1000;
+
+function profileArgs(): string[] {
+ return LOCAL_SERVER_PROFILES.flatMap((p) => ['--profile', p]);
+}
+
+/** Base args that scope every invocation to the managed project + env file. */
+function baseArgs(): string[] {
+ return [
+ 'compose',
+ '-f',
+ composeFilePath(),
+ '--env-file',
+ envFilePath(),
+ '--project-name',
+ LOCAL_SERVER_PROJECT_NAME,
+ ...profileArgs(),
+ ];
+}
+
+async function runCompose(args: string[], timeout: number): Promise<string> {
+ try {
+ const { stdout } = await execFileAsync(DOCKER_EXECUTABLE, args, {
+ cwd: localServerDir(),
+ timeout,
+ maxBuffer: 32 * 1024 * 1024,
+ });
+ return stdout;
+ } catch (error) {
+ const stderr = (error as { stderr?: string } | undefined)?.stderr;
+ const message = stderr?.trim() || (error instanceof Error ? error.message : String(error));
+ throw new Error(`docker ${args.join(' ')} failed: ${message}`);
+ }
+}
+
+/**
+ * Bring the stack up in the background (`up -d`), streaming each line of output
+ * to `onLog` so the UI can show a live tail during the (slow) image pull.
+ * Assumes the compose file and `.env` are written and GHCR login has run. docker
+ * compose emits pull/startup progress on stderr, so both streams are forwarded.
+ */
+export function composeUp(onLog: (line: string) => void): Promise<void> {
+ log.info('local-switch-server: docker compose up');
+ return new Promise((resolve, reject) => {
+ const args = [...baseArgs(), 'up', '-d'];
+ const child = spawn(DOCKER_EXECUTABLE, args, { cwd: localServerDir() });
+ let stderrTail = '';
+
+ const emitLines = (chunk: Buffer) => {
+ for (const raw of chunk.toString('utf8').split('\n')) {
+ const line = raw.replace(/\r$/, '');
+ if (line.length > 0) onLog(line);
+ }
+ };
+
+ const timer = setTimeout(() => {
+ child.kill('SIGTERM');
+ reject(new Error(`docker compose up timed out after ${COMPOSE_TIMEOUT_MS}ms`));
+ }, COMPOSE_TIMEOUT_MS);
+
+ child.stdout.on('data', emitLines);
+ child.stderr.on('data', (chunk: Buffer) => {
+ stderrTail = (stderrTail + chunk.toString('utf8')).slice(-4000);
+ emitLines(chunk);
+ });
+ child.on('error', (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ child.on('close', (code) => {
+ clearTimeout(timer);
+ if (code === 0) resolve();
+ else reject(new Error(`docker compose up failed (exit ${code}): ${stderrTail.trim()}`));
+ });
+ });
+}
+
+/** Stop and remove the stack's containers. `removeVolumes` also destroys the
+ * data volumes (the reset path) — irreversible. */
+export async function composeDown(removeVolumes: boolean): Promise<void> {
+ log.info(`local-switch-server: docker compose down${removeVolumes ? ' -v' : ''}`);
+ await runCompose([...baseArgs(), 'down', ...(removeVolumes ? ['-v'] : [])], 5 * 60 * 1000);
+}
+
+/** Service names currently in the `running` state for the managed project. */
+export async function runningServices(): Promise<string[]> {
+ try {
+ const stdout = await runCompose(
+ [...baseArgs(), 'ps', '--status', 'running', '--services'],
+ 60_000
+ );
+ return stdout
+ .split('\n')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ } catch (error) {
+ log.warn('local-switch-server: `compose ps` failed; treating stack as down', { error });
+ return [];
+ }
+}
+
+/** Whether the core `switch` service is up — our proxy for "the stack is up". */
+export async function isStackRunning(): Promise<boolean> {
+ return (await runningServices()).includes('switch');
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/constants.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/constants.ts
new file mode 100644
index 000000000..b6a46281b
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/constants.ts
@@ -0,0 +1,38 @@
+/**
+ * Fixed coordinates for the managed local stack. These mirror the ports and
+ * hosts baked into the bundled standalone compose (resources/…pinned.yml): the
+ * compose file is the contract, and these constants are how the rest of
+ * switchdash addresses the resulting server.
+ */
+
+/** `docker compose --project-name` for the managed stack, so its containers and
+ * volumes are isolated and discoverable across app restarts. */
+export const LOCAL_SERVER_PROJECT_NAME = 'switchdash-local';
+
+/** Display name of the auto-registered server record. */
+export const LOCAL_SERVER_NAME = 'Local Switch server';
+
+// The managed server's API and gateway URLs are NOT fixed constants: their host
+// ports are chosen from whatever is free on the machine (see ports.ts) so the
+// stack never collides with a dev's existing services. Resolve them via
+// gatewayUrlFor()/apiUrlFor() from the persisted port set.
+
+/** Compose profiles switchdash enables: `collab` (Mattermost bridge + seeder) so
+ * the stack has a working collaboration bridge, and `gateway` so the operator
+ * web dashboard is available. */
+export const LOCAL_SERVER_PROFILES = ['collab', 'gateway'] as const;
+
+/** Registry the private release images live in until the public-repo flip
+ * (CHOO-1260); used for the authenticated `docker login` before pulling. */
+export const GHCR_REGISTRY = 'ghcr.io';
+
+/** The gateway admin account the stack seeds (GATEWAY_ADMIN_EMAIL). switchdash
+ * generates its password, so it also auto-signs-in with these on start rather
+ * than making the user type a secret they never saw. */
+export const LOCAL_SERVER_ADMIN_EMAIL = '[email protected]';
+
+/** Host interface the managed stack's published ports bind to, fed to the
+ * compose `${SWITCH_BIND_ADDR}` interpolation. Loopback so the single-user local
+ * stack is never exposed to the LAN (the standalone compose defaults to all
+ * interfaces for repo users who may want remote access). */
+export const LOCAL_SERVER_BIND_ADDR = '127.0.0.1';
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/controller.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/controller.ts
new file mode 100644
index 000000000..74d1a56a3
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/controller.ts
@@ -0,0 +1,19 @@
+import type {
+ DockerAvailability,
+ LocalServerStatus,
+ StartLocalServerResult,
+} from '@shared/core/local-switch-server/local-switch-server';
+import { createRPCController } from '@shared/lib/ipc/rpc';
+import { localServerService } from './local-server-service';
+
+export const localSwitchServerController = createRPCController({
+ getStatus: (): Promise<LocalServerStatus> => Promise.resolve(localServerService.getStatus()),
+
+ detectDocker: (): Promise<DockerAvailability> => localServerService.detectDocker(),
+
+ start: (): Promise<StartLocalServerResult> => localServerService.start(),
+
+ stop: (): Promise<void> => localServerService.stop(),
+
+ reset: (): Promise<void> => localServerService.reset(),
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.test.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.test.ts
new file mode 100644
index 000000000..3f5b6725f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { classifyDockerError } from './docker';
+
+describe('classifyDockerError', () => {
+ it('maps a missing binary (ENOENT) to not-installed', () => {
+ const err = Object.assign(new Error('spawn docker ENOENT'), { code: 'ENOENT' });
+ expect(classifyDockerError(err).reason).toBe('not-installed');
+ });
+
+ it('maps a daemon-down message to daemon-down', () => {
+ const err = new Error(
+ 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?'
+ );
+ expect(classifyDockerError(err).reason).toBe('daemon-down');
+ });
+
+ it('falls back to daemon-down with the raw message for unknown failures', () => {
+ const err = new Error('some other failure');
+ const result = classifyDockerError(err);
+ expect(result.reason).toBe('daemon-down');
+ expect(result.detail).toContain('some other failure');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.ts
new file mode 100644
index 000000000..3497dc56e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/docker.ts
@@ -0,0 +1,79 @@
+import { execFile } from 'node:child_process';
+import fs from 'node:fs';
+import { promisify } from 'node:util';
+import { log } from '@main/lib/logger';
+import type { DockerAvailability } from '@shared/core/local-switch-server/local-switch-server';
+
+const execFileAsync = promisify(execFile);
+
+function resolveDockerBin(): string {
+ const candidates = [
+ (process.env.DOCKER_PATH || '').trim(),
+ '/opt/homebrew/bin/docker',
+ '/usr/local/bin/docker',
+ '/usr/bin/docker',
+ '/Applications/Docker.app/Contents/Resources/bin/docker',
+ ].filter(Boolean) as string[];
+ for (const p of candidates) {
+ try {
+ if (fs.existsSync(p)) return p;
+ } catch {}
+ }
+ return 'docker';
+}
+
+/** Resolved path to the Docker CLI. */
+export const DOCKER_EXECUTABLE = resolveDockerBin();
+
+/**
+ * Classify a failed `docker version` invocation into the DockerAvailability
+ * "unavailable" shape. Pure so it can be unit-tested against the two failure
+ * modes we care about: the binary is missing (ENOENT) vs the daemon is down
+ * (the CLI runs but can't reach the socket).
+ */
+export function classifyDockerError(error: unknown): {
+ reason: 'not-installed' | 'daemon-down';
+ detail: string;
+} {
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
+ const message = error instanceof Error ? error.message : String(error);
+ if (code === 'ENOENT') {
+ return { reason: 'not-installed', detail: 'The Docker CLI was not found on this system.' };
+ }
+ if (/cannot connect to the docker daemon|is the docker daemon running/i.test(message)) {
+ return {
+ reason: 'daemon-down',
+ detail: 'Docker is installed but the daemon is not running. Start Docker Desktop and retry.',
+ };
+ }
+ return { reason: 'daemon-down', detail: message };
+}
+
+/**
+ * Detect whether Docker is usable: the CLI resolves AND the daemon answers.
+ * `docker version --format {{.Server.Version}}` fails (non-zero exit) when the
+ * daemon is unreachable, which is exactly the signal we want — a plain
+ * `docker --version` would succeed even with the daemon down.
+ */
+export async function detectDocker(): Promise<DockerAvailability> {
+ try {
+ const { stdout } = await execFileAsync(
+ DOCKER_EXECUTABLE,
+ ['version', '--format', '{{.Server.Version}}'],
+ { timeout: 15_000 }
+ );
+ const version = stdout.trim();
+ if (!version) {
+ return {
+ available: false,
+ reason: 'daemon-down',
+ detail: 'Docker daemon reported no version.',
+ };
+ }
+ return { available: true, version };
+ } catch (error) {
+ const { reason, detail } = classifyDockerError(error);
+ log.info(`local-switch-server: docker unavailable (${reason})`);
+ return { available: false, reason, detail };
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.test.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.test.ts
new file mode 100644
index 000000000..e0e852d77
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import { buildEnvFile } from './env-file';
+import type { LocalServerSecrets } from './secret-values';
+
+const secrets: LocalServerSecrets = {
+ dbPassword: 'db-pw',
+ matrixRegistrationSharedSecret: 'matrix-shared',
+ matrixAdminPassword: 'matrix-admin',
+ agentRegistrationToken: 'agent-token',
+ jwtSecretKey: 'jwt-key',
+ gatewayAdminPassword: 'gw-admin',
+ mattermostAdminPassword: 'mm-admin',
+ mattermostUserPassword: 'mm-user',
+};
+
+describe('buildEnvFile', () => {
+ const env = buildEnvFile({
+ version: '1.2.3',
+ registry: 'ghcr.io',
+ namespace: 'sandbox-quantum',
+ ports: { gateway: 51000, api: 51001, mattermost: 51002, postgres: 51003 },
+ secrets,
+ });
+ const vars = Object.fromEntries(
+ env
+ .split('\n')
+ .filter((l) => l && !l.startsWith('#'))
+ .map((l) => l.split('=') as [string, string])
+ .filter(([k]) => k)
+ );
+
+ it('pins the image coordinates from params', () => {
+ expect(vars.SWITCH_REGISTRY).toBe('ghcr.io');
+ expect(vars.SWITCH_IMAGE_NAMESPACE).toBe('sandbox-quantum');
+ expect(vars.SWITCH_VERSION).toBe('1.2.3');
+ });
+
+ it('publishes every host port from the chosen (free) port set', () => {
+ expect(vars.GATEWAY_HOST_PORT).toBe('51000');
+ expect(vars.API_HOST_PORT).toBe('51001');
+ expect(vars.MATTERMOST_HOST_PORT).toBe('51002');
+ expect(vars.POSTGRES_HOST_PORT).toBe('51003');
+ expect(vars.FRONTEND_BASE_URL).toBe('http://localhost:51000');
+ });
+
+ it('binds the managed stack to loopback and seeds the admin account', () => {
+ expect(vars.SWITCH_BIND_ADDR).toBe('127.0.0.1');
+ expect(vars.GATEWAY_ADMIN_EMAIL).toBe('[email protected]');
+ });
+
+ it('injects every secret into its env var', () => {
+ expect(vars.DB_PASSWORD).toBe('db-pw');
+ expect(vars.MATRIX_REGISTRATION_SHARED_SECRET).toBe('matrix-shared');
+ expect(vars.MATRIX_ADMIN_PASSWORD).toBe('matrix-admin');
+ expect(vars.AGENT_REGISTRATION_TOKEN).toBe('agent-token');
+ expect(vars.JWT_SECRET_KEY).toBe('jwt-key');
+ expect(vars.GATEWAY_ADMIN_PASSWORD).toBe('gw-admin');
+ expect(vars.MATTERMOST_ADMIN_PASSWORD).toBe('mm-admin');
+ expect(vars.MATTERMOST_USER_PASSWORD).toBe('mm-user');
+ });
+
+ it('defines every var the compose contract interpolates', () => {
+ const required = [
+ 'SWITCH_BIND_ADDR',
+ 'GATEWAY_HOST_PORT',
+ 'API_HOST_PORT',
+ 'MATTERMOST_HOST_PORT',
+ 'POSTGRES_HOST_PORT',
+ 'DB_HOST',
+ 'DB_PORT',
+ 'DB_USER',
+ 'DB_PASSWORD',
+ 'DB_NAME',
+ 'MATRIX_SERVER',
+ 'MATRIX_SERVER_NAME',
+ 'MATRIX_ADMIN_USER',
+ 'MATRIX_ADMIN_PASSWORD',
+ 'MATRIX_REGISTRATION_SHARED_SECRET',
+ 'AGENT_REGISTRATION_TOKEN',
+ 'JWT_SECRET_KEY',
+ 'GATEWAY_ADMIN_EMAIL',
+ 'GATEWAY_ADMIN_PASSWORD',
+ 'FRONTEND_BASE_URL',
+ 'MATTERMOST_ADMIN_USER',
+ 'MATTERMOST_ADMIN_PASSWORD',
+ 'MATTERMOST_TEAM_NAME',
+ 'MATTERMOST_USER',
+ 'MATTERMOST_USER_PASSWORD',
+ ];
+ for (const key of required) {
+ expect(vars[key], `missing ${key}`).toBeDefined();
+ expect(vars[key], `empty ${key}`).not.toBe('');
+ }
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.ts
new file mode 100644
index 000000000..3d5b76c22
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/env-file.ts
@@ -0,0 +1,72 @@
+import { chmod, mkdir, writeFile } from 'node:fs/promises';
+import { dirname } from 'node:path';
+import { LOCAL_SERVER_ADMIN_EMAIL, LOCAL_SERVER_BIND_ADDR } from './constants';
+import type { LocalServerPorts } from './free-port';
+import type { LocalServerSecrets } from './secret-values';
+
+export type LocalServerEnvParams = {
+ /** switch-core image tag (COMPATIBLE_SWITCH_VERSION). */
+ version: string;
+ /** Image registry host (ghcr.io). */
+ registry: string;
+ /** Image namespace / repo owner. */
+ namespace: string;
+ /** Free host ports chosen for this machine (published on 127.0.0.1). */
+ ports: LocalServerPorts;
+ secrets: LocalServerSecrets;
+};
+
+/**
+ * Render the `.env` docker compose interpolates for the local stack. Pure — the
+ * host/user values are fixed by the compose contract, ports are chosen per
+ * machine, secrets come from the encrypted bundle, and image coordinates are the
+ * app's pin. Kept as a pure function so the exact output is unit-testable.
+ */
+export function buildEnvFile(params: LocalServerEnvParams): string {
+ const { version, registry, namespace, ports, secrets } = params;
+ return [
+ '# Generated by switchdash local-server mode — do not edit by hand.',
+ '# Secrets originate in the app encrypted store; this file is derived.',
+ `SWITCH_REGISTRY=${registry}`,
+ `SWITCH_IMAGE_NAMESPACE=${namespace}`,
+ `SWITCH_VERSION=${version}`,
+ `SWITCH_BIND_ADDR=${LOCAL_SERVER_BIND_ADDR}`,
+ `GATEWAY_HOST_PORT=${ports.gateway}`,
+ `API_HOST_PORT=${ports.api}`,
+ `MATTERMOST_HOST_PORT=${ports.mattermost}`,
+ `POSTGRES_HOST_PORT=${ports.postgres}`,
+ '',
+ 'DB_HOST=postgres',
+ 'DB_PORT=5432',
+ 'DB_USER=postgres',
+ `DB_PASSWORD=${secrets.dbPassword}`,
+ 'DB_NAME=switch',
+ '',
+ 'MATRIX_SERVER=http://localhost:8008',
+ 'MATRIX_SERVER_NAME=localhost',
+ 'MATRIX_ADMIN_USER=admin',
+ `MATRIX_ADMIN_PASSWORD=${secrets.matrixAdminPassword}`,
+ `MATRIX_REGISTRATION_SHARED_SECRET=${secrets.matrixRegistrationSharedSecret}`,
+ '',
+ `AGENT_REGISTRATION_TOKEN=${secrets.agentRegistrationToken}`,
+ `JWT_SECRET_KEY=${secrets.jwtSecretKey}`,
+ `GATEWAY_ADMIN_EMAIL=${LOCAL_SERVER_ADMIN_EMAIL}`,
+ `GATEWAY_ADMIN_PASSWORD=${secrets.gatewayAdminPassword}`,
+ `FRONTEND_BASE_URL=http://localhost:${ports.gateway}`,
+ '',
+ 'MATTERMOST_ADMIN_USER=admin',
+ `MATTERMOST_ADMIN_PASSWORD=${secrets.mattermostAdminPassword}`,
+ 'MATTERMOST_TEAM_NAME=switch',
+ 'MATTERMOST_USER=user',
+ `MATTERMOST_USER_PASSWORD=${secrets.mattermostUserPassword}`,
+ '',
+ ].join('\n');
+}
+
+/** Write the `.env` with owner-only permissions (it holds the stack secrets). */
+export async function writeEnvFile(path: string, content: string): Promise<void> {
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(path, content, { encoding: 'utf8', mode: 0o600 });
+ // writeFile only applies `mode` when creating; enforce it on rewrite too.
+ await chmod(path, 0o600);
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.test.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.test.ts
new file mode 100644
index 000000000..e60d7f637
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { apiUrlFor, gatewayUrlFor, isPorts, pickFreePorts } from './free-port';
+
+describe('pickFreePorts', () => {
+ it('returns four distinct, positive host ports', async () => {
+ const ports = await pickFreePorts();
+ const values = [ports.gateway, ports.api, ports.mattermost, ports.postgres];
+ for (const p of values) {
+ expect(p).toBeGreaterThan(0);
+ expect(p).toBeLessThan(65536);
+ }
+ expect(new Set(values).size).toBe(4);
+ });
+});
+
+describe('isPorts', () => {
+ it('accepts a complete numeric port set', () => {
+ expect(isPorts({ gateway: 1, api: 2, mattermost: 3, postgres: 4 })).toBe(true);
+ });
+
+ it('rejects partial or non-numeric shapes', () => {
+ expect(isPorts({ gateway: 1, api: 2, mattermost: 3 })).toBe(false);
+ expect(isPorts({ gateway: '1', api: 2, mattermost: 3, postgres: 4 })).toBe(false);
+ expect(isPorts(null)).toBe(false);
+ expect(isPorts('nope')).toBe(false);
+ });
+});
+
+describe('url helpers', () => {
+ it('build loopback URLs from the chosen ports', () => {
+ const ports = { gateway: 3300, api: 8000, mattermost: 8065, postgres: 5432 };
+ expect(gatewayUrlFor(ports)).toBe('http://localhost:3300');
+ expect(apiUrlFor(ports)).toBe('http://localhost:8000');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.ts
new file mode 100644
index 000000000..de08eed97
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/free-port.ts
@@ -0,0 +1,76 @@
+import { createServer } from 'node:net';
+
+/**
+ * Host ports the managed stack publishes. The compose binds these to 127.0.0.1
+ * via `${<NAME>_HOST_PORT}` interpolation; the *container-side* ports are fixed
+ * by the images, only the host side is chosen. Picked once from whatever is free
+ * on this machine and persisted, so a dev already running something on 8000 /
+ * 5432 / 3000 never hits a "port is already allocated" failure.
+ */
+export type LocalServerPorts = {
+ /** Operator gateway (dashboard) — what "Open web app" and management calls use. */
+ gateway: number;
+ /** switch-core agent bridge API — a connector's `SWITCH_API_ENDPOINT`. */
+ api: number;
+ /** Mattermost web UI. */
+ mattermost: number;
+ /** Postgres (host-side, for debugging; the stack talks to it over the network). */
+ postgres: number;
+};
+
+/**
+ * Ask the OS for a free TCP port on loopback: bind to :0, let the kernel assign
+ * an unused port, read it back, release it. `taken` holds ports already chosen in
+ * this batch — the socket is closed before the next pick, so without it two picks
+ * could be handed the same port.
+ */
+export async function findFreePort(taken: Set<number>): Promise<number> {
+ for (let attempt = 0; attempt < 50; attempt++) {
+ const port = await new Promise<number>((resolve, reject) => {
+ const srv = createServer();
+ srv.on('error', reject);
+ srv.listen(0, '127.0.0.1', () => {
+ const addr = srv.address();
+ const p = typeof addr === 'object' && addr ? addr.port : 0;
+ srv.close(() => resolve(p));
+ });
+ });
+ if (port && !taken.has(port)) {
+ taken.add(port);
+ return port;
+ }
+ }
+ throw new Error('Could not find a free local port after 50 attempts.');
+}
+
+/** Pick a distinct free port for each service the stack publishes. */
+export async function pickFreePorts(): Promise<LocalServerPorts> {
+ const taken = new Set<number>();
+ return {
+ gateway: await findFreePort(taken),
+ api: await findFreePort(taken),
+ mattermost: await findFreePort(taken),
+ postgres: await findFreePort(taken),
+ };
+}
+
+export function isPorts(value: unknown): value is LocalServerPorts {
+ if (typeof value !== 'object' || value === null) return false;
+ const v = value as Record<string, unknown>;
+ return (
+ typeof v.gateway === 'number' &&
+ typeof v.api === 'number' &&
+ typeof v.mattermost === 'number' &&
+ typeof v.postgres === 'number'
+ );
+}
+
+/** Dashboard URL for a resolved port set. */
+export function gatewayUrlFor(ports: LocalServerPorts): string {
+ return `http://localhost:${ports.gateway}`;
+}
+
+/** Agent-bridge API URL for a resolved port set. */
+export function apiUrlFor(ports: LocalServerPorts): string {
+ return `http://localhost:${ports.api}`;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ghcr-auth.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ghcr-auth.ts
new file mode 100644
index 000000000..0830db2f9
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ghcr-auth.ts
@@ -0,0 +1,66 @@
+import { execFile, spawn } from 'node:child_process';
+import { promisify } from 'node:util';
+import { GH_EXECUTABLE, getGithubTokenFromGhCli } from '@main/core/updates/github-token';
+import { log } from '@main/lib/logger';
+import { GHCR_REGISTRY } from './constants';
+import { DOCKER_EXECUTABLE } from './docker';
+
+const execFileAsync = promisify(execFile);
+
+/** The signed-in GitHub username, needed as the `docker login` user for a GHCR
+ * personal-access token. Null when `gh` is missing / not authenticated. */
+async function getGithubLogin(): Promise<string | null> {
+ try {
+ const { stdout } = await execFileAsync(GH_EXECUTABLE, ['api', 'user', '--jq', '.login'], {
+ timeout: 10_000,
+ });
+ const login = stdout.trim();
+ return login.length > 0 ? login : null;
+ } catch {
+ return null;
+ }
+}
+
+/** `docker login <registry> -u <user> --password-stdin`, feeding the token over
+ * stdin so it never lands in the process argv / command history. */
+function dockerLoginWithToken(registry: string, username: string, token: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(DOCKER_EXECUTABLE, ['login', registry, '-u', username, '--password-stdin']);
+ let stderr = '';
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ stderr += chunk;
+ });
+ child.on('error', reject);
+ child.on('close', (code) => {
+ if (code === 0) resolve();
+ else reject(new Error(`docker login ${registry} failed (exit ${code}): ${stderr.trim()}`));
+ });
+ child.stdin.write(token);
+ child.stdin.end();
+ });
+}
+
+/**
+ * Authenticate Docker to GHCR using the user's existing `gh` login, so private
+ * release images pull before the public-repo flip (CHOO-1260). When no gh token
+ * is available we warn and proceed: if the images are already public this is a
+ * no-op, and if they are private the subsequent `docker compose up` fails loudly
+ * on the pull — which surfaces the real problem rather than hiding it here.
+ */
+export async function ensureGhcrLogin(): Promise<void> {
+ const token = await getGithubTokenFromGhCli();
+ if (!token) {
+ log.warn(
+ 'local-switch-server: no gh CLI token; skipping GHCR login (private image pulls will fail)'
+ );
+ return;
+ }
+ const username = await getGithubLogin();
+ if (!username) {
+ log.warn('local-switch-server: could not resolve GitHub login; skipping GHCR login');
+ return;
+ }
+ await dockerLoginWithToken(GHCR_REGISTRY, username, token);
+ log.info('local-switch-server: authenticated Docker to GHCR');
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/health.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/health.ts
new file mode 100644
index 000000000..3bb8928e8
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/health.ts
@@ -0,0 +1,48 @@
+import { log } from '@main/lib/logger';
+
+const DEFAULT_TIMEOUT_MS = 3 * 60 * 1000;
+const POLL_INTERVAL_MS = 2000;
+
+const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
+ new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
+ return;
+ }
+ const timer = setTimeout(resolve, ms);
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearTimeout(timer);
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
+ },
+ { once: true }
+ );
+ });
+
+/**
+ * Poll the Switch core until its gateway answers, so we only register the server
+ * once it can actually serve requests. `/gateway/auth/config` is unauthenticated
+ * and cheap, so it is the readiness probe. Returns true once healthy, false on
+ * timeout. Honours `signal` so a stop/cancel aborts the wait.
+ */
+export async function waitForHealth(
+ apiUrl: string,
+ opts: { signal?: AbortSignal; timeoutMs?: number } = {}
+): Promise<boolean> {
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ const deadline = Date.now() + timeoutMs;
+ const url = `${apiUrl}/gateway/auth/config`;
+
+ while (Date.now() < deadline) {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
+ if (res.ok) return true;
+ } catch {
+ // Not up yet — keep polling until the deadline.
+ }
+ await sleep(POLL_INTERVAL_MS, opts.signal);
+ }
+ log.warn(`local-switch-server: health check timed out after ${timeoutMs}ms`);
+ return false;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/local-server-service.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/local-server-service.ts
new file mode 100644
index 000000000..abb840902
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/local-server-service.ts
@@ -0,0 +1,219 @@
+import { resolveAgentServers } from '@main/core/agents/resolve-servers';
+import { passwordLogin } from '@main/core/switch-servers/auth';
+import {
+ ensureManagedServer,
+ getManagedServer,
+ setActiveServerId,
+} from '@main/core/switch-servers/servers-store';
+import { events } from '@main/lib/events';
+import { log } from '@main/lib/logger';
+import { COMPATIBLE_SWITCH_VERSION, RELEASE_REPO_OWNER } from '@shared/app-identity';
+import type {
+ DockerAvailability,
+ LocalServerStatus,
+ StartLocalServerResult,
+} from '@shared/core/local-switch-server/local-switch-server';
+import {
+ localServerLogChannel,
+ localServerStatusChannel,
+} from '@shared/events/localSwitchServerEvents';
+import { materialiseComposeFile } from './bundled-compose';
+import { composeDown, composeUp, isStackRunning } from './compose';
+import { GHCR_REGISTRY, LOCAL_SERVER_ADMIN_EMAIL, LOCAL_SERVER_NAME } from './constants';
+import { detectDocker } from './docker';
+import { buildEnvFile, writeEnvFile } from './env-file';
+import { apiUrlFor, gatewayUrlFor } from './free-port';
+import { ensureGhcrLogin } from './ghcr-auth';
+import { waitForHealth } from './health';
+import { envFilePath } from './paths';
+import { clearPorts, resolvePorts } from './ports';
+import { clearSecrets, loadOrCreateSecrets } from './secrets';
+
+/**
+ * Supervises the managed local Switch stack: Docker detection, config
+ * generation, `docker compose` lifecycle, health-gated registration, and
+ * stop/reset. One operation runs at a time (`busy`); every state transition is
+ * pushed to the renderer over `localServerStatusChannel`.
+ *
+ * Deliberately does NOT stop the containers on app quit — the local stack keeps
+ * running so its rooms stay live while switchdash is closed, matching the remote
+ * sidecar model. `dispose()` only aborts an in-flight health wait.
+ */
+class LocalServerService {
+ private status: LocalServerStatus = {
+ phase: 'stopped',
+ serverId: null,
+ version: COMPATIBLE_SWITCH_VERSION,
+ message: null,
+ error: null,
+ };
+
+ private busy = false;
+ private startAbort: AbortController | null = null;
+
+ getStatus(): LocalServerStatus {
+ return this.status;
+ }
+
+ detectDocker(): Promise<DockerAvailability> {
+ return detectDocker();
+ }
+
+ private setStatus(patch: Partial<LocalServerStatus>): void {
+ this.status = { ...this.status, ...patch };
+ events.emit(localServerStatusChannel, this.status);
+ }
+
+ /** Reconcile status at boot so a stack that survived the last quit shows as
+ * running without the user re-starting it. The managed server's URLs are the
+ * per-machine ones persisted at first start, so we reflect the existing record
+ * rather than recomputing — the containers are bound to those ports. */
+ async initialize(): Promise<void> {
+ try {
+ const managed = await getManagedServer();
+ if (managed && (await isStackRunning())) {
+ this.setStatus({ phase: 'running', serverId: managed.id, message: null, error: null });
+ }
+ } catch (error) {
+ log.warn('local-switch-server: boot status reconcile failed', { error });
+ }
+ }
+
+ async start(): Promise<StartLocalServerResult> {
+ if (this.busy) {
+ return { kind: 'error', message: 'A local-server operation is already in progress.' };
+ }
+ this.busy = true;
+ this.startAbort = new AbortController();
+ try {
+ this.setStatus({ phase: 'starting', error: null, message: 'Checking Docker…' });
+ const docker = await detectDocker();
+ if (!docker.available) {
+ this.setStatus({ phase: 'error', error: docker.detail });
+ return { kind: 'docker-unavailable', reason: docker.reason, detail: docker.detail };
+ }
+
+ this.setStatus({ message: 'Authenticating to image registry…' });
+ await ensureGhcrLogin();
+
+ this.setStatus({ message: 'Preparing configuration…' });
+ await materialiseComposeFile();
+ const secrets = await loadOrCreateSecrets();
+ // Pick free host ports for this machine (persisted + reused) so the stack
+ // never collides with a dev's existing services on 8000 / 5432 / 3000.
+ const ports = await resolvePorts();
+ const gatewayUrl = gatewayUrlFor(ports);
+ const apiUrl = apiUrlFor(ports);
+ await writeEnvFile(
+ envFilePath(),
+ buildEnvFile({
+ version: COMPATIBLE_SWITCH_VERSION,
+ registry: GHCR_REGISTRY,
+ namespace: RELEASE_REPO_OWNER,
+ ports,
+ secrets,
+ })
+ );
+
+ this.setStatus({ message: 'Starting containers (pulling images if needed)…' });
+ await composeUp((line) => events.emit(localServerLogChannel, { line }));
+
+ this.setStatus({ message: 'Waiting for the server to become healthy…' });
+ // Probe via the gateway URL (nginx → switch-core), the same path switchdash's
+ // management calls take, so we only register once that whole path answers.
+ const healthy = await waitForHealth(gatewayUrl, {
+ signal: this.startAbort.signal,
+ });
+ if (!healthy) {
+ const error = 'The local server did not become healthy in time.';
+ this.setStatus({ phase: 'error', error });
+ return { kind: 'error', message: error };
+ }
+
+ const server = await ensureManagedServer({
+ name: LOCAL_SERVER_NAME,
+ gatewayUrl,
+ apiUrl,
+ });
+ await setActiveServerId(server.id);
+
+ // switchdash generated the admin password, so sign in on the user's behalf
+ // rather than showing a login wall for a secret they never saw. A failure
+ // here does not fail the start — the stack is healthy; the server view just
+ // falls back to its sign-in panel.
+ this.setStatus({ message: 'Signing in…' });
+ const login = await passwordLogin(
+ server,
+ LOCAL_SERVER_ADMIN_EMAIL,
+ secrets.gatewayAdminPassword
+ );
+ if (!login.success) {
+ log.warn('local-switch-server: auto sign-in failed; server will show a sign-in prompt', {
+ error: login.error,
+ });
+ }
+
+ await resolveAgentServers();
+
+ this.setStatus({ phase: 'running', serverId: server.id, message: null, error: null });
+ return { kind: 'started', serverId: server.id };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log.error('local-switch-server: start failed', { error });
+ this.setStatus({ phase: 'error', error: message });
+ return { kind: 'error', message };
+ } finally {
+ this.busy = false;
+ this.startAbort = null;
+ }
+ }
+
+ async stop(): Promise<void> {
+ if (this.busy) throw new Error('A local-server operation is already in progress.');
+ this.busy = true;
+ try {
+ this.setStatus({ phase: 'stopping', message: 'Stopping containers…' });
+ await composeDown(false);
+ this.setStatus({ phase: 'stopped', message: null, error: null });
+ } catch (error) {
+ this.setStatus({
+ phase: 'error',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ /** Destroy the stack AND its data volumes, and drop the stored secrets so the
+ * next start is a clean install. Irreversible — the caller must confirm. The
+ * caller (renderer) removes the managed server's agents first, since their
+ * server-side identity is wiped here. */
+ async reset(): Promise<void> {
+ if (this.busy) throw new Error('A local-server operation is already in progress.');
+ this.busy = true;
+ try {
+ this.setStatus({ phase: 'stopping', message: 'Destroying containers and data…' });
+ await composeDown(true);
+ await clearSecrets();
+ await clearPorts();
+ this.setStatus({ phase: 'stopped', message: null, error: null });
+ } catch (error) {
+ this.setStatus({
+ phase: 'error',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ dispose(): void {
+ this.startAbort?.abort();
+ this.startAbort = null;
+ }
+}
+
+export const localServerService = new LocalServerService();
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/paths.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/paths.ts
new file mode 100644
index 000000000..0dae6ad22
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/paths.ts
@@ -0,0 +1,20 @@
+import { join } from 'node:path';
+import { app } from 'electron';
+
+/** Root for the managed stack's on-disk runtime artifacts (compose file + env),
+ * under the app's user-data dir so it is per-install and easy to locate. */
+export function localServerDir(): string {
+ return join(app.getPath('userData'), 'local-switch-server');
+}
+
+/** Where the bundled compose is written so `docker compose -f <path>` can run
+ * it. Docker cannot read a file inside the app bundle, so we materialise it. */
+export function composeFilePath(): string {
+ return join(localServerDir(), 'standalone-docker-compose.yml');
+}
+
+/** The generated `.env` docker compose interpolates. Secrets originate in the
+ * encrypted store; this file is a derived runtime artifact (written 0600). */
+export function envFilePath(): string {
+ return join(localServerDir(), '.env');
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ports.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ports.ts
new file mode 100644
index 000000000..5d61764ea
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/ports.ts
@@ -0,0 +1,45 @@
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+import { isPorts, type LocalServerPorts, pickFreePorts } from './free-port';
+import { localServerDir } from './paths';
+
+function portsFilePath(): string {
+ return join(localServerDir(), 'ports.json');
+}
+
+async function loadPersisted(): Promise<LocalServerPorts | null> {
+ try {
+ const parsed: unknown = JSON.parse(await readFile(portsFilePath(), 'utf8'));
+ return isPorts(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+async function persist(ports: LocalServerPorts): Promise<void> {
+ await mkdir(dirname(portsFilePath()), { recursive: true });
+ await writeFile(portsFilePath(), JSON.stringify(ports, null, 2), 'utf8');
+}
+
+/**
+ * The ports the managed stack should publish on. Reuses the persisted choice if
+ * present — the running containers are already bound to those, and reusing keeps
+ * the server's URLs stable across restarts — otherwise picks free ports once and
+ * persists them.
+ */
+export async function resolvePorts(): Promise<LocalServerPorts> {
+ const existing = await loadPersisted();
+ if (existing) return existing;
+ const chosen = await pickFreePorts();
+ await persist(chosen);
+ return chosen;
+}
+
+/** Drop the persisted choice so the next start picks fresh ports (reset path). */
+export async function clearPorts(): Promise<void> {
+ try {
+ await writeFile(portsFilePath(), JSON.stringify({}), 'utf8');
+ } catch {
+ // Best-effort: a missing file is already the desired state.
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml
new file mode 100644
index 000000000..4f21aab08
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml
@@ -0,0 +1,154 @@
+# BUNDLED COPY — do not hand-edit. This is the standalone compose published to
+# GHCR as `standalone-compose:<version>` by the switch-release workflow, pinned
+# to COMPATIBLE_SWITCH_VERSION (src/shared/app-identity.ts) and bundled into the
+# app so local-server mode needs no runtime OCI puller. Re-sync it from the
+# repo's deploy/local/standalone-docker-compose.yml when bumping the pin
+# (scripts/sync-standalone-compose.mjs).
+#
+# Standalone all-in-one Switch stack, running published GHCR images.
+#
+# This file is a VERSIONED CONTRACT: service names, profiles, and the env vars
+# below are the interface switchdash (and any other consumer) pins against. It
+# is itself published to GHCR as an OCI artifact per `switch-v*` release, tagged
+# with the same version as the images. Change the interface deliberately.
+#
+# Images are pulled from GHCR — nothing is built. Repo users who want the
+# build-from-source flow add the build override (see `just standalone-up`):
+# docker compose -f standalone-docker-compose.yml -f standalone-docker-compose.build.yml up
+#
+# Profiles keep optional services opt-in:
+# (core, no profile) postgres, tuwunel, switch — always started
+# collab init-db, mattermost, setup — Mattermost bridge + seeder
+# gateway gateway — operator dashboard
+# Select them with `--profile collab --profile gateway` or COMPOSE_PROFILES.
+#
+# Image coordinates are env-interpolated so the same file retargets registries
+# and pins versions without edits:
+# SWITCH_REGISTRY (default ghcr.io)
+# SWITCH_IMAGE_NAMESPACE (default sandbox-quantum)
+# SWITCH_VERSION (default latest)
+
+services:
+ postgres:
+ image: postgres:16-alpine
+ ports:
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${POSTGRES_HOST_PORT:-5432}:5432"
+ environment:
+ POSTGRES_USER: ${DB_USER}
+ POSTGRES_PASSWORD: ${DB_PASSWORD}
+ POSTGRES_DB: ${DB_NAME}
+ volumes:
+ - pgdata:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
+ interval: 2s
+ timeout: 3s
+ retries: 10
+
+ init-db:
+ image: postgres:16-alpine
+ profiles: ["collab"]
+ environment:
+ PGPASSWORD: ${DB_PASSWORD}
+ entrypoint: >
+ sh -c "
+ until pg_isready -h postgres -U ${DB_USER}; do sleep 1; done
+ psql -h postgres -U ${DB_USER} -tc \"SELECT 1 FROM pg_database WHERE datname='mattermost'\" | grep -q 1 ||
+ psql -h postgres -U ${DB_USER} -c 'CREATE DATABASE mattermost;'
+ "
+ depends_on:
+ postgres:
+ condition: service_healthy
+
+ tuwunel:
+ image: jevolk/tuwunel:v1.7.1
+ volumes:
+ - tuwuneldata:/var/lib/tuwunel
+ environment:
+ TUWUNEL_SERVER_NAME: localhost
+ TUWUNEL_DATABASE_PATH: /var/lib/tuwunel
+ TUWUNEL_ADDRESS: 0.0.0.0
+ TUWUNEL_PORT: "8008"
+ TUWUNEL_ALLOW_FEDERATION: "false"
+ TUWUNEL_ALLOW_REGISTRATION: "false"
+ TUWUNEL_REGISTRATION_SHARED_SECRET: ${MATRIX_REGISTRATION_SHARED_SECRET}
+ TUWUNEL_MAX_REQUEST_SIZE: "20000000"
+
+ mattermost:
+ image: mattermost/mattermost-team-edition:latest
+ profiles: ["collab"]
+ ports:
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${MATTERMOST_HOST_PORT:-8065}:8065"
+ volumes:
+ - mmdata:/mattermost/data
+ environment:
+ MM_SQLSETTINGS_DRIVERNAME: postgres
+ MM_SQLSETTINGS_DATASOURCE: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/mattermost?sslmode=disable
+ MM_SERVICESETTINGS_SITEURL: http://localhost:${MATTERMOST_HOST_PORT:-8065}
+ MM_SERVICESETTINGS_ENABLELOCALMODE: "true"
+ MM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"
+ MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"
+ # Lets the bridge hard-delete (permanent=true) an agent's transient
+ # "working on it…" status post instead of soft-deleting it, which would
+ # leave a "(message deleted)" tombstone. Requires Mattermost >= v10.2.
+ MM_SERVICESETTINGS_ENABLEAPIPOSTDELETION: "true"
+ MM_TEAMSETTINGS_ENABLEOPENSERVER: "true"
+ depends_on:
+ init-db:
+ condition: service_completed_successfully
+
+ switch:
+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:-latest}
+ ports:
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${API_HOST_PORT:-8000}:8000"
+ environment:
+ DB_HOST: postgres
+ DB_PORT: "5432"
+ DB_USER: ${DB_USER}
+ DB_PASSWORD: ${DB_PASSWORD}
+ DB_NAME: ${DB_NAME}
+ MATRIX_SERVER: http://tuwunel:8008
+ MATRIX_SERVER_NAME: localhost
+ MATRIX_ADMIN_USER: ${MATRIX_ADMIN_USER}
+ MATRIX_ADMIN_PASSWORD: ${MATRIX_ADMIN_PASSWORD}
+ MATRIX_REGISTRATION_SHARED_SECRET: ${MATRIX_REGISTRATION_SHARED_SECRET}
+ AGENT_REGISTRATION_TOKEN: ${AGENT_REGISTRATION_TOKEN}
+ JWT_SECRET_KEY: ${JWT_SECRET_KEY}
+ GATEWAY_ADMIN_EMAIL: ${GATEWAY_ADMIN_EMAIL}
+ GATEWAY_ADMIN_PASSWORD: ${GATEWAY_ADMIN_PASSWORD}
+ FRONTEND_BASE_URL: ${FRONTEND_BASE_URL}
+ depends_on:
+ postgres:
+ condition: service_healthy
+ tuwunel:
+ condition: service_started
+
+ gateway:
+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:-latest}
+ profiles: ["gateway"]
+ ports:
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${GATEWAY_HOST_PORT:-3000}:3000"
+ depends_on:
+ - switch
+
+ setup:
+ image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/setup:${SWITCH_VERSION:-latest}
+ profiles: ["collab"]
+ restart: on-failure
+ environment:
+ SWITCH_URL: http://switch:8000
+ MATTERMOST_URL: http://mattermost:8065
+ MATTERMOST_URL_FOR_SWITCH: http://mattermost:8065
+ MATTERMOST_ADMIN_USER: ${MATTERMOST_ADMIN_USER}
+ MATTERMOST_ADMIN_PASSWORD: ${MATTERMOST_ADMIN_PASSWORD}
+ MATTERMOST_TEAM_NAME: ${MATTERMOST_TEAM_NAME}
+ MATTERMOST_USER: ${MATTERMOST_USER}
+ MATTERMOST_USER_PASSWORD: ${MATTERMOST_USER_PASSWORD}
+ depends_on:
+ - mattermost
+ - switch
+
+volumes:
+ pgdata:
+ mmdata:
+ tuwuneldata:
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secret-values.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secret-values.ts
new file mode 100644
index 000000000..9bfa2abb2
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secret-values.ts
@@ -0,0 +1,34 @@
+import { randomBytes } from 'node:crypto';
+
+/** The randomly-generated secrets the local stack needs. These are the source of
+ * truth (kept in the OS-encrypted app-secrets store); the on-disk `.env` docker
+ * reads is derived from them at each start. */
+export type LocalServerSecrets = {
+ dbPassword: string;
+ matrixRegistrationSharedSecret: string;
+ matrixAdminPassword: string;
+ agentRegistrationToken: string;
+ jwtSecretKey: string;
+ gatewayAdminPassword: string;
+ mattermostAdminPassword: string;
+ mattermostUserPassword: string;
+};
+
+function token(bytes = 24): string {
+ return randomBytes(bytes).toString('base64url');
+}
+
+/** Generate a fresh, all-distinct secret bundle. Pure apart from CSPRNG input,
+ * so it has no dependency on the Electron app or DB and is unit-testable. */
+export function generateSecrets(): LocalServerSecrets {
+ return {
+ dbPassword: token(),
+ matrixRegistrationSharedSecret: token(),
+ matrixAdminPassword: token(),
+ agentRegistrationToken: token(),
+ jwtSecretKey: token(32),
+ gatewayAdminPassword: token(),
+ mattermostAdminPassword: token(),
+ mattermostUserPassword: token(),
+ };
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.test.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.test.ts
new file mode 100644
index 000000000..cd8323f7f
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { generateSecrets } from './secret-values';
+
+describe('generateSecrets', () => {
+ it('populates every field with a non-empty value', () => {
+ const s = generateSecrets();
+ for (const [key, value] of Object.entries(s)) {
+ expect(value, `empty ${key}`).toBeTruthy();
+ expect(value.length, `short ${key}`).toBeGreaterThanOrEqual(16);
+ }
+ });
+
+ it('generates distinct values across fields and across calls', () => {
+ const a = generateSecrets();
+ const b = generateSecrets();
+ expect(new Set(Object.values(a)).size).toBe(Object.keys(a).length);
+ expect(a.jwtSecretKey).not.toBe(b.jwtSecretKey);
+ expect(a.dbPassword).not.toBe(b.dbPassword);
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.ts b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.ts
new file mode 100644
index 000000000..8f2bfd5a5
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/local-switch-server/secrets.ts
@@ -0,0 +1,31 @@
+import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';
+import { generateSecrets, type LocalServerSecrets } from './secret-values';
+
+/** Encrypted-store key holding the local stack's secret bundle (JSON). */
+const SECRETS_KEY = 'local-switch-server:secrets';
+
+/**
+ * Return the stored secret bundle, generating and persisting one on first use.
+ * Reusing the same secrets across restarts is required — the Postgres volume was
+ * initialised with the first `DB_PASSWORD`, so regenerating it would lock the
+ * stack out of its own database.
+ */
+export async function loadOrCreateSecrets(): Promise<LocalServerSecrets> {
+ const existing = await encryptedAppSecretsStore.getSecret(SECRETS_KEY);
+ if (existing) {
+ try {
+ return JSON.parse(existing) as LocalServerSecrets;
+ } catch {
+ // Corrupt bundle — fall through and regenerate.
+ }
+ }
+ const fresh = generateSecrets();
+ await encryptedAppSecretsStore.setSecret(SECRETS_KEY, JSON.stringify(fresh));
+ return fresh;
+}
+
+/** Drop the secret bundle so the next start generates fresh credentials. Only
+ * safe to call after the data volumes have been destroyed (reset). */
+export async function clearSecrets(): Promise<void> {
+ await encryptedAppSecretsStore.deleteSecret(SECRETS_KEY);
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/servers-store.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/servers-store.ts
index 803ce6e37..cb268a00a 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/servers-store.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/servers-store.ts
@@ -21,6 +21,7 @@ function mapRow(row: SwitchServerRow): SwitchServer {
name: row.name,
gatewayUrl: row.gatewayUrl,
apiUrl: row.apiUrl,
+ managed: row.managed,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
};
@@ -67,6 +68,65 @@ export async function getServer(id: string): Promise<SwitchServer | null> {
return row ? mapRow(row) : null;
}
+/** The single server switchdash runs itself (local-server mode), or null. */
+export async function getManagedServer(): Promise<SwitchServer | null> {
+ const [row] = await db
+ .select()
+ .from(switchServers)
+ .where(eq(switchServers.managed, true))
+ .limit(1);
+ return row ? mapRow(row) : null;
+}
+
+/**
+ * Upsert the single managed local server record. Reuses the existing managed row
+ * if there is one (updating its URLs, which can change across app versions),
+ * else adopts a row already at this gateway URL (e.g. added by hand), else
+ * inserts. Keeps exactly one managed row rather than duplicating on URL changes.
+ */
+export async function ensureManagedServer(params: AddServerParams): Promise<SwitchServer> {
+ const gatewayUrl = normaliseUrl(params.gatewayUrl);
+ const apiUrl = normaliseUrl(params.apiUrl);
+ // Prefer the single existing managed row (its URLs may have changed across app
+ // versions), then any row already at this gateway URL; otherwise insert.
+ const existing = (await getManagedServer()) ?? (await getServerByGatewayUrl(gatewayUrl));
+ if (existing) {
+ const [row] = await db
+ .update(switchServers)
+ .set({
+ name: params.name.trim(),
+ gatewayUrl,
+ apiUrl,
+ managed: true,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ })
+ .where(eq(switchServers.id, existing.id))
+ .returning();
+ return mapRow(row);
+ }
+ const [row] = await db
+ .insert(switchServers)
+ .values({
+ id: randomUUID(),
+ name: params.name.trim(),
+ gatewayUrl,
+ apiUrl,
+ managed: true,
+ updatedAt: sql`CURRENT_TIMESTAMP`,
+ })
+ .returning();
+ return mapRow(row);
+}
+
+async function getServerByGatewayUrl(gatewayUrl: string): Promise<SwitchServer | null> {
+ const [row] = await db
+ .select()
+ .from(switchServers)
+ .where(eq(switchServers.gatewayUrl, gatewayUrl))
+ .limit(1);
+ return row ? mapRow(row) : null;
+}
+
export async function addServer(params: AddServerParams): Promise<SwitchServer> {
const [row] = await db
.insert(switchServers)
diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.ts
index 423904e0d..3612e8d9a 100644
--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts
+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts
@@ -103,6 +103,10 @@ export const switchServers = sqliteTable(
* `switch-gateway.*`).
*/
apiUrl: text('api_url').notNull(),
+ /** True when switchdash provisions and runs this server itself via
+ * local-server mode (`docker compose`). Managed servers get lifecycle
+ * controls (start/stop/reset) and are not user-editable connection records. */
+ managed: integer('managed', { mode: 'boolean' }).notNull().default(false),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
diff --git a/dash/apps/switchdash-desktop/src/main/index.ts b/dash/apps/switchdash-desktop/src/main/index.ts
index 28afdd51e..d11a33da2 100644
--- a/dash/apps/switchdash-desktop/src/main/index.ts
+++ b/dash/apps/switchdash-desktop/src/main/index.ts
@@ -14,6 +14,7 @@ import { initializeRemoteDiscovery, initializeRemoteWatchers } from './core/agen
import { resolveAgentServers } from './core/agents/resolve-servers';
import { appService } from './core/app/service';
import { localDependencyManager } from './core/dependencies/dependency-managers';
+import { localServerService } from './core/local-switch-server/local-server-service';
import { locationManager } from './core/locations/location-manager';
import { locationSettingsService } from './core/locations/settings/location-settings-service';
import { promptLibraryService } from './core/prompt-library/service';
@@ -126,6 +127,10 @@ void app.whenReady().then(async () => {
void reconcileResourceSampler();
+ // Reflect a managed local Switch stack that survived the last quit, so the UI
+ // shows it running without the user restarting it.
+ void localServerService.initialize();
+
const dependenciesReady = localDependencyManager.probeAll().catch((e: unknown) => {
log.error('Failed to probe dependencies:', e);
});
@@ -191,6 +196,7 @@ app.on('before-quit', (event) => {
event.preventDefault();
agentHookService.dispose();
stopResourceSampler();
+ localServerService.dispose();
updateService.dispose();
void locationManager.dispose().catch((e) => {
log.error('Failed to shutdown location manager:', e);
diff --git a/dash/apps/switchdash-desktop/src/main/rpc.ts b/dash/apps/switchdash-desktop/src/main/rpc.ts
index c5bf65f4b..0da55dc26 100644
--- a/dash/apps/switchdash-desktop/src/main/rpc.ts
+++ b/dash/apps/switchdash-desktop/src/main/rpc.ts
@@ -2,6 +2,7 @@ import { createRPCNamespace, createRPCRouter } from '../shared/lib/ipc/rpc';
import { agentsController } from './core/agents/controller';
import { appController } from './core/app/controller';
import { filesController } from './core/fs/controller';
+import { localSwitchServerController } from './core/local-switch-server/controller';
import { locationsController } from './core/locations/controller';
import { locationRuntimeSettingsController } from './core/locations/location-runtime-settings-controller';
import { promptLibraryController } from './core/prompt-library/controller';
@@ -39,6 +40,7 @@ export const rpcRouter = createRPCRouter({
locationRuntimeSettings: locationRuntimeSettingsController,
switchServers: switchServersController,
switchSetup: switchSetupController,
+ localSwitchServer: localSwitchServerController,
remoteHosts: remoteHostsController,
fs: createRPCNamespace({
watch: filesController,
diff --git a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
index fad564cfe..58b8dcf12 100644
--- a/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/app/modal-registry.ts
@@ -37,7 +37,7 @@ export const modalRegistry = {
feedbackModal: createModal(FeedbackModal),
renameSessionModal: createModal(RenameSessionModal, { size: 'xs' }),
deleteSessionModal: createModal(DeleteSessionModal, { size: 'sm' }),
- addServerModal: createModal(AddServerModal, { size: 'sm' }),
+ addServerModal: createModal(AddServerModal, { size: 'md' }),
assignServerModal: createModal(AssignServerModal, { size: 'sm' }),
// oxlint-disable-next-line typescript/no-explicit-any
} satisfies Record<string, ModalRegistryEntry<any, any>>;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
index 21abe106a..75841a544 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/AddServerModal.tsx
@@ -1,6 +1,8 @@
+import { CircleCheck, HardDrive, Server, TriangleAlert } from 'lucide-react';
import { observer } from 'mobx-react-lite';
-import { useCallback, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { type BaseModalProps } from '@renderer/lib/modal/modal-provider';
+import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
@@ -11,6 +13,8 @@ import {
} from '@renderer/lib/ui/dialog';
import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
import { Input } from '@renderer/lib/ui/input';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { localServerStore } from './local-server-store';
import { switchServersStore } from './switch-servers-store';
type Props = BaseModalProps<void> & {
@@ -22,8 +26,308 @@ type Props = BaseModalProps<void> & {
initialName?: string;
/** When set, the modal edits this existing server instead of adding one. */
serverId?: string;
+ /** Jump straight to a step, skipping the local/remote chooser. */
+ mode?: 'local' | 'remote';
};
+type Step = 'choose' | 'local' | 'remote';
+
+export const AddServerModal = observer(function AddServerModal(props: Props) {
+ const isEdit = props.serverId != null;
+ const [step, setStep] = useState<Step>(isEdit ? 'remote' : (props.mode ?? 'choose'));
+
+ if (step === 'choose') {
+ return (
+ <ChooseStep
+ onLocal={() => setStep('local')}
+ onRemote={() => setStep('remote')}
+ onClose={props.onClose}
+ />
+ );
+ }
+ if (step === 'local') {
+ return (
+ <LocalSetupStep
+ onBack={isEdit ? undefined : () => setStep('choose')}
+ onSuccess={props.onSuccess}
+ onClose={props.onClose}
+ />
+ );
+ }
+ return (
+ <RemoteServerStep
+ {...props}
+ isEdit={isEdit}
+ onBack={isEdit ? undefined : () => setStep('choose')}
+ />
+ );
+});
+
+// ---------------------------------------------------------------------------
+// Step 1 — choose local vs remote
+// ---------------------------------------------------------------------------
+
+function ChooseStep({
+ onLocal,
+ onRemote,
+ onClose,
+}: {
+ onLocal: () => void;
+ onRemote: () => void;
+ onClose: () => void;
+}) {
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Add a Switch server</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="pt-0">
+ <div className="grid gap-3">
+ <ChoiceCard
+ icon={<HardDrive className="size-5" />}
+ title="Local server"
+ description="Run the full Switch stack on this machine with Docker. Best for trying Switch out."
+ onClick={onLocal}
+ />
+ <ChoiceCard
+ icon={<Server className="size-5" />}
+ title="Remote server"
+ description="Connect to an existing Switch gateway by URL."
+ onClick={onRemote}
+ />
+ </div>
+ </DialogContentArea>
+ <DialogFooter>
+ <Button variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
+
+function ChoiceCard({
+ icon,
+ title,
+ description,
+ onClick,
+}: {
+ icon: React.ReactNode;
+ title: string;
+ description: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="bg-card hover:border-border-hover flex items-start gap-3 rounded-lg border border-border p-4 text-left hover:bg-background-tertiary-2"
+ >
+ <span className="mt-0.5 text-foreground-muted">{icon}</span>
+ <span className="space-y-1">
+ <span className="block text-sm font-medium text-foreground">{title}</span>
+ <span className="block text-xs text-foreground-muted">{description}</span>
+ </span>
+ </button>
+ );
+}
+
+function SetupStepItem({ children }: { children: React.ReactNode }) {
+ return (
+ <li className="flex items-start gap-2">
+ <span aria-hidden className="mt-1.5 size-1 shrink-0 rounded-full bg-foreground-muted" />
+ <span>{children}</span>
+ </li>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Step 2a — local server setup (preflight → progress → done)
+// ---------------------------------------------------------------------------
+
+const LocalSetupStep = observer(function LocalSetupStep({
+ onBack,
+ onSuccess,
+ onClose,
+}: {
+ onBack?: () => void;
+ onSuccess: () => void;
+ onClose: () => void;
+}) {
+ const store = localServerStore;
+
+ useEffect(() => {
+ void store.init();
+ void store.checkDocker();
+ }, [store]);
+
+ const running = store.isRunning;
+ const starting = store.isTransitioning;
+ const docker = store.docker;
+ const dockerReady = docker?.available ?? false;
+ const dockerUnavailable = docker && !docker.available ? docker : null;
+ const idle = !running && !starting;
+
+ const primaryLabel = running ? 'Done' : store.phase === 'error' ? 'Retry' : 'Start';
+ const onPrimary = () => {
+ if (running) onSuccess();
+ else void store.start();
+ };
+
+ return (
+ <>
+ <DialogHeader showCloseButton={false}>
+ <DialogTitle>Set up a local server</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea className="space-y-4 pt-0">
+ <div className="flex items-center gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-background-tertiary text-foreground-muted">
+ <HardDrive className="size-5" />
+ </div>
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-foreground">Local Switch server</p>
+ <p className="truncate text-xs text-foreground-muted">
+ switch-core {store.status?.version ?? ''} · runs on this machine via Docker
+ </p>
+ </div>
+ </div>
+
+ {idle && (
+ <div className="bg-card space-y-2 rounded-lg border border-border p-3">
+ <p className="text-xs font-medium text-foreground-muted">Starting will:</p>
+ <ul className="space-y-1.5 text-xs text-foreground-muted">
+ <SetupStepItem>
+ Pull the Switch images from GHCR (first run downloads a few GB)
+ </SetupStepItem>
+ <SetupStepItem>Run Postgres, Matrix, Mattermost and Switch in Docker</SetupStepItem>
+ <SetupStepItem>
+ Register it as your active server, ready to onboard an agent
+ </SetupStepItem>
+ </ul>
+ </div>
+ )}
+
+ {!running && (
+ <DockerStatus ready={dockerReady} unavailable={dockerUnavailable} checking={!docker} />
+ )}
+
+ {running && (
+ <Alert>
+ <CircleCheck className="size-4" />
+ <AlertTitle>Local server is running</AlertTitle>
+ <AlertDescription>
+ It's now in your servers list — open it to onboard an agent.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {store.error && !dockerUnavailable && !running && (
+ <Alert variant="destructive">
+ <AlertTitle>Setup failed</AlertTitle>
+ <AlertDescription>{store.error}</AlertDescription>
+ </Alert>
+ )}
+
+ {(starting || store.logs.length > 0) && !running && (
+ <div className="space-y-1.5">
+ {store.message && starting && (
+ <div className="flex items-center gap-2 text-sm text-foreground">
+ <Spinner className="size-3.5" />
+ <span>{store.message}</span>
+ </div>
+ )}
+ <LogTail lines={store.logs} />
+ </div>
+ )}
+ </DialogContentArea>
+ <DialogFooter>
+ {onBack && !starting ? (
+ <Button variant="outline" onClick={onBack}>
+ Back
+ </Button>
+ ) : (
+ <Button variant="outline" onClick={onClose} disabled={starting}>
+ {running ? 'Close' : 'Cancel'}
+ </Button>
+ )}
+ <ConfirmButton onClick={onPrimary} disabled={starting || (!running && !dockerReady)}>
+ {starting ? 'Starting…' : primaryLabel}
+ </ConfirmButton>
+ </DialogFooter>
+ </>
+ );
+});
+
+function DockerStatus({
+ ready,
+ unavailable,
+ checking,
+}: {
+ ready: boolean;
+ unavailable: { reason: 'not-installed' | 'daemon-down'; detail: string } | null;
+ checking: boolean;
+}) {
+ if (checking) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ <span>Checking Docker…</span>
+ </div>
+ );
+ }
+ if (unavailable) {
+ return (
+ <Alert variant="destructive">
+ <TriangleAlert className="size-4" />
+ <AlertTitle>
+ {unavailable.reason === 'not-installed'
+ ? 'Docker is not installed'
+ : 'Docker is not running'}
+ </AlertTitle>
+ <AlertDescription>{unavailable.detail}</AlertDescription>
+ </Alert>
+ );
+ }
+ if (ready) {
+ return (
+ <div className="flex items-center gap-2 text-sm text-foreground">
+ <CircleCheck className="size-4 text-green-500" />
+ <span>Docker is ready.</span>
+ </div>
+ );
+ }
+ return null;
+}
+
+function LogTail({ lines }: { lines: string[] }) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const el = ref.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [lines]);
+
+ if (lines.length === 0) return null;
+
+ return (
+ <div
+ ref={ref}
+ className="max-h-48 overflow-auto rounded-md border border-border bg-background-tertiary p-2 font-mono text-[11px] leading-relaxed text-foreground-muted"
+ >
+ {lines.map((line, i) => (
+ // Log lines have no stable id; index is fine for an append-only tail.
+ <div key={i} className="break-all whitespace-pre-wrap">
+ {line}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Step 2b — remote server form (also the edit form)
+// ---------------------------------------------------------------------------
+
function looksLikeUrl(value: string): boolean {
try {
const url = new URL(value);
@@ -33,15 +337,16 @@ function looksLikeUrl(value: string): boolean {
}
}
-export const AddServerModal = observer(function AddServerModal({
+const RemoteServerStep = observer(function RemoteServerStep({
onSuccess,
onClose,
+ onBack,
initialGatewayUrl,
initialApiUrl,
initialName,
serverId,
-}: Props) {
- const isEdit = serverId != null;
+ isEdit,
+}: Props & { isEdit: boolean; onBack?: () => void }) {
const [name, setName] = useState(initialName ?? '');
const [gatewayUrl, setGatewayUrl] = useState(initialGatewayUrl ?? '');
const [apiUrl, setApiUrl] = useState(initialApiUrl ?? '');
@@ -68,9 +373,10 @@ export const AddServerModal = observer(function AddServerModal({
if (!isValid) return;
setSubmitting(true);
setError(null);
- const saved = isEdit
- ? await switchServersStore.updateServer(serverId, trimmedName, trimmedGateway, trimmedApi)
- : await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);
+ const saved =
+ isEdit && serverId
+ ? await switchServersStore.updateServer(serverId, trimmedName, trimmedGateway, trimmedApi)
+ : await switchServersStore.addServer(trimmedName, trimmedGateway, trimmedApi);
if (!saved) {
setError(
switchServersStore.error ??
@@ -85,7 +391,7 @@ export const AddServerModal = observer(function AddServerModal({
return (
<>
<DialogHeader showCloseButton={false}>
- <DialogTitle>{isEdit ? 'Edit Switch server' : 'Add Switch server'}</DialogTitle>
+ <DialogTitle>{isEdit ? 'Edit Switch server' : 'Add a remote server'}</DialogTitle>
</DialogHeader>
<DialogContentArea className="pt-0">
<FieldGroup>
@@ -94,7 +400,7 @@ export const AddServerModal = observer(function AddServerModal({
<Input
value={name}
onChange={(e) => setName(e.target.value)}
- placeholder="Local dev"
+ placeholder="Pilot"
autoFocus
/>
</Field>
@@ -123,8 +429,8 @@ export const AddServerModal = observer(function AddServerModal({
</FieldGroup>
</DialogContentArea>
<DialogFooter>
- <Button variant="outline" onClick={onClose}>
- Cancel
+ <Button variant="outline" onClick={onBack ?? onClose}>
+ {onBack ? 'Back' : 'Cancel'}
</Button>
<ConfirmButton onClick={() => void handleSubmit()} disabled={!isValid || submitting}>
{submitting ? (isEdit ? 'Saving…' : 'Adding…') : isEdit ? 'Save changes' : 'Add server'}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
new file mode 100644
index 000000000..f8336a658
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
@@ -0,0 +1,188 @@
+import { CircleStop, Play, TriangleAlert } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useEffect, useState } from 'react';
+import { Alert, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogContentArea,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@renderer/lib/ui/dialog';
+import { Spinner } from '@renderer/lib/ui/spinner';
+import { localServerStore } from './local-server-store';
+
+const card = 'rounded-lg border border-border bg-card p-4';
+
+/**
+ * Lifecycle controls for the managed local Switch stack: live status, Docker
+ * guidance, and start / stop / reset. Rendered inside the managed server's page.
+ */
+export const LocalServerControls = observer(function LocalServerControls() {
+ const store = localServerStore;
+ const [resetOpen, setResetOpen] = useState(false);
+
+ useEffect(() => {
+ void store.checkDocker();
+ }, [store]);
+
+ const transitioning = store.isTransitioning;
+ const dockerUnavailable = store.docker && !store.docker.available ? store.docker : null;
+
+ return (
+ <div className={`${card} space-y-4`}>
+ <div className="flex items-start justify-between gap-3">
+ <div className="space-y-1">
+ <h3 className="text-sm font-medium text-foreground">Local server</h3>
+ <p className="text-xs text-foreground-muted">
+ Runs the full Switch stack on this machine with Docker (switch-core{' '}
+ {store.status?.version ?? ''}).
+ </p>
+ </div>
+ <PhaseBadge />
+ </div>
+
+ {store.message && transitioning && (
+ <div className="flex items-center gap-2 text-sm text-foreground-muted">
+ <Spinner className="size-3.5" />
+ <span>{store.message}</span>
+ </div>
+ )}
+
+ {dockerUnavailable && (
+ <Alert variant="destructive">
+ <TriangleAlert className="size-4" />
+ <AlertTitle>
+ {dockerUnavailable.reason === 'not-installed'
+ ? 'Docker is not installed'
+ : 'Docker is not running'}
+ </AlertTitle>
+ <AlertDescription>{dockerUnavailable.detail}</AlertDescription>
+ </Alert>
+ )}
+
+ {store.error && !dockerUnavailable && (
+ <Alert variant="destructive">
+ <AlertTitle>Something went wrong</AlertTitle>
+ <AlertDescription>{store.error}</AlertDescription>
+ </Alert>
+ )}
+
+ <div className="flex items-center gap-2">
+ {store.isRunning ? (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={transitioning}
+ onClick={() => void store.stop()}
+ >
+ <CircleStop className="size-4" />
+ Stop
+ </Button>
+ ) : (
+ <Button size="sm" disabled={transitioning} onClick={() => void store.start()}>
+ <Play className="size-4" />
+ {store.phase === 'error' ? 'Retry' : 'Start'}
+ </Button>
+ )}
+ </div>
+
+ <p className="text-xs text-foreground-tertiary-passive">
+ The stack keeps running when you close switchdash.
+ </p>
+
+ <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-4">
+ <div className="space-y-0.5">
+ <p className="text-xs font-medium text-foreground">Reset</p>
+ <p className="text-xs text-foreground-tertiary-passive">
+ Permanently deletes the stack's data and every agent configured against it.
+ </p>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={transitioning}
+ className="shrink-0 border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500"
+ onClick={() => setResetOpen(true)}
+ >
+ Reset…
+ </Button>
+ </div>
+
+ <ResetDialog
+ open={resetOpen}
+ onOpenChange={setResetOpen}
+ disabled={transitioning}
+ onConfirm={() => {
+ setResetOpen(false);
+ void store.reset();
+ }}
+ />
+ </div>
+ );
+});
+
+const ResetDialog = observer(function ResetDialog({
+ open,
+ onOpenChange,
+ disabled,
+ onConfirm,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ disabled: boolean;
+ onConfirm: () => void;
+}) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <TriangleAlert className="size-4 text-red-500" />
+ <DialogTitle>Reset local server</DialogTitle>
+ </DialogHeader>
+ <DialogContentArea>
+ <DialogDescription>
+ This permanently deletes the local server and everything on it — all rooms, messages,
+ and{' '}
+ <strong className="text-foreground">every agent you've configured against it</strong>.
+ This can't be undone. A fresh Start rebuilds an empty stack from scratch.
+ </DialogDescription>
+ </DialogContentArea>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" size="sm" />}>Cancel</DialogClose>
+ <Button variant="destructive" size="sm" disabled={disabled} onClick={onConfirm}>
+ Reset and delete all agents
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+});
+
+const PhaseBadge = observer(function PhaseBadge() {
+ const phase = localServerStore.phase;
+ const label: Record<typeof phase, string> = {
+ stopped: 'Stopped',
+ starting: 'Starting',
+ running: 'Running',
+ stopping: 'Stopping',
+ error: 'Error',
+ };
+ const dot: Record<typeof phase, string> = {
+ stopped: 'bg-foreground-muted',
+ starting: 'bg-amber-500',
+ running: 'bg-green-500',
+ stopping: 'bg-amber-500',
+ error: 'bg-red-500',
+ };
+ return (
+ <span className="flex items-center gap-1.5 text-xs text-foreground-muted">
+ <span aria-hidden className={`inline-block size-2 rounded-full ${dot[phase]}`} />
+ {label[phase]}
+ </span>
+ );
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ServersSidebarSection.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ServersSidebarSection.tsx
index f2708cada..13212c84e 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ServersSidebarSection.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/ServersSidebarSection.tsx
@@ -1,4 +1,4 @@
-import { ChevronDown, ChevronRight, Plus, Server } from 'lucide-react';
+import { ChevronDown, ChevronRight, HardDrive, Plus, Server } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
import {
@@ -10,9 +10,11 @@ import {
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { buttonVariants } from '@renderer/lib/ui/button';
import { MicroLabel } from '@renderer/lib/ui/label';
+import { Spinner } from '@renderer/lib/ui/spinner';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { cn } from '@renderer/utils/utils';
import { SidebarMenu, SidebarMenuButton } from '../sidebar/sidebar-primitives';
+import { localServerStore } from './local-server-store';
import { switchServersStore } from './switch-servers-store';
export const ServersSidebarSection = observer(function ServersSidebarSection() {
@@ -21,14 +23,21 @@ export const ServersSidebarSection = observer(function ServersSidebarSection() {
useEffect(() => {
void store.init();
+ void localServerStore.init();
const onFocus = () => void store.refreshAllStatuses();
window.addEventListener('focus', onFocus);
- return () => window.removeEventListener('focus', onFocus);
+ return () => {
+ window.removeEventListener('focus', onFocus);
+ localServerStore.dispose();
+ };
}, [store]);
// Nothing registered yet — keep the sidebar uncluttered, but still expose a
// way to add the first server.
const empty = store.servers.length === 0;
+ // Offer to start a local server whenever there isn't one already, even if the
+ // user has remote servers registered.
+ const hasManagedServer = store.servers.some((s) => s.managed);
return (
<div className="flex flex-col">
@@ -69,16 +78,32 @@ export const ServersSidebarSection = observer(function ServersSidebarSection() {
{store.serversExpanded && (
<SidebarMenu className="px-2 pb-1">
- {empty ? (
+ {store.servers.map((server) => (
+ <ServerEntry key={server.id} serverId={server.id} />
+ ))}
+ {/* Before the managed record exists (still pulling/starting, or a
+ failed attempt), show a placeholder entry so the local server is
+ always visible in the list — not only once it's healthy. */}
+ {!hasManagedServer && localServerStore.phase !== 'stopped' && (
+ <LocalServerPendingEntry onOpen={() => showAddServerModal({ mode: 'local' })} />
+ )}
+ {!hasManagedServer && localServerStore.phase === 'stopped' && (
+ <button
+ type="button"
+ onClick={() => showAddServerModal({ mode: 'local' })}
+ className="w-full px-3 py-1.5 text-left text-xs text-foreground-tertiary hover:text-foreground"
+ >
+ Start a local server…
+ </button>
+ )}
+ {empty && (
<button
type="button"
onClick={() => showAddServerModal({})}
- className="px-3 py-1.5 text-left text-xs text-foreground-tertiary-passive hover:text-foreground-tertiary"
+ className="w-full px-3 py-1.5 text-left text-xs text-foreground-tertiary-passive hover:text-foreground-tertiary"
>
- Add a Switch server…
+ Add a remote server…
</button>
- ) : (
- store.servers.map((server) => <ServerEntry key={server.id} serverId={server.id} />)
)}
</SidebarMenu>
)}
@@ -86,6 +111,30 @@ export const ServersSidebarSection = observer(function ServersSidebarSection() {
);
});
+const LocalServerPendingEntry = observer(function LocalServerPendingEntry({
+ onOpen,
+}: {
+ onOpen: () => void;
+}) {
+ const phase = localServerStore.phase;
+ const failed = phase === 'error';
+ return (
+ <SidebarMenuButton onClick={onOpen} className="justify-between">
+ <span className="flex min-w-0 items-center gap-2">
+ <HardDrive className="size-4 shrink-0" />
+ <span className="truncate">
+ {failed ? 'Local server (setup failed)' : 'Local Switch server'}
+ </span>
+ <span
+ aria-hidden
+ className={cn('size-1.5 shrink-0 rounded-full', failed ? 'bg-red-500' : 'bg-amber-500')}
+ />
+ </span>
+ {phase === 'starting' && <Spinner className="size-3.5 shrink-0" />}
+ </SidebarMenuButton>
+ );
+});
+
const ServerEntry = observer(function ServerEntry({ serverId }: { serverId: string }) {
const store = switchServersStore;
const { navigate } = useNavigate();
@@ -111,10 +160,19 @@ const ServerEntry = observer(function ServerEntry({ serverId }: { serverId: stri
className="justify-between"
>
<span className="flex min-w-0 items-center gap-2">
- <Server className={cn('size-4 shrink-0', isScoped && 'text-foreground')} />
+ {server.managed ? (
+ <HardDrive className={cn('size-4 shrink-0', isScoped && 'text-foreground')} />
+ ) : (
+ <Server className={cn('size-4 shrink-0', isScoped && 'text-foreground')} />
+ )}
<span className={cn('truncate', isScoped && 'font-medium text-foreground')}>
{server.name}
</span>
+ {server.managed && (
+ <span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">
+ Local
+ </span>
+ )}
<span
aria-hidden
className={cn(
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts
new file mode 100644
index 000000000..28da153a6
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/local-server-store.ts
@@ -0,0 +1,192 @@
+import { makeAutoObservable, runInAction } from 'mobx';
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { getLocationManagerStore } from '@renderer/features/locations/stores/location-selectors';
+import { events, rpc } from '@renderer/lib/ipc';
+import type {
+ DockerAvailability,
+ LocalServerStatus,
+} from '@shared/core/local-switch-server/local-switch-server';
+import {
+ localServerLogChannel,
+ localServerStatusChannel,
+} from '@shared/events/localSwitchServerEvents';
+import { switchServersStore } from './switch-servers-store';
+
+/** Cap the retained log tail so a long pull can't grow the buffer unbounded. */
+const MAX_LOG_LINES = 400;
+
+/**
+ * Renderer store for local-server mode. Mirrors the main-process supervisor's
+ * status (streamed over `localServerStatusChannel`) and exposes the lifecycle
+ * actions. On a successful start/reset it refreshes the servers store so the
+ * managed server record appears/updates in the sidebar.
+ */
+export class LocalServerStore {
+ status: LocalServerStatus | null = null;
+ docker: DockerAvailability | null = null;
+ /** True while a start/stop/reset RPC is in flight. */
+ busy = false;
+ error: string | null = null;
+ /** Live `docker compose` output tail during a start. */
+ logs: string[] = [];
+
+ private off: (() => void) | null = null;
+ private offLog: (() => void) | null = null;
+
+ constructor() {
+ makeAutoObservable(this);
+ }
+
+ get phase(): LocalServerStatus['phase'] {
+ return this.status?.phase ?? 'stopped';
+ }
+
+ get message(): string | null {
+ return this.status?.message ?? null;
+ }
+
+ get isRunning(): boolean {
+ return this.phase === 'running';
+ }
+
+ get isTransitioning(): boolean {
+ return this.busy || this.phase === 'starting' || this.phase === 'stopping';
+ }
+
+ async init(): Promise<void> {
+ if (!this.off) {
+ this.off = events.on(localServerStatusChannel, (status) => {
+ runInAction(() => {
+ this.status = status;
+ });
+ });
+ }
+ if (!this.offLog) {
+ this.offLog = events.on(localServerLogChannel, ({ line }) => {
+ runInAction(() => {
+ this.logs.push(line);
+ if (this.logs.length > MAX_LOG_LINES) {
+ this.logs.splice(0, this.logs.length - MAX_LOG_LINES);
+ }
+ });
+ });
+ }
+ try {
+ const status = await rpc.localSwitchServer.getStatus();
+ runInAction(() => {
+ this.status = status;
+ });
+ } catch (cause) {
+ this.setError(cause);
+ }
+ }
+
+ dispose(): void {
+ this.off?.();
+ this.off = null;
+ this.offLog?.();
+ this.offLog = null;
+ }
+
+ async checkDocker(): Promise<void> {
+ try {
+ const docker = await rpc.localSwitchServer.detectDocker();
+ runInAction(() => {
+ this.docker = docker;
+ });
+ } catch (cause) {
+ this.setError(cause);
+ }
+ }
+
+ async start(): Promise<void> {
+ runInAction(() => {
+ this.busy = true;
+ this.error = null;
+ this.logs = [];
+ });
+ try {
+ const result = await rpc.localSwitchServer.start();
+ if (result.kind === 'docker-unavailable') {
+ runInAction(() => {
+ this.docker = { available: false, reason: result.reason, detail: result.detail };
+ this.error = result.detail;
+ });
+ } else if (result.kind === 'error') {
+ runInAction(() => {
+ this.error = result.message;
+ });
+ } else {
+ await switchServersStore.init();
+ }
+ } catch (cause) {
+ this.setError(cause);
+ } finally {
+ runInAction(() => {
+ this.busy = false;
+ });
+ }
+ }
+
+ async stop(): Promise<void> {
+ runInAction(() => {
+ this.busy = true;
+ this.error = null;
+ });
+ try {
+ await rpc.localSwitchServer.stop();
+ } catch (cause) {
+ this.setError(cause);
+ } finally {
+ runInAction(() => {
+ this.busy = false;
+ });
+ }
+ }
+
+ async reset(): Promise<void> {
+ runInAction(() => {
+ this.busy = true;
+ this.error = null;
+ });
+ try {
+ // Delete the managed server's agents first (same path as the sidebar's
+ // "Remove agent", so they drop out of the tree), then wipe the stack —
+ // the wipe destroys their server-side identity, so leaving them would
+ // strand them as "Unnamed agent" rows.
+ await this.removeManagedAgents();
+ await rpc.localSwitchServer.reset();
+ await switchServersStore.init();
+ } catch (cause) {
+ this.setError(cause);
+ } finally {
+ runInAction(() => {
+ this.busy = false;
+ });
+ }
+ }
+
+ /** Remove every location whose agent belongs to the managed local server. */
+ private async removeManagedAgents(): Promise<void> {
+ const managedId = switchServersStore.servers.find((s) => s.managed)?.id;
+ if (!managedId) return;
+ await agentsStore.load();
+ const locationIds = new Set<string>();
+ for (const [locationId, agents] of agentsStore.byLocation) {
+ if (agents.some((a) => a.serverId === managedId)) locationIds.add(locationId);
+ }
+ const manager = getLocationManagerStore();
+ for (const locationId of locationIds) {
+ await manager.removeLocation(locationId);
+ }
+ await agentsStore.load();
+ }
+
+ private setError(cause: unknown): void {
+ runInAction(() => {
+ this.error = cause instanceof Error ? cause.message : String(cause);
+ });
+ }
+}
+
+export const localServerStore = new LocalServerStore();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index 0a9180129..c852b09fc 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -97,12 +97,14 @@ export class SwitchServersStore {
runInAction(() => {
this.statuses.set(serverId, status);
});
- } catch (cause) {
+ } catch {
// An unreachable server is a real, displayable state — record it as
- // disconnected rather than throwing away the whole refresh.
+ // disconnected (the per-server status dot shows it). A background poll
+ // failure must NOT raise the page-level `error` banner: that field is
+ // global, so one unreachable server would paint an error over every
+ // server's view.
runInAction(() => {
this.statuses.set(serverId, { serverId, connected: false, user: null });
- this.error = cause instanceof Error ? cause.message : String(cause);
});
} finally {
runInAction(() => {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
index 2bb5fa34d..c2816c67f 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
@@ -12,6 +12,8 @@ import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import { Label } from '@renderer/lib/ui/label';
import { Spinner } from '@renderer/lib/ui/spinner';
+import { localServerStore } from './local-server-store';
+import { LocalServerControls } from './LocalServerControls';
import { switchServersStore } from './switch-servers-store';
const card = 'rounded-lg border border-border bg-card p-4';
@@ -40,10 +42,16 @@ const ServerMainPanel = observer(function ServerMainPanel() {
const server = store.servers.find((s) => s.id === serverId);
const showEditServerModal = useShowModal('addServerModal');
+ // A managed server that isn't running has no gateway to reach — its
+ // connection status, sign-in, and web-app links are meaningless until it's up,
+ // so we neither fetch nor render them (only the Start/Reset controls show).
+ const detailsVisible = !server?.managed || localServerStore.isRunning;
+
useEffect(() => {
+ if (!detailsVisible) return;
void store.refreshStatus(serverId);
void store.ensureAuthConfig(serverId);
- }, [serverId, store]);
+ }, [serverId, store, detailsVisible]);
if (!server) {
return (
@@ -62,28 +70,33 @@ const ServerMainPanel = observer(function ServerMainPanel() {
<div className="mx-auto w-full max-w-2xl space-y-6 p-6">
<header className="flex items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
- <h2 className="text-xl text-foreground">{server.name}</h2>
+ <div className="flex items-center gap-2">
+ <h2 className="text-xl text-foreground">{server.name}</h2>
+ {server.managed && <Badge variant="secondary">Local</Badge>}
+ </div>
<p className="truncate text-sm text-foreground-muted">{server.gatewayUrl}</p>
<p className="truncate text-xs text-foreground-tertiary-passive">
API: {server.apiUrl}
</p>
</div>
- <Button
- variant="outline"
- size="sm"
- className="shrink-0"
- onClick={() =>
- showEditServerModal({
- serverId,
- initialName: server.name,
- initialGatewayUrl: server.gatewayUrl,
- initialApiUrl: server.apiUrl,
- })
- }
- >
- <Pencil className="size-3.5" />
- Edit
- </Button>
+ {!server.managed && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="shrink-0"
+ onClick={() =>
+ showEditServerModal({
+ serverId,
+ initialName: server.name,
+ initialGatewayUrl: server.gatewayUrl,
+ initialApiUrl: server.apiUrl,
+ })
+ }
+ >
+ <Pencil className="size-3.5" />
+ Edit
+ </Button>
+ )}
</header>
{store.error && (
@@ -93,52 +106,58 @@ const ServerMainPanel = observer(function ServerMainPanel() {
</Alert>
)}
- <div className={`${card} flex items-center justify-between gap-3`}>
- <div className="flex items-center gap-2 text-sm">
- <StatusDot connected={connected} />
- {connected ? (
- <span className="text-foreground">
- Connected{status?.user ? ` as ${status.user.name || status.user.email}` : ''}
- </span>
- ) : (
- <span className="text-foreground-muted">Not signed in</span>
- )}
- {status?.user?.role && <Badge variant="secondary">{status.user.role}</Badge>}
- {refreshing && <Spinner className="size-3.5" />}
- </div>
- <div className="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- disabled={refreshing}
- onClick={() => void store.refreshStatus(serverId)}
- >
- <RefreshCw className="size-4" />
- Refresh
- </Button>
- {connected && (
- <Button variant="ghost" size="sm" onClick={() => void store.logout(serverId)}>
- Sign out
- </Button>
- )}
- </div>
- </div>
+ {server.managed && <LocalServerControls />}
- {!connected && <LoginPanel serverId={serverId} />}
+ {detailsVisible && (
+ <>
+ <div className={`${card} flex items-center justify-between gap-3`}>
+ <div className="flex items-center gap-2 text-sm">
+ <StatusDot connected={connected} />
+ {connected ? (
+ <span className="text-foreground">
+ Connected{status?.user ? ` as ${status.user.name || status.user.email}` : ''}
+ </span>
+ ) : (
+ <span className="text-foreground-muted">Not signed in</span>
+ )}
+ {status?.user?.role && <Badge variant="secondary">{status.user.role}</Badge>}
+ {refreshing && <Spinner className="size-3.5" />}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={refreshing}
+ onClick={() => void store.refreshStatus(serverId)}
+ >
+ <RefreshCw className="size-4" />
+ Refresh
+ </Button>
+ {connected && (
+ <Button variant="ghost" size="sm" onClick={() => void store.logout(serverId)}>
+ Sign out
+ </Button>
+ )}
+ </div>
+ </div>
- <div className={`${card} space-y-3`}>
- <p className="text-sm text-foreground-muted">
- Managing this server's agents and rooms is done in the web app for now.
- </p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => void rpc.app.openExternal(server.gatewayUrl)}
- >
- <ExternalLink className="size-4" />
- Open web app
- </Button>
- </div>
+ {!connected && <LoginPanel serverId={serverId} />}
+
+ <div className={`${card} space-y-3`}>
+ <p className="text-sm text-foreground-muted">
+ Managing this server's agents and rooms is done in the web app for now.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void rpc.app.openExternal(server.gatewayUrl)}
+ >
+ <ExternalLink className="size-4" />
+ Open web app
+ </Button>
+ </div>
+ </>
+ )}
</div>
</div>
);
diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
index 0e8106dff..72a7ffc42 100644
--- a/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.canary.ts
@@ -10,3 +10,6 @@ export const ARTIFACT_PREFIX = 'switchdash-canary';
// Keep in sync with RELEASE_REPO_* in ./app-identity.ts (CHOO-1260 flip point).
export const RELEASE_REPO_OWNER = 'sandbox-quantum';
export const RELEASE_REPO_NAME = 'switch';
+
+// Keep in sync with COMPATIBLE_SWITCH_VERSION in ./app-identity.ts.
+export const COMPATIBLE_SWITCH_VERSION = '0.3.0';
diff --git a/dash/apps/switchdash-desktop/src/shared/app-identity.ts b/dash/apps/switchdash-desktop/src/shared/app-identity.ts
index 895d2dce5..13f2c5453 100644
--- a/dash/apps/switchdash-desktop/src/shared/app-identity.ts
+++ b/dash/apps/switchdash-desktop/src/shared/app-identity.ts
@@ -21,3 +21,10 @@ export const IS_CANARY = isCanary;
// app-identity.canary.ts (keep in sync).
export const RELEASE_REPO_OWNER = 'sandbox-quantum';
export const RELEASE_REPO_NAME = 'switch';
+
+// The switch-core release this app build is compatible with. Local-server mode
+// pulls this version's images and bundles this version's standalone compose
+// artifact. Bump it in lockstep with the bundled compose
+// (src/main/core/local-switch-server/resources/standalone-docker-compose.pinned.yml)
+// so a switchdash release pins a known-good switch-core stack.
+export const COMPATIBLE_SWITCH_VERSION = '0.3.0';
diff --git a/dash/apps/switchdash-desktop/src/shared/core/local-switch-server/local-switch-server.ts b/dash/apps/switchdash-desktop/src/shared/core/local-switch-server/local-switch-server.ts
new file mode 100644
index 000000000..ff1551b6b
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/core/local-switch-server/local-switch-server.ts
@@ -0,0 +1,36 @@
+/**
+ * Shared types for local-server mode: switchdash runs a full Switch stack on the
+ * user's machine via `docker compose`, using the standalone compose artifact
+ * bundled into the app (pinned to COMPATIBLE_SWITCH_VERSION). The main process
+ * owns the container lifecycle; the renderer drives it through these types and
+ * subscribes to the status event.
+ */
+
+/** Lifecycle phase of the managed local stack. */
+export type LocalServerPhase = 'stopped' | 'starting' | 'running' | 'stopping' | 'error';
+
+/** Whether Docker is usable on this machine. `daemon-down` means the binary is
+ * installed but the daemon is not reachable (Docker Desktop not running). */
+export type DockerAvailability =
+ | { available: true; version: string }
+ | { available: false; reason: 'not-installed' | 'daemon-down'; detail: string };
+
+/** Snapshot of the managed local server, emitted on every transition. */
+export type LocalServerStatus = {
+ phase: LocalServerPhase;
+ /** The registered server's id once the stack is up, else null. */
+ serverId: string | null;
+ /** The pinned switch-core version this build runs. */
+ version: string;
+ /** Human-readable current step (e.g. "Pulling images…"), or null. */
+ message: string | null;
+ /** Populated only when `phase === 'error'`. */
+ error: string | null;
+};
+
+/** Outcome of a start request. `docker-unavailable` is separated from generic
+ * errors so the UI can point the user at installing / starting Docker. */
+export type StartLocalServerResult =
+ | { kind: 'started'; serverId: string }
+ | { kind: 'docker-unavailable'; reason: 'not-installed' | 'daemon-down'; detail: string }
+ | { kind: 'error'; message: string };
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
index a3b1c1769..ec7561a67 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -20,6 +20,9 @@ export type SwitchServer = {
* `https://switch-api.example.com` — what an agent's `SWITCH_API_ENDPOINT`
* points at, and what an onboarded agent is matched to its server by. */
apiUrl: string;
+ /** True when switchdash runs this server itself (local-server mode). Managed
+ * servers are driven by the lifecycle controls, not the add/edit-server UI. */
+ managed: boolean;
createdAt: string;
updatedAt: string;
};
diff --git a/dash/apps/switchdash-desktop/src/shared/events/localSwitchServerEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/localSwitchServerEvents.ts
new file mode 100644
index 000000000..a152aeacd
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/shared/events/localSwitchServerEvents.ts
@@ -0,0 +1,10 @@
+import type { LocalServerStatus } from '@shared/core/local-switch-server/local-switch-server';
+import { defineEvent } from '@shared/lib/ipc/events';
+
+export const localServerStatusChannel = defineEvent<LocalServerStatus>(
+ 'local-switch-server:status'
+);
+
+/** A line of `docker compose` output during a start, so the UI can show a live
+ * log tail for the (slow) image pull + container startup. */
+export const localServerLogChannel = defineEvent<{ line: string }>('local-switch-server:log');
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db
index 8608034ac..82fa7cb14 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db and b/dash/apps/switchdash-desktop/tooling/fixtures/baseline.db differ
diff --git a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db
index 2dd336c6c..ca15db7e6 100644
Binary files a/dash/apps/switchdash-desktop/tooling/fixtures/empty.db and b/dash/apps/switchdash-desktop/tooling/fixtures/empty.db differ
diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.yml
index 5aa1a0a04..f836b7922 100644
--- a/deploy/local/standalone-docker-compose.yml
+++ b/deploy/local/standalone-docker-compose.yml
@@ -25,7 +25,7 @@ services:
postgres:
image: postgres:16-alpine
ports:
- - "5432:5432"
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${POSTGRES_HOST_PORT:-5432}:5432"
environment:
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
@@ -71,13 +71,13 @@ services:
image: mattermost/mattermost-team-edition:latest
profiles: ["collab"]
ports:
- - "8065:8065"
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${MATTERMOST_HOST_PORT:-8065}:8065"
volumes:
- mmdata:/mattermost/data
environment:
MM_SQLSETTINGS_DRIVERNAME: postgres
MM_SQLSETTINGS_DATASOURCE: postgres://${DB_USER}:${DB_PASSWORD}@postgres:5432/mattermost?sslmode=disable
- MM_SERVICESETTINGS_SITEURL: http://localhost:8065
+ MM_SERVICESETTINGS_SITEURL: http://localhost:${MATTERMOST_HOST_PORT:-8065}
MM_SERVICESETTINGS_ENABLELOCALMODE: "true"
MM_SERVICESETTINGS_ENABLEBOTACCOUNTCREATION: "true"
MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS: "true"
@@ -93,7 +93,7 @@ services:
switch:
image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/switch-core:${SWITCH_VERSION:-latest}
ports:
- - "8000:8000"
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${API_HOST_PORT:-8000}:8000"
environment:
DB_HOST: postgres
DB_PORT: "5432"
@@ -120,7 +120,7 @@ services:
image: ${SWITCH_REGISTRY:-ghcr.io}/${SWITCH_IMAGE_NAMESPACE:-sandbox-quantum}/gateway:${SWITCH_VERSION:-latest}
profiles: ["gateway"]
ports:
- - "3000:3000"
+ - "${SWITCH_BIND_ADDR:-0.0.0.0}:${GATEWAY_HOST_PORT:-3000}:3000"
depends_on:
- switch