Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): detect and update a managed stack on a stale switch-core (CHOO-1736)
Louis Amaudruz7804c8141293
diff --git a/dash/apps/switchdash-desktop/src/main/core/dependencies/agent-update-service.ts b/dash/apps/switchdash-desktop/src/main/core/dependencies/agent-update-service.tsindex 2619671fe..9cbbd07b2 100644--- a/dash/apps/switchdash-desktop/src/main/core/dependencies/agent-update-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/dependencies/agent-update-service.ts@@ -9,20 +9,13 @@ import {type HostDependencyManager,} from '@switchdash/core/deps/runtime';import type { Logger } from '@switchdash/core/lib';-import semver from 'semver';import { events } from '@main/lib/events';+import { isNewerVersion } from '@main/lib/semver';import { agentInstallationStatusUpdatedChannel } from '@shared/events/appEvents';import { toAgentInstallationStatus } from '../providers/agent-payload-builder';import { LatestVersionService } from './latest-version-service';import { getDependencyDescriptor } from './registry';-function isNewerVersion(installed: string, latest: string): boolean {- const a = semver.coerce(installed);- const b = semver.coerce(latest);- if (a === null || b === null) return false;- return semver.gt(b, a);-}-type UpdateInfo = {latestVersion: string | null;updateAvailable: boolean;diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/compose.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/compose.tsindex 6eab0d4d7..9086662b1 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/compose.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/compose.ts@@ -84,3 +84,43 @@ export async function runningServices(host: ServerHost): Promise<string[]> {export async function isStackRunning(host: ServerHost): Promise<boolean> {return (await runningServices(host)).includes('switch');}++/**+ * Image reference of each running container, keyed by compose service name —+ * the ground truth for what the stack is actually running, as opposed to what+ * the `.env` last asked for.+ *+ * Unlike {@link runningServices} this does NOT swallow failures: a caller+ * deciding whether an upgrade or downgrade is in play must be able to tell+ * "nothing is running" from "could not ask".+ */+export async function runningImages(host: ServerHost): Promise<Map<string, string>> {+ const stdout = await runCompose(+ host,+ [...baseArgs(host), 'ps', '--status', 'running', '--format', 'json'],+ 60_000+ );+ const images = new Map<string, string>();+ for (const entry of parseComposePs(stdout)) {+ if (entry.Service && entry.Image) images.set(entry.Service, entry.Image);+ }+ return images;+}++type ComposePsEntry = { Service?: string; Image?: string };++/** Compose emits `ps --format json` as a JSON array on some versions and as+ * one JSON object per line on others; accept both. */+function parseComposePs(stdout: string): ComposePsEntry[] {+ const trimmed = stdout.trim();+ if (!trimmed) return [];+ if (trimmed.startsWith('[')) {+ const parsed: unknown = JSON.parse(trimmed);+ return Array.isArray(parsed) ? (parsed as ComposePsEntry[]) : [];+ }+ return trimmed+ .split('\n')+ .map((line) => line.trim())+ .filter((line) => line.startsWith('{'))+ .map((line) => JSON.parse(line) as ComposePsEntry);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.test.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.test.tsnew file mode 100644index 000000000..70e6a788c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.test.ts@@ -0,0 +1,199 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ServerHost } from './host/types';++const runningImagesMock = vi.hoisted(() => vi.fn());+const warn = vi.hoisted(() => vi.fn());++vi.mock('./compose', () => ({ runningImages: runningImagesMock }));+vi.mock('@main/lib/logger', () => ({ log: { warn, info: vi.fn(), error: vi.fn() } }));++const { classifyVersionDrift, readDeployedVersion, readVersionStatus } =+ await import('./deployed-version');+const { ENV_FILE_NAME } = await import('./constants');++type FakeHostOptions = {+ images?: Map<string, string>;+ imagesError?: Error;+ env?: string | null;+ envError?: Error;+};++/** Minimal {@link ServerHost} — `readDeployedVersion` only ever touches+ * `readFile` and (through the mocked compose module) the host identity. */+function fakeHost(opts: FakeHostOptions) {+ runningImagesMock.mockImplementation(() => {+ if (opts.imagesError) return Promise.reject(opts.imagesError);+ return Promise.resolve(opts.images ?? new Map());+ });+ return {+ label: 'test host',+ readFile: vi.fn((relPath: string) => {+ expect(relPath).toBe(ENV_FILE_NAME);+ if (opts.envError) return Promise.reject(opts.envError);+ return Promise.resolve(opts.env ?? null);+ }),+ } as unknown as ServerHost & { readFile: ReturnType<typeof vi.fn> };+}++const coreImage = (tag: string) =>+ new Map([['switch', `ghcr.io/sandbox-quantum/switch-core:${tag}`]]);++beforeEach(() => {+ vi.clearAllMocks();+});++describe('readDeployedVersion', () => {+ it('prefers the running core container tag', async () => {+ const host = fakeHost({ images: coreImage('0.11.0'), env: 'SWITCH_VERSION=0.3.0\n' });+ expect(await readDeployedVersion(host)).toEqual({+ kind: 'deployed',+ version: '0.11.0',+ source: 'container',+ });+ // The `.env` is only a fallback — the container tag settled it.+ expect(host.readFile).not.toHaveBeenCalled();+ });++ it('falls back to the .env when the stack is stopped', async () => {+ const host = fakeHost({+ images: new Map(),+ env: 'POSTGRES_PASSWORD=x\nSWITCH_VERSION=0.9.1\nSWITCH_BIND_ADDR=127.0.0.1\n',+ });+ expect(await readDeployedVersion(host)).toEqual({+ kind: 'deployed',+ version: '0.9.1',+ source: 'env-file',+ });+ });++ it('reports absent when nothing was ever deployed', async () => {+ expect(await readDeployedVersion(fakeHost({ images: new Map(), env: null }))).toEqual({+ kind: 'absent',+ });+ });++ it('reports unreadable — not absent — when the daemon cannot be asked and there is no .env', async () => {+ const result = await readDeployedVersion(+ fakeHost({ imagesError: new Error('docker daemon not running'), env: null })+ );+ expect(result.kind).toBe('unreadable');+ expect(result).toMatchObject({ reason: expect.stringContaining('docker daemon not running') });+ });++ it('still uses the .env when the daemon cannot be asked', async () => {+ const host = fakeHost({+ imagesError: new Error('connection refused'),+ env: 'SWITCH_VERSION=0.7.2\n',+ });+ expect(await readDeployedVersion(host)).toEqual({+ kind: 'deployed',+ version: '0.7.2',+ source: 'env-file',+ });+ });++ it('reports unreadable when the .env carries no version', async () => {+ const result = await readDeployedVersion(+ fakeHost({ images: new Map(), env: 'POSTGRES_PASSWORD=x\n' })+ );+ expect(result.kind).toBe('unreadable');+ });++ it('ignores a digest-pinned image and an untagged one', async () => {+ const digest = new Map([['switch', 'ghcr.io/sandbox-quantum/switch-core@sha256:abc123']]);+ expect(await readDeployedVersion(fakeHost({ images: digest, env: null }))).toEqual({+ kind: 'absent',+ });+ const untagged = new Map([['switch', 'ghcr.io/sandbox-quantum/switch-core']]);+ expect(await readDeployedVersion(fakeHost({ images: untagged, env: null }))).toEqual({+ kind: 'absent',+ });+ });++ it('is not confused by a registry port in the image reference', async () => {+ const images = new Map([['switch', 'localhost:5000/sandbox-quantum/switch-core:1.4.0']]);+ expect(await readDeployedVersion(fakeHost({ images, env: null }))).toMatchObject({+ version: '1.4.0',+ });+ });++ it('reads the core service, not another service that happens to be up', async () => {+ const images = new Map([+ ['gateway', 'ghcr.io/sandbox-quantum/gateway:0.11.0'],+ ['postgres', 'postgres:16-alpine'],+ ]);+ expect(await readDeployedVersion(fakeHost({ images, env: null }))).toEqual({ kind: 'absent' });+ });++ it('unquotes a quoted .env value', async () => {+ const host = fakeHost({ images: new Map(), env: 'SWITCH_VERSION="0.5.0"\n' });+ expect(await readDeployedVersion(host)).toMatchObject({ version: '0.5.0' });+ });+});++describe('classifyVersionDrift', () => {+ it('is null when the versions match', () => {+ expect(classifyVersionDrift('0.11.0', '0.11.0')).toBeNull();+ expect(classifyVersionDrift('v0.11.0', '0.11.0')).toBeNull();+ });++ it('calls a behind stack an upgrade', () => {+ expect(classifyVersionDrift('0.3.0', '0.11.0')).toEqual({+ deployed: '0.3.0',+ expected: '0.11.0',+ direction: 'upgrade',+ });+ });++ it('calls an ahead stack a downgrade', () => {+ expect(classifyVersionDrift('0.12.0', '0.11.0')).toEqual({+ deployed: '0.12.0',+ expected: '0.11.0',+ direction: 'downgrade',+ });+ });++ it('surfaces an uncomparable pair rather than assuming it is safe', () => {+ expect(classifyVersionDrift('nightly', '0.11.0')).toEqual({+ deployed: 'nightly',+ expected: '0.11.0',+ direction: 'unknown',+ });+ });+});++describe('readVersionStatus', () => {+ it('reports the deployed version and its drift', async () => {+ const host = fakeHost({ images: coreImage('0.3.0'), env: null });+ expect(await readVersionStatus(host, '0.11.0')).toEqual({+ deployedVersion: '0.3.0',+ drift: { deployed: '0.3.0', expected: '0.11.0', direction: 'upgrade' },+ });+ });++ it('reports no drift for a matching stack', async () => {+ const host = fakeHost({ images: coreImage('0.11.0'), env: null });+ expect(await readVersionStatus(host, '0.11.0')).toEqual({+ deployedVersion: '0.11.0',+ drift: null,+ });+ });++ it('stays quiet but warns when the host cannot be read', async () => {+ const host = fakeHost({ imagesError: new Error('ssh: connection closed'), env: null });+ expect(await readVersionStatus(host, '0.11.0')).toEqual({+ deployedVersion: null,+ drift: null,+ });+ expect(warn).toHaveBeenCalledOnce();+ });++ it('reports nothing for a host with no stack', async () => {+ const host = fakeHost({ images: new Map(), env: null });+ expect(await readVersionStatus(host, '0.11.0')).toEqual({+ deployedVersion: null,+ drift: null,+ });+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.tsnew file mode 100644index 000000000..473f74103--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/deployed-version.ts@@ -0,0 +1,148 @@+import { log } from '@main/lib/logger';+import { compareVersions } from '@main/lib/semver';+import type {+ SwitchVersionDrift,+ SwitchVersionDriftDirection,+} from '@shared/core/managed-switch-server/managed-switch-server';+import { runningImages } from './compose';+import { ENV_FILE_NAME } from './constants';+import type { ServerHost } from './host/types';++/**+ * What switch-core version a managed stack is actually deployed at.+ *+ * The `COMPATIBLE_SWITCH_VERSION` pin only says what THIS build of switchdash+ * wants; it is written into the `.env` at every start. Answering+ * "did the app's pin move underneath a stack that is already up?" needs the+ * other side of the comparison, read back off the host.+ */++/** The core service whose image tag defines the stack's version. */+const CORE_SERVICE = 'switch';++export type DeployedVersion =+ /** Read successfully. `source` records how, since the two differ in strength:+ * `container` is what is running right now; `env-file` is what the last start+ * asked for, which is the only signal available while the stack is stopped. */+ | { kind: 'deployed'; version: string; source: 'container' | 'env-file' }+ /** Nothing has ever been deployed here — no running core container and no+ * `.env`. A first start, not a drift. */+ | { kind: 'absent' }+ /** Neither source could be read. Distinct from `absent` on purpose: an+ * unreachable daemon must not be mistaken for an empty host. */+ | { kind: 'unreadable'; reason: string };++/**+ * Read the switch-core version deployed on `host`.+ *+ * Prefers the running core container's image tag — the only ground truth for+ * what is executing — and falls back to `SWITCH_VERSION` in the on-host `.env`,+ * which still matters when the stack is stopped: the data volumes survive, so a+ * stopped stack's last deployed version is what the database has migrated to.+ */+export async function readDeployedVersion(host: ServerHost): Promise<DeployedVersion> {+ const failures: string[] = [];++ try {+ const image = (await runningImages(host)).get(CORE_SERVICE);+ const tag = image ? imageTag(image) : null;+ if (tag) return { kind: 'deployed', version: tag, source: 'container' };+ } catch (error) {+ failures.push(`container image: ${errorText(error)}`);+ }++ try {+ const env = await host.readFile(ENV_FILE_NAME);+ if (env === null) {+ // No `.env` and no running container: nothing was ever deployed here.+ if (failures.length === 0) return { kind: 'absent' };+ } else {+ const version = envVersion(env);+ if (version) return { kind: 'deployed', version, source: 'env-file' };+ failures.push(`${ENV_FILE_NAME}: no SWITCH_VERSION entry`);+ }+ } catch (error) {+ failures.push(`${ENV_FILE_NAME}: ${errorText(error)}`);+ }++ if (failures.length === 0) return { kind: 'absent' };+ return { kind: 'unreadable', reason: failures.join('; ') };+}++/**+ * Compare a deployed version against this build's pin.+ *+ * Returns null when they match — the common case, and the only one that needs+ * no user-facing surface.+ */+export function classifyVersionDrift(+ deployed: string,+ expected: string+): SwitchVersionDrift | null {+ if (deployed === expected) return null;+ const order = compareVersions(deployed, expected);+ if (order === 0) return null;+ const direction: SwitchVersionDriftDirection =+ order === null ? 'unknown' : order < 0 ? 'upgrade' : 'downgrade';+ return { deployed, expected, direction };+}++/**+ * The `deployedVersion` / `drift` half of a managed server's status, read off+ * `host`. Shared by the local and remote supervisors so both surface the same+ * thing at boot.+ *+ * A host we cannot read reports no drift: the caller is a status reconcile, and+ * inventing a drift banner out of a failed probe would be worse than staying+ * quiet. The start path guards separately (see `startStack`), so an unreadable+ * host here cannot let a downgrade through.+ */+export async function readVersionStatus(+ host: ServerHost,+ expected: string+): Promise<{ deployedVersion: string | null; drift: SwitchVersionDrift | null }> {+ const deployed = await readDeployedVersion(host);+ if (deployed.kind === 'unreadable') {+ log.warn(+ `managed-switch-server: could not read the deployed switch-core version on ${host.label}`,+ { reason: deployed.reason }+ );+ return { deployedVersion: null, drift: null };+ }+ if (deployed.kind === 'absent') return { deployedVersion: null, drift: null };+ return {+ deployedVersion: deployed.version,+ drift: classifyVersionDrift(deployed.version, expected),+ };+}++/** The tag of a `[registry[:port]/]repo[:tag]` image reference, or null when it+ * carries no tag (an implicit `latest`, or a `@sha256:` digest pin — neither+ * names a version we can compare). */+function imageTag(image: string): string | null {+ const lastSlash = image.lastIndexOf('/');+ const name = lastSlash === -1 ? image : image.slice(lastSlash + 1);+ if (name.includes('@')) return null;+ const colon = name.lastIndexOf(':');+ if (colon === -1) return null;+ const tag = name.slice(colon + 1).trim();+ return tag.length > 0 ? tag : null;+}++/** `SWITCH_VERSION` from a generated `.env`, unquoted, or null when absent. */+function envVersion(env: string): string | null {+ for (const raw of env.split('\n')) {+ const line = raw.trim();+ if (!line.startsWith('SWITCH_VERSION=')) continue;+ const value = line+ .slice('SWITCH_VERSION='.length)+ .trim()+ .replace(/^["']|["']$/g, '');+ if (value.length > 0) return value;+ }+ return null;+}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/local-host.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/local-host.tsindex 078d2627e..df68ac857 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/local-host.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/local-host.ts@@ -1,5 +1,5 @@import { spawn } from 'node:child_process';-import { chmod, mkdir, writeFile } from 'node:fs/promises';+import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';import { dirname, join } from 'node:path';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';@@ -35,6 +35,15 @@ export class LocalServerHost implements ServerHost {if (mode !== undefined) await chmod(path, mode);}+ async readFile(relPath: string): Promise<string | null> {+ try {+ return await readFile(join(this.workingDir, relPath), 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;+ throw error;+ }+ }+streamCommand(command: string,args: string[],diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/remote-host.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/remote-host.tsindex fc80ce837..925b63dbb 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/remote-host.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/remote-host.ts@@ -4,6 +4,7 @@ import {} from '@main/core/execution-context/ssh-execution-context';import type { IExecutionContext } from '@main/core/execution-context/types';import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';+import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';@@ -73,6 +74,18 @@ export class RemoteServerHost implements ServerHost {}}+ async readFile(relPath: string): Promise<string | null> {+ try {+ const { content } = await this.fs.read(relPath);+ return content;+ } catch (error) {+ if (error instanceof FileSystemError && error.code === FileSystemErrorCodes.NOT_FOUND) {+ return null;+ }+ throw error;+ }+ }+streamCommand(command: string,args: string[],diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/types.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/types.tsindex d27688cb5..6785d69f6 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/types.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/host/types.ts@@ -57,6 +57,11 @@ export interface ServerHost {* when provided. */writeFile(relPath: string, content: string, mode?: number): Promise<void>;+ /** Read `relPath` under {@link workingDir} as UTF-8, or null when the file+ * does not exist. Any other failure (permissions, transport) throws — an+ * unreadable file is not the same as an absent one. */+ readFile(relPath: string): Promise<string | null>;+/*** Run a command on the host streaming merged stdout+stderr line-by-line to* `onLine`, rooted at {@link workingDir}. Used for the slow `compose up`diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.tsindex b41443d5d..d5aac8bf8 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/local-server-service.ts@@ -3,10 +3,11 @@ import { getManagedServer } from '@main/core/switch-servers/servers-store';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { COMPATIBLE_SWITCH_VERSION } from '@shared/app-identity';-import type {- DockerAvailability,- LocalServerStatus,- StartLocalServerResult,+import {+ type DockerAvailability,+ type LocalServerStatus,+ type StartLocalServerResult,+ switchVersionDowngradeMessage,} from '@shared/core/managed-switch-server/managed-switch-server';import {localServerLogChannel,@@ -14,6 +15,7 @@ import {} from '@shared/events/localSwitchServerEvents';import { isStackRunning } from './compose';import { LOCAL_SERVER_NAME } from './constants';+import { readVersionStatus } from './deployed-version';import { LocalServerHost } from './host/local-host';import type { ServerHost } from './host/types';import { resetStack, startStack, stopStack } from './pipeline';@@ -33,6 +35,8 @@ class LocalServerService {phase: 'stopped',serverId: null,version: COMPATIBLE_SWITCH_VERSION,+ deployedVersion: null,+ drift: null,message: null,error: null,};@@ -54,15 +58,26 @@ class LocalServerService {}/** Reconcile status at boot so a stack that survived the last quit shows as- * running without the user re-starting it. */+ * running without the user re-starting it, and so an app update that moved+ * the switch-core pin underneath it surfaces as drift instead of leaving the+ * user on a stale core indefinitely (CHOO-1736).+ *+ * The drift probe also runs for a stopped stack: its data volumes still hold+ * whatever schema the last version migrated to, which is exactly what makes a+ * downgrade unsafe. */async initialize(): Promise<void> {+ const host: ServerHost = new LocalServerHost();try {const managed = await getManagedServer();- if (managed && (await isStackRunning(new LocalServerHost()))) {+ if (!managed) return;+ if (await isStackRunning(host)) {this.setStatus({ phase: 'running', serverId: managed.id, message: null, error: null });}+ this.setStatus(await readVersionStatus(host, COMPATIBLE_SWITCH_VERSION));} catch (error) {log.warn('local-switch-server: boot status reconcile failed', { error });+ } finally {+ host.dispose();}}@@ -85,10 +100,27 @@ class LocalServerService {});if (result.kind === 'docker-unavailable') {this.setStatus({ phase: 'error', error: result.detail });+ } else if (result.kind === 'version-downgrade') {+ this.setStatus({+ phase: 'error',+ message: null,+ error: switchVersionDowngradeMessage(result.deployed, result.expected),+ deployedVersion: result.deployed,+ drift: { deployed: result.deployed, expected: result.expected, direction: 'downgrade' },+ });} else if (result.kind === 'error') {this.setStatus({ phase: 'error', error: result.message });} else {- this.setStatus({ phase: 'running', serverId: result.serverId, message: null, error: null });+ // The pipeline just wrote this build's pin and converged the containers+ // onto it, so any drift the boot probe found is now resolved.+ this.setStatus({+ phase: 'running',+ serverId: result.serverId,+ message: null,+ error: null,+ deployedVersion: COMPATIBLE_SWITCH_VERSION,+ drift: null,+ });}return result;} catch (error) {diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.test.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.test.tsnew file mode 100644index 000000000..9774b172c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.test.ts@@ -0,0 +1,168 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as AppIdentity from '@shared/app-identity';+import type * as DeployedVersion from './deployed-version';+import type { ServerHost } from './host/types';++/**+ * Covers the downgrade guard only (CHOO-1736). The rest of `startStack` is an+ * orchestration of already-tested pieces; what matters here is that a stack+ * ahead of this build is refused BEFORE anything on the host is touched.+ */++const readDeployedVersionMock = vi.hoisted(() => vi.fn());+const composeUpMock = vi.hoisted(() => vi.fn(() => Promise.resolve()));+const waitForHealthMock = vi.hoisted(() => vi.fn(() => Promise.resolve(true)));+const logError = vi.hoisted(() => vi.fn());+const logWarn = vi.hoisted(() => vi.fn());++// Pin the build's expected version so the guard's arithmetic is not coupled to+// whatever the real pin happens to be.+vi.mock('@shared/app-identity', async (importOriginal) => ({+ ...(await importOriginal<typeof AppIdentity>()),+ COMPATIBLE_SWITCH_VERSION: '0.11.0',+}));+vi.mock('@main/lib/logger', () => ({+ log: { error: logError, warn: logWarn, info: vi.fn() },+}));+vi.mock('./deployed-version', async (importOriginal) => ({+ ...(await importOriginal<typeof DeployedVersion>()),+ readDeployedVersion: readDeployedVersionMock,+}));+vi.mock('./compose', () => ({+ composeUp: composeUpMock,+ composeDown: vi.fn(() => Promise.resolve()),+ runningImages: vi.fn(),+ isStackRunning: vi.fn(),+}));+vi.mock('./health', () => ({ waitForHealth: waitForHealthMock }));+vi.mock('./bundled-compose', () => ({ bundledComposeYaml: () => 'services: {}' }));+vi.mock('./secrets', () => ({+ loadOrCreateSecrets: () => Promise.resolve({ gatewayAdminPassword: 'pw' }),+ clearSecrets: vi.fn(),+}));+vi.mock('./ports', () => ({+ resolvePorts: () =>+ Promise.resolve({ gateway: 3300, api: 8000, mattermost: 8065, postgres: 5432 }),+ clearPorts: vi.fn(),+}));+vi.mock('./env-file', () => ({ buildEnvFile: () => 'SWITCH_VERSION=0.11.0\n' }));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),+ setActiveServerId: vi.fn(),+}));+vi.mock('@main/core/switch-servers/auth', () => ({+ passwordLogin: () => Promise.resolve({ success: true }),+}));+vi.mock('@main/core/agents/resolve-servers', () => ({ resolveAgentServers: vi.fn() }));++const { startStack } = await import('./pipeline');+const { ENV_FILE_NAME } = await import('./constants');++function options() {+ const writeFile = vi.fn(() => Promise.resolve());+ const host = {+ label: 'this computer',+ writeFile,+ detectDocker: () => Promise.resolve({ available: true, version: '27.0.0' }),+ ensureGhcrLogin: vi.fn(() => Promise.resolve()),+ establishNetworking: vi.fn(() => Promise.resolve()),+ };+ return {+ writeFile,+ opts: {+ host: host as unknown as ServerHost,+ ref: { kind: 'local' as const },+ serverName: 'Local',+ onMessage: vi.fn(),+ onLog: vi.fn(),+ signal: new AbortController().signal,+ },+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('startStack version guard', () => {+ it('refuses to start a stack that is ahead of this build', async () => {+ readDeployedVersionMock.mockResolvedValue({+ kind: 'deployed',+ version: '0.12.0',+ source: 'container',+ });+ const { opts, writeFile } = options();++ expect(await startStack(opts)).toEqual({+ kind: 'version-downgrade',+ deployed: '0.12.0',+ expected: '0.11.0',+ });+ // Nothing on the host may be touched: the existing `.env` still names the+ // version the stack was last started with, so the refusal is recoverable+ // just by reinstalling the newer switchdash.+ expect(writeFile).not.toHaveBeenCalled();+ expect(composeUpMock).not.toHaveBeenCalled();+ expect(logError).toHaveBeenCalledOnce();+ });++ it('starts a stack that is behind this build, rewriting the .env', async () => {+ readDeployedVersionMock.mockResolvedValue({+ kind: 'deployed',+ version: '0.3.0',+ source: 'container',+ });+ const { opts, writeFile } = options();++ expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(writeFile).toHaveBeenCalledWith(ENV_FILE_NAME, expect.any(String), 0o600);+ expect(composeUpMock).toHaveBeenCalledOnce();+ });++ it('starts a fresh host with nothing deployed', async () => {+ readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });+ const { opts } = options();+ expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ });++ it('starts a matching stack (the plain restart path)', async () => {+ readDeployedVersionMock.mockResolvedValue({+ kind: 'deployed',+ version: '0.11.0',+ source: 'container',+ });+ const { opts } = options();+ expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ });++ it('proceeds with a warning when the deployed version cannot be read', async () => {+ readDeployedVersionMock.mockResolvedValue({ kind: 'unreadable', reason: 'daemon down' });+ const { opts } = options();++ expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ // Degraded, but disclosed — a transient probe failure must not make the app+ // unstartable.+ expect(logWarn).toHaveBeenCalledOnce();+ });++ it('allows a version it cannot compare, since a downgrade is not proven', async () => {+ readDeployedVersionMock.mockResolvedValue({+ kind: 'deployed',+ version: 'nightly',+ source: 'container',+ });+ const { opts } = options();+ expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ });++ it('refuses before authenticating to the registry, so nothing off-host happens either', async () => {+ readDeployedVersionMock.mockResolvedValue({+ kind: 'deployed',+ version: '0.12.0',+ source: 'env-file',+ });+ const { opts } = options();+ await startStack(opts);+ expect(opts.host.ensureGhcrLogin).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.tsindex 6b0495982..df352b9ff 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -13,6 +13,7 @@ import {GHCR_REGISTRY,LOCAL_SERVER_ADMIN_EMAIL,} from './constants';+import { classifyVersionDrift, readDeployedVersion } from './deployed-version';import { buildEnvFile } from './env-file';import { apiUrlFor, gatewayUrlFor } from './free-port';import { waitForHealth } from './health';@@ -42,10 +43,50 @@ export type StartStackOptions = {};/**- * Full start pipeline: detect Docker → GHCR login → materialise compose + `.env`- * → `compose up` → establish networking → health-gate → register + activate →- * silent admin sign-in → reconcile agent servers. Returns without registering- * anything if Docker is unavailable or the stack never turns healthy.+ * Refuse to point an existing stack at an OLDER switch-core than it already+ * runs. switch-core migrates its database forward at startup and Alembic has no+ * downgrade path, so rolling switchdash back would hand an old core a schema it+ * cannot read — silent, and only discovered once the data is already stuck.+ *+ * Runs before anything is written: the `.env` still names the version the stack+ * was last started with, so a refused start leaves the host exactly as it was+ * and re-installing the newer switchdash is enough to recover.+ *+ * A host whose deployed version cannot be read is allowed through with a+ * warning rather than blocked — a transient daemon or SSH failure must not make+ * the app unstartable — so this is a guard against the known-bad case, not a+ * proof of safety.+ */+async function refuseDowngrade(+ host: ServerHost+): Promise<{ kind: 'version-downgrade'; deployed: string; expected: string } | null> {+ const deployed = await readDeployedVersion(host);+ if (deployed.kind === 'absent') return null;+ if (deployed.kind === 'unreadable') {+ log.warn(`managed-switch-server: starting ${host.label} without a deployed-version check`, {+ reason: deployed.reason,+ });+ return null;+ }+ const drift = classifyVersionDrift(deployed.version, COMPATIBLE_SWITCH_VERSION);+ if (drift?.direction !== 'downgrade') return null;+ log.error(+ `managed-switch-server: refusing to downgrade ${host.label} from switch-core ${drift.deployed} to ${drift.expected}`+ );+ return { kind: 'version-downgrade', deployed: drift.deployed, expected: drift.expected };+}++/**+ * Full start pipeline: detect Docker → refuse a downgrade → GHCR login →+ * materialise compose + `.env` → `compose up` → establish networking →+ * health-gate → register + activate → silent admin sign-in → reconcile agent+ * servers. Returns without registering anything if Docker is unavailable, the+ * stack is newer than this build, or it never turns healthy.+ *+ * Doubles as the update path: the `.env` and compose file are re-materialised+ * from this build every time, so `compose up -d` on an already-running stack+ * re-pulls the newly pinned tags and recreates only the changed containers,+ * leaving the data volumes in place for switch-core to migrate forward.*/export async function startStack(opts: StartStackOptions): Promise<StartLocalServerResult> {const { host, ref, serverName, onMessage, onLog, signal } = opts;@@ -55,6 +96,10 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSerreturn { kind: 'docker-unavailable', reason: docker.reason, detail: docker.detail };}+ onMessage('Checking the deployed version…');+ const downgrade = await refuseDowngrade(host);+ if (downgrade) return downgrade;+onMessage('Authenticating to image registry…');await host.ensureGhcrLogin();diff --git a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.tsindex f4adf68cb..dd2cc71b5 100644--- a/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/managed-switch-server/remote-server-service.ts@@ -8,9 +8,10 @@ import {import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import { COMPATIBLE_SWITCH_VERSION } from '@shared/app-identity';-import type {- DockerAvailability,- StartLocalServerResult,+import {+ type DockerAvailability,+ type StartLocalServerResult,+ switchVersionDowngradeMessage,} from '@shared/core/managed-switch-server/managed-switch-server';import {type RemoteServerStatus,@@ -18,6 +19,7 @@ import {remoteServerStatusChannel,} from '@shared/events/remoteSwitchServerEvents';import { isStackRunning } from './compose';+import { readVersionStatus } from './deployed-version';import { createRemoteServerHost, type RemoteServerHost } from './host/remote-host';import { resetStack, startStack, stopStack } from './pipeline';import { readPersistedPorts } from './ports';@@ -28,6 +30,8 @@ function initialStatus(sshHost: string): RemoteServerStatus {phase: 'stopped',serverId: null,version: COMPATIBLE_SWITCH_VERSION,+ deployedVersion: null,+ drift: null,message: null,error: null,};@@ -104,29 +108,36 @@ class RemoteServerService {/** Adopt an already-running remote stack: re-open its forward and mark it* running. Skipped while the host is blocked — the reachability manager will- * call back through {@link onHostReachable} when it recovers. */+ * call back through {@link onHostReachable} when it recovers.+ *+ * Also records how the host's deployed switch-core compares to this build's+ * pin, so an app update that moved the pin surfaces as drift rather than+ * leaving the host on a stale core (CHOO-1736). That check runs even when the+ * stack is down: its data volumes still hold the schema the last version+ * migrated to, which is what makes a downgrade unsafe. */private async reconcileHost(sshHost: string, serverId: string): Promise<void> {if (hostReachabilityService.isBlocked(sshHost)) return;let host: RemoteServerHost | null = null;+ let adopted = false;try {host = await createRemoteServerHost(sshHost);- if (!(await isStackRunning(host))) {- host.dispose();- return;- }- const ports = await readPersistedPorts(host);- if (!ports) {+ if (await isStackRunning(host)) {+ const ports = await readPersistedPorts(host);+ if (ports) {+ await host.establishNetworking(ports);+ this.hosts.set(sshHost, host);+ adopted = true;+ this.setStatus(sshHost, { phase: 'running', serverId });+ }// Running but we don't know its ports — leave it stopped; the user can// restart to re-derive them rather than forward to the wrong ports.- host.dispose();- return;}- await host.establishNetworking(ports);- this.hosts.set(sshHost, host);- this.setStatus(sshHost, { phase: 'running', serverId });+ this.setStatus(sshHost, await readVersionStatus(host, COMPATIBLE_SWITCH_VERSION));} catch (error) {- host?.dispose();log.warn(`remote-switch-server: boot reconcile failed for ${sshHost}`, { error });+ } finally {+ // The adopted host owns the live port-forward; anything else is throwaway.+ if (!adopted) host?.dispose();}}@@ -161,17 +172,30 @@ class RemoteServerService {if (result.kind === 'docker-unavailable') {this.setStatus(sshHost, { phase: 'error', error: result.detail });host.dispose();+ } else if (result.kind === 'version-downgrade') {+ this.setStatus(sshHost, {+ phase: 'error',+ message: null,+ error: switchVersionDowngradeMessage(result.deployed, result.expected),+ deployedVersion: result.deployed,+ drift: { deployed: result.deployed, expected: result.expected, direction: 'downgrade' },+ });+ host.dispose();} else if (result.kind === 'error') {this.setStatus(sshHost, { phase: 'error', error: result.message });host.dispose();} else {// Keep the host alive — it owns the port-forward.this.hosts.set(sshHost, host);+ // The pipeline just converged the containers onto this build's pin, so+ // any drift the boot probe found is now resolved.this.setStatus(sshHost, {phase: 'running',serverId: result.serverId,message: null,error: null,+ deployedVersion: COMPATIBLE_SWITCH_VERSION,+ drift: null,});}return result;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.tsindex 26474ccf2..48ecc777a 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/remote-switch-setup.ts@@ -3,10 +3,11 @@ import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';import { log } from '@main/lib/logger';+import { isNewerVersion } from '@main/lib/semver';import { getPlugin, listPlugins } from '../providers/plugin-registry';import { cliRulesFor, type SwitchSetupCliRules } from './switch-setup-cli-dialect';import type { SwitchSetupResult, SwitchSetupStatus } from './switch-setup-service';-import { isNewerVersion, marketplaceMatchesSource } from './switch-setup-service';+import { marketplaceMatchesSource } from './switch-setup-service';const EXEC_TIMEOUT_MS = 120_000;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.tsindex 80d7a04ae..836abdf7f 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-setup/switch-setup-service.ts@@ -1,9 +1,9 @@import { readFile } from 'node:fs/promises';import { join } from 'node:path';import { resolveCommandPath } from '@switchdash/core/deps/runtime';-import semver from 'semver';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';import { log } from '@main/lib/logger';+import { isNewerVersion } from '@main/lib/semver';import { READ_PACKAGES_SCOPE } from '@shared/core/npm-registry';import { getPlugin, listPlugins } from '../providers/plugin-registry';import { probeLocalGhAuth } from './local-gh-auth';@@ -98,14 +98,6 @@ function unsupported(agentId: string): SwitchSetupStatus {};}-/** Whether `latest` is a newer semver than `installed`; false when either is unparseable. */-export function isNewerVersion(installed: string, latest: string): boolean {- const a = semver.coerce(installed);- const b = semver.coerce(latest);- if (a === null || b === null) return false;- return semver.gt(b, a);-}-/*** Drives an agent's plugin-marketplace CLI (`<bin> plugin ...`,* `<bin> plugin marketplace ...`) to manage that agent's Switch connectordiff --git a/dash/apps/switchdash-desktop/src/main/lib/semver.test.ts b/dash/apps/switchdash-desktop/src/main/lib/semver.test.tsnew file mode 100644index 000000000..0c06cf5c6--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/lib/semver.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';+import { compareVersions, isNewerVersion } from './semver';++describe('compareVersions', () => {+ it('orders releases', () => {+ expect(compareVersions('0.3.0', '0.11.0')).toBe(-1);+ expect(compareVersions('0.11.0', '0.3.0')).toBe(1);+ expect(compareVersions('0.11.0', '0.11.0')).toBe(0);+ });++ it('coerces the decorations real version strings carry', () => {+ expect(compareVersions('v1.2.3', '1.2.3')).toBe(0);+ expect(compareVersions('switch-core 1.2.3', 'v1.2.4')).toBe(-1);+ });++ it('compares minor and patch numerically, not lexically', () => {+ expect(compareVersions('0.9.0', '0.10.0')).toBe(-1);+ expect(compareVersions('1.0.9', '1.0.10')).toBe(-1);+ });++ it('returns null when either side is not a version', () => {+ expect(compareVersions('latest', '1.2.3')).toBeNull();+ expect(compareVersions('1.2.3', 'main')).toBeNull();+ expect(compareVersions('', '1.2.3')).toBeNull();+ });+});++describe('isNewerVersion', () => {+ it('is true only when the candidate is strictly newer', () => {+ expect(isNewerVersion('1.2.3', '1.2.4')).toBe(true);+ expect(isNewerVersion('1.2.3', '1.2.3')).toBe(false);+ expect(isNewerVersion('1.2.4', '1.2.3')).toBe(false);+ });++ it('keeps what it has when the pair is not comparable', () => {+ expect(isNewerVersion('latest', '1.2.3')).toBe(false);+ expect(isNewerVersion('1.2.3', 'latest')).toBe(false);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/lib/semver.ts b/dash/apps/switchdash-desktop/src/main/lib/semver.tsnew file mode 100644index 000000000..3f6d69638--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/lib/semver.ts@@ -0,0 +1,29 @@+import semver from 'semver';++/**+ * Version comparison for the loosely-formatted version strings this app deals+ * in — CLI `--version` output, container image tags, GitHub release names.+ * Both sides are coerced first, so `v1.2.3`, `1.2.3` and `switch-core 1.2.3`+ * all compare as the same release.+ */++/**+ * Three-way compare of two versions: negative when `a` is older, `0` when they+ * are the same release, positive when `a` is newer.+ *+ * Returns `null` when either side cannot be coerced to a semver, so callers can+ * tell "not comparable" apart from "equal" instead of silently treating an+ * unparseable version as a match.+ */+export function compareVersions(a: string, b: string): -1 | 0 | 1 | null {+ const left = semver.coerce(a);+ const right = semver.coerce(b);+ if (left === null || right === null) return null;+ return semver.compare(left, right);+}++/** Whether `latest` is a strictly newer release than `installed`. An+ * uncomparable pair counts as "not newer" — the caller keeps what it has. */+export function isNewerVersion(installed: string, latest: string): boolean {+ return compareVersions(installed, latest) === -1;+}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.tsxindex bfc501d60..3a88bbafb 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx@@ -15,6 +15,7 @@ import {} from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';import { localServerStore } from './local-server-store';+import { VersionDriftNotice } from './VersionDriftNotice';const card = 'rounded-lg border border-border bg-card p-4';@@ -32,6 +33,13 @@ export const LocalServerControls = observer(function LocalServerControls() {const transitioning = store.isTransitioning;const dockerUnavailable = store.docker && !store.docker.available ? store.docker : null;+ const drift = store.drift;+ // Report the version the stack is actually on, not the one this build wants —+ // they diverge exactly when the drift notice below has something to say.+ const runningVersion = store.status?.deployedVersion ?? store.status?.version ?? '';+ // A stack ahead of this build must not be started at all: doing so would point+ // it at a core older than its database has migrated to (CHOO-1736).+ const downgradeBlocked = drift?.direction === 'downgrade';return (<div className={`${card} space-y-4`}>@@ -39,13 +47,18 @@ export const LocalServerControls = observer(function LocalServerControls() {<div className="space-y-1"><h3 className="text-sm font-medium text-foreground">Managed server</h3><p className="text-xs text-foreground-muted">- Runs the full Switch stack on this computer with Docker (switch-core{' '}- {store.status?.version ?? ''}).+ Runs the full Switch stack on this computer with Docker (switch-core {runningVersion}).</p></div><PhaseBadge /></div>+ <VersionDriftNotice+ drift={drift}+ disabled={transitioning}+ onRestart={() => void store.start()}+ />+{store.message && transitioning && (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -84,9 +97,13 @@ export const LocalServerControls = observer(function LocalServerControls() {Stop</Button>) : (- <Button size="sm" disabled={transitioning} onClick={() => void store.start()}>+ <Button+ size="sm"+ disabled={transitioning || downgradeBlocked}+ onClick={() => void store.start()}+ ><Play className="size-4" />- {store.phase === 'error' ? 'Retry' : 'Start'}+ {store.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}</Button>)}</div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsxindex 671f4e464..238b96918 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx@@ -15,6 +15,7 @@ import {} from '@renderer/lib/ui/dialog';import { Spinner } from '@renderer/lib/ui/spinner';import { remoteServerStore } from './remote-server-store';+import { VersionDriftNotice } from './VersionDriftNotice';const card = 'rounded-lg border border-border bg-card p-4';@@ -48,6 +49,13 @@ export const RemoteServerControls = observer(function RemoteServerControls({const running = store.isRunning(sshHost);const docker = store.dockerFor(sshHost);const dockerUnavailable = docker && !docker.available ? docker : null;+ const drift = store.driftFor(sshHost);+ // Report the version the host is actually on, not the one this build wants —+ // they diverge exactly when the drift notice below has something to say.+ const runningVersion = status.deployedVersion ?? status.version;+ // A stack ahead of this build must not be started at all: doing so would point+ // it at a core older than its database has migrated to (CHOO-1736).+ const downgradeBlocked = drift?.direction === 'downgrade';return (<div className={`${card} space-y-4`}>@@ -55,12 +63,19 @@ export const RemoteServerControls = observer(function RemoteServerControls({<div className="space-y-1"><h3 className="text-sm font-medium text-foreground">Managed server</h3><p className="text-xs text-foreground-muted">- Runs the full Switch stack in Docker on {sshHost}, bridged to this computer over SSH.+ Runs the full Switch stack in Docker on {sshHost}, bridged to this computer over SSH+ {runningVersion ? ` (switch-core ${runningVersion})` : ''}.</p></div><PhaseBadge sshHost={sshHost} /></div>+ <VersionDriftNotice+ drift={drift}+ disabled={transitioning}+ onRestart={() => void store.start(sshHost, name)}+ />+{status.message && transitioning && (<div className="flex items-center gap-2 text-sm text-foreground-muted"><Spinner className="size-3.5" />@@ -101,11 +116,11 @@ export const RemoteServerControls = observer(function RemoteServerControls({) : (<Buttonsize="sm"- disabled={transitioning}+ disabled={transitioning || downgradeBlocked}onClick={() => void store.start(sshHost, name)}><Play className="size-4" />- {status.phase === 'error' ? 'Retry' : 'Start'}+ {status.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}</Button>)}</div>diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsxnew file mode 100644index 000000000..d712d663b--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsx@@ -0,0 +1,66 @@+import { ArrowUpCircle, RefreshCw, TriangleAlert } from 'lucide-react';+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';+import { Button } from '@renderer/lib/ui/button';+import {+ type SwitchVersionDrift,+ switchVersionDowngradeMessage,+} from '@shared/core/managed-switch-server/managed-switch-server';++/**+ * Surfaces a managed stack whose switch-core version no longer matches the one+ * this build of switchdash pins (CHOO-1736).+ *+ * Updating the app moves the pin, but a stack that is already up is never+ * re-provisioned — without this the user silently keeps running the old core.+ * Restarting re-runs the start pipeline, which rewrites the `.env` at the new+ * pin and lets `compose up -d` recreate the changed containers.+ *+ * The downgrade direction gets no action, only an explanation: the stack's+ * database has already migrated forward and switch-core cannot roll back, so+ * there is nothing safe for a button to do.+ */+export function VersionDriftNotice({+ drift,+ disabled,+ onRestart,+}: {+ drift: SwitchVersionDrift | null;+ /** True while a lifecycle operation is in flight (or the host is unreachable). */+ disabled: boolean;+ onRestart: () => void;+}) {+ if (!drift) return null;++ if (drift.direction === 'downgrade') {+ return (+ <Alert variant="destructive">+ <TriangleAlert className="size-4" />+ <AlertTitle>This server is newer than switchdash</AlertTitle>+ <AlertDescription>+ {switchVersionDowngradeMessage(drift.deployed, drift.expected)}+ </AlertDescription>+ </Alert>+ );+ }++ const unknown = drift.direction === 'unknown';+ return (+ <Alert variant="warning">+ {unknown ? <TriangleAlert className="size-4" /> : <ArrowUpCircle className="size-4" />}+ <AlertTitle>+ {unknown ? 'Version mismatch' : `switch-core ${drift.expected} is available`}+ </AlertTitle>+ <AlertDescription>+ {unknown+ ? `This server runs switch-core ${drift.deployed} and this version of switchdash expects ${drift.expected}. Those cannot be compared automatically — restart only if you know ${drift.expected} is not older.`+ : `This server still runs switch-core ${drift.deployed}. Restart it to pull ${drift.expected} and migrate its data. Its rooms and messages are kept.`}+ </AlertDescription>+ <AlertAction>+ <Button size="sm" disabled={disabled} onClick={onRestart}>+ <RefreshCw className="size-4" />+ Restart to update+ </Button>+ </AlertAction>+ </Alert>+ );+}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.tsindex 6f0e97a9b..93c552e33 100644--- 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@@ -4,6 +4,7 @@ import { events, rpc } from '@renderer/lib/ipc';import type {DockerAvailability,LocalServerStatus,+ SwitchVersionDrift,} from '@shared/core/managed-switch-server/managed-switch-server';import {localServerLogChannel,@@ -48,6 +49,11 @@ export class LocalServerStore {return this.phase === 'running';}+ /** Set when the stack's switch-core differs from the version this build pins. */+ get drift(): SwitchVersionDrift | null {+ return this.status?.drift ?? null;+ }+get isTransitioning(): boolean {return this.busy || this.phase === 'starting' || this.phase === 'stopping';}@@ -111,6 +117,10 @@ export class LocalServerStore {this.docker = { available: false, reason: result.reason, detail: result.detail };this.error = result.detail;});+ } else if (result.kind === 'version-downgrade') {+ // The refusal is already on the pushed status as `drift`, which the+ // drift notice explains in full — a second copy in the generic error+ // alert would just say the same thing twice.} else if (result.kind === 'error') {runInAction(() => {this.error = result.message;diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.tsindex 503f22881..72bc53e51 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/remote-server-store.ts@@ -2,7 +2,10 @@ import { makeAutoObservable, runInAction } from 'mobx';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { events, rpc } from '@renderer/lib/ipc';-import type { DockerAvailability } from '@shared/core/managed-switch-server/managed-switch-server';+import type {+ DockerAvailability,+ SwitchVersionDrift,+} from '@shared/core/managed-switch-server/managed-switch-server';import {type RemoteServerStatus,remoteServerLogChannel,@@ -13,7 +16,16 @@ import { switchServersStore } from './switch-servers-store';const MAX_LOG_LINES = 400;function defaultStatus(sshHost: string): RemoteServerStatus {- return { sshHost, phase: 'stopped', serverId: null, version: '', message: null, error: null };+ return {+ sshHost,+ phase: 'stopped',+ serverId: null,+ version: '',+ deployedVersion: null,+ drift: null,+ message: null,+ error: null,+ };}/**@@ -63,6 +75,11 @@ export class RemoteServerStore {return this.busyHosts.has(sshHost) || phase === 'starting' || phase === 'stopping';}+ /** Set when the host's switch-core differs from the version this build pins. */+ driftFor(sshHost: string): SwitchVersionDrift | null {+ return this.statusFor(sshHost).drift;+ }+logsFor(sshHost: string): string[] {return this.logsByHost.get(sshHost) ?? [];}@@ -134,6 +151,10 @@ export class RemoteServerStore {});this.error = result.detail;});+ } else if (result.kind === 'version-downgrade') {+ // The refusal is already on the pushed status as `drift`, which the+ // drift notice explains in full — a second copy in the generic error+ // alert would just say the same thing twice.} else if (result.kind === 'error') {runInAction(() => {this.error = result.message;diff --git a/dash/apps/switchdash-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts b/dash/apps/switchdash-desktop/src/shared/core/managed-switch-server/managed-switch-server.tsindex ff1551b6b..92f719256 100644--- a/dash/apps/switchdash-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts@@ -15,6 +15,46 @@ export type DockerAvailability =| { available: true; version: string }| { available: false; reason: 'not-installed' | 'daemon-down'; detail: string };+/**+ * How the switch-core version a stack is actually deployed at relates to the+ * version this build of switchdash pins.+ *+ * - `upgrade` — the stack is behind; restarting re-pulls and migrates forward.+ * - `downgrade` — the stack is AHEAD. Unsafe: its database has already migrated+ * to a newer schema and switch-core cannot roll one back, so the stack must+ * not be restarted against the older pin.+ * - `unknown` — one of the two is not a comparable semver. Neither direction can+ * be proven, so it is surfaced rather than assumed safe.+ */+export type SwitchVersionDriftDirection = 'upgrade' | 'downgrade' | 'unknown';++/** A mismatch between the deployed switch-core version and this build's pin. */+export type SwitchVersionDrift = {+ /** The version the stack is actually deployed at. */+ deployed: string;+ /** The version this build of switchdash pins. */+ expected: string;+ direction: SwitchVersionDriftDirection;+};++/**+ * Why a downgrade is refused, in one message — shared by the main process (as+ * the status `error` when a start is blocked) and the renderer (as the drift+ * banner) so both say the same thing.+ *+ * Names what is stuck, why it cannot be undone, and the two ways out: the+ * honest answer is "install the newer switchdash again", and a user who is not+ * told that will reach for Reset and lose their data.+ */+export function switchVersionDowngradeMessage(deployed: string, expected: string): string {+ return (+ `This stack runs switch-core ${deployed}, but this version of switchdash pins ${expected}. ` ++ `Starting it would point the stack at an older core than its database has already migrated to, ` ++ `and switch-core cannot roll a migration back. Update switchdash to a version that ships ` ++ `switch-core ${deployed} or newer, or reset the stack to rebuild it empty (this deletes its data).`+ );+}+/** Snapshot of the managed local server, emitted on every transition. */export type LocalServerStatus = {phase: LocalServerPhase;@@ -22,15 +62,23 @@ export type LocalServerStatus = {serverId: string | null;/** The pinned switch-core version this build runs. */version: string;+ /** The version the stack on the host is actually deployed at, once observed.+ * Null when nothing is deployed yet or it could not be read. */+ deployedVersion: string | null;+ /** Set when {@link deployedVersion} differs from {@link version}, else null. */+ drift: SwitchVersionDrift | null;/** 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. */+/** Outcome of a start request. `docker-unavailable` and `version-downgrade` are+ * separated from generic errors so the UI can point the user at installing /+ * starting Docker, or explain why an older build refuses to take over a stack+ * that has already migrated forward. */export type StartLocalServerResult =| { kind: 'started'; serverId: string }| { kind: 'docker-unavailable'; reason: 'not-installed' | 'daemon-down'; detail: string }+ | { kind: 'version-downgrade'; deployed: string; expected: string }| { kind: 'error'; message: string };