Skip to content

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

fix(console): stop same-version installs trading the sidecar (CHOO-1961) (#216)

Christian McDermott8a28f9a082a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dedf5f760..3ae519b2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -502,6 +502,22 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Fixed
+- Two Switch Console installs sharing an agent host no longer trade the sidecar
+ back and forth when they are on the *same* release but carry different builds
+ — the everyday case for dev builds, and the half of the shared-host problem
+ that version ordering could not reach. Each install now mints a deployer
+ identity and stamps it on whatever sidecar it deploys, so an install can tell
+ its own build from another's without relying on the version string. When the
+ versions are equal and the builds differ, the install that got there first
+ keeps the sidecar.
+- The agent's Settings tab says so: the sidecar reads **Another install's
+ build**, names who deployed the running one, and offers Restart — a
+ deliberate takeover — instead of an Update that both sides would keep
+ clicking at each other. Replacement is otherwise unchanged: an older sidecar
+ is still replaced whoever deployed it, and a rebuild of your own is still
+ picked up.
+
### [0.23.0] - 2026-08-14
#### Added
@@ -1375,6 +1391,16 @@ The remote runtime Switch Console deploys to an agent host. Versioned in
`console/apps/switch-console-desktop/src/sidecar/sidecar-version.ts` and deployed
by Switch Console rather than published on its own.
+### [Unreleased]
+
+#### Added
+- The ready file carries a `deployer` field: the identity of the Switch Console
+ install that started this sidecar, echoed from the environment it was
+ launched with. It is the one thing on the host that says *whose* build is
+ running — the content hash says only which. Purely additive, so no contract
+ revision moves: an older client ignores the field, and a client reading a
+ sidecar that omits it must treat that as unknown rather than as its own.
+
### [1.9.2]
#### Changed
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
index 68a6aa6c9..276393ad9 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
@@ -1,6 +1,7 @@
import type { SwitchLaunchSpecialization } from '@switch-console/core/agents/plugins';
import { generateAgentLaunchSpec } from '@main/core/agents/generate-agent-launch-spec';
import type { IExecutionContext } from '@main/core/execution-context/types';
+import { deployerIdentity } from '@main/core/sidecar/deployer-identity';
import { log } from '@main/lib/logger';
import {
agentSidecarTmuxName,
@@ -37,6 +38,7 @@ export interface AgentSidecarParams {
}
async function buildLauncher(params: AgentSidecarParams): Promise<RemoteSidecarLauncher> {
+ const deployerId = await deployerIdentity();
const launchSpec = await generateAgentLaunchSpec({
providerId: params.providerId,
remoteRepoDir: params.repoDir,
@@ -57,6 +59,7 @@ async function buildLauncher(params: AgentSidecarParams): Promise<RemoteSidecarL
deeplinkScheme: params.deeplinkScheme,
launchSpec,
credsSlug: params.credsSlug,
+ deployerId,
},
// Bound once here so every line the launcher writes names the agent it is
// acting for. Sidecar work runs off watchers rather than an RPC call, so
@@ -96,17 +99,18 @@ export async function probeAgentSidecar(
/**
* Read-only status of an agent's sidecar for the UI (running? which build/
* protocol/epoch/pid? how many live sessions?), plus this client's own bundle
- * hash so the caller can render the client-vs-host verdict. Never launches.
+ * hash and deployer identity so the caller can render the client-vs-host
+ * verdict. Never launches.
*/
export async function readAgentSidecarStatus(
params: AgentSidecarParams
-): Promise<{ status: SidecarRunStatus; clientHash: string }> {
+): Promise<{ status: SidecarRunStatus; clientHash: string; clientDeployerId: string }> {
const launcher = await buildLauncher(params);
const [status, clientHash] = await Promise.all([
launcher.readStatus(),
launcher.localBundleHash(),
]);
- return { status, clientHash };
+ return { status, clientHash, clientDeployerId: launcher.localDeployerId() };
}
/**
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
index 27779ebb2..f1717f2dc 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
@@ -23,11 +23,15 @@ const SPEC: AgentLaunchSpec = {
deeplinkScheme: 'switchdash',
};
+/** This client install's deployer identity, as minted once and persisted locally. */
+const DEPLOYER_ID = 'install-under-test';
+
const CONFIG: SidecarLaunchConfig = {
repoDir: '/home/dev/repo',
deeplinkScheme: 'switchdash',
launchSpec: SPEC,
credsSlug: 'claude-code.repo.me',
+ deployerId: DEPLOYER_ID,
};
/** The endpoint the launcher derives for CONFIG — sessions are pointed at this
@@ -38,7 +42,8 @@ const ENDPOINT = { port: 4321, token: 'tok-abc', endpointFile: ENDPOINT_FILE };
const readyLine = (
hash: string | undefined = 'hash-v1',
epoch = 1,
- version: string | undefined = SIDECAR_VERSION
+ version: string | undefined = SIDECAR_VERSION,
+ deployer: string | undefined = DEPLOYER_ID
): string =>
`${JSON.stringify({
event: 'ready',
@@ -47,6 +52,7 @@ const readyLine = (
hash,
epoch,
version,
+ deployer,
})}\n`;
const noopLog = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
@@ -84,6 +90,8 @@ function makeHost(
liveSessions?: number;
/** Bundle hash the (already-running) sidecar's ready line reports. */
readyHash?: string;
+ /** Install that deployed the running sidecar (undefined = predates the field). */
+ readyDeployer?: string;
/** What `tail` of the sidecar log returns after a startup crash. */
logTail?: string;
} = {}
@@ -91,6 +99,7 @@ function makeHost(
const existingSidecar = opts.existingSidecar ?? false;
const readyHash = opts.readyHash ?? 'hash-v1';
const readyVersion = 'readyVersion' in opts ? opts.readyVersion : SIDECAR_VERSION;
+ const readyDeployer = 'readyDeployer' in opts ? opts.readyDeployer : DEPLOYER_ID;
const readyAfter = opts.readyAfter ?? 0;
const diesAfter = opts.diesAfter ?? Infinity;
const calls: ExecCall[] = [];
@@ -141,7 +150,7 @@ function makeHost(
}));
return { stdout: JSON.stringify({ version: '1', epoch, sessions }), stderr: '' };
}
- const line = readyLine(readyHash, epoch, readyVersion);
+ const line = readyLine(readyHash, epoch, readyVersion, readyDeployer);
if (existingSidecar) return { stdout: line, stderr: '' };
const n = catReads++;
if (n < readyAfter) throw new Error('no such file');
@@ -397,6 +406,80 @@ describe('RemoteSidecarLauncher versioning', () => {
expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);
});
+ it('yields to another install’s build of the same version instead of replacing it', async () => {
+ // The residual half of CHOO-1937: version ordering separates two installs on
+ // different releases, but two dev builds of the SAME release differ only by
+ // hash — and a hash says which build, never whose. Each install read the
+ // other's as an upgrade and they traded the sidecar back and forth forever.
+ const { host, calls, puts } = makeHost({
+ existingSidecar: true,
+ readyHash: 'hash-theirs',
+ readyDeployer: 'some-other-install',
+ });
+
+ const endpoint = await makeLauncher(host).deployAndLaunch();
+
+ expect(endpoint).toEqual(ENDPOINT);
+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(false);
+ expect(puts).toHaveLength(0);
+ });
+
+ it('still replaces another install’s OLDER build — replacement stays version-ordered', async () => {
+ // Yielding applies only to the tie. Making it unconditional would be the
+ // blanket version gate `sidecar-version.ts` exists to argue against.
+ const { host, calls } = makeHost({
+ existingSidecar: true,
+ readyHash: 'hash-theirs',
+ readyDeployer: 'some-other-install',
+ readyVersion: '1.0.0',
+ });
+
+ await makeLauncher(host).deployAndLaunch();
+
+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);
+ });
+
+ it('replaces a same-version sidecar this very install deployed — the rebuild loop', async () => {
+ const { host, calls } = makeHost({
+ existingSidecar: true,
+ readyHash: 'hash-mine-but-older',
+ readyDeployer: DEPLOYER_ID,
+ });
+
+ await makeLauncher(host).deployAndLaunch();
+
+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);
+ });
+
+ it('replaces a sidecar deployed before installs identified themselves', async () => {
+ // Unknown is not foreign. One deploy stamps an id, so the trading ends after
+ // a single round rather than the host being frozen on an unowned sidecar.
+ const { host, calls } = makeHost({
+ existingSidecar: true,
+ readyHash: 'hash-old',
+ readyDeployer: undefined,
+ });
+
+ await makeLauncher(host).deployAndLaunch();
+
+ expect(calls.some((c) => c.command === 'tmux' && c.args[0] === 'kill-session')).toBe(true);
+ });
+
+ it('reports who deployed the running sidecar, and what this install is', async () => {
+ const { host } = makeHost({ existingSidecar: true, readyDeployer: 'some-other-install' });
+ const launcher = makeLauncher(host);
+
+ expect((await launcher.readStatus()).deployerId).toBe('some-other-install');
+ expect(launcher.localDeployerId()).toBe(DEPLOYER_ID);
+ });
+
+ it('stamps this install’s identity on the sidecar it launches', async () => {
+ const { host, calls } = makeHost();
+ await makeLauncher(host).deployAndLaunch();
+ const launch = calls.find((c) => c.command === 'tmux' && c.args[0] === 'new-session');
+ expect(launch!.args[6]).toContain(`SWITCHDASH_SIDECAR_DEPLOYER_ID='${DEPLOYER_ID}'`);
+ });
+
it('replaces an incompatible sidecar even when sessions are live', async () => {
// Compatibility is the one reason worth interrupting work for: we cannot
// talk to it at all, so deferring would mean never recovering.
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
index a33f84664..53182fb44 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
@@ -36,7 +36,8 @@ import {
* bound; the launcher polls that file until a line from the incarnation it just
* started appears, then returns the endpoint so the caller can point its remote
* sessions' hook env at the VM-local server. The ready line also carries the
- * sidecar's `version` (human-readable `x.y`) and build `hash`.
+ * sidecar's `version` (human-readable `x.y`), its build `hash`, and the
+ * `deployer` identity of the install that started it.
*
* Replacing a running sidecar is serialised across clients by a host-side deploy
* lock: two clients deploying at once would overwrite the bundle under each
@@ -65,6 +66,10 @@ export interface SidecarLaunchConfig {
* id — so the sidecar reads `.switch/agents/<slug>.json` for this agent's Switch
* identity rather than the legacy shared settings file (CHOO-1440). */
credsSlug: string;
+ /** This Switch Console install's deployer identity, stamped on whatever sidecar
+ * it starts so another install can tell that build apart from its own without
+ * relying on the version string. */
+ deployerId: string;
}
export interface SidecarEndpoint {
@@ -95,6 +100,9 @@ interface ReadyLine {
contract: ContractRange | null;
/** OS process id of the running sidecar, for display. Absent from an older one. */
pid: number | null;
+ /** Which Switch Console install deployed this sidecar. Null for one deployed
+ * before installs identified themselves, which means *unknown* — never "mine". */
+ deployer: string | null;
}
/**
@@ -115,6 +123,9 @@ export interface SidecarRunStatus {
contract: ContractRange | null;
epoch: number | null;
pid: number | null;
+ /** The install that deployed it, or null when it predates deployer identity.
+ * Null must read as unknown, never as this install. */
+ deployerId: string | null;
/** Sessions the running sidecar currently owns, from its durable state. */
liveSessions: number;
}
@@ -136,6 +147,7 @@ function sidecarEnv(config: SidecarLaunchConfig): Record<string, string> {
SWITCHDASH_SIDECAR_REPO_DIR: config.repoDir,
SWITCHDASH_SIDECAR_DEEPLINK_SCHEME: config.deeplinkScheme,
SWITCHDASH_SIDECAR_AGENT_SLUG: config.credsSlug,
+ SWITCHDASH_SIDECAR_DEPLOYER_ID: config.deployerId,
};
}
@@ -167,6 +179,10 @@ function parseReady(raw: string): ReadyLine | null {
const version =
'version' in parsed && typeof parsed.version === 'string' ? parsed.version : null;
const pid = 'pid' in parsed && typeof parsed.pid === 'number' ? parsed.pid : null;
+ const deployer =
+ 'deployer' in parsed && typeof parsed.deployer === 'string' && parsed.deployer
+ ? parsed.deployer
+ : null;
return {
port: parsed.port,
token: parsed.token,
@@ -175,6 +191,7 @@ function parseReady(raw: string): ReadyLine | null {
version,
contract: parseContract(parsed),
pid,
+ deployer,
};
}
return null;
@@ -561,6 +578,7 @@ export class RemoteSidecarLauncher {
contract: null,
epoch: null,
pid: null,
+ deployerId: null,
liveSessions: 0,
};
}
@@ -572,6 +590,7 @@ export class RemoteSidecarLauncher {
contract: ready.contract,
epoch: ready.epoch,
pid: ready.pid,
+ deployerId: ready.deployer,
liveSessions: await this.runningSessionCount(),
};
}
@@ -582,6 +601,12 @@ export class RemoteSidecarLauncher {
return this.hashBundle();
}
+ /** This install's deployer identity, for the caller to compare against
+ * `readStatus().deployerId`. */
+ localDeployerId(): string {
+ return this.config.deployerId;
+ }
+
async probeExisting(): Promise<SidecarEndpoint | null> {
const ready = await this.readRunning();
if (!ready) return null;
@@ -605,6 +630,8 @@ export class RemoteSidecarLauncher {
* - same build → reattach; there is nothing to gain.
* - newer version → reattach; a newer Switch Console deployed it, and replacing
* it would be a downgrade.
+ * - same version, another install's build → reattach; neither of us can claim
+ * to be the upgrade, so whoever got there first keeps it.
* - different build, no live sessions → upgrade, since nothing is disturbed.
* - different build, live sessions → reattach and record that an upgrade is
* pending, rather than interrupting work in flight for a build difference.
@@ -639,6 +666,34 @@ export class RemoteSidecarLauncher {
return this.toEndpoint(ready);
}
+ // Version ordering has nothing left to say once the versions are equal, and
+ // that is the everyday case for two dev builds of one release: each install
+ // reads the other's hash as an upgrade and they trade the sidecar back and
+ // forth for as long as both are open. So when the build on the host is
+ // another install's, yield to it — whoever deployed first keeps it, and the
+ // operator's Restart is the way to take it over deliberately.
+ //
+ // Only ever replaces LESS than before: an older version is still replaced,
+ // and an unidentified sidecar (deployed before this, or by our own install)
+ // still is, so a single deploy ends the trading rather than nothing ever
+ // being upgraded again.
+ if (
+ ready.deployer !== null &&
+ ready.deployer !== this.config.deployerId &&
+ compareSidecarVersions(ready.version, SIDECAR_VERSION) === 0
+ ) {
+ this.log.debug(
+ 'RemoteSidecarLauncher: another install deployed this sidecar at the same version — leaving it in place',
+ {
+ sidecarTmuxName: this.sidecarTmuxName,
+ version: ready.version,
+ runningHash: ready.hash,
+ localHash,
+ }
+ );
+ return this.toEndpoint(ready);
+ }
+
const liveSessions = await this.runningSessionCount();
if (liveSessions > 0) {
this.log.warn(
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
index 45a39caf3..75b4d8270 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
@@ -83,6 +83,12 @@ vi.mock('@main/core/agents/getAgentById', () => ({
getAgentById: vi.fn(async () => ({ autoApprove: false })),
}));
+// Same reason: this install's deployer identity is persisted in the DB, and the
+// sidecar launch path reads it to stamp whatever sidecar it starts.
+vi.mock('@main/core/sidecar/deployer-identity', () => ({
+ deployerIdentity: vi.fn(async () => 'install-under-test'),
+}));
+
vi.mock('@main/core/providers/plugin-registry', () => ({
getPlugin: vi.fn(defaultGetPlugin),
}));
diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts
index b833135a2..a93a10f24 100644
--- a/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts
@@ -61,15 +61,23 @@ async function paramsForAgent(agent: Agent): Promise<AgentSidecarParams> {
*/
async function readAndBroadcast(agentId: string): Promise<AgentSidecarStatus> {
const { agent, sshHost, repoDir, credsSlug } = await requireRemoteAgent(agentId);
- const { status, clientHash } = await readAgentSidecarStatus(await paramsForAgent(agent));
+ const { status, clientHash, clientDeployerId } = await readAgentSidecarStatus(
+ await paramsForAgent(agent)
+ );
const full: AgentSidecarStatus = {
agentId,
running: status.running,
- verdict: verdictFor(status, clientHash, SIDECAR_VERSION),
+ verdict: verdictFor(status, {
+ hash: clientHash,
+ version: SIDECAR_VERSION,
+ deployerId: clientDeployerId,
+ }),
clientHash,
clientVersion: SIDECAR_VERSION,
+ clientDeployerId,
deployedHash: status.hash,
deployedVersion: status.version,
+ deployedBy: status.deployerId,
epoch: status.epoch,
pid: status.pid,
liveSessions: status.liveSessions,
diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.db.test.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.db.test.ts
new file mode 100644
index 000000000..e197b09cb
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.db.test.ts
@@ -0,0 +1,77 @@
+import { openFixture } from '@tooling/utils/db';
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AppDb } from '@main/db/client';
+import { kv } from '@main/db/schema';
+import { deployerIdentity } from './deployer-identity';
+
+const mocks = vi.hoisted(() => ({
+ db: undefined as AppDb | undefined,
+}));
+
+vi.mock('@main/db/client', () => ({
+ get db() {
+ if (!mocks.db) throw new Error('Test database not initialized');
+ return mocks.db;
+ },
+}));
+
+const DEPLOYER_ID_KEY = 'sidecarDeployerId';
+
+describe('deployerIdentity', () => {
+ let fixture: Awaited<ReturnType<typeof openFixture>>;
+
+ beforeEach(async () => {
+ fixture = await openFixture('empty');
+ mocks.db = fixture.db;
+ });
+
+ afterEach(() => {
+ fixture.close();
+ mocks.db = undefined;
+ });
+
+ it('mints an id on first use and keeps it', async () => {
+ const first = await deployerIdentity();
+ expect(first).not.toBe('');
+ expect(await deployerIdentity()).toBe(first);
+ });
+
+ it('persists exactly one row rather than re-minting per call', async () => {
+ // A different id every launch would be worse than none: this install would
+ // read its own previous sidecar as another install's and never upgrade it.
+ await deployerIdentity();
+ await deployerIdentity();
+ expect(await fixture.db.select().from(kv).where(eq(kv.key, DEPLOYER_ID_KEY))).toHaveLength(1);
+ });
+
+ it('returns one shared id when concurrent callers race to mint', async () => {
+ const [a, b, c] = await Promise.all([
+ deployerIdentity(),
+ deployerIdentity(),
+ deployerIdentity(),
+ ]);
+ expect(b).toBe(a);
+ expect(c).toBe(a);
+ });
+
+ it('keeps the id an earlier run already stored', async () => {
+ await fixture.db
+ .insert(kv)
+ .values({ key: DEPLOYER_ID_KEY, value: 'minted-earlier', updatedAt: sql`CURRENT_TIMESTAMP` });
+
+ expect(await deployerIdentity()).toBe('minted-earlier');
+ });
+
+ it('is unique per install', async () => {
+ const mine = await deployerIdentity();
+
+ const other = await openFixture('empty');
+ mocks.db = other.db;
+ try {
+ expect(await deployerIdentity()).not.toBe(mine);
+ } finally {
+ other.close();
+ }
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.ts
new file mode 100644
index 000000000..f1c9eac63
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/deployer-identity.ts
@@ -0,0 +1,63 @@
+import { randomUUID } from 'node:crypto';
+import { eq, sql } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { kv } from '@main/db/schema';
+
+/**
+ * This install's deployer identity: who "my build" belongs to, independently of
+ * the version string.
+ *
+ * A sidecar is deployed to a host, not published to it, and two Switch Console
+ * installs sharing a host both deploy into the same directory. Version ordering
+ * decides between them when their releases differ (CHOO-1937) — but two dev
+ * builds of the SAME release differ only by content hash, and a hash says which
+ * build, never whose. Without an identity each install reads the other's sidecar
+ * as an upgrade and they trade it back and forth for as long as both are open.
+ *
+ * Random rather than derived from the machine, the user, or the install path:
+ * this id is written to a host colleagues can read, and none of those are ours
+ * to disclose. It identifies an install only by being different from every other
+ * one.
+ *
+ * Minted on first use and kept for the life of the install's database. A reset
+ * database mints a new one, which reads as a different install — the sidecar it
+ * previously deployed then looks foreign and is left alone rather than replaced.
+ * That is the safe direction to be wrong in, and Restart still forces it.
+ */
+const DEPLOYER_ID_KEY = 'sidecarDeployerId';
+
+async function readDeployerId(): Promise<string | null> {
+ const [row] = await db.select().from(kv).where(eq(kv.key, DEPLOYER_ID_KEY)).limit(1);
+ const value = row?.value.trim();
+ return value ? value : null;
+}
+
+/**
+ * The id, minting and persisting one if this install has never had one.
+ *
+ * Deliberately un-cached in this process: it precedes SSH round trips that cost
+ * orders of magnitude more than a local point-select, and a cache would need a
+ * test-only way to clear it.
+ *
+ * Raises rather than falling back to a fresh id when it cannot be persisted. An
+ * id that changes every launch is worse than no id at all: every launch would
+ * see its own previous sidecar as another install's and refuse to upgrade it.
+ */
+export async function deployerIdentity(): Promise<string> {
+ const existing = await readDeployerId();
+ if (existing) return existing;
+
+ // `onConflictDoNothing` then re-read, rather than an upsert: two concurrent
+ // callers each mint a candidate and exactly one row survives, so both return
+ // the same id instead of the second overwriting the first.
+ await db
+ .insert(kv)
+ .values({ key: DEPLOYER_ID_KEY, value: randomUUID(), updatedAt: sql`CURRENT_TIMESTAMP` })
+ .onConflictDoNothing();
+
+ const settled = await readDeployerId();
+ if (!settled) {
+ throw new Error("sidecar: could not persist this install's deployer identity");
+ }
+ return settled;
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts
index 30062e161..20ede005d 100644
--- a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.test.ts
@@ -4,6 +4,7 @@ import { verdictFor } from './verdict';
const CLIENT = 'client-hash';
const CLIENT_VERSION = '1.7.0';
+const CLIENT_DEPLOYER = 'install-a';
const status = (over: Partial<SidecarRunStatus>): SidecarRunStatus => ({
running: true,
@@ -13,12 +14,17 @@ const status = (over: Partial<SidecarRunStatus>): SidecarRunStatus => ({
contract: { speaks: 1, accepts: 1 },
epoch: 1,
pid: 100,
+ deployerId: CLIENT_DEPLOYER,
liveSessions: 0,
...over,
});
const verdict = (over: Partial<SidecarRunStatus>) =>
- verdictFor(status(over), CLIENT, CLIENT_VERSION);
+ verdictFor(status(over), {
+ hash: CLIENT,
+ version: CLIENT_VERSION,
+ deployerId: CLIENT_DEPLOYER,
+ });
describe('verdictFor', () => {
it('not-running when nothing is up', () => {
@@ -52,6 +58,48 @@ describe('verdictFor', () => {
expect(verdict({ hash: 'other', version: '2.0', liveSessions: 4 })).toBe('newer-on-host');
});
+ it("other-install when the same version's build belongs to another install", () => {
+ // Version ordering cannot separate them and the hash says which build, never
+ // whose — so without this both installs read the other as an upgrade.
+ expect(verdict({ hash: 'other', deployerId: 'install-b' })).toBe('other-install');
+ });
+
+ it('other-install outranks the live-session check', () => {
+ // Not a deferred upgrade: there is no upgrade here to defer.
+ expect(verdict({ hash: 'other', deployerId: 'install-b', liveSessions: 3 })).toBe(
+ 'other-install'
+ );
+ });
+
+ it('upgrade-available for our own earlier build — the local rebuild loop', () => {
+ expect(verdict({ hash: 'other', deployerId: CLIENT_DEPLOYER })).toBe('upgrade-available');
+ });
+
+ it('upgrade-available for a sidecar deployed before installs identified themselves', () => {
+ // Unknown, not foreign. One deploy stamps an id and the trading stops after
+ // a single round rather than nothing ever being upgraded again.
+ expect(verdict({ hash: 'other', deployerId: null })).toBe('upgrade-available');
+ });
+
+ it('still replaces another install’s OLDER build — version ordering wins first', () => {
+ // Yielding is only for the tie. An older sidecar is replaceable no matter
+ // who deployed it, which is what keeps CHOO-1937 working.
+ expect(verdict({ hash: 'other', version: '1.6', deployerId: 'install-b' })).toBe(
+ 'upgrade-available'
+ );
+ });
+
+ it("newer-on-host outranks another install's identity", () => {
+ expect(verdict({ hash: 'other', version: '1.8', deployerId: 'install-b' })).toBe(
+ 'newer-on-host'
+ );
+ });
+
+ it('up-to-date when another install deployed this exact build', () => {
+ // Same bytes: whose they are makes no difference to anything.
+ expect(verdict({ hash: CLIENT, deployerId: 'install-b' })).toBe('up-to-date');
+ });
+
it('incompatible outranks any build comparison', () => {
// Even the same hash is moot if we cannot speak its protocol — though in
// practice an incompatible sidecar is a different build anyway.
diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts
index 390341bf6..768d2b9e6 100644
--- a/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/verdict.ts
@@ -2,6 +2,14 @@ import type { SidecarRunStatus } from '@main/core/agent-runtime/impl/remote-side
import type { SidecarVerdict } from '@shared/events/sidecarEvents';
import { compareSidecarVersions } from '../../../sidecar/sidecar-version';
+/** What this client ships, and who it is — the other half of the comparison. */
+export interface SidecarClientBuild {
+ hash: string;
+ version: string;
+ /** This install's deployer identity (see `deployer-identity.ts`). */
+ deployerId: string;
+}
+
/**
* Turn a raw host status + this client's build into the client-vs-host verdict.
*
@@ -13,15 +21,21 @@ import { compareSidecarVersions } from '../../../sidecar/sidecar-version';
* upgrade, matching what the launcher will actually do with it. Offering
* "Update" there would invite a downgrade, and on a host two installs share it
* is an invitation each of them accepts in turn (CHOO-1937).
+ *
+ * The same is true one step further down, where version ordering has run out:
+ * a same-version build another install deployed is not an upgrade either, and
+ * offering one is how two dev builds trade the sidecar back and forth. Must stay
+ * in step with `decideExisting` in the launcher — a verdict the deploy policy
+ * disagrees with is an Update button that silently does nothing.
*/
-export function verdictFor(
- status: SidecarRunStatus,
- clientHash: string,
- clientVersion: string
-): SidecarVerdict {
+export function verdictFor(status: SidecarRunStatus, client: SidecarClientBuild): SidecarVerdict {
if (!status.running) return 'not-running';
if (!status.compatible) return 'incompatible';
- if (status.hash === clientHash) return 'up-to-date';
- if (compareSidecarVersions(status.version, clientVersion) > 0) return 'newer-on-host';
+ if (status.hash === client.hash) return 'up-to-date';
+ const order = compareSidecarVersions(status.version, client.version);
+ if (order > 0) return 'newer-on-host';
+ if (order === 0 && status.deployerId !== null && status.deployerId !== client.deployerId) {
+ return 'other-install';
+ }
return status.liveSessions > 0 ? 'upgrade-pending' : 'upgrade-available';
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
index 967e423c2..f32e45cc0 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/sidecar-settings-section.tsx
@@ -1,5 +1,13 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { AlertTriangle, CheckCircle2, Loader2, Power, RefreshCw, XCircle } from 'lucide-react';
+import {
+ AlertTriangle,
+ CheckCircle2,
+ Loader2,
+ Power,
+ RefreshCw,
+ Users,
+ XCircle,
+} from 'lucide-react';
import { useEffect, useState } from 'react';
import { events, rpc } from '@renderer/lib/ipc';
import { Badge } from '@renderer/lib/ui/badge';
@@ -27,6 +35,19 @@ function shortHash(hash: string | null): string {
return hash ? hash.slice(0, SHORT_HASH) : '—';
}
+/**
+ * Who deployed the sidecar that is running, in the operator's terms.
+ *
+ * The id itself is meaningless on its own, so it is shown only for the case
+ * where two of them are being told apart — and then abbreviated, as a handle to
+ * match against the other machine's, not as something to read.
+ */
+function deployedByLabel(status: AgentSidecarStatus): string {
+ if (!status.deployedBy) return 'unknown (deployed before installs were identified)';
+ if (status.deployedBy === status.clientDeployerId) return 'this install';
+ return `another install (${shortHash(status.deployedBy)})`;
+}
+
const VERDICT_DISPLAY: Record<
SidecarVerdict,
{
@@ -39,10 +60,20 @@ const VERDICT_DISPLAY: Record<
'upgrade-available': { label: 'Update available', variant: 'default', icon: RefreshCw },
'upgrade-pending': { label: 'Update pending', variant: 'outline', icon: AlertTriangle },
'newer-on-host': { label: 'Newer on host', variant: 'secondary', icon: CheckCircle2 },
+ 'other-install': { label: "Another install's build", variant: 'secondary', icon: Users },
incompatible: { label: 'Incompatible', variant: 'destructive', icon: AlertTriangle },
'not-running': { label: 'Not running', variant: 'outline', icon: XCircle },
};
+/**
+ * Verdicts where Update has nothing to do, so the button is disabled rather than
+ * offering an action the deploy policy will decline. `other-install` is one of
+ * them: this build is not an upgrade over another install's build of the same
+ * release, and offering it to both installs is the tug-of-war itself. Restart
+ * remains the deliberate way to take the sidecar over.
+ */
+const NOTHING_TO_UPDATE = new Set<SidecarVerdict>(['up-to-date', 'incompatible', 'other-install']);
+
export function SidecarSettingsSection({ agentId }: { agentId: string }) {
const queryClient = useQueryClient();
const queryKey = statusQueryKey(agentId);
@@ -105,7 +136,7 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {
<Button
size="sm"
variant="outline"
- disabled={busy || data.verdict === 'up-to-date' || data.verdict === 'incompatible'}
+ disabled={busy || NOTHING_TO_UPDATE.has(data.verdict)}
onClick={() => upgrade.mutate()}
>
{upgrade.isPending ? (
@@ -138,6 +169,15 @@ export function SidecarSettingsSection({ agentId }: { agentId: string }) {
</Button>
</div>
+ {data.verdict === 'other-install' && (
+ <p className="text-xs text-foreground-muted">
+ Another Switch Console install on this host deployed the running sidecar, from the
+ same release as yours. Neither build is newer, so this one leaves it alone rather than
+ the two of you replacing it in turn. Use Restart to run your build instead — the other
+ install will then leave yours alone.
+ </p>
+ )}
+
{data.verdict === 'upgrade-pending' && (
<p className="text-xs text-foreground-muted">
An update is ready but held back because {data.liveSessions} session
@@ -180,6 +220,7 @@ function VersionRows({ status }: { status: AgentSidecarStatus }) {
: 'not running'
}
/>
+ {status.running && <Row label="Deployed by" value={deployedByLabel(status)} />}
<Row label="Live sessions" value={String(status.liveSessions)} />
<Row label="Host" value={status.sshHost} />
<Row label="Working dir" value={status.repoDir} mono />
diff --git a/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts b/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts
index 917e9a184..15de528eb 100644
--- a/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts
+++ b/console/apps/switch-console-desktop/src/shared/events/sidecarEvents.ts
@@ -13,6 +13,9 @@ import { defineEvent } from '@shared/lib/ipc/events';
* - `newer-on-host` — a newer Switch Console deployed the running sidecar. There is
* nothing to offer: replacing it would be a downgrade, and on a shared host
* two installs doing that to each other never converges.
+ * - `other-install` — another Switch Console install deployed a different build of
+ * the SAME release. Neither build is the upgrade, so this one yields and the
+ * first deployer keeps it; Restart takes it over deliberately.
* - `incompatible` — the host runs a protocol this client cannot speak; it must
* be replaced before this client can use it.
*/
@@ -22,6 +25,7 @@ export type SidecarVerdict =
| 'upgrade-available'
| 'upgrade-pending'
| 'newer-on-host'
+ | 'other-install'
| 'incompatible';
/** Full per-agent sidecar status for the UI. */
@@ -33,9 +37,15 @@ export interface AgentSidecarStatus {
* exact build fingerprint (what actually decides "is an upgrade available"). */
clientHash: string;
clientVersion: string;
+ /** This install's deployer identity — what `deployedBy` is compared against. */
+ clientDeployerId: string;
/** What the host reports running (null when nothing is up). */
deployedHash: string | null;
deployedVersion: string | null;
+ /** The install that deployed the running sidecar. Null when nothing is up, or
+ * when it was deployed before installs identified themselves — unknown, which
+ * is not the same as this one. */
+ deployedBy: string | null;
epoch: number | null;
pid: number | null;
liveSessions: number;
diff --git a/console/apps/switch-console-desktop/src/sidecar/index.ts b/console/apps/switch-console-desktop/src/sidecar/index.ts
index d529535d2..f929f5da2 100644
--- a/console/apps/switch-console-desktop/src/sidecar/index.ts
+++ b/console/apps/switch-console-desktop/src/sidecar/index.ts
@@ -375,6 +375,13 @@ async function main(): Promise<void> {
token: server.getToken(),
hash: bundleHash,
version: SIDECAR_VERSION,
+ // Which Switch Console install deployed this process. Echoed from the env we
+ // were launched with — unlike the hash above, which we recompute because the
+ // launcher's claim about our BYTES can go stale under a concurrent deploy.
+ // Nothing on the host can derive this: who started us is precisely what the
+ // launcher knows and we do not. Omitted when launched without one, and a
+ // reader must take its absence as unknown rather than as its own.
+ deployer: process.env.SWITCHDASH_SIDECAR_DEPLOYER_ID?.trim() || null,
// What this sidecar speaks, declared in the file the client already reads
// (CHOO-1865). The version above says only which release this is;
// compatibility is this. A sidecar deployed before it existed omits the