Skip to content

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

Console: managed server status dots, Server page and frozen workspace (#762)

Louis Amaudruzfa28704b5c40
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts
index 8346226d1..d6b24d4fd 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts
@@ -164,6 +164,23 @@ export async function serviceContainerId(host: ServerHost, service: string): Pro
return id;
}
+/**
+ * When the core container last started, as Docker reports it (ISO-8601), or
+ * null when it is not running. Throws when Docker could not be asked.
+ */
+export async function coreStartedAt(host: ServerHost): Promise<string | null> {
+ if (!(await isStackRunning(host))) return null;
+ const id = await serviceContainerId(host, CORE_SERVICE);
+ const stdout = await runDocker(host, ['inspect', '--format', '{{.State.StartedAt}}', id], 30_000);
+ const startedAt = stdout.trim();
+ if (Number.isNaN(Date.parse(startedAt))) {
+ throw new Error(
+ `Docker reported an unreadable start time for the core container: ${startedAt}`
+ );
+ }
+ return new Date(startedAt).toISOString();
+}
+
/** Service names currently in the `running` state for the managed project. */
export async function runningServices(host: ServerHost): Promise<string[]> {
try {
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts
index dfd411d1f..7915c08b1 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/controller.ts
@@ -1,5 +1,9 @@
+import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';
+import { embeddedControllerService } from '@main/core/embedded-controller/embedded-controllers';
+import { getManagedServer } from '@main/core/switch-servers/servers-store';
import type {
DockerAvailability,
+ LocalActivityEntry,
LocalServerStatus,
StartLocalServerResult,
} from '@shared/core/managed-switch-server/managed-switch-server';
@@ -21,4 +25,27 @@ export const localSwitchServerController = createRPCController({
* next start, instead of pulling this build's pinned images. */
setCheckoutBuild: (enabled: boolean): Promise<void> =>
localServerService.setCheckoutBuild(enabled),
+
+ /** When the running stack started, or null when it is not running. */
+ startedAt: (): Promise<string | null> => localServerService.startedAt(),
+
+ /** The stack's recent history, most recent first. */
+ activity: (): Promise<LocalActivityEntry[]> => localServerService.activity(),
+
+ /**
+ * Move the service on `port` elsewhere and start again. When that moves the
+ * API, the agents pointed at it follow, as they do when a server's address
+ * is edited.
+ */
+ useAnotherPort: async (port: number): Promise<StartLocalServerResult> => {
+ const before = await getManagedServer();
+ const result = await localServerService.useAnotherPort(port);
+ if (result.kind !== 'started' || !before) return result;
+ const after = await getManagedServer();
+ if (after && after.apiUrl !== before.apiUrl) {
+ await propagateServerApiUrl(after.id, after.apiUrl);
+ await embeddedControllerService.followServerApiUrl(after.id);
+ }
+ return result;
+ },
});
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.test.ts
new file mode 100644
index 000000000..7940943ed
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.test.ts
@@ -0,0 +1,45 @@
+import { mkdtemp, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { beforeEach, expect, it, vi } from 'vitest';
+
+const dir = vi.hoisted(() => ({ path: '' }));
+vi.mock('./paths', () => ({ localServerDir: () => dir.path }));
+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }));
+
+const { readLocalActivity, recordLocalActivity } = await import('./local-activity');
+
+beforeEach(async () => {
+ dir.path = await mkdtemp(join(tmpdir(), 'local-activity-'));
+});
+
+it('is empty before anything has happened', async () => {
+ await expect(readLocalActivity()).resolves.toEqual([]);
+});
+
+it('keeps what happened, most recent first', async () => {
+ await recordLocalActivity('started', null);
+ await recordLocalActivity('start-failed', 'port in use');
+
+ const entries = await readLocalActivity();
+ expect(entries.map((e) => [e.action, e.detail])).toEqual([
+ ['start-failed', 'port in use'],
+ ['started', null],
+ ]);
+});
+
+it('keeps only the latest fifty', async () => {
+ for (let i = 0; i < 55; i++) await recordLocalActivity('started', null);
+ expect(await readLocalActivity()).toHaveLength(50);
+});
+
+it('says so when the history cannot be read, rather than showing it as empty', async () => {
+ await writeFile(join(dir.path, 'activity.json'), '{not json', 'utf8');
+ await expect(readLocalActivity()).rejects.toThrow();
+});
+
+it('starts a new history over one it cannot read', async () => {
+ await writeFile(join(dir.path, 'activity.json'), '{not json', 'utf8');
+ await recordLocalActivity('stopped', null);
+ expect((await readLocalActivity()).map((e) => e.action)).toEqual(['stopped']);
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.ts
new file mode 100644
index 000000000..7f4fa4fe1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-activity.ts
@@ -0,0 +1,78 @@
+import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { log } from '@main/lib/logger';
+import type {
+ LocalActivityAction,
+ LocalActivityEntry,
+} from '@shared/core/managed-switch-server/managed-switch-server';
+import { localServerDir } from './paths';
+
+/** Enough to cover the server page's recent activity and "last running". */
+const KEPT = 50;
+
+const ACTIONS: ReadonlySet<string> = new Set<LocalActivityAction>([
+ 'started',
+ 'stopped',
+ 'start-failed',
+ 'updated',
+ 'reset',
+]);
+
+function activityFile(): string {
+ return join(localServerDir(), 'activity.json');
+}
+
+function isEntry(value: unknown): value is LocalActivityEntry {
+ if (typeof value !== 'object' || value === null) return false;
+ const v = value as Record<string, unknown>;
+ return (
+ typeof v.at === 'string' &&
+ typeof v.action === 'string' &&
+ ACTIONS.has(v.action) &&
+ (v.detail === null || typeof v.detail === 'string')
+ );
+}
+
+/**
+ * The local stack's history, most recent first. Empty before anything has been
+ * recorded; throws when the file is there but cannot be read, so the page says
+ * so instead of showing a history that looks merely short.
+ */
+export async function readLocalActivity(): Promise<LocalActivityEntry[]> {
+ let text: string;
+ try {
+ text = await readFile(activityFile(), 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throw error;
+ }
+ const parsed: unknown = JSON.parse(text);
+ if (!Array.isArray(parsed)) throw new Error('The local server history is not a list.');
+ return parsed.filter(isEntry);
+}
+
+/**
+ * Add an entry to the history. A record, not part of the operation it
+ * describes: failing to write it is logged and the operation stands.
+ */
+export async function recordLocalActivity(
+ action: LocalActivityAction,
+ detail: string | null
+): Promise<void> {
+ try {
+ let previous: LocalActivityEntry[] = [];
+ try {
+ previous = await readLocalActivity();
+ } catch (error) {
+ log.warn('local-switch-server: starting a new history over an unreadable one', { error });
+ }
+ const entry: LocalActivityEntry = { at: new Date().toISOString(), action, detail };
+ const next = [entry, ...previous].slice(0, KEPT);
+ await mkdir(localServerDir(), { recursive: true });
+ const tmp = `${activityFile()}.tmp`;
+ await writeFile(tmp, JSON.stringify(next, null, 2), 'utf8');
+ await rename(tmp, activityFile());
+ } catch (error) {
+ log.warn(`local-switch-server: could not record "${action}" in the history`, { error });
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts
index 741b58cbb..657e71429 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.test.ts
@@ -12,6 +12,9 @@ const m = vi.hoisted(() => ({
start: vi.fn<(opts: StartStackOptions) => Promise<StartLocalServerResult>>(),
stop: vi.fn(),
emit: vi.fn(),
+ record: vi.fn(),
+ ports: vi.fn(),
+ remember: vi.fn(),
}));
vi.mock('@shared/app-identity', async (importOriginal) => ({
...(await importOriginal<typeof AppIdentity>()),
@@ -33,7 +36,18 @@ vi.mock('./checkout-build', () => ({
isCheckoutBuildEnabled: vi.fn(),
setCheckoutBuildEnabled: vi.fn(),
}));
-vi.mock('./compose', () => ({ isStackRunning: m.running }));
+const images = vi.hoisted(() => vi.fn());
+vi.mock('./compose', () => ({
+ isStackRunning: m.running,
+ coreStartedAt: vi.fn(),
+ runningImages: images,
+}));
+vi.mock('./local-activity', () => ({
+ readLocalActivity: vi.fn(),
+ recordLocalActivity: m.record,
+}));
+vi.mock('./ports', () => ({ readPersistedPorts: m.ports, rememberPorts: m.remember }));
+vi.mock('./free-port', () => ({ findFreePort: async () => 51234 }));
vi.mock('./deployed-version', () => ({ readVersionStatus: m.version }));
vi.mock('./telemetry-consent', () => ({ readDeployedTelemetry: vi.fn() }));
vi.mock('./managed-upgrade', async (importOriginal) => ({
@@ -265,3 +279,89 @@ it('resets the stack on this computer holding no lock, since nobody else shares
expect(resetStack).toHaveBeenCalledWith(expect.anything(), null);
});
+
+it('says its state has been read once the boot check is done, whatever it found', async () => {
+ m.running.mockResolvedValue(false);
+ m.version.mockResolvedValue({ deployedVersion: '0.11.0', drift: null });
+ const service = new LocalServerService();
+ expect(service.getStatus().checked).toBe(false);
+ await boot(service);
+ expect(service.getStatus()).toMatchObject({ phase: 'stopped', checked: true });
+});
+
+it('records what happens to the stack: an update, a start, a stop, a failed start', async () => {
+ m.running.mockResolvedValue(false);
+ const service = new LocalServerService();
+ await boot(service);
+ await service.start();
+ expect(m.record.mock.calls).toEqual([
+ ['updated', '0.11.0'],
+ ['started', null],
+ ]);
+
+ m.record.mockClear();
+ await service.stop();
+ m.start.mockResolvedValue({ kind: 'error', message: 'bind: address already in use' });
+ await service.start();
+ expect(m.record.mock.calls).toEqual([
+ ['stopped', null],
+ ['start-failed', 'bind: address already in use'],
+ ]);
+});
+
+it('moves only the service on the port that was taken, then starts', async () => {
+ m.running.mockResolvedValue(false);
+ m.version.mockResolvedValue({ deployedVersion: '0.11.0', drift: null });
+ m.start.mockResolvedValue(started);
+ m.ports.mockResolvedValue({ gateway: 8000, api: 8001, mattermost: 8065, postgres: 5432 });
+ const service = new LocalServerService();
+ await boot(service);
+
+ await expect(service.useAnotherPort(8000)).resolves.toEqual(started);
+ expect(m.remember).toHaveBeenCalledWith(expect.anything(), {
+ gateway: 51234,
+ api: 8001,
+ mattermost: 8065,
+ postgres: 5432,
+ });
+ expect(m.start).toHaveBeenCalledOnce();
+});
+
+it('refuses to move a port the server does not use', async () => {
+ m.ports.mockResolvedValue({ gateway: 8000, api: 8001, mattermost: 8065, postgres: 5432 });
+ const service = new LocalServerService();
+ await expect(service.useAnotherPort(9999)).rejects.toThrow('port 9999');
+ expect(m.remember).not.toHaveBeenCalled();
+});
+
+it('reports a stop that errored but left the stack down as stopped', async () => {
+ m.version.mockResolvedValue({ deployedVersion: '0.11.0', drift: null });
+ const service = new LocalServerService();
+ await boot(service);
+ m.stop.mockRejectedValue(new Error('compose down failed: Container switch Stopping'));
+ images.mockResolvedValue(new Map());
+
+ await expect(service.stop()).resolves.toBeUndefined();
+ expect(service.getStatus()).toMatchObject({ phase: 'stopped', error: null, failedTo: null });
+ expect(m.record).toHaveBeenCalledWith('stopped', null);
+});
+
+it('reports a stop that errored with the stack still up, or unreadable, as a failed stop', async () => {
+ m.version.mockResolvedValue({ deployedVersion: '0.11.0', drift: null });
+ const service = new LocalServerService();
+ await boot(service);
+ m.stop.mockRejectedValue(new Error('compose down failed'));
+ images.mockRejectedValue(new Error('docker is gone'));
+
+ await expect(service.stop()).rejects.toThrow('compose down failed');
+ expect(service.getStatus()).toMatchObject({
+ phase: 'error',
+ failedTo: 'stop',
+ error: 'compose down failed',
+ });
+
+ // The next start says nothing about the stop any more.
+ m.start.mockResolvedValue({ kind: 'error', message: 'bind: address already in use' });
+ await service.start();
+ expect(service.getStatus()).toMatchObject({ phase: 'error', failedTo: null });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts
index 202050e02..472d89d39 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts
@@ -12,6 +12,7 @@ import {
CHECKOUT_IMAGE_TAG,
type CheckoutBuild,
type DockerAvailability,
+ type LocalActivityEntry,
type LocalServerStatus,
type StartLocalServerResult,
managedServerUpgradeBlockedReason,
@@ -27,11 +28,13 @@ import {
isCheckoutBuildEnabled,
setCheckoutBuildEnabled,
} from './checkout-build';
-import { isStackRunning } from './compose';
-import { LOCAL_SERVER_NAME } from './constants';
+import { coreStartedAt, isStackRunning, runningImages } from './compose';
+import { CORE_SERVICE, LOCAL_SERVER_NAME } from './constants';
import { readVersionStatus } from './deployed-version';
+import { findFreePort, type LocalServerPorts } from './free-port';
import { LocalServerHost } from './host/local-host';
import type { ServerHost } from './host/types';
+import { readLocalActivity, recordLocalActivity } from './local-activity';
import {
owedUpgrade,
readUpgradeJournal,
@@ -39,6 +42,7 @@ import {
upgradeState,
} from './managed-upgrade';
import { resetStack, startStack, stopStack } from './pipeline';
+import { readPersistedPorts, rememberPorts } from './ports';
import { readDeployedTelemetry } from './telemetry-consent';
/**
@@ -58,6 +62,7 @@ import { readDeployedTelemetry } from './telemetry-consent';
export class LocalServerService {
private status: LocalServerStatus = {
phase: 'stopped',
+ checked: false,
upgrade: null,
serverId: null,
version: COMPATIBLE_SWITCH_VERSION,
@@ -67,6 +72,7 @@ export class LocalServerService {
deployedTelemetry: null,
message: null,
error: null,
+ failedTo: null,
};
private busy = false;
@@ -88,7 +94,9 @@ export class LocalServerService {
}
private setStatus(patch: Partial<LocalServerStatus>): void {
- this.status = { ...this.status, ...patch };
+ // Any change of phase settles what failed, unless the patch says.
+ const failedTo = patch.phase !== undefined ? (patch.failedTo ?? null) : this.status.failedTo;
+ this.status = { ...this.status, ...patch, failedTo };
events.emit(localServerStatusChannel, this.status);
}
@@ -192,6 +200,7 @@ export class LocalServerService {
} catch (error) {
log.warn('local-switch-server: boot status reconcile failed', { error });
} finally {
+ this.setStatus({ checked: true });
host.dispose();
}
// Not awaited: the boot check is done once the upgrade is under way, and a
@@ -263,6 +272,7 @@ export class LocalServerService {
if (result.kind === 'docker-unavailable') {
this.setStatus({ phase: 'error', error: result.detail });
this.failUpgrade(result.detail);
+ await recordLocalActivity('start-failed', result.detail);
} else if (result.kind === 'version-downgrade') {
this.setStatus({
phase: 'error',
@@ -272,14 +282,18 @@ export class LocalServerService {
drift: { deployed: result.deployed, expected: result.expected, direction: 'downgrade' },
upgrade: null,
});
+ await recordLocalActivity('start-failed', this.status.error);
} else if (result.kind === 'matrix-migration-failed') {
const error = matrixMigrationFailedMessage(result.deployed, result.expected);
this.setStatus({ phase: 'error', message: null, error, deployedVersion: result.deployed });
this.failUpgrade(error);
+ await recordLocalActivity('start-failed', error);
} else if (result.kind === 'error') {
this.setStatus({ phase: 'error', error: result.message });
this.failUpgrade(result.message);
+ await recordLocalActivity('start-failed', result.message);
} else {
+ const updatedTo = this.status.upgrade?.to ?? 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({
@@ -292,6 +306,8 @@ export class LocalServerService {
upgrade: null,
deployedTelemetry: { known: true, enabled: result.telemetryEnabled },
});
+ if (updatedTo !== null) await recordLocalActivity('updated', updatedTo);
+ await recordLocalActivity('started', null);
if (this.refused) {
this.refused = false;
for (const listener of this.upgradeListeners) listener(result.serverId);
@@ -304,6 +320,7 @@ export class LocalServerService {
log.error('local-switch-server: start failed', { error });
this.setStatus({ phase: 'error', error: message });
this.failUpgrade(message);
+ await recordLocalActivity('start-failed', message);
reportManagedServerStartThrew('local');
return { kind: 'error', message };
} finally {
@@ -336,14 +353,35 @@ export class LocalServerService {
deployedTelemetry: null,
upgrade: upgrade && upgradeState(upgrade, false),
});
+ await recordLocalActivity('stopped', null);
reportManagedServerOutcome('stop', 'local', 'success');
} catch (error) {
+ reportManagedServerOutcome('stop', 'local', 'failure');
+ // A stop that errors may still have stopped the containers. Say what is
+ // true rather than what the command reported.
+ // Asked so that a failure to ask counts as still running.
+ const stillRunning = await runningImages(host).then(
+ (images) => images.has(CORE_SERVICE),
+ () => true
+ );
+ if (stillRunning) {
+ this.setStatus({
+ phase: 'error',
+ failedTo: 'stop',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw error;
+ }
+ log.warn('local-switch-server: stop reported an error, but the stack is down', { error });
+ const upgrade = this.status.upgrade;
this.setStatus({
- phase: 'error',
- error: error instanceof Error ? error.message : String(error),
+ phase: 'stopped',
+ message: null,
+ error: null,
+ deployedTelemetry: null,
+ upgrade: upgrade && upgradeState(upgrade, false),
});
- reportManagedServerOutcome('stop', 'local', 'failure');
- throw error;
+ await recordLocalActivity('stopped', null);
} finally {
host.dispose();
this.busy = false;
@@ -376,10 +414,12 @@ export class LocalServerService {
drift: null,
upgrade: null,
});
+ await recordLocalActivity('reset', null);
reportManagedServerOutcome('reset', 'local', 'success');
} catch (error) {
this.setStatus({
phase: 'error',
+ failedTo: 'reset',
error: error instanceof Error ? error.message : String(error),
});
reportManagedServerOutcome('reset', 'local', 'failure');
@@ -390,6 +430,49 @@ export class LocalServerService {
}
}
+ /** When the running stack's core container started, or null when it is not
+ * running. */
+ async startedAt(): Promise<string | null> {
+ if (this.status.phase !== 'running') return null;
+ const host: ServerHost = new LocalServerHost();
+ try {
+ return await coreStartedAt(host);
+ } finally {
+ host.dispose();
+ }
+ }
+
+ /** What has happened to the stack, most recent first. */
+ activity(): Promise<LocalActivityEntry[]> {
+ return readLocalActivity();
+ }
+
+ /**
+ * Move whichever of the stack's services publishes on `port` to a free port,
+ * then start it. For a start that failed because something else took the
+ * port since it was chosen.
+ */
+ async useAnotherPort(port: number): Promise<StartLocalServerResult> {
+ if (this.busy || this.starting) {
+ throw new Error('A local-server operation is already in progress.');
+ }
+ const host: ServerHost = new LocalServerHost();
+ try {
+ const ports = await readPersistedPorts(host);
+ if (!ports) throw new Error('This server has not chosen its ports yet.');
+ const service = (Object.keys(ports) as (keyof LocalServerPorts)[]).find(
+ (key) => ports[key] === port
+ );
+ if (!service) throw new Error(`This server does not publish anything on port ${port}.`);
+ const fresh = await findFreePort(new Set(Object.values(ports)));
+ log.info(`local-switch-server: moving ${service} from port ${port} to ${fresh}`);
+ await rememberPorts(host, { ...ports, [service]: fresh });
+ } finally {
+ host.dispose();
+ }
+ return this.start();
+ }
+
dispose(): void {
this.startAbort?.abort();
this.startAbort = null;
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-controller.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-controller.ts
index 3d0624c18..efa6404dd 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-controller.ts
@@ -20,6 +20,9 @@ export const remoteSwitchServerController = createRPCController({
register: (sshHost: string): Promise<StackRegister> => remoteServerService.register(sshHost),
+ /** When the stack on the host started, or null when it is not running. */
+ startedAt: (sshHost: string): Promise<string | null> => remoteServerService.startedAt(sshHost),
+
start: (params: { sshHost: string; name: string }): Promise<StartRemoteServerResult> =>
remoteServerService.start(params.sshHost, params.name),
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts
index 74b4fbc62..4b85a394c 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.test.ts
@@ -921,18 +921,38 @@ describe('stopping and resetting a shared stack', () => {
it('reports a stop that failed, and gives the forward back', async () => {
const host = fakeHost();
- createRemoteServerHost.mockResolvedValue(host);
+ const look = fakeHost();
+ createRemoteServerHost.mockResolvedValueOnce(host).mockResolvedValueOnce(look);
stopStack.mockRejectedValueOnce(new Error('compose down failed'));
+ inspectStack.mockResolvedValue(present(true));
const service = await loadService();
await expect(service.stop('vm-1')).rejects.toThrow(/compose down failed/);
expect(service.getStatus('vm-1')).toMatchObject({
phase: 'error',
+ failedTo: 'stop',
error: 'compose down failed',
});
expect(writeRecord).not.toHaveBeenCalled();
expect(host.dispose).toHaveBeenCalledOnce();
+ expect(look.dispose).toHaveBeenCalledOnce();
+ });
+
+ it('reports a stop that errored but left the containers down as stopped, and says so', async () => {
+ createRemoteServerHost.mockResolvedValueOnce(fakeHost()).mockResolvedValueOnce(fakeHost());
+ stopStack.mockRejectedValueOnce(new Error('SSH transport failure: No response from server'));
+ inspectStack.mockResolvedValue(present(false));
+ const service = await loadService();
+
+ await expect(service.stop('vm-1')).resolves.toBeUndefined();
+
+ expect(service.getStatus('vm-1')).toMatchObject({
+ phase: 'stopped',
+ error: null,
+ failedTo: null,
+ notice: "The stop on vm-1 reported an error, but the server's containers are down.",
+ });
});
it('resets it, deleting its agents first and keeping who did it on the host', async () => {
diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts
index fa440e22e..534c9442d 100644
--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts
+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts
@@ -38,6 +38,7 @@ import {
remoteServerLogChannel,
remoteServerStatusChannel,
} from '@shared/events/remoteSwitchServerEvents';
+import { coreStartedAt } from './compose';
import { hostAccount, readRegister, writeRecord } from './console-register';
import { readVersionStatus } from './deployed-version';
import { apiUrlFor, gatewayUrlFor, type LocalServerPorts } from './free-port';
@@ -100,6 +101,7 @@ function initialStatus(sshHost: string): RemoteServerStatus {
return {
sshHost,
phase: 'stopped',
+ checked: false,
upgrade: null,
serverId: null,
version: COMPATIBLE_SWITCH_VERSION,
@@ -111,6 +113,7 @@ function initialStatus(sshHost: string): RemoteServerStatus {
deployedTelemetry: null,
message: null,
error: null,
+ failedTo: null,
notice: null,
recordWarning: null,
waitingFor: null,
@@ -220,7 +223,12 @@ export class RemoteServerService {
}
private setStatus(sshHost: string, patch: Partial<RemoteServerStatus>): void {
- const next = { ...this.getStatus(sshHost), ...patch, sshHost };
+ // A phase is only ever written once the stack has been looked at.
+ const current = this.getStatus(sshHost);
+ const checked = patch.phase !== undefined || current.checked;
+ // Any change of phase settles what failed, unless the patch says.
+ const failedTo = patch.phase !== undefined ? (patch.failedTo ?? null) : current.failedTo;
+ const next = { ...current, ...patch, sshHost, checked, failedTo };
this.statuses.set(sshHost, next);
events.emit(remoteServerStatusChannel, next);
}
@@ -333,6 +341,38 @@ export class RemoteServerService {
}
}
+ /** Whether the stack on `sshHost` is down, read over a fresh connection.
+ * False when it is running or could not be read: only a stack seen down
+ * counts as stopped. */
+ private async stoppedAfterAll(sshHost: string): Promise<boolean> {
+ if (hostReachabilityService.isBlocked(sshHost)) return false;
+ let host: RemoteServerHost | null = null;
+ try {
+ host = await createRemoteServerHost(sshHost);
+ const stack = await inspectStack(host);
+ return stack.kind === 'absent' || (stack.kind === 'present' && !stack.running);
+ } catch (error) {
+ log.warn(`remote-switch-server: could not look at ${sshHost} after a failed stop`, { error });
+ return false;
+ } finally {
+ host?.dispose();
+ }
+ }
+
+ /** When the stack on `sshHost` started, or null when it is not running here. */
+ async startedAt(sshHost: string): Promise<string | null> {
+ if (this.getStatus(sshHost).phase !== 'running') return null;
+ hostReachabilityService.requireReachable(sshHost);
+ const live = this.hosts.get(sshHost);
+ if (live) return coreStartedAt(live);
+ const host = await createRemoteServerHost(sshHost);
+ try {
+ return await coreStartedAt(host);
+ } finally {
+ host.dispose();
+ }
+ }
+
/** Who uses the stack on `sshHost` and what they last did to it, as the
* Consoles sharing it have recorded on the host. Reads only. */
async register(sshHost: string): Promise<StackRegister> {
@@ -630,6 +670,7 @@ export class RemoteServerService {
// A host that became the live one owns its forward; any other is throwaway.
if (!kept) host?.dispose();
this.busy.delete(sshHost);
+ this.setStatus(sshHost, { checked: true });
}
if (!upgradeNow) return;
try {
@@ -1096,11 +1137,33 @@ export class RemoteServerService {
host = null;
throw error;
}
+ reportManagedServerOutcome('stop', 'remote', 'failure');
+ // A stop that errors — most often because the connection dropped under
+ // it — may still have stopped the containers. Look again over a fresh
+ // connection, and say what is true rather than what the command reported.
+ if (await this.stoppedAfterAll(sshHost)) {
+ log.warn(
+ `remote-switch-server: stop on ${sshHost} reported an error, but the stack is down`,
+ {
+ error,
+ }
+ );
+ const upgrade = this.getStatus(sshHost).upgrade;
+ this.setStatus(sshHost, {
+ phase: 'stopped',
+ message: null,
+ error: null,
+ deployedTelemetry: null,
+ upgrade: upgrade && upgradeState(upgrade, false),
+ notice: `The stop on ${sshHost} reported an error, but the server's containers are down.`,
+ });
+ return;
+ }
this.setStatus(sshHost, {
phase: 'error',
+ failedTo: 'stop',
error: error instanceof Error ? error.message : String(error),
});
- reportManagedServerOutcome('stop', 'remote', 'failure');
throw error;
} finally {
await lease?.release();
@@ -1155,6 +1218,7 @@ export class RemoteServerService {
}
this.setStatus(sshHost, {
phase: 'error',
+ failedTo: 'reset',
error: error instanceof Error ? error.message : String(error),
});
reportManagedServerOutcome('reset', 'remote', 'failure');
diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
index a5bbdc4a9..a2be6fcb9 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
@@ -9,6 +9,7 @@ import { templateImportView } from '@renderer/features/room-templates/room-templ
import { sessionView } from '@renderer/features/sessions/view';
import { settingsView } from '@renderer/features/settings/settings-view';
import { roomView } from '@renderer/features/switch-rooms/view';
+import { managedServerView } from '@renderer/features/switch-servers/managed-server-view';
import { serverAgentsView } from '@renderer/features/switch-servers/server-agents-view';
import { serverRoomsView } from '@renderer/features/switch-servers/server-rooms-view';
import { serverView } from '@renderer/features/switch-servers/view';
@@ -30,6 +31,7 @@ export const views = {
room: roomView,
settings: settingsView,
server: serverView,
+ managedServer: managedServerView,
serverAgents: serverAgentsView,
serverRooms: serverRoomsView,
remoteHosts: remoteHostsView,
diff --git a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
index 545ae3e94..0bf06fddd 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/app/workspace.tsx
@@ -4,6 +4,8 @@ import { OnboardingFlow } from '@renderer/features/onboarding/onboarding-flow';
import { onboardingStore } from '@renderer/features/onboarding/onboarding-store';
import { LeftSidebar } from '@renderer/features/sidebar/left-sidebar';
import { RoomEmbedLayer } from '@renderer/features/switch-rooms/room-embed-layer';
+import { FrozenBanner, frozenServer } from '@renderer/features/switch-servers/frozen-workspace';
+import { FROZEN } from '@renderer/features/switch-servers/managed-server-state';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { CommandShortcutBinder } from '@renderer/lib/commands/command-shortcut-binder';
import { AppKeyboardShortcuts } from '@renderer/lib/components/app-keyboard-shortcuts';
@@ -84,14 +86,20 @@ const Shell = observer(function Shell({ mainContent }: { mainContent: ReactNode
);
case 'onboarding':
return <OnboardingFlow />;
- case 'workspace':
+ case 'workspace': {
+ // A workspace whose server can't answer stays where it was, under a
+ // banner, rather than filling with errors from every call that fails.
+ const frozen = frozenServer(currentViewId);
return (
<WorkspaceLayout
leftSidebar={<LeftSidebar />}
mainContent={mainContent}
persistentLayer={<RoomEmbedLayer />}
+ banner={frozen && <FrozenBanner server={frozen} />}
+ contentClassName={frozen ? FROZEN : undefined}
/>
);
+ }
}
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
index 44b43b41f..cb7b2871b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/managed-agent-list.tsx
@@ -1,5 +1,6 @@
import { Cloud, CloudOff, Server, ServerOff } from 'lucide-react';
import { observer } from 'mobx-react-lite';
+import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -24,7 +25,9 @@ export const ManagedAgentList = observer(function ManagedAgentList() {
const serverId = switchServersStore.activeServerId;
const agents = useManagedAgents(serverId);
if (serverId === null) return null;
- if (agents.error)
+ // A frozen workspace's banner already says why nothing can be listed.
+ const server = switchServersStore.serverById(serverId);
+ if (agents.error && !(server && isFrozenServer(server)))
return (
<div role="alert" className="px-3 py-2 text-xs text-foreground-destructive">
{failureText(agents.error, 'Managed agents could not be listed.')}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts
index 6aa188940..bf8146e6b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.test.ts
@@ -2,6 +2,9 @@ import { describe, expect, it, vi } from 'vitest';
import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';
vi.mock('@renderer/lib/ipc', () => ({ rpc: {} }));
+vi.mock('@renderer/features/switch-servers/server-availability', () => ({
+ serverAvailability: () => 'available',
+}));
vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
switchServersStore: {},
}));
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts
index a007d9f2e..c219ba234 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/use-managed-agents.ts
@@ -1,5 +1,6 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
+import { serverAvailability } from '@renderer/features/switch-servers/server-availability';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { events, rpc } from '@renderer/lib/ipc';
@@ -23,7 +24,12 @@ const MANAGED_AGENTS_REFRESH_MS = 30_000;
*/
export function useManagedAgents(serverId: string | null) {
const queryClient = useQueryClient();
- const signedIn = serverId !== null && switchServersStore.isConnected(serverId);
+ // Not asked while a server this Console runs is down: the call can only
+ // fail, and the list it last gave is the one worth showing meanwhile.
+ const signedIn =
+ serverId !== null &&
+ switchServersStore.isConnected(serverId) &&
+ serverAvailability(serverId) !== 'dormant';
const user = serverId === null ? null : (switchServersStore.statusFor(serverId)?.user ?? null);
// The list is the workspace's, not the server's: switching workspace on the
// same server has to read it again rather than show the last one.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
index 50dc93de0..9750b7793 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/left-sidebar.tsx
@@ -9,6 +9,8 @@ import { SwitchConsoleMark } from '@renderer/lib/switch-console-mark';
import { BoundShortcut } from '@renderer/lib/ui/shortcut';
import { cn } from '@renderer/utils/utils';
import { SWITCH_CONSOLE_DOCS_URL } from '@shared/urls';
+import { FROZEN, isFrozenServer } from '../switch-servers/managed-server-state';
+import { switchServersStore } from '../switch-servers/switch-servers-store';
import { WorkspaceSwitcher } from '../switch-servers/workspace-switcher';
import { SidebarPinnedSessionList } from './pinned-session-list';
import { SessionDiscoveryStatus } from './session-discovery-status';
@@ -35,6 +37,8 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {
const { isDragOver, onDragOver, onDragEnter, onDragLeave, onDrop } = useSidebarDrop();
const managementMode = useAgentManagementMode();
+ const activeServer = switchServersStore.activeServer;
+ const frozen = activeServer !== null && isFrozenServer(activeServer);
return (
<div
@@ -56,7 +60,9 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {
<SidebarSpace />
<SidebarContainer className="min-h-0 w-full flex-1 border-r-0">
<SidebarContent className="flex flex-col">
- <SidebarPinnedSessionList />
+ <div className={cn(frozen && FROZEN)}>
+ <SidebarPinnedSessionList />
+ </div>
{/* The sidebar reads as three blocks — which server, that server's
pages, then its sessions. The switcher and the nav under it are
one block, 8px apart, which the nav owns as its own top padding;
@@ -65,7 +71,7 @@ export const LeftSidebar: React.FC = observer(function LeftSidebar() {
<WorkspaceSwitcher />
<WorkspaceNav />
</div>
- <SidebarGroup className="mt-0 mb-0 flex min-h-0 flex-1 flex-col">
+ <SidebarGroup className={cn('mt-0 mb-0 flex min-h-0 flex-1 flex-col', frozen && FROZEN)}>
{/* With agent management the sections draw their own headings,
inside the list, so they scroll with it. */}
{!managementMode && <SessionsSectionHeader />}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
index dc9a3d71b..c22cb4a7f 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx
@@ -6,8 +6,10 @@ import { ManagedAgentList } from '@renderer/features/managed-agents/managed-agen
import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { switchRoomsStore as roomConnectionsStore } from '@renderer/features/switch-rooms/switch-rooms-store';
+import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
@@ -60,11 +62,12 @@ export const SidebarGroupedList = observer(function SidebarGroupedList() {
// Two things make the loaded state wrong without any mutation here:
// signing in to a server (its rooms were skipped while disconnected, and
- // nothing re-ran the load), and switching which server is active — only the
- // server on screen is loaded, so the one you switch to may never have been.
+ // nothing re-ran the load), and switching which workspace is active — only
+ // the workspace on screen is loaded, so the one you switch to may never have
+ // been, even on the same server.
const stopWatchingServers = reaction(
() => ({
- active: switchServersStore.activeServerId,
+ active: workspacesStore.activeId,
connected: switchServersStore.servers
.filter((s) => switchServersStore.isConnected(s.id))
.map((s) => s.id)
@@ -172,6 +175,9 @@ export function useAgentManagementMode(): boolean {
*/
const RoomStateDisclosure = observer(function RoomStateDisclosure() {
const { navigate } = useNavigate();
+ // The banner over a frozen workspace is the whole explanation.
+ const active = switchServersStore.activeServer;
+ if (active && isFrozenServer(active)) return null;
const signedOut = switchRoomsStore.workspacesNotSignedIn;
const failed = switchRoomsStore.workspacesThatFailedToLoad;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
index d21018db3..e645a15c5 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
@@ -42,6 +42,10 @@ vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
loadRoomNames: vi.fn().mockResolvedValue(undefined),
},
}));
+const availability = vi.hoisted(() => ({ value: 'available' }));
+vi.mock('@renderer/features/switch-servers/server-availability', () => ({
+ serverAvailability: () => availability.value,
+}));
vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
workspacesStore: { activeId: 'workspace-1' },
}));
@@ -67,6 +71,16 @@ describe('agent icon backfill reporting', () => {
beforeEach(() => {
toast.mockClear();
backfillAgentIcons.mockReset();
+ availability.value = 'available';
+ });
+
+ it('does not try, or complain, while the server this Console runs is not running', async () => {
+ availability.value = 'dormant';
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await vi.waitFor(() => expect(backfillAgentIcons).not.toHaveBeenCalled());
+ expect(toast).not.toHaveBeenCalled();
});
it('reports a workspace without the icon endpoint once, not on every refresh', async () => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
index 71f2ec223..38bf9ed01 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -1,6 +1,7 @@
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import type { LocationStore } from '@renderer/features/locations/stores/location';
import type { SessionStore } from '@renderer/features/sessions/stores/session-store';
+import { serverAvailability } from '@renderer/features/switch-servers/server-availability';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { toast } from '@renderer/lib/hooks/use-toast';
@@ -168,7 +169,18 @@ export async function refreshSidebarRoomStateAfterOnboarding(): Promise<void> {
* lettered picture with nothing explaining why.
*/
async function giveExistingAgentsAnIcon(): Promise<void> {
- const workspaceIds = new Set(switchIdentities().map((identity) => identity.workspaceId));
+ // A server this Console runs that is not running has nothing to store them
+ // in yet; its workspace is frozen and says so, and they are saved once it is up.
+ const dormant = new Set(
+ agentsInActiveScope()
+ .filter(({ agent }) => agent.serverId && serverAvailability(agent.serverId) === 'dormant')
+ .map(({ agent }) => agent.workspaceId)
+ );
+ const workspaceIds = new Set(
+ switchIdentities()
+ .map((identity) => identity.workspaceId)
+ .filter((workspaceId) => !dormant.has(workspaceId))
+ );
for (const workspaceId of workspaceIds) {
try {
reportBackfill(workspaceId, await rpc.workspaces.backfillAgentIcons(workspaceId));
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
index 30b5d11a9..d45cc5f0e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
@@ -1,9 +1,12 @@
-import { Bot, DoorOpen, FileText, House } from 'lucide-react';
+import { Bot, DoorOpen, FileText, House, Server } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useRoomHealth } from '@renderer/features/switch-rooms/connection-health';
+import { ManagedServerDot } from '@renderer/features/switch-servers/managed-server-dot';
+import { FROZEN, isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { isCurrentView, useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
import { useWorkspaceSlots } from '@renderer/lib/layout/workspace-slots';
+import { cn } from '@renderer/utils/utils';
import { connectionNeedsAttention } from '@shared/core/switch-rooms/connection-health';
import { SidebarMenu, SidebarMenuButton } from './sidebar-primitives';
@@ -21,17 +24,32 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
const { params: agentsParams } = useParams('serverAgents');
const { params: roomsParams } = useParams('serverRooms');
const { params: templatesParams } = useParams('templates');
+ const { params: managedServerParams } = useParams('managedServer');
const active = switchServersStore.activeServer;
const health = useRoomHealth(active?.id ?? null);
const warningCount =
health.data?.agents.filter((agent) => connectionNeedsAttention(agent.state)).length ?? 0;
if (!active) return null;
+ // While the server can't answer, only the way to it stays live.
+ const frozen = isFrozenServer(active);
const destinations = [
{ view: 'server', icon: House, label: 'Home', params: homeParams },
{ view: 'serverAgents', icon: Bot, label: 'Your Agents', params: agentsParams },
{ view: 'serverRooms', icon: DoorOpen, label: 'Your Rooms', params: roomsParams },
{ view: 'templates', icon: FileText, label: 'Templates', params: templatesParams },
+ // Only for a server this Console runs: the others are run by someone else,
+ // and there is nothing here to start, stop or update.
+ ...(active.managed
+ ? [
+ {
+ view: 'managedServer',
+ icon: Server,
+ label: 'Server',
+ params: managedServerParams,
+ } as const,
+ ]
+ : []),
] as const;
return (
@@ -41,9 +59,15 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
key={view}
isActive={isCurrentView(currentView, view) && params?.serverId === active.id}
onClick={() => navigate(view, { serverId: active.id })}
+ className={cn(frozen && view !== 'managedServer' && FROZEN)}
>
<Icon className="size-[15px] shrink-0" />
{label}
+ {view === 'managedServer' && (
+ <span className="ml-auto flex items-center pr-0.5">
+ <ManagedServerDot server={active} size={7} />
+ </span>
+ )}
{view === 'serverAgents' && (warningCount > 0 || health.isError) && (
<span
className="ml-auto text-xs text-foreground-warning"
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/connection-health.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/connection-health.tsx
index b40d2ab7f..557d39259 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/connection-health.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/connection-health.tsx
@@ -1,6 +1,9 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { AlertTriangle, CirclePause, Loader2 } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
+import { isFrozenServer } from '@renderer/features/switch-servers/managed-server-state';
+import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { events, rpc } from '@renderer/lib/ipc';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
@@ -46,7 +49,7 @@ export function useAgentConnection(agent: Agent | null) {
const health = query.data?.agents.find((entry) => entry.agentId === agent?.id);
return { query, health, state: query.isError ? ('unknown' as const) : health?.state };
}
-export function AgentConnectionIndicator({
+export const AgentConnectionIndicator = observer(function AgentConnectionIndicator({
agent,
showLabel = false,
}: {
@@ -55,6 +58,10 @@ export function AgentConnectionIndicator({
}) {
const { navigate } = useNavigate();
const { query, health, state } = useAgentConnection(agent);
+ // While its server is not running, the workspace's banner already says why
+ // nothing connects; a spinner on every agent would only repeat it.
+ const server = agent.serverId ? switchServersStore.serverById(agent.serverId) : null;
+ if (server && isFrozenServer(server)) return null;
if (!agent.switchAgentId || !state || (!showLabel && state === 'connected')) return null;
const attention = connectionNeedsAttention(state);
const label = connectionLabels[state];
@@ -88,4 +95,4 @@ export function AgentConnectionIndicator({
</TooltipContent>
</Tooltip>
);
-}
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
deleted file mode 100644
index 4927682f1..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/LocalServerControls.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { 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 { Spinner } from '@renderer/lib/ui/spinner';
-import { Switch } from '@renderer/lib/ui/switch';
-import { CHECKOUT_IMAGE_TAG } from '@shared/core/managed-switch-server/managed-switch-server';
-import { localServerStore } from './local-server-store';
-import { LogTail } from './log-tail';
-import { phaseLabel, StackAction, StackSection, StackStatusRow } from './server-stack-section';
-
-/**
- * Lifecycle for the managed local Switch stack: live status, Docker guidance,
- * and start / restart / stop. Rendered as its own section of the server's page;
- * resetting it lives at the bottom of that page rather than here.
- */
-export const LocalServerControls = observer(function LocalServerControls() {
- const store = localServerStore;
- const [showActivity, setShowActivity] = useState(false);
-
- useEffect(() => {
- void store.checkDocker();
- }, [store]);
-
- const transitioning = store.isTransitioning;
- const dockerUnavailable = store.docker && !store.docker.available ? store.docker : null;
- // Report the version the stack is actually on, not the one this build wants —
- // they diverge exactly when the page's drift notice 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 = store.drift?.direction === 'downgrade';
- // Dev builds run from a Switch checkout only; null everywhere else.
- const checkout = store.checkoutBuild;
- const runsCheckoutBuild = store.status?.deployedVersion === CHECKOUT_IMAGE_TAG;
- // The toggle applies from the next start on, so say so while the containers
- // are still the ones the previous choice produced.
- const restartToApply =
- checkout !== null && store.isRunning && checkout.enabled !== runsCheckoutBuild;
-
- return (
- <StackSection>
- <StackStatusRow
- title="Local server"
- phase={store.phase}
- summary={store.isRunning ? 'Running on this computer' : phaseLabel(store.phase)}
- versionDetail={
- runsCheckoutBuild && checkout
- ? `switch-core built from ${checkout.root}`
- : runningVersion
- ? `switch-core ${runningVersion}`
- : null
- }
- activity={
- store.logs.length > 0 ? (
- <button
- type="button"
- onClick={() => setShowActivity((s) => !s)}
- className="text-foreground-muted underline-offset-2 transition-colors hover:text-foreground hover:underline"
- >
- {showActivity ? 'Hide activity' : 'Recent activity'}
- </button>
- ) : null
- }
- actions={
- store.isRunning ? (
- <>
- <StackAction
- label="Restart"
- disabled={transitioning}
- onClick={() => void store.start()}
- />
- <StackAction
- label="Stop"
- danger
- disabled={transitioning}
- onClick={() => void store.stop()}
- />
- </>
- ) : (
- <StackAction
- label={store.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}
- disabled={transitioning || downgradeBlocked}
- onClick={() => void store.start()}
- />
- )
- }
- />
-
- <div className="space-y-3">
- {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>{store.error}</AlertTitle>
- {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
- </Alert>
- )}
-
- {/* Dev builds launched from a Switch checkout only — a released build
- never has a source tree to build from, so the row is absent rather
- than disabled. */}
- {checkout && (
- <div className="flex items-start justify-between gap-3 rounded-md border border-dashed border-border p-3">
- <div className="min-w-0">
- <p className="text-sm text-foreground">Build switch-core from this checkout</p>
- <p className="mt-0.5 text-xs text-foreground-muted">
- Dev builds only. Builds the switch, gateway and setup images from{' '}
- <span className="font-mono break-all">{checkout.root}</span> on every start, instead
- of pulling switch-core {store.status?.version}. They are tagged{' '}
- <span className="font-mono">{CHECKOUT_IMAGE_TAG}</span> so they can't be mistaken
- for a release.
- {restartToApply && ' Restart the server to apply.'}
- </p>
- </div>
- <Switch
- checked={checkout.enabled}
- disabled={transitioning}
- onCheckedChange={(enabled) => void store.setCheckoutBuild(enabled)}
- aria-label="Build switch-core from this checkout"
- />
- </div>
- )}
-
- {/* Behind the disclosure rather than shown the moment there is output:
- the log is what you go looking for, not what the section is for. */}
- {showActivity && store.logs.length > 0 && <LogTail lines={store.logs} placeholder={null} />}
- </div>
- </StackSection>
- );
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
deleted file mode 100644
index 02550033d..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/RemoteServerControls.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-import { Info, 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 { Spinner } from '@renderer/lib/ui/spinner';
-import { othersRecentlySeen } from '@shared/core/managed-switch-server/managed-switch-server';
-import { LogTail } from './log-tail';
-import { remoteServerStore } from './remote-server-store';
-import { phaseLabel, StackAction, StackSection, StackStatusRow } from './server-stack-section';
-import { useSharedActionConfirm } from './shared-action-confirm';
-import { sharedWithSentence } from './shared-consoles';
-
-/**
- * Lifecycle for a managed Switch stack running in Docker on an SSH host. The
- * same section as the local one, reading through per-host accessors; resetting
- * it lives at the bottom of the server's page rather than here.
- */
-export const RemoteServerControls = observer(function RemoteServerControls({
- sshHost,
- name,
-}: {
- sshHost: string;
- name: string;
-}) {
- const store = remoteServerStore;
- const [showActivity, setShowActivity] = useState(false);
- const confirm = useSharedActionConfirm(sshHost);
-
- useEffect(() => {
- void store.init();
- void store.checkDocker(sshHost);
- void store.loadRegister(sshHost);
- // Someone else may have started or removed a stack shown as stopped.
- void store.refresh(sshHost);
- }, [store, sshHost]);
-
- // A remote stack is shared: stopping or restarting it here does so for everyone.
- const others = othersRecentlySeen(store.registerFor(sshHost), new Date());
-
- const status = store.statusFor(sshHost);
- const hostBlocked = store.isHostBlocked(sshHost);
- // Every lifecycle action rides the host's SSH connection, so none of them can
- // succeed while it is down — disable rather than let them fail (CHOO-1780).
- const transitioning = store.isTransitioning(sshHost) || hostBlocked;
- const running = store.isRunning(sshHost);
- const docker = store.dockerFor(sshHost);
- const dockerUnavailable = docker && !docker.available ? docker : null;
- // Report the version the host is actually on, not the one this build wants —
- // they diverge exactly when the page's drift notice 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 = store.driftFor(sshHost)?.direction === 'downgrade';
- const logs = store.logsFor(sshHost);
-
- return (
- <StackSection>
- <StackStatusRow
- title={`Server on ${sshHost}`}
- phase={hostBlocked ? 'unreachable' : status.phase}
- summary={
- running ? `Running on ${sshHost}` : phaseLabel(hostBlocked ? 'unreachable' : status.phase)
- }
- versionDetail={runningVersion ? `switch-core ${runningVersion}` : null}
- activity={
- logs.length > 0 ? (
- <button
- type="button"
- onClick={() => setShowActivity((s) => !s)}
- className="text-foreground-muted underline-offset-2 transition-colors hover:text-foreground hover:underline"
- >
- {showActivity ? 'Hide activity' : 'Recent activity'}
- </button>
- ) : null
- }
- actions={
- running ? (
- <>
- <StackAction
- label="Restart"
- disabled={transitioning}
- onClick={() => confirm.request('restart', () => void store.start(sshHost, name))}
- />
- <StackAction
- label="Stop"
- danger
- disabled={transitioning}
- onClick={() => confirm.request('stop', () => void store.stop(sshHost))}
- />
- </>
- ) : (
- <StackAction
- label={status.phase === 'error' && !downgradeBlocked ? 'Retry' : 'Start'}
- disabled={transitioning || downgradeBlocked}
- onClick={() => void store.start(sshHost, name)}
- />
- )
- }
- />
-
- <div className="space-y-3">
- {sharedWithSentence(others) && (
- <p className="text-xs text-foreground-muted">{sharedWithSentence(others)}</p>
- )}
-
- {status.notice && !transitioning && (
- <Alert>
- <Info className="size-4" />
- <AlertTitle>{status.notice}</AlertTitle>
- </Alert>
- )}
-
- {status.recordWarning && !transitioning && (
- <Alert>
- <TriangleAlert className="size-4 text-amber-500" />
- <AlertTitle>{status.recordWarning}</AlertTitle>
- </Alert>
- )}
-
- {status.message && transitioning && (
- <div className="flex items-center gap-2 text-sm text-foreground-muted">
- <Spinner className="size-3.5" />
- <span>{status.message}</span>
- {/* Only a wait for another Console can be cancelled: nothing has
- been changed yet. */}
- {status.waitingFor && (
- <button
- type="button"
- onClick={() => void store.cancelWait(sshHost)}
- className="text-foreground-muted underline underline-offset-2 transition-colors hover:text-foreground"
- >
- Stop waiting
- </button>
- )}
- </div>
- )}
-
- {dockerUnavailable && (
- <Alert variant="destructive">
- <TriangleAlert className="size-4" />
- <AlertTitle>
- {dockerUnavailable.reason === 'not-installed'
- ? 'Docker is not installed on the host'
- : 'Docker is not running on the host'}
- </AlertTitle>
- <AlertDescription>{dockerUnavailable.detail}</AlertDescription>
- </Alert>
- )}
-
- {store.error && !dockerUnavailable && (
- <Alert variant="destructive">
- <AlertTitle>{store.error}</AlertTitle>
- {store.errorDetail && <AlertDescription>{store.errorDetail}</AlertDescription>}
- </Alert>
- )}
-
- {/* Behind the disclosure rather than shown the moment there is output:
- the log is what you go looking for, not what the section is for. */}
- {showActivity && logs.length > 0 && <LogTail lines={logs} placeholder={null} />}
- </div>
-
- {confirm.dialog}
- </StackSection>
- );
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsx
deleted file mode 100644
index 78a253629..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/VersionDriftNotice.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import { ArrowUpCircle, Play, RefreshCw, TriangleAlert } from 'lucide-react';
-import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';
-import { Button } from '@renderer/lib/ui/button';
-import { Spinner } from '@renderer/lib/ui/spinner';
-import {
- type ManagedServerUpgrade,
- type SwitchVersionDrift,
- switchVersionDowngradeMessage,
-} from '@shared/core/managed-switch-server/managed-switch-server';
-
-const RESUME_NOTE = 'Sessions on this server resume once the update finishes.';
-
-/**
- * Surfaces a managed stack whose switch-core version no longer matches the one
- * this build of Switch Console pins (CHOO-1736).
- *
- * A stack that is behind the pin is upgraded by Console on its own, so for that
- * case this is mostly a status rather than an offer: the update in progress,
- * the error it failed with (and a retry), or — for a stopped stack — that
- * starting it will update it. The exception is a running shared server others
- * have used lately, which is updated only when someone here says so, naming
- * who it reaches. Sessions on the server wait for it either way.
- *
- * 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,
- upgrade,
- progress,
- disabled,
- affected,
- onRestart,
-}: {
- drift: SwitchVersionDrift | null;
- /** The upgrade the stack owes this build, if any. */
- upgrade: ManagedServerUpgrade | null;
- /** Who else an update of a shared server reaches, when anyone does. */
- affected: string | null;
- /** The current step of a start in flight ("Pulling images…"), or null. */
- progress: string | null;
- /** True while a lifecycle operation is in flight (or the host is unreachable). */
- disabled: boolean;
- /** Restart the stack; for an owed upgrade this is what runs it. */
- onRestart: () => void;
-}) {
- if (upgrade) {
- return (
- <ServerUpgradeNotice
- upgrade={upgrade}
- progress={progress}
- disabled={disabled}
- affected={affected}
- onRetry={onRestart}
- />
- );
- }
- if (!drift) return null;
-
- // We could not read what is deployed. No action offered: restarting on the
- // strength of a failed probe could just as easily be a downgrade, and there
- // is nothing here to prove otherwise (CHOO-1865).
- if (drift.direction === 'unreadable') {
- return (
- <Alert variant="warning">
- <TriangleAlert className="size-4" />
- <AlertTitle>Can't tell which switch-core this is running</AlertTitle>
- <AlertDescription>
- {`This app expects ${drift.expected}, but the deployed version could not be read (${drift.reason}). Nothing is known about whether it matches.`}
- </AlertDescription>
- </Alert>
- );
- }
-
- if (drift.direction === 'downgrade') {
- return (
- <Alert variant="destructive">
- <TriangleAlert className="size-4" />
- <AlertTitle>This server is newer than Switch Console</AlertTitle>
- <AlertDescription>
- {switchVersionDowngradeMessage(drift.deployed, drift.expected)}
- </AlertDescription>
- </Alert>
- );
- }
-
- // Behind, but no update recorded yet: the check that starts it is still
- // running.
- if (drift.direction === 'upgrade') {
- return (
- <Alert variant="warning">
- <ArrowUpCircle className="size-4" />
- <AlertTitle>{`switch-core ${drift.expected} is required`}</AlertTitle>
- <AlertDescription>
- {`Still on switch-core ${drift.deployed}. Switch Console updates this server before running sessions on it. ${RESUME_NOTE}`}
- </AlertDescription>
- </Alert>
- );
- }
-
- return (
- <Alert variant="warning">
- <TriangleAlert className="size-4" />
- <AlertTitle>Version mismatch</AlertTitle>
- <AlertDescription>
- {`Runs switch-core ${drift.deployed}; this app expects ${drift.expected}. Can't tell which is newer — restart only if ${drift.expected} isn't older.`}
- </AlertDescription>
- <AlertAction>
- <Button size="sm" disabled={disabled} onClick={onRestart}>
- <RefreshCw className="size-4" />
- Restart to update
- </Button>
- </AlertAction>
- </Alert>
- );
-}
-
-/** The state of an upgrade Console is running (or owes) for a managed stack. */
-export function ServerUpgradeNotice({
- upgrade,
- progress,
- disabled,
- affected,
- onRetry,
-}: {
- upgrade: ManagedServerUpgrade;
- progress: string | null;
- disabled: boolean;
- affected: string | null;
- onRetry: () => void;
-}) {
- const versions = `switch-core ${upgrade.from} → ${upgrade.to}`;
- if (upgrade.state === 'updating') {
- return (
- <Alert role="status" aria-live="polite">
- <Spinner size="sm" />
- <AlertTitle>{`Updating ${versions}…`}</AlertTitle>
- <AlertDescription>
- <p>{`${RESUME_NOTE} Rooms and messages are kept, and the database is backed up before it is migrated.`}</p>
- {progress && <p className="text-foreground-muted">{progress}</p>}
- </AlertDescription>
- </Alert>
- );
- }
- if (upgrade.state === 'failed') {
- return (
- <Alert variant="destructive" role="alert">
- <TriangleAlert className="size-4" />
- <AlertTitle>{`Updating ${versions} failed`}</AlertTitle>
- <AlertDescription>
- <p className="break-words">{upgrade.error}</p>
- <p>Sessions on this server stay paused until the update succeeds.</p>
- </AlertDescription>
- <AlertAction>
- <Button size="sm" disabled={disabled} onClick={onRetry}>
- <RefreshCw className="size-4" />
- Retry
- </Button>
- </AlertAction>
- </Alert>
- );
- }
- if (upgrade.state === 'held') {
- return (
- <Alert variant="warning">
- <ArrowUpCircle className="size-4" />
- <AlertTitle>{`switch-core ${upgrade.to} is required`}</AlertTitle>
- <AlertDescription>
- <p>{`This server runs switch-core ${upgrade.from}. Others use it too, so Switch Console has not updated it on its own: updating restarts it for everyone. Its rooms, agents and data are kept, and the database is backed up first.`}</p>
- {affected && <p>{affected}</p>}
- <p>{RESUME_NOTE}</p>
- </AlertDescription>
- <AlertAction>
- <Button size="sm" disabled={disabled} onClick={onRetry}>
- <RefreshCw className="size-4" />
- Update for everyone
- </Button>
- </AlertAction>
- </Alert>
- );
- }
- return (
- <Alert variant="warning">
- <ArrowUpCircle className="size-4" />
- <AlertTitle>{`switch-core ${upgrade.to} is required`}</AlertTitle>
- <AlertDescription>
- {`This server is stopped on switch-core ${upgrade.from}. Starting it updates it to ${upgrade.to} first. ${RESUME_NOTE}`}
- </AlertDescription>
- <AlertAction>
- <Button size="sm" disabled={disabled} onClick={onRetry}>
- <Play className="size-4" />
- Start and update
- </Button>
- </AlertAction>
- </Alert>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/frozen-workspace.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/frozen-workspace.tsx
new file mode 100644
index 000000000..235752b8b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/frozen-workspace.tsx
@@ -0,0 +1,114 @@
+import { Power } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import type { ViewId } from '@renderer/app/view-registry';
+import { useNavigate } from '@renderer/lib/layout/navigation-provider';
+import { cn } from '@renderer/utils/utils';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { managedServerProgress, startManagedServer } from './managed-server-actions';
+import { TONE_BOX, ToneDot } from './managed-server-dot';
+import {
+ type ManagedServerState,
+ isFrozenServer,
+ managedServerState,
+} from './managed-server-state';
+import { PrimaryButton } from './server-page-ui';
+import { switchServersStore } from './switch-servers-store';
+
+/**
+ * Views that stay usable while the workspace's server can't answer: the
+ * server's own page, which is where it is started, and the ones that are not
+ * about the workspace at all.
+ */
+const NEVER_FROZEN: ReadonlySet<ViewId> = new Set<ViewId>([
+ 'managedServer',
+ 'settings',
+ 'home',
+ 'remoteHosts',
+ 'remoteHost',
+]);
+
+/** The active workspace's server when it is frozen and the view is one it
+ * freezes, else null. */
+export function frozenServer(viewId: ViewId): SwitchServer | null {
+ if (NEVER_FROZEN.has(viewId)) return null;
+ const server = switchServersStore.activeServer;
+ return server && isFrozenServer(server) ? server : null;
+}
+
+/** What the banner says. Plain, and about what you can't do rather than why. */
+export function frozenSentence(server: SwitchServer, state: ManagedServerState): string {
+ const name = server.name;
+ switch (state.reason) {
+ case 'starting':
+ return `${name} is starting. Agents and rooms come back once it's running.`;
+ case 'updating':
+ return `${name} is updating. Agents and rooms come back once it's done.`;
+ case 'stopping':
+ return `${name} is stopping.`;
+ case 'waiting':
+ return `Another Console is busy with ${name}. Agents and rooms come back once it's done.`;
+ case 'busy':
+ return `${name} is busy. Agents and rooms come back once it's running.`;
+ case 'host-unreachable':
+ return `Can't reach ${server.sshHost ?? name}, so agents and rooms are unavailable.`;
+ case 'update-failed':
+ return `${name} couldn't be updated, so agents and rooms are unavailable.`;
+ case 'downgrade':
+ return `${name} runs a newer switch-core than this app, so it can't be started from here.`;
+ case 'docker-unavailable':
+ return `Docker isn't running, so ${name} can't start.`;
+ case 'start-failed':
+ return `${name} couldn't start, so agents and rooms are unavailable.`;
+ case 'stop-failed':
+ return `${name} didn't stop cleanly, so agents and rooms are unavailable.`;
+ case 'reset-failed':
+ return `The reset of ${name} didn't finish, so agents and rooms are unavailable.`;
+ default:
+ return `${name} isn't running, so agents and rooms are unavailable.`;
+ }
+}
+
+/**
+ * Across the top of a frozen workspace: what is wrong, the way to the server's
+ * page, and Start when starting is all it takes. Nothing to press while it is
+ * already changing state, and no Start after a failure: the page says why it
+ * failed, and starting blind would only fail again.
+ */
+export const FrozenBanner = observer(function FrozenBanner({ server }: { server: SwitchServer }) {
+ const { navigate } = useNavigate();
+ const state = managedServerState(server);
+ if (!state) return null;
+ const progress = state.tone === 'working' ? managedServerProgress(server) : null;
+
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ className={cn(
+ 'flex shrink-0 items-center gap-3 border-b-[0.5px] px-4 py-2.5',
+ TONE_BOX[state.tone]
+ )}
+ >
+ <span className="flex w-3 shrink-0 justify-center">
+ <ToneDot tone={state.tone} size={7} />
+ </span>
+ <p className="min-w-0 flex-1 truncate text-[13px] text-foreground">
+ {frozenSentence(server, state)}
+ {progress && <span className="text-[var(--fg-dim)]"> {progress}</span>}
+ </p>
+ <button
+ type="button"
+ onClick={() => navigate('managedServer', { serverId: server.id })}
+ className="shrink-0 rounded-md px-2 py-1 text-[13px] text-[var(--srv-stopped-text)] transition-colors hover:bg-[var(--sel-soft)] hover:text-foreground"
+ >
+ Server details
+ </button>
+ {state.tone === 'stopped' && (
+ <PrimaryButton onClick={() => startManagedServer(server)}>
+ <Power />
+ Start
+ </PrimaryButton>
+ )}
+ </div>
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
index 4210c9e7e..80b2d7568 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts
@@ -8,6 +8,7 @@ import type {
DockerAvailability,
LocalServerStatus,
ManagedServerUpgrade,
+ StartLocalServerResult,
SwitchVersionDrift,
} from '@shared/core/managed-switch-server/managed-switch-server';
import {
@@ -172,6 +173,21 @@ export class LocalServerStore {
}
async start(): Promise<void> {
+ await this.runStart(() => rpc.localSwitchServer.start(), 'Could not start the server.');
+ }
+
+ /** Move whatever publishes on `port` to a free port, then start. */
+ async useAnotherPort(port: number): Promise<void> {
+ await this.runStart(
+ () => rpc.localSwitchServer.useAnotherPort(port),
+ 'Could not move the server to another port.'
+ );
+ }
+
+ private async runStart(
+ call: () => Promise<StartLocalServerResult>,
+ fallback: string
+ ): Promise<void> {
this.pendingLines = [];
if (this.flushTimer) {
clearTimeout(this.flushTimer);
@@ -184,7 +200,7 @@ export class LocalServerStore {
this.logs = [];
});
try {
- const result = await rpc.localSwitchServer.start();
+ const result = await call();
if (result.kind === 'docker-unavailable') {
runInAction(() => {
this.docker = { available: false, reason: result.reason, detail: result.detail };
@@ -202,7 +218,7 @@ export class LocalServerStore {
await switchServersStore.init();
}
} catch (cause) {
- this.setError(cause, 'Could not start the server.');
+ this.setError(cause, fallback);
} finally {
// The command has finished, so nothing more will arrive to trigger a
// flush — the tail's last lines are the ones that say how it went.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-actions.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-actions.ts
new file mode 100644
index 000000000..12b3fe535
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-actions.ts
@@ -0,0 +1,59 @@
+import type { ServerLockHolder } from '@shared/core/managed-switch-server/managed-switch-server';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { localServerStore } from './local-server-store';
+import { remoteServerStore } from './remote-server-store';
+
+/**
+ * A managed server's lifecycle, the same calls whichever store runs it. Kept in
+ * one place so the banner, the switcher and the server page cannot start a
+ * server two different ways.
+ */
+
+function remoteHost(server: SwitchServer): string | null {
+ return server.managementKind === 'remote' ? server.sshHost : null;
+}
+
+/** Start the server, or restart it: re-running the start is also what applies
+ * an update. */
+export function startManagedServer(server: SwitchServer): void {
+ const host = remoteHost(server);
+ if (host) {
+ void remoteServerStore.start(host, server.name);
+ return;
+ }
+ void localServerStore.start();
+}
+
+export function stopManagedServer(server: SwitchServer): void {
+ const host = remoteHost(server);
+ if (host) {
+ void remoteServerStore.stop(host);
+ return;
+ }
+ void localServerStore.stop();
+}
+
+/** What the server is doing right now ("Pulling images…"), or null. */
+export function managedServerProgress(server: SwitchServer): string | null {
+ const host = remoteHost(server);
+ return host ? remoteServerStore.statusFor(host).message : localServerStore.message;
+}
+
+/** Why its last start failed, as the main process reported it, or null. */
+export function managedServerError(server: SwitchServer): string | null {
+ const host = remoteHost(server);
+ const status = host ? remoteServerStore.statusFor(host) : localServerStore.status;
+ return status?.error ?? null;
+}
+
+/** The output of the last start this window saw. */
+export function managedServerLogs(server: SwitchServer): string[] {
+ const host = remoteHost(server);
+ return host ? remoteServerStore.logsFor(host) : localServerStore.logs;
+}
+
+/** The other Console this one is waiting on, or null. */
+export function managedServerWaitingFor(server: SwitchServer): ServerLockHolder | null {
+ const host = remoteHost(server);
+ return host ? remoteServerStore.statusFor(host).waitingFor : null;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-dot.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-dot.tsx
new file mode 100644
index 000000000..351f28fe3
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-dot.tsx
@@ -0,0 +1,86 @@
+import { LoaderCircle } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { cn } from '@renderer/utils/utils';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { type ManagedTone, managedServerState } from './managed-server-state';
+
+export const TONE_DOT: Record<ManagedTone, string> = {
+ running: 'bg-[var(--srv-running)]',
+ working: 'bg-[var(--srv-working)]',
+ attention: 'bg-[var(--srv-working)]',
+ stopped: 'bg-[var(--srv-stopped)]',
+ failed: 'bg-[var(--srv-failed)]',
+};
+
+/** The pill's wash and the text on it. */
+export const TONE_PILL: Record<ManagedTone, string> = {
+ running: 'bg-[var(--srv-running-tint)] text-[var(--srv-running-text)]',
+ working: 'bg-[var(--srv-working-tint)] text-[var(--srv-working-text)]',
+ attention: 'bg-[var(--srv-working-tint)] text-[var(--srv-working-text)]',
+ stopped: 'bg-[var(--srv-stopped-tint)] text-[var(--srv-stopped-text)]',
+ failed: 'bg-[var(--srv-failed-tint)] text-[var(--srv-failed-text)]',
+};
+
+/** A message box or banner: the same hue as the pill, fainter, with a hairline. */
+export const TONE_BOX: Record<ManagedTone, string> = {
+ running: 'border-[var(--srv-stopped-line)] bg-[var(--srv-stopped-box)]',
+ working: 'border-[var(--srv-working-line)] bg-[var(--srv-working-box)]',
+ attention: 'border-[var(--srv-working-line)] bg-[var(--srv-working-box)]',
+ stopped: 'border-[var(--srv-stopped-line)] bg-[var(--srv-stopped-box)]',
+ failed: 'border-[var(--srv-failed-line)] bg-[var(--srv-failed-box)]',
+};
+
+/** The title of a message box, in the box's hue. */
+export const TONE_TITLE: Record<ManagedTone, string> = {
+ running: 'text-foreground',
+ working: 'text-[var(--srv-working-text)]',
+ attention: 'text-[var(--srv-working-text)]',
+ stopped: 'text-foreground',
+ failed: 'text-[var(--srv-failed-text)]',
+};
+
+/** The amber spinner that stands in for a dot while a server changes state. */
+export function WorkingSpinner({ className }: { className?: string }) {
+ return (
+ <LoaderCircle
+ aria-hidden
+ className={cn('size-[11px] shrink-0 animate-spin text-[var(--srv-working)]', className)}
+ />
+ );
+}
+
+export function ToneDot({ tone, size }: { tone: ManagedTone; size: 6 | 7 }) {
+ if (tone === 'working') return <WorkingSpinner />;
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ 'shrink-0 rounded-full',
+ size === 6 ? 'size-1.5' : 'size-[7px]',
+ TONE_DOT[tone]
+ )}
+ />
+ );
+}
+
+/**
+ * A managed server's state as a dot — or a spinner while it changes state —
+ * with no words: the switcher and the sidebar say how a server is with colour
+ * alone. Nothing for a server this Console does not run, or before its state
+ * has been read.
+ */
+export const ManagedServerDot = observer(function ManagedServerDot({
+ server,
+ size,
+}: {
+ server: SwitchServer;
+ size: 6 | 7;
+}) {
+ const state = managedServerState(server);
+ if (!state || !state.known) return null;
+ return (
+ <span role="img" aria-label={state.label} title={state.label} className="flex shrink-0">
+ <ToneDot tone={state.tone} size={size} />
+ </span>
+ );
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.test.ts
new file mode 100644
index 000000000..ff16e6c45
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('./local-server-store', () => ({ localServerStore: {} }));
+vi.mock('./remote-server-store', () => ({ remoteServerStore: {} }));
+
+const { deriveManagedState } = await import('./managed-server-state');
+
+const base = {
+ phase: 'running' as const,
+ checked: true,
+ busy: false,
+ hostBlocked: false,
+ upgrade: null,
+ drift: null,
+ waiting: false,
+ dockerUnavailable: false,
+ failedTo: null,
+};
+
+describe('deriveManagedState', () => {
+ it('is green and answering when running', () => {
+ expect(deriveManagedState(base)).toMatchObject({
+ tone: 'running',
+ label: 'Running',
+ answering: true,
+ known: true,
+ });
+ });
+
+ it('needs attention, but still answers, when an update waits on someone here', () => {
+ const state = deriveManagedState({
+ ...base,
+ upgrade: { state: 'held', from: '0.29.0', to: '0.30.0' },
+ });
+ expect(state).toMatchObject({ tone: 'attention', label: 'Update ready', answering: true });
+ });
+
+ it('is working, and does not answer, while starting, stopping or updating', () => {
+ expect(deriveManagedState({ ...base, phase: 'starting' })).toMatchObject({
+ tone: 'working',
+ answering: false,
+ });
+ expect(deriveManagedState({ ...base, phase: 'stopping' }).label).toBe('Stopping');
+ expect(
+ deriveManagedState({ ...base, upgrade: { state: 'updating', from: '1', to: '2' } }).label
+ ).toBe('Updating');
+ });
+
+ it('still answers while waiting on another Console holding a running server', () => {
+ expect(deriveManagedState({ ...base, waiting: true })).toMatchObject({
+ tone: 'working',
+ answering: true,
+ });
+ expect(deriveManagedState({ ...base, phase: 'stopped', waiting: true }).answering).toBe(false);
+ });
+
+ it('is not known to be stopped until its state has been read', () => {
+ expect(deriveManagedState({ ...base, phase: 'stopped', checked: false })).toMatchObject({
+ tone: 'stopped',
+ known: false,
+ });
+ expect(deriveManagedState({ ...base, phase: 'stopped' }).known).toBe(true);
+ });
+
+ it('is red when it failed, saying which way', () => {
+ expect(deriveManagedState({ ...base, phase: 'error' }).label).toBe('Failed to start');
+ expect(deriveManagedState({ ...base, hostBlocked: true }).label).toBe('Host unreachable');
+ expect(
+ deriveManagedState({
+ ...base,
+ phase: 'error',
+ drift: { deployed: '0.31.0', expected: '0.30.0', direction: 'downgrade' },
+ }).label
+ ).toBe('Newer than this app');
+ expect(
+ deriveManagedState({
+ ...base,
+ upgrade: { state: 'failed', from: '1', to: '2', error: 'x' },
+ })
+ ).toMatchObject({ tone: 'failed', label: 'Update failed', answering: false });
+ expect(deriveManagedState({ ...base, phase: 'error', dockerUnavailable: true }).label).toBe(
+ 'Docker not running'
+ );
+ });
+
+ it('says a stop or a reset that broke partway is that, not a failed start', () => {
+ expect(deriveManagedState({ ...base, phase: 'error', failedTo: 'stop' })).toMatchObject({
+ tone: 'failed',
+ reason: 'stop-failed',
+ label: "Couldn't stop",
+ });
+ expect(deriveManagedState({ ...base, phase: 'error', failedTo: 'reset' }).reason).toBe(
+ 'reset-failed'
+ );
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.ts
new file mode 100644
index 000000000..849c25b25
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-state.ts
@@ -0,0 +1,176 @@
+import type {
+ LocalServerPhase,
+ ManagedServerUpgrade,
+ SwitchVersionDrift,
+} from '@shared/core/managed-switch-server/managed-switch-server';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { localServerStore } from './local-server-store';
+import { remoteServerStore } from './remote-server-store';
+
+/**
+ * The five ways a managed server can be, as a colour:
+ *
+ * - `running` — everything works.
+ * - `working` — starting, stopping, updating, or another Console is busy with it.
+ * - `attention` — running, but something is waiting on you, such as an update.
+ * - `stopped` — not running.
+ * - `failed` — failed to start or update, or can't be managed from here.
+ */
+export type ManagedTone = 'running' | 'working' | 'attention' | 'stopped' | 'failed';
+
+/** Why a server has its tone. The page and the banner word each one. */
+export type ManagedReason =
+ | 'running'
+ | 'starting'
+ | 'stopping'
+ | 'updating'
+ | 'waiting'
+ | 'busy'
+ | 'update-ready'
+ | 'version-mismatch'
+ | 'version-unknown'
+ | 'stopped'
+ | 'host-unreachable'
+ | 'update-failed'
+ | 'downgrade'
+ | 'docker-unavailable'
+ | 'start-failed'
+ | 'stop-failed'
+ | 'reset-failed';
+
+const REASON: Record<ManagedReason, { tone: ManagedTone; label: string; answering: boolean }> = {
+ running: { tone: 'running', label: 'Running', answering: true },
+ starting: { tone: 'working', label: 'Starting', answering: false },
+ stopping: { tone: 'working', label: 'Stopping', answering: false },
+ updating: { tone: 'working', label: 'Updating', answering: false },
+ // Answering is decided by the phase: another Console may hold a running server.
+ waiting: { tone: 'working', label: 'Waiting', answering: false },
+ busy: { tone: 'working', label: 'Working', answering: false },
+ 'update-ready': { tone: 'attention', label: 'Update ready', answering: true },
+ 'version-mismatch': { tone: 'attention', label: 'Version mismatch', answering: true },
+ 'version-unknown': { tone: 'attention', label: 'Version unknown', answering: true },
+ stopped: { tone: 'stopped', label: 'Not running', answering: false },
+ 'host-unreachable': { tone: 'failed', label: 'Host unreachable', answering: false },
+ 'update-failed': { tone: 'failed', label: 'Update failed', answering: false },
+ downgrade: { tone: 'failed', label: 'Newer than this app', answering: false },
+ 'docker-unavailable': { tone: 'failed', label: 'Docker not running', answering: false },
+ 'start-failed': { tone: 'failed', label: 'Failed to start', answering: false },
+ 'stop-failed': { tone: 'failed', label: "Couldn't stop", answering: false },
+ 'reset-failed': { tone: 'failed', label: 'Reset failed', answering: false },
+};
+
+export type ManagedServerState = {
+ tone: ManagedTone;
+ reason: ManagedReason;
+ /** The words on the server page's pill. Never shown in the switcher. */
+ label: string;
+ /**
+ * Whether the server can answer. A workspace on a server that cannot is
+ * frozen; one that needs attention still works, so it is not.
+ */
+ answering: boolean;
+ /**
+ * False until the server's state has been read since launch. A stack that
+ * has not been looked at yet is not known to be stopped, so nothing is
+ * frozen or coloured on its account.
+ */
+ known: boolean;
+};
+
+export type ManagedStateInput = {
+ phase: LocalServerPhase;
+ checked: boolean;
+ /** An action this window asked for is in flight. */
+ busy: boolean;
+ hostBlocked: boolean;
+ upgrade: ManagedServerUpgrade | null;
+ drift: SwitchVersionDrift | null;
+ /** Waiting for another Console to finish with the server. */
+ waiting: boolean;
+ dockerUnavailable: boolean;
+ /** What broke, when an error is from a stop or a reset rather than a start. */
+ failedTo: 'stop' | 'reset' | null;
+};
+
+function stateFor(reason: ManagedReason, known: boolean): ManagedServerState {
+ return { reason, ...REASON[reason], known };
+}
+
+function reasonFor(input: ManagedStateInput): ManagedReason {
+ const { phase, upgrade, drift } = input;
+ if (input.hostBlocked) return 'host-unreachable';
+ if (upgrade?.state === 'updating') return 'updating';
+ if (phase === 'starting') return 'starting';
+ if (phase === 'stopping') return 'stopping';
+ if (input.waiting) return 'waiting';
+ if (input.busy) return 'busy';
+ if (phase === 'error') {
+ if (input.failedTo === 'stop') return 'stop-failed';
+ if (input.failedTo === 'reset') return 'reset-failed';
+ if (drift?.direction === 'downgrade') return 'downgrade';
+ if (upgrade?.state === 'failed') return 'update-failed';
+ if (input.dockerUnavailable) return 'docker-unavailable';
+ return 'start-failed';
+ }
+ if (upgrade?.state === 'failed') return 'update-failed';
+ if (phase === 'running') {
+ if (upgrade?.state === 'held') return 'update-ready';
+ if (drift?.direction === 'unknown') return 'version-mismatch';
+ if (drift?.direction === 'unreadable') return 'version-unknown';
+ return 'running';
+ }
+ return 'stopped';
+}
+
+export function deriveManagedState(input: ManagedStateInput): ManagedServerState {
+ const reason = reasonFor(input);
+ const state = stateFor(reason, reason !== 'stopped' || input.checked);
+ return reason === 'waiting' ? { ...state, answering: input.phase === 'running' } : state;
+}
+
+/** The state of a server this Console runs, or null for any other server. */
+export function managedServerState(server: SwitchServer): ManagedServerState | null {
+ if (!server.managed) return null;
+ if (server.managementKind === 'remote') {
+ if (!server.sshHost) return null;
+ const host = server.sshHost;
+ const status = remoteServerStore.statusFor(host);
+ const docker = remoteServerStore.dockerFor(host);
+ return deriveManagedState({
+ phase: status.phase,
+ checked: status.checked,
+ busy: remoteServerStore.isBusy(host),
+ hostBlocked: remoteServerStore.isHostBlocked(host),
+ upgrade: status.upgrade,
+ drift: status.drift,
+ waiting: status.waitingFor !== null,
+ dockerUnavailable: docker !== null && !docker.available,
+ failedTo: status.failedTo,
+ });
+ }
+ const status = localServerStore.status;
+ if (!status) return stateFor('stopped', false);
+ const docker = localServerStore.docker;
+ return deriveManagedState({
+ phase: status.phase,
+ checked: status.checked,
+ busy: localServerStore.busy,
+ hostBlocked: false,
+ upgrade: status.upgrade,
+ drift: status.drift,
+ waiting: false,
+ dockerUnavailable: docker !== null && !docker.available,
+ failedTo: status.failedTo,
+ });
+}
+
+/** How the parts of a frozen workspace that can't be used are shown: dimmed,
+ * and out of reach of the pointer. */
+export const FROZEN = 'pointer-events-none select-none opacity-[.38]';
+
+/** Whether a workspace on `server` should be frozen: it is managed here, its
+ * state is known, and it cannot answer. */
+export function isFrozenServer(server: SwitchServer): boolean {
+ const state = managedServerState(server);
+ return state !== null && state.known && !state.answering;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-view.tsx
new file mode 100644
index 000000000..68bd69867
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-server-view.tsx
@@ -0,0 +1,712 @@
+import { useQuery } from '@tanstack/react-query';
+import { ArrowUpCircle, Power, Server } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useEffect, useState } from 'react';
+import { type GuardResult, type ViewDefinition } from '@renderer/app/view-registry';
+import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
+import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
+import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
+import { rpc } from '@renderer/lib/ipc';
+import { useParams } from '@renderer/lib/layout/navigation-provider';
+import { Switch } from '@renderer/lib/ui/switch';
+import {
+ CHECKOUT_IMAGE_TAG,
+ type LocalActivityEntry,
+ type StackActivityEntry,
+ othersRecentlySeen,
+ switchVersionDowngradeMessage,
+} from '@shared/core/managed-switch-server/managed-switch-server';
+import { explainStartFailure } from '@shared/core/managed-switch-server/start-failure';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { localServerStore } from './local-server-store';
+import { LogTail } from './log-tail';
+import {
+ managedServerError,
+ managedServerLogs,
+ managedServerProgress,
+ startManagedServer,
+ stopManagedServer,
+} from './managed-server-actions';
+import { WorkingSpinner } from './managed-server-dot';
+import { type ManagedServerState, managedServerState } from './managed-server-state';
+import { managedTelemetryNotice } from './managed-telemetry-notice';
+import { remoteServerStore } from './remote-server-store';
+import { serverIcon } from './server-icon';
+import {
+ ActivityRow,
+ DetailRow,
+ GhostButton,
+ MessageBox,
+ Mono,
+ PrimaryButton,
+ SectionLabel,
+ StatusPill,
+} from './server-page-ui';
+import { ServerResetSection } from './server-reset-section';
+import { ServerSectionTitlebar } from './server-section-titlebar';
+import { activityWhen, agoLabel, sinceLabel } from './server-times';
+import { useSharedActionConfirm } from './shared-action-confirm';
+import { namesOf, selfDesktop, sharedWithSentence } from './shared-consoles';
+import { switchServersStore } from './switch-servers-store';
+import { TelemetryConsentNotice } from './TelemetryConsentNotice';
+
+const ACTIVITY_SHOWN = 5;
+
+function useServerId(): string {
+ return useParams('managedServer').params.serverId;
+}
+
+const ManagedServerTitlebar = observer(function ManagedServerTitlebar() {
+ return <ServerSectionTitlebar serverId={useServerId()} icon={Server} label="Server" />;
+});
+
+/** One line of recent activity, from either kind of record. */
+type ActivityItem = { key: string; what: string; who: string | null; at: string };
+
+const LOCAL_WHAT: Record<LocalActivityEntry['action'], (detail: string | null) => string> = {
+ started: () => 'Started',
+ stopped: () => 'Stopped',
+ 'start-failed': () => 'Start failed',
+ updated: (detail) => (detail ? `Updated to ${detail}` : 'Updated'),
+ reset: () => 'Reset',
+};
+
+const REMOTE_WHAT: Record<StackActivityEntry['action'], string> = {
+ started: 'Started',
+ connected: 'Connected',
+ stopped: 'Stopped',
+ reset: 'Reset',
+ disconnected: 'Disconnected',
+};
+
+function NamesInBold({ names }: { names: string[] }) {
+ return (
+ <>
+ {names.map((name, i) => (
+ <span key={name}>
+ {i > 0 && (i === names.length - 1 ? ' and ' : ', ')}
+ <strong className="font-semibold text-foreground">{name}</strong>
+ </span>
+ ))}
+ </>
+ );
+}
+
+const ManagedServerMainPanel = observer(function ManagedServerMainPanel() {
+ const serverId = useServerId();
+ const server = switchServersStore.servers.find((s) => s.id === serverId);
+ if (!server || !server.managed) {
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 overflow-auto bg-background p-6">
+ <p className="text-sm text-foreground-muted">
+ {server
+ ? 'This server is not run by Switch Console.'
+ : 'This server is no longer available.'}
+ </p>
+ </div>
+ );
+ }
+ return <ManagedServerPage server={server} />;
+});
+
+const ManagedServerPage = observer(function ManagedServerPage({
+ server,
+}: {
+ server: SwitchServer;
+}) {
+ const sshHost = server.managementKind === 'remote' ? server.sshHost : null;
+ const confirm = useSharedActionConfirm(sshHost);
+ const [showLog, setShowLog] = useState(false);
+ const { value: telemetry } = useAppSettingsKey('telemetry');
+ const now = new Date();
+
+ useEffect(() => {
+ void hostReachabilityStore.hydrate();
+ if (sshHost) {
+ void remoteServerStore.init();
+ void remoteServerStore.checkDocker(sshHost);
+ void remoteServerStore.loadRegister(sshHost);
+ // Someone else may have started or removed a stack shown as stopped.
+ void remoteServerStore.refresh(sshHost);
+ } else {
+ void localServerStore.checkDocker();
+ }
+ }, [sshHost]);
+
+ const state = managedServerState(server) ?? null;
+ const status = sshHost ? remoteServerStore.statusFor(sshHost) : localServerStore.status;
+ const reason = state?.reason ?? 'stopped';
+ const answering = state?.answering ?? false;
+
+ const startedAt = useQuery({
+ queryKey: ['managed-server-started-at', server.id, reason],
+ queryFn: () =>
+ sshHost ? rpc.remoteSwitchServer.startedAt(sshHost) : rpc.localSwitchServer.startedAt(),
+ enabled: answering,
+ });
+ const localActivity = useQuery({
+ queryKey: ['local-server-activity', reason],
+ queryFn: () => rpc.localSwitchServer.activity(),
+ enabled: sshHost === null,
+ });
+
+ if (!state || !status) return null;
+
+ const register = sshHost ? remoteServerStore.registerFor(sshHost) : null;
+ const others = othersRecentlySeen(register, now);
+ const self = selfDesktop(register);
+ const activity: ActivityItem[] = sshHost
+ ? (register?.activity ?? []).map((entry) => ({
+ key: `${entry.at}-${entry.consoleId}-${entry.action}`,
+ what: REMOTE_WHAT[entry.action],
+ who: entry.consoleId === register?.self ? 'You' : entry.name,
+ at: entry.at,
+ }))
+ : (localActivity.data ?? []).map((entry) => ({
+ key: `${entry.at}-${entry.action}`,
+ what: LOCAL_WHAT[entry.action](entry.detail),
+ who: 'You',
+ at: entry.at,
+ }));
+ const lastStopped = sshHost
+ ? register?.activity.find((entry) => entry.action === 'stopped')?.at
+ : localActivity.data?.find((entry) => entry.action === 'stopped')?.at;
+ const lastFailedAt = sshHost
+ ? undefined
+ : localActivity.data?.find((entry) => entry.action === 'start-failed')?.at;
+
+ const workspaceNames = workspacesStore
+ .onServer(server.id)
+ .filter((w) => w.tenantId !== null)
+ .map((w) => w.name);
+ const logs = managedServerLogs(server);
+ const Icon = serverIcon(server);
+ const placement = sshHost ?? 'This computer';
+ const deployed = status.deployedVersion ?? status.version;
+ const checkout = sshHost ? null : localServerStore.checkoutBuild;
+ const runsCheckout = status.deployedVersion === CHECKOUT_IMAGE_TAG;
+ const working = state.tone === 'working';
+
+ const restart = () => confirm.request('restart', () => startManagedServer(server));
+ const stop = () => confirm.request('stop', () => stopManagedServer(server));
+ // A retry restarts a server still up for anyone else on it, so it asks the
+ // same way; a stopped one reaches nobody.
+ const retry = status.phase === 'running' ? restart : () => startManagedServer(server);
+ const telemetryNotice = managedTelemetryNotice({
+ running: answering,
+ deployed: status.deployedTelemetry,
+ consent: telemetry?.enabled ?? true,
+ sharedWithOthers: confirm.shared,
+ });
+
+ return (
+ <div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">
+ <div className="mx-auto w-full max-w-[720px] space-y-[18px] p-[22px]">
+ <header className="flex items-center gap-3">
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-[10px] bg-[var(--fill)]">
+ <Icon className="size-[18px] text-[var(--srv-stopped-text)]" />
+ </span>
+ <div className="min-w-0">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2 className="truncate text-[17px] font-semibold text-foreground">{server.name}</h2>
+ <StatusPill state={state} />
+ </div>
+ <p className="truncate text-[13px] text-[var(--fg-dim)]">
+ {placement} · runs with Docker
+ </p>
+ </div>
+ </header>
+
+ <Actions
+ server={server}
+ state={state}
+ hasLogs={logs.length > 0}
+ showLog={showLog}
+ onToggleLog={() => setShowLog((shown) => !shown)}
+ onRestart={restart}
+ onRetry={retry}
+ onStop={stop}
+ />
+
+ {sharedWithSentence(others, self) && (
+ <p className="text-[13px] text-[var(--fg-dim)]">{sharedWithSentence(others, self)}</p>
+ )}
+
+ <Messages
+ server={server}
+ state={state}
+ workspaceNames={workspaceNames}
+ othersNames={namesOf(others, self)}
+ lastFailedAt={lastFailedAt ?? null}
+ now={now}
+ />
+
+ {showLog && logs.length > 0 && <LogTail lines={logs} placeholder={null} />}
+
+ {telemetryNotice && (
+ <TelemetryConsentNotice notice={telemetryNotice} disabled={working} onRestart={restart} />
+ )}
+
+ <section>
+ <SectionLabel>Details</SectionLabel>
+ <div className="mt-1">
+ <DetailRow label="switch-core">
+ {runsCheckout && checkout ? (
+ <span className="font-[Menlo,ui-monospace,monospace] text-[11.5px]">
+ built from {checkout.root}
+ </span>
+ ) : reason === 'update-ready' && status.upgrade ? (
+ <span className="text-[var(--srv-working-text)]">
+ {status.upgrade.from} → {status.upgrade.to}
+ </span>
+ ) : state.tone === 'running' && !status.upgrade && !status.drift ? (
+ `${deployed} · up to date`
+ ) : (
+ deployed
+ )}
+ </DetailRow>
+ {answering && startedAt.data && (
+ <DetailRow label="Running since">{sinceLabel(startedAt.data, now)}</DetailRow>
+ )}
+ {!answering && !working && lastStopped && (
+ <DetailRow label="Last running">{agoLabel(lastStopped, now)}</DetailRow>
+ )}
+ {workspaceNames.length > 0 && (
+ <DetailRow label="Workspaces">
+ {workspaceNames.join(', ')}
+ {working ? ' · available once running' : !answering ? ' · unavailable' : ''}
+ </DetailRow>
+ )}
+ </div>
+ </section>
+
+ {(activity.length > 0 || localActivity.isError) && (
+ <section>
+ <SectionLabel>Recent activity</SectionLabel>
+ <div className="mt-1">
+ {localActivity.isError && (
+ <p className="py-[7px] text-[13px] text-[var(--fg-dim)]">
+ Couldn't read this server's history.
+ </p>
+ )}
+ {activity.slice(0, ACTIVITY_SHOWN).map((item) => (
+ <ActivityRow
+ key={item.key}
+ what={item.what}
+ when={`${item.who ? `${item.who} · ` : ''}${activityWhen(item.at, now)}`}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+
+ {/* Dev builds launched from a Switch checkout only. */}
+ {checkout && (
+ <div className="flex items-start justify-between gap-3 rounded-[10px] border-[0.5px] border-dashed border-[var(--hair-strong)] px-[14px] py-3">
+ <div className="min-w-0">
+ <p className="text-[13px] text-foreground">Build switch-core from this checkout</p>
+ <p className="mt-0.5 text-xs text-[var(--fg-dim)]">
+ Dev builds only. Builds the images from{' '}
+ <span className="font-mono break-all">{checkout.root}</span> on every start instead
+ of pulling switch-core {status.version}.
+ {answering && checkout.enabled !== runsCheckout && ' Restart the server to apply.'}
+ </p>
+ </div>
+ <Switch
+ checked={checkout.enabled}
+ disabled={working}
+ onCheckedChange={(enabled) => void localServerStore.setCheckoutBuild(enabled)}
+ aria-label="Build switch-core from this checkout"
+ />
+ </div>
+ )}
+
+ <ServerResetSection
+ dialogTitle={sshHost ? `Reset server on ${sshHost}` : 'Reset server on this computer'}
+ shared={sshHost !== null}
+ affected={confirm.who}
+ disabled={working}
+ onConfirm={() => {
+ if (sshHost) {
+ void remoteServerStore.reset(sshHost);
+ return;
+ }
+ void localServerStore.reset();
+ }}
+ />
+ {confirm.dialog}
+ </div>
+ </div>
+ );
+});
+
+/** The buttons under the name. At most one is primary. */
+const Actions = observer(function Actions({
+ server,
+ state,
+ hasLogs,
+ showLog,
+ onToggleLog,
+ onRestart,
+ onRetry,
+ onStop,
+}: {
+ server: SwitchServer;
+ state: ManagedServerState;
+ hasLogs: boolean;
+ showLog: boolean;
+ onToggleLog: () => void;
+ onRestart: () => void;
+ onRetry: () => void;
+ onStop: () => void;
+}) {
+ const sshHost = server.managementKind === 'remote' ? server.sshHost : null;
+ const logButton = hasLogs && (
+ <GhostButton onClick={onToggleLog}>{showLog ? 'Hide log' : 'Show log'}</GhostButton>
+ );
+
+ switch (state.reason) {
+ case 'running':
+ case 'version-mismatch':
+ case 'version-unknown':
+ return (
+ <div className="flex flex-wrap gap-2">
+ <GhostButton onClick={onRestart}>Restart</GhostButton>
+ <GhostButton onClick={onStop}>Stop</GhostButton>
+ </div>
+ );
+ case 'update-ready':
+ return (
+ <div className="flex flex-wrap gap-2">
+ {/* The message under it names who the update reaches. */}
+ <PrimaryButton onClick={() => startManagedServer(server)}>
+ <ArrowUpCircle />
+ Update now
+ </PrimaryButton>
+ <GhostButton onClick={onStop}>Stop</GhostButton>
+ </div>
+ );
+ case 'stopped':
+ return (
+ <div className="flex flex-wrap gap-2">
+ <PrimaryButton onClick={() => startManagedServer(server)}>
+ <Power />
+ Start
+ </PrimaryButton>
+ </div>
+ );
+ case 'waiting':
+ return (
+ <div className="flex flex-wrap gap-2">
+ {sshHost && (
+ <GhostButton onClick={() => void remoteServerStore.cancelWait(sshHost)}>
+ Stop waiting
+ </GhostButton>
+ )}
+ {logButton}
+ </div>
+ );
+ case 'starting':
+ case 'stopping':
+ case 'updating':
+ case 'busy':
+ return (
+ <div className="flex flex-wrap gap-2">
+ <GhostButton onClick={onStop} disabled>
+ Stop
+ </GhostButton>
+ {logButton}
+ </div>
+ );
+ case 'host-unreachable':
+ return (
+ <div className="flex flex-wrap gap-2">
+ {sshHost && (
+ <PrimaryButton
+ disabled={hostReachabilityStore.isRetrying(sshHost)}
+ onClick={() => void hostReachabilityStore.retry(sshHost)}
+ >
+ Try again
+ </PrimaryButton>
+ )}
+ </div>
+ );
+ case 'downgrade':
+ // Nothing safe to press: its database has already moved past this app.
+ return logButton ? <div className="flex flex-wrap gap-2">{logButton}</div> : null;
+ case 'stop-failed':
+ return (
+ <div className="flex flex-wrap gap-2">
+ <PrimaryButton onClick={onStop}>Stop again</PrimaryButton>
+ {logButton}
+ </div>
+ );
+ case 'reset-failed':
+ // Running it again is the Reset section's job, behind its confirmation.
+ return logButton ? <div className="flex flex-wrap gap-2">{logButton}</div> : null;
+ case 'start-failed':
+ case 'docker-unavailable':
+ case 'update-failed':
+ return (
+ <div className="flex flex-wrap gap-2">
+ <PrimaryButton onClick={onRetry}>Try again</PrimaryButton>
+ {logButton}
+ </div>
+ );
+ }
+});
+
+/** The message box, when there is something to act on or wait for. */
+const Messages = observer(function Messages({
+ server,
+ state,
+ workspaceNames,
+ othersNames,
+ lastFailedAt,
+ now,
+}: {
+ server: SwitchServer;
+ state: ManagedServerState;
+ workspaceNames: string[];
+ /** Who else has used it lately, as one phrase; empty when nobody has. */
+ othersNames: string;
+ lastFailedAt: string | null;
+ now: Date;
+}) {
+ const sshHost = server.managementKind === 'remote' ? server.sshHost : null;
+ const status = sshHost ? remoteServerStore.statusFor(sshHost) : localServerStore.status;
+ const docker = sshHost ? remoteServerStore.dockerFor(sshHost) : localServerStore.docker;
+ const storeError = sshHost ? remoteServerStore.error : localServerStore.error;
+ const progress = managedServerProgress(server);
+ const upgrade = status?.upgrade ?? null;
+ const drift = status?.drift ?? null;
+
+ const box = (() => {
+ switch (state.reason) {
+ case 'starting':
+ case 'stopping':
+ case 'busy':
+ case 'waiting':
+ return (
+ <MessageBox
+ tone="working"
+ icon={<WorkingSpinner />}
+ title={progress ?? `${state.label}…`}
+ >
+ {progress && /pull/i.test(progress) && (
+ <p>This can take a few minutes the first time.</p>
+ )}
+ </MessageBox>
+ );
+ case 'updating':
+ return (
+ <MessageBox
+ tone="working"
+ icon={<WorkingSpinner />}
+ title={upgrade ? `Updating switch-core ${upgrade.from} → ${upgrade.to}…` : 'Updating…'}
+ >
+ <p>
+ Agents pause until it's done. Rooms and messages are kept, and the database is backed
+ up first.
+ </p>
+ {progress && <p className="text-[var(--fg-dim)]">{progress}</p>}
+ </MessageBox>
+ );
+ case 'update-ready':
+ return (
+ <MessageBox tone="attention" title={`switch-core ${upgrade?.to ?? ''} is ready`}>
+ <p>
+ {othersNames
+ ? `Updating restarts the server for everyone on it. ${othersNames} used it recently; their agents pause for about a minute.`
+ : 'Updating restarts the server; agents pause for about a minute.'}
+ </p>
+ </MessageBox>
+ );
+ case 'version-mismatch':
+ return drift && drift.direction === 'unknown' ? (
+ <MessageBox tone="attention" title="Version mismatch">
+ <p>
+ Runs switch-core {drift.deployed}; this app expects {drift.expected}. Can't tell which
+ is newer, so restart only if {drift.expected} isn't older.
+ </p>
+ </MessageBox>
+ ) : null;
+ case 'version-unknown':
+ return drift && drift.direction === 'unreadable' ? (
+ <MessageBox tone="attention" title="Can't tell which switch-core this runs">
+ <p>This app expects {drift.expected}, but the running version couldn't be read.</p>
+ <Mono>{drift.reason}</Mono>
+ </MessageBox>
+ ) : null;
+ case 'stopped':
+ return (
+ <MessageBox tone="stopped">
+ {workspaceNames.length > 0 ? (
+ <p>
+ Agents and rooms in <NamesInBold names={workspaceNames} /> live here. They come back
+ once it's running.
+ {upgrade &&
+ ` Starting it updates switch-core ${upgrade.from} → ${upgrade.to} first.`}
+ </p>
+ ) : (
+ <p>
+ Agents and rooms on this server come back once it's running.
+ {upgrade &&
+ ` Starting it updates switch-core ${upgrade.from} → ${upgrade.to} first.`}
+ </p>
+ )}
+ </MessageBox>
+ );
+ case 'host-unreachable': {
+ const reachability = sshHost ? hostReachabilityStore.get(sshHost) : null;
+ return (
+ <MessageBox tone="failed" title={`Can't reach ${sshHost ?? server.name}`}>
+ {reachability?.lastError && <Mono>{reachability.lastError}</Mono>}
+ <p>Switch Console keeps trying, and picks the server up again once the host answers.</p>
+ </MessageBox>
+ );
+ }
+ case 'downgrade':
+ return drift && drift.direction === 'downgrade' ? (
+ <MessageBox tone="failed" title="This server is newer than Switch Console">
+ <p>{switchVersionDowngradeMessage(drift.deployed, drift.expected)}</p>
+ </MessageBox>
+ ) : null;
+ case 'docker-unavailable':
+ return (
+ <MessageBox
+ tone="failed"
+ title={
+ docker && !docker.available && docker.reason === 'not-installed'
+ ? `Docker isn't installed${sshHost ? ` on ${sshHost}` : ''}`
+ : `Docker isn't running${sshHost ? ` on ${sshHost}` : ''}`
+ }
+ >
+ {docker && !docker.available && <Mono>{docker.detail}</Mono>}
+ <p>Start Docker, then try again.</p>
+ </MessageBox>
+ );
+ case 'update-failed':
+ return (
+ <MessageBox
+ tone="failed"
+ title={upgrade ? `Couldn't update to switch-core ${upgrade.to}` : "Couldn't update"}
+ >
+ {upgrade?.state === 'failed' && <Mono>{upgrade.error}</Mono>}
+ <p>Agents stay paused until the update succeeds. The server's data is kept.</p>
+ </MessageBox>
+ );
+ case 'start-failed':
+ return (
+ <StartFailedBox
+ error={managedServerError(server) ?? storeError ?? 'The server stopped during start.'}
+ failedAt={lastFailedAt}
+ local={sshHost === null}
+ now={now}
+ />
+ );
+ case 'stop-failed':
+ return (
+ <MessageBox tone="failed" title="Couldn't stop">
+ <Mono>{explainStartFailure(managedServerError(server) ?? '').line}</Mono>
+ <p>It may still be running. Stop it again to finish.</p>
+ </MessageBox>
+ );
+ case 'reset-failed':
+ return (
+ <MessageBox tone="failed" title="The reset didn't finish">
+ <Mono>{explainStartFailure(managedServerError(server) ?? '').line}</Mono>
+ <p>Some of its data may already be gone. Reset it again below to finish.</p>
+ </MessageBox>
+ );
+ case 'running':
+ return null;
+ }
+ })();
+
+ // Said by other Consoles, or about this one's record on the host. Shown on
+ // their own: they are about the server, not about its state.
+ const remote = sshHost ? remoteServerStore.statusFor(sshHost) : null;
+ const working = state.tone === 'working';
+ return (
+ <>
+ {box}
+ {remote?.notice && !working && (
+ <MessageBox tone="stopped">
+ <p>{remote.notice}</p>
+ </MessageBox>
+ )}
+ {remote?.recordWarning && !working && (
+ <MessageBox tone="attention">
+ <p>{remote.recordWarning}</p>
+ </MessageBox>
+ )}
+ {storeError && state.reason !== 'start-failed' && (
+ <MessageBox tone="failed" title={storeError}>
+ {(sshHost ? remoteServerStore.errorDetail : localServerStore.errorDetail) && (
+ <Mono>{sshHost ? remoteServerStore.errorDetail : localServerStore.errorDetail}</Mono>
+ )}
+ </MessageBox>
+ )}
+ </>
+ );
+});
+
+/** Why the last start failed: the line that says so, what to do, and the way
+ * out when it is one this app can take. */
+function StartFailedBox({
+ error,
+ failedAt,
+ local,
+ now,
+}: {
+ error: string;
+ failedAt: string | null;
+ local: boolean;
+ now: Date;
+}) {
+ const failure = explainStartFailure(error);
+ const [moving, setMoving] = useState(false);
+ return (
+ <MessageBox
+ tone="failed"
+ title={failedAt ? `Couldn't start · ${activityWhen(failedAt, now)}` : "Couldn't start"}
+ >
+ <Mono>{failure.line}</Mono>
+ {failure.hint && <p>{failure.hint}</p>}
+ {/* Only here: a remote host's ports are chosen with its forwards, and
+ moving one is not this button's to do. */}
+ {local && failure.port !== null && (
+ <GhostButton
+ disabled={moving}
+ className="h-[26px] text-[12.5px]"
+ onClick={() => {
+ const port = failure.port;
+ if (port === null) return;
+ setMoving(true);
+ void localServerStore.useAnotherPort(port).finally(() => setMoving(false));
+ }}
+ >
+ Use another port
+ </GhostButton>
+ )}
+ </MessageBox>
+ );
+}
+
+export const managedServerView = {
+ WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,
+ TitlebarSlot: ManagedServerTitlebar,
+ MainPanel: ManagedServerMainPanel,
+ canActivate: (params: unknown): GuardResult => {
+ const serverId =
+ typeof params === 'object' && params !== null
+ ? (params as { serverId?: unknown }).serverId
+ : undefined;
+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };
+ if (switchServersStore.loaded && !switchServersStore.servers.some((s) => s.id === serverId)) {
+ return { ok: false, redirect: 'home', discardParams: true };
+ }
+ return { ok: true };
+ },
+} satisfies ViewDefinition<{ serverId: string }>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
index afeeef89b..546ac4e22 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts
@@ -29,6 +29,7 @@ function defaultStatus(sshHost: string): RemoteServerStatus {
return {
sshHost,
phase: 'stopped',
+ checked: false,
upgrade: null,
serverId: null,
version: '',
@@ -40,6 +41,7 @@ function defaultStatus(sshHost: string): RemoteServerStatus {
deployedTelemetry: null,
message: null,
error: null,
+ failedTo: null,
notice: null,
recordWarning: null,
waitingFor: null,
@@ -129,6 +131,11 @@ export class RemoteServerStore {
return hostReachabilityStore.isBlocked(sshHost);
}
+ /** Whether an action this window asked for on the host is in flight. */
+ isBusy(sshHost: string): boolean {
+ return this.busyHosts.has(sshHost);
+ }
+
isRunning(sshHost: string): boolean {
if (this.isHostBlocked(sshHost)) return false;
return this.phaseFor(sshHost) === 'running';
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
index afc5c1c84..17235fa48 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-agents-view.tsx
@@ -36,6 +36,7 @@ import {
import type { Agent } from '@shared/core/agents/agents';
import type { ManagedAgentView } from '@shared/core/managed-agents/managed-agents';
import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';
+import { isFrozenServer } from './managed-server-state';
import { ServerPage } from './server-page';
import { ServerSectionTitlebar } from './server-section-titlebar';
import { switchRoomsStore } from './switch-rooms-store';
@@ -113,7 +114,7 @@ const ServerAgentsPanel = observer(function ServerAgentsPanel() {
<ManagedAgentCard key={agent.agentId} agent={agent} />
))}
</div>
- {managed.error && (
+ {managed.error && !(server && isFrozenServer(server)) && (
<p role="alert" className="mt-3 text-sm text-destructive">
{failureText(managed.error, 'Could not load managed agents.')}
</p>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page-ui.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page-ui.tsx
new file mode 100644
index 000000000..2a8432835
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-page-ui.tsx
@@ -0,0 +1,133 @@
+import type { ReactNode } from 'react';
+import { cn } from '@renderer/utils/utils';
+import { TONE_BOX, TONE_PILL, TONE_TITLE, ToneDot } from './managed-server-dot';
+import type { ManagedServerState, ManagedTone } from './managed-server-state';
+
+/**
+ * The pieces the server page and the frozen-workspace banner are built from.
+ * Their sizes are the design's, written once here rather than at each use.
+ */
+
+type ButtonProps = {
+ children: ReactNode;
+ onClick: () => void;
+ disabled?: boolean;
+ className?: string;
+};
+
+/** The one primary action of a view. */
+export function PrimaryButton({ children, onClick, disabled = false, className }: ButtonProps) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ className={cn(
+ 'inline-flex h-[30px] shrink-0 items-center gap-1.5 rounded-[8px] bg-[var(--srv-primary)] px-3 text-[13px] font-medium text-[var(--srv-primary-fg)] transition-opacity hover:opacity-90 disabled:opacity-50 [&_svg]:size-3.5',
+ className
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+export function GhostButton({ children, onClick, disabled = false, className }: ButtonProps) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ className={cn(
+ 'inline-flex h-[30px] shrink-0 items-center gap-1.5 rounded-[8px] border-[0.5px] border-[var(--hair-strong)] px-3 text-[13px] text-foreground transition-colors hover:bg-[var(--sel-soft)] disabled:pointer-events-none disabled:text-[var(--fg-dim)] disabled:opacity-60 [&_svg]:size-3.5',
+ className
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+/** The state beside the server's name. */
+export function StatusPill({ state }: { state: ManagedServerState }) {
+ return (
+ <span
+ className={cn(
+ 'inline-flex h-5 shrink-0 items-center gap-1.5 rounded-full px-2 text-[11.5px] font-medium',
+ TONE_PILL[state.tone]
+ )}
+ >
+ <ToneDot tone={state.tone} size={6} />
+ {state.label}
+ </span>
+ );
+}
+
+/**
+ * Something to act on or wait for. Shown only then: a healthy page has none.
+ */
+export function MessageBox({
+ tone,
+ title,
+ icon,
+ children,
+}: {
+ tone: ManagedTone;
+ title?: ReactNode;
+ icon?: ReactNode;
+ children?: ReactNode;
+}) {
+ return (
+ <div
+ role={tone === 'failed' ? 'alert' : 'status'}
+ className={cn('rounded-[10px] border-[0.5px] px-[14px] py-3', TONE_BOX[tone])}
+ >
+ {title && (
+ <p className={cn('flex items-center gap-2 text-[13px] font-semibold', TONE_TITLE[tone])}>
+ {icon}
+ {title}
+ </p>
+ )}
+ {children && (
+ <div
+ className={cn('space-y-2 text-[13px] text-[var(--srv-stopped-text)]', title && 'mt-1')}
+ >
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** A raw error, version or path. */
+export function Mono({ children }: { children: ReactNode }) {
+ return (
+ <code className="block font-[Menlo,ui-monospace,monospace] text-[11.5px] break-words text-[var(--srv-mono)]">
+ {children}
+ </code>
+ );
+}
+
+export function SectionLabel({ children }: { children: ReactNode }) {
+ return <h3 className="text-[11.5px] text-[#8A8A8A]">{children}</h3>;
+}
+
+/** One line of the details: a label on the left, its value on the right. */
+export function DetailRow({ label, children }: { label: string; children: ReactNode }) {
+ return (
+ <div className="flex items-baseline justify-between gap-4 border-b-[0.5px] border-[var(--hair-soft)] py-[9px] text-[13px]">
+ <span className="shrink-0 text-[var(--fg-dim)]">{label}</span>
+ <span className="min-w-0 truncate text-right text-foreground">{children}</span>
+ </div>
+ );
+}
+
+/** One line of recent activity: what happened, then who and when. */
+export function ActivityRow({ what, when }: { what: string; when: ReactNode }) {
+ return (
+ <div className="flex items-baseline justify-between gap-4 py-[7px] text-[13px]">
+ <span className="min-w-0 truncate text-foreground">{what}</span>
+ <span className="shrink-0 text-[var(--fg-dim)] opacity-75">{when}</span>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx
index 8bc48fecb..54ed70c11 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx
@@ -3,13 +3,11 @@ import { observer } from 'mobx-react-lite';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { cn } from '@renderer/utils/utils';
-import type {
- DeployedTelemetry,
- ManagedServerUpgrade,
- SwitchVersionDrift,
-} from '@shared/core/managed-switch-server/managed-switch-server';
+import type { SwitchVersionDrift } from '@shared/core/managed-switch-server/managed-switch-server';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
import { localServerStore } from './local-server-store';
+import { ToneDot } from './managed-server-dot';
+import { managedServerState } from './managed-server-state';
import { remoteServerStore } from './remote-server-store';
import { serverAvailability } from './server-availability';
@@ -60,20 +58,6 @@ export function serverStatusLabel(server: SwitchServer): string {
return STATE_LABEL[serverState(server)];
}
-/**
- * The state as the switcher button reads it. It has no placement badge beside
- * it — the whole button is the one server — so the local stack says where it
- * runs here instead.
- */
-const SUBTITLE_LABEL: Record<ServerState, string> = {
- ...STATE_LABEL,
- 'running-local': 'Running locally',
-};
-
-export function serverSubtitleLabel(server: SwitchServer): string {
- return SUBTITLE_LABEL[serverState(server)];
-}
-
/** Where a server runs. Null for one reached by URL: this app does not know. */
export function serverPlacementLabel(server: SwitchServer): string | null {
if (!server.managed) return null;
@@ -94,37 +78,6 @@ export function serverDrift(server: SwitchServer): SwitchVersionDrift | null {
return localServerStore.drift;
}
-/** The upgrade a managed server's stack owes this build, or null. */
-export function serverUpgrade(server: SwitchServer): ManagedServerUpgrade | null {
- if (!server.managed) return null;
- if (server.managementKind === 'remote' && server.sshHost) {
- return remoteServerStore.upgradeFor(server.sshHost);
- }
- return localServerStore.upgrade;
-}
-
-/** The current step of a managed server's lifecycle operation, or null. */
-export function serverProgress(server: SwitchServer): string | null {
- if (!server.managed) return null;
- if (server.managementKind === 'remote' && server.sshHost) {
- return remoteServerStore.statusFor(server.sshHost).message;
- }
- return localServerStore.message;
-}
-
-/**
- * What a managed server's running stack is doing about usage data. Null for a
- * server this app does not run: its operator decides, and the Console's toggle
- * neither reaches it nor claims to.
- */
-export function serverDeployedTelemetry(server: SwitchServer): DeployedTelemetry | null {
- if (!server.managed) return null;
- if (server.managementKind === 'remote' && server.sshHost) {
- return remoteServerStore.deployedTelemetryFor(server.sshHost);
- }
- return localServerStore.deployedTelemetry;
-}
-
const AVATAR_SIZE = {
sm: 'size-6 text-xs',
md: 'size-[26px] text-xs',
@@ -189,6 +142,17 @@ export const ServerStatusPill = observer(function ServerStatusPill({
}: {
server: SwitchServer;
}) {
+ // A server this Console runs says what it is doing — starting, stopping,
+ // updating — rather than only whether it can be reached.
+ const managed = managedServerState(server);
+ if (managed?.known) {
+ return (
+ <span className="flex items-center gap-1.5 rounded-full bg-background-tertiary px-2 py-0.5 text-xs text-foreground-muted">
+ <ToneDot tone={managed.tone} size={6} />
+ {managed.label}
+ </span>
+ );
+ }
return (
<span className="flex items-center gap-1.5 rounded-full bg-background-tertiary px-2 py-0.5 text-xs text-foreground-muted">
<ServerStatusDot server={server} />
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx
deleted file mode 100644
index 3a68f74bc..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stack-section.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import type { ReactNode } from 'react';
-import { Button } from '@renderer/lib/ui/button';
-
-/** The lifecycle states a managed stack reports, local or remote. */
-export type StackPhase = 'stopped' | 'starting' | 'running' | 'stopping' | 'error' | 'unreachable';
-
-const PHASE_LABEL: Record<StackPhase, string> = {
- stopped: 'Stopped',
- starting: 'Starting',
- running: 'Running',
- stopping: 'Stopping',
- error: 'Error',
- unreachable: 'Host unreachable',
-};
-
-const PHASE_DOT: Record<StackPhase, string> = {
- stopped: 'bg-foreground-muted',
- starting: 'bg-amber-500',
- running: 'bg-green-500',
- stopping: 'bg-amber-500',
- error: 'bg-red-500',
- unreachable: 'bg-amber-500',
-};
-
-/**
- * The managed stack's own section of a server page — a heading, a one-line
- * status, and whatever the stack currently has to say for itself.
- *
- * Shared by the local and remote controls so the two read as the same thing in
- * two places rather than as two features that happen to look alike.
- */
-export function StackSection({ children }: { children: ReactNode }) {
- return <section className="space-y-3">{children}</section>;
-}
-
-/**
- * Where the stack is and what can be done about it.
- *
- * `summary` is a sentence rather than the machine's own terse answer — the
- * heading above it already says which stack this is, so the line's job is to
- * say whether it is up and where. The deployed version is carried on its
- * `title` instead of on screen: it is worth having, but only when something has
- * gone wrong enough to look for it, and the drift notice states both versions
- * whenever they actually disagree.
- */
-export function StackStatusRow({
- title,
- phase,
- summary,
- versionDetail,
- activity,
- actions,
-}: {
- title: string;
- phase: StackPhase;
- summary: string;
- versionDetail: string | null;
- /** The "Recent activity" disclosure, when there is any output to disclose. */
- activity?: ReactNode;
- actions: ReactNode;
-}) {
- return (
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <h3 className="text-sm font-medium text-foreground">{title}</h3>
- <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">
- <span aria-hidden className={`size-1.5 shrink-0 rounded-full ${PHASE_DOT[phase]}`} />
- <span className="truncate" title={versionDetail ?? undefined}>
- {summary}
- </span>
- {activity && (
- <>
- <span aria-hidden>·</span>
- {activity}
- </>
- )}
- </div>
- </div>
- <div className="flex shrink-0 items-center gap-3">{actions}</div>
- </div>
- );
-}
-
-/** A stack lifecycle action. Bordered rather than bare text: starting, stopping
- * and restarting a server are consequential enough to look pressable, and a
- * red word with no edge to it reads as a status rather than a control. */
-export function StackAction({
- label,
- danger = false,
- disabled = false,
- onClick,
-}: {
- label: string;
- danger?: boolean;
- disabled?: boolean;
- onClick: () => void;
-}) {
- return (
- <Button
- variant="outline"
- size="sm"
- disabled={disabled}
- onClick={onClick}
- className={
- danger ? 'border-red-500/40 text-red-500 hover:bg-red-500/10 hover:text-red-500' : undefined
- }
- >
- {label}
- </Button>
- );
-}
-
-/** The phase's own words, for the states that are not simply "running". */
-export function phaseLabel(phase: StackPhase): string {
- return PHASE_LABEL[phase];
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
index 1f1c299f8..be2d1a04c 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-stat-tiles.tsx
@@ -2,6 +2,10 @@ import { useQuery } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import {
+ useManagedAgents,
+ withoutManaged,
+} from '@renderer/features/managed-agents/use-managed-agents';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { rpc } from '@renderer/lib/ipc';
import { switchRoomsStore } from './switch-rooms-store';
@@ -35,12 +39,18 @@ export const ServerStatTiles = observer(function ServerStatTiles({
if (!agentsStore.loaded) void agentsStore.load();
}, []);
+ // Counted the way the Your Agents page lists them: this Console's agents,
+ // less the ones the server runs, plus every agent the server runs.
+ const managed = useManagedAgents(serverId);
+ const agentCount =
+ !agentsStore.loaded || managed.isLoading
+ ? null
+ : withoutManaged(agentsStore.agentsOnServer(serverId), managed.data).length +
+ (managed.data?.length ?? 0);
+
return (
<div className="grid grid-cols-3 gap-3">
- <StatTile
- label="Your Agents"
- value={agentsStore.loaded ? agentsStore.agentsOnServer(serverId).length : null}
- />
+ <StatTile label="Your Agents" value={agentCount} />
<StatTile
label="Your Rooms"
value={
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.test.ts
new file mode 100644
index 000000000..c14e160a0
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { activityWhen, agoLabel, sinceLabel } from './server-times';
+
+const NOW = new Date(2026, 9, 14, 15, 30); // a Wednesday
+
+describe('server times', () => {
+ it('says when a server started: today, yesterday, a weekday, then a date', () => {
+ expect(sinceLabel(new Date(2026, 9, 14, 9, 14).toISOString(), NOW)).toBe('Today, 09:14');
+ expect(sinceLabel(new Date(2026, 9, 13, 9, 14).toISOString(), NOW)).toBe('Yesterday, 09:14');
+ expect(sinceLabel(new Date(2026, 9, 12, 10, 2).toISOString(), NOW)).toBe('Monday, 10:02');
+ expect(sinceLabel(new Date(2026, 8, 1, 10, 2).toISOString(), NOW)).toBe('1 Sep, 10:02');
+ });
+
+ it('says when something happened, closest first', () => {
+ expect(activityWhen(new Date(2026, 9, 14, 15, 29, 30).toISOString(), NOW)).toBe('just now');
+ expect(activityWhen(new Date(2026, 9, 14, 15, 27).toISOString(), NOW)).toBe('3 min ago');
+ expect(activityWhen(new Date(2026, 9, 14, 9, 14).toISOString(), NOW)).toBe('today 09:14');
+ expect(activityWhen(new Date(2026, 9, 13, 9, 14).toISOString(), NOW)).toBe('yesterday');
+ expect(activityWhen(new Date(2026, 9, 12, 9, 14).toISOString(), NOW)).toBe('Monday');
+ });
+
+ it('says how long ago', () => {
+ expect(agoLabel(new Date(2026, 9, 12, 15, 30).toISOString(), NOW)).toBe('2 days ago');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.ts
new file mode 100644
index 000000000..b76af5bfe
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-times.ts
@@ -0,0 +1,36 @@
+import { differenceInCalendarDays, format, formatDistanceStrict } from 'date-fns';
+
+/**
+ * When something happened, the way the server page says it: a clock time for
+ * today and yesterday, a weekday within the week, a date before that.
+ */
+export function sinceLabel(iso: string, now: Date): string {
+ const at = new Date(iso);
+ const days = differenceInCalendarDays(now, at);
+ const time = format(at, 'HH:mm');
+ if (days <= 0) return `Today, ${time}`;
+ if (days === 1) return `Yesterday, ${time}`;
+ if (days < 7) return `${format(at, 'EEEE')}, ${time}`;
+ return `${format(at, 'd MMM')}, ${time}`;
+}
+
+/** For recent activity: "just now", "3 min ago", "today 09:14", "yesterday",
+ * a weekday, then a date. */
+export function activityWhen(iso: string, now: Date): string {
+ const at = new Date(iso);
+ const seconds = (now.getTime() - at.getTime()) / 1000;
+ if (seconds < 60) return 'just now';
+ if (seconds < 60 * 60) return `${Math.floor(seconds / 60)} min ago`;
+ const days = differenceInCalendarDays(now, at);
+ if (days <= 0) return `today ${format(at, 'HH:mm')}`;
+ if (days === 1) return 'yesterday';
+ if (days < 7) return format(at, 'EEEE');
+ return format(at, 'd MMM');
+}
+
+/** "2 days ago", for how long a server has been down. */
+export function agoLabel(iso: string, now: Date): string {
+ const at = new Date(iso);
+ if (now.getTime() - at.getTime() < 60_000) return 'just now';
+ return `${formatDistanceStrict(at, now)} ago`;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles-section.tsx
deleted file mode 100644
index bf11ff4a3..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles-section.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { observer } from 'mobx-react-lite';
-import { RelativeTime } from '@renderer/lib/ui/relative-time';
-import { remoteServerStore } from './remote-server-store';
-import { activitySentence, describeConsole } from './shared-consoles';
-
-const ACTIVITY_SHOWN = 5;
-
-/**
- * Who uses a shared remote server, and what they last did to it. Everyone signs
- * in as the server's one admin, so the server cannot tell them apart; each
- * Console records itself on the host instead, and this reads that record.
- * Shows nothing until the record has been read, or when it is empty.
- */
-export const SharedConsolesSection = observer(function SharedConsolesSection({
- sshHost,
-}: {
- sshHost: string;
-}) {
- const store = remoteServerStore;
- const register = store.registerFor(sshHost);
- const error = store.registerErrorFor(sshHost);
- if (!register && !error) return null;
- if (register && register.consoles.length === 0 && register.activity.length === 0 && !error) {
- return null;
- }
-
- return (
- <section className="space-y-3">
- <div className="space-y-0.5">
- <h3 className="text-sm font-medium text-foreground">Consoles using this server</h3>
- <p className="text-xs text-foreground-muted">
- Anyone with access to {sshHost} can connect from their own Switch Console. They all sign
- in as the server’s admin, so each Console records itself on the host — that record is what
- is listed here.
- </p>
- </div>
-
- {error && <p className="text-xs text-destructive">{error}</p>}
-
- {register && register.consoles.length > 0 && (
- <ul className="divide-y divide-border rounded-lg border border-border">
- {register.consoles.map((console) => (
- <li
- key={console.consoleId}
- className="flex items-center justify-between gap-3 px-3 py-2 text-sm"
- >
- <span className="min-w-0 truncate text-foreground">
- {describeConsole(console)}
- {console.consoleId === register.self && (
- <span className="text-foreground-muted"> — this Console</span>
- )}
- </span>
- <span className="shrink-0 text-xs text-foreground-muted">
- {console.appVersion} · seen <RelativeTime value={console.lastSeenAt} />
- </span>
- </li>
- ))}
- </ul>
- )}
-
- {register && register.activity.length > 0 && (
- <div className="space-y-1">
- <p className="text-xs font-medium text-foreground-muted">Recent activity</p>
- <ul className="space-y-0.5 text-xs text-foreground-muted">
- {register.activity.slice(0, ACTIVITY_SHOWN).map((entry) => (
- <li key={`${entry.at}-${entry.consoleId}-${entry.action}`}>
- {activitySentence(entry, register.self)} · <RelativeTime value={entry.at} />
- </li>
- ))}
- </ul>
- </div>
- )}
- </section>
- );
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.test.ts
index b29216544..8becf636b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.test.ts
@@ -4,12 +4,7 @@ import {
type StackConsole,
type StackRegister,
} from '@shared/core/managed-switch-server/managed-switch-server';
-import {
- activitySentence,
- affectedSentence,
- describeConsole,
- sharedWithSentence,
-} from './shared-consoles';
+import { affectedSentence, describeConsole, sharedWithSentence } from './shared-consoles';
const NOW = new Date('2026-09-23T12:00:00.000Z');
@@ -57,27 +52,25 @@ describe('the sentences', () => {
});
it('says nothing about sharing when nobody else uses the server', () => {
- expect(sharedWithSentence([])).toBeNull();
+ expect(sharedWithSentence([], null)).toBeNull();
expect(affectedSentence([], NOW)).toBeNull();
});
it('names one, two, or two and a count of the rest', () => {
- expect(sharedWithSentence([seen('bob@desk', 1)])).toBe(
+ expect(sharedWithSentence([seen('bob@desk', 1)], null)).toBe(
'Shared with bob@desk. Stopping or restarting it affects them too.'
);
- expect(sharedWithSentence([seen('bob@desk', 1), seen('carol@lab', 2)])).toMatch(
+ expect(sharedWithSentence([seen('bob@desk', 1), seen('carol@lab', 2)], null)).toMatch(
/^Shared with bob@desk and carol@lab\./
);
expect(
- sharedWithSentence([seen('bob@desk', 1), seen('carol@lab', 2), seen('dan@home', 3)])
+ sharedWithSentence([seen('bob@desk', 1), seen('carol@lab', 2), seen('dan@home', 3)], null)
).toMatch(/^Shared with bob@desk, carol@lab and 1 other\./);
expect(
- sharedWithSentence([
- seen('bob@desk', 1),
- seen('carol@lab', 2),
- seen('dan@home', 3),
- seen('erin@studio', 4),
- ])
+ sharedWithSentence(
+ [seen('bob@desk', 1), seen('carol@lab', 2), seen('dan@home', 3), seen('erin@studio', 4)],
+ null
+ )
).toMatch(/^Shared with bob@desk, carol@lab and 2 others\./);
});
@@ -93,16 +86,9 @@ describe('the sentences', () => {
expect(affectedSentence(many, NOW)).toMatch(/; and 2 more\.$/);
});
- it('says what happened, and says it was this Console when it was', () => {
- const entry = {
- at: NOW.toISOString(),
- action: 'stopped' as const,
- consoleId: 'bob',
- name: 'bob@desk',
- hostAccount: 'bob',
- };
-
- expect(activitySentence(entry, 'me')).toBe('bob@desk stopped it');
- expect(activitySentence({ ...entry, consoleId: 'me' }, 'me')).toBe('This Console stopped it');
+ it('calls another profile on this same computer that, rather than by its own name', () => {
+ expect(sharedWithSentence([seen('me@mac', 1), seen('bob@desk', 2)], 'me@mac')).toBe(
+ 'Shared with another Console on this computer and bob@desk. Stopping or restarting it affects them too.'
+ );
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.ts
index fd1e93273..c6dafb3f3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/shared-consoles.ts
@@ -1,8 +1,6 @@
import { formatDistanceStrict } from 'date-fns';
import {
othersRecentlySeen,
- type StackActivityAction,
- type StackActivityEntry,
type StackConsole,
type StackRegister,
} from '@shared/core/managed-switch-server/managed-switch-server';
@@ -17,21 +15,37 @@ export function describeConsole(console: Pick<StackConsole, 'name' | 'hostAccoun
return `${console.name} (as ${console.hostAccount})`;
}
-function names(first: StackConsole, rest: StackConsole[]): string {
- const [second, ...more] = rest;
- if (!second) return first.name;
- if (more.length === 0) return `${first.name} and ${second.name}`;
- return `${first.name}, ${second.name} and ${more.length} other${more.length === 1 ? '' : 's'}`;
+/**
+ * This Console's own desktop name on the register, or null before it has
+ * recorded itself. Another Console with the same name is another profile on
+ * this very computer, such as the Canary build.
+ */
+export function selfDesktop(register: StackRegister | null): string | null {
+ if (!register) return null;
+ return register.consoles.find((c) => c.consoleId === register.self)?.name ?? null;
+}
+
+function nameOf(console: StackConsole, self: string | null): string {
+ return self !== null && console.name === self ? 'another Console on this computer' : console.name;
+}
+
+/** `bob@desk`, `bob@desk and carol@lab`, `bob@desk, carol@lab and 2 others`. */
+export function namesOf(others: StackConsole[], self: string | null): string {
+ const unique = [...new Set(others.map((c) => nameOf(c, self)))];
+ const [first, second, ...more] = unique;
+ if (!first) return '';
+ if (!second) return first;
+ if (more.length === 0) return `${first} and ${second}`;
+ return `${first}, ${second} and ${more.length} other${more.length === 1 ? '' : 's'}`;
}
/**
* The line under the server's controls saying it is shared, or null when
* nobody else has used it recently.
*/
-export function sharedWithSentence(others: StackConsole[]): string | null {
- const [first, ...rest] = others;
- if (!first) return null;
- return `Shared with ${names(first, rest)}. Stopping or restarting it affects them too.`;
+export function sharedWithSentence(others: StackConsole[], self: string | null): string | null {
+ if (others.length === 0) return null;
+ return `Shared with ${namesOf(others, self)}. Stopping or restarting it affects them too.`;
}
/**
@@ -65,17 +79,3 @@ export function whoElseSentence(register: StackRegister | null, now: Date): stri
if (register === null) return 'Switch Console could not check who else uses it.';
return affectedSentence(othersRecentlySeen(register, now), now);
}
-
-const ACTION_WORDS: Record<StackActivityAction, string> = {
- started: 'started it',
- connected: 'connected',
- stopped: 'stopped it',
- reset: 'reset it',
- disconnected: 'disconnected',
-};
-
-/** `bob@desk stopped it` — one line of the server's activity. */
-export function activitySentence(entry: StackActivityEntry, self: string): string {
- const who = entry.consoleId === self ? 'This Console' : entry.name;
- return `${who} ${ACTION_WORDS[entry.action]}`;
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/version-drift-notice.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/version-drift-notice.test.ts
deleted file mode 100644
index ed1e08917..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/version-drift-notice.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { createElement } from 'react';
-import { renderToStaticMarkup } from 'react-dom/server';
-import { describe, expect, it, vi } from 'vitest';
-import type {
- ManagedServerUpgrade,
- SwitchVersionDrift,
-} from '@shared/core/managed-switch-server/managed-switch-server';
-import { VersionDriftNotice } from './VersionDriftNotice';
-
-const behind: SwitchVersionDrift = { deployed: '0.10.0', expected: '0.11.0', direction: 'upgrade' };
-
-function render(props: {
- drift: SwitchVersionDrift | null;
- upgrade: ManagedServerUpgrade | null;
- progress?: string | null;
- disabled?: boolean;
- affected?: string | null;
-}): string {
- return renderToStaticMarkup(
- createElement(VersionDriftNotice, {
- progress: null,
- disabled: false,
- affected: null,
- onRestart: vi.fn(),
- ...props,
- })
- );
-}
-
-function text(html: string): string {
- return html
- .replace(/<[^>]+>/g, ' ')
- .replace(/&#x27;/g, "'")
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-describe('VersionDriftNotice for a server behind the pin', () => {
- it('asks before updating a server others use, saying who it reaches', () => {
- const html = text(
- render({
- drift: behind,
- upgrade: { state: 'held', from: '0.10.0', to: '0.11.0' },
- affected: 'Also used recently by bob@desk (as bob), 2 hours ago.',
- })
- );
-
- expect(html).toMatch(/runs switch-core 0\.10\.0/);
- expect(html).toMatch(/updating restarts it for everyone/);
- expect(html).toMatch(/bob@desk \(as bob\), 2 hours ago/);
- expect(html).toMatch(/Update for everyone/);
- });
-
- it('shows the update in progress, with its current step, and no action', () => {
- const html = render({
- drift: behind,
- upgrade: { state: 'updating', from: '0.10.0', to: '0.11.0' },
- progress: 'Backing up the database before updating switch-core 0.10.0 → 0.11.0…',
- });
-
- expect(text(html)).toContain('Updating switch-core 0.10.0 → 0.11.0…');
- expect(text(html)).toContain('Sessions on this server resume once the update finishes.');
- expect(text(html)).toContain('Backing up the database');
- expect(html).toContain('role="status"');
- expect(html).not.toContain('<button');
- expect(text(html)).not.toContain('Restart to update');
- });
-
- it('shows a failed update with its error and a Retry button', () => {
- const html = render({
- drift: behind,
- upgrade: {
- state: 'failed',
- from: '0.10.0',
- to: '0.11.0',
- error: 'pg_dumpall failed: No space left on device',
- },
- });
-
- expect(text(html)).toContain('Updating switch-core 0.10.0 → 0.11.0 failed');
- expect(text(html)).toContain('pg_dumpall failed: No space left on device');
- expect(html).toContain('role="alert"');
- expect(html.match(/<button[^>]*>/g)).toHaveLength(1);
- expect(text(html)).toContain('Retry');
- expect(html).not.toMatch(/<button[^>]*\sdisabled=""/);
- });
-
- it('disables Retry while another operation is in flight', () => {
- const html = render({
- drift: behind,
- upgrade: { state: 'failed', from: '0.10.0', to: '0.11.0', error: 'boom' },
- disabled: true,
- });
-
- expect(html).toMatch(/<button[^>]*\sdisabled=""/);
- });
-
- it('tells a stopped server it will update when started', () => {
- const html = render({
- drift: behind,
- upgrade: { state: 'pending', from: '0.10.0', to: '0.11.0' },
- });
-
- expect(text(html)).toContain('switch-core 0.11.0 is required');
- expect(text(html)).toContain('stopped on switch-core 0.10.0');
- expect(text(html)).toContain('Start and update');
- });
-
- it('never offers the old optional restart for a server that is behind', () => {
- const html = render({ drift: behind, upgrade: null });
-
- expect(text(html)).toContain('switch-core 0.11.0 is required');
- expect(text(html)).not.toContain('Restart to update');
- expect(html).not.toContain('<button');
- });
-});
-
-describe('VersionDriftNotice for the cases it does not upgrade', () => {
- it('still explains a downgrade with no action', () => {
- const html = render({
- drift: { deployed: '0.12.0', expected: '0.11.0', direction: 'downgrade' },
- upgrade: null,
- });
-
- expect(text(html)).toContain('This server is newer than Switch Console');
- expect(html).not.toContain('<button');
- });
-
- it('still reports an unreadable version with no action', () => {
- const html = render({
- drift: { deployed: null, expected: '0.11.0', direction: 'unreadable', reason: 'daemon down' },
- upgrade: null,
- });
-
- expect(text(html)).toContain("Can't tell which switch-core this is running");
- expect(text(html)).toContain('daemon down');
- expect(html).not.toContain('<button');
- });
-
- it('still offers a restart for an uncomparable version', () => {
- const html = render({
- drift: { deployed: 'nightly', expected: '0.11.0', direction: 'unknown' },
- upgrade: null,
- });
-
- expect(text(html)).toContain('Version mismatch');
- expect(text(html)).toContain('Restart to update');
- });
-
- it('renders nothing for a server in step', () => {
- expect(render({ drift: null, upgrade: null })).toBe('');
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
index 0962c06da..5c8f6a5c7 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx
@@ -15,7 +15,6 @@ import { type GuardResult, type ViewDefinition } from '@renderer/app/view-regist
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';
-import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
import { WorkspaceAvatar } from '@renderer/features/workspaces/workspace-avatar';
import { workspaceTitle } from '@renderer/features/workspaces/workspace-title';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
@@ -36,20 +35,10 @@ import {
import { Spinner } from '@renderer/lib/ui/spinner';
import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
import { localServerStore } from './local-server-store';
-import { LocalServerControls } from './LocalServerControls';
-import { managedTelemetryNotice } from './managed-telemetry-notice';
import { MessagingAppsCard } from './MessagingAppsCard';
import { remoteServerStore } from './remote-server-store';
-import { RemoteServerControls } from './RemoteServerControls';
import { serverIcon } from './server-icon';
-import {
- serverDeployedTelemetry,
- serverDrift,
- serverPlacementLabel,
- serverProgress,
- serverUpgrade,
-} from './server-presentation';
-import { ServerResetSection } from './server-reset-section';
+import { serverPlacementLabel } from './server-presentation';
import { ServerSectionTitlebar } from './server-section-titlebar';
import {
machineUnavailableReason,
@@ -58,15 +47,11 @@ import {
useServerSignIn,
} from './server-sign-in';
import { ServerStatTiles } from './server-stat-tiles';
-import { useSharedActionConfirm } from './shared-action-confirm';
-import { SharedConsolesSection } from './shared-consoles-section';
import { loadSwitchCloudOrigin, managedCloudServerId } from './switch-cloud-origin';
import { isSwitchCloudServer } from './switch-cloud-store';
import { switchRoomsStore } from './switch-rooms-store';
import { switchServersStore } from './switch-servers-store';
-import { TelemetryConsentNotice } from './TelemetryConsentNotice';
import { myIdentitiesQueryKey } from './use-my-identities';
-import { VersionDriftNotice } from './VersionDriftNotice';
/** Whether a managed server's stack is currently running (via the store that
* owns its lifecycle). Non-managed servers are always "reachable". */
@@ -77,16 +62,6 @@ function isManagedRunning(server: SwitchServer): boolean {
return localServerStore.isRunning;
}
-/** Re-running the start pipeline is what picks up a new switch-core pin, so
- * "restart to update" and "restart" are the same call on either store. */
-function restartStack(server: SwitchServer): void {
- if (server.managementKind === 'remote' && server.sshHost) {
- void remoteServerStore.start(server.sshHost, server.name);
- return;
- }
- void localServerStore.start();
-}
-
const card = 'rounded-lg border border-border bg-card p-4';
/** How long Refresh keeps spinning at minimum. Long enough to be seen as a
@@ -105,9 +80,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
const serverId = useServerId();
const store = switchServersStore;
const server = store.servers.find((s) => s.id === serverId);
- // A remote server is shared, so restarting it from a notice reaches everyone.
- const remoteHost = server?.managementKind === 'remote' ? server.sshHost : null;
- const confirm = useSharedActionConfirm(remoteHost);
const showEditServerModal = useShowModal('addServerModal');
const showRenameServerModal = useShowModal('renameServerModal');
const showDeleteServerModal = useShowModal('deleteServerModal');
@@ -115,10 +87,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
const queryClient = useQueryClient();
const [refreshingPage, setRefreshingPage] = useState(false);
- // The same answer the Console checks before its own events. Read here rather
- // than pushed with the stack's status so that flipping the toggle in Settings
- // updates this page at once, without waiting for the server to be re-probed.
- const { value: telemetry } = useAppSettingsKey('telemetry');
/**
* Everything the page is showing, re-read.
@@ -208,13 +176,7 @@ const ServerMainPanel = observer(function ServerMainPanel() {
const busy = refreshingPage || store.refreshing.has(serverId);
const unreachable = store.isUnreachable(serverId);
const PlacementIcon = serverIcon(server);
- const drift = serverDrift(server);
const title = workspaceTitle(server);
- const stackTransitioning =
- server.managementKind === 'remote' && server.sshHost
- ? remoteServerStore.isTransitioning(server.sshHost) ||
- remoteServerStore.isHostBlocked(server.sshHost)
- : localServerStore.isTransitioning;
return (
<div className="relative z-10 flex min-h-0 flex-1 flex-col overflow-auto bg-background">
@@ -322,38 +284,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
</Alert>
)}
- {/* An available update is about the whole server, so it leads the page
- rather than waiting inside the stack card further down. */}
- <VersionDriftNotice
- drift={drift}
- upgrade={serverUpgrade(server)}
- progress={serverProgress(server)}
- disabled={stackTransitioning}
- affected={confirm.who}
- onRestart={() =>
- // A held update names who it reaches on its own button; a stopped
- // server reaches nobody.
- isManagedRunning(server) && serverUpgrade(server)?.state !== 'held'
- ? confirm.request('restart', () => restartStack(server))
- : restartStack(server)
- }
- />
-
- {/* Same placement, and for the same reason: a consent decision that has
- not reached this server is about the server, not about one card on
- its page. */}
- <TelemetryConsentNotice
- notice={managedTelemetryNotice({
- running: server.managed && isManagedRunning(server),
- deployed: serverDeployedTelemetry(server),
- consent: telemetry?.enabled ?? true,
- sharedWithOthers: confirm.shared,
- })}
- disabled={stackTransitioning}
- onRestart={() => confirm.request('restart', () => restartStack(server))}
- />
- {confirm.dialog}
-
{detailsVisible && unreachable && <ServerUnreachableCard serverId={serverId} />}
{detailsVisible && !unreachable && (
@@ -377,17 +307,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
</>
)}
- {server.managed &&
- (server.managementKind === 'remote' && server.sshHost ? (
- <RemoteServerControls sshHost={server.sshHost} name={server.name} />
- ) : (
- <LocalServerControls />
- ))}
-
- {server.managed && server.managementKind === 'remote' && server.sshHost && (
- <SharedConsolesSection sshHost={server.sshHost} />
- )}
-
{detailsVisible && !unreachable && (
<div className="flex items-center justify-between gap-3">
<div className="min-w-0 space-y-0.5">
@@ -412,26 +331,6 @@ const ServerMainPanel = observer(function ServerMainPanel() {
</Button>
</div>
)}
-
- {server.managed && (
- <ServerResetSection
- dialogTitle={
- server.managementKind === 'remote' && server.sshHost
- ? `Reset server on ${server.sshHost}`
- : 'Reset server on this computer'
- }
- shared={server.managementKind === 'remote'}
- affected={confirm.who}
- disabled={stackTransitioning}
- onConfirm={() => {
- if (server.managementKind === 'remote' && server.sshHost) {
- void remoteServerStore.reset(server.sshHost);
- return;
- }
- void localServerStore.reset();
- }}
- />
- )}
</div>
</div>
);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
index 4d5cf6f82..7f8f49ff1 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/workspace-switcher.tsx
@@ -41,6 +41,7 @@ import {
workspaceUnavailability,
} from '@shared/core/workspaces/workspaces';
import { localServerStore } from './local-server-store';
+import { ManagedServerDot } from './managed-server-dot';
import { remoteServerStore } from './remote-server-store';
import { serverAvailability } from './server-availability';
import { serverIcon } from './server-icon';
@@ -52,24 +53,26 @@ import {
serverPlacementLabel,
serverState,
serverStatusLabel,
- serverSubtitleLabel,
} from './server-presentation';
import { switchServersStore } from './switch-servers-store';
import { type SwitchCloudAvailability, useSwitchCloud } from './use-switch-cloud';
/**
- * How the button names where you are.
- *
- * A server registered before its workspaces are known names its only workspace
- * after itself, and until the account has been asked the two names are the same
- * — saying both would read as a stutter. Where they differ the server is the
- * more important half of the answer, since the same workspace name can exist on
- * two of them.
+ * A server this Console does not run, said only when something is wrong with
+ * it: the switcher carries no status words, and a reachable server needs no
+ * mark at all. Signed out or unreachable still shows, as a dot whose label
+ * says which, since the menu is otherwise the only place it would be found.
*/
-function switcherSubtitle(workspace: Workspace, server: SwitchServer): string {
- const status = serverSubtitleLabel(server);
- return workspace.name === server.name ? status : `${server.name} · ${status}`;
-}
+const ServerProblemDot = observer(function ServerProblemDot({ server }: { server: SwitchServer }) {
+ const state = serverState(server);
+ if (state === 'connected' || state === 'running-local') return null;
+ const label = serverStatusLabel(server);
+ return (
+ <span role="img" aria-label={label} title={label} className="flex shrink-0">
+ <ServerStatusDot server={server} />
+ </span>
+ );
+});
/**
* Whether the sidebar shows servers rather than workspaces.
@@ -165,7 +168,6 @@ const ServerMenu = observer(function ServerMenu({ activeServer }: { activeServer
const { navigate } = useNavigate();
const showAddServerModal = useShowModal('addServerModal');
const ActiveIcon = serverIcon(activeServer);
- const drift = serverDrift(activeServer);
return (
<div className="px-2">
@@ -184,9 +186,14 @@ const ServerMenu = observer(function ServerMenu({ activeServer }: { activeServer
</span>
<span className="flex items-center gap-1.5 text-xs text-foreground-muted">
<ActiveIcon className="size-3 shrink-0" />
- <span className="truncate">{serverSubtitleLabel(activeServer)}</span>
- <ServerStatusDot server={activeServer} />
- {drift && <ServerDriftIndicator drift={drift} />}
+ {activeServer.managed ? (
+ <>
+ <span className="truncate">{serverPlacementLabel(activeServer)}</span>
+ <ManagedServerDot server={activeServer} size={6} />
+ </>
+ ) : (
+ <ServerProblemDot server={activeServer} />
+ )}
</span>
</span>
<ChevronsUpDown className="size-3.5 shrink-0 text-foreground-muted" />
@@ -261,9 +268,10 @@ const ServerMenuItem = observer(function ServerMenuItem({
title={reason}
onClick={() => {
if (!workspace) return;
+ const dormant = serverAvailability(server.id) === 'dormant';
void workspacesStore
.setActive(workspace.id)
- .then(() => navigate('server', { serverId: server.id }))
+ .then(() => navigate(dormant ? 'managedServer' : 'server', { serverId: server.id }))
.catch(() => {
toast({
title: 'Could not switch server',
@@ -278,8 +286,11 @@ const ServerMenuItem = observer(function ServerMenuItem({
<span className="block truncate text-sm font-medium text-foreground">{server.name}</span>
<span className="flex min-w-0 items-center gap-1.5 text-xs text-foreground-muted">
<Icon className="size-3 shrink-0" />
- <span className="truncate">{serverStatusLabel(server)}</span>
- <ServerStatusDot server={server} />
+ {server.managed ? (
+ <ManagedServerDot server={server} size={6} />
+ ) : (
+ <ServerProblemDot server={server} />
+ )}
{(placement || unavailable) && (
<span className="shrink-0 rounded bg-background-tertiary px-1 py-px text-[10px] font-medium tracking-wide text-foreground-muted uppercase">
{unavailable ? UNAVAILABLE_BADGE[unavailable] : placement}
@@ -287,7 +298,7 @@ const ServerMenuItem = observer(function ServerMenuItem({
)}
</span>
</span>
- {drift && <ServerDriftIndicator drift={drift} />}
+ {drift && !server.managed && <ServerDriftIndicator drift={drift} />}
</DropdownMenuItem>
);
});
@@ -323,7 +334,6 @@ const WorkspaceMenu = observer(function WorkspaceMenu({
const showAddServerModal = useShowModal('addServerModal');
const [query, setQuery] = useState('');
- const drift = serverDrift(activeServer);
const noWorkspaceYet =
active.tenantId === null &&
serverAvailability(activeServer.id) === 'available' &&
@@ -352,11 +362,12 @@ const WorkspaceMenu = observer(function WorkspaceMenu({
{noWorkspaceYet ? 'No workspace yet' : active.name}
</span>
<span className="flex items-center gap-1.5 text-xs text-foreground-muted">
- <span className="truncate">
- {noWorkspaceYet ? activeServer.name : switcherSubtitle(active, activeServer)}
- </span>
- <ServerStatusDot server={activeServer} />
- {drift && <ServerDriftIndicator drift={drift} />}
+ <span className="truncate">{activeServer.name}</span>
+ {activeServer.managed ? (
+ <ManagedServerDot server={activeServer} size={6} />
+ ) : (
+ <ServerProblemDot server={activeServer} />
+ )}
</span>
</span>
<PendingInvitationCount server={activeServer} />
@@ -572,8 +583,9 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
? joinable
: joinable.filter((j) => matchesQuery(j.workspaceName, query));
const extraRows = (signedOut && signInTarget) || noMembership;
+ const dormant = server.managed && availability === 'dormant';
// Collapsed to one row, a server not usable here is found by its own name.
- if (searching && !whole && availability !== 'available') return null;
+ if (searching && !whole && availability !== 'available' && !dormant) return null;
if (
searching &&
!(whole && extraRows) &&
@@ -593,13 +605,30 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
<DropdownMenuLabel className="flex items-center gap-1.5 px-[9px] pt-2.5 pb-1 text-[10.5px] font-semibold tracking-[0.06em] text-[var(--fg-passive)] uppercase">
<Icon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{server.name}</span>
- {drift && <ServerDriftIndicator drift={drift} />}
+ {server.managed ? (
+ <ManagedServerDot server={server} size={6} />
+ ) : (
+ drift && <ServerDriftIndicator drift={drift} />
+ )}
</DropdownMenuLabel>
{/* A server this window cannot use right now collapses to one row that
says why and offers the one thing that changes it: its workspaces
cannot be opened from here until then, so listing them would only
offer clicks that fail. */}
- {!available ? (
+ {dormant ? (
+ // Workspaces on a server this Console runs stay listed while it is not
+ // running — dimmed, and opening onto the server's page, where it can be
+ // started.
+ workspaces.map((workspace) => (
+ <WorkspaceMenuItem
+ key={workspace.id}
+ workspace={workspace}
+ server={server}
+ onServerCount={all.length}
+ dormant
+ />
+ ))
+ ) : !available ? (
whole && (
<UnavailableServerRow server={server} onSignIn={signInTarget ? openForSignIn : null} />
)
@@ -626,6 +655,7 @@ const ServerWorkspaceGroupBody = observer(function ServerWorkspaceGroupBody({
workspace={workspace}
server={server}
onServerCount={all.length}
+ dormant={false}
/>
))
)}
@@ -738,10 +768,14 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
workspace,
server,
onServerCount,
+ dormant,
}: {
workspace: Workspace;
server: SwitchServer;
onServerCount: number;
+ /** Its server is managed here and not running: dimmed, and opens the
+ * server's page rather than the workspace's home. */
+ dormant: boolean;
}) {
const { navigate } = useNavigate();
const { toast } = useToast();
@@ -752,7 +786,7 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
// refuses every call scoped to it — offering it would turn a fact the app
// already knows into an error after the click.
const unavailable = workspaceUnavailability(workspace, onServerCount);
- const canInvite = unavailable === null && administersWorkspace(workspace);
+ const canInvite = !dormant && unavailable === null && administersWorkspace(workspace);
return (
<DropdownMenuItem
@@ -766,7 +800,7 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
onClick={() => {
void workspacesStore
.setActive(workspace.id)
- .then(() => navigate('server', { serverId: server.id }))
+ .then(() => navigate(dormant ? 'managedServer' : 'server', { serverId: server.id }))
.catch(() => {
// Said out loud rather than swallowed: the sidebar would otherwise
// keep showing the workspace you left, under the name of the one
@@ -779,8 +813,16 @@ const WorkspaceMenuItem = observer(function WorkspaceMenuItem({
});
}}
>
- <WorkspaceAvatar name={workspace.name} size="tile" active={isActive} />
- <span data-row-name className="min-w-0 flex-1 truncate text-[var(--fg-name)]">
+ <span className={cn('flex shrink-0', dormant && 'opacity-50')}>
+ <WorkspaceAvatar name={workspace.name} size="tile" active={isActive && !dormant} />
+ </span>
+ <span
+ data-row-name
+ className={cn(
+ 'min-w-0 flex-1 truncate',
+ dormant ? 'text-[var(--fg-dim)]' : 'text-[var(--fg-name)]'
+ )}
+ >
{workspace.name}
</span>
{unavailable && (
diff --git a/console/apps/switch-console-desktop/src/renderer/index.css b/console/apps/switch-console-desktop/src/renderer/index.css
index 79509f69c..bb6518df5 100644
--- a/console/apps/switch-console-desktop/src/renderer/index.css
+++ b/console/apps/switch-console-desktop/src/renderer/index.css
@@ -445,6 +445,31 @@
leaves the active option indistinguishable from the inactive one. */
--segment-track: rgb(0 0 0 / 0.06);
+ /* A managed server's state: a dot, a pill (tint + text on it) and a
+ message box (a fainter wash with a hairline of the same hue). Colour
+ lives only there; the text around them stays neutral. */
+ --srv-running: #4fa05e;
+ --srv-running-tint: rgb(79 160 94 / 0.14);
+ --srv-running-text: #2f7a3f;
+ --srv-working: #e0a23a;
+ --srv-working-tint: rgb(224 162 58 / 0.18);
+ --srv-working-text: #8a5a0f;
+ --srv-working-box: rgb(224 162 58 / 0.08);
+ --srv-working-line: rgb(224 162 58 / 0.3);
+ --srv-stopped: #8a8a8a;
+ --srv-stopped-tint: rgb(0 0 0 / 0.06);
+ --srv-stopped-text: #555555;
+ --srv-stopped-box: rgb(0 0 0 / 0.03);
+ --srv-stopped-line: rgb(0 0 0 / 0.1);
+ --srv-failed: #e5534b;
+ --srv-failed-tint: rgb(229 83 75 / 0.12);
+ --srv-failed-text: #b3261e;
+ --srv-failed-box: rgb(229 83 75 / 0.06);
+ --srv-failed-line: rgb(229 83 75 / 0.28);
+ --srv-primary: #2f5a43;
+ --srv-primary-fg: #f5fbf7;
+ --srv-mono: #3a3a3a;
+
--panel-radius: 12px;
--radius-elevated: 11px;
@@ -754,6 +779,28 @@
reads as sitting on top of the track instead of merging into it. */
--segment-track: rgb(0 0 0 / 0.32);
+ --srv-running: #4fa05e;
+ --srv-running-tint: rgb(79 160 94 / 0.14);
+ --srv-running-text: #8fcb9e;
+ --srv-working: #e0a23a;
+ --srv-working-tint: rgb(224 162 58 / 0.14);
+ --srv-working-text: #e8c07a;
+ --srv-working-box: rgb(224 162 58 / 0.07);
+ --srv-working-line: rgb(224 162 58 / 0.25);
+ --srv-stopped: #6a6a6a;
+ --srv-stopped-tint: rgb(255 255 255 / 0.07);
+ --srv-stopped-text: #c8c8c8;
+ --srv-stopped-box: rgb(255 255 255 / 0.04);
+ --srv-stopped-line: rgb(255 255 255 / 0.1);
+ --srv-failed: #e5534b;
+ --srv-failed-tint: rgb(229 83 75 / 0.14);
+ --srv-failed-text: #f2b8b5;
+ --srv-failed-box: rgb(229 83 75 / 0.08);
+ --srv-failed-line: rgb(229 83 75 / 0.25);
+ --srv-primary: #2f5a43;
+ --srv-primary-fg: #f5fbf7;
+ --srv-mono: #c8c8c8;
+
--panel-radius: 12px;
--radius-elevated: 11px;
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
index cc5792d0a..ccf252259 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
@@ -23,12 +23,19 @@ interface WorkspaceLayoutProps {
* whole client whenever it is unmounted or re-parented.
*/
persistentLayer?: ReactNode;
+ /** Across the top of the main panel, above the view, when the workspace has
+ * something to say about itself — such as its server not running. */
+ banner: ReactNode;
+ /** Classes for the view and the persistent layer under the banner. */
+ contentClassName: string | undefined;
}
export function WorkspaceLayout({
leftSidebar,
mainContent,
persistentLayer = null,
+ banner,
+ contentClassName,
}: WorkspaceLayoutProps) {
const { leftPanelRef, syncLeftOpenFromPanel, isLeftOpen } = useWorkspaceLayoutContext();
const { defaultLayout, onLayoutChanged } = useDefaultLayout({
@@ -85,9 +92,12 @@ export function WorkspaceLayout({
!isLeftOpen && (isMac ? 'pt-9' : 'pt-2')
)}
>
- <div className="relative h-full w-full overflow-hidden rounded-[var(--panel-radius)] shadow-[0_0_0_0.5px_var(--hair)]">
- {mainContent}
- {persistentLayer}
+ <div className="relative flex h-full w-full flex-col overflow-hidden rounded-[var(--panel-radius)] shadow-[0_0_0_0.5px_var(--hair)]">
+ {banner}
+ <div className={cn('relative min-h-0 w-full flex-1', contentClassName)}>
+ {mainContent}
+ {persistentLayer}
+ </div>
</div>
</div>
</ResizablePanel>
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
index d74dacd12..14a656b31 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-workspace-agents.ts
@@ -22,6 +22,14 @@ export function useWorkspaceAgents(workspaceId: string | null) {
});
}
+/**
+ * The last icon each agent was seen with, by workspace and agent. A server
+ * that is stopped or unreachable lists no agents, and without this every row
+ * would fall back to the name-drawn avatar until it answers again — the same
+ * agent changing face with its server's state.
+ */
+const lastKnownIcons = new Map<string, string>();
+
/**
* An agent's chosen icon, or null when it has none, is not in this workspace,
* or the list has not arrived yet.
@@ -29,6 +37,9 @@ export function useWorkspaceAgents(workspaceId: string | null) {
* Null is not an error and callers must not treat it as one: `AgentAvatar`
* draws an avatar from the agent's name instead, so a row renders the right
* picture on first paint and simply sharpens to a custom icon if there is one.
+ *
+ * While the server does not list the agent, the icon it last had is kept. An
+ * agent the server does list with no icon has none, and loses the remembered one.
*/
export function useAgentIconUrl(
workspaceId: string | null,
@@ -36,5 +47,10 @@ export function useAgentIconUrl(
): string | null {
const agents = useWorkspaceAgents(workspaceId);
if (switchAgentId === null) return null;
- return agents.data?.find((agent) => agent.id === switchAgentId)?.iconUrl ?? null;
+ const key = `${workspaceId}:${switchAgentId}`;
+ const listed = agents.data?.find((agent) => agent.id === switchAgentId);
+ if (!listed) return lastKnownIcons.get(key) ?? null;
+ if (listed.iconUrl) lastKnownIcons.set(key, listed.iconUrl);
+ else lastKnownIcons.delete(key);
+ return listed.iconUrl ?? null;
}
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-last-known.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-last-known.test.tsx
new file mode 100644
index 000000000..e8c4a5c63
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-icon-last-known.test.tsx
@@ -0,0 +1,46 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { expect, it, vi } from 'vitest';
+
+const listed = vi.hoisted(() => ({ agents: [] as { id: string; iconUrl: string | null }[] }));
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: { workspaces: { listAgents: async () => listed.agents } },
+}));
+
+import {
+ useAgentIconUrl,
+ workspaceAgentsQueryKey,
+} from '@renderer/lib/stores/use-workspace-agents';
+
+function Probe() {
+ return <span>{useAgentIconUrl('w', 'a') ?? 'none'}</span>;
+}
+
+it('keeps the icon an agent last had while its server lists no agents', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const settle = () => act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
+
+ listed.agents = [{ id: 'a', iconUrl: 'https://icons/gaze.png' }];
+ await act(async () =>
+ createRoot(host).render(
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ )
+ );
+ await settle();
+ expect(host.textContent).toBe('https://icons/gaze.png');
+
+ listed.agents = [];
+ await act(async () => client.invalidateQueries({ queryKey: workspaceAgentsQueryKey('w') }));
+ await settle();
+ expect(host.textContent).toBe('https://icons/gaze.png');
+
+ listed.agents = [{ id: 'a', iconUrl: null }];
+ await act(async () => client.invalidateQueries({ queryKey: workspaceAgentsQueryKey('w') }));
+ await settle();
+ expect(host.textContent).toBe('none');
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx
new file mode 100644
index 000000000..9f88818bf
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/managed-server-view.test.tsx
@@ -0,0 +1,464 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const state = vi.hoisted(() => ({
+ server: null as unknown,
+ localStatus: null as unknown,
+ remoteStatus: null as unknown,
+ register: null as unknown,
+ startedAt: null as string | null,
+ activity: [] as unknown[],
+ localStart: vi.fn(),
+ localStop: vi.fn(),
+ useAnotherPort: vi.fn((_port: number) => Promise.resolve()),
+ remoteStart: vi.fn(),
+ remoteStop: vi.fn(),
+ remoteReset: vi.fn(),
+ cancelWait: vi.fn(),
+}));
+
+vi.mock('@renderer/lib/layout/navigation-provider', () => ({
+ useParams: () => ({ params: { serverId: 'srv-1' } }),
+ useNavigate: () => ({ navigate: vi.fn() }),
+}));
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: {
+ localSwitchServer: {
+ startedAt: () => Promise.resolve(state.startedAt),
+ activity: () => Promise.resolve(state.activity),
+ },
+ remoteSwitchServer: { startedAt: () => Promise.resolve(state.startedAt) },
+ },
+}));
+vi.mock('@renderer/features/settings/use-app-settings-key', () => ({
+ useAppSettingsKey: () => ({ value: { enabled: true } }),
+}));
+vi.mock('@renderer/features/workspaces/workspaces-store', () => ({
+ workspacesStore: {
+ onServer: () => [
+ { id: 'w1', name: 'Default', tenantId: 't1' },
+ { id: 'w2', name: 'Scratch', tenantId: 't2' },
+ ],
+ },
+}));
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: {
+ loaded: true,
+ get servers() {
+ return [state.server];
+ },
+ },
+}));
+vi.mock('@renderer/features/switch-servers/local-server-store', () => ({
+ localServerStore: {
+ get status() {
+ return state.localStatus;
+ },
+ get message() {
+ return (state.localStatus as { message: string | null } | null)?.message ?? null;
+ },
+ docker: null,
+ busy: false,
+ logs: [],
+ error: null,
+ errorDetail: null,
+ checkoutBuild: null,
+ checkDocker: () => Promise.resolve(),
+ start: (...args: unknown[]) => state.localStart(...args),
+ stop: (...args: unknown[]) => state.localStop(...args),
+ useAnotherPort: (port: number) => state.useAnotherPort(port),
+ reset: vi.fn(),
+ setCheckoutBuild: vi.fn(),
+ },
+}));
+vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({
+ remoteServerStore: {
+ statusFor: () => state.remoteStatus,
+ dockerFor: () => null,
+ registerFor: () => state.register,
+ logsFor: () => [],
+ isBusy: () => false,
+ isHostBlocked: () => false,
+ error: null,
+ errorDetail: null,
+ init: () => Promise.resolve(),
+ checkDocker: () => Promise.resolve(),
+ loadRegister: () => Promise.resolve(),
+ refresh: () => Promise.resolve(),
+ start: (...args: unknown[]) => state.remoteStart(...args),
+ stop: (...args: unknown[]) => state.remoteStop(...args),
+ reset: (...args: unknown[]) => state.remoteReset(...args),
+ cancelWait: (...args: unknown[]) => state.cancelWait(...args),
+ },
+}));
+vi.mock('@renderer/features/remote-hosts/host-reachability-store', () => ({
+ hostReachabilityStore: {
+ hydrate: () => Promise.resolve(),
+ get: () => null,
+ isBlocked: () => false,
+ isRetrying: () => false,
+ retry: vi.fn(),
+ },
+}));
+
+import { managedServerView } from '@renderer/features/switch-servers/managed-server-view';
+import '@renderer/index.css';
+
+const LOCAL = {
+ id: 'srv-1',
+ name: 'Local dev',
+ gatewayUrl: 'http://localhost:41000',
+ apiUrl: 'http://localhost:41001',
+ managed: true,
+ managementKind: 'local' as const,
+ sshHost: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+};
+const REMOTE = { ...LOCAL, name: 'Dev VM', managementKind: 'remote' as const, sshHost: 'vm-1' };
+
+function status(patch: Record<string, unknown>) {
+ return {
+ phase: 'running',
+ checked: true,
+ upgrade: null,
+ serverId: 'srv-1',
+ version: '0.30.0',
+ deployedVersion: '0.30.0',
+ drift: null,
+ checkoutBuild: null,
+ deployedTelemetry: null,
+ message: null,
+ error: null,
+ failedTo: null,
+ notice: null,
+ recordWarning: null,
+ waitingFor: null,
+ sshHost: 'vm-1',
+ ...patch,
+ };
+}
+
+const BOB = {
+ consoleId: 'bob',
+ name: 'bob@desk',
+ hostAccount: 'bob',
+ appVersion: '0.37.0',
+ lastSeenAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
+};
+const SHARED = { self: 'me', consoles: [BOB], activity: [] };
+const ALONE = { self: 'me', consoles: [], activity: [] };
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+beforeEach(() => {
+ state.server = LOCAL;
+ state.localStatus = status({});
+ state.remoteStatus = status({});
+ state.register = ALONE;
+ state.startedAt = null;
+ state.activity = [];
+ for (const fn of [
+ state.localStart,
+ state.localStop,
+ state.useAnotherPort,
+ state.remoteStart,
+ state.remoteStop,
+ state.remoteReset,
+ state.cancelWait,
+ ]) {
+ fn.mockClear();
+ }
+});
+
+afterEach(async () => {
+ await act(async () => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function render() {
+ const Page = managedServerView.MainPanel;
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <Page />
+ </QueryClientProvider>
+ )
+ );
+ // Let the queries settle.
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
+}
+
+function text(): string {
+ return container?.textContent ?? '';
+}
+
+function button(label: RegExp): HTMLButtonElement {
+ const found = [...document.querySelectorAll('button')].find((b) =>
+ label.test(b.textContent?.trim() ?? '')
+ );
+ if (!found) throw new Error(`no button matching ${label}`);
+ return found;
+}
+
+function hasButton(label: RegExp): boolean {
+ return [...document.querySelectorAll('button')].some((b) =>
+ label.test(b.textContent?.trim() ?? '')
+ );
+}
+
+function messageBoxes(): Element[] {
+ return [...(container?.querySelectorAll('[role="status"], [role="alert"]') ?? [])];
+}
+
+function dialogText(): string {
+ return [...document.querySelectorAll('[role="dialog"]')].map((d) => d.textContent).join(' ');
+}
+
+async function click(element: HTMLElement): Promise<void> {
+ await act(async () => element.click());
+}
+
+describe('a running server', () => {
+ it('says it is running and up to date, offers Restart and Stop, and has no message', async () => {
+ state.startedAt = new Date().toISOString();
+ await render();
+
+ expect(text()).toContain('Running');
+ expect(text()).toContain('0.30.0 · up to date');
+ expect(text()).toContain('Running since');
+ expect(text()).toContain('This computer · runs with Docker');
+ expect(hasButton(/^Restart$/)).toBe(true);
+ expect(hasButton(/^Stop$/)).toBe(true);
+ expect(messageBoxes()).toHaveLength(0);
+ });
+
+ it('lists what has happened to it, most recent first', async () => {
+ state.activity = [
+ { at: new Date().toISOString(), action: 'started', detail: null },
+ { at: new Date(Date.now() - 86_400_000).toISOString(), action: 'updated', detail: '0.30.0' },
+ ];
+ await render();
+
+ expect(text()).toContain('Recent activity');
+ expect(text()).toMatch(/Started.*You · just now.*Updated to 0\.30\.0.*You · yesterday/);
+ });
+});
+
+describe('a server that is not running', () => {
+ it('names the workspaces that live on it and starts it from the one primary button', async () => {
+ state.localStatus = status({ phase: 'stopped' });
+ await render();
+
+ expect(text()).toContain('Not running');
+ expect(text()).toContain('Agents and rooms in Default and Scratch live here.');
+ expect(text()).toContain('Default, Scratch · unavailable');
+ await click(button(/^Start$/));
+ expect(state.localStart).toHaveBeenCalled();
+ });
+
+ it('says when it last ran', async () => {
+ state.localStatus = status({ phase: 'stopped' });
+ state.activity = [
+ { at: new Date(Date.now() - 2 * 86_400_000).toISOString(), action: 'stopped', detail: null },
+ ];
+ await render();
+
+ expect(text()).toContain('Last running2 days ago');
+ });
+});
+
+describe('a server that is starting', () => {
+ it('shows what it is doing, warns a first pull is slow, and offers nothing to press', async () => {
+ state.localStatus = status({ phase: 'starting', message: 'Pulling images…' });
+ await render();
+
+ expect(text()).toContain('Pulling images…');
+ expect(text()).toContain('This can take a few minutes the first time.');
+ expect(text()).toContain('available once running');
+ expect(button(/^Stop$/).disabled).toBe(true);
+ });
+});
+
+describe('a server that failed to start', () => {
+ it('shows the line that says why, what to do, and moves the port when asked', async () => {
+ state.localStatus = status({
+ phase: 'error',
+ error:
+ 'Error response from daemon: driver failed\ngateway: bind 0.0.0.0:8000: address already in use',
+ });
+ await render();
+
+ expect(text()).toContain('Failed to start');
+ expect(text()).toContain('gateway: bind 0.0.0.0:8000: address already in use');
+ expect(text()).toContain('Another program is using port 8000.');
+ await click(button(/^Use another port$/));
+ expect(state.useAnotherPort).toHaveBeenCalledWith(8000);
+ });
+
+ it('offers no way to move the port of a server on another host', async () => {
+ state.server = REMOTE;
+ state.remoteStatus = status({
+ phase: 'error',
+ error: 'gateway: bind 0.0.0.0:8000: address already in use',
+ });
+ await render();
+
+ expect(hasButton(/^Use another port$/)).toBe(false);
+ expect(hasButton(/^Try again$/)).toBe(true);
+ });
+
+ it('offers nothing to press for a server newer than this app', async () => {
+ state.localStatus = status({
+ phase: 'error',
+ deployedVersion: '0.31.0',
+ drift: { deployed: '0.31.0', expected: '0.30.0', direction: 'downgrade' },
+ });
+ await render();
+
+ expect(text()).toContain('This server is newer than Switch Console');
+ expect(hasButton(/^(Start|Try again)$/)).toBe(false);
+ });
+});
+
+describe('a stop that failed', () => {
+ it('says it could not stop, and offers to stop again rather than to start', async () => {
+ state.server = REMOTE;
+ state.remoteStatus = status({
+ phase: 'error',
+ failedTo: 'stop',
+ error: 'docker compose down failed: Container switch Stopping',
+ });
+ await render();
+
+ expect(text()).toContain("Couldn't stop");
+ expect(text()).not.toContain('Failed to start');
+ expect(hasButton(/^(Start|Try again)$/)).toBe(false);
+ await click(button(/^Stop again$/));
+ expect(state.remoteStop).toHaveBeenCalledWith('vm-1');
+ });
+});
+
+describe('a shared remote server', () => {
+ beforeEach(() => {
+ state.server = REMOTE;
+ state.register = SHARED;
+ });
+
+ it('says who else uses it', async () => {
+ await render();
+ expect(text()).toContain('Shared with bob@desk.');
+ expect(text()).toContain('vm-1 · runs with Docker');
+ });
+
+ it('asks before stopping it, naming who it reaches', async () => {
+ await render();
+ await click(button(/^Stop$/));
+
+ expect(state.remoteStop).not.toHaveBeenCalled();
+ expect(dialogText()).toContain('bob@desk');
+ });
+
+ it('asks before restarting it', async () => {
+ await render();
+ await click(button(/^Restart$/));
+
+ expect(state.remoteStart).not.toHaveBeenCalled();
+ expect(dialogText()).toContain('bob@desk');
+ });
+
+ it('updates at once from a held update, whose message names who it reaches', async () => {
+ state.remoteStatus = status({
+ upgrade: { state: 'held', from: '0.29.0', to: '0.30.0' },
+ deployedVersion: '0.29.0',
+ });
+ await render();
+
+ expect(text()).toContain('Update ready');
+ expect(text()).toContain('switch-core 0.30.0 is ready');
+ expect(text()).toContain('bob@desk used it recently');
+ expect(text()).toContain('0.29.0 → 0.30.0');
+ await click(button(/^Update now$/));
+ expect(state.remoteStart).toHaveBeenCalledWith('vm-1', 'Dev VM');
+ });
+
+ it('asks before a retried update restarts it for the others', async () => {
+ state.remoteStatus = status({
+ upgrade: { state: 'failed', from: '0.29.0', to: '0.30.0', error: 'backup failed' },
+ });
+ await render();
+
+ expect(text()).toContain('backup failed');
+ await click(button(/^Try again$/));
+ expect(state.remoteStart).not.toHaveBeenCalled();
+ expect(dialogText()).toContain('bob@desk');
+ });
+
+ it('shows what other Consoles did to it', async () => {
+ state.remoteStatus = status({
+ notice: 'bob@desk stopped this server.',
+ recordWarning: 'Could not record that you started it.',
+ });
+ await render();
+
+ expect(text()).toContain('bob@desk stopped this server.');
+ expect(text()).toContain('Could not record that you started it.');
+ });
+
+ it('says a reset deletes it for everyone, naming them, and resets that host', async () => {
+ await render();
+ await click(button(/^Reset…$/));
+
+ expect(dialogText()).toContain('bob@desk');
+ });
+});
+
+describe('a remote server nobody else uses', () => {
+ beforeEach(() => {
+ state.server = REMOTE;
+ state.register = ALONE;
+ });
+
+ it('stops at once', async () => {
+ await render();
+ await click(button(/^Stop$/));
+ expect(state.remoteStop).toHaveBeenCalledWith('vm-1');
+ });
+
+ it('says who it is waiting for, and stops waiting when asked', async () => {
+ state.remoteStatus = status({
+ phase: 'running',
+ message: 'Waiting for bob@desk (as bob) to finish starting the server…',
+ waitingFor: {
+ name: 'bob@desk',
+ hostAccount: 'bob',
+ action: 'starting',
+ heldForSeconds: 10,
+ expiresInSeconds: 50,
+ },
+ });
+ await render();
+
+ expect(text()).toContain('Waiting for bob@desk (as bob) to finish starting the server…');
+ await click(button(/^Stop waiting$/));
+ expect(state.cancelWait).toHaveBeenCalledWith('vm-1');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-server-controls.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-server-controls.test.tsx
deleted file mode 100644
index 685307714..000000000
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/remote-server-controls.test.tsx
+++ /dev/null
@@ -1,277 +0,0 @@
-import { act } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-vi.hoisted(() => {
- window.electronAPI ??= {
- invoke: () => Promise.resolve(undefined),
- eventOn: () => () => {},
- eventSend: () => {},
- } as unknown as typeof window.electronAPI;
-});
-
-function defaultStatus() {
- return {
- sshHost: 'vm-1',
- phase: 'running' as const,
- upgrade: null,
- serverId: 'srv-1',
- version: '0.37.0',
- deployedVersion: '0.37.0',
- drift: null,
- checkoutBuild: null,
- deployedTelemetry: null,
- message: null as string | null,
- error: null as string | null,
- notice: null as string | null,
- recordWarning: null as string | null,
- waitingFor: null as unknown,
- };
-}
-
-const state = vi.hoisted(() => ({
- register: null as unknown,
- status: undefined as unknown,
- hostBlocked: false,
- transitioning: false,
- running: true,
- docker: null as unknown,
- drift: null as unknown,
- logs: [] as string[],
- error: null as string | null,
- errorDetail: null as string | null,
- start: vi.fn(),
- stop: vi.fn(),
- cancelWait: vi.fn(),
- refresh: vi.fn(),
-}));
-
-vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({
- remoteServerStore: {
- init: () => Promise.resolve(),
- checkDocker: () => Promise.resolve(),
- loadRegister: () => Promise.resolve(),
- registerFor: () => state.register,
- statusFor: () => state.status,
- isHostBlocked: () => state.hostBlocked,
- isTransitioning: () => state.transitioning,
- isRunning: () => state.running,
- dockerFor: () => state.docker,
- driftFor: () => state.drift,
- logsFor: () => state.logs,
- get error() {
- return state.error;
- },
- get errorDetail() {
- return state.errorDetail;
- },
- start: (...args: unknown[]) => state.start(...args),
- stop: (...args: unknown[]) => state.stop(...args),
- cancelWait: (...args: unknown[]) => state.cancelWait(...args),
- refresh: (...args: unknown[]) => state.refresh(...args),
- },
-}));
-
-import { RemoteServerControls } from '@renderer/features/switch-servers/RemoteServerControls';
-import '@renderer/index.css';
-
-let container: HTMLDivElement | null = null;
-let root: Root | null = null;
-
-const OTHER_CONSOLE = {
- consoleId: 'bob',
- name: 'bob@desk',
- hostAccount: 'bob',
- appVersion: '0.37.0',
- lastSeenAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
-};
-
-beforeEach(() => {
- state.register = { self: 'me', consoles: [], activity: [] };
- state.status = defaultStatus();
- state.hostBlocked = false;
- state.transitioning = false;
- state.running = true;
- state.docker = null;
- state.drift = null;
- state.logs = [];
- state.error = null;
- state.errorDetail = null;
- state.start.mockReset();
- state.stop.mockReset();
- state.cancelWait.mockReset();
-});
-
-afterEach(async () => {
- await act(async () => root?.unmount());
- container?.remove();
- container = null;
- root = null;
-});
-
-async function render() {
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- await act(async () => root!.render(<RemoteServerControls sshHost="vm-1" name="Team Server" />));
-}
-
-function button(label: RegExp): HTMLButtonElement {
- const found = [...document.querySelectorAll('button')].find((b) =>
- label.test(b.textContent ?? '')
- );
- if (!found) throw new Error(`no button matching ${label}`);
- return found as HTMLButtonElement;
-}
-
-function dialogText(): string {
- return document.querySelector('[role="dialog"]')?.textContent ?? '';
-}
-
-async function click(element: HTMLElement): Promise<void> {
- await act(async () => element.click());
-}
-
-describe('sharing notice', () => {
- it('says who else has used the server recently', async () => {
- state.register = { self: 'me', consoles: [OTHER_CONSOLE], activity: [] };
- await render();
-
- expect(document.body.textContent).toContain(
- 'Shared with bob@desk. Stopping or restarting it affects them too.'
- );
- });
-
- it('says nothing when nobody else has used it', async () => {
- state.register = { self: 'me', consoles: [], activity: [] };
- await render();
-
- expect(document.body.textContent).not.toContain('Shared with');
- });
-});
-
-describe('host notices', () => {
- it('shows the status notice as an alert', async () => {
- state.status = { ...defaultStatus(), notice: 'Someone else started this stack.' };
- await render();
-
- expect(document.body.textContent).toContain('Someone else started this stack.');
- });
-
- it('shows the record warning as an alert', async () => {
- state.status = {
- ...defaultStatus(),
- recordWarning: 'Could not record that this Console started it.',
- };
- await render();
-
- expect(document.body.textContent).toContain('Could not record that this Console started it.');
- });
-});
-
-describe('stopping or restarting a shared stack', () => {
- it('asks before stopping it when others have used it lately', async () => {
- state.register = { self: 'me', consoles: [OTHER_CONSOLE], activity: [] };
- await render();
-
- await click(button(/^Stop$/));
-
- expect(state.stop).not.toHaveBeenCalled();
- expect(dialogText()).toMatch(/Stop the server on vm-1 for everyone\?/);
-
- await click(button(/Stop for everyone/));
-
- expect(state.stop).toHaveBeenCalledWith('vm-1');
- });
-
- it('asks before restarting it when others have used it lately', async () => {
- state.register = { self: 'me', consoles: [OTHER_CONSOLE], activity: [] };
- await render();
-
- await click(button(/^Restart$/));
-
- expect(state.start).not.toHaveBeenCalled();
- expect(dialogText()).toMatch(/Restart the server on vm-1 for everyone\?/);
-
- await click(button(/Restart for everyone/));
-
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('stops at once when nobody else has used it', async () => {
- state.register = { self: 'me', consoles: [], activity: [] };
- await render();
-
- await click(button(/^Stop$/));
-
- expect(state.stop).toHaveBeenCalledWith('vm-1');
- expect(dialogText()).toBe('');
- });
-
- it('restarts at once when nobody else has used it', async () => {
- state.register = { self: 'me', consoles: [], activity: [] };
- await render();
-
- await click(button(/^Restart$/));
-
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- expect(dialogText()).toBe('');
- });
-});
-
-describe('a stack ahead of this build', () => {
- it('disables Start rather than let a downgrade run', async () => {
- state.running = false;
- state.status = { ...defaultStatus(), phase: 'stopped' };
- state.drift = { deployed: '0.40.0', expected: '0.37.0', direction: 'downgrade' };
- await render();
-
- expect(button(/^Start$/).disabled).toBe(true);
- });
-});
-
-describe('waiting for another Console', () => {
- const bob = {
- name: 'bob@desk',
- hostAccount: 'bob',
- action: 'starting' as const,
- heldForSeconds: 40,
- expiresInSeconds: 80,
- };
-
- it('says who it is waiting for, and stops waiting when asked', async () => {
- state.transitioning = true;
- state.status = {
- ...defaultStatus(),
- phase: 'starting',
- message: 'Waiting for bob@desk (as bob) to finish starting the server…',
- waitingFor: bob,
- };
- await render();
-
- expect(document.body.textContent).toContain(
- 'Waiting for bob@desk (as bob) to finish starting the server…'
- );
- await click(button(/^Stop waiting$/));
-
- expect(state.cancelWait).toHaveBeenCalledWith('vm-1');
- });
-
- it('offers no way to stop a start that is not waiting on anyone', async () => {
- state.transitioning = true;
- state.status = { ...defaultStatus(), phase: 'starting', message: 'Starting containers…' };
- await render();
-
- expect(document.body.textContent).toContain('Starting containers…');
- expect(() => button(/^Stop waiting$/)).toThrow();
- });
-});
-
-describe('opening the page', () => {
- it('has the host looked at again, in case someone else started or removed the server', async () => {
- state.refresh.mockReset();
- await render();
-
- expect(state.refresh).toHaveBeenCalledWith('vm-1');
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx
index 1cd726da5..17eff91cf 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-stat-tiles.test.tsx
@@ -20,8 +20,19 @@ vi.mock('@renderer/lib/ipc', () => ({
rpc: { workspaces: { listBridges: async () => [] } },
}));
+const managed = vi.hoisted(() => ({ data: undefined as unknown[] | undefined }));
+
vi.mock('@renderer/features/locations/stores/agents-store', () => ({
- agentsStore: { loaded: true, load: async () => {}, agentsOnServer: () => [{}, {}] },
+ agentsStore: {
+ loaded: true,
+ load: async () => {},
+ agentsOnServer: () => [{ switchAgentId: 'a' }, { switchAgentId: 'b' }],
+ },
+}));
+
+vi.mock('@renderer/features/managed-agents/use-managed-agents', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useManagedAgents: () => ({ data: managed.data, isLoading: false }),
}));
vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
@@ -44,6 +55,7 @@ let container: HTMLDivElement | null = null;
let root: Root | null = null;
beforeEach(() => {
+ managed.data = undefined;
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
});
@@ -81,3 +93,9 @@ it('counts the agents onboarded on the server', async () => {
const tile = agentsTile(await render());
expect(tile.querySelectorAll('p')[1].textContent).toBe('2');
});
+
+it('counts the agents the server runs too, once each, as the Your Agents page lists them', async () => {
+ managed.data = [{ agentId: 'b' }, { agentId: 'c' }, { agentId: 'd' }];
+ const tile = agentsTile(await render());
+ expect(tile.querySelectorAll('p')[1].textContent).toBe('4');
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
index d46dbdb5d..a85176693 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/server-view-shared.test.tsx
@@ -100,17 +100,6 @@ vi.mock('@renderer/features/locations/stores/agents-store', () => ({
vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
switchRoomsStore: { refreshRoomState: () => Promise.resolve() },
}));
-vi.mock('@renderer/features/switch-servers/RemoteServerControls', () => ({
- RemoteServerControls: () => <div>remote controls</div>,
-}));
-vi.mock('@renderer/features/switch-servers/LocalServerControls', () => ({
- LocalServerControls: () => <div>local controls</div>,
-}));
-vi.mock('@renderer/features/switch-servers/shared-consoles-section', () => ({
- SharedConsolesSection: ({ sshHost }: { sshHost: string }) => (
- <div>{`consoles using ${sshHost}`}</div>
- ),
-}));
vi.mock('@renderer/features/switch-servers/MessagingAppsCard', () => ({
MessagingAppsCard: () => null,
}));
@@ -147,7 +136,6 @@ const BOB = {
};
const SHARED = { self: 'me', consoles: [BOB], activity: [] };
-const ALONE = { self: 'me', consoles: [], activity: [] };
let container: HTMLDivElement | null = null;
let root: Root | null = null;
@@ -190,10 +178,6 @@ function button(label: RegExp): HTMLElement {
return found as HTMLElement;
}
-function dialogText(): string {
- return [...document.querySelectorAll('[role="dialog"]')].map((d) => d.textContent).join(' ');
-}
-
function menuTrigger(): HTMLElement {
return document.querySelector('[aria-label="Server actions"]') as HTMLElement;
}
@@ -231,129 +215,3 @@ describe('the server menu', () => {
expect(button(/^Disconnect from server…$/)).toBeDefined();
});
});
-
-describe('restarting from a notice', () => {
- it('asks before a retried update restarts a server others use, naming them', async () => {
- state.upgrade = { state: 'failed', from: '0.27.0', to: '0.28.0', error: 'pull failed' };
- await render();
-
- await click(button(/^Retry$/));
-
- expect(state.start).not.toHaveBeenCalled();
- expect(dialogText()).toMatch(/Restart the server on vm-1 for everyone\?/);
- expect(dialogText()).toContain('bob@desk (as bob)');
- await click(button(/^Restart for everyone$/));
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('updates at once from a held update, whose own button names who it reaches', async () => {
- state.upgrade = { state: 'held', from: '0.27.0', to: '0.28.0' };
- await render();
-
- expect(document.body.textContent).toContain('bob@desk (as bob)');
- await click(button(/^Update for everyone$/));
-
- expect(dialogText()).toBe('');
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('starts a stopped server that owes an update without asking: it reaches nobody', async () => {
- state.running = false;
- state.upgrade = { state: 'pending', from: '0.27.0', to: '0.28.0' };
- await render();
-
- await click(button(/^Start and update$/));
-
- expect(dialogText()).toBe('');
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('restarts at once when nobody else uses the server', async () => {
- state.register = ALONE;
- state.upgrade = { state: 'failed', from: '0.27.0', to: '0.28.0', error: 'pull failed' };
- await render();
-
- await click(button(/^Retry$/));
-
- expect(dialogText()).toBe('');
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('asks before restarting to apply a usage-data “no” to a server others use', async () => {
- state.consent = false;
- state.deployedTelemetry = { known: true, enabled: true };
- await render();
-
- await click(button(/^Restart to apply$/));
-
- expect(state.start).not.toHaveBeenCalled();
- expect(dialogText()).toMatch(/Restart the server on vm-1 for everyone\?/);
- });
-
- it('offers no restart for a “yes” a shared server would not apply over the others', async () => {
- state.consent = true;
- state.deployedTelemetry = { known: true, enabled: false };
- await render();
-
- expect(() => button(/^Restart to apply$/)).toThrow();
- });
-
- it('offers that restart when nobody else uses the server', async () => {
- state.register = ALONE;
- state.consent = true;
- state.deployedTelemetry = { known: true, enabled: false };
- await render();
-
- await click(button(/^Restart to apply$/));
-
- expect(state.start).toHaveBeenCalledWith('vm-1', 'Team Server');
- });
-
- it('restarts a server on this computer without asking anyone', async () => {
- state.server = { ...REMOTE, managementKind: 'local', sshHost: null };
- state.register = null;
- state.localDrift = { deployed: 'dev-checkout', expected: '0.28.0', direction: 'unknown' };
- await render();
-
- await click(button(/^Restart to update$/));
-
- expect(dialogText()).toBe('');
- expect(state.localStart).toHaveBeenCalled();
- });
-
- it('asks before restarting a remote server others use to fix a version mismatch', async () => {
- state.drift = { deployed: 'dev-checkout', expected: '0.28.0', direction: 'unknown' };
- await render();
-
- await click(button(/^Restart to update$/));
-
- expect(state.start).not.toHaveBeenCalled();
- expect(dialogText()).toMatch(/Restart the server on vm-1 for everyone\?/);
- });
-});
-
-describe('the rest of a shared server’s page', () => {
- it('lists the Consoles using a remote server', async () => {
- await render();
-
- expect(document.body.textContent).toContain('consoles using vm-1');
- });
-
- it('lists none for a server on this computer', async () => {
- state.server = { ...REMOTE, managementKind: 'local', sshHost: null };
- await render();
-
- expect(document.body.textContent).not.toContain('consoles using');
- });
-
- it('says a reset deletes it for everyone, naming them, and resets that host', async () => {
- await render();
-
- await click(button(/^Reset…$/));
-
- expect(dialogText()).toContain('everyone who uses it');
- expect(dialogText()).toContain('bob@desk (as bob)');
- await click(button(/^Reset and delete all agents$/));
- expect(state.reset).toHaveBeenCalledWith('vm-1');
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/shared-consoles-section.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/shared-consoles-section.test.tsx
deleted file mode 100644
index f6798dea9..000000000
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/shared-consoles-section.test.tsx
+++ /dev/null
@@ -1,130 +0,0 @@
-import { act } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-vi.hoisted(() => {
- window.electronAPI ??= {
- invoke: () => Promise.resolve(undefined),
- eventOn: () => () => {},
- eventSend: () => {},
- } as unknown as typeof window.electronAPI;
-});
-
-const state = vi.hoisted(() => ({
- register: null as unknown,
- registerError: null as string | null,
-}));
-
-vi.mock('@renderer/features/switch-servers/remote-server-store', () => ({
- remoteServerStore: {
- registerFor: () => state.register,
- registerErrorFor: () => state.registerError,
- },
-}));
-
-import { SharedConsolesSection } from '@renderer/features/switch-servers/shared-consoles-section';
-import '@renderer/index.css';
-
-let container: HTMLDivElement | null = null;
-let root: Root | null = null;
-
-const SELF_CONSOLE = {
- consoleId: 'me',
- name: 'me@laptop',
- hostAccount: 'deploy',
- appVersion: '0.37.0',
- lastSeenAt: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
-};
-
-const OTHER_CONSOLE = {
- consoleId: 'bob',
- name: 'bob@desk',
- hostAccount: 'bob',
- appVersion: '0.36.0',
- lastSeenAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
-};
-
-beforeEach(() => {
- state.register = null;
- state.registerError = null;
-});
-
-afterEach(async () => {
- await act(async () => root?.unmount());
- container?.remove();
- container = null;
- root = null;
-});
-
-async function render() {
- container = document.createElement('div');
- document.body.appendChild(container);
- root = createRoot(container);
- await act(async () => root!.render(<SharedConsolesSection sshHost="vm-1" />));
-}
-
-describe('listing who uses a shared server', () => {
- it('renders nothing before the register has been read', async () => {
- state.register = null;
- state.registerError = null;
- await render();
-
- expect(container?.textContent).toBe('');
- });
-
- it('renders nothing for a server nobody has recorded anything on', async () => {
- state.register = { self: 'me', consoles: [], activity: [] };
- await render();
-
- expect(container?.textContent).toBe('');
- });
-
- it('lists each Console, marking this Console among them', async () => {
- state.register = { self: 'me', consoles: [SELF_CONSOLE, OTHER_CONSOLE], activity: [] };
- await render();
-
- const items = [...document.querySelectorAll('li')];
- const selfItem = items.find((li) => li.textContent?.includes('me@laptop'));
- const otherItem = items.find((li) => li.textContent?.includes('bob@desk'));
-
- expect(selfItem?.textContent).toContain('me@laptop (as deploy)');
- expect(selfItem?.textContent).toContain('this Console');
- expect(otherItem?.textContent).toContain('bob@desk (as bob)');
- expect(otherItem?.textContent).not.toContain('this Console');
- });
-
- it('shows recent activity lines', async () => {
- state.register = {
- self: 'me',
- consoles: [SELF_CONSOLE],
- activity: [
- {
- at: new Date().toISOString(),
- action: 'started',
- consoleId: 'me',
- name: 'me@laptop',
- hostAccount: 'deploy',
- },
- {
- at: new Date().toISOString(),
- action: 'stopped',
- consoleId: 'bob',
- name: 'bob@desk',
- hostAccount: 'bob',
- },
- ],
- };
- await render();
-
- expect(document.body.textContent).toContain('This Console started it');
- expect(document.body.textContent).toContain('bob@desk stopped it');
- });
-
- it('shows the error reading the register, when there is one', async () => {
- state.register = null;
- state.registerError = 'Could not read who uses this server.';
- await render();
-
- expect(document.body.textContent).toContain('Could not read who uses this server.');
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/version-drift-notice-layout.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/version-drift-notice-layout.test.tsx
deleted file mode 100644
index 97b60c3c0..000000000
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/version-drift-notice-layout.test.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { act } from 'react';
-import { createRoot } from 'react-dom/client';
-import { afterEach, describe, expect, it } from 'vitest';
-import { VersionDriftNotice } from '@renderer/features/switch-servers/VersionDriftNotice';
-import '@renderer/index.css';
-
-/**
- * `AlertAction` used to be positioned absolutely over a fixed `pr-18` gutter,
- * which only clears the text while the action stays narrower than that gutter.
- * "Restart to update" was roughly twice as wide, so the drift description ran
- * underneath the button (CHOO-1736). The stopped server's "Start and update"
- * action is as wide, and shares the layout.
- *
- * These assertions are on measured geometry rather than class strings: the bug
- * was invisible at the markup level — every class was present and correct — and
- * only a real layout reveals the overlap.
- */
-
-const PANEL_WIDTH = 660;
-
-let container: HTMLDivElement | null = null;
-
-async function renderNotice(deployed: string, expected: string): Promise<HTMLDivElement> {
- container = document.createElement('div');
- container.style.width = `${PANEL_WIDTH}px`;
- document.body.appendChild(container);
- const root = createRoot(container);
- await act(async () =>
- root.render(
- <VersionDriftNotice
- drift={{ direction: 'upgrade', deployed, expected }}
- upgrade={{ state: 'pending', from: deployed, to: expected }}
- progress={null}
- disabled={false}
- affected={null}
- onRestart={() => {}}
- />
- )
- );
- return container;
-}
-
-function rectsOverlap(a: DOMRect, b: DOMRect): boolean {
- return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
-}
-
-afterEach(() => {
- container?.remove();
- container = null;
-});
-
-describe('version drift notice layout', () => {
- it('keeps the restart button clear of the description text', async () => {
- const el = await renderNotice('0.11.0', '0.12.1');
- const button = el.querySelector('button');
- const description = el.querySelector('[data-slot="alert-description"]');
-
- expect(button).not.toBeNull();
- expect(description).not.toBeNull();
-
- const buttonRect = button!.getBoundingClientRect();
- const descriptionRect = description!.getBoundingClientRect();
-
- // Guard the guard: a zero-width button would trivially satisfy the overlap
- // check while proving nothing.
- expect(buttonRect.width).toBeGreaterThan(100);
- expect(descriptionRect.width).toBeGreaterThan(100);
-
- expect(rectsOverlap(buttonRect, descriptionRect)).toBe(false);
- });
-
- it('keeps the title clear of the restart button', async () => {
- const el = await renderNotice('0.11.0', '0.12.1');
- const button = el.querySelector('button');
- const title = el.querySelector('[data-slot="alert-title"]');
-
- const buttonRect = button!.getBoundingClientRect();
- const titleRect = title!.getBoundingClientRect();
-
- expect(rectsOverlap(buttonRect, titleRect)).toBe(false);
- });
-
- it('still clears the text when the version strings are long', async () => {
- const el = await renderNotice('0.11.0-rc.20260806+build.5', '0.12.1-rc.20260807+build.9');
- const button = el.querySelector('button');
- const description = el.querySelector('[data-slot="alert-description"]');
-
- const buttonRect = button!.getBoundingClientRect();
- const descriptionRect = description!.getBoundingClientRect();
-
- expect(rectsOverlap(buttonRect, descriptionRect)).toBe(false);
- });
-
- it('keeps the notice within its container', async () => {
- const el = await renderNotice('0.11.0', '0.12.1');
- const alert = el.querySelector('[data-slot="alert"]');
- const button = el.querySelector('button');
-
- const alertRect = alert!.getBoundingClientRect();
- const buttonRect = button!.getBoundingClientRect();
-
- expect(buttonRect.right).toBeLessThanOrEqual(alertRect.right + 0.5);
- });
-});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
index 2a3aff312..b4e50a62c 100644
--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/workspace-switcher.test.tsx
@@ -117,7 +117,6 @@ vi.mock('@renderer/features/switch-servers/server-presentation', () => ({
serverState: (server: SwitchServer) =>
state.unavailable.has(server.id) ? 'signed-out' : 'connected',
serverStatusLabel: (server: SwitchServer) => `${server.name} status`,
- serverSubtitleLabel: (server: SwitchServer) => `${server.name} status`,
}));
vi.mock('@renderer/features/switch-servers/server-icon', () => ({
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts
index aee6b4d2f..9afb61d26 100644
--- a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts
@@ -165,6 +165,9 @@ export function managedServerUpgradeBlockedReason(
/** Snapshot of the managed local server, emitted on every transition. */
export type LocalServerStatus = {
phase: LocalServerPhase;
+ /** Whether the stack's state has been read since launch. Until it has, a
+ * `stopped` phase is only the starting value, not something observed. */
+ checked: boolean;
/** Set while the stack is behind this build's pin and not yet upgraded. */
upgrade: ManagedServerUpgrade | null;
/** The registered server's id once the stack is up, else null. */
@@ -189,6 +192,10 @@ export type LocalServerStatus = {
message: string | null;
/** Populated only when `phase === 'error'`. */
error: string | null;
+ /** What failed when `phase === 'error'` and it was not a start: a stop or a
+ * reset that broke partway. Null for a failed start, and whenever the phase
+ * is anything else. */
+ failedTo: 'stop' | 'reset' | null;
};
/**
@@ -216,7 +223,7 @@ export class ManagedServerStoppedError extends Error {
/** Human-readable one-liner for a stopped managed stack, used in errors and the UI. */
export function managedServerStoppedReason(serverName: string, phase: LocalServerPhase): string {
if (phase === 'error') {
- return `${serverName}'s Switch stack failed to start, so its gateway is not running. Fix the error on the server's page, then start it again.`;
+ return `${serverName} isn't running: its last start or stop failed. See the server's page.`;
}
return `${serverName}'s Switch stack is not running. Start it from the server's page, then retry.`;
}
@@ -273,6 +280,19 @@ export type ConnectRemoteServerResult =
| { kind: 'cancelled' }
| { kind: 'error'; message: string };
+/** Something that happened to the stack on this computer, as Console recorded it. */
+export type LocalActivityAction = 'started' | 'stopped' | 'start-failed' | 'updated' | 'reset';
+
+/** One entry of the local stack's history. Only this Console acts on it, so
+ * there is no "who". */
+export type LocalActivityEntry = {
+ /** ISO timestamp. */
+ at: string;
+ action: LocalActivityAction;
+ /** The version an update moved to, or why a start failed; else null. */
+ detail: string | null;
+};
+
/** Something a Console did to a shared remote stack, as recorded on its host. */
export type StackActivityAction = 'started' | 'connected' | 'stopped' | 'reset' | 'disconnected';
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.test.ts b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.test.ts
new file mode 100644
index 000000000..83045eded
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { explainStartFailure } from './start-failure';
+
+describe('explainStartFailure', () => {
+ it('finds the port another program holds, from either way Docker says it', () => {
+ expect(
+ explainStartFailure('compose up failed\ngateway: bind 0.0.0.0:8000: address already in use')
+ ).toEqual({
+ line: 'gateway: bind 0.0.0.0:8000: address already in use',
+ hint: 'Another program is using port 8000. Quit it, or use another port, then try again.',
+ port: 8000,
+ });
+ expect(
+ explainStartFailure('Bind for 127.0.0.1:41000 failed: port is already allocated').port
+ ).toBe(41000);
+ });
+
+ it('says what to do about Docker not running', () => {
+ const failure = explainStartFailure(
+ 'Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?'
+ );
+ expect(failure.hint).toBe("Docker isn't running. Open Docker Desktop, then try again.");
+ expect(failure.port).toBeNull();
+ });
+
+ it('gives no advice it cannot back, only the first line of an error it does not know', () => {
+ expect(explainStartFailure('\nsomething odd happened\nmore detail')).toEqual({
+ line: 'something odd happened',
+ hint: null,
+ port: null,
+ });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.ts b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.ts
new file mode 100644
index 000000000..4a4310bef
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/start-failure.ts
@@ -0,0 +1,68 @@
+/**
+ * A failed start explained in a sentence a person can act on.
+ *
+ * `line` is the part of the raw error that says what happened, shown as it is
+ * so nothing is hidden behind the explanation. `hint` is what to do about it,
+ * or null when the error is not one we recognise: then the raw line is all
+ * there is, rather than a guess dressed up as advice.
+ */
+export type StartFailure = {
+ line: string;
+ hint: string | null;
+ /** The host port something else holds, when that is what stopped the start. */
+ port: number | null;
+};
+
+const MAX_LINE = 240;
+
+const PORT_IN_USE = [
+ /bind [^\s]*?:(\d+): address already in use/i,
+ /bind for [^\s]*?:(\d+) failed: port is already allocated/i,
+ /ports? (?:are|is) not available:.*?:(\d+)/i,
+];
+
+const KNOWN: { pattern: RegExp; hint: string }[] = [
+ {
+ pattern:
+ /cannot connect to the docker daemon|is the docker daemon running|docker desktop is not running/i,
+ hint: "Docker isn't running. Open Docker Desktop, then try again.",
+ },
+ {
+ pattern: /no space left on device/i,
+ hint: 'The disk is full. Free up some space, then try again.',
+ },
+ {
+ pattern:
+ /pull access denied|manifest unknown|tls handshake timeout|i\/o timeout|dial tcp|temporary failure in name resolution|net\/http: request canceled/i,
+ hint: "The server's images couldn't be downloaded. Check your internet connection, then try again.",
+ },
+];
+
+function trimLine(line: string): string {
+ const flat = line.trim().replace(/\s+/g, ' ');
+ return flat.length > MAX_LINE ? `${flat.slice(0, MAX_LINE - 1)}…` : flat;
+}
+
+/** The line of `error` that matches `pattern`, else the first non-empty one. */
+function lineFor(lines: string[], pattern: RegExp | null): string {
+ const hit = pattern ? lines.find((line) => pattern.test(line)) : undefined;
+ return trimLine(hit ?? lines[0] ?? '');
+}
+
+export function explainStartFailure(error: string): StartFailure {
+ const lines = error.split('\n').filter((line) => line.trim() !== '');
+ for (const pattern of PORT_IN_USE) {
+ const match = error.match(pattern);
+ if (!match) continue;
+ const port = Number(match[1]);
+ return {
+ line: lineFor(lines, pattern),
+ hint: `Another program is using port ${port}. Quit it, or use another port, then try again.`,
+ port,
+ };
+ }
+ for (const { pattern, hint } of KNOWN) {
+ if (pattern.test(error)) return { line: lineFor(lines, pattern), hint, port: null };
+ }
+ return { line: lineFor(lines, null), hint: null, port: null };
+}
diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
index be6242260..29037496f 100644
--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
@@ -15,6 +15,7 @@ export const VIEW_IDS = [
'room',
'settings',
'server',
+ 'managedServer',
'serverAgents',
'serverRooms',
'remoteHosts',