Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(switchdash): bound and serialise remote PTY attachment
amaudruz11e5977d73de
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.test.tsnew file mode 100644index 000000000..6986064ad--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.test.ts@@ -0,0 +1,167 @@+import { describe, expect, it } from 'vitest';+import { AttachQueue, AttachQueueClearedError } from './attach-queue';++/** A promise plus the handles to settle it from the test body. */+function deferred<T = void>() {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++/** Queue with no real timers: records each requested delay instead of waiting. */+function makeQueue() {+ const delays: number[] = [];+ const queue = new AttachQueue(250, async (ms) => {+ delays.push(ms);+ });+ return { queue, delays };+}++describe('AttachQueue', () => {+ it('never runs two tasks concurrently', async () => {+ const { queue } = makeQueue();+ let inFlight = 0;+ let maxInFlight = 0;+ const order: string[] = [];++ const task = (name: string) => async () => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ order.push(`start:${name}`);+ // Yield repeatedly so an unserialised queue would interleave here.+ await Promise.resolve();+ await Promise.resolve();+ order.push(`end:${name}`);+ inFlight -= 1;+ };++ await Promise.all([queue.run(task('a')), queue.run(task('b')), queue.run(task('c'))]);++ expect(maxInFlight).toBe(1);+ expect(order).toEqual(['start:a', 'end:a', 'start:b', 'end:b', 'start:c', 'end:c']);+ });++ it('holds a queued task until the one in flight settles', async () => {+ const { queue } = makeQueue();+ const first = deferred();+ let secondStarted = false;++ const firstRun = queue.run(() => first.promise);+ const secondRun = queue.run(async () => {+ secondStarted = true;+ });++ await Promise.resolve();+ expect(secondStarted).toBe(false);++ first.resolve();+ await Promise.all([firstRun, secondRun]);+ expect(secondStarted).toBe(true);+ });++ it('waits between tasks but not before the first', async () => {+ const { queue, delays } = makeQueue();++ await queue.run(async () => 'a');+ expect(delays).toEqual([]);++ const second = queue.run(async () => 'b');+ const third = queue.run(async () => 'c');+ await Promise.all([second, third]);++ // One gap before 'b' and one before 'c' — never before the queue's first task.+ expect(delays).toEqual([250, 250]);+ });++ it('resolves each caller with its own task result', async () => {+ const { queue } = makeQueue();++ const results = await Promise.all([+ queue.run(async () => 'a'),+ queue.run(async () => 'b'),+ queue.run(async () => 'c'),+ ]);++ expect(results).toEqual(['a', 'b', 'c']);+ });++ it('delivers a task rejection to its caller without stalling the queue', async () => {+ const { queue } = makeQueue();++ const failing = queue.run(async () => {+ throw new Error('attach failed');+ });+ const following = queue.run(async () => 'ran anyway');++ await expect(failing).rejects.toThrow('attach failed');+ await expect(following).resolves.toBe('ran anyway');+ });++ it('clear() drops queued tasks without running them', async () => {+ const { queue } = makeQueue();+ const first = deferred();+ let secondStarted = false;++ const firstRun = queue.run(() => first.promise);+ const secondRun = queue.run(async () => {+ secondStarted = true;+ });++ queue.clear();+ first.resolve();+ await firstRun;++ await expect(secondRun).rejects.toBeInstanceOf(AttachQueueClearedError);+ expect(secondStarted).toBe(false);+ });++ it('clear() leaves the in-flight task running', async () => {+ const { queue } = makeQueue();+ const inFlight = deferred<string>();++ const running = queue.run(() => inFlight.promise);+ await Promise.resolve();++ queue.clear();+ inFlight.resolve('completed');++ await expect(running).resolves.toBe('completed');+ });++ it('accepts new work after being cleared', async () => {+ const { queue } = makeQueue();+ const first = deferred();++ const firstRun = queue.run(() => first.promise);+ const dropped = queue.run(async () => 'dropped');+ queue.clear();+ await expect(dropped).rejects.toBeInstanceOf(AttachQueueClearedError);++ first.resolve();+ await firstRun;++ await expect(queue.run(async () => 'fresh')).resolves.toBe('fresh');+ });++ it('reports the number of tasks waiting for a turn', async () => {+ const { queue } = makeQueue();+ const first = deferred();++ const firstRun = queue.run(() => first.promise);+ await Promise.resolve();+ // The in-flight task is not counted.+ expect(queue.depth).toBe(0);++ const second = queue.run(async () => undefined);+ const third = queue.run(async () => undefined);+ expect(queue.depth).toBe(2);++ first.resolve();+ await Promise.all([firstRun, second, third]);+ expect(queue.depth).toBe(0);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.tsnew file mode 100644index 000000000..c8e38b8fe--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/attach-queue.ts@@ -0,0 +1,95 @@+/**+ * Serialises PTY attach work for one SSH connection.+ *+ * Every remote session on a host shares a single ssh2 transport, and an attach+ * opens several channels on it (SFTP for hooks, an exec to resolve the CLI, the+ * pty itself). When a transport is rebuilt, every session on that host wants to+ * re-attach at once: 51 sessions on one host produced 51 attaches inside the+ * same millisecond, which saturated the tunnel, pushed channel opens past+ * `CHANNEL_OPEN_TIMEOUT_MS`, and tripped the connection manager's wedge+ * watchdog — rebuilding the transport and starting the same stampede again.+ *+ * Running attaches one at a time with a gap between them keeps the number of+ * in-flight channel opens at roughly one, which is what the slower tunnels+ * (an IAP or SSM ProxyCommand) can actually absorb.+ */++/** Gap between the end of one task and the start of the next. */+const DEFAULT_INTER_TASK_DELAY_MS = 250;++export class AttachQueueClearedError extends Error {+ constructor() {+ super('Attach cancelled: the SSH connection dropped before this attach started');+ this.name = 'AttachQueueClearedError';+ }+}++interface QueuedTask {+ /** Runs the caller's task and settles its promise. Never rejects. */+ readonly run: () => Promise<void>;+ /** Rejects the caller's promise without running the task. */+ readonly cancel: () => void;+}++export class AttachQueue {+ private readonly pending: QueuedTask[] = [];+ private running = false;++ constructor(+ private readonly interTaskDelayMs: number = DEFAULT_INTER_TASK_DELAY_MS,+ private readonly sleep: (ms: number) => Promise<void> = (ms) =>+ new Promise((resolve) => setTimeout(resolve, ms))+ ) {}++ /** Tasks waiting for a turn, excluding the one in flight. */+ get depth(): number {+ return this.pending.length;+ }++ /**+ * Run `task` once the queue reaches it. Resolves or rejects with the task's+ * own outcome; a rejection is delivered to that caller only and never stalls+ * the queue. Rejects with `AttachQueueClearedError` if `clear()` discards it+ * before it starts.+ */+ run<T>(task: () => Promise<T>): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ this.pending.push({+ // Both handlers are supplied, so the returned promise always fulfils —+ // the drain loop can await it purely for pacing.+ run: () => task().then(resolve, reject),+ cancel: () => reject(new AttachQueueClearedError()),+ });+ if (!this.running) void this.drain();+ });+ }++ /**+ * Drop every task that has not started yet, rejecting its caller so nothing+ * awaits a turn that will never come. The task in flight is left alone — it+ * already owns channels on the transport and abandoning it here would leak+ * them. Used when the connection drops: the queued attaches were aimed at a+ * transport that no longer exists.+ */+ clear(): void {+ const dropped = this.pending.splice(0);+ for (const task of dropped) task.cancel();+ }++ private async drain(): Promise<void> {+ this.running = true;+ try {+ let isFirst = true;+ while (this.pending.length > 0) {+ if (!isFirst) await this.sleep(this.interTaskDelayMs);+ isFirst = false;+ // `clear()` can empty the queue while we sleep.+ const next = this.pending.shift();+ if (!next) break;+ await next.run();+ }+ } finally {+ this.running = false;+ }+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/production-remote-attachment-pool.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/production-remote-attachment-pool.tsnew file mode 100644index 000000000..e967c8174--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/production-remote-attachment-pool.ts@@ -0,0 +1,30 @@+import { appSettingsService } from '@main/core/settings/settings-service';+import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';+import { RemoteAttachmentPool } from './remote-attachment-pool';++/**+ * The app-wide attachment pool, wired to real settings and the real SSH+ * connection manager.+ *+ * The connection listener lives here — one for the whole app — replacing the+ * per-runtime listener each `SshAgentRuntime` used to register. That fan-out was+ * the reconnect storm: every session on a host re-attached in the same tick,+ * saturating the transport that had only just come back.+ */+export const remoteAttachmentPool = new RemoteAttachmentPool({+ readCap: async () => (await appSettingsService.get('remote')).maxAttachedSessionsPerHost,+});++sshConnectionManager.on('connection-event', (event) => {+ switch (event.type) {+ case 'disconnected':+ case 'reconnecting':+ remoteAttachmentPool.handleConnectionLost(event.connectionId);+ break;+ case 'reconnected':+ void remoteAttachmentPool.replayAfterReconnect(event.connectionId);+ break;+ default:+ break;+ }+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.test.tsnew file mode 100644index 000000000..8e79acbf4--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.test.ts@@ -0,0 +1,277 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { AttachQueue } from './attach-queue';+import { RemoteAttachmentPool } from './remote-attachment-pool';+import type { AttachState, AttachableRuntime } from './types';++vi.mock('@main/lib/logger', () => ({+ log: { child: () => ({ debug() {}, info() {}, warn() {} }), info() {}, warn() {}, error() {} },+}));++/** A runtime whose attach/detach just flips a flag, so policy is what's under test. */+class FakeRuntime implements AttachableRuntime {+ attached = false;+ attachCalls = 0;+ detachCalls = 0;+ failNextAttach = false;++ constructor(+ readonly attachSessionId: string,+ readonly attachHostKey: string+ ) {}++ async ensureAttachable(): Promise<void> {}++ async attach(): Promise<void> {+ this.attachCalls += 1;+ if (this.failNextAttach) {+ this.failNextAttach = false;+ throw new Error('attach failed');+ }+ this.attached = true;+ }++ async detachForEviction(): Promise<void> {+ this.detachCalls += 1;+ this.attached = false;+ }++ isAttached(): boolean {+ return this.attached;+ }+}++describe('RemoteAttachmentPool', () => {+ const HOST_A = 'agent-ssh:dev-vm';+ const HOST_B = 'agent-ssh:other-vm';++ let cap: number;+ let published: Array<{ sessionId: string; state: AttachState }>;+ let pool: RemoteAttachmentPool;++ const add = (sessionId: string, hostKey = HOST_A) => {+ const runtime = new FakeRuntime(sessionId, hostKey);+ pool.register(runtime);+ return runtime;+ };++ const attachedIds = (runtimes: FakeRuntime[]) =>+ runtimes.filter((r) => r.attached).map((r) => r.attachSessionId);++ beforeEach(() => {+ cap = 2;+ published = [];+ pool = new RemoteAttachmentPool({+ readCap: async () => cap,+ // No real timers: the stagger is AttachQueue's contract, tested there.+ makeQueue: () => new AttachQueue(0, async () => {}),+ publish: ({ sessionId, state }) => published.push({ sessionId, state }),+ });+ });++ it('attaches a registered session on request', async () => {+ const a = add('a');++ await expect(pool.requestAttach('a', 'user')).resolves.toBe('attached');+ expect(a.attached).toBe(true);+ expect(pool.stateOf('a')).toBe('attached');+ });++ it('is a no-op for a session it does not know', async () => {+ await expect(pool.requestAttach('ghost', 'user')).resolves.toBe('detached');+ });++ it('evicts the least-recently-viewed session when the host is at capacity', async () => {+ const a = add('a');+ const b = add('b');+ const c = add('c');++ await pool.requestAttach('a', 'user');+ await pool.requestAttach('b', 'user');+ await pool.requestAttach('c', 'user');++ // 'a' was viewed longest ago, so it makes room for 'c'.+ expect(attachedIds([a, b, c])).toEqual(['b', 'c']);+ expect(a.detachCalls).toBe(1);+ });++ it('counts capacity per host rather than globally', async () => {+ const a1 = add('a1', HOST_A);+ const a2 = add('a2', HOST_A);+ const b1 = add('b1', HOST_B);+ const b2 = add('b2', HOST_B);++ await pool.requestAttach('a1', 'user');+ await pool.requestAttach('b1', 'user');+ await pool.requestAttach('a2', 'user');+ await pool.requestAttach('b2', 'user');++ // Both hosts are at their own cap of 2; neither starved the other.+ expect(attachedIds([a1, a2, b1, b2])).toEqual(['a1', 'a2', 'b1', 'b2']);+ });++ it('never evicts the focused session', async () => {+ const a = add('a');+ const b = add('b');+ const c = add('c');++ // 'a' is focused and therefore pinned, even though it is the oldest.+ pool.setFocused('a');+ await pool.requestAttach('a', 'user');+ await pool.requestAttach('b', 'user');+ await pool.requestAttach('c', 'user');++ expect(a.attached).toBe(true);+ expect(attachedIds([a, b, c])).toEqual(['a', 'c']);+ });++ it('re-focusing unpins the previous session so a cap of one cannot deadlock', async () => {+ cap = 1;+ const a = add('a');+ const b = add('b');++ pool.setFocused('a');+ await pool.requestAttach('a', 'user');+ expect(a.attached).toBe(true);++ // Focus moves first, which is what makes 'a' evictable for 'b'.+ pool.setFocused('b');+ await pool.requestAttach('b', 'user');++ expect(a.attached).toBe(false);+ expect(b.attached).toBe(true);+ });++ it('treats a viewed session as recently used without attaching it', async () => {+ const a = add('a');+ const b = add('b');+ const c = add('c');++ await pool.requestAttach('a', 'user');+ await pool.requestAttach('b', 'user');+ pool.noteViewed('a');+ await pool.requestAttach('c', 'user');++ // 'a' was touched last, so 'b' is now the oldest and goes instead.+ expect(attachedIds([a, b, c])).toEqual(['a', 'c']);+ });++ it('reports a failed attach without leaving the session stuck attaching', async () => {+ const a = add('a');+ a.failNextAttach = true;++ await expect(pool.requestAttach('a', 'user')).resolves.toBe('failed');+ expect(pool.stateOf('a')).toBe('failed');+ expect(published.map((p) => p.state)).toEqual(['attaching', 'failed']);+ });++ it('publishes attaching then attached on success', async () => {+ add('a');++ await pool.requestAttach('a', 'user');++ expect(published).toEqual([+ { sessionId: 'a', state: 'attaching' },+ { sessionId: 'a', state: 'attached' },+ ]);+ });++ it('marks every session on a host detached when its connection drops', async () => {+ const a = add('a');+ const b = add('b');+ const other = add('z', HOST_B);+ await pool.requestAttach('a', 'user');+ await pool.requestAttach('b', 'user');+ await pool.requestAttach('z', 'user');++ pool.handleConnectionLost(HOST_A);++ expect(pool.stateOf('a')).toBe('detached');+ expect(pool.stateOf('b')).toBe('detached');+ // The other host is untouched.+ expect(pool.stateOf('z')).toBe('attached');+ // The PTYs died with the transport; the pool records that, it does not detach again.+ expect(a.detachCalls).toBe(0);+ expect(b.detachCalls).toBe(0);+ expect(other.detachCalls).toBe(0);+ });++ it('replays at most the cap after a reconnect, most-recently-viewed first', async () => {+ const runtimes = ['a', 'b', 'c', 'd'].map((id) => add(id));+ for (const id of ['a', 'b', 'c', 'd']) pool.noteViewed(id);+ // Simulate the transport dying: nothing is attached any more.+ for (const runtime of runtimes) runtime.attached = false;++ await pool.replayAfterReconnect(HOST_A);+ await vi.waitFor(() => expect(attachedIds(runtimes)).toHaveLength(2));++ // 'd' and 'c' were viewed most recently; 'a' and 'b' stay detached and keep+ // running on the VM rather than stampeding the transport that just returned.+ expect(attachedIds(runtimes).sort()).toEqual(['c', 'd']);+ });++ it('replays the focused session first even when it was not the most recent', async () => {+ cap = 1;+ const runtimes = ['a', 'b', 'c'].map((id) => add(id));+ pool.setFocused('a');+ pool.noteViewed('b');+ pool.noteViewed('c');+ for (const runtime of runtimes) runtime.attached = false;++ await pool.replayAfterReconnect(HOST_A);+ await vi.waitFor(() => expect(attachedIds(runtimes)).toHaveLength(1));++ expect(attachedIds(runtimes)).toEqual(['a']);+ });++ it('drops queued attaches when the connection is lost mid-replay', async () => {+ const gate = { release: () => {} };+ const blocker = new Promise<void>((resolve) => {+ gate.release = resolve;+ });+ const a = add('a');+ const b = add('b');+ a.attach = async () => {+ await blocker;+ a.attached = true;+ };++ const first = pool.requestAttach('a', 'user');+ const second = pool.requestAttach('b', 'user');+ // 'b' is still queued behind 'a' when the transport dies.+ pool.handleConnectionLost(HOST_A);+ gate.release();+ await Promise.all([first, second]);++ expect(b.attachCalls).toBe(0);+ expect(pool.stateOf('b')).toBe('detached');+ });++ it('forgets a session on unregister and unpins it if focused', async () => {+ const a = add('a');+ await pool.requestAttach('a', 'user');++ pool.setFocused('a');+ pool.unregister('a');++ expect(pool.stateOf('a')).toBe('detached');+ await expect(pool.requestAttach('a', 'user')).resolves.toBe('detached');+ expect(a.attachCalls).toBe(1);+ });++ it('does not re-attach a session that is already attached', async () => {+ const a = add('a');+ await pool.requestAttach('a', 'user');+ await pool.requestAttach('a', 'focus');++ expect(a.attachCalls).toBe(1);+ });++ it('keeps a live session attached when its runtime re-registers', async () => {+ const a = add('a');+ await pool.requestAttach('a', 'user');++ pool.register(a);++ expect(pool.stateOf('a')).toBe('attached');+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.tsnew file mode 100644index 000000000..0cb20570c--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/remote-attachment-pool.ts@@ -0,0 +1,346 @@+import { events } from '@main/lib/events';+import { log } from '@main/lib/logger';+import { sessionAttachmentChangedChannel } from '@shared/core/sessions/sessionEvents';+import { AttachQueue, AttachQueueClearedError } from './attach-queue';+import type { AttachReason, AttachState, AttachableRuntime } from './types';++/**+ * Bounds how many remote sessions hold a live terminal, per SSH host.+ *+ * Every session on a host shares one ssh2 transport. A terminal is a channel+ * held open for as long as it is attached, and an attach opens several more+ * (SFTP for hooks, an exec to resolve the CLI). One host with 51 attached+ * sessions saturated its tunnel, pushed channel opens past their deadline, and+ * tripped the connection manager's wedge watchdog — which rebuilt the transport,+ * prompting all 51 to re-attach in the same tick and wedge it again, every ~16+ * minutes indefinitely.+ *+ * The pool fixes both halves of that: a cap with LRU eviction keeps the steady+ * state small, and a per-host queue makes every attach serial and staggered so a+ * reconnect can never stampede. Eviction is cheap because a detached session is+ * not a stopped one — the agent keeps running in its tmux pane on the VM and its+ * shared sidecar relay keeps reporting status, room and notifications. Only the+ * view goes away.+ *+ * Local runtimes never register: they have no shared transport to protect.+ */++interface PoolEntry {+ runtime: AttachableRuntime;+ hostKey: string;+ state: AttachState;+}++export interface RemoteAttachmentPoolDeps {+ /** Resolves the per-host cap. Read per request so a settings change takes effect live. */+ readCap: () => Promise<number>;+ makeQueue?: () => AttachQueue;+ publish?: (payload: {+ sessionId: string;+ state: AttachState;+ hostKey: string;+ reason?: AttachReason;+ }) => void;+}++export class RemoteAttachmentPool {+ /**+ * Insertion-ordered by view recency: re-inserting on view puts a session at+ * the back, so the front is the least-recently-viewed eviction candidate.+ */+ private readonly entries = new Map<string, PoolEntry>();+ private readonly queues = new Map<string, AttachQueue>();+ /** Attaches in progress, so overlapping requests share one outcome. */+ private readonly inFlight = new Map<string, Promise<AttachState>>();+ private focusedSessionId: string | null = null;++ constructor(private readonly deps: RemoteAttachmentPoolDeps) {}++ // ─── Membership ──────────────────────────────────────────────────────────++ register(runtime: AttachableRuntime): void {+ const sessionId = runtime.attachSessionId;+ const existing = this.entries.get(sessionId);+ this.entries.set(sessionId, {+ runtime,+ hostKey: runtime.attachHostKey,+ // A re-provisioned runtime for a live session keeps its state.+ state: existing?.state ?? (runtime.isAttached() ? 'attached' : 'detached'),+ });+ }++ unregister(sessionId: string): void {+ this.entries.delete(sessionId);+ if (this.focusedSessionId === sessionId) this.focusedSessionId = null;+ }++ stateOf(sessionId: string): AttachState {+ return this.entries.get(sessionId)?.state ?? 'detached';+ }++ capacityFor(hostKey: string): { cap: number; attached: number } {+ return { cap: this.lastKnownCap, attached: this.attachedOn(hostKey).length };+ }++ // ─── Focus ───────────────────────────────────────────────────────────────++ /**+ * Record which session the user is looking at. The focused session is pinned:+ * it is never chosen for eviction, and it is the first thing re-attached after+ * a reconnect. Pinning happens before the attach request, so the previously+ * focused session becomes evictable and a cap of 1 cannot deadlock.+ */+ setFocused(sessionId: string | null): void {+ this.focusedSessionId = sessionId;+ if (!sessionId) return;+ const entry = this.entries.get(sessionId);+ if (!entry) return;+ this.touch(sessionId);+ void this.requestAttach(sessionId, 'focus').catch(() => {+ // requestAttach already recorded the failure and published it.+ });+ }++ /** Move a session to the most-recently-viewed end without attaching it. */+ noteViewed(sessionId: string): void {+ this.touch(sessionId);+ }++ // ─── Attach / detach ─────────────────────────────────────────────────────++ /**+ * Ensure `sessionId` has a live terminal, evicting the least-recently-viewed+ * session on its host if the host is at capacity. Never refuses: the caller+ * asked to see this session, and eviction is cheap.+ */+ async requestAttach(sessionId: string, reason: AttachReason): Promise<AttachState> {+ const entry = this.entries.get(sessionId);+ if (!entry) return 'detached';+ if (entry.runtime.isAttached()) {+ this.setState(entry, sessionId, 'attached', reason);+ return 'attached';+ }+ // Coalesce onto the attach already in flight rather than reporting a+ // half-truth: `setFocused` and an explicit request routinely overlap, and+ // both callers want the real outcome.+ const inFlight = this.inFlight.get(sessionId);+ if (inFlight) return inFlight;++ const attempt = this.performAttach(entry, sessionId, reason).finally(() => {+ if (this.inFlight.get(sessionId) === attempt) this.inFlight.delete(sessionId);+ });+ this.inFlight.set(sessionId, attempt);+ return attempt;+ }++ private async performAttach(+ entry: PoolEntry,+ sessionId: string,+ reason: AttachReason+ ): Promise<AttachState> {+ this.touch(sessionId);+ this.setState(entry, sessionId, 'attaching', reason);++ const queue = this.queueFor(entry.hostKey);+ try {+ await queue.run(async () => {+ // Re-check inside the queue: the session may have been unregistered, or+ // already attached by another request, while it waited its turn.+ const current = this.entries.get(sessionId);+ if (!current || current.runtime.isAttached()) return;+ await this.evictForCapacity(current.hostKey, sessionId);+ log.info('RemoteAttachmentPool: attaching session', {+ event: 'remote_attach',+ sessionId,+ hostKey: current.hostKey,+ reason,+ queueDepth: queue.depth,+ attachedCount: this.attachedOn(current.hostKey).length,+ });+ await current.runtime.attach();+ });+ } catch (error) {+ const cancelled = error instanceof AttachQueueClearedError;+ const live = this.entries.get(sessionId);+ if (live) this.setState(live, sessionId, cancelled ? 'detached' : 'failed', reason);+ if (!cancelled) {+ log.warn('RemoteAttachmentPool: attach failed', {+ sessionId,+ hostKey: entry.hostKey,+ reason,+ error: String(error),+ });+ }+ return cancelled ? 'detached' : 'failed';+ }++ const settled = this.entries.get(sessionId);+ if (!settled) return 'detached';+ const state: AttachState = settled.runtime.isAttached() ? 'attached' : 'detached';+ this.setState(settled, sessionId, state, reason);+ return state;+ }++ /** Detach a session's terminal on purpose, leaving its agent running. */+ async requestDetach(sessionId: string): Promise<void> {+ const entry = this.entries.get(sessionId);+ if (!entry) return;+ if (this.focusedSessionId === sessionId) this.focusedSessionId = null;+ await this.detach(entry, sessionId);+ }++ // ─── Connection lifecycle ────────────────────────────────────────────────++ /**+ * The transport for `hostKey` went away: every PTY on it died with it. Drop+ * queued attaches aimed at the dead transport and record the truth, so the UI+ * shows detached rather than a terminal that will never produce output.+ */+ handleConnectionLost(hostKey: string): void {+ this.queues.get(hostKey)?.clear();+ for (const [sessionId, entry] of this.entries) {+ if (entry.hostKey !== hostKey) continue;+ if (entry.state === 'detached') continue;+ this.setState(entry, sessionId, 'detached');+ }+ }++ /**+ * The transport for `hostKey` is back. Re-attach the focused session plus the+ * most-recently-viewed others up to the cap — staggered through the queue.+ *+ * The remaining sessions stay detached deliberately. Their agents never+ * stopped, and re-attaching all of them is precisely what used to re-wedge the+ * connection fifteen seconds later.+ */+ async replayAfterReconnect(hostKey: string): Promise<void> {+ const cap = await this.readCap();+ const candidates = this.replayOrder(hostKey).slice(0, cap);+ if (candidates.length === 0) return;++ log.info('RemoteAttachmentPool: replaying attachments after reconnect', {+ event: 'remote_attach_replay',+ hostKey,+ replaying: candidates.length,+ cap,+ });++ for (const sessionId of candidates) {+ void this.requestAttach(sessionId, 'reconnect').catch(() => {+ // Already logged and published by requestAttach.+ });+ }+ }++ // ─── Internals ───────────────────────────────────────────────────────────++ /** Most-recently-viewed first, focused session always leading. */+ private replayOrder(hostKey: string): string[] {+ const onHost = [...this.entries]+ .filter(([, entry]) => entry.hostKey === hostKey)+ .map(([sessionId]) => sessionId)+ .reverse();+ const focused = this.focusedSessionId;+ if (focused && onHost.includes(focused)) {+ return [focused, ...onHost.filter((id) => id !== focused)];+ }+ return onHost;+ }++ private async evictForCapacity(hostKey: string, incomingSessionId: string): Promise<void> {+ const cap = await this.readCap();+ // The incoming session is not attached yet, so it needs a free slot.+ while (this.attachedOn(hostKey).length >= cap) {+ const victimId = this.evictionCandidate(hostKey, incomingSessionId);+ if (!victimId) return; // Everything attached is pinned or is the incoming session.+ const victim = this.entries.get(victimId);+ if (!victim) continue;+ log.info('RemoteAttachmentPool: evicting least-recently-viewed session', {+ event: 'remote_attach_evict',+ sessionId: victimId,+ hostKey,+ cap,+ forSessionId: incomingSessionId,+ });+ await this.detach(victim, victimId);+ }+ }++ /** Least-recently-viewed attached session on the host that may be evicted. */+ private evictionCandidate(hostKey: string, incomingSessionId: string): string | null {+ for (const [sessionId, entry] of this.entries) {+ if (entry.hostKey !== hostKey) continue;+ if (sessionId === incomingSessionId) continue;+ if (sessionId === this.focusedSessionId) continue;+ if (!entry.runtime.isAttached()) continue;+ return sessionId;+ }+ return null;+ }++ private async detach(entry: PoolEntry, sessionId: string): Promise<void> {+ try {+ await entry.runtime.detachForEviction();+ } catch (error) {+ log.warn('RemoteAttachmentPool: detach failed', {+ sessionId,+ hostKey: entry.hostKey,+ error: String(error),+ });+ }+ this.setState(entry, sessionId, 'detached');+ }++ private attachedOn(hostKey: string): string[] {+ return [...this.entries]+ .filter(([, entry]) => entry.hostKey === hostKey && entry.runtime.isAttached())+ .map(([sessionId]) => sessionId);+ }++ /** Re-insert so the session moves to the most-recently-viewed end of the map. */+ private touch(sessionId: string): void {+ const entry = this.entries.get(sessionId);+ if (!entry) return;+ this.entries.delete(sessionId);+ this.entries.set(sessionId, entry);+ }++ private queueFor(hostKey: string): AttachQueue {+ let queue = this.queues.get(hostKey);+ if (!queue) {+ queue = this.deps.makeQueue?.() ?? new AttachQueue();+ this.queues.set(hostKey, queue);+ }+ return queue;+ }++ private lastKnownCap = 4;++ private async readCap(): Promise<number> {+ try {+ this.lastKnownCap = Math.max(1, await this.deps.readCap());+ } catch (error) {+ log.warn('RemoteAttachmentPool: could not read attachment cap; using last known', {+ cap: this.lastKnownCap,+ error: String(error),+ });+ }+ return this.lastKnownCap;+ }++ private setState(+ entry: PoolEntry,+ sessionId: string,+ state: AttachState,+ reason?: AttachReason+ ): void {+ if (entry.state === state) return;+ entry.state = state;+ const payload = { sessionId, state, hostKey: entry.hostKey, reason };+ if (this.deps.publish) {+ this.deps.publish(payload);+ return;+ }+ events.emit(sessionAttachmentChangedChannel, payload);+ }+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/types.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/types.tsnew file mode 100644index 000000000..a0fb26c06--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/attachment/types.ts@@ -0,0 +1,41 @@+import type { Session } from '@shared/core/sessions/sessions';++/** Whether a session's local PTY view of its remote agent is currently open. */+export type AttachState = 'detached' | 'attaching' | 'attached' | 'failed';++/** Why an attach was requested — for logs and for replay ordering. */+export type AttachReason = 'focus' | 'user' | 'startup' | 'adopt' | 'reconnect';++/**+ * The slice of a remote agent runtime the attachment pool drives.+ *+ * Kept deliberately narrow so the pool never imports `SshAgentRuntime` (which+ * pulls in the whole sidecar/pty stack) and so tests can drive it with a stub.+ * Only remote runtimes implement it: a local agent has no shared SSH transport+ * to protect, so `LocalAgentRuntime` never registers and stays uncapped.+ */+export interface AttachableRuntime {+ /** The pooled SSH connection this runtime shares, `agent-ssh:<host>`. The cap is per host. */+ readonly attachHostKey: string;+ readonly attachSessionId: string;++ /**+ * Bring up everything the session needs *except* the PTY: the on-VM sidecar+ * and its shared hook-event relay. Idempotent. Must be called before the+ * session can report status, room membership or notifications — those arrive+ * over the relay, not the terminal.+ */+ ensureAttachable(session: Session): Promise<void>;++ /** Open the local PTY onto the already-running remote tmux pane. */+ attach(): Promise<void>;++ /**+ * Close the local PTY only. The agent keeps running in its tmux pane and the+ * shared relay keeps reporting for it, so an evicted session is still live —+ * just not being watched.+ */+ detachForEviction(): Promise<void>;++ isAttached(): boolean;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.test.tsnew file mode 100644index 000000000..9c12fc0b2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.test.ts@@ -0,0 +1,188 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { RawHookRequest } from '@main/core/agent-hooks/hook-server';+import { SidecarRelayRegistry, sidecarRelayKey } from './sidecar-relay-registry';++const mocks = vi.hoisted(() => ({+ /** Captures the deps each constructed relay was given, so tests can drive its sink. */+ instances: [] as Array<{+ deps: Record<string, unknown>;+ start: ReturnType<typeof vi.fn>;+ stop: ReturnType<typeof vi.fn>;+ }>,+}));++vi.mock('./remote-hook-event-relay', () => ({+ RemoteHookEventRelay: class {+ start = vi.fn();+ stop = vi.fn();+ constructor(public deps: Record<string, unknown>) {+ mocks.instances.push({ deps, start: this.start, stop: this.stop });+ }+ },+}));++vi.mock('@main/lib/logger', () => ({+ log: { child: () => ({ debug() {}, info() {}, warn() {} }), info() {}, warn() {} },+}));++function rawEvent(overrides: Partial<RawHookRequest> = {}): RawHookRequest {+ return { ptyId: 'claude-session-a', type: 'stop', body: '{}', ...overrides };+}++/** Drives the sink the registry installed on the relay it created. */+function sinkOf(index = 0): (raw: RawHookRequest) => Promise<void> {+ return mocks.instances[index]!.deps.sink as (raw: RawHookRequest) => Promise<void>;+}++describe('SidecarRelayRegistry', () => {+ const key = sidecarRelayKey({+ connectionId: 'agent-ssh:dev-vm',+ repoDir: '/home/me/agent',+ credsSlug: 'my-agent',+ });++ let registry: SidecarRelayRegistry;+ let sink: ReturnType<typeof vi.fn<(raw: RawHookRequest) => Promise<void>>>;++ const subscribe = (sessionId: string, onSessionTerminated = vi.fn()) => {+ const subscriber = { sessionId, onSessionTerminated };+ registry.acquire({+ key,+ credsSlug: 'my-agent',+ subscriber,+ opener: { openChannel: vi.fn() },+ port: 4000,+ token: 'tok',+ resolveEndpoint: async () => ({ port: 4000, token: 'tok' }),+ sink,+ });+ return subscriber;+ };++ beforeEach(() => {+ mocks.instances.length = 0;+ registry = new SidecarRelayRegistry();+ sink = vi.fn<(raw: RawHookRequest) => Promise<void>>(async () => {});+ });++ it('starts exactly one relay however many sessions share the sidecar', () => {+ subscribe('session-a');+ subscribe('session-b');+ subscribe('session-c');++ expect(mocks.instances).toHaveLength(1);+ expect(mocks.instances[0]!.start).toHaveBeenCalledTimes(1);+ expect(registry.subscriberCount(key)).toBe(3);+ });++ it('replays a normal event through the hook path exactly once', async () => {+ subscribe('session-a');+ subscribe('session-b');+ subscribe('session-c');++ await sinkOf()(rawEvent());++ // The event carries its own ptyId, so one delivery routes it correctly —+ // this is the 16x duplicate processing the shared relay removes.+ expect(sink).toHaveBeenCalledTimes(1);+ });++ it('fans session-terminated out to every subscriber', async () => {+ const a = subscribe('session-a');+ const b = subscribe('session-b');+ const c = subscribe('session-c');++ const body = JSON.stringify({ sessionId: 'session-b' });+ await sinkOf()(rawEvent({ type: 'session-terminated', body }));++ for (const subscriber of [a, b, c]) {+ expect(subscriber.onSessionTerminated).toHaveBeenCalledWith(body);+ }+ // A terminated broadcast is not a hook event.+ expect(sink).not.toHaveBeenCalled();+ });++ it('keeps the relay running while any subscriber remains', () => {+ subscribe('session-a');+ subscribe('session-b');++ registry.release(key, 'session-a');++ expect(mocks.instances[0]!.stop).not.toHaveBeenCalled();+ expect(registry.subscriberCount(key)).toBe(1);+ });++ it('stops the relay when the last subscriber leaves', () => {+ subscribe('session-a');+ subscribe('session-b');++ registry.release(key, 'session-a');+ registry.release(key, 'session-b');++ expect(mocks.instances[0]!.stop).toHaveBeenCalledTimes(1);+ expect(registry.get(key)).toBeUndefined();+ });++ it('starts a fresh relay when re-acquired after the last release', () => {+ subscribe('session-a');+ registry.release(key, 'session-a');+ subscribe('session-b');++ expect(mocks.instances).toHaveLength(2);+ expect(mocks.instances[1]!.start).toHaveBeenCalledTimes(1);+ });++ it('keeps one relay per sidecar when a host serves several agents', () => {+ subscribe('session-a');+ const otherKey = sidecarRelayKey({+ connectionId: 'agent-ssh:dev-vm',+ repoDir: '/home/me/other-agent',+ credsSlug: 'other-agent',+ });+ registry.acquire({+ key: otherKey,+ credsSlug: 'other-agent',+ subscriber: { sessionId: 'session-z', onSessionTerminated: vi.fn() },+ opener: { openChannel: vi.fn() },+ port: 4100,+ token: 'tok2',+ resolveEndpoint: async () => ({ port: 4100, token: 'tok2' }),+ sink,+ });++ expect(mocks.instances).toHaveLength(2);+ expect(registry.subscriberCount(key)).toBe(1);+ expect(registry.subscriberCount(otherKey)).toBe(1);+ });++ it('re-acquiring for the same session replaces its subscriber without restarting the relay', async () => {+ subscribe('session-a');+ const replacement = subscribe('session-a');++ expect(mocks.instances).toHaveLength(1);+ expect(registry.subscriberCount(key)).toBe(1);++ await sinkOf()(rawEvent({ type: 'session-terminated', body: '{}' }));+ expect(replacement.onSessionTerminated).toHaveBeenCalledTimes(1);+ });++ it('gives the relay an endpoint resolver that outlives the first subscriber', () => {+ subscribe('session-a');+ subscribe('session-b');+ registry.release(key, 'session-a');++ // The resolver is the relay's only way to follow a restarted sidecar onto a+ // fresh port/token; it must not have been torn down with session-a.+ expect(mocks.instances[0]!.deps.resolveEndpoint).toBeTypeOf('function');+ expect(mocks.instances[0]!.stop).not.toHaveBeenCalled();+ });++ it('releasing an unknown key or session is a no-op', () => {+ subscribe('session-a');++ expect(() => registry.release('no-such-key', 'session-a')).not.toThrow();+ expect(() => registry.release(key, 'no-such-session')).not.toThrow();+ expect(registry.subscriberCount(key)).toBe(1);+ expect(mocks.instances[0]!.stop).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.tsnew file mode 100644index 000000000..b8e7dfec2--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-relay-registry.ts@@ -0,0 +1,151 @@+import type { RawHookRequest } from '@main/core/agent-hooks/hook-server';+import { log } from '@main/lib/logger';+import { RemoteHookEventRelay, type EndpointResolver } from './remote-hook-event-relay';+import type { SidecarChannelOpener } from './sidecar-http';++/**+ * One hook-event relay per sidecar, shared by every session it serves.+ *+ * A sidecar is agent-scoped: one process on the VM serves every session in that+ * agent's repo dir, and its `/events` ring buffer already carries the events of+ * all of them. switchdash routes each event by the `ptyId` the event itself+ * carries (see `dbContextResolver`), never by which relay delivered it — so a+ * single relay per sidecar is sufficient *and* correct.+ *+ * Before this registry a relay was created per session, so N sessions on one+ * sidecar meant N long-poll `direct-tcpip` channels churning against the same+ * SSH transport and every event replayed through the hook path N times. On one+ * real host that was 54 relays for 13 sidecars, with 16 relays on the busiest.+ *+ * Ref-counted: the relay starts on the first acquire and stops on the last+ * release. Releasing is a teardown operation only — evicting a session's PTY+ * must NOT release, or the evicted session would go status-blind while its+ * agent carries on working.+ */++/** Identifies the one sidecar process a set of sessions share. */+export function sidecarRelayKey(params: {+ connectionId: string;+ repoDir: string;+ credsSlug: string;+}): string {+ return `${params.connectionId}::${params.repoDir}::${params.credsSlug}`;+}++/** A session's interest in one sidecar's event stream. */+export interface RelaySubscriber {+ readonly sessionId: string;+ /** Called for every `session-terminated` broadcast; the subscriber filters for its own id. */+ onSessionTerminated(rawBody: string): void;+}++export interface RelayAcquireParams {+ key: string;+ /** The agent name the sidecar is keyed on — log attribution only. */+ credsSlug: string;+ subscriber: RelaySubscriber;+ opener: SidecarChannelOpener;+ port: number;+ token: string;+ /**+ * Re-resolves the sidecar endpoint after repeated poll failures. Captured+ * from the first subscriber and kept for the entry's whole life — a restarted+ * sidecar binds a fresh port and token, and the relay must follow it even+ * after the session that first opened it is gone.+ */+ resolveEndpoint: EndpointResolver;+ /** Replays a non-terminated event through switchdash's hook path. Called once per event. */+ sink: (raw: RawHookRequest) => Promise<void>;+}++interface RelayEntry {+ relay: RemoteHookEventRelay;+ subscribers: Map<string, RelaySubscriber>;+}++export class SidecarRelayRegistry {+ private readonly entries = new Map<string, RelayEntry>();++ /**+ * Join `subscriber` to the relay for `key`, starting one if this is the first+ * subscriber. Re-acquiring for a session id already present replaces that+ * subscriber (a re-provisioned runtime) without disturbing the relay.+ */+ acquire(params: RelayAcquireParams): void {+ const existing = this.entries.get(params.key);+ if (existing) {+ existing.subscribers.set(params.subscriber.sessionId, params.subscriber);+ return;+ }++ const subscribers = new Map<string, RelaySubscriber>([+ [params.subscriber.sessionId, params.subscriber],+ ]);++ const relay = new RemoteHookEventRelay({+ opener: params.opener,+ port: params.port,+ token: params.token,+ resolveEndpoint: params.resolveEndpoint,+ sink: async (raw) => {+ if (raw.type === 'session-terminated') {+ // Every session on this sidecar must hear it: the terminated id may+ // belong to any of them, and each filters for its own.+ for (const subscriber of [...subscribers.values()]) {+ subscriber.onSessionTerminated(raw.body);+ }+ return;+ }+ await params.sink(raw);+ },+ // Bound explicitly rather than inherited: the relay polls on its own timer+ // for as long as any session needs it, so a scope captured from whichever+ // session happened to start it would drift out of date.+ log: log.child({ component: 'hook-relay', agentSlug: params.credsSlug }),+ });++ this.entries.set(params.key, { relay, subscribers });+ relay.start();++ log.info('SidecarRelayRegistry: started shared relay', {+ sidecarKey: params.key,+ port: params.port,+ });+ }++ /**+ * Drop `sessionId`'s interest in `key`, stopping the relay when it was the+ * last. Teardown only — never call this to evict a PTY.+ */+ release(key: string, sessionId: string): void {+ const entry = this.entries.get(key);+ if (!entry) return;++ entry.subscribers.delete(sessionId);+ if (entry.subscribers.size > 0) return;++ entry.relay.stop();+ this.entries.delete(key);+ log.info('SidecarRelayRegistry: stopped shared relay (last subscriber left)', {+ sidecarKey: key,+ });+ }++ /** The relay serving `key`, if one is running. */+ get(key: string): RemoteHookEventRelay | undefined {+ return this.entries.get(key)?.relay;+ }++ /** Live subscriber count for `key` — for tests and diagnostics. */+ subscriberCount(key: string): number {+ return this.entries.get(key)?.subscribers.size ?? 0;+ }++ /** Stop every relay and forget every subscriber. App shutdown and test teardown. */+ stopAll(): void {+ for (const entry of this.entries.values()) entry.relay.stop();+ this.entries.clear();+ }+}++export const sidecarRelayRegistry = new SidecarRelayRegistry();diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 33bbb67d9..6f063ebed 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -5,6 +5,7 @@ import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import type { Session } from '@shared/core/sessions/sessions';+import { sidecarRelayRegistry } from './sidecar-relay-registry';import { SshAgentRuntime } from './ssh-agent-runtime';const openSsh2Pty = vi.hoisted(() => vi.fn());@@ -209,6 +210,10 @@ describe('SshAgentRuntime', () => {httpPostJsonOverChannel.mockClear();vi.mocked(events.emit).mockClear();connectionListeners.length = 0;+ // The relay registry is a module singleton keyed by host+dir+agent, so a+ // relay acquired by one test would otherwise be reused by the next and its+ // fresh proxy never polled.+ sidecarRelayRegistry.stopAll();ptySessionRegistry.unregister('location-1:session-1');});@@ -381,25 +386,94 @@ describe('SshAgentRuntime', () => {expect(httpPostJsonOverChannel).not.toHaveBeenCalled();});- it('re-attaches a remote tmux session on reconnect without relaunching the sidecar', async () => {+ it('re-attaches a remote tmux session without relaunching the sidecar', async () => {+ // Re-attach is driven by RemoteAttachmentPool rather than a per-runtime+ // reconnect listener: 51 sessions each listening meant 51 simultaneous+ // attaches on a transport that had only just come back.const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];mockSpawn(exitHandlers);const item = session();+ const provider = sshProvider({ tmux: true });- await sshProvider({ tmux: true }).start(item);+ await provider.start(item);expect(openSsh2Pty).toHaveBeenCalledTimes(1);expect(deployAndLaunch).toHaveBeenCalledTimes(1);// The interactive PTY dies with the dropped connection; for tmux the- // provider tears down the local session but leaves it desired.+ // provider tears down the local session but keeps it re-attachable.for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 1 });- emitReconnected('ssh-1');- await vi.waitFor(() => expect(openSsh2Pty).toHaveBeenCalledTimes(2));+ await provider.attach();++ expect(openSsh2Pty).toHaveBeenCalledTimes(2);// Re-attach reuses the still-running sidecar + relay rather than relaunching.expect(deployAndLaunch).toHaveBeenCalledTimes(1);});+ it('re-attaches after an eviction, which clears the supervisor desired flag', async () => {+ // dehydrate() -> detachPty() -> supervisor.stop() clears `desired`. attach()+ // must not gate on it, or an evicted session could never come back.+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);+ const provider = sshProvider({ tmux: true });++ await provider.start(session());+ expect(openSsh2Pty).toHaveBeenCalledTimes(1);++ await provider.detachForEviction();+ expect(provider.isAttached()).toBe(false);++ await provider.attach();+ expect(openSsh2Pty).toHaveBeenCalledTimes(2);+ });++ it('does not report the agent as exited when a session is evicted', async () => {+ // The sidebar derives status from hook events; a deliberate detach must not+ // look like the agent stopping, or every eviction would flip it to idle.+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);+ const provider = sshProvider({ tmux: true });++ await provider.start(session());+ vi.mocked(events.emit).mockClear();++ await provider.detachForEviction();++ expect(vi.mocked(events.emit)).not.toHaveBeenCalledWith(+ agentSessionExitedChannel,+ expect.anything()+ );+ });++ it('makes a session attachable without opening a PTY', async () => {+ // Provisioned-but-not-viewed sessions still need the sidecar and its relay:+ // status, room membership and notifications all arrive over the relay.+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);+ const provider = sshProvider({ tmux: true });++ await provider.ensureAttachable(session());++ expect(deployAndLaunch).toHaveBeenCalledTimes(1);+ expect(openSsh2Pty).not.toHaveBeenCalled();+ expect(provider.isAttached()).toBe(false);+ });++ it('does not re-launch the sidecar when ensureAttachable is called again', async () => {+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);+ const provider = sshProvider({ tmux: true });+ const item = session();++ await provider.ensureAttachable(item);+ await provider.ensureAttachable(item);+ // The subsequent attach reuses it too.+ await provider.attach();++ expect(deployAndLaunch).toHaveBeenCalledTimes(1);+ expect(openSsh2Pty).toHaveBeenCalledTimes(1);+ });+it('ignores reconnect events for other connections', async () => {const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];mockSpawn(exitHandlers);diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 3eddc80f4..26451f362 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -1,6 +1,7 @@import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';+import type { AttachableRuntime } from '@main/core/agent-runtime/attachment/types';import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';import { getAgentById } from '@main/core/agents/getAgentById';@@ -17,12 +18,11 @@ import { getTerminalColorEnv } from '@main/core/pty/terminal-color-scheme';import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';import { sessionHooks } from '@main/core/sessions/session-hooks';import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';-import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';-import type { SshConnectionManagerEvent } from '@main/core/ssh/lifecycle/ssh-connection-manager';import { events } from '@main/lib/events';import { runWithLogContext } from '@main/lib/log-context';import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';import type { AgentSessionConfig } from '@shared/core/providers/agent-session';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';@@ -31,11 +31,11 @@ import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import type { Session } from '@shared/core/sessions/sessions';import { ensureAgentSidecar, probeAgentSidecar } from './ensure-agent-sidecar';import { scheduleInitialPromptInjection } from './keystroke-injection';-import { RemoteHookEventRelay } from './remote-hook-event-relay';import { createRemotePluginFs } from './remote-plugin-fs';import type { SidecarEndpoint, SidecarHost } from './remote-sidecar-launcher';import { resolveAgentExecutable } from './resolve-agent-executable';import { httpPostJsonOverChannel } from './sidecar-http';+import { sidecarRelayKey, sidecarRelayRegistry } from './sidecar-relay-registry';const DEFAULT_COLS = 80;const DEFAULT_ROWS = 24;@@ -48,17 +48,49 @@ function parseExtraArgs(value: string | undefined): string[] {return value.trim().split(/\s+/);}-export class SshAgentRuntime implements AgentRuntimeProvider {+/**+ * Coalesce concurrent calls that do the same per-workspace work.+ *+ * Sidecar ensure and hook install are keyed by repo dir, not by session, so+ * every session in a dir would otherwise repeat them — on one real host that+ * meant 51 identical SFTP writes and tmux probes racing at startup. Only+ * in-flight calls are shared; once settled the next caller does the work again,+ * so this coalesces a burst without caching a result that can go stale.+ */+function dedupeInFlight<T>(+ registry: Map<string, Promise<T>>,+ key: string,+ work: () => Promise<T>+): Promise<T> {+ const inFlight = registry.get(key);+ if (inFlight) return inFlight;+ const promise = work().finally(() => {+ if (registry.get(key) === promise) registry.delete(key);+ });+ registry.set(key, promise);+ return promise;+}++/** Keyed by sidecar (`connectionId::repoDir::credsSlug`). */+const sidecarEnsuresInFlight = new Map<string, Promise<SidecarEndpoint>>();+/** Keyed by `connectionId::repoDir::providerId`. The written paths are unused. */+const remoteHookInstallsInFlight = new Map<string, Promise<unknown>>();++export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime {private pty: Pty | null = null;private known = false;/** The session this runtime last started — kept for reconnect rehydration. */private session: Session | null = null;- private relay: RemoteHookEventRelay | null = null;+ /** Key of the shared sidecar relay this session subscribes to, when joined. */+ private relayKey: string | null = null;+ /** True once the sidecar is up and the relay joined — the `ensureAttachable` guard. */+ private sidecarReady = false;+ /** Hook env pointing the agent at its sidecar; resolved by `ensureAttachable`. */+ private hookEnv: Record<string, string> = {};/** Last resolved sidecar endpoint (agent-scoped, shared by all sessions on the* VM), captured at launch so a delete can POST /disconnect without re-ensuring. */private sidecarEndpoint: SidecarEndpoint | null = null;private supervisor = new AgentRuntimeSupervisor();- private readonly handleConnectionEvent: (evt: SshConnectionManagerEvent) => void;private readonly locationId: string;private readonly sessionPath: string;private readonly sessionId: string;@@ -103,17 +135,59 @@ export class SshAgentRuntime implements AgentRuntimeProvider {this.fs = fs;this.proxy = proxy;this.connectionId = connectionId;- this.handleConnectionEvent = (evt: SshConnectionManagerEvent) => {- if (evt.type === 'reconnected' && evt.connectionId === this.connectionId) {- this.rehydrate().catch((e: unknown) => {- log.error('SshAgentRuntime: rehydrate after reconnect failed', {- connectionId: this.connectionId,- error: String(e),- });- });- }- };- sshConnectionManager.on('connection-event', this.handleConnectionEvent);+ // Deliberately no per-runtime `connection-event` listener: every session on+ // a host would re-attach in the same tick on reconnect, which is what+ // saturated the shared transport and re-tripped the wedge watchdog.+ // `RemoteAttachmentPool` owns one listener per connection and replays a+ // bounded, staggered set instead.+ }++ // ─── AttachableRuntime ───────────────────────────────────────────────────++ get attachHostKey(): string {+ return this.connectionId;+ }++ get attachSessionId(): string {+ return this.sessionId;+ }++ isAttached(): boolean {+ return this.pty !== null;+ }++ /**+ * Bring up everything except the PTY: the on-VM sidecar and the shared+ * hook-event relay, plus the hook env the agent is launched with.+ *+ * Called at provision time so a session that is never opened still reports+ * status, room membership and notifications — all of which arrive over the+ * relay, not the terminal. Idempotent.+ */+ async ensureAttachable(session: Session): Promise<void> {+ this.known = true;+ this.session = session;+ if (!this.tmux) return;+ if (this.sidecarReady) return;++ // Install the agent's hooks into the remote workspace before launch so the+ // hook env actually has commands to run — without this the remote agent+ // posts nothing to the sidecar (local sessions get this via+ // ensureHooksInstalled).+ await this.installRemoteHooks(session.providerId);+ const endpoint = await this.launchSidecar(session);+ this.hookEnv = buildAgentHookEnv({+ port: endpoint.port,+ ptyId: makePtyId(session.providerId, this.sessionId),+ token: endpoint.token,+ endpointFile: endpoint.endpointFile,+ });+ this.sidecarReady = true;+ }++ /** Close the local PTY but leave the agent running in tmux and the relay joined. */+ async detachForEviction(): Promise<void> {+ await this.dehydrate();}/** The registry key of this session's agent PTY. */@@ -122,35 +196,31 @@ export class SshAgentRuntime implements AgentRuntimeProvider {}/**- * Re-attach the remote session if it was live before an SSH drop but its- * interactive PTY died with the connection. On tmux hosts the agent process- * survives inside its pane and the on-VM sidecar keeps running, so this only- * re-opens the local PTY onto the existing pane — the sidecar and its- * self-healing event relay are reused rather than relaunched.+ * Open the local PTY onto the remote tmux pane. The agent process lives in+ * that pane and the on-VM sidecar keeps running regardless, so this only+ * re-opens the view — the sidecar and its shared event relay are reused+ * rather than relaunched.+ *+ * Deliberately does NOT gate on `supervisor.isDesired()`: `detachPty` clears+ * `desired`, so an evicted session could otherwise never be re-attached.+ * `beginStart` still short-circuits when a PTY is live or a spawn is already+ * in flight, so repeated calls remain safe.*/- private async rehydrate(): Promise<void> {+ async attach(): Promise<void> {if (!this.known || this.pty) return;- if (!this.supervisor.isDesired()) return;const session = this.session;if (!session) return;- return this.withLogScope(() => this.rehydrateInternal(session));+ return this.withLogScope(() => this.attachInternal(session));}- private async rehydrateInternal(session: Session): Promise<void> {+ private async attachInternal(session: Session): Promise<void> {const size = ptySessionRegistry.getLastSize(this.ptySessionId) ?? {cols: DEFAULT_COLS,rows: DEFAULT_ROWS,};- log.info('SshAgentRuntime: re-attaching session after reconnect', {- sessionId: this.sessionId,- });- await this.startInternal(session, size, true, undefined, true, {+ log.info('SshAgentRuntime: attaching session', { sessionId: this.sessionId });+ await this.startInternal(session, size, true, undefined, false, {shellRefreshRetried: false,- }).catch((e: unknown) => {- log.error('SshAgentRuntime: re-attach failed', {- sessionId: this.sessionId,- error: String(e),- });});}@@ -177,6 +247,9 @@ export class SshAgentRuntime implements AgentRuntimeProvider {* with the `SWITCHDASH_HOOK_*` env vars, but those only matter if the settings* actually register the hook commands — otherwise the agent posts no room/* status events to the sidecar. Best-effort: a failure is logged, not fatal.+ *+ * The settings file is per workspace, not per session, so concurrent installs+ * from every session in a dir are coalesced onto one write.*/private async installRemoteHooks(providerId: string): Promise<void> {const plugin = getPlugin(providerId);@@ -189,8 +262,13 @@ export class SshAgentRuntime implements AgentRuntimeProvider {});return;}+ const writeHooks = plugin.behavior.hooks.writeHooks;try {- await plugin.behavior.hooks.writeHooks(createRemotePluginFs(this.fs), []);+ await dedupeInFlight(+ remoteHookInstallsInFlight,+ `${this.connectionId}::${this.sessionPath}::${providerId}`,+ () => writeHooks(createRemotePluginFs(this.fs), [])+ );log.info('SshAgentRuntime: installed remote agent hooks', { providerId });} catch (error) {log.warn('SshAgentRuntime: failed to install remote agent hooks', {@@ -200,6 +278,11 @@ export class SshAgentRuntime implements AgentRuntimeProvider {}}+ /** The agent name the sidecar is keyed on — must match `ensureAgentSidecar`'s `credsSlug`. */+ private credsSlugFor(session: Session, agent: Agent | undefined): string {+ return agent?.name ?? session.agentName ?? session.agentId;+ }+private async launchSidecar(session: Session): Promise<SidecarEndpoint> {// One agent-scoped sidecar serves every session on the VM (this one and any// the sidecar's own watcher auto-starts) — ensure it is running and point@@ -208,22 +291,30 @@ export class SshAgentRuntime implements AgentRuntimeProvider {// the agent's bypass-permissions setting (not this UI session's).const agent = await getAgentById(session.agentId);const host = this.createSidecarHost();- const endpoint = await ensureAgentSidecar({- providerId: session.providerId,- repoDir: this.sessionPath,- deeplinkScheme: DEEPLINK_SCHEME,- autoApprove: agent?.autoApprove ?? false,- credsSlug: agent?.name ?? session.agentName ?? session.agentId,- agentName: agent?.name ?? session.agentName ?? null,- ctx: this.ctx,- connectionId: this.connectionId,- host,- });+ const credsSlug = this.credsSlugFor(session, agent);+ // Every session in this dir would otherwise re-run the same deploy+launch on+ // startup; coalesce so one host sees one ensure, not one per session.+ const endpoint = await dedupeInFlight(+ sidecarEnsuresInFlight,+ sidecarRelayKey({ connectionId: this.connectionId, repoDir: this.sessionPath, credsSlug }),+ () =>+ ensureAgentSidecar({+ providerId: session.providerId,+ repoDir: this.sessionPath,+ deeplinkScheme: DEEPLINK_SCHEME,+ autoApprove: agent?.autoApprove ?? false,+ credsSlug,+ agentName: agent?.name ?? session.agentName ?? null,+ ctx: this.ctx,+ connectionId: this.connectionId,+ host,+ })+ );// Drop any sidecar left in this directory by an earlier generation of the// agent's name — it is still polling Switch and no other path can see it.if (agent) await reapStaleSidecarsForAgent(agent, host, this.sessionPath);this.sidecarEndpoint = endpoint;- this.startRelay(endpoint);+ this.joinRelay(endpoint, session, credsSlug);return endpoint;}@@ -279,31 +370,47 @@ export class SshAgentRuntime implements AgentRuntimeProvider {}/**- * Mirror the sidecar's hook events back into switchdash so its UI reflects the- * remote session's room and status. Replays through the same hook path as- * local sessions, but with `startLocalPoller: false` — the sidecar already- * polls and injects on the VM.+ * Join the shared relay that mirrors the sidecar's hook events back into+ * switchdash, so the UI reflects this remote session's room and status.+ * Replays through the same hook path as local sessions, but with+ * `startLocalPoller: false` — the sidecar already polls and injects on the VM.+ *+ * One relay serves every session on the sidecar: its `/events` ring carries+ * all of them and `handleRawHook` routes each event by the `ptyId` the event+ * itself carries, so a per-session relay would only duplicate the poll and the+ * work. `session-terminated` is the exception and is fanned out to every+ * subscriber by the registry.*/- private startRelay(endpoint: SidecarEndpoint): void {- this.relay?.stop();- const proxy = this.proxy;- const relay = new RemoteHookEventRelay({- opener: { openChannel: (port) => proxy.forwardOut(port) },+ private joinRelay(endpoint: SidecarEndpoint, session: Session, credsSlug: string): void {+ this.relayKey = sidecarRelayKey({+ connectionId: this.connectionId,+ repoDir: this.sessionPath,+ credsSlug,+ });+ sidecarRelayRegistry.acquire({+ key: this.relayKey,+ credsSlug,+ subscriber: {+ sessionId: this.sessionId,+ onSessionTerminated: (body) => this.onRemoteTerminated(body),+ },+ opener: { openChannel: (port) => this.proxy.forwardOut(port) },port: endpoint.port,token: endpoint.token,// Follow the sidecar if it restarts on a different port with a new token,// instead of polling the dead one for the rest of the app's life. Probe,// never launch: a relay must not resurrect a sidecar the user stopped.+ // Resolved from the session captured here rather than `this.session`,+ // which is cleared on teardown while the shared relay lives on for the+ // other sessions.resolveEndpoint: async () => {- const session = this.session;- if (!session) return null;const agent = await getAgentById(session.agentId);const next = await probeAgentSidecar({providerId: session.providerId,repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,- credsSlug: agent?.name ?? session.agentName ?? session.agentId,+ credsSlug,agentName: agent?.name ?? session.agentName ?? null,ctx: this.ctx,connectionId: this.connectionId,@@ -314,39 +421,30 @@ export class SshAgentRuntime implements AgentRuntimeProvider {return next;},sink: async (raw) => {- if (raw.type === 'session-terminated') {- this.onRemoteTerminated(raw.body);- return;- }await agentHookService.handleRawHook(raw, { startLocalPoller: false });},- // Bound explicitly rather than inherited: the relay polls on its own timer- // for the lifetime of the session, and a scope captured from whatever call- // happened to start it would drift out of date.- log: log.child({- component: 'hook-relay',- sessionId: this.sessionId,- agentId: this.session?.agentId,- agentName: this.session?.agentName ?? undefined,- }),});- this.relay = relay;- relay.start();}- private stopRelay(): void {- const relay = this.relay;- if (!relay) return;- this.relay = null;- relay.stop();+ /**+ * Leave the shared relay. Teardown only: evicting this session's PTY must not+ * call this, or the session would stop reporting status while its agent keeps+ * working in its tmux pane.+ */+ private leaveRelay(): void {+ const key = this.relayKey;+ if (!key) return;+ this.relayKey = null;+ this.sidecarReady = false;+ sidecarRelayRegistry.release(key, this.sessionId);}private stopSidecar(): void {- // Only detach this session's relay. The sidecar is agent-scoped and shared- // (other sessions + its notification watcher rely on it), so ending one- // session must not kill it — it is torn down when auto_session is disabled- // or the agent is removed (see stopRemoteWatcher).- this.stopRelay();+ // Only leave this session's shared relay. The sidecar is agent-scoped and+ // shared (other sessions + its notification watcher rely on it), so ending+ // one session must not kill it — it is torn down when auto_session is+ // disabled or the agent is removed (see stopRemoteWatcher).+ this.leaveRelay();}/**@@ -477,30 +575,16 @@ export class SshAgentRuntime implements AgentRuntimeProvider {// switchdash is closed; it injects room messages into the agent's tmux pane.// It therefore requires tmux, must be up before the agent so the agent's// hook env can point at it, and shares the tmux session as its inject target.+ //+ // `ensureAttachable` is idempotent, so this is a no-op when the session was+ // already made attachable at provision time. Passing the hook env on every+ // attach is safe: `buildTmuxShellLine` supplies it via `tmux new-session -e`,+ // which tmux applies only when it creates the session — an existing pane is+ // reused untouched.let hookEnv: Record<string, string> = {};- if (tmuxSessionName && this.relay) {- // Re-attach path (e.g. after an SSH reconnect): the agent is still- // running in its tmux pane and the sidecar + its self-healing relay are- // already live, so re-open the PTY onto the existing pane and skip the- // hook install + sidecar launch. The running agent keeps its original- // hook env, so we need not re-supply it.- log.info('SshAgentRuntime: re-attaching to running tmux session + sidecar', {- sessionId: this.sessionId,- });- } else if (tmuxSessionName) {- const ptyId = makePtyId(session.providerId, this.sessionId);- // Install the agent's hooks into the remote workspace before launch so- // the hook env below actually has commands to run — without this the- // remote agent posts nothing to the sidecar (local sessions get this via- // ensureHooksInstalled).- await this.installRemoteHooks(session.providerId);- const endpoint = await this.launchSidecar(session);- hookEnv = buildAgentHookEnv({- port: endpoint.port,- ptyId,- token: endpoint.token,- endpointFile: endpoint.endpointFile,- });+ if (tmuxSessionName) {+ await this.ensureAttachable(session);+ hookEnv = this.hookEnv;} else {log.warn('SshAgentRuntime: tmux disabled — remote agent will not stay connected to Switch while detached',@@ -696,7 +780,6 @@ export class SshAgentRuntime implements AgentRuntimeProvider {}async destroy(): Promise<void> {- sshConnectionManager.off('connection-event', this.handleConnectionEvent);const wasKnown = this.known;await this.detach();if (this.tmux && wasKnown) {diff --git a/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts b/dash/apps/switchdash-desktop/src/main/core/settings/schema.tsindex e078a9632..95ca101df 100644--- a/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts+++ b/dash/apps/switchdash-desktop/src/main/core/settings/schema.ts@@ -123,6 +123,20 @@ export const browserSettingsSchema = zexport const resourceMonitorSettingsSchema = z.object({ enabled: z.boolean() });+/**+ * How many sessions on one remote host keep a live terminal at once.+ *+ * Every session on a host shares a single SSH transport, and an attached+ * terminal holds a channel on it for as long as it is attached. Past a handful,+ * a slow tunnel (an IAP or SSM ProxyCommand) stops answering channel opens and+ * the transport is torn down and rebuilt in a loop. Detaching costs nothing+ * real: the agent keeps running in its tmux pane on the VM and keeps reporting+ * status, so this bounds a display concern, not the work.+ */+export const remoteSettingsSchema = z.object({+ maxAttachedSessionsPerHost: z.number().int().min(1).max(64),+});+export const openInSettingsSchema = z.object({default: openInAppIdSchema,hidden: z.array(openInAppIdSchema),@@ -143,6 +157,7 @@ export const APP_SETTINGS_SCHEMA_MAP = {browser: browserSettingsSchema,resourceMonitor: resourceMonitorSettingsSchema,changesViewMode: changesViewModeSchema,+ remote: remoteSettingsSchema,} as const;export const appSettingsSchema = z.object({@@ -160,4 +175,5 @@ export const appSettingsSchema = z.object({browser: browserSettingsSchema,resourceMonitor: resourceMonitorSettingsSchema,changesViewMode: changesViewModeSchema,+ remote: remoteSettingsSchema,});diff --git a/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts b/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.tsindex f1b7cdff1..f375b0641 100644--- a/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts+++ b/dash/apps/switchdash-desktop/src/main/core/settings/settings-registry.ts@@ -68,6 +68,9 @@ export const SETTINGS_DEFAULTS = {resourceMonitor: {enabled: false,},+ remote: {+ maxAttachedSessionsPerHost: 4,+ },changesViewMode: {unstaged: 'flat' as const,staged: 'flat' as const,diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.tsindex 06736cda4..54f98c2b8 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts@@ -82,3 +82,17 @@ export const sessionProvisionedChannel = defineEvent<{locationId: string;sshConnectionId?: string;}>('session:provisioned');++/**+ * A remote session's terminal was attached or detached.+ *+ * Attachment is bounded per host and owned by the main process, so the renderer+ * is told rather than asked. `detached` is a normal resting state, not an+ * error — the agent keeps running on the VM and keeps reporting status.+ */+export const sessionAttachmentChangedChannel = defineEvent<{+ sessionId: string;+ state: 'detached' | 'attaching' | 'attached' | 'failed';+ hostKey: string;+ reason?: 'focus' | 'user' | 'startup' | 'adopt' | 'reconnect';+}>('session:attachment-changed');