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
fix(switchdash): recover remote sessions' room after restart/sleep (CHOO-1417) (#31)
Louis Amaudruz86d20a9eca67
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.tsindex 26575fc84..4d9cb8678 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.test.ts@@ -67,6 +67,14 @@ const eventsEmit = vi.fn();vi.mock('@main/lib/events', () => ({events: { emit: (...args: unknown[]) => eventsEmit(...args) },}));+const mirrorRemoteSessionRoom = vi.fn();+const clearSessionRoom = vi.fn();+vi.mock('@main/core/switch-rooms/switch-room-service', () => ({+ switchRoomService: {+ mirrorRemoteSessionRoom: (...args: unknown[]) => mirrorRemoteSessionRoom(...args),+ clearSession: (...args: unknown[]) => clearSessionRoom(...args),+ },+}));import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';@@ -117,6 +125,54 @@ describe('RemoteSessionReconciler', () => {expect(createSession).not.toHaveBeenCalled();});+ it('mirrors the sidecar-reported room into switchRoomService on adoption', async () => {+ knownRows = [];+ httpGetJsonOverChannel.mockResolvedValue({+ sessions: [{ sessionId: 'session-new', roomId: 'room-1' }],+ });+ await reconcile('agent-1');++ expect(mirrorRemoteSessionRoom).toHaveBeenCalledWith(+ { sessionId: 'session-new', providerId: 'claude', ptyId: 'claude-session-session-new' },+ 'room-1',+ 'switch-1'+ );+ });++ it('mirrors the room for an already-known session too (reflects a reconnect)', async () => {+ // The row already exists (not re-adopted), but its room must still be+ // mirrored every tick — this is how a post-restart reconnect surfaces.+ knownRows = [{ id: 'session-known' }];+ httpGetJsonOverChannel.mockResolvedValue({+ sessions: [{ sessionId: 'session-known', roomId: 'room-9' }],+ });+ await reconcile('agent-1');++ expect(createSession).not.toHaveBeenCalled();+ expect(mirrorRemoteSessionRoom).toHaveBeenCalledWith(+ { sessionId: 'session-known', providerId: 'claude', ptyId: 'claude-session-session-known' },+ 'room-9',+ 'switch-1'+ );+ });++ it('does not mirror a room for a session the sidecar reports as roomless', async () => {+ knownRows = [{ id: 'session-bare' }];+ httpGetJsonOverChannel.mockResolvedValue({+ sessions: [{ sessionId: 'session-bare', roomId: null }],+ });+ await reconcile('agent-1');++ expect(mirrorRemoteSessionRoom).not.toHaveBeenCalled();+ });++ it('clears the room mirror when a session row is removed', async () => {+ knownRows = [{ id: 'session-term', agentId: 'agent-1' }];+ await handleRemoteTerminated('session-term');++ expect(clearSessionRoom).toHaveBeenCalledWith('session-term');+ });+it('does nothing when the sidecar reports no sessions', async () => {httpGetJsonOverChannel.mockResolvedValue({ sessions: [] });await reconcile('agent-1');diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.tsindex 0b243f7fe..8cd1d2344 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -7,11 +7,13 @@ import { sshConnectionIdForHost } from '@main/core/locations/location-transport'import { sessionHooks } from '@main/core/sessions/session-hooks';import { sessionService } from '@main/core/sessions/session-service';import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-connection-manager';+import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';+import { makePtyId } from '@shared/core/pty/ptyId';import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';@@ -109,6 +111,9 @@ class RemoteSessionReconciler {this.tombstone(sessionId);for (const ids of this.adopted.values()) ids.delete(sessionId);this.missingStreak.delete(sessionId);+ // Drop the room badge for a session that is going away, so the renderer+ // does not keep showing a stale room for a row it is about to remove.+ switchRoomService.clearSession(sessionId);let deleted: { changes: number };try {deleted = await db.delete(sessions).where(eq(sessions.id, sessionId));@@ -253,9 +258,18 @@ class RemoteSessionReconciler {): new Set<string>();for (const vm of vmSessions) {- if (known.has(vm.sessionId)) continue;if (this.isTombstoned(vm.sessionId)) continue;- await this.adoptSession(agent, vm.sessionId, vm.roomId);+ if (!known.has(vm.sessionId)) {+ await this.adoptSession(agent, vm.sessionId, vm.roomId);+ }+ // Mirror the room the sidecar reports into switchRoomService every tick —+ // this is what recovers a session's room after a restart/wake (the row is+ // re-adopted but the room association is otherwise dropped) and reflects a+ // later reconnect/room switch, for both freshly-adopted and already-known+ // sessions. Only sets a room the sidecar actually reports; clearing is left+ // to the prune/terminate path so a transient null poll cannot flicker the+ // badge off a still-live session.+ if (vm.roomId) this.mirrorSessionRoom(agent, vm.sessionId, vm.roomId);}await this.pruneVanished(agentId, vmIds);@@ -367,6 +381,23 @@ class RemoteSessionReconciler {}}+ /**+ * Record, for display, the room the sidecar reports a session is attending.+ * Skipped when the agent has no Switch identity (it cannot be in a room), so+ * the mirrored connection always carries a real Switch agent id. The ptyId is+ * derived deterministically from provider + session id (the same scheme the+ * hook/relay path uses), keeping the connection shape identical whether the+ * room came from a live hook or this snapshot mirror.+ */+ private mirrorSessionRoom(agent: Agent, sessionId: string, roomId: string): void {+ if (!agent.switchAgentId) return;+ switchRoomService.mirrorRemoteSessionRoom(+ { sessionId, providerId: agent.providerId, ptyId: makePtyId(agent.providerId, sessionId) },+ roomId,+ agent.switchAgentId+ );+ }+/*** Create a switchdash session row whose id equals the VM's session id, so* the session-start path attaches to the running tmux pane rather than spawningdiff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.tsindex 0f1b9aded..c2eae4ef8 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.test.ts@@ -15,12 +15,21 @@ vi.mock('./switch-notification-poller', () => ({switchNotificationPoller: { connect: vi.fn(), disconnect: vi.fn(), dispose: vi.fn() },}));+const dbInsert = vi.fn();vi.mock('@main/db/client', () => {const where = () => Promise.resolve([] as unknown[]);const from = () => ({ where });const onConflictDoUpdate = () => Promise.resolve(undefined);const values = () => ({ onConflictDoUpdate });- return { db: { select: () => ({ from }), insert: () => ({ values }) } };+ return {+ db: {+ select: () => ({ from }),+ insert: () => {+ dbInsert();+ return { values };+ },+ },+ };});const { switchRoomService } = await import('./switch-room-service');@@ -36,6 +45,7 @@ describe('SwitchRoomService', () => {beforeEach(() => {switchRoomService.dispose();emit.mockClear();+ dbInsert.mockClear();});it('records a connection and emits a change', () => {@@ -84,4 +94,50 @@ describe('SwitchRoomService', () => {switchRoomService.clearSession('nope');expect(emit).not.toHaveBeenCalled();});++ it('mirrors a remote session room for display and emits a change', () => {+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-a', 'agent-1');++ expect(switchRoomService.getConnections()).toEqual([+ { sessionId: 'session-1', roomId: 'room-a', agentId: 'agent-1' },+ ]);+ expect(emit).toHaveBeenCalledWith(sessionRoomChangedChannel, {+ sessionId: 'session-1',+ roomId: 'room-a',+ agentId: 'agent-1',+ });+ });++ it('does not re-emit when mirroring the same room every tick', () => {+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-a', 'agent-1');+ emit.mockClear();+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-a', 'agent-1');+ expect(emit).not.toHaveBeenCalled();+ });++ it('re-emits when a mirrored session switches room', () => {+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-a', 'agent-1');+ emit.mockClear();+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-b', 'agent-1');+ expect(emit).toHaveBeenCalledWith(sessionRoomChangedChannel, {+ sessionId: 'session-1',+ roomId: 'room-b',+ agentId: 'agent-1',+ });+ });++ it('does not persist a mirrored remote room (no restore-blob write)', async () => {+ // The reconciler re-derives remote rooms from the live sidecar snapshot on+ // every boot, so a mirrored room must not enter the persisted restore set —+ // else restoreSwitchRoomSessions would try to relaunch it at next startup.+ switchRoomService.mirrorRemoteSessionRoom(ctx, 'room-a', 'agent-1');+ await Promise.resolve();+ await Promise.resolve();+ expect(dbInsert).not.toHaveBeenCalled();+ });++ it('setSessionRoom does persist (contrast with the mirror path)', async () => {+ switchRoomService.setSessionRoom(ctx, 'room-a', 'agent-1', 'Room A');+ await vi.waitFor(() => expect(dbInsert).toHaveBeenCalled());+ });});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.tsindex 8b790b647..9060f5fa2 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-room-service.ts@@ -88,6 +88,43 @@ class SwitchRoomService implements IDisposable {});}+ /**+ * Mirror the room a remote session is attending, as reported by the on-VM+ * sidecar's `/sessions` snapshot. Unlike setSessionRoom (the local+ * connect_to_room hook path) this records the association for DISPLAY only: it+ * does not persist to the restore blob and does not start switchdash's+ * notification poller — the sidecar owns polling and injection on the VM, and+ * the reconciler re-derives the room from the live snapshot every tick, so+ * there is nothing to restore across restarts. The unchanged-guard keeps the+ * steady-state 2s reconcile from re-emitting; a genuine room switch emits+ * `sessionRoomChangedChannel` so the renderer badge updates.+ */+ mirrorRemoteSessionRoom(ctx: SessionRoomContext, roomId: string, agentId: string): void {+ const previous = this.connections.get(ctx.sessionId);+ if (previous && previous.roomId === roomId && previous.agentId === agentId) return;++ this.connections.set(ctx.sessionId, {+ sessionId: ctx.sessionId,+ roomId,+ agentId,+ roomName: previous?.roomName ?? null,+ providerId: ctx.providerId,+ ptyId: ctx.ptyId,+ });++ log.info('SwitchRoomService: mirrored remote session room', {+ sessionId: ctx.sessionId,+ roomId,+ agentId,+ });++ events.emit(sessionRoomChangedChannel, {+ sessionId: ctx.sessionId,+ roomId,+ agentId,+ });+ }+/*** Re-establish a session's room connection and poller from persisted state.* Called when a session's PTY (re)launches — e.g. after an app restart — so