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(switchdash): derive a session's Switch connection id so a supervisor restart cannot strand it (CHOO-1931) (#125)

Louis Amaudruz1c942a82987d
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
index 6f69a131c..f7cc219e6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.test.ts
@@ -7,7 +7,7 @@ import { type PromptInjector, RoomConnection } from './room-connection';
import { resolveSessionControl } from './session-control';
import type { AgentBridgeEvent, AttachmentRef } from './switch-event-format';
-const silentLog = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
+const silentLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
const creds = { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' };
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
index 7a535c2a1..d0aa83f58 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/room-connection.ts
@@ -117,6 +117,7 @@ export interface PromptInjector {
export interface RoomConnectionLogger {
debug(message: string, meta?: Record<string, unknown>): void;
+ info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
error(message: string, meta?: Record<string, unknown>): void;
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.test.ts
new file mode 100644
index 000000000..97e0382f3
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import { sessionConnectionId, uuidV5 } from './session-connection-id';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
+
+describe('uuidV5', () => {
+ it('matches the published vector for the DNS namespace', () => {
+ // The canonical v5 answer every UUID library agrees on. This is what says
+ // the hand-rolled implementation is a real UUIDv5 and not merely stable.
+ const dns = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+ expect(uuidV5('www.example.com', dns)).toBe('2ed6657d-e927-568b-95e1-2665a8aea6a2');
+ });
+
+ it('separates the namespace from the name', () => {
+ const a = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
+ const b = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
+ expect(uuidV5('same-name', a)).not.toBe(uuidV5('same-name', b));
+ });
+});
+
+describe('sessionConnectionId', () => {
+ // The bug this exists to prevent: a restarted supervisor must recompute the
+ // id the already-running agent is still stamping on its tool calls.
+ it('is the same id every time for a session', () => {
+ const first = sessionConnectionId('7c2f0f2e-1f1a-4c1e-9d6b-2f8a1d3c4b5e');
+ const second = sessionConnectionId('7c2f0f2e-1f1a-4c1e-9d6b-2f8a1d3c4b5e');
+ expect(second).toBe(first);
+ });
+
+ it('is stable across process boundaries', () => {
+ // Pinned literally, not recomputed: a change to the namespace or the hash
+ // would still pass a self-consistency check while repointing every live
+ // session at a connection its agent has never heard of.
+ expect(sessionConnectionId('7c2f0f2e-1f1a-4c1e-9d6b-2f8a1d3c4b5e')).toBe(
+ '47b895fe-7db3-5dc1-a137-4876fbe80485'
+ );
+ });
+
+ it('gives different sessions different connections', () => {
+ expect(sessionConnectionId('session-a')).not.toBe(sessionConnectionId('session-b'));
+ });
+
+ it('produces a well-formed v5 UUID the server will accept', () => {
+ for (const sessionId of ['session-a', '', 'ünïcode-session', 'x'.repeat(500)]) {
+ expect(sessionConnectionId(sessionId)).toMatch(UUID_RE);
+ }
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.ts
new file mode 100644
index 000000000..9cf191d51
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-connection-id.ts
@@ -0,0 +1,63 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * The Switch connection id a session's tool calls are expected to arrive on,
+ * derived from the session id.
+ *
+ * A supervisor (switchdash or the on-host sidecar) opens the connection before
+ * the session launches and hands the id over in `SWITCH_CONNECTION_ID`. The
+ * agent reads that variable once, at startup, and stamps it on every tool call
+ * for the rest of its life. A random id therefore only survives as long as the
+ * supervisor process does: on restart the supervisor mints a new one while the
+ * agent — whose pane outlives the supervisor — keeps sending the old one, which
+ * the server sweeps once its heartbeat lapses. Every subsequent tool call is
+ * then rejected, permanently, and each rejection also releases the room slot.
+ *
+ * Deriving the id from the session id removes the hand-off from the recovery
+ * path entirely: a restarted supervisor recomputes the id the pane is already
+ * holding, and reopening an id the same agent already holds is a takeover that
+ * keeps the connection's room claim. There is nothing to persist and nothing to
+ * re-deliver, so this works from a cold start with no state at all.
+ *
+ * The value must stay globally unique — the server keys connections by id alone
+ * across every agent — which is what the UUIDv5 hash buys over anything shorter
+ * or more readable.
+ *
+ * Only one supervisor derives an id for any given session: switchdash's poller
+ * declines remote sessions, which are the sidecar's. Two supervisors deriving
+ * for the same session would fight over one connection.
+ */
+export function sessionConnectionId(sessionId: string): string {
+ return uuidV5(sessionId, SESSION_CONNECTION_NAMESPACE);
+}
+
+/**
+ * Namespace for session-derived connection ids. Arbitrary but fixed: changing
+ * it re-points every session at a different connection, which is the same
+ * breakage this module exists to prevent.
+ */
+const SESSION_CONNECTION_NAMESPACE = '37b41592-2345-455b-8b74-545f79dda0c7';
+
+/**
+ * RFC 4122 §4.3 name-based UUID, SHA-1 flavour.
+ *
+ * Hand-rolled because the repo carries no `uuid` dependency and this is the
+ * only caller. Exported so the conformance vectors in the spec can be asserted
+ * directly — an id that is merely stable but not a well-formed UUID would be
+ * rejected by the server's validation.
+ */
+export function uuidV5(name: string, namespace: string): string {
+ const namespaceBytes = Buffer.from(namespace.replaceAll('-', ''), 'hex');
+ const hash = createHash('sha1').update(namespaceBytes).update(name, 'utf8').digest();
+ const bytes = hash.subarray(0, 16);
+ bytes[6] = (bytes[6] & 0x0f) | 0x50;
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+ const hex = bytes.toString('hex');
+ return [
+ hex.slice(0, 8),
+ hex.slice(8, 12),
+ hex.slice(12, 16),
+ hex.slice(16, 20),
+ hex.slice(20, 32),
+ ].join('-');
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
index 85ab5705f..d987a0c71 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-notification-poller.ts
@@ -1,4 +1,3 @@
-import { randomUUID } from 'node:crypto';
import * as os from 'node:os';
import * as path from 'node:path';
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
@@ -14,6 +13,7 @@ import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
import { PtyInjectionSink } from './injection-sink';
import { PluginPromptInjector } from './plugin-prompt-injector';
import { RoomConnection } from './room-connection';
+import { sessionConnectionId } from './session-connection-id';
import { resolveSessionControl } from './session-control';
import {
readSwitchAgentCredentials,
@@ -218,7 +218,11 @@ class SwitchNotificationPoller {
noteAgentName(creds.agentId, slug);
const ptySessionId = makeAgentPtySessionId(location.id, ctx.sessionId);
- const connectionId = randomUUID();
+ // Derived, not random: a tmux-backed session survives switchdash quitting,
+ // and reattaching to a live pane cannot revise the environment it was
+ // launched with — the `-e` flags only apply to a pane being created. So a
+ // restarted switchdash has to arrive at the id that pane already holds.
+ const connectionId = sessionConnectionId(ctx.sessionId);
// Consumed, not just read: it belongs to this session's launch, and a
// later session must not rewind to a message this one already handled.
const startCursor = this.pendingStart.get(creds.agentId);
diff --git a/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts b/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts
index 458f55207..623091f3b 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts
@@ -10,6 +10,25 @@ export function makePtyId(provider: AgentProviderId | 'shell', sessionId: string
return `${provider}${SESSION_SEP}${sessionId}`;
}
+/**
+ * Narrow a provider id that arrived as an opaque string — from a database row
+ * or a launch spec read off disk — to one `makePtyId` can use.
+ *
+ * Throws rather than passing the value through, because `parsePtyId` only
+ * recognises registered providers: a pty id built from an unknown one parses
+ * back as null, and every hook callback carrying it is then dropped with no
+ * indication of why.
+ */
+export function asPtyProviderId(value: string): AgentProviderId | 'shell' {
+ if (value === 'shell' || (AGENT_PROVIDER_IDS as readonly string[]).includes(value)) {
+ return value as AgentProviderId | 'shell';
+ }
+ throw new Error(
+ `unknown agent provider '${value}': pty ids built from it cannot be parsed back, ` +
+ 'so the session would receive no hook events'
+ );
+}
+
export function parsePtyId(id: string): {
providerId: AgentProviderId | 'shell';
sessionId: string;
diff --git a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
index 53613f595..56dcbcac8 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/notification-watcher.test.ts
@@ -118,7 +118,9 @@ describe('NotificationWatcher spawn decision', () => {
const launch = vi.fn(async () => {
throw new Error('boom');
});
- const fetchMock = vi.fn(async () => new Response(null, { status: 200 }));
+ const fetchMock = vi.fn(
+ async (_url: string | URL, _init?: RequestInit) => new Response(null, { status: 200 })
+ );
vi.stubGlobal('fetch', fetchMock);
handle(makeWatcher(makeSpawner({ launch })), 'room-x');
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
index 9a2f2aea9..c83116fa3 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
@@ -59,9 +59,9 @@ function makeSpawner(over: Partial<InProcessSessionSpawnerDeps> = {}) {
const runtime = { hasLiveRoom: vi.fn(() => false) };
const spawner = new InProcessSessionSpawner({
spec: SPEC,
- locationId: 'proj-1',
hookPort: 4321,
hookToken: 'hooktok',
+ endpointFile: `${CWD}/.switchdash/sidecar-endpoint.json`,
runtime,
switchEnv: {
SWITCH_API_ENDPOINT: 'https://switch.example.com',
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
index 05843e4b9..0f31391e6 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
@@ -8,7 +8,7 @@ import { createPluginFs } from '@main/core/providers/plugin-fs';
import { getPlugin } from '@main/core/providers/plugin-registry';
import { quoteShellArg } from '@main/utils/shellEscape';
import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';
-import { makePtyId } from '@shared/core/pty/ptyId';
+import { asPtyProviderId, makePtyId } from '@shared/core/pty/ptyId';
import { type AgentLaunchSpec, materializeAgentCommand } from './agent-launch-spec';
import { atomicWriteFile } from './atomic-file';
import type { SessionSpawner, WatcherLogger } from './notification-watcher';
@@ -170,7 +170,9 @@ export class InProcessSessionSpawner implements SessionSpawner {
...this.deps.switchEnv,
...buildAgentHookEnv({
port: hookPort,
- ptyId: makePtyId(spec.providerId, sessionId),
+ // The spec is JSON off the host's disk, so its provider id is only a
+ // string until something checks it.
+ ptyId: makePtyId(asPtyProviderId(spec.providerId), sessionId),
token: hookToken,
endpointFile,
}),
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
index 43a54c162..6d53ce349 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -19,7 +19,13 @@ vi.mock('@main/core/providers/plugin-registry', () => ({
const silentLog = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
function fakeConnection(): ManagedConnection {
- return { start: vi.fn(), stop: vi.fn(), onAgentStatusChange: vi.fn() };
+ return {
+ start: vi.fn(),
+ stop: vi.fn(),
+ onAgentStatusChange: vi.fn(),
+ reportActivity: vi.fn(),
+ connection: 'conn-1',
+ };
}
function switchRoomHook(roomId: string, ptyId: string): RawHookRequest {
@@ -60,7 +66,6 @@ function makeRuntime() {
const registry = fakeRegistry();
const runtime = new SidecarRuntime({
creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },
- locationId: 'proj-1',
deeplinkScheme: 'switchdash',
tmuxRun: vi.fn(),
isPaneLive: () => true,
@@ -126,6 +131,30 @@ describe('SidecarRuntime (multi-session)', () => {
expect(created[0].conn.start).toHaveBeenCalledTimes(1);
});
+ // CHOO-1931. The pane outlives the sidecar and keeps stamping the id it was
+ // launched with, so a restarted sidecar has to arrive at that same id — a
+ // fresh random one is swept by the server and every tool call from that
+ // session 409s for the rest of its life.
+ it('gives a session the same connection id after a restart', () => {
+ const first = makeRuntime();
+ const before = first.runtime.ensureForSession('session-a', 'codex', 'room-1');
+
+ // A restart is a brand-new runtime holding none of the previous state.
+ const second = makeRuntime();
+ const after = second.runtime.ensureForSession('session-a', 'codex', 'room-1');
+
+ expect(after).toBe(before);
+ expect(second.created[0].deps.connectionId).toBe(before);
+ });
+
+ it('gives concurrent sessions distinct connection ids', () => {
+ const { runtime } = makeRuntime();
+
+ expect(runtime.ensureForSession('session-a', 'codex', 'room-1')).not.toBe(
+ runtime.ensureForSession('session-b', 'codex', 'room-2')
+ );
+ });
+
it('opens a session at head when no cursor was handed over', () => {
const { runtime, created } = makeRuntime();
@@ -210,7 +239,6 @@ describe('SidecarRuntime (multi-session)', () => {
let paneLive = true;
const runtime = new SidecarRuntime({
creds: { agentId: 'agent-1', apiEndpoint: 'https://switch.test', token: 'tok' },
- locationId: 'proj-1',
deeplinkScheme: 'switchdash',
tmuxRun: vi.fn(),
isPaneLive: () => paneLive,
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index d59e67089..21f46ec7f 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -1,4 +1,3 @@
-import { randomUUID } from 'node:crypto';
import * as os from 'node:os';
import * as path from 'node:path';
import { deriveAgentStatus } from '@main/core/agent-hooks/derive-agent-status';
@@ -12,6 +11,7 @@ import {
type RoomConnectionLogger,
type SwitchCredentials,
} from '@main/core/switch-rooms/room-connection';
+import { sessionConnectionId } from '@main/core/switch-rooms/session-connection-id';
import { resolveSessionControl } from '@main/core/switch-rooms/session-control';
import { type TmuxRun, TmuxInjectionSink } from '@main/core/switch-rooms/tmux-injection-sink';
import { parsePtyId } from '@shared/core/pty/ptyId';
@@ -25,6 +25,9 @@ export interface ManagedConnection {
status: Parameters<RoomConnection['onAgentStatusChange']>[0],
notificationType?: Parameters<RoomConnection['onAgentStatusChange']>[1]
): void;
+ reportActivity(detail: string): void;
+ /** The connection id this session's tool calls are expected to arrive on. */
+ readonly connection: string;
}
export type RoomConnectionFactory = (deps: RoomConnectionDeps) => ManagedConnection;
@@ -60,7 +63,9 @@ export interface SessionRegistry {
interface SessionConnection {
connection: ManagedConnection;
- roomId: string;
+ /** Null for a session whose connection is open but whose room the server has
+ * not named yet — `connectRoom` already branches on exactly that state. */
+ roomId: string | null;
tmuxTarget: string;
}
@@ -231,7 +236,10 @@ export class SidecarRuntime {
startCursor?: number
): string {
const tmuxTarget = makeAgentTmuxSessionName(sessionId);
- const connectionId = randomUUID();
+ // Derived, not random: the session's pane outlives this process and keeps
+ // stamping the id it was launched with, so a restarted sidecar has to
+ // recompute that id rather than mint one the agent will never hear about.
+ const connectionId = sessionConnectionId(sessionId);
const connection = this.deps.createConnection({
creds: this.deps.creds,
roomId,
@@ -319,13 +327,16 @@ export class SidecarRuntime {
/**
* Sessions the runtime has connected to a room, for switchdash to reconcile
* into its UI. Only panes that are still live are reported so a session whose
- * agent has exited does not surface as a ghost row.
+ * agent has exited does not surface as a ghost row — and only sessions whose
+ * room the server has actually named, since a room-less one has nothing for
+ * switchdash to reconcile against.
*/
connectedSessions(): Array<{ sessionId: string; roomId: string }> {
const out: Array<{ sessionId: string; roomId: string }> = [];
for (const [sessionId, session] of this.sessions) {
- if (this.deps.isPaneLive(session.tmuxTarget)) {
- out.push({ sessionId, roomId: session.roomId });
+ const roomId = session.roomId;
+ if (roomId && this.deps.isPaneLive(session.tmuxTarget)) {
+ out.push({ sessionId, roomId });
}
}
return out;
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
index c6e1147b6..dd2298f12 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-version.ts
@@ -27,7 +27,7 @@
* it, fail the operation with a message naming the upgrade rather than
* continuing without whatever the endpoint was for.
*/
-export const SIDECAR_VERSION = '1.6';
+export const SIDECAR_VERSION = '1.7';
/**
* Oldest major this client can still speak to. Raise it only when support for an
diff --git a/dash/apps/switchdash-desktop/tsconfig.json b/dash/apps/switchdash-desktop/tsconfig.json
index 34e1248aa..2ba0eb68c 100644
--- a/dash/apps/switchdash-desktop/tsconfig.json
+++ b/dash/apps/switchdash-desktop/tsconfig.json
@@ -21,6 +21,7 @@
"src/renderer/**/*",
"src/preload/**/*",
"src/shared/**/*",
+ "src/sidecar/**/*",
"src/types/**/*",
"src/test/**/*",
"tooling/**/*"
diff --git a/dash/packages/switch-agent-runtime/package.json b/dash/packages/switch-agent-runtime/package.json
index 5a34912b1..25fa31200 100644
--- a/dash/packages/switch-agent-runtime/package.json
+++ b/dash/packages/switch-agent-runtime/package.json
@@ -1,6 +1,6 @@
{
"name": "@sandbox-quantum/switch-agent-runtime",
- "version": "0.1.4",
+ "version": "0.1.5",
"description": "Switch agent protocol client, and the local MCP runtime built on it",
"license": "Apache-2.0",
"author": {
diff --git a/dash/packages/switch-agent-runtime/src/bin.ts b/dash/packages/switch-agent-runtime/src/bin.ts
index 95fa2576f..6c4b00355 100644
--- a/dash/packages/switch-agent-runtime/src/bin.ts
+++ b/dash/packages/switch-agent-runtime/src/bin.ts
@@ -460,6 +460,66 @@ async function loadOperations(): Promise<void> {
process.stderr.write(`switch: serving ${operations.length} operations locally\n`);
}
+/**
+ * Whether the server rejected a call because the connection it was stamped with
+ * no longer exists.
+ *
+ * Two status codes for one condition: `/ops/*` answers 409 and `/connection/*`
+ * answers 404, so matching on either alone misses half the surface. The id is
+ * checked too — a 409 naming some *other* connection is a different fault and
+ * must not be dressed up as this one.
+ */
+function isDeadConnection(status: number, body: string): boolean {
+ if (status !== 409 && status !== 404) return false;
+ return body.includes(CONNECTION_ID) && body.includes('is not open');
+}
+
+/** Whether the operator has already been told this connection is dead. */
+let deadConnectionReported = false;
+
+/**
+ * Explain a dead connection instead of passing the server's wording through.
+ *
+ * Raw, the rejection reads `409: connection <uuid> is not open; reconnect and
+ * resume from your cursor` — advice this process cannot take when the id was
+ * handed to it by a supervisor. It is fixed for the life of the process, so
+ * every retry fails identically. Meanwhile events keep arriving on the
+ * supervisor's own stream, so the session reads the room perfectly and is
+ * simply unable to answer: exactly the shape of failure that looks healthy.
+ *
+ * Say what happened, and that a restart is the only way out.
+ */
+function deadConnectionMessage(operation: string): string {
+ if (!OWNS_CONNECTION) {
+ if (!deadConnectionReported) {
+ deadConnectionReported = true;
+ process.stderr.write(
+ `switch: FATAL — the supervisor's connection (${CONNECTION_ID}) is gone. ` +
+ 'It restarted after handing this session the id, and the id cannot be ' +
+ 'refreshed from here. Every Switch tool call will fail until this ' +
+ 'session is restarted.\n'
+ );
+ }
+ return (
+ `Switch is unreachable from this session: ${operation} was refused because ` +
+ `connection ${CONNECTION_ID} no longer exists on the server.\n\n` +
+ 'The supervisor that launched this session (switchdash, or the sidecar on ' +
+ 'this host) handed over that connection and has since restarted. The id ' +
+ 'was read once at startup and cannot be refreshed, so this is permanent ' +
+ 'for this session — retrying will fail the same way.\n\n' +
+ 'Note that incoming events may still be arriving normally, so the session ' +
+ 'looks fine while being unable to post anything. Tell the user plainly ' +
+ 'that you cannot reach Switch and that the session has to be restarted.'
+ );
+ }
+ process.stderr.write(`switch: connection ${CONNECTION_ID} lapsed and was refused\n`);
+ return (
+ `Switch refused ${operation}: connection ${CONNECTION_ID} had lapsed. This ` +
+ 'process owns that connection, so its heartbeat reopens the stream on the ' +
+ 'same id within a couple of seconds — retry the call.'
+ );
+}
+
async function callOperation(
name: string,
args: Record<string, unknown>
@@ -481,6 +541,9 @@ async function callOperation(
});
const text = await resp.text();
if (!resp.ok) {
+ if (isDeadConnection(resp.status, text)) {
+ return { isError: true, content: [{ type: 'text', text: deadConnectionMessage(name) }] };
+ }
return { isError: true, content: [{ type: 'text', text: `${resp.status}: ${text}` }] };
}
const data = JSON.parse(text) as { result?: unknown };