Skip to content

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

refactor(switchdash): collapse session = conversation = 1 and simplify everything downstream (CHOO-1424) (#21)

Louis Amaudruza3388f44e192
diff --git a/dash/AGENTS.md b/dash/AGENTS.md
index 3229c2247..530e91b73 100644
--- a/dash/AGENTS.md
+++ b/dash/AGENTS.md
@@ -5,7 +5,7 @@ coding agents in parallel. Each agent runs in its own session at the project roo
are no Git worktrees). An agent runs either locally or — when configured remote — on an
SSH host, where it runs inside tmux next to a switchdash-deployed sidecar so it keeps
working and listening to its Switch rooms while switchdash is closed (CHOO-1059). It
-combines provider-agnostic CLI agent execution, session and conversation management,
+combines provider-agnostic CLI agent execution, session management,
terminal sessions, MCP and skills, and packaging for desktop releases.
Switchdash is an open-source fork; upstream attribution is recorded in `NOTICE`. The
@@ -226,7 +226,7 @@ Shared IPC primitives, provider metadata, events, MCP types, skills types, and
domain types live under `src/shared/`.
Major main-process domains live under `src/main/core/`: agent hooks, agents, app,
-conversations, dependencies, execution context, fs, projects, prompt library, PTY,
+agent runtime, dependencies, execution context, fs, projects, prompt library, PTY,
resource monitor, runtime, search, secrets, sessions, settings, switch agents,
terminal shell, terminals, updates, view state, and workspaces. Stateful
main-process concerns use singleton services; expected failures should use the
@@ -299,8 +299,8 @@ pnpm run lint
- Access session and project MobX stores through selectors and session view hooks:
`getSessionStore`, `asProvisioned`, `sessionViewKind`, `getSessionManagerStore`,
`getProjectStore`, `asMounted`, `useSessionViewKind`, `useWorkspace`,
- `useWorkspaceId`, `useDevServers`, `useWorkspaceViewModel`, `useConversations`,
- and `useTerminals`.
+ `useWorkspaceId`, `useDevServers`, `useWorkspaceViewModel`, and
+ `useSessionAgent`.
- Never use `asProvisioned(...)!` or `asMounted(...)!`; use explicit null checks.
- State guards must check `kind !== 'ready'` rather than enumerating non-ready states.
- Access session managers through `getSessionManagerStore(projectId)`, not `project.sessionManager`.
diff --git a/dash/apps/switchdash-desktop/src/main/app/deeplinks.ts b/dash/apps/switchdash-desktop/src/main/app/deeplinks.ts
index 13e375fa9..c83efd564 100644
--- a/dash/apps/switchdash-desktop/src/main/app/deeplinks.ts
+++ b/dash/apps/switchdash-desktop/src/main/app/deeplinks.ts
@@ -28,9 +28,9 @@ type ParsedDeeplink = {
server: string;
agentId: string;
roomId: string;
- /** Shared conversation id; present on links from current switchdash builds and
+ /** Shared session id; present on links from current switchdash builds and
* preferred for resolution (works on any client). Empty for older links. */
- conversationId: string;
+ sessionId: string;
};
// A deeplink that arrived before the renderer was ready (cold start). Flushed
@@ -53,12 +53,12 @@ function parseSessionDeeplink(rawUrl: string): ParsedDeeplink | null {
const server = url.searchParams.get('server') ?? '';
const agentId = url.searchParams.get('agent') ?? '';
const roomId = url.searchParams.get('room') ?? '';
- const conversationId = url.searchParams.get('conversation') ?? '';
+ const sessionId = url.searchParams.get('session') ?? '';
if (!server || !agentId || !roomId) {
log.warn('deeplink: missing server/agent/room', { rawUrl });
return null;
}
- return { server, agentId, roomId, conversationId };
+ return { server, agentId, roomId, sessionId };
}
function focusWindow(): void {
diff --git a/dash/apps/switchdash-desktop/src/main/app/menu.ts b/dash/apps/switchdash-desktop/src/main/app/menu.ts
index ff878761a..bdd0259ad 100644
--- a/dash/apps/switchdash-desktop/src/main/app/menu.ts
+++ b/dash/apps/switchdash-desktop/src/main/app/menu.ts
@@ -2,7 +2,6 @@ import { app, clipboard, Menu, shell } from 'electron';
import { events } from '@main/lib/events';
import {
menuCheckForUpdatesChannel,
- menuCloseTabChannel,
menuGiveFeedbackChannel,
menuOpenSettingsChannel,
menuQuitRequestedChannel,
@@ -94,11 +93,7 @@ export function setupApplicationMenu(): void {
]
: []),
isMac
- ? {
- label: 'Close Tab',
- accelerator: 'CmdOrCtrl+W',
- click: () => events.emit(menuCloseTabChannel, undefined),
- }
+ ? { role: 'close' as const }
: {
label: 'Quit',
accelerator: 'CmdOrCtrl+Q',
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
index 28693f78a..46dc1deb8 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/agent-hook-service.ts
@@ -1,11 +1,11 @@
import type { IDisposable, IInitializable } from '@switchdash/shared';
import { eq } from 'drizzle-orm';
-import { conversationEvents } from '@main/core/conversations/conversation-events';
-import { saveProviderSessionId } from '@main/core/conversations/save-provider-session-id';
-import { loadSessionWithAgent } from '@main/core/conversations/session-join';
-import { setProviderSessionId } from '@main/core/conversations/set-provider-session-id';
-import { touchConversation } from '@main/core/conversations/touchConversation';
import { getPlugin } from '@main/core/providers/plugin-registry';
+import { saveProviderSessionId } from '@main/core/sessions/operations/save-provider-session-id';
+import { setProviderSessionId } from '@main/core/sessions/operations/set-provider-session-id';
+import { touchSession } from '@main/core/sessions/operations/touchSession';
+import { sessionHooks } from '@main/core/sessions/session-hooks';
+import { loadSessionWithAgent } from '@main/core/sessions/session-join';
import { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
import { db } from '@main/db/client';
@@ -13,12 +13,12 @@ import { sessions } from '@main/db/schema';
import { events } from '@main/lib/events';
import { HookCore, type Hookable } from '@main/lib/hookable';
import { log } from '@main/lib/logger';
-import {
- conversationAgentStatusChangedChannel,
- conversationChangedChannel,
-} from '@shared/core/conversations/conversationEvents';
import { isValidProviderSessionId } from '@shared/core/providers/agent-provider-registry';
import { type AgentEvent, type AgentStatus } from '@shared/core/providers/agentEvents';
+import {
+ sessionAgentStatusChangedChannel,
+ sessionChangedChannel,
+} from '@shared/core/sessions/sessionEvents';
import { dbContextResolver } from './db-context-resolver';
import { deriveAgentStatus } from './derive-agent-status';
import { parseHookEvent } from './event-enricher';
@@ -39,21 +39,20 @@ function determineSoundEvent(
}
async function handleSessionEvent(
- ctx: { conversationId: string; sessionId: string; projectId: string; providerId: string },
+ ctx: { sessionId: string; projectId: string; providerId: string },
providerSessionId: string
): Promise<void> {
if (!isValidProviderSessionId(ctx.providerId, providerSessionId)) return;
if (ctx.providerId === 'droid') {
- await saveProviderSessionId(ctx.conversationId, providerSessionId);
+ await saveProviderSessionId(ctx.sessionId, providerSessionId);
return;
}
- const updated = await setProviderSessionId(ctx.conversationId, providerSessionId);
+ const updated = await setProviderSessionId(ctx.sessionId, providerSessionId);
if (!updated) return;
- events.emit(conversationChangedChannel, {
- conversationId: ctx.conversationId,
+ events.emit(sessionChangedChannel, {
sessionId: ctx.sessionId,
projectId: ctx.projectId,
changes: { providerSessionId },
@@ -118,7 +117,7 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
// Surface the running turn's activity on the bridged channel by refreshing
// the "working on it…" message. A no-op unless a room-triggered turn is
// live. In-process call: the `events` bus is renderer-bound (see below).
- switchNotificationPoller.onAgentActivity(parsed.ctx.conversationId, parsed.detail);
+ switchNotificationPoller.onAgentActivity(parsed.ctx.sessionId, parsed.detail);
return;
}
@@ -131,43 +130,38 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
async initialize(): Promise<void> {
await this.server.start(async (raw) => this.handleRawHook(raw, { startLocalPoller: true }));
- conversationEvents.on(
- 'conversation:input-submitted',
- ({ projectId, sessionId, conversationId, providerId }) => {
- // Only synthesise a 'start' event when the plugin does not supply its own
- // start hook (e.g. UserPromptSubmit). Providers with start-capable hooks
- // get 'working' from the real hook event instead.
- const plugin = getPlugin(providerId);
- const hooksDesc = plugin?.capabilities.hooks;
- const supportedEvents =
- hooksDesc && hooksDesc.kind !== 'none' ? hooksDesc.supportedEvents : [];
- const hasStartHook = supportedEvents.includes('start');
-
- if (!hasStartHook) {
- const agentEvent: AgentEvent = {
- type: 'start',
- source: 'input',
- providerId,
- projectId,
- sessionId,
- conversationId,
- timestamp: Date.now(),
- payload: {},
- };
- this.emitAgentEvent(agentEvent, isAppFocused());
- }
+ sessionHooks.on('session:input-submitted', ({ projectId, sessionId, providerId }) => {
+ // Only synthesise a 'start' event when the plugin does not supply its own
+ // start hook (e.g. UserPromptSubmit). Providers with start-capable hooks
+ // get 'working' from the real hook event instead.
+ const plugin = getPlugin(providerId);
+ const hooksDesc = plugin?.capabilities.hooks;
+ const supportedEvents =
+ hooksDesc && hooksDesc.kind !== 'none' ? hooksDesc.supportedEvents : [];
+ const hasStartHook = supportedEvents.includes('start');
+
+ if (!hasStartHook) {
+ const agentEvent: AgentEvent = {
+ type: 'start',
+ source: 'input',
+ providerId,
+ projectId,
+ sessionId,
+ timestamp: Date.now(),
+ payload: {},
+ };
+ this.emitAgentEvent(agentEvent, isAppFocused());
+ }
- const now = new Date().toISOString();
- void touchConversation(conversationId, now).then(() => {
- events.emit(conversationChangedChannel, {
- conversationId,
- sessionId,
- projectId,
- changes: { lastInteractedAt: now },
- });
+ const now = new Date().toISOString();
+ void touchSession(sessionId, now).then(() => {
+ events.emit(sessionChangedChannel, {
+ sessionId,
+ projectId,
+ changes: { lastInteractedAt: now },
});
- }
- );
+ });
+ });
// Persist agent status to DB and emit simplified IPC for renderer.
this.on('agent:event', async (event) => {
@@ -179,7 +173,7 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
event.type === 'notification' ? event.payload.notificationType : undefined;
log.debug('AgentHookService: agent status change', {
- conversationId: event.conversationId,
+ sessionId: event.sessionId,
status,
eventType: event.type,
...(notificationType ? { notificationType } : {}),
@@ -191,15 +185,14 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
// ipcMain), so an in-process emit never reaches an in-process listener — the
// poller would otherwise never observe a turn finishing and would release
// its gate only via the 60s fallback.
- switchNotificationPoller.onAgentStatusChange(event.conversationId, status, notificationType);
+ switchNotificationPoller.onAgentStatusChange(event.sessionId, status, notificationType);
await db
.update(sessions)
.set({ agentStatus: status, agentStatusSeen: seen })
- .where(eq(sessions.id, event.conversationId));
+ .where(eq(sessions.id, event.sessionId));
- events.emit(conversationAgentStatusChangedChannel, {
- conversationId: event.conversationId,
+ events.emit(sessionAgentStatusChangedChannel, {
sessionId: event.sessionId,
projectId: event.projectId,
status,
@@ -212,24 +205,23 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
// Reset a stuck 'working' status to 'idle' when the agent PTY exits
// unexpectedly (the user interrupts/kills the agent before a 'stop' or
// 'error' hook fires). Subscribed in-process: the `events` bus only delivers
- // main→renderer, so this handler must use conversationEvents. Poller/room
+ // main→renderer, so this handler must use sessionHooks. Poller/room
// teardown is NOT done here — this also fires on respawn, where the poller
// should survive; that teardown lives at the stop/delete lifecycle points.
- conversationEvents.on('conversation:session-exited', ({ conversationId, sessionId }) => {
+ sessionHooks.on('session:agent-exited', ({ sessionId }) => {
void (async () => {
try {
- const loaded = await loadSessionWithAgent(conversationId);
+ const loaded = await loadSessionWithAgent(sessionId);
if (!loaded || loaded.row.agentStatus !== 'working') return;
await db
.update(sessions)
.set({ agentStatus: 'idle', agentStatusSeen: 1 })
- .where(eq(sessions.id, conversationId));
+ .where(eq(sessions.id, sessionId));
- switchNotificationPoller.onAgentStatusChange(conversationId, 'idle');
+ switchNotificationPoller.onAgentStatusChange(sessionId, 'idle');
- events.emit(conversationAgentStatusChangedChannel, {
- conversationId,
+ events.emit(sessionAgentStatusChangedChannel, {
sessionId,
projectId: loaded.projectId,
status: 'idle',
@@ -238,7 +230,7 @@ class AgentHookService implements IInitializable, IDisposable, Hookable<AgentHoo
});
} catch (error) {
log.warn('AgentHookService: failed to reset stuck working status on exit', {
- conversationId,
+ sessionId,
error: String(error),
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts
index bc62525da..a23a9ff7c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/db-context-resolver.ts
@@ -1,22 +1,21 @@
-import { loadSessionWithAgent } from '@main/core/conversations/session-join';
+import { loadSessionWithAgent } from '@main/core/sessions/session-join';
import { parsePtyId } from '@shared/core/pty/ptyId';
import type { ContextResolver } from './event-enricher';
/**
- * The local main process's hook context resolver: derives the conversation
- * context for a `ptyId` by parsing it and loading the session (for its
- * project id) from the database.
+ * The local main process's hook context resolver: derives the session context
+ * for a `ptyId` by parsing it and loading the session (for its project id)
+ * from the database.
*/
export const dbContextResolver: ContextResolver = async (ptyId) => {
const parsed = parsePtyId(ptyId);
if (!parsed) return null;
- const loaded = await loadSessionWithAgent(parsed.conversationId);
+ const loaded = await loadSessionWithAgent(parsed.sessionId);
if (!loaded) return null;
return {
- conversationId: parsed.conversationId,
- sessionId: parsed.conversationId,
+ sessionId: parsed.sessionId,
projectId: loaded.projectId,
providerId: parsed.providerId,
ptyId,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts
index c6f754a99..be48031e0 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/derive-agent-status.test.ts
@@ -7,8 +7,7 @@ function event(partial: Partial<AgentEvent> & Pick<AgentEvent, 'type'>): AgentEv
source: 'hook',
providerId: 'claude-code',
projectId: 'p',
- conversationId: 'c',
- sessionId: 'c',
+ sessionId: 's',
timestamp: 1,
payload: {},
...partial,
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
index fd1ebe490..51d88f78f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.test.ts
@@ -1,13 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
-import { type ContextResolver, type ConversationContext, parseHookEvent } from './event-enricher';
+import { type ContextResolver, type AgentHookContext, parseHookEvent } from './event-enricher';
import type { RawHookRequest } from './hook-server';
-const ctx: ConversationContext = {
- conversationId: 'conv-1',
- sessionId: 'conv-1',
+const ctx: AgentHookContext = {
+ sessionId: 'session-1',
projectId: 'proj-1',
providerId: 'claude-code',
- ptyId: 'claude-code::conv-1',
+ ptyId: 'claude-code::session-1',
};
const fixedResolver: ContextResolver = async () => ctx;
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
index a99b4b8a4..b6d1b80dd 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/event-enricher.ts
@@ -4,8 +4,7 @@ import { getPlugin } from '@main/core/providers/plugin-registry';
import type { AgentEvent } from '@shared/core/providers/agentEvents';
import type { RawHookRequest } from './hook-server';
-export type ConversationContext = {
- conversationId: string;
+export type AgentHookContext = {
sessionId: string;
projectId: string;
providerId: string;
@@ -13,19 +12,19 @@ export type ConversationContext = {
};
/**
- * Resolves the conversation context for an incoming hook's `ptyId`. Injected so
+ * Resolves the session context for an incoming hook's `ptyId`. Injected so
* the parser stays free of the database: the local main process supplies a
* DB-backed resolver, the remote sidecar a fixed one for its single agent.
*/
-export type ContextResolver = (ptyId: string) => Promise<ConversationContext | null>;
+export type ContextResolver = (ptyId: string) => Promise<AgentHookContext | null>;
export type ParsedHookEvent =
| { kind: 'status'; event: AgentEvent }
- | { kind: 'session'; ctx: ConversationContext; providerSessionId: string }
- | { kind: 'activity'; ctx: ConversationContext; detail: string }
+ | { kind: 'session'; ctx: AgentHookContext; providerSessionId: string }
+ | { kind: 'activity'; ctx: AgentHookContext; detail: string }
| {
kind: 'switch-room';
- ctx: ConversationContext;
+ ctx: AgentHookContext;
roomId: string;
agentId: string;
roomName: string | null;
@@ -67,7 +66,7 @@ function parseBody(raw: RawHookRequest): Record<string, unknown> {
function canonicalToAgentEvent(
canonical: CanonicalHookEvent & { kind: 'status' },
- ctx: ConversationContext
+ ctx: AgentHookContext
): AgentEvent {
return {
type: canonical.type,
@@ -75,7 +74,6 @@ function canonicalToAgentEvent(
ptyId: ctx.ptyId,
providerId: ctx.providerId,
projectId: ctx.projectId,
- conversationId: ctx.conversationId,
sessionId: ctx.sessionId,
timestamp: Date.now(),
payload: {
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts
index ac54cfaa3..0a384f390 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-config-service.ts
@@ -36,7 +36,7 @@ async function ensureGitIgnoreEntries(sessionPath: string, entries: string[]): P
/**
* Ensures hooks and plugins are installed for the given provider on every
- * conversation spawn. Writes are idempotent (small-file merges), so re-writing
+ * agent spawn. Writes are idempotent (small-file merges), so re-writing
* before every spawn removes the "config got cleaned mid-session" failure mode.
*
* Returns true if hooks are available for this provider (i.e. hook env vars
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
index 29aa435eb..7cf7f893d 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.test.ts
@@ -112,11 +112,11 @@ describe('HookServer /events endpoint', () => {
it('serves the sessions snapshot as JSON and rejects a bad token', async () => {
server = new HookServer(noopLog);
await server.start(async () => {}, {
- sessionsProvider: () => [{ conversationId: 'conv-1', roomId: 'room-1' }],
+ sessionsProvider: () => [{ sessionId: 'session-1', roomId: 'room-1' }],
});
const ok = await get(server.getPort(), '/sessions', server.getToken());
expect(ok.status).toBe(200);
- expect(JSON.parse(ok.body).sessions).toEqual([{ conversationId: 'conv-1', roomId: 'room-1' }]);
+ expect(JSON.parse(ok.body).sessions).toEqual([{ sessionId: 'session-1', roomId: 'room-1' }]);
const forbidden = await get(server.getPort(), '/sessions', 'wrong-token');
expect(forbidden.status).toBe(403);
@@ -165,29 +165,24 @@ describe('HookServer /events endpoint', () => {
const port = server.getPort();
const token = server.getToken();
- const ok = await post(port, '/disconnect', token, JSON.stringify({ conversationId: 'conv-1' }));
+ const ok = await post(port, '/disconnect', token, JSON.stringify({ sessionId: 'session-1' }));
expect(ok.status).toBe(200);
- expect(disconnectHandler).toHaveBeenCalledWith('conv-1', false);
+ expect(disconnectHandler).toHaveBeenCalledWith('session-1', false);
const terminated = await post(
port,
'/disconnect',
token,
- JSON.stringify({ conversationId: 'conv-2', terminated: true })
+ JSON.stringify({ sessionId: 'session-2', terminated: true })
);
expect(terminated.status).toBe(200);
- expect(disconnectHandler).toHaveBeenCalledWith('conv-2', true);
+ expect(disconnectHandler).toHaveBeenCalledWith('session-2', true);
- const forbidden = await post(
- port,
- '/disconnect',
- 'wrong',
- JSON.stringify({ conversationId: 'x' })
- );
+ const forbidden = await post(port, '/disconnect', 'wrong', JSON.stringify({ sessionId: 'x' }));
expect(forbidden.status).toBe(403);
});
- it('rejects /disconnect with a missing conversationId', async () => {
+ it('rejects /disconnect with a missing sessionId', async () => {
const disconnectHandler = vi.fn();
server = new HookServer(noopLog);
await server.start(async () => {}, { disconnectHandler });
@@ -203,7 +198,7 @@ describe('HookServer /events endpoint', () => {
server.getPort(),
'/disconnect',
server.getToken(),
- JSON.stringify({ conversationId: 'conv-1' })
+ JSON.stringify({ sessionId: 'session-1' })
);
expect(res.status).toBe(404);
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
index 2a7015077..1a2015f82 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/hook-server.ts
@@ -90,7 +90,7 @@ export type HookHandler = (raw: RawHookRequest) => Promise<void>;
/** One VM-side session switchdash can reconcile into its UI. */
export interface SidecarSessionInfo {
- conversationId: string;
+ sessionId: string;
/** The Switch room the agent is attending, or null for a session that has
* not joined a room (still discoverable so it can be attached to). */
roomId: string | null;
@@ -106,7 +106,7 @@ export type SidecarSessionsProvider = () => SidecarSessionInfo[] | Promise<Sidec
* and false when a single client is merely stepping away (app quit / teardown)
* and the session should survive for others.
*/
-export type SidecarDisconnectHandler = (conversationId: string, terminated: boolean) => void;
+export type SidecarDisconnectHandler = (sessionId: string, terminated: boolean) => void;
export class HookServer {
private server: http.Server | null = null;
@@ -285,23 +285,23 @@ export class HookServer {
if (body.length > 1_000_000) req.destroy();
});
req.on('end', () => {
- let conversationId = '';
+ let sessionId = '';
let terminated = false;
try {
- const parsed = JSON.parse(body) as { conversationId?: unknown; terminated?: unknown };
- if (typeof parsed.conversationId === 'string') conversationId = parsed.conversationId;
+ const parsed = JSON.parse(body) as { sessionId?: unknown; terminated?: unknown };
+ if (typeof parsed.sessionId === 'string') sessionId = parsed.sessionId;
terminated = parsed.terminated === true;
} catch {
- conversationId = '';
+ sessionId = '';
}
- if (!conversationId) {
- this.log.warn('HookServer: /disconnect missing conversationId');
+ if (!sessionId) {
+ this.log.warn('HookServer: /disconnect missing sessionId');
res.writeHead(400);
res.end();
return;
}
try {
- handler(conversationId, terminated);
+ handler(sessionId, terminated);
} catch (err) {
this.log.warn('HookServer: /disconnect handler error', { error: String(err) });
res.writeHead(500);
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts
index 4fc2c3678..c29bcf9f7 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-hooks/notification.ts
@@ -78,7 +78,6 @@ export async function maybeShowNotification(event: AgentEvent, appFocused: boole
events.emit(notificationFocusSessionChannel, {
projectId: event.projectId,
sessionId: event.sessionId,
- conversationId: event.conversationId,
});
}
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.test.ts
new file mode 100644
index 000000000..121c9b0d7
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Pty } from '@main/core/pty/pty';
+import {
+ AGENT_FRESH_RECOVERY_GRACE_MS,
+ MAX_AGENT_RESUME_ATTEMPTS,
+ AgentRuntimeSupervisor,
+} from './agent-runtime-supervisor';
+
+function fakePty(): Pty {
+ return {
+ write: vi.fn(),
+ resize: vi.fn(),
+ kill: vi.fn(),
+ onData: vi.fn(),
+ onExit: vi.fn(),
+ };
+}
+
+describe('AgentRuntimeSupervisor', () => {
+ it('rejects and kills a spawn that returns after explicit stop invalidated its token', () => {
+ const supervisor = new AgentRuntimeSupervisor();
+ const token = supervisor.beginStart();
+ expect(token).toBeDefined();
+
+ supervisor.stop();
+
+ const pty = fakePty();
+ expect(supervisor.acceptSpawn(token!, pty)).toBe(false);
+ });
+
+ it('falls back to a fresh replacement after one resume exit', () => {
+ const supervisor = new AgentRuntimeSupervisor();
+ const initial = fakePty();
+ const initialToken = supervisor.beginStart({ mode: 'fresh' });
+ expect(supervisor.acceptSpawn(initialToken!, initial)).toBe(true);
+
+ expect(supervisor.handleExit(initial)).toEqual({ kind: 'respawnResume' });
+
+ for (let attempt = 1; attempt <= MAX_AGENT_RESUME_ATTEMPTS; attempt += 1) {
+ const pty = fakePty();
+ const token = supervisor.beginStart({
+ requireDesired: true,
+ mode: 'resume',
+ });
+ expect(supervisor.acceptSpawn(token!, pty)).toBe(true);
+
+ const decision = supervisor.handleExit(pty);
+ if (attempt < MAX_AGENT_RESUME_ATTEMPTS) {
+ expect(decision).toEqual({ kind: 'respawnResume' });
+ } else {
+ expect(decision).toEqual({ kind: 'respawnFresh' });
+ }
+ }
+ });
+
+ it('fails when a fresh recovery exits before the startup grace period', () => {
+ const supervisor = new AgentRuntimeSupervisor();
+ const first = fakePty();
+ const firstToken = supervisor.beginStart({ mode: 'resume' });
+ expect(supervisor.acceptSpawn(firstToken!, first)).toBe(true);
+
+ expect(supervisor.handleExit(first)).toEqual({ kind: 'respawnFresh' });
+
+ const fresh = fakePty();
+ const freshToken = supervisor.beginStart({
+ requireDesired: true,
+ mode: 'fresh',
+ });
+ expect(supervisor.acceptSpawn(freshToken!, fresh)).toBe(true);
+ expect(supervisor.handleExit(fresh)).toEqual({ kind: 'failed' });
+ expect(supervisor.isDesired()).toBe(false);
+ });
+
+ it('resets recovery after a fresh replacement survives the startup grace period', () => {
+ vi.useFakeTimers();
+ try {
+ const supervisor = new AgentRuntimeSupervisor();
+ const first = fakePty();
+ const firstToken = supervisor.beginStart({ mode: 'resume' });
+ expect(supervisor.acceptSpawn(firstToken!, first)).toBe(true);
+
+ expect(supervisor.handleExit(first)).toEqual({ kind: 'respawnFresh' });
+
+ const fresh = fakePty();
+ const freshToken = supervisor.beginStart({
+ requireDesired: true,
+ mode: 'fresh',
+ });
+ expect(supervisor.acceptSpawn(freshToken!, fresh)).toBe(true);
+
+ vi.advanceTimersByTime(AGENT_FRESH_RECOVERY_GRACE_MS);
+ expect(supervisor.handleExit(fresh)).toEqual({ kind: 'respawnResume' });
+
+ const retry = fakePty();
+ const retryToken = supervisor.beginStart({
+ requireDesired: true,
+ mode: 'resume',
+ });
+ expect(supervisor.acceptSpawn(retryToken!, retry)).toBe(true);
+ expect(supervisor.handleExit(retry)).toEqual({ kind: 'respawnFresh' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.ts
similarity index 56%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.ts
index 92ac4e713..7fc0342f4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/agent-runtime-supervisor.ts
@@ -1,28 +1,28 @@
import type { Pty } from '@main/core/pty/pty';
-type ConversationSpawnToken = {
- mode: ConversationSpawnMode;
+type AgentSpawnToken = {
+ mode: AgentSpawnMode;
freshRecovery: boolean;
};
-type ConversationSpawnMode = 'fresh' | 'resume';
+type AgentSpawnMode = 'fresh' | 'resume';
-type ActiveConversationPty = {
+type ActiveAgentPty = {
pty: Pty;
- mode: ConversationSpawnMode;
+ mode: AgentSpawnMode;
freshRecovery: boolean;
};
-type ConversationRuntime = {
+type AgentRuntimeState = {
desired: boolean;
- active?: ActiveConversationPty;
- spawnInFlight?: ConversationSpawnToken;
+ active?: ActiveAgentPty;
+ spawnInFlight?: AgentSpawnToken;
consecutiveResumeExits: number;
recoveryGraceTimer?: ReturnType<typeof setTimeout>;
};
-export const MAX_CONVERSATION_RESUME_ATTEMPTS = 1;
-export const CONVERSATION_FRESH_RECOVERY_GRACE_MS = 5_000;
+export const MAX_AGENT_RESUME_ATTEMPTS = 1;
+export const AGENT_FRESH_RECOVERY_GRACE_MS = 5_000;
export type ExitDecision =
| { kind: 'stale' }
@@ -31,14 +31,19 @@ export type ExitDecision =
| { kind: 'respawnFresh' }
| { kind: 'respawnResume' };
-export class ConversationSessionSupervisor {
- private runtimes = new Map<string, ConversationRuntime>();
+/**
+ * Desired-vs-actual supervisor for the single agent PTY of one session.
+ * Owns the crash-recovery ladder: resume → (a resume exit) → fresh →
+ * (dies within the startup grace) → fail; a fresh replacement that survives
+ * the grace period resets the ladder.
+ */
+export class AgentRuntimeSupervisor {
+ private runtime: AgentRuntimeState | null = null;
beginStart(
- sessionId: string,
- options: { requireDesired?: boolean; mode?: ConversationSpawnMode } = {}
- ): ConversationSpawnToken | undefined {
- const runtime = this.getOrCreateRuntime(sessionId);
+ options: { requireDesired?: boolean; mode?: AgentSpawnMode } = {}
+ ): AgentSpawnToken | undefined {
+ const runtime = this.getOrCreateRuntime();
if (runtime.active || runtime.spawnInFlight) return undefined;
if (options.requireDesired === true && !runtime.desired) return undefined;
@@ -47,14 +52,14 @@ export class ConversationSessionSupervisor {
const token = {
mode,
freshRecovery:
- mode === 'fresh' && runtime.consecutiveResumeExits >= MAX_CONVERSATION_RESUME_ATTEMPTS,
+ mode === 'fresh' && runtime.consecutiveResumeExits >= MAX_AGENT_RESUME_ATTEMPTS,
};
runtime.spawnInFlight = token;
return token;
}
- acceptSpawn(sessionId: string, token: ConversationSpawnToken, pty: Pty): boolean {
- const runtime = this.runtimes.get(sessionId);
+ acceptSpawn(token: AgentSpawnToken, pty: Pty): boolean {
+ const runtime = this.runtime;
if (!runtime || runtime.spawnInFlight !== token) return false;
runtime.spawnInFlight = undefined;
@@ -66,19 +71,19 @@ export class ConversationSessionSupervisor {
freshRecovery: token.freshRecovery,
};
if (token.freshRecovery) {
- this.scheduleRecoveryReset(sessionId, runtime, pty);
+ this.scheduleRecoveryReset(runtime, pty);
}
return true;
}
- failSpawn(sessionId: string, token: ConversationSpawnToken): void {
- const runtime = this.runtimes.get(sessionId);
+ failSpawn(token: AgentSpawnToken): void {
+ const runtime = this.runtime;
if (!runtime || runtime.spawnInFlight !== token) return;
runtime.spawnInFlight = undefined;
}
- stop(sessionId: string): Pty | undefined {
- const runtime = this.runtimes.get(sessionId);
+ stop(): Pty | undefined {
+ const runtime = this.runtime;
if (!runtime) return undefined;
runtime.desired = false;
@@ -91,12 +96,12 @@ export class ConversationSessionSupervisor {
return pty;
}
- isDesired(sessionId: string): boolean {
- return this.runtimes.get(sessionId)?.desired === true;
+ isDesired(): boolean {
+ return this.runtime?.desired === true;
}
- handleExit(sessionId: string, pty: Pty): ExitDecision {
- const runtime = this.runtimes.get(sessionId);
+ handleExit(pty: Pty): ExitDecision {
+ const runtime = this.runtime;
if (!runtime || runtime.active?.pty !== pty) return { kind: 'stale' };
const exitedMode = runtime.active.mode;
@@ -109,14 +114,14 @@ export class ConversationSessionSupervisor {
if (exitedMode === 'resume') {
runtime.consecutiveResumeExits += 1;
- if (runtime.consecutiveResumeExits >= MAX_CONVERSATION_RESUME_ATTEMPTS) {
- runtime.consecutiveResumeExits = MAX_CONVERSATION_RESUME_ATTEMPTS;
+ if (runtime.consecutiveResumeExits >= MAX_AGENT_RESUME_ATTEMPTS) {
+ runtime.consecutiveResumeExits = MAX_AGENT_RESUME_ATTEMPTS;
return { kind: 'respawnFresh' };
}
return { kind: 'respawnResume' };
}
- if (freshRecovery && runtime.consecutiveResumeExits >= MAX_CONVERSATION_RESUME_ATTEMPTS) {
+ if (freshRecovery && runtime.consecutiveResumeExits >= MAX_AGENT_RESUME_ATTEMPTS) {
runtime.desired = false;
runtime.consecutiveResumeExits = 0;
return { kind: 'failed' };
@@ -126,16 +131,16 @@ export class ConversationSessionSupervisor {
return { kind: 'respawnResume' };
}
- forget(sessionId: string): void {
- const runtime = this.runtimes.get(sessionId);
+ forget(): void {
+ const runtime = this.runtime;
if (runtime) this.clearRecoveryGraceTimer(runtime);
- this.runtimes.delete(sessionId);
+ this.runtime = null;
}
- private scheduleRecoveryReset(sessionId: string, runtime: ConversationRuntime, pty: Pty): void {
+ private scheduleRecoveryReset(runtime: AgentRuntimeState, pty: Pty): void {
this.clearRecoveryGraceTimer(runtime);
runtime.recoveryGraceTimer = setTimeout(() => {
- if (this.runtimes.get(sessionId) !== runtime) return;
+ if (this.runtime !== runtime) return;
if (runtime.active?.pty !== pty || !runtime.active.freshRecovery) return;
runtime.active = {
@@ -144,24 +149,22 @@ export class ConversationSessionSupervisor {
};
runtime.consecutiveResumeExits = 0;
runtime.recoveryGraceTimer = undefined;
- }, CONVERSATION_FRESH_RECOVERY_GRACE_MS);
+ }, AGENT_FRESH_RECOVERY_GRACE_MS);
}
- private clearRecoveryGraceTimer(runtime: ConversationRuntime): void {
+ private clearRecoveryGraceTimer(runtime: AgentRuntimeState): void {
if (!runtime.recoveryGraceTimer) return;
clearTimeout(runtime.recoveryGraceTimer);
runtime.recoveryGraceTimer = undefined;
}
- private getOrCreateRuntime(sessionId: string): ConversationRuntime {
- let runtime = this.runtimes.get(sessionId);
- if (!runtime) {
- runtime = {
+ private getOrCreateRuntime(): AgentRuntimeState {
+ if (!this.runtime) {
+ this.runtime = {
desired: false,
consecutiveResumeExits: 0,
};
- this.runtimes.set(sessionId, runtime);
}
- return runtime;
+ return this.runtime;
}
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ensure-agent-sidecar.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
similarity index 97%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/ensure-agent-sidecar.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
index 8640be476..1e6ef485f 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ensure-agent-sidecar.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ensure-agent-sidecar.ts
@@ -11,7 +11,7 @@ import { resolveSidecarBundlePath } from './resolve-sidecar-bundle';
/**
* Deploy + launch (or reattach to) the one agent-scoped remote sidecar and
- * return its hook endpoint. Shared by the SSH conversation provider (which
+ * return its hook endpoint. Shared by the SSH agent runtime (which
* points a UI-started session's hook env at the endpoint) and the auto-session
* setup path (which just needs the sidecar — and its watcher — running). One
* sidecar per remote repo dir, so both callers reattach to the same instance.
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
similarity index 85%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
index bcbe92d40..54a9922e9 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.test.ts
@@ -1,18 +1,24 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Pty, PtyExitInfo } from '@main/core/pty/pty';
-import type { Conversation } from '@shared/core/conversations/conversations';
+import type { Session } from '@shared/core/sessions/sessions';
import { scheduleInitialPromptInjection } from './keystroke-injection';
-function makeConversation(providerId: Conversation['providerId']): Conversation {
+function makeSession(providerId: Session['providerId']): Session {
+ const now = '2024-01-01T00:00:00.000Z';
return {
- id: 'conv-1',
- projectId: 'proj-1',
- sessionId: 'session-1',
+ id: 'session-1',
+ agentId: 'agent-1',
providerId,
title: '',
+ shellId: 'system',
+ status: 'in_progress',
+ statusChangedAt: now,
+ agentSessionId: null,
+ isInitialSession: false,
+ isPinned: false,
autoApprove: false,
- lastInteractedAt: null,
- isInitialConversation: false,
+ createdAt: now,
+ updatedAt: now,
};
}
@@ -57,7 +63,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
@@ -75,7 +81,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
@@ -88,7 +94,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: 'line one\nline two',
isResuming: false,
});
@@ -102,7 +108,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('opencode'),
+ session: makeSession('opencode'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
@@ -116,7 +122,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('grok'),
+ session: makeSession('grok'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
@@ -130,7 +136,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('claude'),
+ session: makeSession('claude'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
@@ -144,7 +150,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: true,
});
@@ -158,7 +164,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: ' ',
isResuming: false,
});
@@ -172,7 +178,7 @@ describe('scheduleInitialPromptInjection', () => {
const { pty, write, emitData, emitExit } = makePty();
scheduleInitialPromptInjection({
pty,
- conversation: makeConversation('hermes'),
+ session: makeSession('hermes'),
initialPrompt: 'Fix the bug',
isResuming: false,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
similarity index 77%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
index e0e1ba530..b5571e8af 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/keystroke-injection.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/keystroke-injection.ts
@@ -1,7 +1,7 @@
import { getPlugin } from '@main/core/providers/plugin-registry';
import type { Pty } from '@main/core/pty/pty';
import { log } from '@main/lib/logger';
-import type { Conversation } from '@shared/core/conversations/conversations';
+import type { Session } from '@shared/core/sessions/sessions';
import { buildPromptInjectionPayload } from '@shared/prompt-injection';
// Inject only after the TUI has produced output and stayed idle for a beat;
@@ -11,14 +11,14 @@ const MAX_WAIT_MS = 15_000;
export function scheduleInitialPromptInjection(args: {
pty: Pty;
- conversation: Conversation;
+ session: Session;
initialPrompt: string | undefined;
isResuming: boolean;
}): void {
if (args.isResuming) return;
if (!args.initialPrompt?.trim()) return;
- const plugin = getPlugin(args.conversation.providerId);
+ const plugin = getPlugin(args.session.providerId);
const promptDelivery = plugin.capabilities.prompt;
if (promptDelivery.kind !== 'keystroke') return;
@@ -26,7 +26,7 @@ export function scheduleInitialPromptInjection(args: {
const submitDelayMs = promptDelivery.submitDelayMs;
const payload = buildPromptInjectionPayload({
- providerId: args.conversation.providerId,
+ providerId: args.session.providerId,
text: args.initialPrompt,
});
@@ -47,9 +47,9 @@ export function scheduleInitialPromptInjection(args: {
}
args.pty.write(`${payload}${submitSequence}`);
} catch (error) {
- log.warn('ConversationProvider: failed to inject initial prompt', {
- providerId: args.conversation.providerId,
- conversationId: args.conversation.id,
+ log.warn('AgentRuntime: failed to inject initial prompt', {
+ providerId: args.session.providerId,
+ sessionId: args.session.id,
error: String(error),
});
}
@@ -70,9 +70,9 @@ export function scheduleInitialPromptInjection(args: {
if (quietTimer) clearTimeout(quietTimer);
clearTimeout(maxWaitTimer);
if (!promptWasInjected) {
- log.warn('ConversationProvider: PTY exited before initial prompt could be injected', {
- providerId: args.conversation.providerId,
- conversationId: args.conversation.id,
+ log.warn('AgentRuntime: PTY exited before initial prompt could be injected', {
+ providerId: args.session.providerId,
+ sessionId: args.session.id,
sawAnyOutput,
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/conversation-provider-respawn.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
similarity index 76%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/conversation-provider-respawn.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
index 6501deeb0..9f78f5246 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/conversation-provider-respawn.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts
@@ -1,12 +1,12 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { CONVERSATION_FRESH_RECOVERY_GRACE_MS } from '@main/core/conversations/conversation-session-supervisor';
+import { AGENT_FRESH_RECOVERY_GRACE_MS } from '@main/core/agent-runtime/agent-runtime-supervisor';
import type { Pty, PtyExitInfo } from '@main/core/pty/pty';
import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';
-import type { Conversation } from '@shared/core/conversations/conversations';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { ptyExitChannel } from '@shared/core/pty/ptyEvents';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
-import { LocalConversationProvider } from './local-conversation';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
+import type { Session } from '@shared/core/sessions/sessions';
+import { LocalAgentRuntime } from './local-agent-runtime';
const spawnLocalPty = vi.hoisted(() => vi.fn());
const buildCommandMock = vi.hoisted(() =>
@@ -154,8 +154,8 @@ const { agentHookService } = await import('@main/core/agent-hooks/agent-hook-ser
const { appSettingsService } = await import('@main/core/settings/settings-service');
type RespawnState = {
- knownSessionIds: Set<string>;
- sessions: Map<string, Pty>;
+ known: boolean;
+ pty: Pty | null;
};
function localProvider({
@@ -173,10 +173,10 @@ function localProvider({
ctx = {} as never,
}: {
tmux?: boolean;
- shellProfile?: ConstructorParameters<typeof LocalConversationProvider>[0]['shellProfile'];
- ctx?: ConstructorParameters<typeof LocalConversationProvider>[0]['ctx'];
+ shellProfile?: ConstructorParameters<typeof LocalAgentRuntime>[0]['shellProfile'];
+ ctx?: ConstructorParameters<typeof LocalAgentRuntime>[0]['ctx'];
} = {}) {
- return new LocalConversationProvider({
+ return new LocalAgentRuntime({
projectId: 'project-1',
sessionId: 'session-1',
sessionPath: '/tmp/session-1',
@@ -186,16 +186,22 @@ function localProvider({
});
}
-function conversation(): Conversation {
+function session(): Session {
+ const now = '2024-01-01T00:00:00.000Z';
return {
- id: 'conversation-1',
- projectId: 'project-1',
- sessionId: 'session-1',
+ id: 'session-1',
+ agentId: 'agent-1',
providerId: 'codex',
- title: 'Conversation 1',
- lastInteractedAt: null,
+ title: 'Session 1',
+ shellId: 'system',
+ status: 'in_progress',
+ statusChangedAt: now,
+ agentSessionId: null,
providerSessionId: 'provider-session-1',
- isInitialConversation: false,
+ isInitialSession: false,
+ isPinned: false,
+ createdAt: now,
+ updatedAt: now,
};
}
@@ -222,7 +228,7 @@ function mockSettings(): void {
});
}
-describe('conversation provider respawn state', () => {
+describe('local agent runtime respawn state', () => {
beforeEach(() => {
vi.useRealTimers();
spawnLocalPty.mockReset();
@@ -236,7 +242,7 @@ describe('conversation provider respawn state', () => {
vi.mocked(events.emit).mockClear();
vi.mocked(agentHookService.getPort).mockReturnValue(0);
vi.mocked(agentHookService.getToken).mockReturnValue('token');
- ptySessionRegistry.unregister('project-1:session-1:conversation-1');
+ ptySessionRegistry.unregister('project-1:session-1');
});
it('passes global editor variables to local agent sessions', async () => {
@@ -248,7 +254,7 @@ describe('conversation provider respawn state', () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
- await localProvider().startSession(conversation());
+ await localProvider().start(session());
const request = spawnLocalPty.mock.calls[0][0] as { env: Record<string, string> };
expect(request.env.EDITOR).toBe('zed');
@@ -268,21 +274,20 @@ describe('conversation provider respawn state', () => {
});
it('uses the injected shell profile for local agent sessions', async () => {
- const shellProfile: ConstructorParameters<typeof LocalConversationProvider>[0]['shellProfile'] =
- {
- id: 'bash',
- resolvedShellId: 'bash',
- resolvedFromSystem: false,
- executable: 'bash',
- available: true,
- family: 'posix',
- interactiveArgs: ['-il'],
- commandArgs: ['-lc'],
- };
+ const shellProfile: ConstructorParameters<typeof LocalAgentRuntime>[0]['shellProfile'] = {
+ id: 'bash',
+ resolvedShellId: 'bash',
+ resolvedFromSystem: false,
+ executable: 'bash',
+ available: true,
+ family: 'posix',
+ interactiveArgs: ['-il'],
+ commandArgs: ['-lc'],
+ };
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
- await localProvider({ shellProfile }).startSession(conversation());
+ await localProvider({ shellProfile }).start(session());
expect(spawnLocalPty).toHaveBeenCalledWith(
expect.objectContaining({
@@ -293,21 +298,20 @@ describe('conversation provider respawn state', () => {
});
it('sets SHELL to the injected POSIX shell for local agent sessions', async () => {
- const shellProfile: ConstructorParameters<typeof LocalConversationProvider>[0]['shellProfile'] =
- {
- id: 'bash',
- resolvedShellId: 'bash',
- resolvedFromSystem: false,
- executable: '/bin/bash',
- available: true,
- family: 'posix',
- interactiveArgs: ['-il'],
- commandArgs: ['-lc'],
- };
+ const shellProfile: ConstructorParameters<typeof LocalAgentRuntime>[0]['shellProfile'] = {
+ id: 'bash',
+ resolvedShellId: 'bash',
+ resolvedFromSystem: false,
+ executable: '/bin/bash',
+ available: true,
+ family: 'posix',
+ interactiveArgs: ['-il'],
+ commandArgs: ['-lc'],
+ };
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
- await localProvider({ shellProfile }).startSession(conversation());
+ await localProvider({ shellProfile }).start(session());
expect(spawnLocalPty).toHaveBeenCalledWith(
expect.objectContaining({
@@ -319,9 +323,9 @@ describe('conversation provider respawn state', () => {
it('prepares OpenCode hooks when hook config is available', async () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
- const item = { ...conversation(), providerId: 'opencode' as const };
+ const item = { ...session(), providerId: 'opencode' as const };
- await localProvider().startSession(item);
+ await localProvider().start(item);
expect(installPluginMock).toHaveBeenCalledWith(expect.anything(), {
kind: 'workspace',
@@ -329,7 +333,7 @@ describe('conversation provider respawn state', () => {
});
});
- it('starts a local conversation fresh after a resumed session exits', async () => {
+ it('starts a local agent fresh after a resumed session exits', async () => {
vi.useFakeTimers();
try {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
@@ -341,9 +345,9 @@ describe('conversation provider respawn state', () => {
const provider = localProvider();
const size = { cols: 100, rows: 40 };
const initialPrompt = 'continue';
- const item = conversation();
+ const item = session();
- await provider.startSession(item, size, true, initialPrompt);
+ await provider.start(item, size, true, initialPrompt);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -366,9 +370,9 @@ describe('conversation provider respawn state', () => {
return fakePty(handlers);
});
const provider = localProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item, undefined, true);
+ await provider.start(item, undefined, true);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
for (const handler of exitHandlers[1] ?? []) handler({ exitCode: 0 });
@@ -377,10 +381,7 @@ describe('conversation provider respawn state', () => {
expect(spawnLocalPty).toHaveBeenCalledTimes(2);
expect(events.emit).toHaveBeenCalledWith(
agentSessionExitedChannel,
- expect.objectContaining({
- conversationId: item.id,
- sessionId: item.sessionId,
- })
+ expect.objectContaining({ sessionId: item.id })
);
} finally {
vi.useRealTimers();
@@ -397,12 +398,12 @@ describe('conversation provider respawn state', () => {
return fakePty(handlers);
});
const provider = localProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item, undefined, true);
+ await provider.start(item, undefined, true);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
- await vi.advanceTimersByTimeAsync(CONVERSATION_FRESH_RECOVERY_GRACE_MS);
+ await vi.advanceTimersByTimeAsync(AGENT_FRESH_RECOVERY_GRACE_MS);
for (const handler of exitHandlers[1] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -415,22 +416,22 @@ describe('conversation provider respawn state', () => {
}
});
- it('emits PTY exit when a local conversation unregisters before the registry exit handler runs', async () => {
+ it('emits PTY exit when a local agent unregisters before the registry exit handler runs', async () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
const exitInfo = { exitCode: 0 };
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
const provider = localProvider();
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
+ const sessionId = makeAgentPtySessionId('project-1', item.id);
- await provider.startSession(item);
+ await provider.start(item);
vi.mocked(events.emit).mockClear();
for (const handler of exitHandlers) handler(exitInfo);
expect(events.emit).toHaveBeenCalledWith(ptyExitChannel, exitInfo, sessionId);
});
- it('uses the last observed terminal size when replacing a local conversation', async () => {
+ it('uses the last observed terminal size when replacing a local agent', async () => {
vi.useFakeTimers();
try {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
@@ -440,10 +441,10 @@ describe('conversation provider respawn state', () => {
return fakePty(handlers);
});
const provider = localProvider();
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
+ const sessionId = makeAgentPtySessionId('project-1', item.id);
- await provider.startSession(item, { cols: 100, rows: 40 }, true);
+ await provider.start(item, { cols: 100, rows: 40 }, true);
ptySessionRegistry.resize(sessionId, 68, 42);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -457,7 +458,7 @@ describe('conversation provider respawn state', () => {
}
});
- it('starts a local conversation fresh after one resume replacement exits', async () => {
+ it('starts a local agent fresh after one resume replacement exits', async () => {
vi.useFakeTimers();
try {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
@@ -467,9 +468,9 @@ describe('conversation provider respawn state', () => {
return fakePty(handlers);
});
const provider = localProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
for (let index = 0; index < 2; index += 1) {
for (const handler of exitHandlers[index] ?? []) handler({ exitCode: 1 });
@@ -495,9 +496,9 @@ describe('conversation provider respawn state', () => {
throw new Error('spawn failed');
});
const provider = localProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
for (const handler of exitHandlers) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -513,11 +514,11 @@ describe('conversation provider respawn state', () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
const provider = localProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
for (const handler of exitHandlers) handler({ exitCode: 0 });
- await provider.stopSession(item.id);
+ await provider.stop();
await vi.advanceTimersByTimeAsync(500);
expect(spawnLocalPty).toHaveBeenCalledTimes(1);
@@ -532,9 +533,9 @@ describe('conversation provider respawn state', () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
const provider = localProvider({ tmux: true });
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
vi.mocked(events.emit).mockClear();
for (const handler of exitHandlers) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -542,17 +543,14 @@ describe('conversation provider respawn state', () => {
expect(spawnLocalPty).toHaveBeenCalledTimes(1);
expect(events.emit).toHaveBeenCalledWith(
agentSessionExitedChannel,
- expect.objectContaining({
- conversationId: item.id,
- sessionId: item.sessionId,
- })
+ expect.objectContaining({ sessionId: item.id })
);
} finally {
vi.useRealTimers();
}
});
- it('detaches local tmux conversations without killing the tmux session', async () => {
+ it('detaches local tmux agents without killing the tmux session', async () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
const pty = fakePty(exitHandlers);
spawnLocalPty.mockReturnValue(pty);
@@ -560,59 +558,56 @@ describe('conversation provider respawn state', () => {
exec: vi.fn(async () => ({ stdout: '', stderr: '' })),
};
const provider = localProvider({ tmux: true, ctx: ctx as never });
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
vi.mocked(events.emit).mockClear();
- await provider.detachSession(item.id);
+ await provider.dehydrate();
for (const handler of exitHandlers) handler({ exitCode: 0 });
expect(pty.kill).toHaveBeenCalledTimes(1);
expect(ctx.exec).not.toHaveBeenCalled();
expect(events.emit).not.toHaveBeenCalledWith(agentSessionExitedChannel, expect.anything());
- expect((provider as unknown as RespawnState).knownSessionIds.has(sessionId)).toBe(true);
+ expect((provider as unknown as RespawnState).known).toBe(true);
});
- it('kills tmux when explicitly stopping a detached local conversation', async () => {
+ it('kills tmux when explicitly stopping a detached local agent', async () => {
const exitHandlers: Array<(info: PtyExitInfo) => void> = [];
spawnLocalPty.mockReturnValue(fakePty(exitHandlers));
const ctx = {
exec: vi.fn(async () => ({ stdout: '', stderr: '' })),
};
const provider = localProvider({ tmux: true, ctx: ctx as never });
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
- await provider.startSession(item);
- await provider.detachSession(item.id);
- await provider.stopSession(item.id);
+ await provider.start(item);
+ await provider.dehydrate();
+ await provider.stop();
expect(ctx.exec).toHaveBeenCalledWith('tmux', [
'kill-session',
'-t',
- expect.stringContaining(Buffer.from(`conv-${item.id}`, 'utf8').toString('base64url')),
+ expect.stringContaining(Buffer.from(`session-${item.id}`, 'utf8').toString('base64url')),
]);
- expect((provider as unknown as RespawnState).knownSessionIds.has(sessionId)).toBe(false);
+ expect((provider as unknown as RespawnState).known).toBe(false);
});
- it('ignores stale local attach exits after a tmux conversation is rehydrated', async () => {
+ it('ignores stale local attach exits after a tmux agent is rehydrated', async () => {
const firstExitHandlers: Array<(info: PtyExitInfo) => void> = [];
const secondExitHandlers: Array<(info: PtyExitInfo) => void> = [];
const firstPty = fakePty(firstExitHandlers);
const secondPty = fakePty(secondExitHandlers);
spawnLocalPty.mockReturnValueOnce(firstPty).mockReturnValueOnce(secondPty);
const provider = localProvider({ tmux: true });
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
- await provider.startSession(item);
- await provider.detachSession(item.id);
- await provider.startSession(item);
+ await provider.start(item);
+ await provider.dehydrate();
+ await provider.start(item);
vi.mocked(events.emit).mockClear();
for (const handler of firstExitHandlers) handler({ exitCode: 0 });
- expect((provider as unknown as RespawnState).sessions.get(sessionId)).toBe(secondPty);
+ expect((provider as unknown as RespawnState).pty).toBe(secondPty);
expect(events.emit).not.toHaveBeenCalledWith(agentSessionExitedChannel, expect.anything());
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/local-conversation.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
similarity index 54%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/local-conversation.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
index 9b8ab3a2a..e5e937eab 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/local-conversation.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts
@@ -2,10 +2,9 @@ import { homedir } from 'node:os';
import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';
import { ensureHooksInstalled } from '@main/core/agent-hooks/hook-config-service';
import { workspaceTrustService } from '@main/core/agent-hooks/workspace-trust-service';
-import { conversationEvents } from '@main/core/conversations/conversation-events';
-import { ConversationSessionSupervisor } from '@main/core/conversations/conversation-session-supervisor';
-import { resolveAgentSessionCommandArgs } from '@main/core/conversations/resolve-agent-session-command';
-import type { ConversationProvider } from '@main/core/conversations/types';
+import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';
+import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';
+import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import { localDependencyManager } from '@main/core/dependencies/dependency-managers';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
@@ -18,16 +17,17 @@ import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';
import { logLocalPtySpawnWarnings, resolveLocalPtySpawn } from '@main/core/pty/pty-spawn-platform';
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 { switchNotificationPoller } from '@main/core/switch-rooms/switch-notification-poller';
import { switchRoomService } from '@main/core/switch-rooms/switch-room-service';
import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
import { events } from '@main/lib/events';
import { log } from '@main/lib/logger';
-import type { Conversation } from '@shared/core/conversations/conversations';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makePtyId } from '@shared/core/pty/ptyId';
-import { makePtySessionId, parsePtySessionId } from '@shared/core/pty/ptySessionId';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
+import type { Session } from '@shared/core/sessions/sessions';
import { scheduleInitialPromptInjection } from './keystroke-injection';
import { resolveAgentExecutable } from './resolve-agent-executable';
@@ -40,10 +40,10 @@ function parseExtraArgs(value: string | undefined): string[] {
return value.trim().split(/\s+/);
}
-export class LocalConversationProvider implements ConversationProvider {
- private sessions = new Map<string, Pty>();
- private knownSessionIds = new Set<string>();
- private supervisor = new ConversationSessionSupervisor();
+export class LocalAgentRuntime implements AgentRuntimeProvider {
+ private pty: Pty | null = null;
+ private known = false;
+ private supervisor = new AgentRuntimeSupervisor();
private readonly projectId: string;
private readonly sessionPath: string;
private readonly sessionId: string;
@@ -81,8 +81,13 @@ export class LocalConversationProvider implements ConversationProvider {
this.sessionEnvVars = sessionEnvVars;
}
- async startSession(
- conversation: Conversation,
+ /** The registry key of this session's agent PTY (session id == session id). */
+ private get ptySessionId(): string {
+ return makeAgentPtySessionId(this.projectId, this.sessionId);
+ }
+
+ async start(
+ session: Session,
initialSize: { cols: number; rows: number } = {
cols: DEFAULT_COLS,
rows: DEFAULT_ROWS,
@@ -90,25 +95,21 @@ export class LocalConversationProvider implements ConversationProvider {
isResuming: boolean = false,
initialPrompt?: string
): Promise<void> {
- return this.startSessionInternal(conversation, initialSize, isResuming, initialPrompt, false);
+ return this.startInternal(session, initialSize, isResuming, initialPrompt, false);
}
- private async startSessionInternal(
- conversation: Conversation,
+ private async startInternal(
+ session: Session,
initialSize: { cols: number; rows: number },
isResuming: boolean,
initialPrompt: string | undefined,
requireDesired: boolean
): Promise<void> {
- const sessionId = makePtySessionId(
- conversation.projectId,
- conversation.sessionId,
- conversation.id
- );
- this.knownSessionIds.add(sessionId);
+ const ptySessionId = this.ptySessionId;
+ this.known = true;
- const spawnSize = ptySessionRegistry.getLastSize(sessionId) ?? initialSize;
- const spawnToken = this.supervisor.beginStart(sessionId, {
+ const spawnSize = ptySessionRegistry.getLastSize(ptySessionId) ?? initialSize;
+ const spawnToken = this.supervisor.beginStart({
requireDesired,
mode: isResuming ? 'resume' : 'fresh',
});
@@ -116,26 +117,25 @@ export class LocalConversationProvider implements ConversationProvider {
try {
await workspaceTrustService.maybeAutoTrustLocal({
- providerId: conversation.providerId,
+ providerId: session.providerId,
cwd: this.sessionPath,
homedir: homedir(),
- force: conversation.autoApprove === true,
+ force: session.autoApprove === true,
});
await ensureHooksInstalled({
- providerId: conversation.providerId,
+ providerId: session.providerId,
sessionPath: this.sessionPath,
});
- const providerConfig = await providerOverrideSettings.getItem(conversation.providerId);
- const agentSession = resolveAgentSessionCommandArgs(conversation, isResuming);
- const plugin = getPlugin(conversation.providerId);
+ const providerConfig = await providerOverrideSettings.getItem(session.providerId);
+ const agentSession = resolveAgentSessionCommandArgs(session, isResuming);
+ const plugin = getPlugin(session.providerId);
const subagentsBehavior = plugin.behavior.subagents;
- const binaryName =
- plugin.capabilities.hostDependency.binaryNames[0] ?? conversation.providerId;
- const cachedStatePath = localDependencyManager.get(conversation.providerId as never)?.path;
+ const binaryName = plugin.capabilities.hostDependency.binaryNames[0] ?? session.providerId;
+ const cachedStatePath = localDependencyManager.get(session.providerId as never)?.path;
const executableCli = await resolveAgentExecutable({
- providerId: conversation.providerId,
+ providerId: session.providerId,
binaryName,
ctx: this.ctx,
hostDependencyStore,
@@ -144,17 +144,17 @@ export class LocalConversationProvider implements ConversationProvider {
const extraArgs = [
...parseExtraArgs(providerConfig?.extraArgs),
- ...(conversation.subagentName && subagentsBehavior
- ? subagentsBehavior.launchArgs(this.sessionPath, conversation.subagentName)
+ ...(session.subagentName && subagentsBehavior
+ ? subagentsBehavior.launchArgs(this.sessionPath, session.subagentName)
: []),
];
const agentCommand = plugin.behavior.prompt!.buildCommand({
cli: executableCli,
extraArgs,
- autoApprove: conversation.autoApprove ?? false,
+ autoApprove: session.autoApprove ?? false,
initialPrompt: agentSession.isResuming ? undefined : initialPrompt,
sessionId: agentSession.sessionId,
- providerSessionId: conversation.providerSessionId ?? undefined,
+ providerSessionId: session.providerSessionId ?? undefined,
isResuming: agentSession.isResuming,
model: '',
});
@@ -162,7 +162,7 @@ export class LocalConversationProvider implements ConversationProvider {
const customEnv = providerConfig?.env ?? {};
const providerVars: Record<string, string> = { ...agentCommand.env, ...customEnv };
- const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(conversation.id) : undefined;
+ const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;
const resolved = resolveLocalPtySpawn({
platform: process.platform,
@@ -177,12 +177,11 @@ export class LocalConversationProvider implements ConversationProvider {
},
});
- logLocalPtySpawnWarnings('LocalConversationProvider', resolved.warnings, {
- conversationId: conversation.id,
- sessionId,
+ logLocalPtySpawnWarnings('LocalAgentRuntime', resolved.warnings, {
+ sessionId: ptySessionId,
});
- const ptyId = makePtyId(conversation.providerId, conversation.id);
+ const ptyId = makePtyId(session.providerId, this.sessionId);
const port = agentHookService.getPort();
const token = agentHookService.getToken();
const colorEnv = await getTerminalColorEnv();
@@ -191,14 +190,14 @@ export class LocalConversationProvider implements ConversationProvider {
// every settings file and reach the spawned MCP server, so inject them
// last (highest precedence).
const subagentVars =
- conversation.subagentName && subagentsBehavior
+ session.subagentName && subagentsBehavior
? await subagentsBehavior.readLaunchEnv(
createPluginFs(this.sessionPath),
- conversation.subagentName
+ session.subagentName
)
: {};
const pty = spawnLocalPty({
- id: sessionId,
+ id: ptySessionId,
command: resolved.command,
args: resolved.args,
cwd: resolved.cwd,
@@ -217,58 +216,52 @@ export class LocalConversationProvider implements ConversationProvider {
});
pty.onExit((info) => {
- const decision = this.supervisor.handleExit(sessionId, pty);
+ const decision = this.supervisor.handleExit(pty);
if (decision.kind === 'stale') return;
- const replacementSize = ptySessionRegistry.getLastSize(sessionId) ?? spawnSize;
+ const replacementSize = ptySessionRegistry.getLastSize(ptySessionId) ?? spawnSize;
- ptySessionRegistry.unregister(sessionId, { pty, exitInfo: info });
- this.sessions.delete(sessionId);
+ ptySessionRegistry.unregister(ptySessionId, { pty, exitInfo: info });
+ this.pty = null;
if (decision.kind === 'stopped') return;
- events.emit(agentSessionExitedChannel, {
- conversationId: conversation.id,
- sessionId: conversation.sessionId,
- });
+ events.emit(agentSessionExitedChannel, { sessionId: this.sessionId });
// In-process counterpart for main-process consumers — `events` only
- // reaches the renderer (see conversation-events).
- conversationEvents._emit('conversation:session-exited', {
- conversationId: conversation.id,
- sessionId: conversation.sessionId,
- });
+ // reaches the renderer (see session-hooks).
+ sessionHooks._emit('session:agent-exited', { sessionId: this.sessionId });
if (this.tmux) {
return;
}
- if (this.supervisor.isDesired(sessionId)) {
+ if (this.supervisor.isDesired()) {
this.scheduleReplacement({
- conversation,
+ session,
initialSize: replacementSize,
isResuming: decision.kind === 'respawnResume',
});
}
});
- if (!this.supervisor.acceptSpawn(sessionId, spawnToken, pty)) {
+ if (!this.supervisor.acceptSpawn(spawnToken, pty)) {
try {
pty.kill();
} catch {}
- if (ptySessionRegistry.get(sessionId) === pty) {
- ptySessionRegistry.unregister(sessionId);
+ if (ptySessionRegistry.get(ptySessionId) === pty) {
+ ptySessionRegistry.unregister(ptySessionId);
}
return;
}
- ptySessionRegistry.register(sessionId, pty, {
+ ptySessionRegistry.register(ptySessionId, pty, {
metadata: {
- providerId: conversation.providerId,
- title: conversation.title,
+ providerId: session.providerId,
+ title: session.title,
},
});
- this.sessions.set(sessionId, pty);
+ this.pty = pty;
scheduleInitialPromptInjection({
pty,
- conversation,
+ session,
initialPrompt,
isResuming: agentSession.isResuming,
});
@@ -277,127 +270,100 @@ export class LocalConversationProvider implements ConversationProvider {
// live tool call, so a resumed session would otherwise go silent.
void switchRoomService
.restorePoller({
- conversationId: conversation.id,
- projectId: conversation.projectId,
- providerId: conversation.providerId,
+ sessionId: this.sessionId,
+ projectId: this.projectId,
+ providerId: session.providerId,
ptyId,
})
.catch((error) => {
- log.warn('LocalConversationProvider: failed to restore Switch room poller', {
- conversationId: conversation.id,
+ log.warn('LocalAgentRuntime: failed to restore Switch room poller', {
+ sessionId: this.sessionId,
error: String(error),
});
});
} catch (error) {
- this.supervisor.failSpawn(sessionId, spawnToken);
+ this.supervisor.failSpawn(spawnToken);
throw error;
}
}
- private detachPty(sessionId: string): void {
- const pty = this.supervisor.stop(sessionId) ?? this.sessions.get(sessionId);
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
+ private detachPty(): void {
+ const pty = this.supervisor.stop() ?? this.pty;
+ this.pty = null;
+ ptySessionRegistry.unregister(this.ptySessionId);
if (pty) {
try {
pty.kill();
} catch (e) {
- log.warn('LocalAgentProvider: error killing PTY', {
- sessionId,
+ log.warn('LocalAgentRuntime: error killing PTY', {
+ sessionId: this.sessionId,
error: String(e),
});
}
}
}
- async detachSession(conversationId: string): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.sessionId, conversationId);
- this.detachPty(sessionId);
- switchNotificationPoller.disconnect(conversationId);
- switchRoomService.clearSession(conversationId);
+ async dehydrate(): Promise<void> {
+ this.detachPty();
+ switchNotificationPoller.disconnect(this.sessionId);
+ switchRoomService.clearSession(this.sessionId);
if (!this.tmux) {
- this.knownSessionIds.delete(sessionId);
- this.supervisor.forget(sessionId);
+ this.known = false;
+ this.supervisor.forget();
}
}
- async stopSession(conversationId: string): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.sessionId, conversationId);
- switchNotificationPoller.disconnect(conversationId);
- switchRoomService.clearSession(conversationId);
- this.knownSessionIds.delete(sessionId);
- const pty = this.supervisor.stop(sessionId) ?? this.sessions.get(sessionId);
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
- if (pty) {
- try {
- pty.kill();
- } catch (e) {
- log.warn('LocalAgentProvider: error killing PTY', {
- sessionId,
- error: String(e),
- });
- }
- }
+ async stop(): Promise<void> {
+ switchNotificationPoller.disconnect(this.sessionId);
+ switchRoomService.clearSession(this.sessionId);
+ this.known = false;
+ this.detachPty();
if (this.tmux) {
- await killTmuxSession(this.ctx, makeAgentTmuxSessionName(conversationId));
+ await killTmuxSession(this.ctx, makeAgentTmuxSessionName(this.sessionId));
}
- this.supervisor.forget(sessionId);
+ this.supervisor.forget();
}
- async destroyAll(): Promise<void> {
- const sessionIds = Array.from(this.knownSessionIds);
- await this.detachAll();
- if (this.tmux) {
- await Promise.all(
- sessionIds.map((id) => {
- const conversationId = parsePtySessionId(id)?.leafId;
- return conversationId
- ? killTmuxSession(this.ctx, makeAgentTmuxSessionName(conversationId))
- : Promise.resolve();
- })
- );
+ async destroy(): Promise<void> {
+ const wasKnown = this.known;
+ await this.detach();
+ if (this.tmux && wasKnown) {
+ await killTmuxSession(this.ctx, makeAgentTmuxSessionName(this.sessionId));
}
- for (const sessionId of sessionIds) {
- this.supervisor.forget(sessionId);
- }
- this.knownSessionIds.clear();
+ this.supervisor.forget();
+ this.known = false;
}
- async detachAll(): Promise<void> {
- for (const [sessionId, pty] of this.sessions) {
- this.supervisor.stop(sessionId);
- const conversationId = parsePtySessionId(sessionId)?.leafId;
- if (conversationId) {
- switchNotificationPoller.disconnect(conversationId);
- switchRoomService.clearSession(conversationId);
- }
+ async detach(): Promise<void> {
+ if (this.pty) {
+ const pty = this.pty;
+ this.supervisor.stop();
+ switchNotificationPoller.disconnect(this.sessionId);
+ switchRoomService.clearSession(this.sessionId);
try {
pty.kill();
} catch {}
- ptySessionRegistry.unregister(sessionId);
+ ptySessionRegistry.unregister(this.ptySessionId);
+ this.pty = null;
}
- this.sessions.clear();
}
private scheduleReplacement({
- conversation,
+ session,
initialSize,
isResuming,
}: {
- conversation: Conversation;
+ session: Session;
initialSize: { cols: number; rows: number };
isResuming: boolean;
}): void {
setTimeout(() => {
- this.startSessionInternal(conversation, initialSize, isResuming, undefined, true).catch(
- (e) => {
- log.error('LocalConversationProvider: replacement failed', {
- conversationId: conversation.id,
- error: String(e),
- });
- }
- );
+ this.startInternal(session, initialSize, isResuming, undefined, true).catch((e) => {
+ log.error('LocalAgentRuntime: replacement failed', {
+ sessionId: this.sessionId,
+ error: String(e),
+ });
+ });
}, RESPAWN_DELAY_MS);
}
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-hook-event-relay.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-hook-event-relay.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.test.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-hook-event-relay.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-hook-event-relay.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-hook-event-relay.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-plugin-fs.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.test.ts
similarity index 97%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-plugin-fs.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.test.ts
index 4f1b8fcab..818ecfc45 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-plugin-fs.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.test.ts
@@ -10,7 +10,7 @@ function adapter(stub: Partial<FileSystemProvider>) {
return createRemotePluginFs(stub as unknown as FileSystemProvider);
}
-describe('createRemotePluginFs (conversations)', () => {
+describe('createRemotePluginFs (agent runtime)', () => {
it('read returns the file content', async () => {
const read = vi.fn(async () => ({ content: 'hello', truncated: false, totalSize: 5 }));
const fs = adapter({ read });
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-plugin-fs.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-plugin-fs.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-plugin-fs.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
similarity index 99%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
index 44e1791ad..1ff45ebcc 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.test.ts
@@ -156,7 +156,6 @@ describe('RemoteSidecarLauncher', () => {
const inner = launch!.args[6];
expect(inner).toContain("SWITCHDASH_SIDECAR_REPO_DIR='/home/dev/repo'");
expect(inner).toContain("SWITCHDASH_SIDECAR_PROJECT_ID='proj-1'");
- expect(inner).not.toContain('SWITCHDASH_SIDECAR_CONVERSATION_ID');
expect(inner).not.toContain('SWITCHDASH_SIDECAR_TMUX_TARGET');
expect(inner).toContain('.switchdash/sidecar.mjs');
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
similarity index 99%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
index 661f055d3..ea70a6254 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/remote-sidecar-launcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/remote-sidecar-launcher.ts
@@ -102,7 +102,7 @@ const defaultSleep = (ms: number): Promise<void> =>
/**
* Deterministic, agent-scoped tmux session name for the sidecar, derived from
- * the remote repo dir so every caller (the SSH conversation provider and the
+ * the remote repo dir so every caller (the SSH agent runtime and the
* auto-session setup path) computes the same name and reattaches to the one
* shared sidecar. Deliberately does NOT end in `-sidecar` so the legacy
* per-session `reapOrphanedSidecars` never mistakes it for an orphan.
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-agent-executable.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-agent-executable.test.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-agent-executable.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-agent-executable.test.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-agent-executable.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-agent-executable.ts
similarity index 97%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-agent-executable.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-agent-executable.ts
index cfd8548ef..fce6aceb6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-agent-executable.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-agent-executable.ts
@@ -19,7 +19,7 @@ function cacheKey(providerId: string, connectionId?: string): string {
}
/**
- * Resolve the absolute path of the agent binary to use for conversation spawns.
+ * Resolve the absolute path of the agent binary to use for agent spawns.
*
* Resolution order:
* 1. selection.kind === 'pinned': use selection.realpath if it exists on disk; otherwise fall through.
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-sidecar-bundle.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-sidecar-bundle.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/resolve-sidecar-bundle.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/resolve-sidecar-bundle.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/sidecar-http.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.test.ts
similarity index 97%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/sidecar-http.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.test.ts
index b33e1dc47..e51686627 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/sidecar-http.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.test.ts
@@ -86,12 +86,12 @@ describe('httpPostJsonOverChannel', () => {
port: 1234,
token: 'tok',
path: '/disconnect',
- body: { conversationId: 'conv-1' },
+ body: { sessionId: 'session-1' },
timeoutMs: 1000,
});
expect(channel.written).toContain('POST /disconnect HTTP/1.1');
expect(channel.written).toContain('x-switchdash-token: tok');
- expect(channel.written).toContain('{"conversationId":"conv-1"}');
+ expect(channel.written).toContain('{"sessionId":"session-1"}');
channel.emit('data', Buffer.from('HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n'));
await expect(promise).resolves.toBeUndefined();
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/sidecar-http.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts
similarity index 100%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/sidecar-http.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/sidecar-http.ts
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
similarity index 81%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
index e7274407c..c16cd2096 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts
@@ -2,10 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Pty, PtyExitInfo } from '@main/core/pty/pty';
import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';
import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';
-import type { Conversation } from '@shared/core/conversations/conversations';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
-import { SshConversationProvider } from './ssh-conversation';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
+import type { Session } from '@shared/core/sessions/sessions';
+import { SshAgentRuntime } from './ssh-agent-runtime';
const openSsh2Pty = vi.hoisted(() => vi.fn());
const buildCommandMock = vi.hoisted(() =>
@@ -67,10 +67,6 @@ vi.mock('./keystroke-injection', () => ({
scheduleInitialPromptInjection: vi.fn(),
}));
-vi.mock('@main/core/conversations/conversation-events', () => ({
- conversationEvents: { _emit: vi.fn() },
-}));
-
vi.mock('@main/lib/events', () => ({
events: { emit: vi.fn(), on: vi.fn(() => () => {}) },
}));
@@ -113,8 +109,8 @@ function emitReconnected(connectionId: string): void {
const { events } = await import('@main/lib/events');
type ProviderState = {
- knownSessionIds: Set<string>;
- sessions: Map<string, Pty>;
+ known: boolean;
+ pty: Pty | null;
};
function makeProxy(overrides: Partial<SshClientProxy> = {}): SshClientProxy {
@@ -129,7 +125,7 @@ function makeProxy(overrides: Partial<SshClientProxy> = {}): SshClientProxy {
} as unknown as SshClientProxy;
}
-function makeCtx(): ConstructorParameters<typeof SshConversationProvider>[0]['ctx'] {
+function makeCtx(): ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'] {
return { exec: vi.fn(async () => ({ stdout: '', stderr: '' })) } as never;
}
@@ -140,9 +136,9 @@ function sshProvider({
}: {
proxy?: SshClientProxy;
tmux?: boolean;
- ctx?: ConstructorParameters<typeof SshConversationProvider>[0]['ctx'];
+ ctx?: ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'];
} = {}) {
- return new SshConversationProvider({
+ return new SshAgentRuntime({
projectId: 'project-1',
sessionId: 'session-1',
sessionPath: '/repo',
@@ -154,16 +150,22 @@ function sshProvider({
});
}
-function conversation(): Conversation {
+function session(): Session {
+ const now = '2024-01-01T00:00:00.000Z';
return {
- id: 'conversation-1',
- projectId: 'project-1',
- sessionId: 'session-1',
+ id: 'session-1',
+ agentId: 'agent-1',
providerId: 'codex',
- title: 'Conversation 1',
- lastInteractedAt: null,
+ title: 'Session 1',
+ shellId: 'system',
+ status: 'in_progress',
+ statusChangedAt: now,
+ agentSessionId: null,
providerSessionId: 'provider-session-1',
- isInitialConversation: false,
+ isInitialSession: false,
+ isPinned: false,
+ createdAt: now,
+ updatedAt: now,
};
}
@@ -185,7 +187,7 @@ function mockSpawn(exitHandlers: Array<Array<(info: PtyExitInfo) => void>>): voi
});
}
-describe('SshConversationProvider', () => {
+describe('SshAgentRuntime', () => {
beforeEach(() => {
vi.useRealTimers();
openSsh2Pty.mockReset();
@@ -197,16 +199,16 @@ describe('SshConversationProvider', () => {
httpPostJsonOverChannel.mockClear();
vi.mocked(events.emit).mockClear();
connectionListeners.length = 0;
- ptySessionRegistry.unregister('project-1:session-1:conversation-1');
+ ptySessionRegistry.unregister('project-1:session-1');
});
it('spawns the agent over SSH and registers a remote pty', async () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
+ const sessionId = makeAgentPtySessionId('project-1', item.id);
- await sshProvider().startSession(item);
+ await sshProvider().start(item);
expect(openSsh2Pty).toHaveBeenCalledTimes(1);
expect(resolveSshCommand).toHaveBeenCalledWith(
@@ -221,7 +223,7 @@ describe('SshConversationProvider', () => {
it('propagates a failed SSH channel open as an error', async () => {
openSsh2Pty.mockResolvedValue({ success: false, error: new Error('channel refused') });
- await expect(sshProvider().startSession(conversation())).rejects.toThrow('channel refused');
+ await expect(sshProvider().start(session())).rejects.toThrow('channel refused');
});
it('restarts a resumed session fresh after it exits', async () => {
@@ -229,9 +231,9 @@ describe('SshConversationProvider', () => {
try {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
- const item = conversation();
+ const item = session();
- await sshProvider().startSession(item, { cols: 80, rows: 24 }, true, 'continue');
+ await sshProvider().start(item, { cols: 80, rows: 24 }, true, 'continue');
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
await vi.advanceTimersByTimeAsync(500);
@@ -250,9 +252,9 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const proxy = makeProxy();
- const item = conversation();
+ const item = session();
- await sshProvider({ proxy }).startSession(item);
+ await sshProvider({ proxy }).start(item);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 127 });
await vi.advanceTimersByTimeAsync(500);
@@ -269,11 +271,11 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const provider = sshProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 0 });
- await provider.stopSession(item.id);
+ await provider.stop();
await vi.advanceTimersByTimeAsync(500);
expect(openSsh2Pty).toHaveBeenCalledTimes(1);
@@ -286,24 +288,24 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const provider = sshProvider();
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
+ await provider.start(item);
vi.mocked(events.emit).mockClear();
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 1 });
expect(events.emit).toHaveBeenCalledWith(
agentSessionExitedChannel,
- expect.objectContaining({ conversationId: item.id, sessionId: item.sessionId })
+ expect.objectContaining({ sessionId: item.id })
);
});
it('launches the sidecar and points the agent hook env at it when tmux is on', async () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
- const item = conversation();
+ const item = session();
- await sshProvider({ tmux: true }).startSession(item);
+ await sshProvider({ tmux: true }).start(item);
expect(deployAndLaunch).toHaveBeenCalledTimes(1);
const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;
@@ -316,9 +318,9 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const proxy = makeProxy();
- const item = conversation();
+ const item = session();
- await sshProvider({ proxy, tmux: true }).startSession(item);
+ await sshProvider({ proxy, tmux: true }).start(item);
await vi.waitFor(() => expect(proxy.forwardOut).toHaveBeenCalledWith(9999));
});
@@ -330,10 +332,10 @@ describe('SshConversationProvider', () => {
mockSpawn(exitHandlers);
const proxy = makeProxy({ forwardOut: vi.fn(async () => ({ destroy: vi.fn() }) as never) });
const provider = sshProvider({ proxy, tmux: true });
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
- await provider.stopSession(item.id);
+ await provider.start(item);
+ await provider.stop();
expect(sidecarStop).not.toHaveBeenCalled();
});
@@ -343,16 +345,16 @@ describe('SshConversationProvider', () => {
mockSpawn(exitHandlers);
const proxy = makeProxy({ forwardOut: vi.fn(async () => ({ destroy: vi.fn() }) as never) });
const provider = sshProvider({ proxy, tmux: true });
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
- await provider.stopSession(item.id);
+ await provider.start(item);
+ await provider.stop();
expect(httpPostJsonOverChannel).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
path: '/disconnect',
- body: { conversationId: item.id, terminated: true },
+ body: { sessionId: item.id, terminated: true },
})
);
});
@@ -361,10 +363,10 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const provider = sshProvider({ tmux: false });
- const item = conversation();
+ const item = session();
- await provider.startSession(item);
- await provider.stopSession(item.id);
+ await provider.start(item);
+ await provider.stop();
expect(httpPostJsonOverChannel).not.toHaveBeenCalled();
});
@@ -372,9 +374,9 @@ describe('SshConversationProvider', () => {
it('re-attaches a remote tmux session on reconnect without relaunching the sidecar', async () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
- const item = conversation();
+ const item = session();
- await sshProvider({ tmux: true }).startSession(item);
+ await sshProvider({ tmux: true }).start(item);
expect(openSsh2Pty).toHaveBeenCalledTimes(1);
expect(deployAndLaunch).toHaveBeenCalledTimes(1);
@@ -391,9 +393,9 @@ describe('SshConversationProvider', () => {
it('ignores reconnect events for other connections', async () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
- const item = conversation();
+ const item = session();
- await sshProvider({ tmux: true }).startSession(item);
+ await sshProvider({ tmux: true }).start(item);
for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 1 });
emitReconnected('ssh-OTHER');
@@ -405,14 +407,13 @@ describe('SshConversationProvider', () => {
const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];
mockSpawn(exitHandlers);
const provider = sshProvider();
- const item = conversation();
- const sessionId = makePtySessionId(item.projectId, item.sessionId, item.id);
+ const item = session();
- await provider.startSession(item);
- const pty = (provider as unknown as ProviderState).sessions.get(sessionId)!;
- await provider.stopSession(item.id);
+ await provider.start(item);
+ const pty = (provider as unknown as ProviderState).pty!;
+ await provider.stop();
expect(pty.kill).toHaveBeenCalled();
- expect((provider as unknown as ProviderState).knownSessionIds.has(sessionId)).toBe(false);
+ expect((provider as unknown as ProviderState).known).toBe(false);
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
similarity index 58%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
index b6e3e28a7..97649970c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/impl/ssh-conversation.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts
@@ -1,9 +1,8 @@
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';
-import { conversationEvents } from '@main/core/conversations/conversation-events';
-import { ConversationSessionSupervisor } from '@main/core/conversations/conversation-session-supervisor';
-import { resolveAgentSessionCommandArgs } from '@main/core/conversations/resolve-agent-session-command';
-import type { ConversationProvider } from '@main/core/conversations/types';
+import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';
+import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';
+import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
import type { FileSystemProvider } from '@main/core/fs/types';
@@ -15,17 +14,18 @@ import { resolveSshCommand } from '@main/core/pty/spawn-utils';
import { openSsh2Pty } from '@main/core/pty/ssh2-pty';
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 { log } from '@main/lib/logger';
-import type { Conversation } from '@shared/core/conversations/conversations';
import type { AgentSessionConfig } from '@shared/core/providers/agent-session';
import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';
import { makePtyId } from '@shared/core/pty/ptyId';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
+import type { Session } from '@shared/core/sessions/sessions';
import { ensureAgentSidecar } from './ensure-agent-sidecar';
import { scheduleInitialPromptInjection } from './keystroke-injection';
import { RemoteHookEventRelay } from './remote-hook-event-relay';
@@ -45,15 +45,16 @@ function parseExtraArgs(value: string | undefined): string[] {
return value.trim().split(/\s+/);
}
-export class SshConversationProvider implements ConversationProvider {
- private sessions = new Map<string, Pty>();
- private knownSessionIds = new Set<string>();
- private conversations = new Map<string, Conversation>();
- private relays = new Map<string, RemoteHookEventRelay>();
+export class SshAgentRuntime implements AgentRuntimeProvider {
+ 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;
/** 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: { port: number; token: string } | null = null;
- private supervisor = new ConversationSessionSupervisor();
+ private supervisor = new AgentRuntimeSupervisor();
private readonly handleConnectionEvent: (evt: SshConnectionManagerEvent) => void;
private readonly projectId: string;
private readonly sessionPath: string;
@@ -102,7 +103,7 @@ export class SshConversationProvider implements ConversationProvider {
this.handleConnectionEvent = (evt: SshConnectionManagerEvent) => {
if (evt.type === 'reconnected' && evt.connectionId === this.connectionId) {
this.rehydrate().catch((e: unknown) => {
- log.error('SshConversationProvider: rehydrate after reconnect failed', {
+ log.error('SshAgentRuntime: rehydrate after reconnect failed', {
connectionId: this.connectionId,
error: String(e),
});
@@ -112,35 +113,38 @@ export class SshConversationProvider implements ConversationProvider {
sshConnectionManager.on('connection-event', this.handleConnectionEvent);
}
+ /** The registry key of this session's agent PTY. */
+ private get ptySessionId(): string {
+ return makeAgentPtySessionId(this.projectId, this.sessionId);
+ }
+
/**
- * Re-attach every remote session that was live before an SSH drop but whose
+ * 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.
*/
private async rehydrate(): Promise<void> {
- for (const sessionId of this.knownSessionIds) {
- if (this.sessions.has(sessionId)) continue;
- if (!this.supervisor.isDesired(sessionId)) continue;
- const conversation = this.conversations.get(sessionId);
- if (!conversation) continue;
- const size = ptySessionRegistry.getLastSize(sessionId) ?? {
- cols: DEFAULT_COLS,
- rows: DEFAULT_ROWS,
- };
- log.info('SshConversationProvider: re-attaching session after reconnect', {
- conversationId: conversation.id,
- });
- await this.startSessionInternal(conversation, size, true, undefined, true, {
- shellRefreshRetried: false,
- }).catch((e: unknown) => {
- log.error('SshConversationProvider: re-attach failed', {
- conversationId: conversation.id,
- error: String(e),
- });
+ if (!this.known || this.pty) return;
+ if (!this.supervisor.isDesired()) return;
+ const session = this.session;
+ if (!session) return;
+ 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, {
+ shellRefreshRetried: false,
+ }).catch((e: unknown) => {
+ log.error('SshAgentRuntime: re-attach failed', {
+ sessionId: this.sessionId,
+ error: String(e),
});
- }
+ });
}
private createSidecarHost(): SidecarHost {
@@ -151,7 +155,7 @@ export class SshConversationProvider implements ConversationProvider {
putFile: (localAbsPath, remoteRelPath) => {
if (!fs.copyLocalFile) {
throw new Error(
- 'SshConversationProvider: remote filesystem does not support copyLocalFile; cannot deploy sidecar bundle'
+ 'SshAgentRuntime: remote filesystem does not support copyLocalFile; cannot deploy sidecar bundle'
);
}
return fs.copyLocalFile(localAbsPath, remoteRelPath);
@@ -172,7 +176,7 @@ export class SshConversationProvider implements ConversationProvider {
const hooks = plugin.capabilities.hooks;
if (hooks.kind !== 'config' || !plugin.behavior.hooks) return;
if (hooks.scope !== 'workspace') {
- log.warn('SshConversationProvider: skipping non-workspace-scoped remote hooks', {
+ log.warn('SshAgentRuntime: skipping non-workspace-scoped remote hooks', {
providerId,
scope: hooks.scope,
});
@@ -180,25 +184,22 @@ export class SshConversationProvider implements ConversationProvider {
}
try {
await plugin.behavior.hooks.writeHooks(createRemotePluginFs(this.fs), []);
- log.info('SshConversationProvider: installed remote agent hooks', { providerId });
+ log.info('SshAgentRuntime: installed remote agent hooks', { providerId });
} catch (error) {
- log.warn('SshConversationProvider: failed to install remote agent hooks', {
+ log.warn('SshAgentRuntime: failed to install remote agent hooks', {
providerId,
error: String(error),
});
}
}
- private async launchSidecar(
- conversation: Conversation,
- sessionId: string
- ): Promise<{ port: number; token: string }> {
+ private async launchSidecar(session: Session): Promise<{ port: number; token: string }> {
// 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
// this session's hooks at its shared hook server. Reattaches if already up.
const endpoint = await ensureAgentSidecar({
- providerId: conversation.providerId,
- projectId: conversation.projectId,
+ providerId: session.providerId,
+ projectId: this.projectId,
repoDir: this.sessionPath,
deeplinkScheme: DEEPLINK_SCHEME,
ctx: this.ctx,
@@ -206,21 +207,18 @@ export class SshConversationProvider implements ConversationProvider {
host: this.createSidecarHost(),
});
this.sidecarEndpoint = endpoint;
- this.startRelay(sessionId, endpoint);
+ this.startRelay(endpoint);
return endpoint;
}
/**
- * Tell the on-VM sidecar to drop this conversation's room connection so its
+ * Tell the on-VM sidecar to drop this session's room connection so its
* poll + renew heartbeat stops — otherwise the agent keeps renewing and shows
* `live` in the room with no session behind it (CHOO-1106). Best-effort: a
* failure is logged, not thrown (the reconciler tombstone is the backstop). No
* endpoint means no sidecar was ever launched for this provider — nothing to do.
*/
- private async disconnectSidecarSession(
- conversationId: string,
- terminated: boolean
- ): Promise<void> {
+ private async disconnectSidecarSession(sessionId: string, terminated: boolean): Promise<void> {
const endpoint = this.sidecarEndpoint;
if (!endpoint) return;
// Bound the whole round-trip: opening the SSH channel can itself hang on a
@@ -234,10 +232,10 @@ export class SshConversationProvider implements ConversationProvider {
);
});
try {
- await Promise.race([this.postDisconnect(endpoint, conversationId, terminated), timeout]);
+ await Promise.race([this.postDisconnect(endpoint, sessionId, terminated), timeout]);
} catch (error) {
- log.warn('SshConversationProvider: failed to disconnect sidecar session', {
- conversationId,
+ log.warn('SshAgentRuntime: failed to disconnect sidecar session', {
+ sessionId,
error: String(error),
});
} finally {
@@ -247,7 +245,7 @@ export class SshConversationProvider implements ConversationProvider {
private async postDisconnect(
endpoint: { port: number; token: string },
- conversationId: string,
+ sessionId: string,
terminated: boolean
): Promise<void> {
const channel = await this.proxy.forwardOut(endpoint.port);
@@ -256,7 +254,7 @@ export class SshConversationProvider implements ConversationProvider {
port: endpoint.port,
token: endpoint.token,
path: '/disconnect',
- body: { conversationId, terminated },
+ body: { sessionId, terminated },
timeoutMs: SIDECAR_DISCONNECT_TIMEOUT_MS,
});
} finally {
@@ -270,8 +268,8 @@ export class SshConversationProvider implements ConversationProvider {
* local sessions, but with `startLocalPoller: false` — the sidecar already
* polls and injects on the VM.
*/
- private startRelay(sessionId: string, endpoint: { port: number; token: string }): void {
- this.relays.get(sessionId)?.stop();
+ private startRelay(endpoint: { port: number; token: string }): void {
+ this.relay?.stop();
const proxy = this.proxy;
const relay = new RemoteHookEventRelay({
opener: { openChannel: (port) => proxy.forwardOut(port) },
@@ -286,27 +284,27 @@ export class SshConversationProvider implements ConversationProvider {
},
log,
});
- this.relays.set(sessionId, relay);
+ this.relay = relay;
relay.start();
}
- private stopRelay(sessionId: string): void {
- const relay = this.relays.get(sessionId);
+ private stopRelay(): void {
+ const relay = this.relay;
if (!relay) return;
- this.relays.delete(sessionId);
+ this.relay = null;
relay.stop();
}
- private stopSidecar(sessionId: string): void {
+ 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(sessionId);
+ this.stopRelay();
}
- async startSession(
- conversation: Conversation,
+ async start(
+ session: Session,
initialSize: { cols: number; rows: number } = {
cols: DEFAULT_COLS,
rows: DEFAULT_ROWS,
@@ -314,43 +312,38 @@ export class SshConversationProvider implements ConversationProvider {
isResuming: boolean = false,
initialPrompt?: string
): Promise<void> {
- return this.startSessionInternal(conversation, initialSize, isResuming, initialPrompt, false, {
+ return this.startInternal(session, initialSize, isResuming, initialPrompt, false, {
shellRefreshRetried: false,
});
}
- private async startSessionInternal(
- conversation: Conversation,
+ private async startInternal(
+ session: Session,
initialSize: { cols: number; rows: number },
isResuming: boolean,
initialPrompt: string | undefined,
requireDesired: boolean,
options: { shellRefreshRetried: boolean }
): Promise<void> {
- const sessionId = makePtySessionId(
- conversation.projectId,
- conversation.sessionId,
- conversation.id
- );
- this.knownSessionIds.add(sessionId);
- this.conversations.set(sessionId, conversation);
-
- const spawnSize = ptySessionRegistry.getLastSize(sessionId) ?? initialSize;
- const spawnToken = this.supervisor.beginStart(sessionId, {
+ const ptySessionId = this.ptySessionId;
+ this.known = true;
+ this.session = session;
+
+ const spawnSize = ptySessionRegistry.getLastSize(ptySessionId) ?? initialSize;
+ const spawnToken = this.supervisor.beginStart({
requireDesired,
mode: isResuming ? 'resume' : 'fresh',
});
if (!spawnToken) return;
try {
- const providerConfig = await providerOverrideSettings.getItem(conversation.providerId);
- const agentSession = resolveAgentSessionCommandArgs(conversation, isResuming);
- const plugin = getPlugin(conversation.providerId);
+ const providerConfig = await providerOverrideSettings.getItem(session.providerId);
+ const agentSession = resolveAgentSessionCommandArgs(session, isResuming);
+ const plugin = getPlugin(session.providerId);
- const binaryName =
- plugin.capabilities.hostDependency.binaryNames[0] ?? conversation.providerId;
+ const binaryName = plugin.capabilities.hostDependency.binaryNames[0] ?? session.providerId;
const executableCli = await resolveAgentExecutable({
- providerId: conversation.providerId,
+ providerId: session.providerId,
binaryName,
ctx: this.ctx,
hostDependencyStore,
@@ -360,10 +353,10 @@ export class SshConversationProvider implements ConversationProvider {
const agentCommand = plugin.behavior.prompt!.buildCommand({
cli: executableCli,
extraArgs: parseExtraArgs(providerConfig?.extraArgs),
- autoApprove: conversation.autoApprove ?? false,
+ autoApprove: session.autoApprove ?? false,
initialPrompt: agentSession.isResuming ? undefined : initialPrompt,
sessionId: agentSession.sessionId,
- providerSessionId: conversation.providerSessionId ?? undefined,
+ providerSessionId: session.providerSessionId ?? undefined,
isResuming: agentSession.isResuming,
model: '',
});
@@ -371,18 +364,17 @@ export class SshConversationProvider implements ConversationProvider {
const customEnv = providerConfig?.env ?? {};
const providerEnv: Record<string, string> = { ...agentCommand.env, ...customEnv };
- const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(conversation.id) : undefined;
+ const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;
const cfg: AgentSessionConfig = {
sessionId: this.sessionId,
- conversationId: conversation.id,
- providerId: conversation.providerId,
+ providerId: session.providerId,
command: agentCommand.command,
args: agentCommand.args,
cwd: this.sessionPath,
shellSetup: this.shellSetup,
tmuxSessionName,
- autoApprove: conversation.autoApprove ?? false,
+ autoApprove: session.autoApprove ?? false,
resume: agentSession.isResuming,
};
@@ -391,28 +383,28 @@ export class SshConversationProvider implements ConversationProvider {
// 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.
let hookEnv: Record<string, string> = {};
- if (tmuxSessionName && this.relays.has(sessionId)) {
+ 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('SshConversationProvider: re-attaching to running tmux session + sidecar', {
- conversationId: conversation.id,
+ log.info('SshAgentRuntime: re-attaching to running tmux session + sidecar', {
+ sessionId: this.sessionId,
});
} else if (tmuxSessionName) {
- const ptyId = makePtyId(conversation.providerId, conversation.id);
+ 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(conversation.providerId);
- const endpoint = await this.launchSidecar(conversation, sessionId);
+ await this.installRemoteHooks(session.providerId);
+ const endpoint = await this.launchSidecar(session);
hookEnv = buildAgentHookEnv({ port: endpoint.port, ptyId, token: endpoint.token });
} else {
log.warn(
- 'SshConversationProvider: tmux disabled — remote agent will not stay connected to Switch while detached',
- { conversationId: conversation.id }
+ 'SshAgentRuntime: tmux disabled — remote agent will not stay connected to Switch while detached',
+ { sessionId: this.sessionId }
);
}
@@ -428,15 +420,15 @@ export class SshConversationProvider implements ConversationProvider {
);
const result = await openSsh2Pty(this.proxy, {
- id: sessionId,
+ id: ptySessionId,
command: sshCommand,
cols: spawnSize.cols,
rows: spawnSize.rows,
});
if (!result.success) {
- log.error('SshConversationProvider: failed to open SSH channel', {
- sessionId,
+ log.error('SshAgentRuntime: failed to open SSH channel', {
+ sessionId: ptySessionId,
error: result.error.message,
});
throw new Error(result.error.message);
@@ -446,22 +438,21 @@ export class SshConversationProvider implements ConversationProvider {
pty.onExit((info) => {
const { exitCode } = info;
- const decision = this.supervisor.handleExit(sessionId, pty);
+ const decision = this.supervisor.handleExit(pty);
if (decision.kind === 'stale') return;
- const replacementSize = ptySessionRegistry.getLastSize(sessionId) ?? spawnSize;
+ const replacementSize = ptySessionRegistry.getLastSize(ptySessionId) ?? spawnSize;
- ptySessionRegistry.unregister(sessionId, { pty, exitInfo: info });
- this.sessions.delete(sessionId);
+ ptySessionRegistry.unregister(ptySessionId, { pty, exitInfo: info });
+ this.pty = null;
if (decision.kind === 'stopped') return;
- this.emitExited(conversation);
+ this.emitExited();
if (this.tmux) return;
if (exitCode === SHELL_NOT_FOUND_EXIT_CODE && !options.shellRefreshRetried) {
this.scheduleShellRefreshRetry({
- conversation,
- sessionId,
+ session,
initialSize: replacementSize,
isResuming: decision.kind === 'respawnResume',
initialPrompt,
@@ -469,87 +460,80 @@ export class SshConversationProvider implements ConversationProvider {
return;
}
- if (this.supervisor.isDesired(sessionId)) {
+ if (this.supervisor.isDesired()) {
this.scheduleReplacement({
- conversation,
+ session,
initialSize: replacementSize,
isResuming: decision.kind === 'respawnResume',
});
}
});
- if (!this.supervisor.acceptSpawn(sessionId, spawnToken, pty)) {
+ if (!this.supervisor.acceptSpawn(spawnToken, pty)) {
try {
pty.kill();
} catch {}
- if (ptySessionRegistry.get(sessionId) === pty) {
- ptySessionRegistry.unregister(sessionId);
+ if (ptySessionRegistry.get(ptySessionId) === pty) {
+ ptySessionRegistry.unregister(ptySessionId);
}
return;
}
- ptySessionRegistry.register(sessionId, pty, {
+ ptySessionRegistry.register(ptySessionId, pty, {
metadata: {
- providerId: conversation.providerId,
- title: conversation.title,
+ providerId: session.providerId,
+ title: session.title,
isRemote: true,
},
});
- this.sessions.set(sessionId, pty);
+ this.pty = pty;
scheduleInitialPromptInjection({
pty,
- conversation,
+ session,
initialPrompt,
isResuming: agentSession.isResuming,
});
} catch (error) {
- this.supervisor.failSpawn(sessionId, spawnToken);
+ this.supervisor.failSpawn(spawnToken);
throw error;
}
}
- private emitExited(conversation: Conversation): void {
- events.emit(agentSessionExitedChannel, {
- conversationId: conversation.id,
- sessionId: conversation.sessionId,
- });
- conversationEvents._emit('conversation:session-exited', {
- conversationId: conversation.id,
- sessionId: conversation.sessionId,
- });
+ private emitExited(): void {
+ events.emit(agentSessionExitedChannel, { sessionId: this.sessionId });
+ sessionHooks._emit('session:agent-exited', { sessionId: this.sessionId });
}
- private detachPty(sessionId: string): void {
- const pty = this.supervisor.stop(sessionId) ?? this.sessions.get(sessionId);
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
+ private detachPty(): void {
+ const pty = this.supervisor.stop() ?? this.pty;
+ this.pty = null;
+ ptySessionRegistry.unregister(this.ptySessionId);
if (pty) {
try {
pty.kill();
} catch (e) {
- log.warn('SshConversationProvider: error killing PTY', {
- sessionId,
+ log.warn('SshAgentRuntime: error killing PTY', {
+ sessionId: this.sessionId,
error: String(e),
});
}
}
}
- async detachSession(conversationId: string): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.sessionId, conversationId);
- this.detachPty(sessionId);
+ async dehydrate(): Promise<void> {
+ this.detachPty();
if (!this.tmux) {
- this.knownSessionIds.delete(sessionId);
- this.supervisor.forget(sessionId);
+ this.known = false;
+ this.supervisor.forget();
}
}
- async stopSession(conversationId: string): Promise<void> {
- await this.teardownSession(conversationId, { disconnectSidecar: true, killTmux: true });
+ async stop(): Promise<void> {
+ await this.teardownSession({ disconnectSidecar: true, killTmux: true });
}
/**
- * Tear down this client's local state for a session. `disconnectSidecar` +
+ * Tear down this client's local state for the session. `disconnectSidecar` +
* `killTmux` are true for a deliberate delete/kill originating here (which also
* makes the sidecar broadcast a `session-terminated` event). They are false on
* the receiving side of that broadcast (`onRemoteTerminated`): the initiator
@@ -557,141 +541,112 @@ export class SshConversationProvider implements ConversationProvider {
* repeating either here would be wasteful and — for the disconnect — would
* re-broadcast in a loop.
*/
- private async teardownSession(
- conversationId: string,
- opts: { disconnectSidecar: boolean; killTmux: boolean }
- ): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.sessionId, conversationId);
- this.knownSessionIds.delete(sessionId);
- this.conversations.delete(sessionId);
- if (this.tmux && opts.disconnectSidecar)
- await this.disconnectSidecarSession(conversationId, true);
- this.stopSidecar(sessionId);
- const pty = this.supervisor.stop(sessionId) ?? this.sessions.get(sessionId);
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
- if (pty) {
- try {
- pty.kill();
- } catch (e) {
- log.warn('SshConversationProvider: error killing PTY', {
- sessionId,
- error: String(e),
- });
- }
+ private async teardownSession(opts: {
+ disconnectSidecar: boolean;
+ killTmux: boolean;
+ }): Promise<void> {
+ this.known = false;
+ this.session = null;
+ if (this.tmux && opts.disconnectSidecar) {
+ await this.disconnectSidecarSession(this.sessionId, true);
}
+ this.stopSidecar();
+ this.detachPty();
if (this.tmux && opts.killTmux) {
- await killTmuxSession(this.ctx, makeAgentTmuxSessionName(conversationId));
+ await killTmuxSession(this.ctx, makeAgentTmuxSessionName(this.sessionId));
}
- this.supervisor.forget(sessionId);
+ this.supervisor.forget();
}
/**
* Handle a `session-terminated` broadcast from the sidecar: another client (or
- * this one) deliberately deleted the session. Tear down local state without
- * re-killing tmux or re-disconnecting the sidecar, then signal the DB-level
- * cleanup so the session row is removed everywhere and cannot be re-attached
- * into a blank session. Idempotent — safe if this client never had the session.
+ * this one) deliberately deleted a session on this VM. The shared sidecar
+ * broadcasts to every session's relay, so the terminated id may belong to a
+ * different session — local state is only torn down when it is ours, but the
+ * DB-level cleanup is signalled either way so the session row is removed
+ * everywhere and cannot be re-attached into a blank session.
*/
private onRemoteTerminated(rawBody: string): void {
- let conversationId = '';
+ let terminatedSessionId = '';
try {
- const parsed = JSON.parse(rawBody) as { conversationId?: unknown };
- if (typeof parsed.conversationId === 'string') conversationId = parsed.conversationId;
+ const parsed = JSON.parse(rawBody) as { sessionId?: unknown };
+ if (typeof parsed.sessionId === 'string') terminatedSessionId = parsed.sessionId;
} catch {
- conversationId = '';
+ terminatedSessionId = '';
}
- if (!conversationId) {
- log.warn('SshConversationProvider: session-terminated event missing conversationId');
+ if (!terminatedSessionId) {
+ log.warn('SshAgentRuntime: session-terminated event missing sessionId');
return;
}
- void this.teardownSession(conversationId, { disconnectSidecar: false, killTmux: false }).catch(
- (e: unknown) => {
- log.warn('SshConversationProvider: error tearing down terminated session', {
- conversationId,
- error: String(e),
- });
- }
- );
- conversationEvents._emit('conversation:remote-terminated', {
+ if (terminatedSessionId === this.sessionId) {
+ void this.teardownSession({ disconnectSidecar: false, killTmux: false }).catch(
+ (e: unknown) => {
+ log.warn('SshAgentRuntime: error tearing down terminated session', {
+ sessionId: terminatedSessionId,
+ error: String(e),
+ });
+ }
+ );
+ }
+ sessionHooks._emit('session:remote-terminated', {
projectId: this.projectId,
sessionId: this.sessionId,
- conversationId,
+ terminatedSessionId,
});
}
- async destroyAll(): Promise<void> {
+ async destroy(): Promise<void> {
sshConnectionManager.off('connection-event', this.handleConnectionEvent);
- const sessionIds = Array.from(this.knownSessionIds);
- await this.detachAll();
- if (this.tmux) {
- await Promise.all(
- sessionIds.map((id) => {
- const conversation = this.conversations.get(id);
- return conversation
- ? this.disconnectSidecarSession(conversation.id, true)
- : Promise.resolve();
- })
- );
- }
- for (const id of sessionIds) this.stopSidecar(id);
- const conversationIds = sessionIds
- .map((id) => this.conversations.get(id)?.id)
- .filter((id): id is string => id !== undefined);
- for (const id of sessionIds) this.conversations.delete(id);
- if (this.tmux) {
- await Promise.all(
- conversationIds.map((id) => killTmuxSession(this.ctx, makeAgentTmuxSessionName(id)))
- );
+ const wasKnown = this.known;
+ await this.detach();
+ if (this.tmux && wasKnown) {
+ await this.disconnectSidecarSession(this.sessionId, true);
}
- for (const sessionId of sessionIds) {
- this.supervisor.forget(sessionId);
+ this.stopSidecar();
+ this.session = null;
+ if (this.tmux && wasKnown) {
+ await killTmuxSession(this.ctx, makeAgentTmuxSessionName(this.sessionId));
}
- this.knownSessionIds.clear();
+ this.supervisor.forget();
+ this.known = false;
}
- async detachAll(): Promise<void> {
- for (const [sessionId, pty] of this.sessions) {
- this.supervisor.stop(sessionId);
+ async detach(): Promise<void> {
+ if (this.pty) {
+ const pty = this.pty;
+ this.supervisor.stop();
try {
pty.kill();
} catch {}
- ptySessionRegistry.unregister(sessionId);
+ ptySessionRegistry.unregister(this.ptySessionId);
+ this.pty = null;
}
- this.sessions.clear();
}
private scheduleShellRefreshRetry({
- conversation,
- sessionId,
+ session,
initialSize,
isResuming,
initialPrompt,
}: {
- conversation: Conversation;
- sessionId: string;
+ session: Session;
initialSize: { cols: number; rows: number };
isResuming: boolean;
initialPrompt: string | undefined;
}): void {
setTimeout(() => {
- if (!this.supervisor.isDesired(sessionId)) return;
+ if (!this.supervisor.isDesired()) return;
this.proxy
.refreshRemoteShellProfile()
.then(() => {
- if (!this.supervisor.isDesired(sessionId)) return;
- return this.startSessionInternal(
- conversation,
- initialSize,
- isResuming,
- initialPrompt,
- true,
- { shellRefreshRetried: true }
- );
+ if (!this.supervisor.isDesired()) return;
+ return this.startInternal(session, initialSize, isResuming, initialPrompt, true, {
+ shellRefreshRetried: true,
+ });
})
.catch((e) => {
- log.error('SshConversationProvider: shell refresh retry failed', {
- conversationId: conversation.id,
+ log.error('SshAgentRuntime: shell refresh retry failed', {
+ sessionId: this.sessionId,
error: String(e),
});
});
@@ -699,20 +654,20 @@ export class SshConversationProvider implements ConversationProvider {
}
private scheduleReplacement({
- conversation,
+ session,
initialSize,
isResuming,
}: {
- conversation: Conversation;
+ session: Session;
initialSize: { cols: number; rows: number };
isResuming: boolean;
}): void {
setTimeout(() => {
- this.startSessionInternal(conversation, initialSize, isResuming, undefined, true, {
+ this.startInternal(session, initialSize, isResuming, undefined, true, {
shellRefreshRetried: false,
}).catch((e) => {
- log.error('SshConversationProvider: replacement failed', {
- conversationId: conversation.id,
+ log.error('SshAgentRuntime: replacement failed', {
+ sessionId: this.sessionId,
error: String(e),
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
similarity index 65%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.test.ts
rename to dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
index 38680158b..865298aff 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.test.ts
@@ -1,17 +1,23 @@
import { pluginRegistry } from '@switchdash/plugins/agents';
import { describe, expect, it } from 'vitest';
-import type { Conversation } from '@shared/core/conversations/conversations';
+import type { Session } from '@shared/core/sessions/sessions';
import { resolveAgentSessionCommandArgs } from './resolve-agent-session-command';
-function makeConversation(overrides: Partial<Conversation> = {}): Conversation {
+function makeSession(overrides: Partial<Session> = {}): Session {
+ const now = '2024-01-01T00:00:00.000Z';
return {
- id: 'conv-1',
- projectId: 'proj-1',
- sessionId: 'session-1',
+ id: 'session-1',
+ agentId: 'agent-1',
providerId: 'droid',
title: 'Test',
- lastInteractedAt: null,
- isInitialConversation: false,
+ shellId: 'system',
+ status: 'in_progress',
+ statusChangedAt: now,
+ agentSessionId: null,
+ isInitialSession: false,
+ isPinned: false,
+ createdAt: now,
+ updatedAt: now,
...overrides,
};
}
@@ -20,7 +26,7 @@ describe('resolveAgentSessionCommandArgs', () => {
it('uses stored Codex session id when resuming', () => {
expect(
resolveAgentSessionCommandArgs(
- makeConversation({
+ makeSession({
providerId: 'codex',
providerSessionId: '019c95f6-cd96-7812-ba15-574286674599',
}),
@@ -30,35 +36,33 @@ describe('resolveAgentSessionCommandArgs', () => {
});
it('starts fresh instead of resuming Codex --last without a stored session id', () => {
- expect(resolveAgentSessionCommandArgs(makeConversation({ providerId: 'codex' }), true)).toEqual(
- {
- sessionId: 'conv-1',
- isResuming: false,
- }
- );
+ expect(resolveAgentSessionCommandArgs(makeSession({ providerId: 'codex' }), true)).toEqual({
+ sessionId: 'session-1',
+ isResuming: false,
+ });
});
it('uses stored Droid session id when resuming', () => {
expect(
resolveAgentSessionCommandArgs(
- makeConversation({ providerSessionId: '31477a03-961a-4451-82d4-efded56947fc' }),
+ makeSession({ providerSessionId: '31477a03-961a-4451-82d4-efded56947fc' }),
true
)
).toEqual({ sessionId: '31477a03-961a-4451-82d4-efded56947fc', isResuming: true });
});
it('starts fresh when resuming Droid without a stored session id', () => {
- expect(resolveAgentSessionCommandArgs(makeConversation(), true)).toEqual({
- sessionId: 'conv-1',
+ expect(resolveAgentSessionCommandArgs(makeSession(), true)).toEqual({
+ sessionId: 'session-1',
isResuming: false,
});
});
it('keeps resume enabled when provider session ids are unavailable', () => {
expect(
- resolveAgentSessionCommandArgs(makeConversation(), true, { requireProviderSessionId: false })
+ resolveAgentSessionCommandArgs(makeSession(), true, { requireProviderSessionId: false })
).toEqual({
- sessionId: 'conv-1',
+ sessionId: 'session-1',
isResuming: true,
});
});
@@ -66,21 +70,21 @@ describe('resolveAgentSessionCommandArgs', () => {
it('passes through for non-Droid providers', () => {
expect(
resolveAgentSessionCommandArgs(
- makeConversation({
+ makeSession({
providerId: 'claude',
providerSessionId: '31477a03-961a-4451-82d4-efded56947fc',
}),
true
)
- ).toEqual({ sessionId: 'conv-1', isResuming: true });
+ ).toEqual({ sessionId: 'session-1', isResuming: true });
});
- it('builds a Claude replacement resume command from the logical conversation id', () => {
- const conversation = makeConversation({
+ it('builds a Claude replacement resume command from the logical session id', () => {
+ const session = makeSession({
id: '6fac6620-9fa8-4604-b7e0-1fe361589104',
providerId: 'claude',
});
- const spawnPlan = resolveAgentSessionCommandArgs(conversation, true);
+ const spawnPlan = resolveAgentSessionCommandArgs(session, true);
const result = pluginRegistry.get('claude')!.behavior.prompt!.buildCommand({
cli: 'claude',
autoApprove: false,
@@ -91,22 +95,22 @@ describe('resolveAgentSessionCommandArgs', () => {
expect(result.command).toBe('claude');
expect(result.args).toContain('--resume');
- expect(result.args).toContain(conversation.id);
+ expect(result.args).toContain(session.id);
});
it('builds a Codex replacement resume command from the stored provider session id', () => {
- const conversation = makeConversation({
+ const session = makeSession({
id: '6fac6620-9fa8-4604-b7e0-1fe361589104',
providerId: 'codex',
providerSessionId: 'provider-session-1',
});
- const spawnPlan = resolveAgentSessionCommandArgs(conversation, true);
+ const spawnPlan = resolveAgentSessionCommandArgs(session, true);
const result = pluginRegistry.get('codex')!.behavior.prompt!.buildCommand({
cli: 'codex',
autoApprove: false,
model: '',
sessionId: spawnPlan.sessionId,
- providerSessionId: conversation.providerSessionId ?? undefined,
+ providerSessionId: session.providerSessionId ?? undefined,
isResuming: spawnPlan.isResuming,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts
new file mode 100644
index 000000000..7eec9e7a2
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/resolve-agent-session-command.ts
@@ -0,0 +1,20 @@
+import type { Session } from '@shared/core/sessions/sessions';
+
+/** Droid `--resume` needs the provider-native session UUID, not the Switchdash session id. */
+export function resolveAgentSessionCommandArgs(
+ session: Session,
+ isResuming: boolean,
+ options: { requireProviderSessionId?: boolean } = {}
+): { sessionId: string; isResuming: boolean } {
+ if ((session.providerId === 'codex' || session.providerId === 'droid') && isResuming) {
+ if (session.providerSessionId) {
+ return { sessionId: session.providerSessionId, isResuming: true };
+ }
+ if (options.requireProviderSessionId === false) {
+ return { sessionId: session.id, isResuming };
+ }
+ return { sessionId: session.id, isResuming: false };
+ }
+
+ return { sessionId: session.id, isResuming };
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/types.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/types.ts
new file mode 100644
index 000000000..06c4a27ee
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/types.ts
@@ -0,0 +1,30 @@
+import { type Session } from '@shared/core/sessions/sessions';
+
+/**
+ * Runtime handle for the single agent process of one session (one session =
+ * one agent run). Implementations own the PTY, the respawn
+ * supervisor, and — for SSH — the sidecar relay for that one agent.
+ */
+export interface AgentRuntimeProvider {
+ start(
+ session: Session,
+ initialSize?: { cols: number; rows: number },
+ isResuming?: boolean,
+ initialPrompt?: string
+ ): Promise<void>;
+ /**
+ * Close the local PTY view of the agent (the `dehydrateSession` RPC).
+ * On tmux the agent keeps running and stays re-attachable; otherwise the
+ * agent is gone and respawn tracking is cleared.
+ */
+ dehydrate(): Promise<void>;
+ /**
+ * Detach at session teardown: kill the local PTY but keep re-attach
+ * bookkeeping (tmux pane, sidecar, reconnect listener) intact.
+ */
+ detach(): Promise<void>;
+ /** Stop the agent for good: kill the PTY and tmux pane, disconnect the sidecar. */
+ stop(): Promise<void>;
+ /** Terminate teardown: stop everything and release agent-scoped listeners. */
+ destroy(): Promise<void>;
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts
index 42b2a4e2a..ff8660097 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/connect-remote-agent.ts
@@ -1,4 +1,4 @@
-import type { SidecarHost } from '@main/core/conversations/impl/remote-sidecar-launcher';
+import type { SidecarHost } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';
import type { IExecutionContext } from '@main/core/execution-context/types';
import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
index 984246a1d..3e9f3169c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/generate-agent-launch-spec.ts
@@ -1,4 +1,4 @@
-import { resolveAgentExecutable } from '@main/core/conversations/impl/resolve-agent-executable';
+import { resolveAgentExecutable } from '@main/core/agent-runtime/impl/resolve-agent-executable';
import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';
import type { IExecutionContext } from '@main/core/execution-context/types';
import { getPlugin } from '@main/core/providers/plugin-registry';
@@ -17,7 +17,7 @@ function parseExtraArgs(value: string | undefined): string[] {
/**
* Precompute the provider-specific launch recipe for a remote agent's
* auto-started sessions, resolving the agent binary on the VM and baking in
- * placeholder tokens for the two per-spawn values (conversation id + initial
+ * placeholder tokens for the two per-spawn values (session id + initial
* prompt). The VM watcher — which has no plugin registry — substitutes those
* tokens per spawn, so all provider knowledge stays here in switchdash.
*
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.ts
index 6e73f2b6a..58737f9c3 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
@@ -32,10 +32,10 @@ vi.mock('./connect-remote-agent', () => ({
host: {},
}),
}));
-vi.mock('@main/core/conversations/impl/ensure-agent-sidecar', () => ({
+vi.mock('@main/core/agent-runtime/impl/ensure-agent-sidecar', () => ({
probeAgentSidecar: () => probeAgentSidecar(),
}));
-vi.mock('@main/core/conversations/impl/sidecar-http', () => ({
+vi.mock('@main/core/agent-runtime/impl/sidecar-http', () => ({
httpGetJsonOverChannel: () => httpGetJsonOverChannel(),
}));
vi.mock('@main/core/sessions/session-service', () => ({
@@ -58,7 +58,7 @@ vi.mock('@main/lib/events', () => ({
events: { emit: (...args: unknown[]) => eventsEmit(...args) },
}));
-import { conversationEvents } from '@main/core/conversations/conversation-events';
+import { sessionHooks } from '@main/core/sessions/session-hooks';
import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';
import { remoteSessionReconciler } from './remote-session-reconciler';
@@ -69,12 +69,12 @@ function reconcile(agentId: string): Promise<void> {
).reconcileOnce(agentId);
}
-function handleRemoteTerminated(conversationId: string): Promise<void> {
+function handleRemoteTerminated(sessionId: string): Promise<void> {
return (
remoteSessionReconciler as unknown as {
handleRemoteTerminated: (id: string) => Promise<void>;
}
- ).handleRemoteTerminated(conversationId);
+ ).handleRemoteTerminated(sessionId);
}
describe('RemoteSessionReconciler', () => {
@@ -84,24 +84,24 @@ describe('RemoteSessionReconciler', () => {
remoteSessionReconciler.dispose();
});
- it('adopts a VM session switchdash has never seen, keyed by the VM conversation id', async () => {
+ it('adopts a VM session switchdash has never seen, keyed by the VM session id', async () => {
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-new', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-new', roomId: 'room-1' }],
});
await reconcile('agent-1');
expect(createSession).toHaveBeenCalledTimes(1);
expect(createSession).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'conv-new', agentId: 'agent-1', autoApprove: true })
+ expect.objectContaining({ id: 'session-new', agentId: 'agent-1', autoApprove: true })
);
- expect(provisionWorkspace).toHaveBeenCalledWith('conv-new');
+ expect(provisionWorkspace).toHaveBeenCalledWith('session-new');
});
it('skips a VM session that already has a switchdash row', async () => {
- knownRows = [{ id: 'conv-known' }];
+ knownRows = [{ id: 'session-known' }];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-known', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-known', roomId: 'room-1' }],
});
await reconcile('agent-1');
expect(createSession).not.toHaveBeenCalled();
@@ -120,28 +120,28 @@ describe('RemoteSessionReconciler', () => {
expect(createSession).not.toHaveBeenCalled();
});
- it('refuses to re-adopt a tombstoned (just-deleted) conversation id', async () => {
+ it('refuses to re-adopt a tombstoned (just-deleted) session id', async () => {
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-deleted', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-deleted', roomId: 'room-1' }],
});
- remoteSessionReconciler.tombstone('conv-deleted');
+ remoteSessionReconciler.tombstone('session-deleted');
await reconcile('agent-1');
expect(createSession).not.toHaveBeenCalled();
});
it('removes a remotely-terminated session row, emits deletion, and refuses re-adoption', async () => {
- const emitSpy = vi.spyOn(conversationEvents, '_emit');
- await handleRemoteTerminated('conv-term');
+ const emitSpy = vi.spyOn(sessionHooks, '_emit');
+ await handleRemoteTerminated('session-term');
expect(deleteWhere).toHaveBeenCalledTimes(1);
- expect(emitSpy).toHaveBeenCalledWith('conversation:deleted', 'conv-term');
+ expect(emitSpy).toHaveBeenCalledWith('session:deleted', 'session-term');
// The tombstone set during teardown must block re-adoption from a stale snapshot.
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-term', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-term', roomId: 'room-1' }],
});
await reconcile('agent-1');
expect(createSession).not.toHaveBeenCalled();
@@ -152,60 +152,60 @@ describe('RemoteSessionReconciler', () => {
it('notifies the renderer (session:deleted) with the resolved projectId when a row is removed', async () => {
// The removal originates in the main process, so the renderer needs an IPC
// event to drop the sidebar row (a user-initiated delete removes it itself).
- knownRows = [{ id: 'conv-term', agentId: 'agent-1' }];
- await handleRemoteTerminated('conv-term');
+ knownRows = [{ id: 'session-term', agentId: 'agent-1' }];
+ await handleRemoteTerminated('session-term');
expect(eventsEmit).toHaveBeenCalledWith(sessionDeletedChannel, {
- sessionId: 'conv-term',
+ sessionId: 'session-term',
projectId: 'proj-1',
});
});
- it('does not emit conversation:deleted when the row was already gone (no-op delete)', async () => {
+ it('does not emit session:deleted when the row was already gone (no-op delete)', async () => {
// Every relay/instance delivers the same session-terminated; only the first
// delete removes a row, the rest are no-ops and must stay silent.
deleteWhere.mockResolvedValueOnce({ changes: 0 });
- const emitSpy = vi.spyOn(conversationEvents, '_emit');
- await handleRemoteTerminated('conv-already-gone');
+ const emitSpy = vi.spyOn(sessionHooks, '_emit');
+ await handleRemoteTerminated('session-already-gone');
expect(deleteWhere).toHaveBeenCalledTimes(1);
- expect(emitSpy).not.toHaveBeenCalledWith('conversation:deleted', 'conv-already-gone');
+ expect(emitSpy).not.toHaveBeenCalledWith('session:deleted', 'session-already-gone');
emitSpy.mockRestore();
});
it('prunes an adopted session only after it stays absent for the threshold', async () => {
- const emitSpy = vi.spyOn(conversationEvents, '_emit');
+ const emitSpy = vi.spyOn(sessionHooks, '_emit');
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-a', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-a', roomId: 'room-1' }],
});
- await reconcile('agent-1'); // adopt conv-a
+ await reconcile('agent-1'); // adopt session-a
expect(createSession).toHaveBeenCalledTimes(1);
// Row now exists (so it is not re-adopted); VM stops reporting it.
- knownRows = [{ id: 'conv-a' }];
+ knownRows = [{ id: 'session-a' }];
httpGetJsonOverChannel.mockResolvedValue({ sessions: [] });
await reconcile('agent-1'); // streak 1
await reconcile('agent-1'); // streak 2
expect(deleteWhere).not.toHaveBeenCalled();
await reconcile('agent-1'); // streak 3 → prune
expect(deleteWhere).toHaveBeenCalledTimes(1);
- expect(emitSpy).toHaveBeenCalledWith('conversation:deleted', 'conv-a');
+ expect(emitSpy).toHaveBeenCalledWith('session:deleted', 'session-a');
emitSpy.mockRestore();
});
it('does not prune an adopted session that keeps being reported', async () => {
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-a', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-a', roomId: 'room-1' }],
});
await reconcile('agent-1'); // adopt
- knownRows = [{ id: 'conv-a' }];
+ knownRows = [{ id: 'session-a' }];
// Absent once, then present again — streak must reset, no prune.
httpGetJsonOverChannel.mockResolvedValueOnce({ sessions: [] });
await reconcile('agent-1');
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-a', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-a', roomId: 'room-1' }],
});
await reconcile('agent-1');
await reconcile('agent-1');
@@ -217,23 +217,23 @@ describe('RemoteSessionReconciler', () => {
knownRows = [];
httpGetJsonOverChannel.mockResolvedValue({
sessions: [
- { conversationId: 'conv-deleted', roomId: 'room-1' },
- { conversationId: 'conv-new', roomId: 'room-2' },
+ { sessionId: 'session-deleted', roomId: 'room-1' },
+ { sessionId: 'session-new', roomId: 'room-2' },
],
});
- remoteSessionReconciler.tombstone('conv-deleted');
+ remoteSessionReconciler.tombstone('session-deleted');
await reconcile('agent-1');
expect(createSession).toHaveBeenCalledTimes(1);
- expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'conv-new' }));
+ expect(createSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'session-new' }));
});
it('skips a VM session whose row belongs to another agent (global id check)', async () => {
- // The sessions PK is the conversation id; a row minted under a different
+ // The sessions PK is the session id; a row minted under a different
// agent must block adoption or the insert would crash with UNIQUE failed.
- knownRows = [{ id: 'conv-shared', agentId: 'agent-OTHER' }];
+ knownRows = [{ id: 'session-shared', agentId: 'agent-OTHER' }];
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-shared', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-shared', roomId: 'room-1' }],
});
await reconcile('agent-1');
expect(createSession).not.toHaveBeenCalled();
@@ -246,7 +246,7 @@ describe('RemoteSessionReconciler', () => {
error: { type: 'already-exists' },
} as never);
httpGetJsonOverChannel.mockResolvedValue({
- sessions: [{ conversationId: 'conv-race', roomId: 'room-1' }],
+ sessions: [{ sessionId: 'session-race', roomId: 'room-1' }],
});
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.ts
index 8c5f2697e..7c1c401c1 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
@@ -1,9 +1,9 @@
import { eq, inArray } from 'drizzle-orm';
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
-import { conversationEvents } from '@main/core/conversations/conversation-events';
-import { probeAgentSidecar } from '@main/core/conversations/impl/ensure-agent-sidecar';
-import type { SidecarEndpoint } from '@main/core/conversations/impl/remote-sidecar-launcher';
-import { httpGetJsonOverChannel } from '@main/core/conversations/impl/sidecar-http';
+import { probeAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';
+import type { SidecarEndpoint } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
+import { httpGetJsonOverChannel } from '@main/core/agent-runtime/impl/sidecar-http';
+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 { agentSshConnectionId } from '@main/core/workspaces/resolve-agent-workspace';
@@ -23,7 +23,7 @@ const SESSIONS_REQUEST_TIMEOUT_MS = 10_000;
// should never fire — it is the backstop that guarantees the `inFlight` guard
// can never wedge permanently and silently stop reconciliation for good.
const TICK_DEADLINE_MS = 45_000;
-// How long a just-deleted conversation id is refused re-adoption. The delete
+// How long a just-deleted session id is refused re-adoption. The delete
// path sends the sidecar a /disconnect, but a reconcile tick can race it (both
// run on a ~2s cadence) and re-adopt the id from a stale /sessions snapshot
// before the disconnect lands — recreating the ghost row we just deleted. The
@@ -39,7 +39,7 @@ const TOMBSTONE_TTL_MS = 10_000;
const PRUNE_MISSING_THRESHOLD = 3;
interface SidecarSessionsResponse {
- sessions: Array<{ conversationId: string; roomId: string | null }>;
+ sessions: Array<{ sessionId: string; roomId: string | null }>;
}
/**
@@ -47,17 +47,17 @@ interface SidecarSessionsResponse {
* notification watcher auto-starting a session when the agent is addressed while
* switchdash was closed) in the switchdash UI.
*
- * The VM is the source of truth: it mints the conversation id and runs the agent
+ * The VM is the source of truth: it mints the session id and runs the agent
* in a tmux pane with no switchdash DB row. This reconciler polls the sidecar's
- * `GET /sessions` snapshot and, for each conversation id switchdash has never
- * seen, creates a session row with `id = the VM's conversation id`. Because the
+ * `GET /sessions` snapshot and, for each session id switchdash has never
+ * seen, creates a session row with `id = the VM's session id`. Because the
* tmux session name is derived deterministically from that id, the normal
* session-start path then *attaches* to the already-running pane (same as the
* post-reconnect rehydrate) rather than spawning a second agent — so the session
* appears live in the UI, with its real terminal and its hook-event relay.
*
* One periodic poll per watched remote agent. Idempotent: an already-known
- * conversation id is skipped, so re-polling only ever adds newly-spawned
+ * session id is skipped, so re-polling only ever adds newly-spawned
* sessions. The sidecar endpoint (port + token) is resolved fresh each cycle, so
* a sidecar that restarted — or a VM that rebooted — is re-ensured and its new
* token picked up automatically.
@@ -69,16 +69,16 @@ class RemoteSessionReconciler {
/** Cached sidecar endpoint per agent, so a steady-state tick doesn't re-ensure
* (rewrite the spec, reattach) every tick — only when the cached poll fails. */
private readonly endpoints = new Map<string, SidecarEndpoint>();
- /** conversationId → expiry ts for just-deleted sessions we must not re-adopt. */
+ /** sessionId → expiry ts for just-deleted sessions we must not re-adopt. */
private readonly tombstones = new Map<string, number>();
- /** agentId → conversation ids this reconciler adopted (candidates for pruning). */
+ /** agentId → session ids this reconciler adopted (candidates for pruning). */
private readonly adopted = new Map<string, Set<string>>();
- /** conversationId → consecutive reconcile passes it has been absent from `/sessions`. */
+ /** sessionId → consecutive reconcile passes it has been absent from `/sessions`. */
private readonly missingStreak = new Map<string, number>();
/** sidecar key (host::repoDir) → agentId currently reconciling that sidecar.
* The sidecar — and its /sessions snapshot — is scoped to host+dir, so two
* agents sharing a dir would double-poll it and race to adopt the same
- * conversation ids. One reconciler per sidecar; duplicates stop themselves. */
+ * session ids. One reconciler per sidecar; duplicates stop themselves. */
private readonly sidecarKeys = new Map<string, string>();
constructor() {
@@ -86,40 +86,40 @@ class RemoteSessionReconciler {
// sidecar and surfaced here (the owning provider has already torn down its
// PTY). Delete the local row + tombstone it so this client stops showing a
// ghost and the next reconcile tick cannot re-adopt it from a stale snapshot.
- conversationEvents.on('conversation:remote-terminated', ({ conversationId }) => {
- void this.handleRemoteTerminated(conversationId);
+ sessionHooks.on('session:remote-terminated', ({ terminatedSessionId }) => {
+ void this.handleRemoteTerminated(terminatedSessionId);
});
}
- private async handleRemoteTerminated(conversationId: string): Promise<void> {
- if (await this.removeLocalSession(conversationId)) {
- log.info('RemoteSessionReconciler: removed remotely-terminated session', { conversationId });
+ private async handleRemoteTerminated(sessionId: string): Promise<void> {
+ if (await this.removeLocalSession(sessionId)) {
+ log.info('RemoteSessionReconciler: removed remotely-terminated session', { sessionId });
}
}
/**
* Delete a session's local row, tombstone it (so the next reconcile tick cannot
* re-adopt it from a stale snapshot), drop it from the adopted/missing tracking,
- * and emit `conversation:deleted` so the UI updates. Returns false (and does not
+ * and emit `session:deleted` so the UI updates. Returns false (and does not
* emit) if the DB delete fails. Idempotent — deleting an already-gone row is a
* no-op. Shared by the `session-terminated` push and the vanished-session prune.
*/
- private async removeLocalSession(conversationId: string): Promise<boolean> {
- this.tombstone(conversationId);
- for (const ids of this.adopted.values()) ids.delete(conversationId);
- this.missingStreak.delete(conversationId);
+ private async removeLocalSession(sessionId: string): Promise<boolean> {
+ this.tombstone(sessionId);
+ for (const ids of this.adopted.values()) ids.delete(sessionId);
+ this.missingStreak.delete(sessionId);
let deleted: { changes: number };
let agentId: string | undefined;
try {
const [row] = await db
.select({ agentId: sessions.agentId })
.from(sessions)
- .where(eq(sessions.id, conversationId));
+ .where(eq(sessions.id, sessionId));
agentId = row?.agentId;
- deleted = await db.delete(sessions).where(eq(sessions.id, conversationId));
+ deleted = await db.delete(sessions).where(eq(sessions.id, sessionId));
} catch (error) {
log.warn('RemoteSessionReconciler: failed to delete session row', {
- conversationId,
+ sessionId,
error: String(error),
});
return false;
@@ -128,7 +128,7 @@ class RemoteSessionReconciler {
// `session-terminated`) still "succeeds", so gate the event + log on an
// actual row removal to avoid redundant deleted-events and log spam.
if (deleted.changes === 0) return false;
- conversationEvents._emit('conversation:deleted', conversationId);
+ sessionHooks._emit('session:deleted', sessionId);
// Tell the renderer to drop the row too. Unlike a user-initiated delete
// (the renderer removes it itself), this removal originates in the main
// process, so without an IPC event every attached window shows a ghost row
@@ -137,33 +137,33 @@ class RemoteSessionReconciler {
const projectId = agentId ? (await getAgentById(agentId))?.projectId : undefined;
if (projectId) {
log.info('RemoteSessionReconciler: notifying UI to remove session (remote-driven delete)', {
- conversationId,
+ sessionId,
projectId,
});
- events.emit(sessionDeletedChannel, { sessionId: conversationId, projectId });
+ events.emit(sessionDeletedChannel, { sessionId: sessionId, projectId });
} else {
log.warn(
'RemoteSessionReconciler: could not resolve projectId for removed session — sidebar row may linger until restart',
- { conversationId, agentId }
+ { sessionId, agentId }
);
}
return true;
}
/**
- * Refuse re-adoption of a conversation id for a short window after switchdash
+ * Refuse re-adoption of a session id for a short window after switchdash
* deletes it, closing the race where a reconcile tick re-adopts it from a stale
* sidecar `/sessions` snapshot before the delete's `/disconnect` lands.
*/
- tombstone(conversationId: string): void {
- this.tombstones.set(conversationId, Date.now() + TOMBSTONE_TTL_MS);
+ tombstone(sessionId: string): void {
+ this.tombstones.set(sessionId, Date.now() + TOMBSTONE_TTL_MS);
}
- private isTombstoned(conversationId: string): boolean {
- const expiry = this.tombstones.get(conversationId);
+ private isTombstoned(sessionId: string): boolean {
+ const expiry = this.tombstones.get(sessionId);
if (expiry === undefined) return false;
if (expiry <= Date.now()) {
- this.tombstones.delete(conversationId);
+ this.tombstones.delete(sessionId);
return false;
}
return true;
@@ -250,10 +250,10 @@ class RemoteSessionReconciler {
const conn = await connectRemoteAgent(agent);
const response = await this.fetchSessions(agent, conn);
const vmSessions = response.sessions ?? [];
- const vmIds = new Set(vmSessions.map((s) => s.conversationId));
+ const vmIds = new Set(vmSessions.map((s) => s.sessionId));
// Check adoption candidates against ALL local sessions, not just this
- // agent's: a conversation id is globally unique (it is the sessions PK),
+ // agent's: a session id is globally unique (it is the sessions PK),
// and the sidecar snapshot carries no agent attribution — another agent
// may legitimately own the row already.
const known = vmIds.size
@@ -267,9 +267,9 @@ class RemoteSessionReconciler {
)
: new Set<string>();
for (const vm of vmSessions) {
- if (known.has(vm.conversationId)) continue;
- if (this.isTombstoned(vm.conversationId)) continue;
- await this.adoptSession(agent, vm.conversationId, vm.roomId);
+ if (known.has(vm.sessionId)) continue;
+ if (this.isTombstoned(vm.sessionId)) continue;
+ await this.adoptSession(agent, vm.sessionId, vm.roomId);
}
await this.pruneVanished(agentId, vmIds);
@@ -321,7 +321,7 @@ class RemoteSessionReconciler {
if (await this.removeLocalSession(id)) {
log.info('RemoteSessionReconciler: pruned VM session no longer reported', {
agentId,
- conversationId: id,
+ sessionId: id,
});
}
}
@@ -384,18 +384,18 @@ class RemoteSessionReconciler {
}
/**
- * Create a switchdash session row whose id equals the VM's conversation id, so
+ * 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 spawning
* a fresh agent. No initial prompt — the agent is already connected to the room
* and processing the waiting message.
*/
private async adoptSession(
agent: Agent,
- conversationId: string,
+ sessionId: string,
roomId: string | null
): Promise<void> {
const result = await sessionService.createSession({
- id: conversationId,
+ id: sessionId,
agentId: agent.id,
title: roomId ? `Switch room ${roomId}` : 'Remote session',
autoApprove: true,
@@ -406,13 +406,13 @@ class RemoteSessionReconciler {
// between our snapshot and the insert — it is adopted, just not by us.
log.info('RemoteSessionReconciler: session row already exists — skipping adoption', {
agentId: agent.id,
- conversationId,
+ sessionId,
});
return;
}
log.warn('RemoteSessionReconciler: failed to adopt VM session', {
agentId: agent.id,
- conversationId,
+ sessionId,
roomId,
error: JSON.stringify(result.error),
});
@@ -422,10 +422,10 @@ class RemoteSessionReconciler {
// not session:provisioned — without the latter an open renderer leaves the
// session stuck "Setting up workspace…". provisionWorkspace is idempotent and
// emits the provisioned event the renderer needs.
- await sessionService.provisionWorkspace(conversationId).catch((error) => {
+ await sessionService.provisionWorkspace(sessionId).catch((error) => {
log.warn('RemoteSessionReconciler: post-adopt provision-reconcile failed', {
agentId: agent.id,
- conversationId,
+ sessionId,
error: String(error),
});
});
@@ -434,11 +434,11 @@ class RemoteSessionReconciler {
adoptedIds = new Set();
this.adopted.set(agent.id, adoptedIds);
}
- adoptedIds.add(conversationId);
- this.missingStreak.delete(conversationId);
+ adoptedIds.add(sessionId);
+ this.missingStreak.delete(sessionId);
log.info('RemoteSessionReconciler: adopted VM-spawned session', {
agentId: agent.id,
- conversationId,
+ sessionId,
roomId,
});
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
index c9dbca515..12016f1a7 100644
--- a/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remote-watcher.ts
@@ -1,6 +1,6 @@
import { DEEPLINK_SCHEME } from '@main/app/deeplinks';
-import { ensureAgentSidecar } from '@main/core/conversations/impl/ensure-agent-sidecar';
-import { writeWatchEnabled } from '@main/core/conversations/impl/remote-sidecar-launcher';
+import { ensureAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';
+import { writeWatchEnabled } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';
import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
import { log } from '@main/lib/logger';
import { connectRemoteAgent } from './connect-remote-agent';
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-events.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-events.ts
deleted file mode 100644
index a2ad03185..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-events.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { HookCore, type Hookable } from '@main/lib/hookable';
-import { log } from '@main/lib/logger';
-import type { Conversation } from '@shared/core/conversations/conversations';
-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-
-export type ConversationCrudHooks = {
- 'conversation:created': (conversation: Conversation) => void | Promise<void>;
- 'conversation:renamed': (
- conversationId: string,
- projectId: string,
- sessionId: string,
- newTitle: string
- ) => void | Promise<void>;
- 'conversation:deleted': (conversationId: string) => void | Promise<void>;
- /**
- * A remote session was deliberately terminated on another client (or this one)
- * and the sidecar broadcast a `session-terminated` event. The owning provider
- * has already torn down its local PTY/relay; this signals the DB-level cleanup
- * (delete the row, tombstone the id, emit `conversation:deleted`) so the ghost
- * row does not linger and get re-attached into a blank tmux session.
- */
- 'conversation:remote-terminated': (params: {
- projectId: string;
- sessionId: string;
- conversationId: string;
- }) => void | Promise<void>;
- /**
- * An agent PTY exited unexpectedly (i.e. not a deliberate stop). In-process
- * counterpart to the renderer-bound `agentSessionExitedChannel` — main-process
- * reactions must use this, since `events` only delivers main→renderer.
- */
- 'conversation:session-exited': (params: {
- conversationId: string;
- sessionId: string;
- }) => void | Promise<void>;
- 'conversation:input-submitted': (params: {
- projectId: string;
- sessionId: string;
- conversationId: string;
- providerId: AgentProviderId;
- }) => void | Promise<void>;
-};
-
-class ConversationEvents implements Hookable<ConversationCrudHooks> {
- private readonly _core = new HookCore<ConversationCrudHooks>((name, e) =>
- log.error(`ConversationEvents: ${String(name)} hook error`, e)
- );
-
- on<K extends keyof ConversationCrudHooks>(name: K, handler: ConversationCrudHooks[K]) {
- return this._core.on(name, handler);
- }
-
- _emit<K extends keyof ConversationCrudHooks>(
- name: K,
- ...args: Parameters<ConversationCrudHooks[K]>
- ): void {
- this._core.callHookBackground(name, ...args);
- }
-}
-
-export const conversationEvents = new ConversationEvents();
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.test.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.test.ts
deleted file mode 100644
index beb782f9b..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/conversation-session-supervisor.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import type { Pty } from '@main/core/pty/pty';
-import {
- CONVERSATION_FRESH_RECOVERY_GRACE_MS,
- MAX_CONVERSATION_RESUME_ATTEMPTS,
- ConversationSessionSupervisor,
-} from './conversation-session-supervisor';
-
-function fakePty(): Pty {
- return {
- write: vi.fn(),
- resize: vi.fn(),
- kill: vi.fn(),
- onData: vi.fn(),
- onExit: vi.fn(),
- };
-}
-
-describe('ConversationSessionSupervisor', () => {
- it('rejects and kills a spawn that returns after explicit stop invalidated its token', () => {
- const supervisor = new ConversationSessionSupervisor();
- const token = supervisor.beginStart('session-1');
- expect(token).toBeDefined();
-
- supervisor.stop('session-1');
-
- const pty = fakePty();
- expect(supervisor.acceptSpawn('session-1', token!, pty)).toBe(false);
- });
-
- it('falls back to a fresh replacement after one resume exit', () => {
- const supervisor = new ConversationSessionSupervisor();
- const initial = fakePty();
- const initialToken = supervisor.beginStart('session-1', { mode: 'fresh' });
- expect(supervisor.acceptSpawn('session-1', initialToken!, initial)).toBe(true);
-
- expect(supervisor.handleExit('session-1', initial)).toEqual({ kind: 'respawnResume' });
-
- for (let attempt = 1; attempt <= MAX_CONVERSATION_RESUME_ATTEMPTS; attempt += 1) {
- const pty = fakePty();
- const token = supervisor.beginStart('session-1', {
- requireDesired: true,
- mode: 'resume',
- });
- expect(supervisor.acceptSpawn('session-1', token!, pty)).toBe(true);
-
- const decision = supervisor.handleExit('session-1', pty);
- if (attempt < MAX_CONVERSATION_RESUME_ATTEMPTS) {
- expect(decision).toEqual({ kind: 'respawnResume' });
- } else {
- expect(decision).toEqual({ kind: 'respawnFresh' });
- }
- }
- });
-
- it('fails when a fresh recovery exits before the startup grace period', () => {
- const supervisor = new ConversationSessionSupervisor();
- const first = fakePty();
- const firstToken = supervisor.beginStart('session-1', { mode: 'resume' });
- expect(supervisor.acceptSpawn('session-1', firstToken!, first)).toBe(true);
-
- expect(supervisor.handleExit('session-1', first)).toEqual({ kind: 'respawnFresh' });
-
- const fresh = fakePty();
- const freshToken = supervisor.beginStart('session-1', {
- requireDesired: true,
- mode: 'fresh',
- });
- expect(supervisor.acceptSpawn('session-1', freshToken!, fresh)).toBe(true);
- expect(supervisor.handleExit('session-1', fresh)).toEqual({ kind: 'failed' });
- expect(supervisor.isDesired('session-1')).toBe(false);
- });
-
- it('resets recovery after a fresh replacement survives the startup grace period', () => {
- vi.useFakeTimers();
- try {
- const supervisor = new ConversationSessionSupervisor();
- const first = fakePty();
- const firstToken = supervisor.beginStart('session-1', { mode: 'resume' });
- expect(supervisor.acceptSpawn('session-1', firstToken!, first)).toBe(true);
-
- expect(supervisor.handleExit('session-1', first)).toEqual({ kind: 'respawnFresh' });
-
- const fresh = fakePty();
- const freshToken = supervisor.beginStart('session-1', {
- requireDesired: true,
- mode: 'fresh',
- });
- expect(supervisor.acceptSpawn('session-1', freshToken!, fresh)).toBe(true);
-
- vi.advanceTimersByTime(CONVERSATION_FRESH_RECOVERY_GRACE_MS);
- expect(supervisor.handleExit('session-1', fresh)).toEqual({ kind: 'respawnResume' });
-
- const retry = fakePty();
- const retryToken = supervisor.beginStart('session-1', {
- requireDesired: true,
- mode: 'resume',
- });
- expect(supervisor.acceptSpawn('session-1', retryToken!, retry)).toBe(true);
- expect(supervisor.handleExit('session-1', retry)).toEqual({ kind: 'respawnFresh' });
- } finally {
- vi.useRealTimers();
- }
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/createConversation.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/createConversation.ts
deleted file mode 100644
index 3e43fc5bc..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/createConversation.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { randomUUID } from 'node:crypto';
-import { and, eq, sql } from 'drizzle-orm';
-import { withCompensation } from '@main/core/utils/compensation';
-import { db } from '@main/db/client';
-import { agents, sessions } from '@main/db/schema';
-import { events } from '@main/lib/events';
-import { log } from '@main/lib/logger';
-import { conversationCreatedChannel } from '@shared/core/conversations/conversationEvents';
-import {
- type Conversation,
- type CreateConversationParams,
-} from '@shared/core/conversations/conversations';
-import { type AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-import { type AgentEvent } from '@shared/core/providers/agentEvents';
-import { agentHookService } from '../agent-hooks/agent-hook-service';
-import { isAppFocused } from '../agent-hooks/notification';
-import { resolveSession } from '../projects/utils';
-import { conversationEvents } from './conversation-events';
-import { mapSessionRowToConversation } from './utils';
-
-type ConversationCreateDb = Pick<typeof db, 'delete' | 'insert' | 'select'>;
-
-function emitInitialPromptStarted(
- conversation: Conversation,
- params: CreateConversationParams
-): void {
- if (!params.initialPrompt?.trim()) return;
-
- const agentEvent: AgentEvent = {
- type: 'start',
- source: 'input',
- providerId: params.provider,
- projectId: params.projectId,
- sessionId: params.sessionId,
- conversationId: conversation.id,
- timestamp: Date.now(),
- payload: {},
- };
- agentHookService.emitAgentEvent(agentEvent, isAppFocused());
-}
-
-/**
- * Resolves the agent that should own a new session, given the project and the
- * provider the renderer requested. A session belongs to exactly one agent; the
- * agent carries the provider, so we match on (projectId, providerId).
- */
-async function resolveAgentId(
- database: ConversationCreateDb,
- projectId: string,
- provider: AgentProviderId
-): Promise<string> {
- const [row] = await database
- .select({ id: agents.id })
- .from(agents)
- .where(and(eq(agents.projectId, projectId), eq(agents.providerId, provider)))
- .limit(1);
- if (!row) {
- throw new Error(`No agent for project ${projectId} with provider ${provider}`);
- }
- return row.id;
-}
-
-export async function createConversation(
- params: CreateConversationParams,
- database: ConversationCreateDb = db
-): Promise<Conversation> {
- const id = params.id ?? randomUUID();
- const agentId = await resolveAgentId(database, params.projectId, params.provider);
-
- const config = params.autoApprove === undefined ? undefined : { autoApprove: params.autoApprove };
-
- const [row] = await database
- .insert(sessions)
- .values({
- id,
- agentId,
- title: params.title,
- config,
- agentSessionId: id,
- isInitialSession: params.isInitialConversation ?? false,
- createdAt: sql`CURRENT_TIMESTAMP`,
- updatedAt: sql`CURRENT_TIMESTAMP`,
- lastInteractedAt: new Date().toISOString(),
- })
- .returning();
-
- const session = resolveSession(params.projectId, params.sessionId);
- if (!session) {
- throw new Error('Session not found');
- }
-
- const conversation = mapSessionRowToConversation(row, params.projectId, params.provider);
-
- await withCompensation({
- action: () =>
- session.conversations.startSession(
- conversation,
- params.initialSize,
- false,
- params.initialPrompt
- ),
- compensate: async () => {
- await database.delete(sessions).where(eq(sessions.id, row.id)).execute();
- },
- onCompensationError: (error) => {
- log.error('createConversation: failed to roll back session row after spawn failure', {
- conversationId: id,
- error: error instanceof Error ? error.message : String(error),
- });
- },
- });
-
- conversationEvents._emit('conversation:created', conversation);
- events.emit(conversationCreatedChannel, { conversation });
- emitInitialPromptStarted(conversation, params);
-
- return conversation;
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/dehydrateConversation.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/dehydrateConversation.ts
deleted file mode 100644
index ce6e671e2..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/dehydrateConversation.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { resolveSession } from '../projects/utils';
-
-export async function dehydrateConversation(
- projectId: string,
- sessionId: string,
- conversationId: string
-): Promise<void> {
- const session = resolveSession(projectId, sessionId);
- await session?.conversations.detachSession(conversationId);
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/deleteConversation.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/deleteConversation.ts
deleted file mode 100644
index 088202776..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/deleteConversation.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { remoteSessionReconciler } from '@main/core/agents/remote-session-reconciler';
-import { projectManager } from '@main/core/projects/project-manager';
-import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';
-import { db } from '@main/db/client';
-import { sessions } from '@main/db/schema';
-import { resolveSession } from '../projects/utils';
-import { conversationEvents } from './conversation-events';
-
-export async function deleteConversation(
- projectId: string,
- sessionId: string,
- conversationId: string
-): Promise<void> {
- await db.delete(sessions).where(eq(sessions.id, conversationId));
-
- // Refuse reconciler re-adoption of this id before the sidecar /disconnect
- // (sent below via stopSession) lands, so it can't recreate the ghost row.
- remoteSessionReconciler.tombstone(conversationId);
-
- conversationEvents._emit('conversation:deleted', conversationId);
-
- const session = resolveSession(projectId, sessionId);
- if (session) {
- await session.conversations.stopSession(conversationId);
- } else {
- const project = projectManager.getProject(projectId);
- if (project) {
- await killTmuxSession(project.ctx, makeAgentTmuxSessionName(conversationId));
- }
- }
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversations.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/getConversations.ts
deleted file mode 100644
index 2376bac2e..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversations.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { eq, isNull } from 'drizzle-orm';
-import { db } from '@main/db/client';
-import { agents, sessions } from '@main/db/schema';
-import { mapSessionRowToConversation } from './utils';
-
-export async function getConversations() {
- const rows = await db
- .select({ session: sessions, projectId: agents.projectId, providerId: agents.providerId })
- .from(sessions)
- .innerJoin(agents, eq(sessions.agentId, agents.id))
- .where(isNull(sessions.archivedAt));
- return rows.map(({ session, projectId, providerId }) =>
- mapSessionRowToConversation(session, projectId, providerId, false)
- );
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForProject.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForProject.ts
deleted file mode 100644
index 9229939cb..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForProject.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { db } from '@main/db/client';
-import { agents, sessions } from '@main/db/schema';
-import { mapSessionRowToConversation } from './utils';
-
-export async function getConversationsForProject(projectId: string) {
- const rows = await db
- .select({ session: sessions, providerId: agents.providerId })
- .from(sessions)
- .innerJoin(agents, eq(sessions.agentId, agents.id))
- .where(eq(agents.projectId, projectId));
- return rows.map(({ session, providerId }) =>
- mapSessionRowToConversation(session, projectId, providerId, false)
- );
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForSession.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForSession.ts
deleted file mode 100644
index 7e169443c..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/getConversationsForSession.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { loadSessionWithAgent } from './session-join';
-import { mapSessionRowToConversation } from './utils';
-
-export async function getConversationsForSession(_projectId: string, sessionId: string) {
- const loaded = await loadSessionWithAgent(sessionId);
- if (!loaded) return [];
- return [mapSessionRowToConversation(loaded.row, loaded.projectId, loaded.providerId, false)];
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/hydrateConversation.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/hydrateConversation.ts
deleted file mode 100644
index 66b7e16ed..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/hydrateConversation.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { db } from '@main/db/client';
-import { sessions } from '@main/db/schema';
-import { resolveSession } from '../projects/utils';
-import { loadSessionWithAgent } from './session-join';
-import { mapSessionRowToConversation } from './utils';
-
-export async function hydrateConversation(
- projectId: string,
- sessionId: string,
- conversationId: string
-): Promise<void> {
- const session = resolveSession(projectId, sessionId);
- if (!session) throw new Error('Session not found');
-
- const loaded = await loadSessionWithAgent(conversationId);
- if (!loaded) throw new Error('Conversation not found');
- const row = loaded.row;
-
- const isFirstSpawn = row.agentSessionId === null;
-
- if (isFirstSpawn) {
- // Write agent_session_id before spawning — idempotency guard against double-hydrate.
- await db
- .update(sessions)
- .set({ agentSessionId: conversationId })
- .where(eq(sessions.id, conversationId));
- }
-
- const config = row.config ?? {};
- const isResuming = !isFirstSpawn;
-
- await session.conversations.startSession(
- mapSessionRowToConversation(row, loaded.projectId, loaded.providerId, isResuming),
- undefined,
- isResuming,
- isFirstSpawn ? config.initialPrompt : undefined
- );
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/renameConversation.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/renameConversation.ts
deleted file mode 100644
index c12bbdd49..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/renameConversation.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { eq } from 'drizzle-orm';
-import { db } from '@main/db/client';
-import { sessions } from '@main/db/schema';
-import { MAX_CONVERSATION_TITLE_LENGTH } from '@shared/core/conversations/conversations';
-import { conversationEvents } from './conversation-events';
-import { loadSessionWithAgent } from './session-join';
-
-export async function renameConversation(conversationId: string, name: string) {
- const title = name.trim().slice(0, MAX_CONVERSATION_TITLE_LENGTH);
-
- const existing = await loadSessionWithAgent(conversationId);
-
- await db.update(sessions).set({ title }).where(eq(sessions.id, conversationId));
-
- if (existing) {
- conversationEvents._emit(
- 'conversation:renamed',
- conversationId,
- existing.projectId,
- conversationId,
- title
- );
- }
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.ts
deleted file mode 100644
index 546453919..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/resolve-agent-session-command.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { Conversation } from '@shared/core/conversations/conversations';
-
-/** Droid `--resume` needs the provider-native session UUID, not the Switchdash conversation id. */
-export function resolveAgentSessionCommandArgs(
- conversation: Conversation,
- isResuming: boolean,
- options: { requireProviderSessionId?: boolean } = {}
-): { sessionId: string; isResuming: boolean } {
- if ((conversation.providerId === 'codex' || conversation.providerId === 'droid') && isResuming) {
- if (conversation.providerSessionId) {
- return { sessionId: conversation.providerSessionId, isResuming: true };
- }
- if (options.requireProviderSessionId === false) {
- return { sessionId: conversation.id, isResuming };
- }
- return { sessionId: conversation.id, isResuming: false };
- }
-
- return { sessionId: conversation.id, isResuming };
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/types.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/types.ts
deleted file mode 100644
index fa5ddeb75..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/types.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { type Conversation } from '@shared/core/conversations/conversations';
-
-export interface ConversationProvider {
- startSession(
- conversation: Conversation,
- initialSize?: { cols: number; rows: number },
- isResuming?: boolean,
- initialPrompt?: string
- ): Promise<void>;
- detachSession(conversationId: string): Promise<void>;
- stopSession(conversationId: string): Promise<void>;
- destroyAll(): Promise<void>;
- detachAll(): Promise<void>;
-}
-
-export type ConversationConfig = {
- autoApprove?: boolean;
- /** Provider-native session id (e.g. Codex rollout UUID) used when resuming. */
- providerSessionId?: string;
-};
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/utils.ts b/dash/apps/switchdash-desktop/src/main/core/conversations/utils.ts
deleted file mode 100644
index 1f0305fc6..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/utils.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { type SessionRow } from '@main/db/schema';
-import { type Conversation } from '@shared/core/conversations/conversations';
-import { type AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-import { type AgentStatus } from '@shared/core/providers/agentEvents';
-
-/**
- * In switchdash a conversation IS a session (the old switchdash "conversation" was
- * renamed to "session"). `projectId` and `providerId` are denormalised from the
- * owning agent and must be supplied by the caller (which has joined `agents`).
- */
-export function mapSessionRowToConversation(
- row: SessionRow,
- projectId: string,
- providerId: AgentProviderId,
- resume: boolean = false
-): Conversation {
- const config = row.config ?? {};
- return {
- id: row.id,
- title: row.title,
- sessionId: row.id,
- projectId,
- providerId,
- autoApprove: config.autoApprove,
- providerSessionId: config.providerSessionId,
- subagentName: config.subagentName,
- resume: resume,
- lastInteractedAt: row.lastInteractedAt ?? null,
- isInitialConversation: row.isInitialSession,
- agentStatus: (row.agentStatus as AgentStatus | null) ?? null,
- agentStatusSeen: row.agentStatusSeen === 1,
- };
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/dependencies/dependency-managers.ts b/dash/apps/switchdash-desktop/src/main/core/dependencies/dependency-managers.ts
index 909954afd..fedb19feb 100644
--- a/dash/apps/switchdash-desktop/src/main/core/dependencies/dependency-managers.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/dependencies/dependency-managers.ts
@@ -1,5 +1,5 @@
import { HostDependencyManager, type DependencyId } from '@switchdash/core/deps/runtime';
-import { clearResolvedPathCache } from '@main/core/conversations/impl/resolve-agent-executable';
+import { clearResolvedPathCache } from '@main/core/agent-runtime/impl/resolve-agent-executable';
import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';
import { appSettingsService } from '@main/core/settings/settings-service';
import { resolveLocalAutomationShellWithSystemFallback } from '@main/core/terminal-shell/resolver';
diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts b/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts
index 1a6b62311..98b0334f4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/projects/project-provider.ts
@@ -5,16 +5,15 @@ import type { FileSystemProvider } from '@main/core/fs/types';
import type { MachineRef } from '@main/core/runtime/types';
import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';
import type { WorkspaceProviderData } from '@shared/core/workspaces/workspace-provider-data';
-import type { ConversationProvider } from '../conversations/types';
+import type { AgentRuntimeProvider } from '../agent-runtime/types';
import { sessionRuntimeManager } from '../sessions/session-runtime-manager';
-import type { TerminalProvider } from '../terminals/terminal-provider';
import type { WorkspaceType } from '../workspaces/workspace-factory';
import type { ProjectSettingsProvider } from './settings/provider';
export type { WorkspaceProviderData };
export type ProvisionResult = {
- sessionProvider: SessionProvider;
+ agent: AgentRuntimeProvider;
persistData: {
workspaceId: string;
workspaceProviderData?: WorkspaceProviderData;
@@ -22,14 +21,6 @@ export type ProvisionResult = {
};
};
-export interface SessionProvider {
- readonly sessionId: string;
- readonly sessionBranch: string | undefined;
- readonly sessionEnvVars: Record<string, string>;
- readonly conversations: ConversationProvider;
- readonly terminals: TerminalProvider;
-}
-
/**
* Transport-specific dependencies: the only things that differ between local and SSH.
* Pure data — no lifecycle methods.
diff --git a/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts b/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts
index df2b2b0e8..39872752e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/projects/utils.ts
@@ -1,8 +1,8 @@
import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';
import { sessionRuntimeManager } from '../sessions/session-runtime-manager';
-export function resolveSession(_projectId: string, sessionId: string) {
- return sessionRuntimeManager.getSession(sessionId) ?? null;
+export function resolveSessionAgent(_projectId: string, sessionId: string) {
+ return sessionRuntimeManager.getAgent(sessionId) ?? null;
}
export function resolveWorkspace(_projectId: string, workspaceId: string) {
diff --git a/dash/apps/switchdash-desktop/src/main/core/providers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/providers/controller.ts
index 2cdaaeb2c..0d89bece7 100644
--- a/dash/apps/switchdash-desktop/src/main/core/providers/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/providers/controller.ts
@@ -8,7 +8,7 @@ import type {
import type { ProviderCustomConfig } from '@shared/core/app-settings';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import { createRPCController } from '@shared/lib/ipc/rpc';
-import { clearResolvedPathCache } from '../conversations/impl/resolve-agent-executable';
+import { clearResolvedPathCache } from '../agent-runtime/impl/resolve-agent-executable';
import { agentUpdateService } from '../dependencies/agent-update-service';
import { getDependencyManager } from '../dependencies/dependency-managers';
import { hostDependencyStore } from '../dependencies/host-dependency-store';
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts b/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts
index 123195684..af3f040d9 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/controller.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { basename } from 'node:path';
import { err, ok } from '@switchdash/shared';
-import { conversationEvents } from '@main/core/conversations/conversation-events';
+import { sessionHooks } from '@main/core/sessions/session-hooks';
import { log } from '@main/lib/logger';
import { parsePtySessionId } from '@shared/core/pty/ptySessionId';
import { createRPCController } from '@shared/lib/ipc/rpc';
@@ -33,10 +33,9 @@ export const ptyController = createRPCController({
if (meta?.providerId && !meta.isRemote) {
const parsed = parsePtySessionId(sessionId);
if (parsed) {
- conversationEvents._emit('conversation:input-submitted', {
+ sessionHooks._emit('session:input-submitted', {
projectId: parsed.projectId,
sessionId: parsed.scopeId,
- conversationId: parsed.leafId,
providerId: meta.providerId,
});
}
@@ -85,45 +84,22 @@ export const ptyController = createRPCController({
},
/**
- * Stop a session for good without deleting its conversation/terminal record.
+ * Stop a lifecycle-script PTY for good. Lifecycle scripts never respawn, so
+ * a raw kill is sufficient and safe.
*
- * Unlike `kill`, which only terminates the OS process, this routes through
- * the owning provider so the session is removed from its respawn tracking
- * (`knownSessionIds`/`sessions`). A bare `kill` leaves those intact, so the
- * provider's `onExit` handler respawns the PTY ~500ms later — which is what
- * made killing from the resource monitor appear to do nothing. The tab and
- * its history are preserved; the session simply stays stopped until the session
- * is remounted or the user starts a new one.
+ * Agent PTYs are session lifecycle, not raw PTY I/O — stop those through
+ * `rpc.sessions.stopAgent` instead; this rejects them.
*/
stopSession: async (sessionId: string) => {
const parsed = parsePtySessionId(sessionId);
if (!parsed) return err({ type: 'invalid_session' as const });
- const { scopeId, leafId } = parsed;
- // Agents and terminals are scoped by session id, so the session lookup resolves
- // the owning provider. Conversation PTYs carry a providerId in their
- // registry metadata; plain terminals do not — that distinguishes the two.
- const session = sessionRuntimeManager.getSession(scopeId);
- if (session) {
- const isConversation = ptySessionRegistry.getMetadata(sessionId)?.providerId !== undefined;
- try {
- if (isConversation) {
- await session.conversations.stopSession(leafId);
- } else {
- await session.terminals.killTerminal(leafId);
- }
- } catch (e) {
- log.warn('ptyController.stopSession: error stopping session PTY', {
- sessionId,
- error: String(e),
- });
- return err({ type: 'stop_failed' as const, message: String((e as Error)?.message || e) });
- }
- return ok();
+ // Agent PTYs carry a providerId in their registry metadata; lifecycle
+ // scripts do not — that distinguishes the two.
+ if (ptySessionRegistry.getMetadata(sessionId)?.providerId !== undefined) {
+ return err({ type: 'invalid_session' as const });
}
- // Lifecycle scripts are scoped by workspace id (no session match) and never
- // respawn, so a raw kill is sufficient and safe.
const pty = ptySessionRegistry.get(sessionId);
if (pty) {
try {
@@ -142,7 +118,7 @@ export const ptyController = createRPCController({
* connected ssh2 client — no local ssh/scp binaries are involved.
*
* The session ID encodes the project and scope (`projectId:scopeId:leafId`),
- * where `scopeId` is a session ID for conversation uploads.
+ * where `scopeId` is a session ID for agent-session uploads.
*/
uploadFiles: async (args: { sessionId: string; localPaths: string[] }) => {
try {
@@ -152,8 +128,7 @@ export const ptyController = createRPCController({
}
const { scopeId } = parsed;
- const sessionProvider = sessionRuntimeManager.getSession(scopeId);
- if (!sessionProvider) return err({ type: 'not_ssh' as const });
+ if (!sessionRuntimeManager.getAgent(scopeId)) return err({ type: 'not_ssh' as const });
const workspaceId = sessionRuntimeManager.getWorkspaceId(scopeId) ?? '';
const workspace = workspaceRegistry.get(workspaceId);
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.test.ts b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.test.ts
index b5ce615b2..dd6b30f24 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.test.ts
@@ -158,7 +158,7 @@ describe('buildAgentEnv provider env forwarding', () => {
const { buildAgentEnv } = await loadPtyEnv();
const env = buildAgentEnv({
agentApiVars: false,
- hook: { port: 1234, ptyId: 'claude:conv-1', token: 'real-token' },
+ hook: { port: 1234, ptyId: 'claude:session-1', token: 'real-token' },
providerVars: {
ANTHROPIC_BASE_URL: 'https://example.test',
EDITOR: 'vim',
@@ -171,7 +171,7 @@ describe('buildAgentEnv provider env forwarding', () => {
expect(env.ANTHROPIC_BASE_URL).toBe('https://example.test');
expect(env.EDITOR).toBe('vim');
expect(env.SWITCHDASH_HOOK_PORT).toBe('1234');
- expect(env.SWITCHDASH_PTY_ID).toBe('claude:conv-1');
+ expect(env.SWITCHDASH_PTY_ID).toBe('claude:session-1');
expect(env.SWITCHDASH_HOOK_TOKEN).toBe('real-token');
});
@@ -180,7 +180,7 @@ describe('buildAgentEnv provider env forwarding', () => {
const managed = buildAgentEnv({
agentApiVars: false,
- hook: { port: 1234, ptyId: 'claude:conv-1', token: 'tok' },
+ hook: { port: 1234, ptyId: 'claude:session-1', token: 'tok' },
});
expect(managed.SWITCH_CHANNEL_DISABLE_POLL).toBe('1');
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts
index 9583c790d..3a88497f8 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/pty-env.ts
@@ -148,7 +148,7 @@ export interface AgentHookEnv {
* and stands the in-session Switch connector's own poll loop down so it does
* not race switchdash's poller on the bridge's destructive event queue.
*
- * Shared by `buildAgentEnv` (local) and the SSH conversation provider (remote)
+ * Shared by `buildAgentEnv` (local) and the SSH agent runtime (remote)
* so the hook wiring — including the no-double-delivery gate — lives in one
* place.
*/
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/spawn-utils.test.ts b/dash/apps/switchdash-desktop/src/main/core/pty/spawn-utils.test.ts
index 7c79b1638..664330e3e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/spawn-utils.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/spawn-utils.test.ts
@@ -8,10 +8,9 @@ import { resolveSshCommand } from './spawn-utils';
function makeAgentConfig(overrides: Partial<AgentSessionConfig> = {}): AgentSessionConfig {
return {
sessionId: 'session-1',
- conversationId: 'conv-1',
providerId: 'claude',
command: 'claude',
- args: ['--resume', 'conv-1'],
+ args: ['--resume', 'session-1'],
cwd: '/workspace',
autoApprove: false,
resume: false,
@@ -93,7 +92,7 @@ describe('resolveSshCommand', () => {
const result = resolveSshCommand('agent', makeAgentConfig(), undefined, zshProfile);
expect(result).toBe(
- `'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''conv-1'\\'''`
+ `'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''session-1'\\'''`
);
});
@@ -108,7 +107,7 @@ describe('resolveSshCommand', () => {
);
expect(result).toBe(
- `'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; export FOO='\\''bar'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''conv-1'\\'''`
+ `'/bin/zsh' -lc 'export PATH='\\''/Users/jona/.local/bin:/opt/homebrew/bin:/usr/bin'\\''; export FOO='\\''bar'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''session-1'\\'''`
);
});
@@ -118,7 +117,7 @@ describe('resolveSshCommand', () => {
});
expect(result).toBe(
- `'/bin/sh' -c 'export FOO='\\''bar'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''conv-1'\\'''`
+ `'/bin/sh' -c 'export FOO='\\''bar'\\''; cd "/workspace" && '\\''claude'\\'' '\\''--resume'\\'' '\\''session-1'\\'''`
);
});
@@ -133,7 +132,7 @@ describe('resolveSshCommand', () => {
);
expect(result).toBe(
- `'/bin/sh' -c 'export PATH='\\''/usr/bin'\\''; cd "/workspace" && export FOO=bar && '\\''claude'\\'' '\\''--resume'\\'' '\\''conv-1'\\'''`
+ `'/bin/sh' -c 'export PATH='\\''/usr/bin'\\''; cd "/workspace" && export FOO=bar && '\\''claude'\\'' '\\''--resume'\\'' '\\''session-1'\\'''`
);
});
@@ -167,7 +166,7 @@ describe('resolveSshCommand', () => {
expect(result).toContain('tmux -u new-session -d -s \\"agent-session\\"');
expect(result).toContain('tmux -u attach-session -t \\"=agent-session\\"');
expect(result).toContain('/bin/sh -c');
- expect(result).toContain("'\\''claude'\\'' '\\''--resume'\\'' '\\''conv-1'\\''");
+ expect(result).toContain("'\\''claude'\\'' '\\''--resume'\\'' '\\''session-1'\\''");
});
it('launches remote general terminals with the captured remote shell', () => {
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts
index bfbe6e4e6..db5e9de60 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.test.ts
@@ -58,34 +58,30 @@ describe('buildTmuxShellLine', () => {
});
describe('makeAgentTmuxSessionName', () => {
- const conversationId = 'c1fc96ca-d642-4a5e-a392-8205391e2d11';
+ const sessionId = 'c1fc96ca-d642-4a5e-a392-8205391e2d11';
- it('derives the pane name from the conversationId alone (no projectId/scopeId)', () => {
+ it('derives the pane name from the sessionId alone (no projectId)', () => {
// The core CHOO-1181 guarantee: two switchdash clients with DIFFERENT local
// projectIds/scopeIds must compute the SAME tmux name for the same shared
- // conversation, so they attach to one pane instead of each spawning a blank
- // one. So the name must be a pure function of the conversationId.
- const name = makeAgentTmuxSessionName(conversationId);
+ // session, so they attach to one pane instead of each spawning a blank
+ // one. So the name must be a pure function of the sessionId.
+ const name = makeAgentTmuxSessionName(sessionId);
expect(name).toBe(
- `switchdash-${Buffer.from(`conv-${conversationId}`, 'utf8').toString('base64url')}`
+ `switchdash-${Buffer.from(`session-${sessionId}`, 'utf8').toString('base64url')}`
);
});
it('matches the sidecar (VM) derivation so a client attaches to the sidecar-spawned pane', () => {
- expect(makeAgentTmuxSessionName(conversationId)).toBe(
- makeSidecarAgentTmuxSessionName(conversationId)
- );
+ expect(makeAgentTmuxSessionName(sessionId)).toBe(makeSidecarAgentTmuxSessionName(sessionId));
});
it('round-trips through parseAgentTmuxSessionName (lets the sidecar enumerate panes)', () => {
- expect(parseAgentTmuxSessionName(makeAgentTmuxSessionName(conversationId))).toBe(
- conversationId
- );
+ expect(parseAgentTmuxSessionName(makeAgentTmuxSessionName(sessionId))).toBe(sessionId);
});
it('parseAgentTmuxSessionName ignores non-agent tmux sessions', () => {
expect(parseAgentTmuxSessionName('switchdash-sidecar-320390b87bfaee19')).toBeNull();
- // A terminal / legacy pane whose decoded payload is not `conv-<id>`.
+ // A terminal / legacy pane whose decoded payload is not `session-<id>`.
expect(
parseAgentTmuxSessionName(
`switchdash-${Buffer.from('proj:scope:leaf').toString('base64url')}`
diff --git a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts
index fa63796c2..5097d3ea4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/pty/tmux-session-name.ts
@@ -64,17 +64,17 @@ export function makeTmuxSessionName(sessionId: string): string {
}
/**
- * tmux session name for an AGENT conversation's pane, derived from the
- * conversationId alone. The conversationId is minted once (by whichever client
- * or the VM sidecar starts the session) and is shared verbatim across every
- * switchdash client and the sidecar, so all of them compute the identical tmux
- * name and attach to the SAME pane — enabling concurrent multi-client access
- * (CHOO-1181). It must NOT fold in projectId/scopeId: those are switchdash-
- * instance-local ids that differ per client, which would give each client a
- * different pane name and silently spawn a fresh blank session on attach.
+ * tmux session name for an AGENT's pane, derived from the session id alone.
+ * The session id is minted once (by whichever client or the VM sidecar starts
+ * the session) and is shared verbatim across every switchdash client and the
+ * sidecar, so all of them compute the identical tmux name and attach to the
+ * SAME pane — enabling concurrent multi-client access (CHOO-1181). It must NOT
+ * fold in projectId: that is a switchdash-instance-local id that differs per
+ * client, which would give each client a different pane name and silently
+ * spawn a fresh blank session on attach.
*/
-export function makeAgentTmuxSessionName(conversationId: string): string {
- return makeTmuxSessionName(`conv-${conversationId}`);
+export function makeAgentTmuxSessionName(sessionId: string): string {
+ return makeTmuxSessionName(`session-${sessionId}`);
}
export async function killTmuxSession(ctx: IExecutionContext, sessionName: string): Promise<void> {
diff --git a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts
index 551180ff2..336213183 100644
--- a/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/resource-monitor/resource-sampler.test.ts
@@ -82,7 +82,7 @@ describe('resource sampler', () => {
setPlatform('linux');
registryState.active = [
{
- sessionId: 'project-1:session-1:conversation-1',
+ sessionId: 'project-1:session-1',
pid: 100,
metadata: { providerId: 'amp', title: 'Amp' },
},
@@ -111,7 +111,7 @@ describe('resource sampler', () => {
expect(pidusageMock).toHaveBeenCalledWith([100, 101, 102]);
expect(snapshot.entries).toHaveLength(1);
expect(snapshot.entries[0]).toMatchObject({
- sessionId: 'project-1:session-1:conversation-1',
+ sessionId: 'project-1:session-1',
pid: 100,
ppid: 1,
cpu: 7,
@@ -142,12 +142,12 @@ describe('resource sampler', () => {
it('attributes separate process trees to separate active sessions', async () => {
registryState.active = [
{
- sessionId: 'project-1:session-1:conversation-1',
+ sessionId: 'project-1:session-1',
pid: 100,
metadata: { providerId: 'amp', title: 'Amp 1' },
},
{
- sessionId: 'project-2:session-2:conversation-2',
+ sessionId: 'project-2:session-2',
pid: 200,
metadata: { providerId: 'amp', title: 'Amp 2' },
},
@@ -166,7 +166,7 @@ describe('resource sampler', () => {
expect(pidusageMock).toHaveBeenCalledWith([100, 102, 101, 200, 201]);
expect(snapshot.entries).toHaveLength(2);
expect(snapshot.entries[0]).toMatchObject({
- sessionId: 'project-1:session-1:conversation-1',
+ sessionId: 'project-1:session-1',
pid: 100,
ppid: 1,
cpu: 6,
@@ -174,7 +174,7 @@ describe('resource sampler', () => {
title: 'Amp 1',
});
expect(snapshot.entries[1]).toMatchObject({
- sessionId: 'project-2:session-2:conversation-2',
+ sessionId: 'project-2:session-2',
pid: 200,
ppid: 1,
cpu: 9,
diff --git a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts b/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
index 164c3b7af..93b55c947 100644
--- a/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/search/search-service.ts
@@ -3,12 +3,11 @@ import { db, sqlite } from '@main/db/client';
import { agents, projects, sessions } from '@main/db/schema';
import { log } from '@main/lib/logger';
import { ALL_COMMAND_DEFS } from '@shared/commands';
-import type { Conversation } from '@shared/core/conversations/conversations';
import type { CommandPaletteQuery, SearchItem, SearchItemKind } from '@shared/core/search';
import type { Session } from '@shared/core/sessions/sessions';
import type { Project } from '@shared/projects';
-import { conversationEvents } from '../conversations/conversation-events';
import { projectEvents } from '../projects/project-events';
+import { sessionHooks } from '../sessions/session-hooks';
import { sessionService } from '../sessions/session-service';
import { workspaceFileIndexService } from './workspace-file-index-service';
@@ -22,16 +21,9 @@ type FtsRow = {
};
type RecentSessionRow = {
- id: string;
- name: string;
- project_id: string;
-};
-
-type RecentConversationRow = {
id: string;
title: string;
project_id: string;
- session_id: string;
};
class SearchService {
@@ -40,23 +32,13 @@ class SearchService {
sessionService.on('session:updated', (session) => this.upsertSession(session));
sessionService.on('session:archived', (sessionId) => this.removeByType('session', sessionId));
sessionService.on('session:deleted', (sessionId) => this.removeByType('session', sessionId));
+ // Row deletions outside the sessionService path (e.g. the remote-session
+ // reconciler pruning a VM session) must also leave the index.
+ sessionHooks.on('session:deleted', (sessionId) => this.removeByType('session', sessionId));
projectEvents.on('project:created', (project) => this.upsertProject(project));
projectEvents.on('project:deleted', (projectId) => this.removeByType('project', projectId));
- conversationEvents.on('conversation:created', (conversation) =>
- this.upsertConversation(conversation)
- );
- conversationEvents.on(
- 'conversation:renamed',
- (conversationId, projectId, sessionId, newTitle) => {
- this.upsertConversationById(conversationId, projectId, sessionId, newTitle);
- }
- );
- conversationEvents.on('conversation:deleted', (conversationId) =>
- this.removeByType('conversation', conversationId)
- );
-
this.backfill();
this.seedCommands();
}
@@ -78,29 +60,15 @@ class SearchService {
let rows: FtsRow[];
try {
- if (context?.sessionId) {
- rows = sqlite
- .prepare(
- `SELECT item_type, item_id, project_id, session_id, title, bm25(search_index) AS rank
- FROM search_index
- WHERE search_index MATCH ?
- AND (item_type != 'conversation' OR session_id = ?)
- ORDER BY rank
- LIMIT 30`
- )
- .all(ftsQuery, context.sessionId) as FtsRow[];
- } else {
- rows = sqlite
- .prepare(
- `SELECT item_type, item_id, project_id, session_id, title, bm25(search_index) AS rank
- FROM search_index
- WHERE search_index MATCH ?
- AND item_type != 'conversation'
- ORDER BY rank
- LIMIT 30`
- )
- .all(ftsQuery) as FtsRow[];
- }
+ rows = sqlite
+ .prepare(
+ `SELECT item_type, item_id, project_id, session_id, title, bm25(search_index) AS rank
+ FROM search_index
+ WHERE search_index MATCH ?
+ ORDER BY rank
+ LIMIT 30`
+ )
+ .all(ftsQuery) as FtsRow[];
} catch (e) {
log.warn('SearchService: FTS query failed', { query, error: String(e) });
return [];
@@ -137,59 +105,41 @@ class SearchService {
private recents(context?: CommandPaletteQuery['context']): SearchItem[] {
const sessionStmt = context?.projectId
? sqlite.prepare(
- `SELECT t.id, t.name, t.project_id
- FROM sessions t
- WHERE t.archived_at IS NULL AND t.project_id = ?
- ORDER BY t.last_interacted_at DESC
+ `SELECT s.id, s.title, a.project_id
+ FROM sessions s
+ JOIN agents a ON a.id = s.agent_id
+ WHERE s.archived_at IS NULL AND a.project_id = ?
+ ORDER BY s.last_interacted_at DESC
LIMIT 10`
)
: sqlite.prepare(
- `SELECT t.id, t.name, t.project_id
- FROM sessions t
- WHERE t.archived_at IS NULL
- ORDER BY t.last_interacted_at DESC
+ `SELECT s.id, s.title, a.project_id
+ FROM sessions s
+ JOIN agents a ON a.id = s.agent_id
+ WHERE s.archived_at IS NULL
+ ORDER BY s.last_interacted_at DESC
LIMIT 10`
);
- const sessionRows = (
- context?.projectId ? sessionStmt.all(context.projectId) : sessionStmt.all()
- ) as RecentSessionRow[];
+ let sessionRows: RecentSessionRow[];
+ try {
+ sessionRows = (
+ context?.projectId ? sessionStmt.all(context.projectId) : sessionStmt.all()
+ ) as RecentSessionRow[];
+ } catch (e) {
+ log.warn('SearchService: recents query failed', { error: String(e) });
+ return [];
+ }
- const results: SearchItem[] = sessionRows.map((r) => ({
+ return sessionRows.map((r) => ({
kind: 'session' as const,
id: r.id,
projectId: r.project_id,
sessionId: null,
- title: r.name,
+ title: r.title,
subtitle: '',
score: 0,
}));
-
- if (context?.sessionId) {
- const conversationRows = sqlite
- .prepare(
- `SELECT c.id, c.title, c.project_id, c.session_id
- FROM conversations c
- WHERE c.session_id = ?
- ORDER BY c.last_interacted_at DESC
- LIMIT 10`
- )
- .all(context.sessionId) as RecentConversationRow[];
-
- for (const r of conversationRows) {
- results.push({
- kind: 'conversation',
- id: r.id,
- projectId: r.project_id,
- sessionId: r.session_id,
- title: r.title,
- subtitle: '',
- score: 0,
- });
- }
- }
-
- return results;
}
private upsertSession(session: Session): void {
@@ -227,43 +177,6 @@ class SearchService {
}
}
- private upsertConversation(conversation: Conversation): void {
- try {
- sqlite
- .prepare(
- `INSERT OR REPLACE INTO search_index(item_type, item_id, project_id, session_id, title, keywords)
- VALUES ('conversation', ?, ?, ?, ?, '')`
- )
- .run(conversation.id, conversation.projectId, conversation.sessionId, conversation.title);
- } catch (e) {
- log.warn('SearchService: upsertConversation failed', {
- conversationId: conversation.id,
- error: String(e),
- });
- }
- }
-
- private upsertConversationById(
- conversationId: string,
- projectId: string,
- sessionId: string,
- title: string
- ): void {
- try {
- sqlite
- .prepare(
- `INSERT OR REPLACE INTO search_index(item_type, item_id, project_id, session_id, title, keywords)
- VALUES ('conversation', ?, ?, ?, ?, '')`
- )
- .run(conversationId, projectId, sessionId, title);
- } catch (e) {
- log.warn('SearchService: upsertConversationById failed', {
- conversationId,
- error: String(e),
- });
- }
- }
-
private removeByType(itemType: string, itemId: string): void {
try {
sqlite
@@ -320,9 +233,7 @@ class SearchService {
sqlite.transaction(() => {
for (const t of allSessions) {
if (t.archivedAt) continue;
- // A session is also its own conversation (1:1) in switchdash.
upsertStmt.run('session', t.id, t.projectId, null, t.title, '');
- upsertStmt.run('conversation', t.id, t.projectId, t.id, t.title, '');
}
for (const p of allProjects) {
upsertStmt.run('project', p.id, null, null, p.name, p.path);
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts
index 3cfd4fbaf..ded64abd9 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/controller.ts
@@ -1,28 +1,17 @@
-import { createConversation } from '@main/core/conversations/createConversation';
-import { dehydrateConversation } from '@main/core/conversations/dehydrateConversation';
-import { deleteConversation } from '@main/core/conversations/deleteConversation';
-import { getConversations } from '@main/core/conversations/getConversations';
-import { getConversationsForProject } from '@main/core/conversations/getConversationsForProject';
-import { getConversationsForSession } from '@main/core/conversations/getConversationsForSession';
-import { hydrateConversation } from '@main/core/conversations/hydrateConversation';
-import { markConversationSeen } from '@main/core/conversations/markConversationSeen';
-import { renameConversation } from '@main/core/conversations/renameConversation';
import type { CreateSessionParams, SessionLifecycleStatus } from '@shared/core/sessions/sessions';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { generateSessionName } from './name-generation/generateSessionName';
+import { dehydrateSession } from './operations/dehydrateSession';
+import { getSession } from './operations/getSession';
+import { hydrateSession } from './operations/hydrateSession';
+import { markSessionSeen } from './operations/markSessionSeen';
import { sessionService } from './session-service';
export const sessionController = createRPCController({
- // Ex-conversation engine ops (a conversation is a session in switchdash).
- getConversations,
- createConversation,
- deleteConversation,
- hydrateConversation,
- dehydrateConversation,
- renameConversation,
- getConversationsForSession,
- getConversationsForProject,
- markConversationSeen,
+ getSession,
+ hydrateSession,
+ dehydrateSession,
+ markSessionSeen,
async createSession(params: CreateSessionParams) {
return sessionService.createSession(params);
},
@@ -53,6 +42,9 @@ export const sessionController = createRPCController({
async teardownSession(_projectId: string, sessionId: string) {
return sessionService.teardown(sessionId, 'terminate');
},
+ async stopAgent(sessionId: string) {
+ return sessionService.stopAgent(sessionId);
+ },
async provisionWorkspace(sessionId: string) {
return sessionService.provisionWorkspace(sessionId);
},
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts
index d9781e870..a17062e36 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.test.ts
@@ -85,7 +85,7 @@ describe('createSession', () => {
mocks.provisionSessionRuntime.mockResolvedValue({
path: '/repo',
workspaceId: 'project-1',
- sessionProvider: { conversations: { startSession: mocks.startSession } },
+ agent: { start: mocks.startSession },
});
mocks.registerSession.mockResolvedValue(undefined);
mocks.startSession.mockResolvedValue(undefined);
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts
index 166c67dde..da68a8dc0 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/createSession.ts
@@ -1,11 +1,10 @@
import { err, ok, type Result } from '@switchdash/shared';
import { eq, sql } from 'drizzle-orm';
import { getAgentById } from '@main/core/agents/getAgentById';
-import { mapSessionRowToConversation } from '@main/core/conversations/utils';
import { projectManager } from '@main/core/projects/project-manager';
import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
-import type { ConversationConfig } from '@shared/core/conversations/conversation-config';
+import type { SessionConfig } from '@shared/core/sessions/session-config';
import type {
CreateSessionError,
CreateSessionSuccess,
@@ -30,7 +29,7 @@ export async function createSession(
const project = projectManager.getProject(agent.projectId);
if (!project) return err({ type: 'agent-not-found' });
- const configObj: ConversationConfig = {};
+ const configObj: SessionConfig = {};
if (params.autoApprove !== undefined) configObj.autoApprove = params.autoApprove;
if (params.initialPrompt?.trim()) configObj.initialPrompt = params.initialPrompt.trim();
if (params.subagentName?.trim()) configObj.subagentName = params.subagentName.trim();
@@ -55,7 +54,7 @@ export async function createSession(
.returning();
// Callers with externally-minted ids (the remote session reconciler adopting
- // a VM conversation) can race another creator for the same id — surface that
+ // a VM session) can race another creator for the same id — surface that
// as a Result instead of a raw UNIQUE-constraint throw.
if (!row) return err({ type: 'already-exists' });
@@ -65,13 +64,7 @@ export async function createSession(
const built = await provisionSessionRuntime(session, project);
await sessionRuntimeManager.registerSession(session.id, built, project.projectId, project.ctx);
- const conversation = mapSessionRowToConversation(row, project.projectId, agent.providerId);
- await built.sessionProvider.conversations.startSession(
- conversation,
- params.initialSize,
- false,
- params.initialPrompt
- );
+ await built.agent.start(session, params.initialSize, false, params.initialPrompt);
} catch (e) {
await db.delete(sessions).where(eq(sessions.id, params.id));
return err({ type: 'spawn-failed', message: e instanceof Error ? e.message : String(e) });
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts
new file mode 100644
index 000000000..289fce4d3
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/dehydrateSession.ts
@@ -0,0 +1,6 @@
+import { resolveSessionAgent } from '../../projects/utils';
+
+export async function dehydrateSession(projectId: string, sessionId: string): Promise<void> {
+ const agent = resolveSessionAgent(projectId, sessionId);
+ await agent?.dehydrate();
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts
new file mode 100644
index 000000000..3b2318093
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/getSession.ts
@@ -0,0 +1,9 @@
+import { type Session } from '@shared/core/sessions/sessions';
+import { loadSessionWithAgent } from '../session-join';
+import { mapSessionRowToSession } from '../utils/utils';
+
+export async function getSession(sessionId: string): Promise<Session | null> {
+ const loaded = await loadSessionWithAgent(sessionId);
+ if (!loaded) return null;
+ return mapSessionRowToSession(loaded.row, loaded.providerId);
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts
new file mode 100644
index 000000000..b987a5cb0
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/hydrateSession.ts
@@ -0,0 +1,32 @@
+import { eq } from 'drizzle-orm';
+import { db } from '@main/db/client';
+import { sessions } from '@main/db/schema';
+import { resolveSessionAgent } from '../../projects/utils';
+import { loadSessionWithAgent } from '../session-join';
+import { mapSessionRowToSession } from '../utils/utils';
+
+export async function hydrateSession(projectId: string, sessionId: string): Promise<void> {
+ const agent = resolveSessionAgent(projectId, sessionId);
+ if (!agent) throw new Error('Session not found');
+
+ const loaded = await loadSessionWithAgent(sessionId);
+ if (!loaded) throw new Error('Session row not found');
+ const row = loaded.row;
+
+ const isFirstSpawn = row.agentSessionId === null;
+
+ if (isFirstSpawn) {
+ // Write agent_session_id before spawning — idempotency guard against double-hydrate.
+ await db.update(sessions).set({ agentSessionId: sessionId }).where(eq(sessions.id, sessionId));
+ }
+
+ const config = row.config ?? {};
+ const isResuming = !isFirstSpawn;
+
+ await agent.start(
+ mapSessionRowToSession(row, loaded.providerId),
+ undefined,
+ isResuming,
+ isFirstSpawn ? config.initialPrompt : undefined
+ );
+}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/markConversationSeen.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/markSessionSeen.ts
similarity index 61%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/markConversationSeen.ts
rename to dash/apps/switchdash-desktop/src/main/core/sessions/operations/markSessionSeen.ts
index bfcec05ae..b7fe46228 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/markConversationSeen.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/markSessionSeen.ts
@@ -2,6 +2,6 @@ import { eq } from 'drizzle-orm';
import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
-export async function markConversationSeen(conversationId: string): Promise<void> {
- await db.update(sessions).set({ agentStatusSeen: 1 }).where(eq(sessions.id, conversationId));
+export async function markSessionSeen(sessionId: string): Promise<void> {
+ await db.update(sessions).set({ agentStatusSeen: 1 }).where(eq(sessions.id, sessionId));
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/save-provider-session-id.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts
similarity index 62%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/save-provider-session-id.ts
rename to dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts
index 84ca01204..7a1513efe 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/save-provider-session-id.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/save-provider-session-id.ts
@@ -3,23 +3,23 @@ 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 { isDroidProviderSessionId } from '@shared/core/conversations/conversation-config';
-import { conversationChangedChannel } from '@shared/core/conversations/conversationEvents';
-import { loadSessionWithAgent } from './session-join';
+import { isDroidProviderSessionId } from '@shared/core/sessions/session-config';
+import { sessionChangedChannel } from '@shared/core/sessions/sessionEvents';
+import { loadSessionWithAgent } from '../session-join';
export async function saveProviderSessionId(
- conversationId: string,
+ sessionId: string,
providerSessionId: string
): Promise<void> {
if (!isDroidProviderSessionId(providerSessionId)) {
log.warn('saveProviderSessionId: ignored invalid Droid session id', {
- conversationId,
+ sessionId,
providerSessionId,
});
return;
}
- const loaded = await loadSessionWithAgent(conversationId);
+ const loaded = await loadSessionWithAgent(sessionId);
if (!loaded) return;
const config = loaded.row.config ?? {};
@@ -28,11 +28,10 @@ export async function saveProviderSessionId(
await db
.update(sessions)
.set({ config: { ...config, providerSessionId }, updatedAt: new Date().toISOString() })
- .where(eq(sessions.id, conversationId));
+ .where(eq(sessions.id, sessionId));
- events.emit(conversationChangedChannel, {
- conversationId,
- sessionId: conversationId,
+ events.emit(sessionChangedChannel, {
+ sessionId,
projectId: loaded.projectId,
changes: { providerSessionId },
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/set-provider-session-id.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/set-provider-session-id.ts
similarity index 84%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/set-provider-session-id.ts
rename to dash/apps/switchdash-desktop/src/main/core/sessions/operations/set-provider-session-id.ts
index 14b61e1cb..77ad645fe 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/set-provider-session-id.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/set-provider-session-id.ts
@@ -3,7 +3,7 @@ import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
export async function setProviderSessionId(
- conversationId: string,
+ sessionId: string,
providerSessionId: string
): Promise<boolean> {
const trimmed = providerSessionId.trim();
@@ -12,7 +12,7 @@ export async function setProviderSessionId(
const [row] = await db
.select({ config: sessions.config })
.from(sessions)
- .where(eq(sessions.id, conversationId))
+ .where(eq(sessions.id, sessionId))
.limit(1);
if (!row) return false;
@@ -23,7 +23,7 @@ export async function setProviderSessionId(
await db
.update(sessions)
.set({ config: { ...config, providerSessionId: trimmed } })
- .where(eq(sessions.id, conversationId));
+ .where(eq(sessions.id, sessionId));
return true;
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/touchConversation.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/touchSession.ts
similarity index 56%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/touchConversation.ts
rename to dash/apps/switchdash-desktop/src/main/core/sessions/operations/touchSession.ts
index ab05ff51a..26710e9d5 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/touchConversation.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/operations/touchSession.ts
@@ -2,9 +2,6 @@ import { eq } from 'drizzle-orm';
import { db } from '@main/db/client';
import { sessions } from '@main/db/schema';
-export async function touchConversation(
- conversationId: string,
- lastInteractedAt: string
-): Promise<void> {
- await db.update(sessions).set({ lastInteractedAt }).where(eq(sessions.id, conversationId));
+export async function touchSession(sessionId: string, lastInteractedAt: string): Promise<void> {
+ await db.update(sessions).set({ lastInteractedAt }).where(eq(sessions.id, sessionId));
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts
index 67e4c210e..59b66197b 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-builder.ts
@@ -1,6 +1,4 @@
import { getAgentById } from '@main/core/agents/getAgentById';
-import type { ConversationProvider } from '@main/core/conversations/types';
-import type { TerminalProvider } from '@main/core/terminals/terminal-provider';
import { resolveAgentWorkspace } from '@main/core/workspaces/resolve-agent-workspace';
import type { Workspace } from '@main/core/workspaces/workspace';
import { workspaceRegistry } from '@main/core/workspaces/workspace-registry';
@@ -10,10 +8,11 @@ import {
type ProvisionStep,
} from '@shared/core/sessions/sessionEvents';
import type { Session } from '@shared/core/sessions/sessions';
-import type { ProjectProvider, SessionProvider } from '../projects/project-provider';
+import type { AgentRuntimeProvider } from '../agent-runtime/types';
+import type { ProjectProvider } from '../projects/project-provider';
import type { ProjectSettingsProvider } from '../projects/settings/provider';
import {
- buildSessionProviders,
+ buildAgentRuntime,
createWorkspaceFactory,
resolveSessionEnv,
type WorkspaceType,
@@ -29,13 +28,13 @@ export type SessionRuntimeResult = {
path: string;
workspaceId: string;
worktreeGitDir?: string;
- sessionProvider: SessionProvider;
+ agent: AgentRuntimeProvider;
};
/**
* Provisions the runtime for a session: acquires the project-dir workspace
* (running lifecycle scripts once per project dir) and builds the session's
- * conversation + terminal providers in the project root.
+ * agent runtime in the project root.
*/
export async function provisionSessionRuntime(
session: Session,
@@ -83,7 +82,7 @@ export async function provisionSessionRuntime(
let buildSucceeded = false;
try {
- const buildResult = await buildSessionFromWorkspace(
+ const runtime = await buildSessionFromWorkspace(
session,
workspace,
type,
@@ -96,7 +95,7 @@ export async function provisionSessionRuntime(
path: workDir,
workspaceId,
worktreeGitDir: undefined,
- sessionProvider: buildResult.sessionProvider,
+ agent: runtime,
};
} finally {
if (!buildSucceeded) {
@@ -115,18 +114,9 @@ export function emitSessionProvisionProgress(data: {
sessionProvisionEvents.emitProgress(data);
}
-export type BuildSessionResult = {
- sessionProvider: SessionProvider;
- conversationProvider: ConversationProvider;
- terminalProvider: TerminalProvider;
-};
-
/**
- * Shared tail of the provision flow — builds a SessionProvider from an already-acquired
- * workspace. Works for both local and SSH transports.
- *
- * Returns all three provider objects so callers can keep references for
- * reconnect rehydration.
+ * Shared tail of the provision flow — builds the session's agent runtime from
+ * an already-acquired workspace. Works for both local and SSH transports.
*/
export async function buildSessionFromWorkspace(
session: Session,
@@ -135,7 +125,7 @@ export async function buildSessionFromWorkspace(
projectId: string,
projectPath: string,
settings: ProjectSettingsProvider
-): Promise<BuildSessionResult> {
+): Promise<AgentRuntimeProvider> {
const { sessionEnvVars, tmuxEnabled, shellSetup } = await resolveSessionEnv(
session,
workspace,
@@ -143,24 +133,12 @@ export async function buildSessionFromWorkspace(
settings
);
- const { conversations: conversationProvider, terminals: terminalProvider } =
- await buildSessionProviders(type, {
- projectId,
- sessionId: session.id,
- workspaceId: workspace.id,
- sessionPath: workspace.path,
- tmuxEnabled,
- shellSetup,
- sessionEnvVars,
- });
-
- const sessionProvider: SessionProvider = {
+ return buildAgentRuntime(type, {
+ projectId,
sessionId: session.id,
- sessionBranch: undefined,
+ sessionPath: workspace.path,
+ tmuxEnabled,
+ shellSetup,
sessionEnvVars,
- conversations: conversationProvider,
- terminals: terminalProvider,
- };
-
- return { sessionProvider, conversationProvider, terminalProvider };
+ });
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts
new file mode 100644
index 000000000..b59dbbdab
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-hooks.ts
@@ -0,0 +1,52 @@
+import { HookCore, type Hookable } from '@main/lib/hookable';
+import { log } from '@main/lib/logger';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+
+/**
+ * In-process hook bus for session/agent runtime events. Distinct from the
+ * renderer-bound IPC channels in `@shared/core/sessions/sessionEvents` —
+ * main-process reactions must use this bus, since `events` only delivers
+ * main→renderer.
+ */
+export type SessionHookMap = {
+ /** The session row was deleted outside the sessionService delete path. */
+ 'session:deleted': (sessionId: string) => void | Promise<void>;
+ /**
+ * A remote session was deliberately terminated on another client (or this one)
+ * and the sidecar broadcast a `session-terminated` event. The owning runtime
+ * has already torn down its local PTY/relay; this signals the DB-level cleanup
+ * (delete the row, tombstone the id, emit `session:deleted`) so the ghost
+ * row does not linger and get re-attached into a blank tmux session.
+ */
+ 'session:remote-terminated': (params: {
+ projectId: string;
+ sessionId: string;
+ terminatedSessionId: string;
+ }) => void | Promise<void>;
+ /**
+ * The session's agent PTY exited unexpectedly (i.e. not a deliberate stop).
+ * In-process counterpart to the renderer-bound `agentSessionExitedChannel`.
+ */
+ 'session:agent-exited': (params: { sessionId: string }) => void | Promise<void>;
+ 'session:input-submitted': (params: {
+ projectId: string;
+ sessionId: string;
+ providerId: AgentProviderId;
+ }) => void | Promise<void>;
+};
+
+class SessionHooks implements Hookable<SessionHookMap> {
+ private readonly _core = new HookCore<SessionHookMap>((name, e) =>
+ log.error(`SessionHooks: ${String(name)} hook error`, e)
+ );
+
+ on<K extends keyof SessionHookMap>(name: K, handler: SessionHookMap[K]) {
+ return this._core.on(name, handler);
+ }
+
+ _emit<K extends keyof SessionHookMap>(name: K, ...args: Parameters<SessionHookMap[K]>): void {
+ this._core.callHookBackground(name, ...args);
+ }
+}
+
+export const sessionHooks = new SessionHooks();
diff --git a/dash/apps/switchdash-desktop/src/main/core/conversations/session-join.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
similarity index 91%
rename from dash/apps/switchdash-desktop/src/main/core/conversations/session-join.ts
rename to dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
index 5e56deaf5..f0e1c0e33 100644
--- a/dash/apps/switchdash-desktop/src/main/core/conversations/session-join.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-join.ts
@@ -11,7 +11,7 @@ export type SessionWithAgent = {
/**
* Loads a session row joined with its owning agent, exposing the agent's
- * `projectId` and `providerId` (denormalised onto the conversation/session view).
+ * `projectId` and `providerId` (denormalised onto the session view).
*/
export async function loadSessionWithAgent(
sessionId: string
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts
index 97aacd35a..e8b85bc6a 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-runtime-manager.ts
@@ -1,20 +1,14 @@
import { ok, type Result } from '@switchdash/shared';
+import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import type { IExecutionContext } from '@main/core/execution-context/types';
-import {
- killTmuxSession,
- makeAgentTmuxSessionName,
- makeTmuxSessionName,
-} from '@main/core/pty/tmux-session-name';
+import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';
import type { SessionRuntimeResult } from '@main/core/sessions/session-builder';
-import { getSessionSessionLeafIds } from '@main/core/sessions/session-targets';
import { workspaceRegistry, type TeardownMode } from '@main/core/workspaces/workspace-registry';
-import { HookCore, type Hookable } from '@main/lib/hookable';
import { LifecycleMap } from '@main/lib/lifecycle-map';
import { log } from '@main/lib/logger';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
import type { SessionBootstrapStatus } from '@shared/core/sessions/sessions';
import type { WorkspaceType as SharedWorkspaceType } from '@shared/core/workspaces/workspaces';
-import type { ProvisionResult, SessionProvider } from '../projects/project-provider';
+import type { ProvisionResult } from '../projects/project-provider';
import { withTimeout } from '../projects/utils';
import {
formatProvisionSessionError,
@@ -33,58 +27,30 @@ export type WorkspaceHint = {
type StoredSession = ProvisionResult & { projectId: string; ctx: IExecutionContext };
-export type SessionManagerHooks = {
- 'session:provisioned': (info: {
- projectId: string;
- sessionId: string;
- branchName: string | undefined;
- workspaceId: string;
- worktreeGitDir?: string;
- }) => void | Promise<void>;
- 'session:torn-down': (info: {
- projectId: string;
- sessionId: string;
- workspaceId: string;
- }) => void | Promise<void>;
-};
-
async function executeTeardown(
- session: SessionProvider,
+ agent: AgentRuntimeProvider,
workspaceId: string,
mode: TeardownMode
): Promise<void> {
if (mode === 'detach') {
- await session.conversations.detachAll();
- await session.terminals.detachAll();
+ await agent.detach();
} else {
- await session.conversations.destroyAll();
- await session.terminals.destroyAll();
+ await agent.destroy();
}
await workspaceRegistry.release(workspaceId, mode);
}
async function cleanupDetachedSessions(
- projectId: string,
+ _projectId: string,
sessionId: string,
ctx: IExecutionContext
): Promise<void> {
- const { conversationIds, terminalIds } = await getSessionSessionLeafIds(projectId, sessionId);
- // Agent conversations key their pane on the shared conversationId (so all
- // clients converge on one tmux session); terminals stay on the instance-local
- // pty-session-id scheme.
- const tmuxNames = [
- ...conversationIds.map((conversationId) => makeAgentTmuxSessionName(conversationId)),
- ...terminalIds.map((terminalId) =>
- makeTmuxSessionName(makePtySessionId(projectId, sessionId, terminalId))
- ),
- ];
- await Promise.all(tmuxNames.map((name) => killTmuxSession(ctx, name)));
+ // The agent pane is keyed on the shared session id, so all clients converge
+ // on one tmux session.
+ await killTmuxSession(ctx, makeAgentTmuxSessionName(sessionId));
}
class SessionRuntimeManager {
- private readonly _hooks = new HookCore<SessionManagerHooks>((name, e) =>
- log.error(`SessionManager: ${String(name)} hook error`, e)
- );
private readonly _lifecycle = new LifecycleMap<
StoredSession,
ProvisionSessionError,
@@ -92,21 +58,13 @@ class SessionRuntimeManager {
>({
postTeardown: (sessionId, stored) => {
this._sessionsByProject.get(stored.projectId)?.delete(sessionId);
- this._hooks.callHookBackground('session:torn-down', {
- projectId: stored.projectId,
- sessionId,
- workspaceId: stored.persistData.workspaceId,
- });
},
});
private readonly _sessionsByProject = new Map<string, Set<string>>();
- readonly hooks: Hookable<SessionManagerHooks> = this._hooks;
-
/**
* Registers a fully-provisioned session into the lifecycle map.
* Idempotent — if the session is already registered, returns immediately.
- * Fires `session:provisioned` hook for git watchers and PR sync.
*/
async registerSession(
sessionId: string,
@@ -115,7 +73,7 @@ class SessionRuntimeManager {
ctx: IExecutionContext
): Promise<void> {
const stored: StoredSession = {
- sessionProvider: result.sessionProvider,
+ agent: result.agent,
persistData: {
workspaceId: result.workspaceId,
worktreeGitDir: result.worktreeGitDir,
@@ -130,14 +88,6 @@ class SessionRuntimeManager {
const byProject = this._sessionsByProject.get(projectId) ?? new Set<string>();
byProject.add(sessionId);
this._sessionsByProject.set(projectId, byProject);
-
- this._hooks.callHookBackground('session:provisioned', {
- projectId,
- sessionId,
- branchName: result.sessionProvider.sessionBranch,
- workspaceId: result.workspaceId,
- worktreeGitDir: result.worktreeGitDir,
- });
}
async teardownSession(
@@ -146,10 +96,10 @@ class SessionRuntimeManager {
): Promise<Result<void, TeardownSessionError>> {
const result = this._lifecycle.teardown(
sessionId,
- async ({ sessionProvider, persistData, projectId, ctx }) => {
+ async ({ agent, persistData, projectId, ctx }) => {
try {
await withTimeout(
- executeTeardown(sessionProvider, persistData.workspaceId, mode),
+ executeTeardown(agent, persistData.workspaceId, mode),
SESSION_TIMEOUT_MS
);
return ok();
@@ -178,10 +128,7 @@ class SessionRuntimeManager {
sessionIds.flatMap((id) => {
const stored = this._lifecycle.get(id);
if (!stored) return [];
- return [
- stored.sessionProvider.conversations.detachAll(),
- stored.sessionProvider.terminals.detachAll(),
- ];
+ return [stored.agent.detach()];
})
);
// Remove entries from lifecycle maps without running workspace teardown.
@@ -197,8 +144,9 @@ class SessionRuntimeManager {
}
}
- getSession(sessionId: string): SessionProvider | undefined {
- return this._lifecycle.get(sessionId)?.sessionProvider;
+ /** The live agent runtime for a provisioned session, if any. */
+ getAgent(sessionId: string): AgentRuntimeProvider | undefined {
+ return this._lifecycle.get(sessionId)?.agent;
}
getWorkspaceId(sessionId: string): string | undefined {
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts
index fde2afe9c..6bfa88865 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/session-service.ts
@@ -72,8 +72,8 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {
}
/**
- * Provisions the runtime for a session: builds the conversation + terminal
- * providers in the project root and registers the session. Idempotent —
+ * Provisions the runtime for a session: builds the agent runtime
+ * in the project root and registers the session. Idempotent —
* fast-paths when already live. Fires the `session:workspace-ready` hook and
* emits the `session:provisioned` IPC event on success.
*/
@@ -85,7 +85,7 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {
if (!project) throw new Error(`Project not found: ${session.agentProjectId}`);
// Idempotency: session is already live — return current state.
- if (sessionRuntimeManager.getSession(sessionId)) {
+ if (sessionRuntimeManager.getAgent(sessionId)) {
const pd = sessionRuntimeManager.getPersistData(sessionId);
const provisionResult: ProvisionResult = {
path: project.repoPath,
@@ -153,6 +153,18 @@ export class SessionService implements Hookable<SessionLifecycleHooks> {
return sessionRuntimeManager.teardownSession(sessionId, mode);
}
+ /**
+ * Stop a session's agent for good without deleting the session row. Routes
+ * through the agent runtime so the PTY leaves respawn tracking and stays
+ * stopped (a bare `pty.kill` would be respawned by the supervisor ~500ms
+ * later). No-op when the session has no live runtime.
+ */
+ async stopAgent(sessionId: string): Promise<void> {
+ const agent = sessionRuntimeManager.getAgent(sessionId);
+ if (!agent) return;
+ await agent.stop();
+ }
+
async deleteSession(projectId: string, sessionId: string): Promise<void> {
await deleteSession(projectId, sessionId);
this._hooks.callHookBackground('session:deleted', sessionId, projectId);
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/session-targets.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/session-targets.ts
deleted file mode 100644
index 69cdf22c5..000000000
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/session-targets.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-export type SessionSessionLeafIds = {
- conversationIds: string[];
- terminalIds: string[];
-};
-
-/**
- * In switchdash a session is 1:1 with its conversation (the agent run) and with
- * its single shell, so the only leaf id is the session id itself.
- */
-export async function getSessionSessionLeafIds(
- _projectId: string,
- sessionId: string
-): Promise<SessionSessionLeafIds> {
- return {
- conversationIds: [sessionId],
- terminalIds: [],
- };
-}
diff --git a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
index 4e4092ba1..b0455fdef 100644
--- a/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/sessions/utils/utils.ts
@@ -25,6 +25,7 @@ export function mapSessionRowToSession(row: SessionRow, providerId: AgentProvide
archivedAt: row.archivedAt ?? undefined,
lastInteractedAt: row.lastInteractedAt ?? undefined,
autoApprove: config.autoApprove,
+ providerSessionId: config.providerSessionId,
subagentName: config.subagentName,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
diff --git a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
index 3caa3cb06..a2540d9ad 100644
--- a/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/ssh/lifecycle/ssh-connection-manager.ts
@@ -115,7 +115,7 @@ interface ConnectionRecord {
* True once this record has had a ready connection. Any later ready is
* surfaced as 'reconnected' — including a manual forceReconnect, which has
* no backoff state — so consumers that re-attach sessions on a restored
- * transport (terminal + conversation providers) always get their signal.
+ * transport (terminal + agent runtime providers) always get their signal.
*/
hasConnectedBefore: boolean;
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
index 5a9d83626..0c26e4bbd 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/auto-session-watcher.test.ts
@@ -67,7 +67,7 @@ describe('AutoSessionWatcher.handleNotification', () => {
it('does not spawn when a live session already attends the room', async () => {
getConnections.mockReturnValue([
- { conversationId: 'c1', roomId: 'room-x', agentId: 'switch-agent-1' },
+ { sessionId: 'c1', roomId: 'room-x', agentId: 'switch-agent-1' },
]);
const watcher = fakeWatcher();
@@ -88,7 +88,7 @@ describe('AutoSessionWatcher.handleNotification', () => {
it('treats a live session in a different room as not attending', async () => {
getConnections.mockReturnValue([
- { conversationId: 'c1', roomId: 'other-room', agentId: 'switch-agent-1' },
+ { sessionId: 'c1', roomId: 'other-room', agentId: 'switch-agent-1' },
]);
const watcher = fakeWatcher();
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts
index 5a647460c..157a82899 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/injection-sink.test.ts
@@ -15,15 +15,15 @@ describe('PtyInjectionSink', () => {
const pty = { write: vi.fn() };
vi.mocked(ptySessionRegistry.get).mockReturnValue(pty as never);
- const sink = new PtyInjectionSink('project:session:conversation');
+ const sink = new PtyInjectionSink('project-1:session-1');
expect(sink.acquire()).toBe(pty);
- expect(ptySessionRegistry.get).toHaveBeenCalledWith('project:session:conversation');
+ expect(ptySessionRegistry.get).toHaveBeenCalledWith('project-1:session-1');
});
it('returns null when no PTY is live', () => {
vi.mocked(ptySessionRegistry.get).mockReturnValue(undefined as never);
- const sink = new PtyInjectionSink('project:session:conversation');
+ const sink = new PtyInjectionSink('project-1:session-1');
expect(sink.acquire()).toBeNull();
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
index 18e1e0c0b..d0f1eee7c 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/restore-sessions.ts
@@ -1,7 +1,7 @@
-import { hydrateConversation } from '@main/core/conversations/hydrateConversation';
-import { loadSessionWithAgent } from '@main/core/conversations/session-join';
import { getProjectById } from '@main/core/projects/operations/getProjects';
import { projectManager } from '@main/core/projects/project-manager';
+import { hydrateSession } from '@main/core/sessions/operations/hydrateSession';
+import { loadSessionWithAgent } from '@main/core/sessions/session-join';
import { sessionService } from '@main/core/sessions/session-service';
import { log } from '@main/lib/logger';
import { switchRoomService } from './switch-room-service';
@@ -10,32 +10,32 @@ import { switchRoomService } from './switch-room-service';
* Launch every session that was connected to a Switch room before the last
* shutdown, so it receives and responds to room events without the user opening
* its terminal. Replays the renderer's open sequence from the main process:
- * mount the project → provision the session runtime → hydrate the conversation
+ * mount the project → provision the session runtime → hydrate the session
* (which spawns the PTY and, via the session-launch path, restarts the room
- * poller). Sessions whose conversation or project no longer exist are pruned.
+ * poller). Sessions whose row or project no longer exist are pruned.
*
* This deliberately spawns the agent process for each room-connected session at
* startup — keystroke injection requires a live TUI, so there is no lighter way
* to deliver room messages to an unopened session.
*/
export async function restoreSwitchRoomSessions(): Promise<void> {
- const conversationIds = await switchRoomService.listPersistedConversationIds();
- if (conversationIds.length === 0) return;
+ const sessionIds = await switchRoomService.listPersistedSessionIds();
+ if (sessionIds.length === 0) return;
const stale: string[] = [];
let launched = 0;
- for (const conversationId of conversationIds) {
+ for (const sessionId of sessionIds) {
try {
- const loaded = await loadSessionWithAgent(conversationId);
+ const loaded = await loadSessionWithAgent(sessionId);
if (!loaded) {
- stale.push(conversationId);
+ stale.push(sessionId);
continue;
}
const project = await getProjectById(loaded.projectId);
if (!project) {
- stale.push(conversationId);
+ stale.push(sessionId);
continue;
}
@@ -43,7 +43,7 @@ export async function restoreSwitchRoomSessions(): Promise<void> {
const opened = await projectManager.openProject(project);
if (!opened.success) {
log.warn('restoreSwitchRoomSessions: failed to open project; skipping session', {
- conversationId,
+ sessionId,
projectId: loaded.projectId,
error: opened.error,
});
@@ -51,13 +51,12 @@ export async function restoreSwitchRoomSessions(): Promise<void> {
}
}
- await sessionService.provisionWorkspace(conversationId);
- // sessionId === conversationId in this data model.
- await hydrateConversation(loaded.projectId, conversationId, conversationId);
+ await sessionService.provisionWorkspace(sessionId);
+ await hydrateSession(loaded.projectId, sessionId);
launched += 1;
} catch (error) {
log.warn('restoreSwitchRoomSessions: failed to launch room-connected session', {
- conversationId,
+ sessionId,
error: String(error),
});
}
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 0add86eac..43a3079bb 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
@@ -120,7 +120,7 @@ describe('RoomConnection', () => {
creds,
roomId: 'room-1',
roomName: 'Room One',
- conversationId: 'conv-1',
+ sessionId: 'session-1',
sink,
injector,
control,
@@ -479,7 +479,7 @@ describe('RoomConnection', () => {
creds,
roomId: 'room-1',
roomName: 'Room One',
- conversationId: 'conv-1',
+ sessionId: 'session-1',
sink: { acquire: () => ({ write: vi.fn() }) },
injector,
control,
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 75997a966..3d735b27f 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
@@ -84,7 +84,7 @@ function formatElapsed(ms: number): string {
/**
* The runtime states switch-core surfaces on bridged channels. The richer
- * per-conversation `AgentStatus` is collapsed onto these before reporting:
+ * per-session `AgentStatus` is collapsed onto these before reporting:
* `completed` → `idle` (work done, nothing to surface) and `error` →
* `awaiting-input` (needs the operator's attention).
*/
@@ -130,7 +130,7 @@ interface QueuedInjection {
/**
* The triggering message's thread id (its `thread_id`) when it was in a
* thread, so the bridge surfaces runtime state in that thread. null at the
- * conversation root.
+ * room root.
*/
threadId: string | null;
}
@@ -151,10 +151,10 @@ export interface RoomConnectionDeps {
creds: SwitchCredentials;
roomId: string;
roomName: string | null;
- /** The switchdash conversation id of the session this connection drives, so
+ /** The switchdash session id of the session this connection drives, so
* the deeplink can resolve to the exact session on any client (the shared
- * conversation id is the same across clients; the local room mapping is not). */
- conversationId: string;
+ * session id is the same across clients; the local room mapping is not). */
+ sessionId: string;
sink: InjectionSink;
injector: PromptInjector;
/** Per-agent-type session-control support + keystroke recipes (reset /
@@ -192,7 +192,7 @@ export class RoomConnection {
private readonly creds: SwitchCredentials;
private readonly roomId: string;
private readonly roomName: string | null;
- private readonly conversationId: string;
+ private readonly sessionId: string;
private readonly sink: InjectionSink;
private readonly injector: PromptInjector;
private readonly control: SessionControl;
@@ -234,7 +234,7 @@ export class RoomConnection {
this.creds = deps.creds;
this.roomId = deps.roomId;
this.roomName = deps.roomName;
- this.conversationId = deps.conversationId;
+ this.sessionId = deps.sessionId;
this.sink = deps.sink;
this.injector = deps.injector;
this.control = deps.control;
@@ -293,9 +293,9 @@ export class RoomConnection {
server: this.creds.apiEndpoint,
agent: this.creds.agentId,
room: this.roomId,
- // The shared conversation id resolves to the exact session on any client
+ // The shared session id resolves to the exact session on any client
// (a client that only adopted the session has no room mapping to match on).
- conversation: this.conversationId,
+ session: this.sessionId,
});
return `${this.deeplinkScheme}://session?${params.toString()}`;
}
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 ea272cfaa..6fa2ae44f 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
@@ -8,7 +8,7 @@ import { db } from '@main/db/client';
import { projects, sessions } from '@main/db/schema';
import { log } from '@main/lib/logger';
import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
import { PtyInjectionSink } from './injection-sink';
import { PluginPromptInjector } from './plugin-prompt-injector';
import { RoomConnection } from './room-connection';
@@ -43,28 +43,28 @@ class SwitchNotificationPoller {
* queue and renew loop are preserved.
*/
connect(ctx: SessionRoomContext, roomId: string, roomName: string | null): void {
- const existing = this.connections.get(ctx.conversationId);
+ const existing = this.connections.get(ctx.sessionId);
if (existing && existing.room === roomId) return;
- this.disconnect(ctx.conversationId);
+ this.disconnect(ctx.sessionId);
void this.start(ctx, roomId, roomName).catch((error) => {
log.warn('SwitchNotificationPoller: failed to start poller', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
error: String(error),
});
});
}
/** Stop polling for a session (room switch-away or session exit). */
- disconnect(conversationId: string): void {
- const conn = this.connections.get(conversationId);
+ disconnect(sessionId: string): void {
+ const conn = this.connections.get(sessionId);
if (!conn) return;
conn.stop();
- this.connections.delete(conversationId);
- log.debug('SwitchNotificationPoller: poll stopped', { conversationId });
+ this.connections.delete(sessionId);
+ log.debug('SwitchNotificationPoller: poll stopped', { sessionId });
}
dispose(): void {
- for (const conversationId of [...this.connections.keys()]) this.disconnect(conversationId);
+ for (const sessionId of [...this.connections.keys()]) this.disconnect(sessionId);
}
private async start(
@@ -79,7 +79,7 @@ class SwitchNotificationPoller {
.limit(1);
if (!project) {
log.warn('SwitchNotificationPoller: no project dir for session; cannot read credentials', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
projectId: ctx.projectId,
});
return;
@@ -88,7 +88,7 @@ class SwitchNotificationPoller {
// Remote agents poll from their on-host sidecar (CHOO-1059); the local
// poller reads local credential files, which a remote-only agent has none of.
log.debug('SwitchNotificationPoller: remote-only project; local poller does not apply', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
projectId: ctx.projectId,
});
return;
@@ -101,7 +101,7 @@ class SwitchNotificationPoller {
const [sessionRow] = await db
.select({ config: sessions.config })
.from(sessions)
- .where(eq(sessions.id, ctx.conversationId))
+ .where(eq(sessions.id, ctx.sessionId))
.limit(1);
const subagentName = sessionRow?.config?.subagentName;
@@ -114,29 +114,29 @@ class SwitchNotificationPoller {
if (!creds) {
log.warn(
'SwitchNotificationPoller: missing Switch credentials (SWITCH_API_TOKEN/ENDPOINT/AGENT_ID) — cannot poll room',
- { conversationId: ctx.conversationId, dir: project.path, roomId, subagentName }
+ { sessionId: ctx.sessionId, dir: project.path, roomId, subagentName }
);
return;
}
- const ptySessionId = makePtySessionId(ctx.projectId, ctx.conversationId, ctx.conversationId);
+ const ptySessionId = makeAgentPtySessionId(ctx.projectId, ctx.sessionId);
const connection = new RoomConnection({
creds,
roomId,
roomName,
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
sink: new PtyInjectionSink(ptySessionId),
injector: new PluginPromptInjector(ctx.providerId),
control: resolveSessionControl(ctx.providerId),
deeplinkScheme: DEEPLINK_SCHEME,
isHumanTyping: () => isHumanInputRecent(ptySessionId),
- mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', ctx.conversationId),
+ mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', ctx.sessionId),
log,
});
- this.connections.set(ctx.conversationId, connection);
+ this.connections.set(ctx.sessionId, connection);
log.debug('SwitchNotificationPoller: poll started', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
roomId,
roomName,
agentId: creds.agentId,
@@ -152,11 +152,11 @@ class SwitchNotificationPoller {
* polling.
*/
onAgentStatusChange(
- conversationId: string,
+ sessionId: string,
status: AgentStatus,
notificationType?: NotificationType
): void {
- const connection = this.connections.get(conversationId);
+ const connection = this.connections.get(sessionId);
if (!connection) return;
connection.onAgentStatusChange(status, notificationType);
}
@@ -167,8 +167,8 @@ class SwitchNotificationPoller {
* directly by AgentHookService for the same renderer-bound-bus reason as
* `onAgentStatusChange`. A no-op for sessions we aren't polling.
*/
- onAgentActivity(conversationId: string, detail: string): void {
- const connection = this.connections.get(conversationId);
+ onAgentActivity(sessionId: string, detail: string): void {
+ const connection = this.connections.get(sessionId);
if (!connection) return;
connection.reportActivity(detail);
}
diff --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.ts
index e144f453c..387b7bdc4 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
@@ -26,10 +26,10 @@ vi.mock('@main/db/client', () => {
const { switchRoomService } = await import('./switch-room-service');
const ctx = {
- conversationId: 'conv-1',
+ sessionId: 'session-1',
projectId: 'proj-1',
providerId: 'claude',
- ptyId: 'claude-conv-conv-1',
+ ptyId: 'claude-session-session-1',
};
describe('SwitchRoomService', () => {
@@ -42,10 +42,10 @@ describe('SwitchRoomService', () => {
switchRoomService.setSessionRoom(ctx, 'room-a', 'agent-1', 'Room A');
expect(switchRoomService.getConnections()).toEqual([
- { conversationId: 'conv-1', roomId: 'room-a', agentId: 'agent-1' },
+ { sessionId: 'session-1', roomId: 'room-a', agentId: 'agent-1' },
]);
expect(emit).toHaveBeenCalledWith(sessionRoomChangedChannel, {
- conversationId: 'conv-1',
+ sessionId: 'session-1',
roomId: 'room-a',
agentId: 'agent-1',
});
@@ -63,18 +63,18 @@ describe('SwitchRoomService', () => {
switchRoomService.setSessionRoom(ctx, 'room-b', 'agent-1', 'Room B');
expect(switchRoomService.getConnections()).toEqual([
- { conversationId: 'conv-1', roomId: 'room-b', agentId: 'agent-1' },
+ { sessionId: 'session-1', roomId: 'room-b', agentId: 'agent-1' },
]);
});
it('clears a connection and emits nulls', () => {
switchRoomService.setSessionRoom(ctx, 'room-a', 'agent-1', 'Room A');
emit.mockClear();
- switchRoomService.clearSession('conv-1');
+ switchRoomService.clearSession('session-1');
expect(switchRoomService.getConnections()).toEqual([]);
expect(emit).toHaveBeenCalledWith(sessionRoomChangedChannel, {
- conversationId: 'conv-1',
+ sessionId: 'session-1',
roomId: null,
agentId: null,
});
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.ts
index 257c4aa9d..3709ed284 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
@@ -9,7 +9,7 @@ import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomE
import { switchNotificationPoller } from './switch-notification-poller';
export type SessionRoomContext = {
- conversationId: string;
+ sessionId: string;
projectId: string;
providerId: string;
ptyId: string;
@@ -54,11 +54,11 @@ class SwitchRoomService implements IDisposable {
agentId: string,
roomName: string | null
): void {
- const previous = this.connections.get(ctx.conversationId);
+ const previous = this.connections.get(ctx.sessionId);
const unchanged = previous && previous.roomId === roomId && previous.agentId === agentId;
- this.connections.set(ctx.conversationId, {
- conversationId: ctx.conversationId,
+ this.connections.set(ctx.sessionId, {
+ sessionId: ctx.sessionId,
roomId,
agentId,
roomName,
@@ -69,25 +69,23 @@ class SwitchRoomService implements IDisposable {
// Persist so a resumed session re-polls this room after an app restart,
// even though the connect_to_room hook only fires on a live tool call.
- void this.persistConnection(ctx.conversationId, { roomId, agentId, roomName }).catch(
- (error) => {
- log.warn('SwitchRoomService: failed to persist connection', {
- conversationId: ctx.conversationId,
- error: String(error),
- });
- }
- );
+ void this.persistConnection(ctx.sessionId, { roomId, agentId, roomName }).catch((error) => {
+ log.warn('SwitchRoomService: failed to persist connection', {
+ sessionId: ctx.sessionId,
+ error: String(error),
+ });
+ });
if (unchanged) return;
log.info('SwitchRoomService: session connected to room', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
roomId,
agentId,
});
events.emit(sessionRoomChangedChannel, {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
roomId,
agentId,
});
@@ -100,11 +98,11 @@ class SwitchRoomService implements IDisposable {
* connect_to_room again. No-op when the session has no persisted room.
*/
async restorePoller(ctx: SessionRoomContext): Promise<void> {
- const persisted = await this.getPersisted(ctx.conversationId);
+ const persisted = await this.getPersisted(ctx.sessionId);
if (!persisted) return;
log.info('SwitchRoomService: restoring room poller for resumed session', {
- conversationId: ctx.conversationId,
+ sessionId: ctx.sessionId,
roomId: persisted.roomId,
});
@@ -112,17 +110,17 @@ class SwitchRoomService implements IDisposable {
switchNotificationPoller.connect(ctx, persisted.roomId, persisted.roomName);
}
- /** Conversation ids that had a live room connection before the last shutdown. */
- async listPersistedConversationIds(): Promise<string[]> {
+ /** Session ids that had a live room connection before the last shutdown. */
+ async listPersistedSessionIds(): Promise<string[]> {
return Object.keys(await this.readPersisted());
}
/** Forget persisted connections whose sessions no longer exist. */
- async prunePersisted(conversationIds: string[]): Promise<void> {
- if (conversationIds.length === 0) return;
+ async prunePersisted(sessionIds: string[]): Promise<void> {
+ if (sessionIds.length === 0) return;
const map = await this.readPersisted();
let changed = false;
- for (const id of conversationIds) {
+ for (const id of sessionIds) {
if (id in map) {
delete map[id];
changed = true;
@@ -132,13 +130,13 @@ class SwitchRoomService implements IDisposable {
}
/** Drop a session's connection (on room switch-away or session exit). */
- clearSession(conversationId: string): void {
- if (!this.connections.delete(conversationId)) return;
+ clearSession(sessionId: string): void {
+ if (!this.connections.delete(sessionId)) return;
- log.info('SwitchRoomService: session disconnected from room', { conversationId });
+ log.info('SwitchRoomService: session disconnected from room', { sessionId });
events.emit(sessionRoomChangedChannel, {
- conversationId,
+ sessionId,
roomId: null,
agentId: null,
});
@@ -146,16 +144,16 @@ class SwitchRoomService implements IDisposable {
/** The current set of live session→room connections. */
getConnections(): SessionRoomConnection[] {
- return [...this.connections.values()].map(({ conversationId, roomId, agentId }) => ({
- conversationId,
+ return [...this.connections.values()].map(({ sessionId, roomId, agentId }) => ({
+ sessionId,
roomId,
agentId,
}));
}
- private async getPersisted(conversationId: string): Promise<PersistedConnection | null> {
+ private async getPersisted(sessionId: string): Promise<PersistedConnection | null> {
const map = await this.readPersisted();
- return map[conversationId] ?? null;
+ return map[sessionId] ?? null;
}
private async readPersisted(): Promise<Record<string, PersistedConnection>> {
@@ -172,11 +170,11 @@ class SwitchRoomService implements IDisposable {
}
private async persistConnection(
- conversationId: string,
+ sessionId: string,
connection: PersistedConnection
): Promise<void> {
const map = await this.readPersisted();
- map[conversationId] = connection;
+ map[sessionId] = connection;
await this.writePersisted(map);
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts
index 7fa94d003..37222ea67 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.test.ts
@@ -54,28 +54,8 @@ describe('LocalTerminalProvider', () => {
vi.mocked(ptySessionRegistry.register).mockClear();
});
- it('registers user terminals with their display name for resource monitor labels', async () => {
- const provider = new LocalTerminalProvider({
- projectId: terminal.projectId,
- scopeId: terminal.sessionId,
- sessionPath: '/repo',
- ctx,
- });
-
- await provider.spawnTerminal(terminal);
-
- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
- expect(ptySessionRegistry.register).toHaveBeenCalledWith(
- sessionId,
- expect.anything(),
- expect.objectContaining({ metadata: { title: terminal.name } })
- );
- });
-
it('cleans up cached shell profiles after a non-respawned exit', async () => {
const provider = new LocalTerminalProvider({
- projectId: terminal.projectId,
- scopeId: terminal.sessionId,
sessionPath: '/repo',
ctx,
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts
index b00da2b21..a4ffe1140 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/local-terminal-provider.ts
@@ -18,11 +18,7 @@ import { log } from '@main/lib/logger';
import { makePtySessionId } from '@shared/core/pty/ptySessionId';
import type { TerminalShellId } from '@shared/core/terminals/terminal-settings';
import type { Terminal } from '@shared/core/terminals/terminals';
-import {
- type LifecycleScriptSpawnRequest,
- type TerminalProvider,
- type TerminalSpawnOptions,
-} from '../terminal-provider';
+import { type LifecycleScriptSpawnRequest, type TerminalProvider } from '../terminal-provider';
const DEFAULT_COLS = 80;
const DEFAULT_ROWS = 24;
@@ -41,9 +37,6 @@ export class LocalTerminalProvider implements TerminalProvider {
private knownSessionIds = new Set<string>();
private shellProfiles = new Map<string, ResolvedShellProfile>();
private respawnCounts = new Map<string, number>();
- private readonly projectId: string;
- private readonly workspaceId: string;
- private readonly scopeId: string;
private readonly sessionPath: string;
private readonly tmux: boolean;
private readonly shellSetup?: string;
@@ -51,27 +44,18 @@ export class LocalTerminalProvider implements TerminalProvider {
private readonly sessionEnvVars: Record<string, string>;
constructor({
- projectId,
- workspaceId,
- scopeId,
sessionPath,
tmux = false,
shellSetup,
ctx,
sessionEnvVars = {},
}: {
- projectId: string;
- workspaceId?: string;
- scopeId: string;
sessionPath: string;
tmux?: boolean;
shellSetup?: string;
ctx: IExecutionContext;
sessionEnvVars?: Record<string, string>;
}) {
- this.projectId = projectId;
- this.workspaceId = workspaceId ?? scopeId;
- this.scopeId = scopeId;
this.sessionPath = sessionPath;
this.tmux = tmux;
this.shellSetup = shellSetup;
@@ -79,28 +63,6 @@ export class LocalTerminalProvider implements TerminalProvider {
this.sessionEnvVars = sessionEnvVars;
}
- async spawnTerminal(
- terminal: Terminal,
- initialSize: { cols: number; rows: number } = { cols: DEFAULT_COLS, rows: DEFAULT_ROWS },
- options: TerminalSpawnOptions = {}
- ): Promise<void> {
- return this.spawnWithPolicy(
- terminal,
- initialSize,
- options.command
- ? { kind: 'argv', command: options.command.command, args: options.command.args }
- : undefined,
- undefined,
- options.shell ?? terminal.shellId,
- { title: terminal.name },
- {
- respawnOnExit: true,
- preserveBufferOnExit: false,
- watchDevServer: true,
- }
- );
- }
-
async spawnLifecycleScript({
terminal,
command,
@@ -252,23 +214,6 @@ export class LocalTerminalProvider implements TerminalProvider {
return profile;
}
- async killTerminal(terminalId: string): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.scopeId, terminalId);
- this.knownSessionIds.delete(sessionId);
- const pty = this.sessions.get(sessionId);
- if (pty) {
- try {
- pty.kill();
- } catch {}
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
- }
- this.shellProfiles.delete(sessionId);
- if (this.tmux) {
- await killTmuxSession(this.ctx, makeTmuxSessionName(sessionId));
- }
- }
-
async destroyAll(): Promise<void> {
const sessionIds = Array.from(this.knownSessionIds);
await this.detachAll();
@@ -279,7 +224,7 @@ export class LocalTerminalProvider implements TerminalProvider {
this.shellProfiles.clear();
}
- async detachAll(): Promise<void> {
+ private async detachAll(): Promise<void> {
for (const [sessionId, pty] of this.sessions) {
try {
pty.kill();
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts
index 9fcf3e808..8067781b6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.test.ts
@@ -34,13 +34,6 @@ vi.mock('@main/core/pty/pty-session-registry', () => ({
},
}));
-vi.mock('@main/core/ssh/lifecycle/production-ssh-connection-manager', () => ({
- sshConnectionManager: {
- on: vi.fn(),
- off: vi.fn(),
- },
-}));
-
vi.mock('@main/core/pty/terminal-color-scheme', () => ({
getTerminalColorEnv: vi.fn().mockResolvedValue({}),
}));
@@ -79,90 +72,37 @@ describe('SshTerminalProvider', () => {
}));
});
- const ptyFromCall = async (index: number): Promise<{ kill: ReturnType<typeof vi.fn> }> => {
- const result = vi.mocked(openSsh2Pty).mock.results[index]!;
- const value = (await result.value) as { data: { kill: ReturnType<typeof vi.fn> } };
- return value.data;
- };
-
- it('re-attaches a terminal whose stale session is still mapped after a reconnect', async () => {
+ it('cleans up cached shell profiles after a non-respawned exit', async () => {
const provider = new SshTerminalProvider({
- projectId: terminal.projectId,
scopeId: terminal.sessionId,
sessionPath: '/repo',
ctx,
proxy,
- connectionId: 'ssh-1',
});
- await provider.spawnTerminal(terminal);
- expect(openSsh2Pty).toHaveBeenCalledTimes(1);
- const stalePty = await ptyFromCall(0);
- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
-
- // The dead channel's `close` has not fired, so the session is still mapped.
- await provider.rehydrate();
-
- // Re-spawned despite the lingering session, and the stale channel was torn
- // down locally (pty killed + unregistered) without touching remote tmux.
- expect(openSsh2Pty).toHaveBeenCalledTimes(2);
- expect(stalePty.kill).toHaveBeenCalled();
- expect(ptySessionRegistry.unregister).toHaveBeenCalledWith(sessionId, { pty: stalePty });
- });
-
- it('ignores a late exit from a discarded pty so it does not tear down the replacement', async () => {
- const provider = new SshTerminalProvider({
- projectId: terminal.projectId,
- scopeId: terminal.sessionId,
- sessionPath: '/repo',
- ctx,
- proxy,
- connectionId: 'ssh-1',
+ await provider.spawnLifecycleScript({
+ terminal,
+ command: 'echo ready',
});
- await provider.spawnTerminal(terminal); // pty A, exit handler [0]
- await provider.rehydrate(); // discards A, spawns pty B, exit handler [1]
-
const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
- const sessions = (provider as unknown as { sessions: Map<string, unknown> }).sessions;
- const replacement = sessions.get(sessionId);
- expect(replacement).toBeDefined();
-
- // Fire the discarded pty A's late exit.
- ptyMock.exitHandlers[0]!({ exitCode: 0 });
-
- // The replacement session B is untouched.
- expect(sessions.get(sessionId)).toBe(replacement);
- });
-
- it('registers user terminals with their display name for resource monitor labels', async () => {
- const provider = new SshTerminalProvider({
- projectId: terminal.projectId,
- scopeId: terminal.sessionId,
- sessionPath: '/repo',
- ctx,
- proxy,
- connectionId: 'ssh-1',
- });
+ expect(
+ (provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)
+ ).toBe(true);
- await provider.spawnTerminal(terminal);
+ for (const handler of ptyMock.exitHandlers) handler({ exitCode: 0 });
- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
- expect(ptySessionRegistry.register).toHaveBeenCalledWith(
- sessionId,
- expect.anything(),
- expect.objectContaining({ metadata: { title: terminal.name, isRemote: true } })
- );
+ expect(
+ (provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)
+ ).toBe(false);
});
- it('cleans up cached shell profiles after a non-respawned exit', async () => {
+ it('registers lifecycle-script ptys as remote for resource monitor labels', async () => {
const provider = new SshTerminalProvider({
- projectId: terminal.projectId,
scopeId: terminal.sessionId,
sessionPath: '/repo',
ctx,
proxy,
- connectionId: 'ssh-1',
});
await provider.spawnLifecycleScript({
@@ -171,14 +111,10 @@ describe('SshTerminalProvider', () => {
});
const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
- expect(
- (provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)
- ).toBe(true);
-
- for (const handler of ptyMock.exitHandlers) handler({ exitCode: 0 });
-
- expect(
- (provider as unknown as { shellProfiles: Map<string, unknown> }).shellProfiles.has(sessionId)
- ).toBe(false);
+ expect(ptySessionRegistry.register).toHaveBeenCalledWith(
+ sessionId,
+ expect.anything(),
+ expect.objectContaining({ metadata: { isRemote: true } })
+ );
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts
index 5a1d90b1c..bffdf5d20 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/impl/ssh-terminal-provider.ts
@@ -6,15 +6,12 @@ import { resolveSshCommand } from '@main/core/pty/spawn-utils';
import { openSsh2Pty } from '@main/core/pty/ssh2-pty';
import { getTerminalColorEnv } from '@main/core/pty/terminal-color-scheme';
import { killTmuxSession, makeTmuxSessionName } from '@main/core/pty/tmux-session-name';
-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 { resolveTerminalShellWithSystemFallback } from '@main/core/terminal-shell/resolver';
import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
import {
type LifecycleScriptSpawnRequest,
type TerminalProvider,
- type TerminalSpawnOptions,
} from '@main/core/terminals/terminal-provider';
import { log } from '@main/lib/logger';
import { makePtySessionId } from '@shared/core/pty/ptySessionId';
@@ -29,7 +26,6 @@ const MAX_RESPAWNS = 2;
type SpawnPolicy = {
respawnOnExit: boolean;
preserveBufferOnExit: boolean;
- trackForRehydrate: boolean;
};
export class SshTerminalProvider implements TerminalProvider {
@@ -39,9 +35,6 @@ export class SshTerminalProvider implements TerminalProvider {
private knownSessionIds = new Set<string>();
private shellProfiles = new Map<string, ResolvedShellProfile>();
private respawnCounts = new Map<string, number>();
- private terminals = new Map<string, Terminal>();
- private readonly projectId: string;
- private readonly workspaceId: string;
private readonly scopeId: string;
private readonly sessionPath: string;
private readonly sessionEnvVars: Record<string, string>;
@@ -49,12 +42,8 @@ export class SshTerminalProvider implements TerminalProvider {
private readonly shellSetup?: string;
private readonly ctx: IExecutionContext;
private readonly proxy: SshClientProxy;
- private readonly connectionId: string;
- private readonly _handleReconnect: (evt: SshConnectionManagerEvent) => void;
constructor({
- projectId,
- workspaceId,
scopeId,
sessionPath,
sessionEnvVars = {},
@@ -62,10 +51,7 @@ export class SshTerminalProvider implements TerminalProvider {
shellSetup,
ctx,
proxy,
- connectionId,
}: {
- projectId: string;
- workspaceId?: string;
scopeId: string;
sessionPath: string;
sessionEnvVars?: Record<string, string>;
@@ -73,10 +59,7 @@ export class SshTerminalProvider implements TerminalProvider {
shellSetup?: string;
ctx: IExecutionContext;
proxy: SshClientProxy;
- connectionId: string;
}) {
- this.projectId = projectId;
- this.workspaceId = workspaceId ?? scopeId;
this.scopeId = scopeId;
this.sessionPath = sessionPath;
this.sessionEnvVars = sessionEnvVars;
@@ -84,39 +67,6 @@ export class SshTerminalProvider implements TerminalProvider {
this.shellSetup = shellSetup;
this.ctx = ctx;
this.proxy = proxy;
- this.connectionId = connectionId;
- this._handleReconnect = (evt: SshConnectionManagerEvent) => {
- if (evt.type === 'reconnected' && evt.connectionId === this.connectionId) {
- this.rehydrate().catch((e: unknown) => {
- log.error('SshTerminalProvider: rehydrate failed after reconnect', {
- scopeId: this.scopeId,
- connectionId: this.connectionId,
- error: String(e),
- });
- });
- }
- };
- sshConnectionManager.on('connection-event', this._handleReconnect);
- }
-
- async spawnTerminal(
- terminal: Terminal,
- initialSize: { cols: number; rows: number } = { cols: DEFAULT_COLS, rows: DEFAULT_ROWS },
- options: TerminalSpawnOptions = {}
- ): Promise<void> {
- return this.spawnWithPolicy(
- terminal,
- initialSize,
- options.command,
- undefined,
- options.shell ?? terminal.shellId,
- { title: terminal.name, isRemote: true },
- {
- respawnOnExit: true,
- preserveBufferOnExit: false,
- trackForRehydrate: true,
- }
- );
}
async spawnLifecycleScript({
@@ -137,7 +87,6 @@ export class SshTerminalProvider implements TerminalProvider {
{
respawnOnExit,
preserveBufferOnExit,
- trackForRehydrate: false,
}
);
}
@@ -154,9 +103,6 @@ export class SshTerminalProvider implements TerminalProvider {
const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
this.knownSessionIds.add(sessionId);
if (this.sessions.has(sessionId)) return;
- if (policy.trackForRehydrate) {
- this.terminals.set(terminal.id, terminal);
- }
const cfg: GeneralSessionConfig = {
sessionId: this.scopeId,
@@ -271,87 +217,17 @@ export class SshTerminalProvider implements TerminalProvider {
return profile;
}
- /**
- * Re-attach every tracked terminal after an SSH reconnect. The previous
- * channel is dead once the transport was rebuilt even if its `close` has not
- * fired yet, so the session may still linger in the map — skipping it (the
- * old behavior) left the pane frozen. We discard the stale local channel
- * first (the remote tmux session survives, so the re-spawn re-attaches to it)
- * and always re-spawn.
- */
- async rehydrate(): Promise<void> {
- const terminals = Array.from(this.terminals.values());
- let reattached = 0;
- await Promise.all(
- terminals.map(async (terminal) => {
- const sessionId = makePtySessionId(terminal.projectId, terminal.sessionId, terminal.id);
- this.discardLocalSession(sessionId);
- try {
- await this.spawnTerminal(terminal);
- reattached += 1;
- } catch (e) {
- log.error('SshTerminalProvider: rehydrate failed', {
- terminalId: terminal.id,
- error: String(e),
- });
- }
- })
- );
- log.warn('SshTerminalProvider: rehydrated terminals after reconnect', {
- connectionId: this.connectionId,
- scopeId: this.scopeId,
- total: terminals.length,
- reattached,
- });
- }
-
- /**
- * Tear down the local (dead) PTY channel for a session without touching the
- * remote tmux session, and drop it from the maps so a subsequent spawn is not
- * skipped by the `sessions.has` guard. `unregister` is pty-scoped so it is a
- * no-op if the session has already been replaced.
- */
- private discardLocalSession(sessionId: string): void {
- const pty = this.sessions.get(sessionId);
- if (!pty) return;
- this.sessions.delete(sessionId);
- try {
- pty.kill();
- } catch {}
- ptySessionRegistry.unregister(sessionId, { pty });
- }
-
- async killTerminal(terminalId: string): Promise<void> {
- const sessionId = makePtySessionId(this.projectId, this.scopeId, terminalId);
- this.knownSessionIds.delete(sessionId);
- const pty = this.sessions.get(sessionId);
- if (pty) {
- try {
- pty.kill();
- } catch {}
- this.sessions.delete(sessionId);
- ptySessionRegistry.unregister(sessionId);
- }
- this.terminals.delete(terminalId);
- this.shellProfiles.delete(sessionId);
- if (this.tmux) {
- await killTmuxSession(this.ctx, makeTmuxSessionName(sessionId));
- }
- }
-
async destroyAll(): Promise<void> {
- sshConnectionManager.off('connection-event', this._handleReconnect);
const sessionIds = Array.from(this.knownSessionIds);
await this.detachAll();
if (this.tmux) {
await Promise.all(sessionIds.map((id) => killTmuxSession(this.ctx, makeTmuxSessionName(id))));
}
this.knownSessionIds.clear();
- this.terminals.clear();
this.shellProfiles.clear();
}
- async detachAll(): Promise<void> {
+ private async detachAll(): Promise<void> {
for (const [sessionId, pty] of this.sessions) {
try {
pty.kill();
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts
index 35a7e1817..f7169dc3a 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/lifecycle-script-coordinator.test.ts
@@ -77,7 +77,6 @@ function makeTerminalProvider(): {
const requests: LifecycleScriptSpawnRequest[] = [];
const provider: TerminalProvider = {
kind: 'local',
- async spawnTerminal() {},
async spawnLifecycleScript(request) {
const { terminal } = request;
const pty = new FakePty();
@@ -91,9 +90,7 @@ function makeTerminalProvider(): {
}
);
},
- async killTerminal() {},
async destroyAll() {},
- async detachAll() {},
};
return { provider, spawned, requests };
diff --git a/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts b/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts
index 4e00aa97d..8050c5aef 100644
--- a/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/terminals/terminal-provider.ts
@@ -1,4 +1,3 @@
-import type { TerminalShellId } from '@shared/core/terminals/terminal-settings';
import type { Terminal } from '@shared/core/terminals/terminals';
export type LifecycleScriptSpawnRequest = {
@@ -11,20 +10,12 @@ export type LifecycleScriptSpawnRequest = {
watchDevServer?: boolean;
};
-export type TerminalSpawnOptions = {
- command?: { command: string; args: string[] };
- shell?: TerminalShellId;
-};
-
+/**
+ * Spawns lifecycle-script PTYs (setup/run/teardown) for a workspace. One
+ * instance per workspace, owned by its LifecycleScriptService.
+ */
export interface TerminalProvider {
readonly kind: 'local' | 'ssh';
- spawnTerminal(
- terminal: Terminal,
- initialSize?: { cols: number; rows: number },
- options?: TerminalSpawnOptions
- ): Promise<void>;
spawnLifecycleScript(request: LifecycleScriptSpawnRequest): Promise<void>;
- killTerminal(terminalId: string): Promise<void>;
destroyAll(): Promise<void>;
- detachAll(): Promise<void>;
}
diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts
index a7b1ffa58..b3d7098d1 100644
--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.test.ts
@@ -1,10 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
-import { buildSessionProviders } from './workspace-factory';
+import { buildAgentRuntime } from './workspace-factory';
const connect = vi.hoisted(() => vi.fn(async () => ({ isConnected: true })));
const register = vi.hoisted(() => vi.fn());
-const sshConversationCtor = vi.hoisted(() => vi.fn());
-const sshTerminalCtor = vi.hoisted(() => vi.fn());
+const sshAgentRuntimeCtor = vi.hoisted(() => vi.fn());
// The ssh branch never touches the database; stub the client so importing the
// local-provider transitive graph doesn't open a real sqlite file at load.
@@ -18,15 +17,9 @@ vi.mock('@main/core/sessions/remote-session-preflight', () => ({
preflightRemoteSession: vi.fn(async () => {}),
}));
-vi.mock('@main/core/conversations/impl/ssh-conversation', () => ({
- SshConversationProvider: vi.fn(function (args: unknown) {
- sshConversationCtor(args);
- }),
-}));
-
-vi.mock('@main/core/terminals/impl/ssh-terminal-provider', () => ({
- SshTerminalProvider: vi.fn(function (args: unknown) {
- sshTerminalCtor(args);
+vi.mock('@main/core/agent-runtime/impl/ssh-agent-runtime', () => ({
+ SshAgentRuntime: vi.fn(function (args: unknown) {
+ sshAgentRuntimeCtor(args);
}),
}));
@@ -40,28 +33,23 @@ const SSH_TYPE = {
const OPTS = {
projectId: 'proj-1',
sessionId: 'session-1',
- workspaceId: 'proj-1:ssh:box:/home/dev/r',
sessionPath: '/home/dev/r',
tmuxEnabled: false, // project setting is off; remote must still force tmux on
sessionEnvVars: {},
};
-describe('buildSessionProviders (ssh)', () => {
- it('connects to the agent host and builds SSH providers with tmux forced on', async () => {
- await buildSessionProviders(SSH_TYPE, OPTS);
+describe('buildAgentRuntime (ssh)', () => {
+ it('connects to the agent host and builds the SSH runtime with tmux forced on', async () => {
+ await buildAgentRuntime(SSH_TYPE, OPTS);
expect(register).toHaveBeenCalledWith('agent-ssh:box', expect.any(Function));
expect(connect).toHaveBeenCalledWith('agent-ssh:box');
- expect(sshConversationCtor).toHaveBeenCalledTimes(1);
- const convArgs = sshConversationCtor.mock.calls[0]![0] as Record<string, unknown>;
- expect(convArgs.tmux).toBe(true);
- expect(convArgs.connectionId).toBe('agent-ssh:box');
- expect(convArgs.fs).toBeDefined();
- expect(convArgs.proxy).toBeDefined();
-
- const termArgs = sshTerminalCtor.mock.calls[0]![0] as Record<string, unknown>;
- expect(termArgs.tmux).toBe(true);
- expect(termArgs.connectionId).toBe('agent-ssh:box');
+ expect(sshAgentRuntimeCtor).toHaveBeenCalledTimes(1);
+ const agentArgs = sshAgentRuntimeCtor.mock.calls[0]![0] as Record<string, unknown>;
+ expect(agentArgs.tmux).toBe(true);
+ expect(agentArgs.connectionId).toBe('agent-ssh:box');
+ expect(agentArgs.fs).toBeDefined();
+ expect(agentArgs.proxy).toBeDefined();
});
});
diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts
index 7558b7e25..b7a1b56f4 100644
--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-factory.ts
@@ -1,6 +1,6 @@
-import { LocalConversationProvider } from '@main/core/conversations/impl/local-conversation';
-import { SshConversationProvider } from '@main/core/conversations/impl/ssh-conversation';
-import type { ConversationProvider } from '@main/core/conversations/types';
+import { LocalAgentRuntime } from '@main/core/agent-runtime/impl/local-agent-runtime';
+import { SshAgentRuntime } from '@main/core/agent-runtime/impl/ssh-agent-runtime';
+import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';
import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';
import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';
import type { IExecutionContext } from '@main/core/execution-context/types';
@@ -17,7 +17,6 @@ import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';
import { LocalTerminalProvider } from '@main/core/terminals/impl/local-terminal-provider';
import { SshTerminalProvider } from '@main/core/terminals/impl/ssh-terminal-provider';
import { runLifecycleScriptWithPolicy } from '@main/core/terminals/lifecycle-script-coordinator';
-import type { TerminalProvider } from '@main/core/terminals/terminal-provider';
import type { Workspace } from '@main/core/workspaces/workspace';
import { LifecycleScriptService } from '@main/core/workspaces/workspace-lifecycle-service';
import { type WorkspaceFactoryResult } from '@main/core/workspaces/workspace-registry';
@@ -99,9 +98,6 @@ export function createWorkspaceFactory(
// Workspace terminal provider (used only by lifecycle scripts)
const terminalOpts = {
- projectId: context.projectId,
- workspaceId,
- scopeId: workspaceId,
sessionPath: workDir,
tmux: tmuxEnabled,
shellSetup,
@@ -112,8 +108,8 @@ export function createWorkspaceFactory(
_type.kind === 'ssh'
? new SshTerminalProvider({
...terminalOpts,
+ scopeId: workspaceId,
proxy: await connectSshWorkspace(_type),
- connectionId: _type.connectionId,
})
: new LocalTerminalProvider(terminalOpts);
@@ -224,42 +220,36 @@ export function createWorkspaceFactory(
};
}
-type SessionProviderOpts = {
+type AgentRuntimeOpts = {
projectId: string;
sessionId: string;
- workspaceId: string;
sessionPath: string;
tmuxEnabled: boolean;
shellSetup?: string;
sessionEnvVars: Record<string, string>;
};
-async function resolveLocalConversationShellProfile(
- sessionId: string
-): Promise<ResolvedShellProfile> {
+async function resolveLocalAgentShellProfile(sessionId: string): Promise<ResolvedShellProfile> {
const { defaultShell } = await appSettingsService.get('terminal');
return await resolveLocalAutomationShellWithSystemFallback({
intent: defaultShell,
onFallback: (error) => {
- log.warn(
- 'buildSessionProviders: preferred local conversation shell unavailable, using fallback',
- {
- shell: error.shell,
- sessionId,
- }
- );
+ log.warn('buildAgentRuntime: preferred local agent shell unavailable, using fallback', {
+ shell: error.shell,
+ sessionId,
+ });
},
});
}
/**
- * Creates session-scoped conversation and terminal providers for the given transport type.
- * The exec function is derived internally from the WorkspaceType.
+ * Creates the session's agent runtime for the given transport type. The exec
+ * function is derived internally from the WorkspaceType.
*/
-export async function buildSessionProviders(
+export async function buildAgentRuntime(
_type: WorkspaceType,
- opts: SessionProviderOpts
-): Promise<{ conversations: ConversationProvider; terminals: TerminalProvider }> {
+ opts: AgentRuntimeOpts
+): Promise<AgentRuntimeProvider> {
if (_type.kind === 'ssh') {
const proxy = await connectSshWorkspace(_type);
const ctx = new SshExecutionContext(proxy, { root: _type.remoteRepoDir });
@@ -269,58 +259,32 @@ export async function buildSessionProviders(
await preflightRemoteSession({ ctx, fs, log, host: _type.host, workDir: _type.remoteRepoDir });
// Remote sessions always run under tmux — it persists the agent's PTY and
// is the pane the sidecar injects into and reattaches to.
- return {
- conversations: new SshConversationProvider({
- projectId: opts.projectId,
- sessionPath: opts.sessionPath,
- sessionId: opts.sessionId,
- tmux: true,
- shellSetup: opts.shellSetup,
- ctx,
- fs,
- proxy,
- connectionId: _type.connectionId,
- sessionEnvVars: opts.sessionEnvVars,
- }),
- terminals: new SshTerminalProvider({
- projectId: opts.projectId,
- workspaceId: opts.workspaceId,
- scopeId: opts.sessionId,
- sessionPath: opts.sessionPath,
- tmux: true,
- shellSetup: opts.shellSetup,
- ctx,
- proxy,
- connectionId: _type.connectionId,
- sessionEnvVars: opts.sessionEnvVars,
- }),
- };
- }
-
- const ctx = new LocalExecutionContext();
- const conversationShellProfile = await resolveLocalConversationShellProfile(opts.sessionId);
- return {
- conversations: new LocalConversationProvider({
+ return new SshAgentRuntime({
projectId: opts.projectId,
sessionPath: opts.sessionPath,
sessionId: opts.sessionId,
- tmux: opts.tmuxEnabled,
- shellSetup: opts.shellSetup,
- shellProfile: conversationShellProfile,
- ctx,
- sessionEnvVars: opts.sessionEnvVars,
- }),
- terminals: new LocalTerminalProvider({
- projectId: opts.projectId,
- workspaceId: opts.workspaceId,
- scopeId: opts.sessionId,
- sessionPath: opts.sessionPath,
- tmux: opts.tmuxEnabled,
+ tmux: true,
shellSetup: opts.shellSetup,
ctx,
+ fs,
+ proxy,
+ connectionId: _type.connectionId,
sessionEnvVars: opts.sessionEnvVars,
- }),
- };
+ });
+ }
+
+ const ctx = new LocalExecutionContext();
+ const agentShellProfile = await resolveLocalAgentShellProfile(opts.sessionId);
+ return new LocalAgentRuntime({
+ projectId: opts.projectId,
+ sessionPath: opts.sessionPath,
+ sessionId: opts.sessionId,
+ tmux: opts.tmuxEnabled,
+ shellSetup: opts.shellSetup,
+ shellProfile: agentShellProfile,
+ ctx,
+ sessionEnvVars: opts.sessionEnvVars,
+ });
}
/**
diff --git a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts
index b05419a01..cd974fc0e 100644
--- a/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/workspaces/workspace-lifecycle-service.test.ts
@@ -58,7 +58,6 @@ function makeTerminalProvider(): {
const requests: LifecycleScriptSpawnRequest[] = [];
const provider: TerminalProvider = {
kind: 'local',
- async spawnTerminal() {},
async spawnLifecycleScript(request) {
const { terminal } = request;
const pty = new FakePty();
@@ -72,9 +71,7 @@ function makeTerminalProvider(): {
}
);
},
- async killTerminal() {},
async destroyAll() {},
- async detachAll() {},
};
return { provider, spawned, requests };
diff --git a/dash/apps/switchdash-desktop/src/main/db/schema.ts b/dash/apps/switchdash-desktop/src/main/db/schema.ts
index f28f062bc..19b219d87 100644
--- a/dash/apps/switchdash-desktop/src/main/db/schema.ts
+++ b/dash/apps/switchdash-desktop/src/main/db/schema.ts
@@ -2,8 +2,8 @@ import { sql } from 'drizzle-orm';
import { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core';
import { versionedJsonColumn } from '@main/db/versioned-column';
import { agentRemoteConfig, type AgentConnectionKind } from '@shared/core/agents/agent-connection';
-import { conversationConfig } from '@shared/core/conversations/conversation-config';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { sessionConfig } from '@shared/core/sessions/session-config';
import type { TerminalShellId } from '@shared/core/terminals/terminal-settings';
// ---------------------------------------------------------------------------
@@ -180,7 +180,7 @@ export const sessions = sqliteTable(
.notNull()
.references(() => agents.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
- config: versionedJsonColumn(conversationConfig)('config'),
+ config: versionedJsonColumn(sessionConfig)('config'),
shellId: text('shell_id').$type<TerminalShellId>().notNull().default('system'),
status: text('status'),
agentSessionId: text('agent_session_id'),
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
index 69aa2ace0..e51dced55 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/command-palette-modal.tsx
@@ -1,16 +1,8 @@
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Command } from 'cmdk';
-import {
- Activity,
- File,
- FolderOpen,
- GitBranch,
- MessageSquare,
- type LucideIcon,
-} from 'lucide-react';
+import { Activity, File, FolderOpen, GitBranch, type LucideIcon } from 'lucide-react';
import { useObserver } from 'mobx-react-lite';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
-import { conversationRegistry } from '@renderer/features/sessions/stores/conversation-registry';
import { getSessionStore } from '@renderer/features/sessions/stores/session-selectors';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
import { commandRegistry } from '@renderer/lib/commands/registry';
@@ -25,7 +17,6 @@ import { cn } from '@renderer/utils/utils';
import { ALL_COMMAND_DEFS, type CommandDef } from '@shared/commands';
import type { SearchItem } from '@shared/core/search';
import { getCommandIcon } from './command-icons';
-import { PaletteConversationItem } from './palette-conversation-item';
import { PALETTE_ITEM_CLASS } from './palette-item-styles';
import { PaletteNotificationsGroup } from './palette-notifications-group';
import { PaletteProjectsGroup } from './palette-projects-group';
@@ -53,7 +44,6 @@ const KIND_ICON: Record<string, React.ReactNode> = {
action: null,
session: <GitBranch size={14} className="shrink-0 text-foreground/40" />,
project: <FolderOpen size={14} className="shrink-0 text-foreground/40" />,
- conversation: <MessageSquare size={14} className="shrink-0 text-foreground/40" />,
};
const GROUP_CLASS = cn(
@@ -65,10 +55,8 @@ const GROUP_CLASS = cn(
// Ordered allowlists for the "Suggested Actions" empty-state group. Defined at
// module scope so the arrays keep stable references across renders.
const SESSION_SUGGESTED = [
- 'session.newConversation',
'session.sidebarChanges',
'session.sidebarFiles',
- 'session.sidebarConversations',
'session.toggleTerminalDrawer',
'resource-monitor',
'app.giveFeedback',
@@ -248,7 +236,6 @@ export function CommandPaletteModal({
? resourceMonitorAction
: null;
const sessionResults = rankedDb.filter((r): r is SearchItem => r.kind === 'session');
- const conversationResults = rankedDb.filter((r): r is SearchItem => r.kind === 'conversation');
const handleNavigateToSession = (item: SearchItem) => {
if (!item.projectId) return;
@@ -261,12 +248,6 @@ export function CommandPaletteModal({
navigate('project', { projectId: item.id });
};
- const handleNavigateToConversation = (item: SearchItem) => {
- if (!item.projectId || !item.sessionId) return;
- handleClose();
- navigate('session', { projectId: item.projectId, sessionId: item.sessionId });
- };
-
const handleOpenFile = (item: SearchItem) => {
if (!item.projectId || !item.sessionId) return;
handleClose();
@@ -276,7 +257,6 @@ export function CommandPaletteModal({
const handleSelect = (item: SearchItem) => {
if (item.kind === 'session') return handleNavigateToSession(item);
if (item.kind === 'project') return handleNavigateToProject(item);
- if (item.kind === 'conversation') return handleNavigateToConversation(item);
if (item.kind === 'file') return handleOpenFile(item);
};
@@ -383,21 +363,6 @@ export function CommandPaletteModal({
);
}
}
- if (item.kind === 'conversation' && item.projectId && item.sessionId) {
- const convStore = conversationRegistry
- .get(item.sessionId)
- ?.conversations.get(item.id);
- if (convStore) {
- return (
- <PaletteConversationItem
- key={`conversation:${item.id}`}
- conv={convStore}
- value={`conversation:${item.id}`}
- onSelect={() => handleNavigateToConversation(item)}
- />
- );
- }
- }
if (item.kind === 'file') {
return (
<PaletteFileItem
@@ -465,30 +430,6 @@ export function CommandPaletteModal({
navigate={navigate}
/>
)}
- {sessionId && conversationResults.length > 0 && (
- <Command.Group heading="Recent Conversations" className={GROUP_CLASS}>
- {conversationResults.slice(0, 5).map((item) => {
- const convStore = item.sessionId
- ? conversationRegistry.get(item.sessionId)?.conversations.get(item.id)
- : undefined;
- return convStore ? (
- <PaletteConversationItem
- key={item.id}
- conv={convStore}
- value={item.id}
- onSelect={() => handleNavigateToConversation(item)}
- />
- ) : (
- <PaletteItem
- key={item.id}
- value={item.id}
- item={item}
- onSelect={() => handleNavigateToConversation(item)}
- />
- );
- })}
- </Command.Group>
- )}
</>
)}
</Command.List>
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-conversation-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-conversation-item.tsx
deleted file mode 100644
index e0901d19c..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-conversation-item.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { Command } from 'cmdk';
-import { observer } from 'mobx-react-lite';
-import { AgentStatusIndicator } from '@renderer/features/sessions/components/agent-status-indicator';
-import type { ConversationStore } from '@renderer/features/sessions/conversations/conversation-manager';
-import { formatConversationTitleForDisplay } from '@renderer/features/sessions/conversations/conversation-title-utils';
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
-import { PALETTE_ITEM_CLASS } from './palette-item-styles';
-
-export const PaletteConversationItem = observer(function PaletteConversationItem({
- conv,
- value,
- onSelect,
-}: {
- conv: ConversationStore;
- value: string;
- onSelect: () => void;
-}) {
- const title = formatConversationTitleForDisplay(conv.data.providerId, conv.data.title ?? '');
-
- return (
- <Command.Item value={value} onSelect={onSelect} className={PALETTE_ITEM_CLASS}>
- <AgentIcon id={conv.data.providerId} size={16} />
- <span className="flex-1 truncate">{title}</span>
- <AgentStatusIndicator status={conv.indicatorStatus} disableTooltip />
- </Command.Item>
- );
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx
index 32ace9388..4d7aa6d4b 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/palette-notifications-group.tsx
@@ -4,17 +4,13 @@ import {
asMounted,
getProjectManagerStore,
} from '@renderer/features/projects/stores/project-selectors';
-import type { ConversationStore } from '@renderer/features/sessions/conversations/conversation-manager';
-import { conversationRegistry } from '@renderer/features/sessions/stores/conversation-registry';
+import { sessionAgentRegistry } from '@renderer/features/sessions/stores/session-agent-registry';
import { isRegistered, type SessionStore } from '@renderer/features/sessions/stores/session-store';
import type { NavigateFnTyped } from '@renderer/lib/layout/navigation-provider';
import { cn } from '@renderer/utils/utils';
-import { PaletteConversationItem } from './palette-conversation-item';
import { PaletteSessionItem } from './palette-session-item';
-type NotificationItem =
- | { kind: 'session'; projectId: string; sessionStore: SessionStore }
- | { kind: 'conversation'; projectId: string; sessionId: string; conv: ConversationStore };
+type NotificationItem = { projectId: string; sessionStore: SessionStore };
const GROUP_CLASS = cn(
'[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5',
@@ -45,23 +41,14 @@ export function PaletteNotificationsGroup({
for (const [tid, sessionStore] of mounted.sessionManager.sessions) {
if (!isRegistered(sessionStore)) continue;
- const conversations = conversationRegistry.get(tid);
- if (!conversations) continue;
+ const agent = sessionAgentRegistry.get(tid);
+ if (!agent) continue;
- const status = conversations.sessionStatus;
+ const status = agent.sessionStatus;
// Only surface awaiting-input, error, completed — not working or idle.
if (!status || status === 'idle' || status === 'working') continue;
- if (pid === currentProjectId && tid === currentSessionId) {
- // We're already in this session — surface individual unseen conversations.
- for (const conv of conversations.conversations.values()) {
- if (!conv.seen && conv.indicatorStatus) {
- result.push({ kind: 'conversation', projectId: pid, sessionId: tid, conv });
- }
- }
- } else {
- result.push({ kind: 'session', projectId: pid, sessionStore });
- }
+ result.push({ projectId: pid, sessionStore });
}
}
@@ -72,37 +59,25 @@ export function PaletteNotificationsGroup({
return (
<Command.Group heading="Notifications" className={GROUP_CLASS}>
- {items.map((item) => {
- if (item.kind === 'conversation') {
- return (
- <PaletteConversationItem
- key={item.conv.data.id}
- conv={item.conv}
- value={`notif:conversation:${item.conv.data.id}`}
- onSelect={() => {
- if (item.projectId !== currentProjectId || item.sessionId !== currentSessionId) {
- navigate('session', { projectId: item.projectId, sessionId: item.sessionId });
- }
- onClose();
- }}
- />
- );
- }
- return (
- <PaletteSessionItem
- key={item.sessionStore.data.id}
- sessionStore={item.sessionStore}
- value={`notif:session:${item.sessionStore.data.id}`}
- onSelect={() => {
+ {items.map((item) => (
+ <PaletteSessionItem
+ key={item.sessionStore.data.id}
+ sessionStore={item.sessionStore}
+ value={`notif:session:${item.sessionStore.data.id}`}
+ onSelect={() => {
+ if (
+ item.projectId !== currentProjectId ||
+ item.sessionStore.data.id !== currentSessionId
+ ) {
navigate('session', {
projectId: item.projectId,
sessionId: item.sessionStore.data.id,
});
- onClose();
- }}
- />
- );
- })}
+ }
+ onClose();
+ }}
+ />
+ ))}
</Command.Group>
);
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts
index 4249c84e1..277d484c0 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-utils.ts
@@ -1,7 +1,4 @@
-import {
- getConversationsForSession,
- getTerminalsForSession,
-} from '@renderer/features/sessions/stores/session-selectors';
+import { getSessionAgent } from '@renderer/features/sessions/stores/session-selectors';
import { appState } from '@renderer/lib/stores/app-state';
import { formatBytes } from '@renderer/utils/formatBytes';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
@@ -36,7 +33,7 @@ const UNKNOWN_PROJECT_ID = '__unknown__';
/**
* Lifecycle-script PTYs are labelled by their terminal id (see
- * `createLifecycleScriptTerminalId`), which has no provider/conversation
+ * `createLifecycleScriptTerminalId`), which has no provider/session
* metadata. Map those ids to friendly labels so they don't render as the
* truncated "script-l…" leaf id.
*/
@@ -155,15 +152,14 @@ export function buildGroups(entries: ResourcePtyEntry[]): Group[] {
if (session) {
bucketKey = sessionId;
sessionName = session.displayName;
- const conv = getConversationsForSession(sessionId)?.conversations.get(entry.leafId);
- const terminal = getTerminalsForSession(sessionId)?.terminals.get(entry.leafId);
- providerId = conv?.data.providerId;
- displayTitle = conv?.data.title ?? terminal?.data.name;
+ const agent = entry.leafId === sessionId ? getSessionAgent(sessionId)?.agent : undefined;
+ providerId = agent?.data.providerId;
+ displayTitle = agent?.data.title;
}
}
// Fall back to metadata supplied by the sampler (covers cases where the
- // owning project isn't mounted, so the conversation/terminal join above misses).
+ // owning project isn't mounted, so the session/terminal join above misses).
providerId ??= entry.providerId;
displayTitle ??= entry.title;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx
index b52e3e7aa..93fb6c166 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/command-palette/resource-monitor-view.tsx
@@ -193,24 +193,19 @@ function AgentRow({ entry }: { entry: Entry }) {
>
{norm.toFixed(0)}% · {formatBytes(entry.memory)}
</span>
- <StopButton
- sessionId={entry.sessionId}
- label={label}
- armed={armed}
- onArmedChange={setArmed}
- />
+ <StopButton entry={entry} label={label} armed={armed} onArmedChange={setArmed} />
</div>
</div>
);
}
function StopButton({
- sessionId,
+ entry,
label,
armed,
onArmedChange,
}: {
- sessionId: string;
+ entry: Entry;
label: string;
armed: boolean;
onArmedChange: (armed: boolean) => void;
@@ -244,7 +239,13 @@ function StopButton({
clearReset();
setStopping(true);
try {
- await rpc.pty.stopSession(sessionId);
+ // Agent PTYs are session lifecycle (routed through the agent runtime so
+ // they stay stopped); terminals and lifecycle scripts are raw PTY stops.
+ if (entry.providerId) {
+ await rpc.sessions.stopAgent(entry.scopeId);
+ } else {
+ await rpc.pty.stopSession(entry.sessionId);
+ }
await appState.resourceMonitor.refresh();
setStopping(false);
onArmedChange(false);
@@ -253,7 +254,7 @@ function StopButton({
onArmedChange(false);
}
},
- [armed, stopping, sessionId, clearReset, onArmedChange]
+ [armed, stopping, entry, clearReset, onArmedChange]
);
if (armed) {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx b/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx
index 177de24dc..6bd3a1757 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/projects/components/session-view/session-row.tsx
@@ -8,7 +8,7 @@ import {
} from '@renderer/features/sessions/stores/session-selectors';
import { type SessionStore } from '@renderer/features/sessions/stores/session-store';
import { SessionRoomBadge } from '@renderer/features/switch-rooms/session-room-badge';
-import { StackedAgentLogos } from '@renderer/lib/components/stacked-agent-logos';
+import { AgentIcon } from '@renderer/lib/components/agent-icon';
import { useNavigate } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { Checkbox } from '@renderer/lib/ui/checkbox';
@@ -101,8 +101,15 @@ export const SessionRow = observer(function SessionRow({
<span className="min-w-0 truncate text-left text-sm">{session.data.title}</span>
</div>
</div>
- <SessionRoomBadge conversationId={session.data.id} />
- <StackedAgentLogos stats={session.conversationStats} />
+ <SessionRoomBadge sessionId={session.data.id} />
+ {session.agentProviderId && (
+ <span
+ className="relative flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-sm bg-background-2 ring-2 ring-background"
+ title={session.agentProviderId}
+ >
+ <AgentIcon id={session.agentProviderId} size={14} />
+ </span>
+ )}
<div
className={cn(
'flex min-w-8 shrink-0 items-center justify-end',
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.test.ts
deleted file mode 100644
index be12e8a7b..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ConversationManagerStore } from './conversation-manager';
-
-const hydrateConversation = vi.hoisted(() => vi.fn());
-const dehydrateConversation = vi.hoisted(() => vi.fn());
-const frontendConnect = vi.hoisted(() => vi.fn());
-const frontendDispose = vi.hoisted(() => vi.fn());
-
-vi.mock('@renderer/features/sessions/stores/open-file-in-file-editor', () => ({
- makeFileLinkHandlers: () => ({
- onOpenExternal: vi.fn(),
- onOpenFile: vi.fn(),
- }),
-}));
-
-vi.mock('@renderer/lib/ipc', () => ({
- events: { on: () => () => {} },
- rpc: {
- conversations: {
- dehydrateConversation,
- getConversationsForSession: vi.fn(),
- hydrateConversation,
- },
- },
-}));
-
-vi.mock('@renderer/lib/pty/pty', () => ({
- FrontendPty: class {
- constructor(readonly sessionId: string) {}
-
- connect = frontendConnect;
- dispose = frontendDispose;
- },
-}));
-
-describe('ConversationManagerStore session hydration', () => {
- beforeEach(() => {
- hydrateConversation.mockReset();
- dehydrateConversation.mockReset();
- frontendConnect.mockReset();
- frontendDispose.mockReset();
-
- hydrateConversation.mockResolvedValue(undefined);
- dehydrateConversation.mockResolvedValue(undefined);
- frontendConnect.mockResolvedValue(undefined);
- });
-
- it('does not hydrate conversations from the PTY session connect path', async () => {
- const store = new ConversationManagerStore('project-1', 'session-1', [
- {
- id: 'conversation-1',
- projectId: 'project-1',
- sessionId: 'session-1',
- providerId: 'codex',
- title: 'Conversation 1',
- lastInteractedAt: null,
- isInitialConversation: false,
- },
- ]);
-
- const session = store.sessions.get('conversation-1');
- expect(session).toBeDefined();
-
- await session?.connect();
-
- expect(hydrateConversation).not.toHaveBeenCalled();
- expect(frontendConnect).toHaveBeenCalledTimes(1);
-
- store.dispose();
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.ts
deleted file mode 100644
index a33855de3..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-manager.ts
+++ /dev/null
@@ -1,357 +0,0 @@
-import type { IDisposable } from '@switchdash/shared';
-import { action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
-import { makeFileLinkHandlers } from '@renderer/features/sessions/stores/file-link-handlers';
-import { events, rpc } from '@renderer/lib/ipc';
-import { PtySession } from '@renderer/lib/pty/pty-session';
-import { Resource } from '@renderer/lib/stores/resource';
-import { log } from '@renderer/utils/logger';
-import { soundPlayer } from '@renderer/utils/soundPlayer';
-import {
- conversationAgentStatusChangedChannel,
- conversationChangedChannel,
- conversationCreatedChannel,
-} from '@shared/core/conversations/conversationEvents';
-import {
- type Conversation,
- type CreateConversationParams,
-} from '@shared/core/conversations/conversations';
-import {
- agentSessionExitedChannel,
- type AgentStatus,
- type NotificationType,
-} from '@shared/core/providers/agentEvents';
-import { makePtySessionId } from '@shared/core/pty/ptySessionId';
-
-export class ConversationManagerStore implements IDisposable {
- private offAgentStatusChanged: (() => void) | null = null;
- private offSessionExited: (() => void) | null = null;
- private offConversationCreated: (() => void) | null = null;
- private offConversationChanges: (() => void) | null = null;
- private readonly _disposeReaction: () => void;
-
- /** Data layer: plain Conversation records loaded from the main process. */
- readonly list: Resource<Conversation[]>;
- /** Runtime state stores keyed by conversation id — populated by reaction on list.data. */
- conversations = observable.map<string, ConversationStore>();
- /** Session layer keyed by conversation id — created alongside data, connected lazily. */
- sessions = observable.map<string, PtySession>();
-
- constructor(
- private readonly projectId: string,
- private readonly sessionId: string,
- preloaded?: Conversation[]
- ) {
- makeObservable(this, {
- conversations: observable,
- sessions: observable,
- sessionStatus: computed,
- });
-
- const hasPreloaded = preloaded !== undefined;
- this.list = new Resource<Conversation[]>(
- hasPreloaded ? null : () => rpc.sessions.getConversationsForSession(projectId, sessionId),
- hasPreloaded ? [] : [{ kind: 'demand' }],
- hasPreloaded ? { init: preloaded } : undefined
- );
-
- // When preloaded data is available, populate the maps synchronously so
- // they are accessible immediately — even when this constructor is called
- // from within a MobX action, where reaction callbacks (including
- // fireImmediately) are deferred until the outermost action completes.
- if (preloaded) {
- runInAction(() => {
- for (const conversation of preloaded) {
- if (!this.conversations.has(conversation.id)) {
- this.conversations.set(conversation.id, new ConversationStore(conversation));
- }
- if (!this.sessions.has(conversation.id)) {
- this.sessions.set(conversation.id, this.createSession(conversation));
- }
- }
- });
- }
-
- // Sync conversations and sessions maps whenever resource data changes.
- // fireImmediately handles the non-preloaded case; for preloaded data the
- // maps are already populated above so this is a no-op on first run.
- this._disposeReaction = reaction(
- () => this.list.data,
- (data) => {
- if (!data) return;
- runInAction(() => {
- for (const conversation of data) {
- if (!this.conversations.has(conversation.id)) {
- this.conversations.set(conversation.id, new ConversationStore(conversation));
- }
- if (!this.sessions.has(conversation.id)) {
- this.sessions.set(conversation.id, this.createSession(conversation));
- }
- }
- });
- },
- { fireImmediately: true }
- );
-
- this.offAgentStatusChanged = this.listenToAgentStatusChanged();
- this.offSessionExited = this.listenToSessionExited();
- this.offConversationCreated = this.listenToConversationCreated();
- this.offConversationChanges = this.listenToConversationChanges();
- }
-
- private addConversation(conversation: Conversation): void {
- if (!this.conversations.has(conversation.id)) {
- this.conversations.set(conversation.id, new ConversationStore(conversation));
- }
- if (!this.sessions.has(conversation.id)) {
- this.sessions.set(conversation.id, this.createSession(conversation));
- }
- }
-
- private listenToAgentStatusChanged(): () => void {
- return events.on(conversationAgentStatusChangedChannel, (payload) => {
- if (payload.sessionId !== this.sessionId) return;
- const conversationStore = this.conversations.get(payload.conversationId);
- if (!conversationStore) return;
-
- runInAction(() => {
- conversationStore.status = payload.status;
- conversationStore.seen = payload.seen;
- if (payload.status !== 'awaiting-input') {
- conversationStore.lastNotificationType = null;
- }
- });
-
- if (payload.soundEvent) {
- soundPlayer.play(payload.soundEvent, true);
- }
- });
- }
-
- private listenToSessionExited(): () => void {
- return events.on(agentSessionExitedChannel, (event) => {
- if (event.sessionId !== this.sessionId) return;
- const conversationStore = this.conversations.get(event.conversationId);
- if (!conversationStore) return;
- conversationStore.clearWorking();
- });
- }
-
- private listenToConversationCreated(): () => void {
- return events.on(conversationCreatedChannel, ({ conversation }) => {
- if (conversation.sessionId !== this.sessionId || conversation.projectId !== this.projectId)
- return;
- runInAction(() => {
- this.addConversation(conversation);
- });
- });
- }
-
- private listenToConversationChanges(): () => void {
- return events.on(conversationChangedChannel, (event) => {
- if (event.sessionId !== this.sessionId) return;
- const store = this.conversations.get(event.conversationId);
- if (!store) return;
- runInAction(() => {
- Object.assign(store.data, event.changes);
- });
- });
- }
-
- get sessionStatus(): AgentStatus | null {
- let hasWorking = false;
- let hasUnseenError = false;
- let hasUnseenCompleted = false;
- for (const conversation of this.conversations.values()) {
- if (!conversation.seen && conversation.status === 'awaiting-input') return 'awaiting-input';
- if (conversation.status === 'working') hasWorking = true;
- if (!conversation.seen && conversation.status === 'error') hasUnseenError = true;
- if (!conversation.seen && conversation.status === 'completed') hasUnseenCompleted = true;
- }
- if (hasWorking) return 'working';
- if (hasUnseenError) return 'error';
- if (hasUnseenCompleted) return 'completed';
- return null;
- }
-
- async createConversation(params: CreateConversationParams): Promise<Conversation> {
- const conversation = await rpc.sessions.createConversation(params);
- runInAction(() => {
- this.addConversation(conversation);
- if (params.initialPrompt?.trim()) {
- this.conversations.get(conversation.id)?.setWorking();
- }
- });
- return conversation;
- }
-
- async markConversationWorking(conversationId: string): Promise<void> {
- if (!this.list.data) {
- await this.list.load();
- }
-
- runInAction(() => {
- const store = this.conversations.get(conversationId);
- if (!store) {
- log.warn(`ConversationManagerStore: conversation ${conversationId} not found after load`, {
- projectId: this.projectId,
- sessionId: this.sessionId,
- });
- return;
- }
- store.setWorking();
- });
- }
-
- async hydrateConversation(conversationId: string): Promise<void> {
- await rpc.sessions.hydrateConversation(this.projectId, this.sessionId, conversationId);
- }
-
- async dehydrateConversation(conversationId: string): Promise<void> {
- const session = this.sessions.get(conversationId);
- session?.dispose();
- await rpc.sessions.dehydrateConversation(this.projectId, this.sessionId, conversationId);
- }
-
- async deleteConversation(conversationId: string): Promise<void> {
- const store = this.conversations.get(conversationId);
- const session = this.sessions.get(conversationId);
- if (!store) return;
-
- runInAction(() => {
- this.conversations.delete(conversationId);
- this.sessions.delete(conversationId);
- });
-
- try {
- await rpc.sessions.deleteConversation(this.projectId, this.sessionId, conversationId);
- session?.destroy();
- } catch (err) {
- runInAction(() => {
- this.conversations.set(conversationId, store);
- if (session) this.sessions.set(conversationId, session);
- });
- throw err;
- }
- }
-
- async renameConversation(conversationId: string, name: string): Promise<void> {
- const store = this.conversations.get(conversationId);
- if (!store) return;
-
- const previousTitle = store.data.title;
-
- runInAction(() => {
- store.data.title = name;
- });
-
- try {
- await rpc.sessions.renameConversation(conversationId, name);
- } catch (err) {
- runInAction(() => {
- store.data.title = previousTitle;
- });
- throw err;
- }
- }
-
- dispose(): void {
- this._disposeReaction();
- this.offAgentStatusChanged?.();
- this.offAgentStatusChanged = null;
- this.offSessionExited?.();
- this.offSessionExited = null;
- this.offConversationCreated?.();
- this.offConversationCreated = null;
- this.offConversationChanges?.();
- this.offConversationChanges = null;
- for (const session of this.sessions.values()) {
- session.destroy();
- }
- }
-
- private createSession(conversation: Conversation): PtySession {
- const handlers = makeFileLinkHandlers(conversation.projectId, conversation.sessionId);
- return new PtySession(
- makePtySessionId(conversation.projectId, conversation.sessionId, conversation.id),
- undefined,
- handlers.onOpenFile,
- handlers.onOpenExternal,
- { clearOnBackendStart: true }
- );
- }
-}
-
-export class ConversationStore {
- data: Conversation;
- status: AgentStatus;
- seen: boolean;
- lastNotificationType: NotificationType | null = null;
-
- constructor(conversation: Conversation) {
- this.data = conversation;
- this.status = conversation.agentStatus ?? 'idle';
- this.seen = conversation.agentStatusSeen ?? true;
- makeObservable(this, {
- data: observable,
- status: observable,
- seen: observable,
- lastNotificationType: observable,
- setStatus: action,
- setAwaitingInput: action,
- setWorking: action,
- clearWorking: action,
- markSeen: action,
- isInitialConversation: computed,
- indicatorStatus: computed,
- });
- }
-
- get isInitialConversation(): boolean {
- return this.data.isInitialConversation === true;
- }
-
- get indicatorStatus(): AgentStatus | null {
- if (this.status === 'working') return 'working';
- if (this.seen) return null;
- if (this.status === 'awaiting-input') return 'awaiting-input';
- if (this.status === 'error') return 'error';
- if (this.status === 'completed') return 'completed';
- return null;
- }
-
- setStatus(status: AgentStatus) {
- this.status = status;
- this.seen = status === 'idle' || status === 'working';
- if (status !== 'awaiting-input') {
- this.lastNotificationType = null;
- }
- }
-
- setAwaitingInput(notificationType: NotificationType) {
- this.lastNotificationType = notificationType;
- this.setStatus('awaiting-input');
- }
-
- setWorking() {
- if (this.status === 'awaiting-input' && this.lastNotificationType === 'permission_prompt') {
- return;
- }
- this.lastNotificationType = null;
- this.setStatus('working');
- }
-
- clearWorking() {
- if (this.status === 'working' || this.status === 'awaiting-input') {
- this.setStatus('idle');
- }
- }
-
- markSeen() {
- this.seen = true;
- void rpc.sessions.markConversationSeen(this.data.id);
- }
-
- dispose() {
- // Session is managed by ConversationManagerStore.sessions — nothing to do here.
- }
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-title-utils.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-title-utils.ts
deleted file mode 100644
index 4a193d912..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/conversation-title-utils.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { type AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-
-type ConversationTitleInput = {
- providerId: AgentProviderId;
- title: string;
-};
-
-function capitalizeProviderId(providerId: AgentProviderId): string {
- return `${providerId.charAt(0).toUpperCase()}${providerId.slice(1)}`;
-}
-
-function parseDefaultTitleIndex(title: string, providerId: AgentProviderId): number | null {
- const match = title.match(new RegExp(`^${providerId} \\(([1-9]\\d*)\\)$`, 'i'));
- if (!match) return null;
-
- const rawIndex = match[1];
- const index = Number(rawIndex);
- if (!Number.isInteger(index) || index < 1) return null;
- if (String(index) !== rawIndex) return null;
- return index;
-}
-
-export function formatConversationTitleForDisplay(
- providerId: AgentProviderId,
- title: string
-): string {
- const index = parseDefaultTitleIndex(title, providerId);
- if (index === null) return title;
- return `${capitalizeProviderId(providerId)} (${index})`;
-}
-
-export function nextDefaultConversationTitle(
- providerId: AgentProviderId,
- conversations: ConversationTitleInput[]
-): string {
- const used = new Set<number>();
-
- for (const conversation of conversations) {
- if (conversation.providerId !== providerId) continue;
- const index = parseDefaultTitleIndex(conversation.title, providerId);
- if (index !== null) used.add(index);
- }
-
- let next = 1;
- while (used.has(next)) next += 1;
-
- return `${capitalizeProviderId(providerId)} (${next})`;
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/provider-selection.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/provider-selection.ts
deleted file mode 100644
index 1e59b08ed..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/provider-selection.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import {
- AGENT_PROVIDER_IDS,
- type AgentProviderId,
-} from '@shared/core/providers/agent-provider-registry';
-
-type ResolveConversationProviderSelectionParams = {
- defaultProviderId: AgentProviderId;
- providerOverride: AgentProviderId | null;
- installedProviderIds: AgentProviderId[];
- availabilityKnown: boolean;
-};
-
-export type ConversationProviderSelection = {
- providerId: AgentProviderId | null;
- createDisabled: boolean;
-};
-
-export function resolveConversationProviderSelection({
- defaultProviderId,
- providerOverride,
- installedProviderIds,
- availabilityKnown,
-}: ResolveConversationProviderSelectionParams): ConversationProviderSelection {
- const installedSet = new Set(installedProviderIds);
- const fallbackProviderId =
- availabilityKnown && !installedSet.has(defaultProviderId)
- ? AGENT_PROVIDER_IDS.find((id) => installedSet.has(id))
- : undefined;
-
- const noInstalledAgents = availabilityKnown && installedSet.size === 0;
- const effectiveDefaultProviderId = noInstalledAgents
- ? null
- : (fallbackProviderId ?? defaultProviderId);
- const providerId = providerOverride ?? effectiveDefaultProviderId;
- const providerInstalled = providerId ? installedSet.has(providerId) : false;
-
- return {
- providerId,
- createDisabled: providerId === null || (availabilityKnown && !providerInstalled),
- };
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/use-effective-provider.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/use-effective-provider.ts
deleted file mode 100644
index 878bcd06c..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/conversations/use-effective-provider.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useMemo, useState } from 'react';
-import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
-import { useAgentInstallationStatuses } from '@renderer/lib/stores/use-agent-installation-statuses';
-import {
- isValidProviderId,
- type AgentProviderId,
-} from '@shared/core/providers/agent-provider-registry';
-import { resolveConversationProviderSelection } from './provider-selection';
-
-export type EffectiveProvider = {
- providerId: AgentProviderId | null;
- setProviderOverride: (id: AgentProviderId | null) => void;
- createDisabled: boolean;
-};
-
-export function useEffectiveProvider(
- connectionId?: string,
- initialOverride?: AgentProviderId
-): EffectiveProvider {
- const [providerOverride, setProviderOverride] = useState<AgentProviderId | null>(
- initialOverride ?? null
- );
-
- const { value: defaultAgentValue } = useAppSettingsKey('defaultAgent');
- const defaultProviderId: AgentProviderId = isValidProviderId(defaultAgentValue)
- ? defaultAgentValue
- : 'claude';
-
- const { data: statuses } = useAgentInstallationStatuses(connectionId);
- const availabilityKnown = statuses !== undefined;
-
- const installedProviderIds = useMemo(
- () =>
- (statuses ?? []).filter((s) => s.status === 'available').map((s) => s.id as AgentProviderId),
- [statuses]
- );
-
- const { providerId, createDisabled } = resolveConversationProviderSelection({
- defaultProviderId,
- providerOverride,
- installedProviderIds,
- availabilityKnown,
- });
-
- return { providerId, setProviderOverride, createDisabled };
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx
index ed67f7583..0fd3fe35f 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-terminal.tsx
@@ -3,7 +3,7 @@ import { observer } from 'mobx-react-lite';
import { useEffect, useRef } from 'react';
import { useIsActiveSession } from '@renderer/features/sessions/hooks/use-is-active-session';
import {
- useConversations,
+ useSessionAgent,
useSessionViewContext,
useWorkspaceId,
useWorkspaceViewModel,
@@ -15,21 +15,20 @@ import { useTerminalSearch } from '@renderer/lib/pty/use-terminal-search';
/**
* The entire session view: one `claude` terminal. A switchdash session has
- * exactly one conversation, so we mount its PTY directly — no tabs, no panes,
+ * exactly one agent, so we mount its PTY directly — no tabs, no panes,
* no context bar.
*/
export const SessionTerminal = observer(function SessionTerminal() {
const { sessionId } = useSessionViewContext();
const sessionView = useWorkspaceViewModel();
- const conversations = useConversations();
+ const agentStore = useSessionAgent();
const workspaceId = useWorkspaceId();
const isActive = useIsActiveSession(sessionId);
const autoFocus = isActive && sessionView.focusedRegion === 'main';
- // A session has a single conversation — take the first one.
- const conversation = conversations.conversations.values().next().value;
- const session = conversation ? (conversations.sessions.get(conversation.data.id) ?? null) : null;
+ const agent = agentStore.agent;
+ const session = agentStore.pty;
const ptySessionId = session?.sessionId ?? null;
const containerRef = useRef<HTMLDivElement>(null);
@@ -71,7 +70,7 @@ export const SessionTerminal = observer(function SessionTerminal() {
}
}, [sessionStatus]);
- const onInterruptPress = conversation ? () => conversation.clearWorking() : undefined;
+ const onInterruptPress = agent ? () => agent.clearWorking() : undefined;
return (
<div
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx
index e58fa873a..768b2f91e 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/session-view-context.tsx
@@ -1,18 +1,16 @@
import { observer } from 'mobx-react-lite';
import { createContext, useContext, type ReactNode } from 'react';
import { ProjectViewWrapper } from '@renderer/features/projects/components/project-view-wrapper';
-import type { ConversationManagerStore } from '@renderer/features/sessions/conversations/conversation-manager';
+import type { SessionAgentStore } from '@renderer/features/sessions/stores/session-agent-store';
import {
- getConversationsForSession,
+ getSessionAgent,
getSessionStore,
- getTerminalsForSession,
getWorkspaceForSession,
sessionViewKind,
type SessionViewKind,
} from '@renderer/features/sessions/stores/session-selectors';
import type { WorkspaceStore } from '@renderer/features/sessions/stores/workspace';
import type { WorkspaceViewModel } from '@renderer/features/sessions/stores/workspace-view-model';
-import type { TerminalManagerStore } from '@renderer/features/sessions/terminals/terminal-manager';
interface SessionViewContext {
projectId: string;
@@ -82,22 +80,12 @@ export function useWorkspaceViewModel(): WorkspaceViewModel {
return viewModel;
}
-/** Returns the ConversationManagerStore for the session. Throws if not registered. */
-export function useConversations(): ConversationManagerStore {
+/** Returns the SessionAgentStore for the session. Throws if not registered. */
+export function useSessionAgent(): SessionAgentStore {
const { sessionId } = useSessionViewContext();
- const mgr = getConversationsForSession(sessionId);
- if (!mgr) {
- throw new Error('useConversations: session is not registered (no conversation manager)');
+ const store = getSessionAgent(sessionId);
+ if (!store) {
+ throw new Error('useSessionAgent: session is not registered (no session-agent store)');
}
- return mgr;
-}
-
-/** Returns the TerminalManagerStore for the session. Throws if not registered. */
-export function useTerminals(): TerminalManagerStore {
- const { sessionId } = useSessionViewContext();
- const mgr = getTerminalsForSession(sessionId);
- if (!mgr) {
- throw new Error('useTerminals: session is not registered (no terminal manager)');
- }
- return mgr;
+ return store;
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.test.ts
deleted file mode 100644
index 701e30af3..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.test.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import {
- ConversationHydrationReconciler,
- DEHYDRATE_RETRY_DELAY_MS,
- type ConversationSessionAdapter,
-} from './conversation-hydration-reconciler';
-
-function deferred<T = void>(): {
- promise: Promise<T>;
- resolve: (value: T | PromiseLike<T>) => void;
- reject: (reason?: unknown) => void;
-} {
- let resolve: (value: T | PromiseLike<T>) => void = () => {};
- let reject: (reason?: unknown) => void = () => {};
- const promise = new Promise<T>((res, rej) => {
- resolve = res;
- reject = rej;
- });
- return { promise, resolve, reject };
-}
-
-function makeHarness() {
- const adapter: ConversationSessionAdapter = {
- hydrateConversation: vi.fn().mockResolvedValue(undefined),
- dehydrateConversation: vi.fn().mockResolvedValue(undefined),
- };
- const logger = { warn: vi.fn() };
- const reconciler = new ConversationHydrationReconciler({
- sessionId: 'session-1',
- getConversations: () => adapter,
- log: logger,
- });
- return {
- adapter,
- logger,
- reconciler,
- hydrateConversation: vi.mocked(adapter.hydrateConversation),
- dehydrateConversation: vi.mocked(adapter.dehydrateConversation),
- };
-}
-
-describe('ConversationHydrationReconciler', () => {
- it('hydrates desired conversations', async () => {
- const { reconciler, hydrateConversation } = makeHarness();
-
- reconciler.sync(['conversation-1']);
- await Promise.resolve();
-
- expect(hydrateConversation).toHaveBeenCalledTimes(1);
- expect(hydrateConversation).toHaveBeenCalledWith('conversation-1');
- });
-
- it('dedupes repeated syncs while hydrate is in flight', () => {
- const { reconciler, hydrateConversation } = makeHarness();
- hydrateConversation.mockReturnValue(deferred().promise);
-
- reconciler.sync(['conversation-1']);
- reconciler.sync(['conversation-1']);
-
- expect(hydrateConversation).toHaveBeenCalledTimes(1);
- });
-
- it('dehydrates when hydrate finishes after the conversation is no longer desired', async () => {
- const { reconciler, hydrateConversation, dehydrateConversation } = makeHarness();
- const hydrate = deferred();
- hydrateConversation.mockReturnValue(hydrate.promise);
-
- reconciler.sync(['conversation-1']);
- reconciler.sync([]);
-
- expect(dehydrateConversation).not.toHaveBeenCalled();
-
- hydrate.resolve();
- await hydrate.promise;
- await Promise.resolve();
-
- expect(dehydrateConversation).toHaveBeenCalledTimes(1);
- expect(dehydrateConversation).toHaveBeenCalledWith('conversation-1');
- });
-
- it('accepts a hydrate that finishes after close and reopen', async () => {
- const { reconciler, hydrateConversation, dehydrateConversation } = makeHarness();
- const hydrate = deferred();
- hydrateConversation.mockReturnValue(hydrate.promise);
-
- reconciler.sync(['conversation-1']);
- reconciler.sync([]);
- reconciler.sync(['conversation-1']);
-
- hydrate.resolve();
- await hydrate.promise;
- await Promise.resolve();
-
- expect(dehydrateConversation).not.toHaveBeenCalled();
- expect(hydrateConversation).toHaveBeenCalledTimes(1);
- });
-
- it('rehydrates when dehydrate finishes after the conversation is desired again', async () => {
- const { reconciler, hydrateConversation, dehydrateConversation } = makeHarness();
- const dehydrate = deferred();
- dehydrateConversation.mockReturnValueOnce(dehydrate.promise);
-
- reconciler.sync(['conversation-1']);
- await Promise.resolve();
- expect(hydrateConversation).toHaveBeenCalledTimes(1);
-
- reconciler.sync([]);
- reconciler.sync(['conversation-1']);
-
- dehydrate.resolve();
- await dehydrate.promise;
- await Promise.resolve();
- await Promise.resolve();
-
- expect(hydrateConversation).toHaveBeenCalledTimes(2);
- });
-
- it('does not mark as hydrated when hydrate fails', async () => {
- const { reconciler, hydrateConversation, dehydrateConversation, logger } = makeHarness();
- hydrateConversation.mockRejectedValueOnce(new Error('hydrate failed'));
-
- reconciler.sync(['conversation-1']);
- await Promise.resolve();
- await Promise.resolve();
-
- expect(logger.warn).toHaveBeenCalledTimes(1);
-
- reconciler.sync([]);
- await Promise.resolve();
-
- expect(dehydrateConversation).not.toHaveBeenCalled();
- });
-
- it('stops hydrated conversations on dispose', async () => {
- const { reconciler, dehydrateConversation } = makeHarness();
-
- reconciler.sync(['conversation-1']);
- await Promise.resolve();
-
- reconciler.dispose();
- await Promise.resolve();
-
- expect(dehydrateConversation).toHaveBeenCalledTimes(1);
- expect(dehydrateConversation).toHaveBeenCalledWith('conversation-1');
- });
-
- it('retries failed dehydrate without waiting for another sync', async () => {
- vi.useFakeTimers();
- try {
- const { reconciler, dehydrateConversation, logger } = makeHarness();
- dehydrateConversation
- .mockRejectedValueOnce(new Error('dehydrate failed'))
- .mockResolvedValueOnce(undefined);
-
- reconciler.sync(['conversation-1']);
- await Promise.resolve();
-
- reconciler.sync([]);
- await Promise.resolve();
-
- expect(dehydrateConversation).toHaveBeenCalledTimes(1);
- expect(logger.warn).toHaveBeenCalledTimes(1);
-
- await vi.advanceTimersByTimeAsync(DEHYDRATE_RETRY_DELAY_MS);
-
- expect(dehydrateConversation).toHaveBeenCalledTimes(2);
- expect(dehydrateConversation).toHaveBeenLastCalledWith('conversation-1');
- } finally {
- vi.useRealTimers();
- }
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.ts
deleted file mode 100644
index a96746105..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-hydration-reconciler.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import type { IDisposable } from '@switchdash/shared';
-
-export type ConversationSessionAdapter = {
- hydrateConversation(conversationId: string): Promise<void>;
- dehydrateConversation(conversationId: string): Promise<void>;
-};
-
-type Logger = {
- warn(message: string, data?: unknown): void;
-};
-
-type ConversationHydrationReconcilerOptions = {
- sessionId: string;
- getConversations: () => ConversationSessionAdapter | undefined;
- log: Logger;
-};
-
-type SessionState = 'stopped' | 'starting' | 'running' | 'stopping';
-
-export const DEHYDRATE_RETRY_DELAY_MS = 500;
-
-type Entry = {
- desired: boolean;
- state: SessionState;
- dehydrateRetryTimer: ReturnType<typeof setTimeout> | null;
-};
-
-export class ConversationHydrationReconciler implements IDisposable {
- private readonly sessionId: string;
- private readonly getConversations: () => ConversationSessionAdapter | undefined;
- private readonly log: Logger;
- private readonly entries = new Map<string, Entry>();
- private disposed = false;
-
- constructor({ sessionId, getConversations, log }: ConversationHydrationReconcilerOptions) {
- this.sessionId = sessionId;
- this.getConversations = getConversations;
- this.log = log;
- }
-
- sync(openConversationIds: Iterable<string>): void {
- if (this.disposed) return;
-
- const desired = new Set(openConversationIds);
- const ids = new Set([...this.entries.keys(), ...desired]);
-
- for (const id of ids) {
- const entry = this.getOrCreateEntry(id);
- entry.desired = desired.has(id);
- if (entry.desired) this.clearDehydrateRetry(entry);
- this.reconcile(id, entry);
- this.cleanupIfIdle(id, entry);
- }
- }
-
- dispose(): void {
- this.disposed = true;
- for (const [id, entry] of this.entries) {
- this.clearDehydrateRetry(entry);
- entry.desired = false;
- this.reconcile(id, entry);
- this.cleanupIfIdle(id, entry);
- }
- }
-
- private getOrCreateEntry(id: string): Entry {
- const existing = this.entries.get(id);
- if (existing) return existing;
- const entry: Entry = { desired: false, state: 'stopped', dehydrateRetryTimer: null };
- this.entries.set(id, entry);
- return entry;
- }
-
- private reconcile(id: string, entry: Entry): void {
- if (entry.desired && entry.state === 'stopped') {
- void this.hydrate(id, entry);
- return;
- }
- if (!entry.desired && entry.state === 'running') {
- void this.dehydrate(id, entry);
- }
- }
-
- private async hydrate(id: string, entry: Entry): Promise<void> {
- const conversations = this.getConversations();
- if (!conversations) return;
-
- entry.state = 'starting';
- try {
- await conversations.hydrateConversation(id);
- } catch (error) {
- entry.state = 'stopped';
- this.log.warn('ConversationHydrationReconciler: failed to hydrate conversation', {
- sessionId: this.sessionId,
- conversationId: id,
- error,
- });
- this.cleanupIfIdle(id, entry);
- return;
- }
-
- entry.state = 'running';
- // intent may have flipped while we awaited — tear down if no longer wanted
- if (entry.desired) return;
- void this.dehydrate(id, entry, 'stale-hydrate');
- }
-
- private async dehydrate(
- id: string,
- entry: Entry,
- reason: 'sync' | 'stale-hydrate' = 'sync'
- ): Promise<void> {
- const conversations = this.getConversations();
- if (!conversations) {
- entry.state = 'stopped';
- this.cleanupIfIdle(id, entry);
- return;
- }
-
- entry.state = 'stopping';
- try {
- await conversations.dehydrateConversation(id);
- } catch (error) {
- entry.state = 'running';
- this.log.warn(
- reason === 'stale-hydrate'
- ? 'ConversationHydrationReconciler: failed to dehydrate stale conversation'
- : 'ConversationHydrationReconciler: failed to dehydrate conversation',
- {
- sessionId: this.sessionId,
- conversationId: id,
- error,
- }
- );
- if (!entry.desired) this.scheduleDehydrateRetry(id, entry);
- return;
- }
-
- entry.state = 'stopped';
- this.clearDehydrateRetry(entry);
- // intent may have flipped while we awaited — restart if wanted again
- if (entry.desired) {
- this.reconcile(id, entry);
- return;
- }
- this.cleanupIfIdle(id, entry);
- }
-
- private cleanupIfIdle(id: string, entry: Entry): void {
- if (entry.desired || entry.state !== 'stopped') return;
- this.clearDehydrateRetry(entry);
- this.entries.delete(id);
- }
-
- private scheduleDehydrateRetry(id: string, entry: Entry): void {
- if (this.disposed || entry.dehydrateRetryTimer) return;
- entry.dehydrateRetryTimer = setTimeout(() => {
- entry.dehydrateRetryTimer = null;
- if (this.entries.get(id) !== entry || entry.desired) return;
- this.reconcile(id, entry);
- this.cleanupIfIdle(id, entry);
- }, DEHYDRATE_RETRY_DELAY_MS);
- }
-
- private clearDehydrateRetry(entry: Entry): void {
- if (!entry.dehydrateRetryTimer) return;
- clearTimeout(entry.dehydrateRetryTimer);
- entry.dehydrateRetryTimer = null;
- }
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-registry.ts
deleted file mode 100644
index 6eee57cda..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/conversation-registry.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { ConversationManagerStore } from '@renderer/features/sessions/conversations/conversation-manager';
-import type { Conversation } from '@shared/core/conversations/conversations';
-
-export class ConversationRegistry {
- private readonly entries = new Map<string, ConversationManagerStore>();
-
- acquire(
- sessionId: string,
- projectId: string,
- preloaded?: Conversation[]
- ): ConversationManagerStore {
- const existing = this.entries.get(sessionId);
- if (existing) return existing;
- const store = new ConversationManagerStore(projectId, sessionId, preloaded);
- this.entries.set(sessionId, store);
- return store;
- }
-
- get(sessionId: string): ConversationManagerStore | undefined {
- return this.entries.get(sessionId);
- }
-
- release(sessionId: string): void {
- const store = this.entries.get(sessionId);
- if (!store) return;
- store.dispose();
- this.entries.delete(sessionId);
- }
-}
-
-export const conversationRegistry = new ConversationRegistry();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts
new file mode 100644
index 000000000..f5805c2f4
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-registry.ts
@@ -0,0 +1,27 @@
+import { SessionAgentStore } from '@renderer/features/sessions/stores/session-agent-store';
+import type { Session } from '@shared/core/sessions/sessions';
+
+export class SessionAgentRegistry {
+ private readonly entries = new Map<string, SessionAgentStore>();
+
+ acquire(sessionId: string, projectId: string, preloaded?: Session[]): SessionAgentStore {
+ const existing = this.entries.get(sessionId);
+ if (existing) return existing;
+ const store = new SessionAgentStore(projectId, sessionId, preloaded);
+ this.entries.set(sessionId, store);
+ return store;
+ }
+
+ get(sessionId: string): SessionAgentStore | undefined {
+ return this.entries.get(sessionId);
+ }
+
+ release(sessionId: string): void {
+ const store = this.entries.get(sessionId);
+ if (!store) return;
+ store.dispose();
+ this.entries.delete(sessionId);
+ }
+}
+
+export const sessionAgentRegistry = new SessionAgentRegistry();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts
new file mode 100644
index 000000000..63c6e1c9e
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SessionAgentStore } from './session-agent-store';
+
+const hydrateSession = vi.hoisted(() => vi.fn());
+const dehydrateSession = vi.hoisted(() => vi.fn());
+const frontendConnect = vi.hoisted(() => vi.fn());
+const frontendDispose = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/features/sessions/stores/open-file-in-file-editor', () => ({
+ makeFileLinkHandlers: () => ({
+ onOpenExternal: vi.fn(),
+ onOpenFile: vi.fn(),
+ }),
+}));
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: {
+ sessions: {
+ dehydrateSession,
+ getSession: vi.fn(),
+ hydrateSession,
+ },
+ },
+}));
+
+vi.mock('@renderer/lib/pty/pty', () => ({
+ FrontendPty: class {
+ constructor(readonly sessionId: string) {}
+
+ connect = frontendConnect;
+ dispose = frontendDispose;
+ },
+}));
+
+describe('SessionAgentStore hydration', () => {
+ beforeEach(() => {
+ hydrateSession.mockReset();
+ dehydrateSession.mockReset();
+ frontendConnect.mockReset();
+ frontendDispose.mockReset();
+
+ hydrateSession.mockResolvedValue(undefined);
+ dehydrateSession.mockResolvedValue(undefined);
+ frontendConnect.mockResolvedValue(undefined);
+ });
+
+ const now = '2024-01-01T00:00:00.000Z';
+ const sessionRecord = {
+ id: 'session-1',
+ agentId: 'agent-1',
+ providerId: 'codex' as const,
+ title: 'Session 1',
+ shellId: 'system' as const,
+ status: 'in_progress' as const,
+ statusChangedAt: now,
+ agentSessionId: null,
+ isInitialSession: false,
+ isPinned: false,
+ createdAt: now,
+ updatedAt: now,
+ };
+
+ it('does not hydrate the session from the PTY session connect path', async () => {
+ const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);
+
+ const session = store.pty;
+ expect(session).toBeDefined();
+
+ await session?.connect();
+
+ expect(hydrateSession).not.toHaveBeenCalled();
+ expect(frontendConnect).toHaveBeenCalledTimes(1);
+
+ store.dispose();
+ });
+
+ it('hydrates when desired and dehydrates when released', async () => {
+ const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);
+
+ store.setHydrationDesired(true);
+ await vi.waitFor(() => expect(hydrateSession).toHaveBeenCalledTimes(1));
+
+ store.setHydrationDesired(false);
+ await vi.waitFor(() => expect(dehydrateSession).toHaveBeenCalledTimes(1));
+
+ store.dispose();
+ });
+
+ it('tears back down when intent flips while a hydrate is in flight', async () => {
+ let resolveHydrate: (() => void) | undefined;
+ hydrateSession.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveHydrate = resolve;
+ })
+ );
+ const store = new SessionAgentStore('project-1', 'session-1', [sessionRecord]);
+
+ store.setHydrationDesired(true);
+ await vi.waitFor(() => expect(hydrateSession).toHaveBeenCalledTimes(1));
+ store.setHydrationDesired(false);
+ resolveHydrate?.();
+ await vi.waitFor(() => expect(dehydrateSession).toHaveBeenCalledTimes(1));
+
+ store.dispose();
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts
new file mode 100644
index 000000000..e6e5a8b59
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-agent-store.ts
@@ -0,0 +1,327 @@
+import type { IDisposable } from '@switchdash/shared';
+import { action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
+import { makeFileLinkHandlers } from '@renderer/features/sessions/stores/file-link-handlers';
+import { events, rpc } from '@renderer/lib/ipc';
+import { PtySession } from '@renderer/lib/pty/pty-session';
+import { Resource } from '@renderer/lib/stores/resource';
+import { log } from '@renderer/utils/logger';
+import { soundPlayer } from '@renderer/utils/soundPlayer';
+import {
+ agentSessionExitedChannel,
+ type AgentStatus,
+ type NotificationType,
+} from '@shared/core/providers/agentEvents';
+import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';
+import {
+ sessionAgentStatusChangedChannel,
+ sessionChangedChannel,
+} from '@shared/core/sessions/sessionEvents';
+import { type Session } from '@shared/core/sessions/sessions';
+
+export const DEHYDRATE_RETRY_DELAY_MS = 500;
+
+type HydrationState = 'stopped' | 'starting' | 'running' | 'stopping';
+
+/**
+ * Renderer-side handle for a session's single agent: its status store, its PTY
+ * session, and the hydrate/dehydrate lifecycle that connects the agent PTY
+ * while the session view is provisioned. One instance per session, held in the
+ * session-agent registry.
+ */
+export class SessionAgentStore implements IDisposable {
+ private offAgentStatusChanged: (() => void) | null = null;
+ private offSessionExited: (() => void) | null = null;
+ private offSessionChanges: (() => void) | null = null;
+ private readonly _disposeReaction: () => void;
+
+ /** Data layer: the session record loaded from the main process (1:1 with this store). */
+ readonly list: Resource<Session[]>;
+ /** The session's single agent-status store — null until the session record loads. */
+ agent: AgentStatusStore | null = null;
+ /** The agent's PTY session — created alongside the record, connected lazily. */
+ pty: PtySession | null = null;
+
+ // Hydration lifecycle: desired-vs-actual for the agent PTY, with the same
+ // stale-flip handling and dehydrate retry the old reconciler had.
+ private hydrationDesired = false;
+ private hydrationState: HydrationState = 'stopped';
+ private dehydrateRetryTimer: ReturnType<typeof setTimeout> | null = null;
+ private hydrationDisposed = false;
+
+ constructor(
+ private readonly projectId: string,
+ private readonly sessionId: string,
+ preloaded?: Session[]
+ ) {
+ makeObservable(this, {
+ agent: observable,
+ pty: observable,
+ sessionStatus: computed,
+ });
+
+ const hasPreloaded = preloaded !== undefined;
+ this.list = new Resource<Session[]>(
+ hasPreloaded ? null : () => rpc.sessions.getSession(sessionId).then((s) => (s ? [s] : [])),
+ hasPreloaded ? [] : [{ kind: 'demand' }],
+ hasPreloaded ? { init: preloaded } : undefined
+ );
+
+ // When preloaded data is available, populate synchronously so the store is
+ // usable immediately — even when this constructor is called from within a
+ // MobX action, where reaction callbacks (including fireImmediately) are
+ // deferred until the outermost action completes.
+ if (preloaded) {
+ runInAction(() => this.adopt(preloaded[0]));
+ }
+
+ // Adopt the session record whenever resource data changes. fireImmediately
+ // handles the non-preloaded case; for preloaded data the store is already
+ // populated above so this is a no-op on first run.
+ this._disposeReaction = reaction(
+ () => this.list.data,
+ (data) => {
+ if (!data?.length) return;
+ runInAction(() => this.adopt(data[0]));
+ },
+ { fireImmediately: true }
+ );
+
+ this.offAgentStatusChanged = this.listenToAgentStatusChanged();
+ this.offSessionExited = this.listenToSessionExited();
+ this.offSessionChanges = this.listenToSessionChanges();
+ }
+
+ private adopt(session: Session | undefined): void {
+ if (!session) return;
+ if (!this.agent) {
+ this.agent = new AgentStatusStore(session);
+ }
+ if (!this.pty) {
+ const handlers = makeFileLinkHandlers(this.projectId, this.sessionId);
+ this.pty = new PtySession(
+ makeAgentPtySessionId(this.projectId, this.sessionId),
+ undefined,
+ handlers.onOpenFile,
+ handlers.onOpenExternal,
+ { clearOnBackendStart: true }
+ );
+ }
+ }
+
+ private listenToAgentStatusChanged(): () => void {
+ return events.on(sessionAgentStatusChangedChannel, (payload) => {
+ if (payload.sessionId !== this.sessionId) return;
+ const agent = this.agent;
+ if (!agent) return;
+
+ runInAction(() => {
+ agent.status = payload.status;
+ agent.seen = payload.seen;
+ if (payload.status !== 'awaiting-input') {
+ agent.lastNotificationType = null;
+ }
+ });
+
+ if (payload.soundEvent) {
+ soundPlayer.play(payload.soundEvent, true);
+ }
+ });
+ }
+
+ private listenToSessionExited(): () => void {
+ return events.on(agentSessionExitedChannel, (event) => {
+ if (event.sessionId !== this.sessionId) return;
+ this.agent?.clearWorking();
+ });
+ }
+
+ private listenToSessionChanges(): () => void {
+ return events.on(sessionChangedChannel, (event) => {
+ if (event.sessionId !== this.sessionId) return;
+ const agent = this.agent;
+ if (!agent) return;
+ runInAction(() => {
+ Object.assign(agent.data, event.changes);
+ });
+ });
+ }
+
+ /** The session's agent status as shown on sidebar badges and notifications. */
+ get sessionStatus(): AgentStatus | null {
+ return this.agent?.indicatorStatus ?? null;
+ }
+
+ async markWorking(): Promise<void> {
+ if (!this.list.data) {
+ await this.list.load();
+ }
+
+ runInAction(() => {
+ if (!this.agent) {
+ log.warn(`SessionAgentStore: session ${this.sessionId} not found after load`, {
+ projectId: this.projectId,
+ });
+ return;
+ }
+ this.agent.setWorking();
+ });
+ }
+
+ // --- Hydration lifecycle -------------------------------------------------
+
+ /** Keep the agent PTY hydrated while the session view is provisioned. */
+ setHydrationDesired(desired: boolean): void {
+ if (this.hydrationDisposed) return;
+ this.hydrationDesired = desired;
+ if (desired) this.clearDehydrateRetry();
+ this.reconcileHydration();
+ }
+
+ private reconcileHydration(): void {
+ if (this.hydrationDesired && this.hydrationState === 'stopped') {
+ void this.hydrate();
+ return;
+ }
+ if (!this.hydrationDesired && this.hydrationState === 'running') {
+ void this.dehydrate();
+ }
+ }
+
+ private async hydrate(): Promise<void> {
+ this.hydrationState = 'starting';
+ try {
+ await rpc.sessions.hydrateSession(this.projectId, this.sessionId);
+ } catch (error) {
+ this.hydrationState = 'stopped';
+ log.warn('SessionAgentStore: failed to hydrate session', {
+ sessionId: this.sessionId,
+ error,
+ });
+ return;
+ }
+
+ this.hydrationState = 'running';
+ // intent may have flipped while we awaited — tear down if no longer wanted
+ if (this.hydrationDesired) return;
+ void this.dehydrate('stale-hydrate');
+ }
+
+ private async dehydrate(reason: 'sync' | 'stale-hydrate' = 'sync'): Promise<void> {
+ this.hydrationState = 'stopping';
+ this.pty?.dispose();
+ try {
+ await rpc.sessions.dehydrateSession(this.projectId, this.sessionId);
+ } catch (error) {
+ this.hydrationState = 'running';
+ log.warn(
+ reason === 'stale-hydrate'
+ ? 'SessionAgentStore: failed to dehydrate stale session'
+ : 'SessionAgentStore: failed to dehydrate session',
+ { sessionId: this.sessionId, error }
+ );
+ if (!this.hydrationDesired) this.scheduleDehydrateRetry();
+ return;
+ }
+
+ this.hydrationState = 'stopped';
+ this.clearDehydrateRetry();
+ // intent may have flipped while we awaited — restart if wanted again
+ if (this.hydrationDesired) this.reconcileHydration();
+ }
+
+ private scheduleDehydrateRetry(): void {
+ if (this.hydrationDisposed || this.dehydrateRetryTimer) return;
+ this.dehydrateRetryTimer = setTimeout(() => {
+ this.dehydrateRetryTimer = null;
+ if (this.hydrationDesired) return;
+ this.reconcileHydration();
+ }, DEHYDRATE_RETRY_DELAY_MS);
+ }
+
+ private clearDehydrateRetry(): void {
+ if (!this.dehydrateRetryTimer) return;
+ clearTimeout(this.dehydrateRetryTimer);
+ this.dehydrateRetryTimer = null;
+ }
+
+ dispose(): void {
+ this.hydrationDesired = false;
+ if (this.hydrationState === 'running') void this.dehydrate();
+ this.hydrationDisposed = true;
+ this.clearDehydrateRetry();
+ this._disposeReaction();
+ this.offAgentStatusChanged?.();
+ this.offAgentStatusChanged = null;
+ this.offSessionExited?.();
+ this.offSessionExited = null;
+ this.offSessionChanges?.();
+ this.offSessionChanges = null;
+ this.pty?.destroy();
+ }
+}
+
+export class AgentStatusStore {
+ data: Session;
+ status: AgentStatus;
+ seen: boolean;
+ lastNotificationType: NotificationType | null = null;
+
+ constructor(session: Session) {
+ this.data = session;
+ this.status = session.agentStatus ?? 'idle';
+ this.seen = session.agentStatusSeen ?? true;
+ makeObservable(this, {
+ data: observable,
+ status: observable,
+ seen: observable,
+ lastNotificationType: observable,
+ setStatus: action,
+ setAwaitingInput: action,
+ setWorking: action,
+ clearWorking: action,
+ markSeen: action,
+ indicatorStatus: computed,
+ });
+ }
+
+ get indicatorStatus(): AgentStatus | null {
+ if (this.status === 'working') return 'working';
+ if (this.seen) return null;
+ if (this.status === 'awaiting-input') return 'awaiting-input';
+ if (this.status === 'error') return 'error';
+ if (this.status === 'completed') return 'completed';
+ return null;
+ }
+
+ setStatus(status: AgentStatus) {
+ this.status = status;
+ this.seen = status === 'idle' || status === 'working';
+ if (status !== 'awaiting-input') {
+ this.lastNotificationType = null;
+ }
+ }
+
+ setAwaitingInput(notificationType: NotificationType) {
+ this.lastNotificationType = notificationType;
+ this.setStatus('awaiting-input');
+ }
+
+ setWorking() {
+ if (this.status === 'awaiting-input' && this.lastNotificationType === 'permission_prompt') {
+ return;
+ }
+ this.lastNotificationType = null;
+ this.setStatus('working');
+ }
+
+ clearWorking() {
+ if (this.status === 'working' || this.status === 'awaiting-input') {
+ this.setStatus('idle');
+ }
+ }
+
+ markSeen() {
+ this.seen = true;
+ void rpc.sessions.markSessionSeen(this.data.id);
+ }
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
index 18225936e..81651e49e 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.test.ts
@@ -12,17 +12,14 @@ type MockViewModel = {
const mocks = vi.hoisted(() => ({
archiveSession: vi.fn(),
- conversationAcquire: vi.fn(),
- conversationRelease: vi.fn(),
- getConversationsForProject: vi.fn(),
+ agentAcquire: vi.fn(),
+ agentRelease: vi.fn(),
getProjectManagerStore: vi.fn(),
getSessionGitWorktreeStore: vi.fn(),
getSessions: vi.fn(),
mountProject: vi.fn(),
provisionWorkspace: vi.fn(),
teardownSession: vi.fn(),
- terminalAcquire: vi.fn(),
- terminalRelease: vi.fn(),
viewModels: [] as MockViewModel[],
viewStateGet: vi.fn(),
workspaceActivate: vi.fn(),
@@ -41,7 +38,6 @@ vi.mock('@renderer/lib/ipc', () => ({
},
sessions: {
archiveSession: mocks.archiveSession,
- getConversationsForProject: mocks.getConversationsForProject,
getSessions: mocks.getSessions,
provisionWorkspace: mocks.provisionWorkspace,
teardownSession: mocks.teardownSession,
@@ -91,19 +87,11 @@ vi.mock('./workspace-registry', () => ({
},
}));
-vi.mock('./conversation-registry', () => ({
- conversationRegistry: {
- acquire: mocks.conversationAcquire,
+vi.mock('./session-agent-registry', () => ({
+ sessionAgentRegistry: {
+ acquire: mocks.agentAcquire,
get: vi.fn(),
- release: mocks.conversationRelease,
- },
-}));
-
-vi.mock('./terminal-registry', () => ({
- terminalRegistry: {
- acquire: mocks.terminalAcquire,
- get: vi.fn(),
- release: mocks.terminalRelease,
+ release: mocks.agentRelease,
},
}));
@@ -134,7 +122,6 @@ describe('SessionManagerStore archive lifecycle', () => {
vi.clearAllMocks();
mocks.viewModels.length = 0;
mocks.archiveSession.mockResolvedValue(undefined);
- mocks.getConversationsForProject.mockResolvedValue([]);
mocks.getProjectManagerStore.mockReturnValue({ mountProject: mocks.mountProject });
mocks.getSessions.mockResolvedValue([]);
mocks.mountProject.mockResolvedValue(undefined);
@@ -160,8 +147,7 @@ describe('SessionManagerStore archive lifecycle', () => {
expect(mocks.archiveSession).toHaveBeenCalledWith('project-1', 'session-1');
expect(mocks.teardownSession).not.toHaveBeenCalled();
- expect(mocks.conversationRelease).toHaveBeenCalledWith('session-1');
- expect(mocks.terminalRelease).toHaveBeenCalledWith('session-1');
+ expect(mocks.agentRelease).toHaveBeenCalledWith('session-1');
expect(viewModel.dispose).toHaveBeenCalledOnce();
expect(store.state).toBe('unprovisioned');
expect(store.phase).toBe('idle');
@@ -181,8 +167,7 @@ describe('SessionManagerStore archive lifecycle', () => {
await manager.provisionSession(session.id);
- expect(mocks.conversationAcquire).toHaveBeenCalledWith('session-1', 'project-1');
- expect(mocks.terminalAcquire).toHaveBeenCalledWith('session-1', 'project-1');
+ expect(mocks.agentAcquire).toHaveBeenCalledWith('session-1', 'project-1');
expect(store.state).toBe('provisioned');
expect(store.viewModel).toBe(mocks.viewModels[1]);
expect(mocks.viewModels[1].initialize).toHaveBeenCalledOnce();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts
index d0618dc58..a7a8074f9 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-manager.ts
@@ -3,7 +3,6 @@ import { toast } from 'sonner';
import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';
import type { ProjectSettingsStore } from '@renderer/features/projects/stores/project-settings-store';
import { events, rpc } from '@renderer/lib/ipc';
-import type { Conversation } from '@shared/core/conversations/conversations';
import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
import {
lifecycleScriptStatusChannel,
@@ -16,9 +15,10 @@ import {
import type {
CreateSessionError,
CreateSessionParams,
+ Session,
SessionLifecycleStatus,
} from '@shared/core/sessions/sessions';
-import { conversationRegistry } from './conversation-registry';
+import { sessionAgentRegistry } from './session-agent-registry';
import {
createUnprovisionedSession,
createUnregisteredSession,
@@ -28,7 +28,6 @@ import {
isUnregistered,
type SessionStore,
} from './session-store';
-import { terminalRegistry } from './terminal-registry';
import { workspaceRegistry } from './workspace-registry';
function formatCreateSessionError(error: CreateSessionError): string {
@@ -73,17 +72,10 @@ export class SessionManagerStore {
if (!agent || agent.projectId !== this.projectId || this.sessions.has(session.id)) return;
runInAction(() => {
this.sessions.set(session.id, createUnprovisionedSession(this.projectId, session));
- // Acquire conversation/terminal managers inside the same action so the
- // WorkspaceViewModel's reaction on `conversations.size` registers the
- // manager's observable map as a dependency on its first evaluation.
- // Pass no preloaded list: this session was created elsewhere (the
- // auto-session watcher / another window), so there is no optimistic
- // conversation to seed. An empty array would mark the manager as fully
- // preloaded with zero conversations and disable its demand fetch,
- // leaving the terminal stuck on a spinner; omitting it lets the manager
- // load the real conversation via getConversationsForSession.
- conversationRegistry.acquire(session.id, this.projectId);
- terminalRegistry.acquire(session.id, this.projectId);
+ // This session was created elsewhere (the auto-session watcher /
+ // another window), so there is no record to seed — omit the preloaded
+ // list so the store demand-fetches the real session record.
+ sessionAgentRegistry.acquire(session.id, this.projectId);
// A provisioned event for this session may have arrived first (the
// automation path emits created→provisioned back-to-back). Apply it
// now so the session reaches 'ready' without waiting for a restart.
@@ -171,33 +163,20 @@ export class SessionManagerStore {
}
private _releaseSessionRegistries(sessionId: string): void {
- conversationRegistry.release(sessionId);
- terminalRegistry.release(sessionId);
+ sessionAgentRegistry.release(sessionId);
}
loadSessions(): Promise<void> {
if (!this._loadPromise) {
- this._loadPromise = Promise.all([
- rpc.sessions.getSessions(this.projectId),
- rpc.sessions.getConversationsForProject(this.projectId),
- ])
- .then(([sessions, allConversations]) => {
- const conversationsBySession = new Map<string, Conversation[]>();
- for (const conv of allConversations) {
- const list = conversationsBySession.get(conv.sessionId) ?? [];
- list.push(conv);
- conversationsBySession.set(conv.sessionId, list);
- }
+ this._loadPromise = rpc.sessions
+ .getSessions(this.projectId)
+ .then((sessions) => {
runInAction(() => {
for (const t of sessions) {
this.sessions.set(t.id, createUnprovisionedSession(this.projectId, t));
- // Preload conversations for each session so sidebar badges are available immediately.
- conversationRegistry.acquire(
- t.id,
- this.projectId,
- conversationsBySession.get(t.id) ?? []
- );
- terminalRegistry.acquire(t.id, this.projectId);
+ // Seed the agent store with the session record so sidebar badges
+ // are available immediately.
+ sessionAgentRegistry.acquire(t.id, this.projectId, [t]);
}
});
})
@@ -235,42 +214,41 @@ export class SessionManagerStore {
}
const providerId = agent.providerId;
- const clearOptimisticInitialConversationWorking = () => {
+ const clearOptimisticInitialWorking = () => {
if (!params.initialPrompt?.trim()) return;
- conversationRegistry
- .acquire(params.id, this.projectId)
- .conversations.get(params.id)
- ?.clearWorking();
+ sessionAgentRegistry.acquire(params.id, this.projectId).agent?.clearWorking();
};
runInAction(() => {
- // A session is its own (single) conversation in switchdash; create the
- // optimistic conversation record keyed by the session id.
- const optimistic: Conversation = {
+ // Create the optimistic session record keyed by the session id.
+ const now = new Date().toISOString();
+ const optimistic: Session = {
id: params.id,
- projectId: this.projectId,
- sessionId: params.id,
+ agentId: params.agentId,
providerId: providerId as AgentProviderId,
title: params.title,
- lastInteractedAt: null,
+ shellId: params.shellId ?? 'system',
+ status: 'in_progress',
+ statusChangedAt: now,
+ agentSessionId: null,
+ isInitialSession: true,
+ isPinned: false,
autoApprove: params.autoApprove ?? false,
subagentName: params.subagentName,
- isInitialConversation: true,
+ createdAt: now,
+ updatedAt: now,
};
- const conversationManager = conversationRegistry.acquire(params.id, this.projectId, [
- optimistic,
- ]);
+ const agentStore = sessionAgentRegistry.acquire(params.id, this.projectId, [optimistic]);
if (params.initialPrompt?.trim()) {
- void conversationManager.markConversationWorking(params.id);
+ void agentStore.markWorking();
}
- terminalRegistry.acquire(params.id, this.projectId);
});
const result = await rpc.sessions
.createSession(JSON.parse(JSON.stringify(toJS(params))) as typeof params)
.catch((e: unknown) => {
const message = e instanceof Error ? e.message : String(e);
- clearOptimisticInitialConversationWorking();
+ clearOptimisticInitialWorking();
runInAction(() => {
const current = this.sessions.get(params.id);
if (current && isUnregistered(current)) {
@@ -283,7 +261,7 @@ export class SessionManagerStore {
if (!result.success) {
const message = formatCreateSessionError(result.error);
- clearOptimisticInitialConversationWorking();
+ clearOptimisticInitialWorking();
runInAction(() => {
const current = this.sessions.get(params.id);
if (current && isUnregistered(current)) {
@@ -298,7 +276,7 @@ export class SessionManagerStore {
const current = this.sessions.get(params.id);
if (current && isUnregistered(current)) {
current.transitionToUnprovisioned(result.data.session, 'provision');
- // Conversation and terminal registries already acquired in the optimistic phase.
+ // The session-agent registry entry was already acquired in the optimistic phase.
}
});
@@ -352,8 +330,7 @@ export class SessionManagerStore {
runInAction(() => {
const current = this.sessions.get(sessionId);
if (current && isUnprovisioned(current)) {
- conversationRegistry.acquire(sessionId, this.projectId);
- terminalRegistry.acquire(sessionId, this.projectId);
+ sessionAgentRegistry.acquire(sessionId, this.projectId);
current.ensureRegisteredStores();
current.transitionToProvisioned(
{ ...current.data, lastInteractedAt: new Date().toISOString() },
@@ -388,8 +365,7 @@ export class SessionManagerStore {
private _applyProvisioned(sessionId: string, path: string, workspaceId: string): void {
const current = this.sessions.get(sessionId);
if (current && isUnprovisioned(current)) {
- conversationRegistry.acquire(sessionId, this.projectId);
- terminalRegistry.acquire(sessionId, this.projectId);
+ sessionAgentRegistry.acquire(sessionId, this.projectId);
current.ensureRegisteredStores();
current.transitionToProvisioned(
{ ...current.data, lastInteractedAt: new Date().toISOString() },
@@ -524,7 +500,7 @@ export class SessionManagerStore {
});
try {
- // Release conversation and terminal registries before disposing each session.
+ // Release the session-agent registry entry before disposing each session.
removed.forEach((t, id) => {
this._releaseSessionRegistries(id);
t.dispose();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts
index c9b8b8139..e966cd488 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-selectors.ts
@@ -2,7 +2,7 @@ import { isUnmountedProject } from '@renderer/features/projects/stores/project';
import { getProjectManagerStore } from '@renderer/features/projects/stores/project-selectors';
import type { AgentStatus } from '@shared/core/providers/agentEvents';
import type { Session } from '@shared/core/sessions/sessions';
-import { conversationRegistry } from './conversation-registry';
+import { sessionAgentRegistry } from './session-agent-registry';
import type { SessionManagerStore } from './session-manager';
import {
isProvisioned,
@@ -11,7 +11,6 @@ import {
registeredSessionData,
type SessionStore,
} from './session-store';
-import { terminalRegistry } from './terminal-registry';
import { workspaceRegistry } from './workspace-registry';
import type { WorkspaceViewModel } from './workspace-view-model';
@@ -45,8 +44,8 @@ export function getSessionView(
}
export function sessionAgentStatus(store: SessionStore): AgentStatus | null {
- const mgr = conversationRegistry.get(store.data.id);
- return mgr?.sessionStatus ?? null;
+ const agent = sessionAgentRegistry.get(store.data.id);
+ return agent?.sessionStatus ?? null;
}
export type SessionViewKind =
@@ -125,12 +124,8 @@ export function getWorkspaceViewModel(
return getSessionStore(projectId, sessionId)?.viewModel ?? undefined;
}
-export function getConversationsForSession(sessionId: string) {
- return conversationRegistry.get(sessionId);
-}
-
-export function getTerminalsForSession(sessionId: string) {
- return terminalRegistry.get(sessionId);
+export function getSessionAgent(sessionId: string) {
+ return sessionAgentRegistry.get(sessionId);
}
/** Returns the display name from any session store variant. */
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts
index 64533c1e8..2480dd83a 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.test.ts
@@ -35,12 +35,6 @@ vi.mock('./workspace-registry', () => ({
},
}));
-vi.mock('./conversation-registry', () => ({
- conversationRegistry: {
- get: vi.fn(),
- },
-}));
-
vi.mock('@renderer/lib/ipc', () => ({
events: {
on: vi.fn(() => () => {}),
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts
index 38836febf..a6fad30c2 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/session-store.ts
@@ -8,7 +8,6 @@ import type {
Session,
SessionLifecycleStatus,
} from '@shared/core/sessions/sessions';
-import { conversationRegistry } from './conversation-registry';
import { workspaceRegistry } from './workspace-registry';
import { WorkspaceViewModel } from './workspace-view-model';
@@ -156,22 +155,10 @@ export class SessionStore {
}
}
- get conversationStats(): Record<string, number> {
- if (this.state === 'unregistered') {
- return {};
- }
- if (this.state === 'provisioned') {
- const mgr = conversationRegistry.get(this.data.id);
- if (mgr) {
- const counts: Record<string, number> = {};
- for (const conv of mgr.conversations.values()) {
- const id = conv.data.providerId;
- counts[id] = (counts[id] ?? 0) + 1;
- }
- return counts;
- }
- }
- return {};
+ /** The provider of this session's agent, for the sidebar row logo. */
+ get agentProviderId(): string | null {
+ if (!isRegistered(this)) return null;
+ return this.data.providerId ?? null;
}
async rename(name: string): Promise<Result<RenameSessionSuccess, RenameSessionError>> {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/terminal-registry.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/terminal-registry.ts
deleted file mode 100644
index 25cbe3344..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/terminal-registry.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { observable } from 'mobx';
-import { TerminalManagerStore } from '@renderer/features/sessions/terminals/terminal-manager';
-
-export class TerminalRegistry {
- private readonly entries = observable.map<string, TerminalManagerStore>();
-
- acquire(sessionId: string, projectId: string): TerminalManagerStore {
- const existing = this.entries.get(sessionId);
- if (existing) return existing;
- const store = new TerminalManagerStore(projectId, sessionId);
- this.entries.set(sessionId, store);
- return store;
- }
-
- get(sessionId: string): TerminalManagerStore | undefined {
- return this.entries.get(sessionId);
- }
-
- release(sessionId: string): void {
- const store = this.entries.get(sessionId);
- if (!store) return;
- store.dispose();
- this.entries.delete(sessionId);
- }
-}
-
-export const terminalRegistry = new TerminalRegistry();
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx
index 474af6908..46e88b5dc 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/stores/workspace-view-model.tsx
@@ -1,17 +1,15 @@
import type { ILifecycle } from '@switchdash/shared';
-import { makeAutoObservable, reaction } from 'mobx';
-import { log } from '@renderer/utils/logger';
+import { makeAutoObservable } from 'mobx';
import type { Session } from '@shared/core/sessions/sessions';
-import { ConversationHydrationReconciler } from './conversation-hydration-reconciler';
-import { conversationRegistry } from './conversation-registry';
+import { sessionAgentRegistry } from './session-agent-registry';
import type { SessionStore } from './session-store';
/**
* A switchdash session is a single `claude` terminal. The switchdash multi-pane
* workspace (tabs, splits, diff/editor/browser, terminal drawer) has been
- * removed — this view model only keeps the session's one conversation hydrated,
- * which is what connects its PTY. The terminal itself is rendered by
- * `SessionTerminal`.
+ * removed — this view model only keeps the session's agent hydrated while the
+ * session is provisioned, which is what connects its PTY. The terminal itself
+ * is rendered by `SessionTerminal`.
*/
export class WorkspaceViewModel implements ILifecycle {
/** Which region of the session view has focus. Kept for the terminal pane. */
@@ -19,45 +17,25 @@ export class WorkspaceViewModel implements ILifecycle {
readonly sessionId: string;
- private readonly _hydration: ConversationHydrationReconciler;
- private _disposers: (() => void)[] = [];
private _active = false;
- constructor(private readonly _sessionStore: SessionStore) {
+ constructor(_sessionStore: SessionStore) {
this.sessionId = (_sessionStore.data as Session).id;
- this._hydration = new ConversationHydrationReconciler({
- sessionId: this.sessionId,
- getConversations: () => conversationRegistry.get(this.sessionId),
- log,
- });
- makeAutoObservable<WorkspaceViewModel, '_hydration'>(this, { _hydration: false });
+ makeAutoObservable(this);
}
/** Called when the session becomes provisioned. */
initialize(): void {
if (this._active) return;
this._active = true;
-
- // Keep every conversation for this session hydrated. Sessions have exactly one,
- // so this connects (and keeps connected) the single claude PTY.
- this._disposers.push(
- reaction(
- () => {
- const conversations = conversationRegistry.get(this.sessionId);
- return conversations ? [...conversations.conversations.keys()].sort() : [];
- },
- (ids) => this._hydration.sync(ids),
- { fireImmediately: true }
- )
- );
+ sessionAgentRegistry.get(this.sessionId)?.setHydrationDesired(true);
}
/** Called when the session becomes unprovisioned. */
suspend(): void {
- for (const dispose of this._disposers) dispose();
- this._disposers = [];
- this._hydration.dispose();
+ if (!this._active) return;
this._active = false;
+ sessionAgentRegistry.get(this.sessionId)?.setHydrationDesired(false);
}
dispose(): void {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.test.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.test.ts
deleted file mode 100644
index 09c770c7a..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { getTabbedPtySessionId, getTabbedPtySessionIds } from './tabbed-pty-panel-sessions';
-
-describe('tabbed PTY panel session identity', () => {
- it('uses the session-owned id instead of a recomputed entity id', () => {
- const entity = {
- data: { id: 'script-id' },
- session: { sessionId: 'project:workspace:script-id' },
- };
-
- const recomputedId = `project:session:${entity.data.id}`;
- const sessionId = getTabbedPtySessionId(entity, (item) => item.session);
-
- expect(sessionId).toBe('project:workspace:script-id');
- expect(sessionId).not.toBe(recomputedId);
- });
-
- it('derives all pane session ids from their owned sessions', () => {
- const entities = [
- { session: { sessionId: 'project:workspace:setup' }, recomputedId: 'project:session:setup' },
- { session: { sessionId: 'project:workspace:run' }, recomputedId: 'project:session:run' },
- ];
-
- expect(getTabbedPtySessionIds(entities, (item) => item.session)).toEqual([
- 'project:workspace:setup',
- 'project:workspace:run',
- ]);
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.ts
deleted file mode 100644
index 386bab59b..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel-sessions.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-export type SessionIdOwner = {
- sessionId: string;
-};
-
-export function getTabbedPtySessionId<TEntity>(
- entity: TEntity,
- getSession: (entity: TEntity) => SessionIdOwner
-): string {
- return getSession(entity).sessionId;
-}
-
-export function getTabbedPtySessionIds<TEntity>(
- entities: TEntity[],
- getSession: (entity: TEntity) => SessionIdOwner
-): string[] {
- return entities.map((entity) => getTabbedPtySessionId(entity, getSession));
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel.tsx
deleted file mode 100644
index eaa8abd2d..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/tabbed-pty-panel.tsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import { observer } from 'mobx-react-lite';
-import React, { useEffect, useMemo, useRef } from 'react';
-import { PaneSizingProvider } from '@renderer/lib/pty/pane-sizing-context';
-import { PtyPane } from '@renderer/lib/pty/pty-pane';
-import { type PtySession } from '@renderer/lib/pty/pty-session';
-import { TerminalSearchOverlay } from '@renderer/lib/pty/terminal-search-overlay';
-import { useTerminalSearch } from '@renderer/lib/pty/use-terminal-search';
-import { type TabViewProvider } from '@renderer/lib/stores/generic-tab-view';
-import { cn } from '@renderer/utils/utils';
-import { getTabbedPtySessionIds } from './tabbed-pty-panel-sessions';
-
-export interface TabbedPtyPanelProps<TEntity> {
- store: TabViewProvider<TEntity, never> | undefined;
- getSession: (entity: TEntity) => PtySession;
- paneId: string;
- tabBar: React.ReactNode;
- emptyState: React.ReactNode;
- autoFocus?: boolean;
- onFocusChange?: (focused: boolean) => void;
- onEnterPress?: (entity: TEntity) => void;
- onInterruptPress?: (entity: TEntity) => void;
- mapShiftEnterToCtrlJ?: boolean;
- workspaceId: string;
-}
-
-export const TabbedPtyPanel = observer(function TabbedPtyPanel<TEntity>({
- store,
- getSession,
- paneId,
- tabBar,
- emptyState,
- autoFocus,
- onFocusChange,
- onEnterPress,
- onInterruptPress,
- mapShiftEnterToCtrlJ,
- workspaceId,
-}: TabbedPtyPanelProps<TEntity>) {
- const tabs = useMemo(() => store?.tabs ?? [], [store?.tabs]);
- const activeTab = store?.activeTab;
-
- const allSessionIds = useMemo(
- () => getTabbedPtySessionIds(tabs, getSession),
-
- [tabs, getSession]
- );
-
- const activeSession = activeTab ? getSession(activeTab) : null;
- const activeSessionId = activeSession?.sessionId ?? null;
- const activeOnEnterPress = activeTab && onEnterPress ? () => onEnterPress(activeTab) : undefined;
- const activeOnInterruptPress =
- activeTab && onInterruptPress ? () => onInterruptPress(activeTab) : undefined;
-
- const containerRef = useRef<HTMLDivElement>(null);
- const terminalContainerRef = useRef<HTMLDivElement>(null);
- const terminalRef = useRef<{ focus: () => void }>(null);
- const focusPendingRef = useRef(false);
- const {
- isSearchOpen,
- searchQuery,
- searchStatus,
- searchInputRef,
- closeSearch,
- handleSearchQueryChange,
- stepSearch,
- } = useTerminalSearch({
- terminal: activeSession?.pty?.terminal,
- containerRef: terminalContainerRef,
- enabled: Boolean(activeSession?.pty),
- onCloseFocus: () => terminalRef.current?.focus(),
- });
-
- // Fire when autoFocus becomes true (session switch) or the active session changes.
- // If the terminal is already mounted, focus immediately; otherwise hold focus on
- // the container so keyboard input has a home while the PTY is connecting.
- useEffect(() => {
- if (!autoFocus) return;
- if (terminalRef.current) {
- terminalRef.current.focus();
- focusPendingRef.current = false;
- } else {
- containerRef.current?.focus();
- focusPendingRef.current = true;
- }
- }, [autoFocus, activeSessionId]);
-
- // Fire when the session transitions to 'ready' (MobX observer re-renders automatically
- // because activeSession?.status is read in the render body below).
- const sessionStatus = activeSession?.status;
- useEffect(() => {
- if (sessionStatus === 'ready' && focusPendingRef.current) {
- focusPendingRef.current = false;
- terminalRef.current?.focus();
- }
- }, [sessionStatus]);
-
- return (
- <div
- ref={containerRef}
- tabIndex={-1}
- className="flex h-full flex-col outline-none"
- onFocus={() => {
- onFocusChange?.(true);
- }}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- onFocusChange?.(false);
- }
- }}
- >
- <div className="shrink-0">{tabBar}</div>
- <PaneSizingProvider paneId={paneId} sessionIds={allSessionIds}>
- {tabs.length === 0 ? (
- emptyState
- ) : (
- <div className={cn('flex min-h-0 flex-1 flex-col')}>
- {activeSessionId && activeSession?.status === 'ready' && activeSession.pty ? (
- <div ref={terminalContainerRef} className="relative flex h-full min-h-0 flex-1">
- <TerminalSearchOverlay
- isOpen={isSearchOpen}
- fullWidth
- searchQuery={searchQuery}
- searchStatus={searchStatus}
- searchInputRef={searchInputRef}
- onQueryChange={handleSearchQueryChange}
- onStep={stepSearch}
- onClose={closeSearch}
- />
- <PtyPane
- ref={terminalRef}
- sessionId={activeSessionId}
- pty={activeSession.pty}
- className="h-full w-full"
- onEnterPress={activeOnEnterPress}
- onInterruptPress={activeOnInterruptPress}
- mapShiftEnterToCtrlJ={mapShiftEnterToCtrlJ}
- workspaceId={workspaceId}
- />
- </div>
- ) : null}
- </div>
- )}
- </PaneSizingProvider>
- </div>
- );
-}) as <TEntity>(props: TabbedPtyPanelProps<TEntity>) => React.ReactElement;
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-manager.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-manager.ts
deleted file mode 100644
index d5061993d..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-manager.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { IDisposable } from '@switchdash/shared';
-import { makeObservable, observable } from 'mobx';
-import type { PtySession } from '@renderer/lib/pty/pty-session';
-import { type Terminal } from '@shared/core/terminals/terminals';
-
-/**
- * In switchdash a session is 1:1 with its shell (`session.shellId`) — there is
- * no separate `terminals` table or RPC namespace. This store is retained only so
- * existing consumers (session view context, resource monitor) keep compiling; it
- * holds no terminals and performs no I/O. Per-session PTY hydration is driven by
- * the conversation manager instead.
- */
-export class TerminalManagerStore implements IDisposable {
- readonly projectId: string;
- readonly sessionId: string;
- terminals = observable.map<string, TerminalStore>();
- sessions = observable.map<string, PtySession>();
-
- constructor(projectId: string, sessionId: string) {
- this.projectId = projectId;
- this.sessionId = sessionId;
- makeObservable(this, {
- terminals: observable,
- sessions: observable,
- });
- }
-
- get isLoaded(): boolean {
- return true;
- }
-
- dispose(): void {
- for (const session of this.sessions.values()) {
- session.destroy();
- }
- }
-}
-
-export class TerminalStore {
- data: Terminal;
-
- constructor(terminal: Terminal) {
- this.data = terminal;
- makeObservable(this, { data: observable });
- }
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-pty-content.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-pty-content.tsx
deleted file mode 100644
index 2743f605e..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/terminals/terminal-pty-content.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-import { observer } from 'mobx-react-lite';
-import { useEffect, useMemo, useRef, type ReactNode } from 'react';
-import { PaneSizingProvider } from '@renderer/lib/pty/pane-sizing-context';
-import { PtyPane } from '@renderer/lib/pty/pty-pane';
-import { type PtySession } from '@renderer/lib/pty/pty-session';
-import { TerminalSearchOverlay } from '@renderer/lib/pty/terminal-search-overlay';
-import { useTerminalSearch } from '@renderer/lib/pty/use-terminal-search';
-import { cssVar } from '@renderer/utils/cssVars';
-import { cn } from '@renderer/utils/utils';
-
-export interface TerminalPtyContentProps {
- activeSession: PtySession | null;
- allSessionIds: string[];
- paneId: string;
- autoFocus?: boolean;
- onFocusChange?: (focused: boolean) => void;
- onEnterPress?: () => void;
- onInterruptPress?: () => void;
- mapShiftEnterToCtrlJ?: boolean;
- emptyState: ReactNode;
- workspaceId: string;
- className?: string;
-}
-
-export const TerminalPtyContent = observer(function TerminalPtyContent({
- activeSession,
- allSessionIds,
- paneId,
- autoFocus,
- onFocusChange,
- onEnterPress,
- onInterruptPress,
- mapShiftEnterToCtrlJ,
- emptyState,
- workspaceId,
- className,
-}: TerminalPtyContentProps) {
- const activeSessionId = activeSession?.sessionId ?? null;
-
- const containerRef = useRef<HTMLDivElement>(null);
- const terminalContainerRef = useRef<HTMLDivElement>(null);
- const terminalRef = useRef<{ focus: () => void }>(null);
- const focusPendingRef = useRef(false);
-
- const {
- isSearchOpen,
- searchQuery,
- searchStatus,
- searchInputRef,
- closeSearch,
- handleSearchQueryChange,
- stepSearch,
- } = useTerminalSearch({
- terminal: activeSession?.pty?.terminal,
- containerRef: terminalContainerRef,
- enabled: Boolean(activeSession?.pty),
- onCloseFocus: () => terminalRef.current?.focus(),
- });
-
- // Fire when autoFocus becomes true or the active session changes.
- useEffect(() => {
- if (!autoFocus) return;
- if (terminalRef.current) {
- terminalRef.current.focus();
- focusPendingRef.current = false;
- } else {
- containerRef.current?.focus();
- focusPendingRef.current = true;
- }
- }, [autoFocus, activeSessionId]);
-
- // Fire when the session transitions to 'ready'.
- const sessionStatus = activeSession?.status;
- useEffect(() => {
- if (sessionStatus === 'ready' && focusPendingRef.current) {
- focusPendingRef.current = false;
- terminalRef.current?.focus();
- }
- }, [sessionStatus]);
-
- const sessionIds = useMemo(() => allSessionIds, [allSessionIds]);
-
- const hasSessions = sessionIds.length > 0;
-
- return (
- <div
- ref={containerRef}
- tabIndex={-1}
- className={cn('flex h-full flex-col outline-none', className)}
- onFocus={() => onFocusChange?.(true)}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- onFocusChange?.(false);
- }
- }}
- >
- <PaneSizingProvider paneId={paneId} sessionIds={sessionIds}>
- {!hasSessions ? (
- emptyState
- ) : (
- <div className="flex min-h-0 flex-1 flex-col">
- {activeSessionId && activeSession?.status === 'ready' && activeSession.pty ? (
- <div ref={terminalContainerRef} className="relative flex h-full min-h-0 flex-1">
- <TerminalSearchOverlay
- isOpen={isSearchOpen}
- fullWidth
- searchQuery={searchQuery}
- searchStatus={searchStatus}
- searchInputRef={searchInputRef}
- onQueryChange={handleSearchQueryChange}
- onStep={stepSearch}
- onClose={closeSearch}
- />
- <PtyPane
- ref={terminalRef}
- sessionId={activeSessionId}
- pty={activeSession.pty}
- className="h-full w-full"
- themeOverride={{
- background: cssVar('--background'),
- }}
- onEnterPress={onEnterPress}
- onInterruptPress={onInterruptPress}
- mapShiftEnterToCtrlJ={mapShiftEnterToCtrlJ}
- workspaceId={workspaceId}
- />
- </div>
- ) : null}
- </div>
- )}
- </PaneSizingProvider>
- </div>
- );
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sessions/types.ts b/dash/apps/switchdash-desktop/src/renderer/features/sessions/types.ts
index 70cbe5e12..f376fd726 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sessions/types.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sessions/types.ts
@@ -1,5 +1,3 @@
-export type SidebarTab = 'conversations' | 'changes' | 'files';
-
export type FileRendererData =
| { kind: 'text' }
| { kind: 'markdown' }
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
index 2025d1e34..ae71e980c 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-deeplink-listener.tsx
@@ -28,18 +28,16 @@ function findSessionForRoom(roomId: string): { projectId: string; sessionId: str
}
/**
- * Resolve a session directly by its (shared) conversation id, which is the same
+ * Resolve a session directly by its (shared) session id, which is the same
* across every client — unlike the room mapping, which only exists on a client
* that has an active relay for the session. This is what makes the deeplink open
* the right session on a different switchdash client that merely adopted it.
*/
-function findSessionByConversation(
- conversationId: string
-): { projectId: string; sessionId: string } | null {
+function findSessionById(sessionId: string): { projectId: string; sessionId: string } | null {
for (const projectId of getProjectManagerStore().projects.keys()) {
const manager = getSessionManagerStore(projectId);
- if (manager?.sessions.has(conversationId)) {
- return { projectId, sessionId: conversationId };
+ if (manager?.sessions.has(sessionId)) {
+ return { projectId, sessionId: sessionId };
}
}
return null;
@@ -58,16 +56,14 @@ export function SessionDeeplinkListener(): null {
useEffect(() => {
roomConnectionsStore.ensureLoaded();
void agentsStore.load();
- return events.on(sessionDeeplinkChannel, ({ agentId, roomId, server, conversationId }) => {
+ return events.on(sessionDeeplinkChannel, ({ agentId, roomId, server, sessionId }) => {
void (async () => {
- // Prefer the shared conversation id (resolves on any client); fall back
+ // Prefer the shared session id (resolves on any client); fall back
// to room matching for older links that didn't carry it.
- const match =
- (conversationId ? findSessionByConversation(conversationId) : null) ??
- findSessionForRoom(roomId);
+ const match = (sessionId ? findSessionById(sessionId) : null) ?? findSessionForRoom(roomId);
if (!match) {
console.warn('[deeplink] no local session for deeplink', {
- conversationId,
+ sessionId,
roomId,
agentId,
server,
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-room-badge.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-room-badge.tsx
index ab3ffa441..c8385f1a5 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-room-badge.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/session-room-badge.tsx
@@ -9,15 +9,15 @@ import { switchRoomsStore } from './switch-rooms-store';
* room. Renders nothing when the session is not connected to any room.
*/
export const SessionRoomBadge = observer(function SessionRoomBadge({
- conversationId,
+ sessionId,
}: {
- conversationId: string;
+ sessionId: string;
}) {
useEffect(() => {
switchRoomsStore.ensureLoaded();
}, []);
- const roomId = switchRoomsStore.roomForSession(conversationId);
+ const roomId = switchRoomsStore.roomForSession(sessionId);
if (!roomId) return null;
return (
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
index 9d0ecd0d3..61524aff3 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-rooms/switch-rooms-store.ts
@@ -9,17 +9,17 @@ import { sessionRoomChangedChannel } from '@shared/core/switch-rooms/switchRoomE
* disappears here when it switches rooms or its session exits.
*/
class SwitchRoomsStore {
- /** conversationId → connected room id. */
- private roomByConversation = new Map<string, string>();
+ /** sessionId → connected room id. */
+ private roomBySession = new Map<string, string>();
private loaded = false;
constructor() {
makeAutoObservable(this, {}, { autoBind: true });
- events.on(sessionRoomChangedChannel, ({ conversationId, roomId }) => {
+ events.on(sessionRoomChangedChannel, ({ sessionId, roomId }) => {
runInAction(() => {
- if (roomId) this.roomByConversation.set(conversationId, roomId);
- else this.roomByConversation.delete(conversationId);
+ if (roomId) this.roomBySession.set(sessionId, roomId);
+ else this.roomBySession.delete(sessionId);
});
});
}
@@ -30,16 +30,16 @@ class SwitchRoomsStore {
this.loaded = true;
void rpc.switchRooms.getConnections().then((connections) => {
runInAction(() => {
- for (const { conversationId, roomId } of connections) {
- this.roomByConversation.set(conversationId, roomId);
+ for (const { sessionId, roomId } of connections) {
+ this.roomBySession.set(sessionId, roomId);
}
});
});
}
/** The room a session is currently connected to, or null. */
- roomForSession(conversationId: string): string | null {
- return this.roomByConversation.get(conversationId) ?? null;
+ roomForSession(sessionId: string): string | null {
+ return this.roomBySession.get(sessionId) ?? null;
}
}
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts b/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts
index 92102f32d..a51db947c 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/commands/types.ts
@@ -6,7 +6,7 @@ export interface AppCommand {
description?: string;
/** Links to APP_SHORTCUTS for hotkey binding and display. */
shortcutKey?: ShortcutSettingsKey;
- /** Display group in the command palette (e.g. 'Conversations', 'Panel', 'Tabs'). */
+ /** Display group in the command palette (e.g. 'Session', 'Panel', 'Navigation'). */
group?: string;
/**
* When false the command is visible in the palette but not executable and
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/components/stacked-agent-logos.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/components/stacked-agent-logos.tsx
deleted file mode 100644
index 9f0f348a4..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/lib/components/stacked-agent-logos.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { AgentIcon } from '@renderer/lib/components/agent-icon';
-import { useAgents } from '@renderer/lib/stores/use-agents';
-
-interface StackedAgentLogosProps {
- /** Map of providerId to conversation count, same shape as task.conversationStats */
- stats: Record<string, number>;
-}
-
-export function StackedAgentLogos({ stats }: StackedAgentLogosProps) {
- const entries = Object.entries(stats);
- const { data: agents } = useAgents();
- if (entries.length === 0) return null;
-
- const nameMap = new Map((agents ?? []).map((a) => [a.id, a.name]));
-
- return (
- <div className="flex shrink-0 items-center [&>span]:ring-2 [&>span]:ring-background [&>span:not(:first-child)]:-ml-1.5">
- {entries.map(([providerId, count]) => {
- const name = nameMap.get(providerId) ?? providerId;
- return (
- <span
- key={providerId}
- className="relative flex h-5 w-5 items-center justify-center overflow-hidden rounded-sm bg-background-2"
- title={count > 1 ? `${name}: ${String(count)}` : name}
- >
- <AgentIcon id={providerId} size={14} />
- {count > 1 && (
- <span className="absolute -right-px -bottom-px rounded-tl bg-background px-px text-[8px] leading-none font-semibold text-foreground-passive">
- {count}
- </span>
- )}
- </span>
- );
- })}
- </div>
- );
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/useTabShortcuts.ts b/dash/apps/switchdash-desktop/src/renderer/lib/hooks/useTabShortcuts.ts
deleted file mode 100644
index b9f97e37b..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/lib/hooks/useTabShortcuts.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { useHotkey } from '@tanstack/react-hotkeys';
-import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
-import { TAB_NAVIGATION_HOTKEYS } from '@shared/shortcuts';
-import { getEffectiveHotkey, getHotkeyRegistration } from './useKeyboardShortcuts';
-
-/**
- * Minimal interface required for tab navigation shortcuts.
- * Both TabViewProvider stores and EditorViewStore satisfy this shape.
- */
-export interface TabNavigationProvider {
- setNextTabActive: () => void;
- setPreviousTabActive: () => void;
- setTabActiveIndex: (index: number) => void;
- closeActiveTab: () => void;
-}
-
-export interface UseTabShortcutsOptions {
- /**
- * When false, all tab shortcuts are disabled. Use this to scope shortcuts
- * to a specific panel so they only fire when that panel is focused.
- * Defaults to true (always enabled when store is present).
- */
- focused?: boolean;
- closeActiveTab?: () => void;
-}
-
-/**
- * Hotkeys for jumping to a specific tab by position (1-indexed).
- * These are internal constants — not user-configurable via APP_SHORTCUTS.
- */
-const TAB_INDEX_HOTKEYS = [
- 'Mod+1',
- 'Mod+2',
- 'Mod+3',
- 'Mod+4',
- 'Mod+5',
- 'Mod+6',
- 'Mod+7',
- 'Mod+8',
- 'Mod+9',
-] as const;
-
-/**
- * Registers keyboard shortcuts for tab navigation within any TabNavigationProvider.
- *
- * Shortcuts:
- * tabNext (default Mod+Alt+ArrowRight) — next tab
- * tabPrev (default Mod+Alt+ArrowLeft) — previous tab
- * Control+Tab / Control+Shift+Tab — next / previous tab
- * tabClose (default Mod+W) — close active tab
- * Mod+1–9 — jump to tab by index (not configurable)
- *
- * Note: Mod+] and Mod+[ are reserved for history back/forward navigation
- * (navigateForward / navigateBack) in useKeyboardShortcuts.ts.
- *
- * Pass `focused: false` to disable shortcuts when the panel is not focused,
- * preventing conflicts when multiple tab panels are mounted simultaneously.
- */
-export function useTabShortcuts(
- store: TabNavigationProvider | undefined,
- options?: UseTabShortcutsOptions
-): void {
- const { value: keyboard } = useAppSettingsKey('keyboard');
- const enabled = !!store && (options?.focused ?? true);
- const tabNextHotkey = getEffectiveHotkey('tabNext', keyboard);
- const tabPrevHotkey = getEffectiveHotkey('tabPrev', keyboard);
- const tabCloseHotkey = getEffectiveHotkey('tabClose', keyboard);
-
- useHotkey(
- getHotkeyRegistration('tabNext', keyboard),
- () => {
- store?.setNextTabActive();
- },
- { enabled: enabled && tabNextHotkey !== null, conflictBehavior: 'allow' }
- );
- useHotkey(
- getHotkeyRegistration('tabPrev', keyboard),
- () => {
- store?.setPreviousTabActive();
- },
- { enabled: enabled && tabPrevHotkey !== null, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_NAVIGATION_HOTKEYS.next,
- (e) => {
- e.preventDefault();
- store?.setNextTabActive();
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_NAVIGATION_HOTKEYS.previous,
- (e) => {
- e.preventDefault();
- store?.setPreviousTabActive();
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- getHotkeyRegistration('tabClose', keyboard),
- (e) => {
- e.preventDefault();
- (options?.closeActiveTab ?? store?.closeActiveTab)?.();
- },
- { enabled: enabled && tabCloseHotkey !== null, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[0],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(0);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[1],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(1);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[2],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(2);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[3],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(3);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[4],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(4);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[5],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(5);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[6],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(6);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[7],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(7);
- },
- { enabled, conflictBehavior: 'allow' }
- );
- useHotkey(
- TAB_INDEX_HOTKEYS[8],
- (e) => {
- e.preventDefault();
- store?.setTabActiveIndex(8);
- },
- { enabled, conflictBehavior: 'allow' }
- );
-}
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pane-sizing-context.tsx b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pane-sizing-context.tsx
index 9d4e154d3..aefebc95a 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pane-sizing-context.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pane-sizing-context.tsx
@@ -13,12 +13,12 @@
* needing a mounted terminal.
*
* Usage:
- * <PaneSizingProvider paneId="conversations" sessionIds={allConversationSessionIds}>
+ * <PaneSizingProvider paneId="agents" sessionIds={agentPtySessionIds}>
* ...
* <TerminalPane sessionId={activeSessionId} />
* </PaneSizingProvider>
*
- * For split panes (e.g. conversation pane + right-panel terminal pane), each
+ * For split panes (e.g. agent pane + right-panel terminal pane), each
* pane gets its own <PaneSizingProvider> with a distinct paneId. No other
* changes required.
*/
@@ -122,7 +122,7 @@ export function PaneSizingProvider({ paneId, sessionIds, children }: PaneSizingP
}, [paneId]);
// When sessionIds change, send the current known dimensions to any sessions
- // that are newly added (e.g. a conversation was just created).
+ // that are newly added (e.g. a session was just created).
useEffect(() => {
const prev = sessionsRef.current;
const added = sessionIds.filter((id) => !prev.includes(id));
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-session.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-session.ts
index 4e54250da..11d59367d 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-session.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty-session.ts
@@ -35,7 +35,7 @@ export class PtySession {
});
// Lazy connect: auto-connects the first time any observer reads status.
// Sessions are created at data-load time without connecting; this fires
- // when the session is first rendered as the active conversation or terminal.
+ // when the session is first rendered as the active agent or terminal.
onBecomeObserved(this, 'status', () => {
if (this.status === 'disconnected') void this.connect();
});
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty.ts b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty.ts
index a5e41b3f5..63c00cbdf 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/pty/pty.ts
@@ -52,7 +52,7 @@ export function buildTheme(theme?: SessionTheme): ITerminalOptions['theme'] {
*
* Lifecycle: created and owned by PtySession (stores/pty-session.ts), one per
* live session. Survives React component unmounts (e.g. navigating away from a
- * task), and is disposed only when the entity (terminal or conversation) is
+ * task), and is disposed only when the entity (terminal or agent session) is
* explicitly deleted.
*/
export class FrontendPty {
@@ -209,7 +209,7 @@ export class FrontendPty {
}
/**
- * Permanently dispose this session (terminal or conversation deleted).
+ * Permanently dispose this session (terminal or agent session deleted).
* Unsubscribes from the main process, tears down the IPC data listener,
* disposes the xterm Terminal, and removes the owned container from the DOM.
*/
diff --git a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts
index 1c792a344..cd9ad9e44 100644
--- a/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/lib/stores/navigation-history-store.ts
@@ -103,7 +103,7 @@ export class NavigationHistoryStore {
* identical entries so no-op back steps are not created.
* The cursor is clamped to the surviving entry nearest the removed position.
*
- * Hook point for future entity-cleanup (deleted conversations, closed tabs, etc.).
+ * Hook point for future entity-cleanup (deleted sessions, closed tabs, etc.).
*/
prune(predicate: (entry: HistoryEntry) => boolean): void {
const currentEntry = this.entries[this.index];
diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/conversation-provider-selection.test.ts b/dash/apps/switchdash-desktop/src/renderer/tests/conversation-provider-selection.test.ts
deleted file mode 100644
index 72b77a0cb..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/tests/conversation-provider-selection.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { resolveConversationProviderSelection } from '@renderer/features/sessions/conversations/provider-selection';
-
-describe('resolveConversationProviderSelection', () => {
- it('keeps default provider while availability is unknown', () => {
- const selection = resolveConversationProviderSelection({
- defaultProviderId: 'claude',
- providerOverride: null,
- installedProviderIds: [],
- availabilityKnown: false,
- });
-
- expect(selection.providerId).toBe('claude');
- expect(selection.createDisabled).toBe(false);
- });
-
- it('falls back to the first installed provider when default is unavailable', () => {
- const selection = resolveConversationProviderSelection({
- defaultProviderId: 'claude',
- providerOverride: null,
- installedProviderIds: ['codex', 'qwen'],
- availabilityKnown: true,
- });
-
- expect(selection.providerId).toBe('codex');
- expect(selection.createDisabled).toBe(false);
- });
-
- it('disables creation when no agents are installed', () => {
- const selection = resolveConversationProviderSelection({
- defaultProviderId: 'claude',
- providerOverride: null,
- installedProviderIds: [],
- availabilityKnown: true,
- });
-
- expect(selection.providerId).toBeNull();
- expect(selection.createDisabled).toBe(true);
- });
-
- it('honors an explicit provider override', () => {
- const selection = resolveConversationProviderSelection({
- defaultProviderId: 'claude',
- providerOverride: 'codex',
- installedProviderIds: ['codex'],
- availabilityKnown: true,
- });
-
- expect(selection.providerId).toBe('codex');
- expect(selection.createDisabled).toBe(false);
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/conversation-title-utils.test.ts b/dash/apps/switchdash-desktop/src/renderer/tests/conversation-title-utils.test.ts
deleted file mode 100644
index 8dc3835d7..000000000
--- a/dash/apps/switchdash-desktop/src/renderer/tests/conversation-title-utils.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import {
- formatConversationTitleForDisplay,
- nextDefaultConversationTitle,
-} from '@renderer/features/sessions/conversations/conversation-title-utils';
-
-describe('nextDefaultConversationTitle', () => {
- it('fills the smallest missing index for a provider', () => {
- const title = nextDefaultConversationTitle('codex', [
- { providerId: 'codex', title: 'codex (1)' },
- { providerId: 'codex', title: 'codex (3)' },
- ]);
-
- expect(title).toBe('Codex (2)');
- });
-
- it('appends when there are no gaps', () => {
- const title = nextDefaultConversationTitle('codex', [
- { providerId: 'codex', title: 'codex (1)' },
- { providerId: 'codex', title: 'codex (2)' },
- { providerId: 'codex', title: 'codex (3)' },
- ]);
-
- expect(title).toBe('Codex (4)');
- });
-
- it('ignores other providers and non-default titles', () => {
- const title = nextDefaultConversationTitle('codex', [
- { providerId: 'claude', title: 'claude (1)' },
- { providerId: 'codex', title: 'release-triage' },
- { providerId: 'codex', title: 'codex (2)' },
- ]);
-
- expect(title).toBe('Codex (1)');
- });
-
- it('formats existing lowercase default titles for display', () => {
- expect(formatConversationTitleForDisplay('codex', 'codex (2)')).toBe('Codex (2)');
- expect(formatConversationTitleForDisplay('gemini', 'gemini (1)')).toBe('Gemini (1)');
- });
-
- it('leaves custom conversation titles unchanged', () => {
- expect(formatConversationTitleForDisplay('codex', 'release-triage')).toBe('release-triage');
- });
-});
diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/file-link-provider.test.ts b/dash/apps/switchdash-desktop/src/renderer/tests/file-link-provider.test.ts
index d06c7d483..3a6c7cca0 100644
--- a/dash/apps/switchdash-desktop/src/renderer/tests/file-link-provider.test.ts
+++ b/dash/apps/switchdash-desktop/src/renderer/tests/file-link-provider.test.ts
@@ -52,7 +52,7 @@ describe('file link provider', () => {
' Local agents do not use the terminal shell resolver at all. In src/main/core/'
),
new MockBufferLine(
- ' conversations/impl/local-conversation.ts:140, agent sessions call resolveLocalPtySpawn'
+ ' agent-runtime/impl/local-agent-runtime.ts:140, agent sessions call resolveLocalPtySpawn'
),
]);
@@ -61,15 +61,15 @@ describe('file link provider', () => {
start: { x: 66, y: 1 },
end: { x: 79, y: 1 },
},
- text: 'src/main/core/conversations/impl/local-conversation.ts',
+ text: 'src/main/core/agent-runtime/impl/local-agent-runtime.ts',
isExternal: false,
};
const expectedSecondLineLink = {
range: {
start: { x: 3, y: 2 },
- end: { x: 42, y: 2 },
+ end: { x: 43, y: 2 },
},
- text: 'src/main/core/conversations/impl/local-conversation.ts',
+ text: 'src/main/core/agent-runtime/impl/local-agent-runtime.ts',
isExternal: false,
};
expect(findFileLinks(buffer, 1)).toEqual([expectedFirstLineLink]);
diff --git a/dash/apps/switchdash-desktop/src/shared/commands.ts b/dash/apps/switchdash-desktop/src/shared/commands.ts
index e53b1d050..168d7e7a4 100644
--- a/dash/apps/switchdash-desktop/src/shared/commands.ts
+++ b/dash/apps/switchdash-desktop/src/shared/commands.ts
@@ -93,24 +93,6 @@ export const APP_COMMAND_DEFS = defineCommandDefs([
] as const);
export const SESSION_COMMAND_DEFS = defineCommandDefs([
- {
- id: 'session.newConversation',
- label: 'New Conversation',
- description: 'Create a new conversation in the current session',
- scope: 'session',
- shortcutKey: 'newConversation',
- group: 'Conversations',
- iconKey: 'message-square-plus',
- },
- {
- id: 'session.newConversationSplitRight',
- label: 'New Conversation in Right Split',
- description: 'Create a new conversation in a split pane to the right',
- scope: 'session',
- shortcutKey: 'newConversationSplitRight',
- group: 'Conversations',
- iconKey: 'columns-2',
- },
{
id: 'session.sidebarChanges',
label: 'View Changes',
@@ -120,15 +102,6 @@ export const SESSION_COMMAND_DEFS = defineCommandDefs([
group: 'View',
iconKey: 'file-diff',
},
- {
- id: 'session.sidebarConversations',
- label: 'View Conversations',
- description: 'Open the Conversations panel in the right sidebar',
- scope: 'session',
- shortcutKey: 'sidebarConversations',
- group: 'View',
- iconKey: 'message-square',
- },
{
id: 'session.sidebarFiles',
label: 'View Files',
diff --git a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.ts b/dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.ts
deleted file mode 100644
index ac34a8695..000000000
--- a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import z from 'zod';
-import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';
-
-const DROID_SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-export function isDroidProviderSessionId(value: string): boolean {
- return DROID_SESSION_ID_PATTERN.test(value);
-}
-
-const conversationConfigV0Schema = z.object({
- autoApprove: z.boolean().optional(),
- /** Provider-native session id (e.g. Droid UUID) for resuming the correct chat. */
- providerSessionId: z.string().optional(),
- /** Initial prompt to deliver on the first spawn; cleared from config after the session starts. */
- initialPrompt: z.string().optional(),
- /**
- * When set, this session runs as a Claude Code subagent of its (parent) agent:
- * the CLI is launched with `--agent <subagentName>` and the subagent's own
- * Switch credentials file, so it participates in rooms under the subagent's
- * identity. The value is the bare subagent name (the `.claude/agents/<name>.md`
- * file stem), which also names its `.claude/switch-subagents/<name>.settings.json`.
- */
- subagentName: z.string().optional(),
-});
-
-export const conversationConfig = defineVersionedSchema()
- .unversioned(conversationConfigV0Schema)
- .build();
-
-export type ConversationConfig = typeof conversationConfig.Type;
diff --git a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversationEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/conversations/conversationEvents.ts
deleted file mode 100644
index a32fdc32f..000000000
--- a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversationEvents.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { Conversation } from '@shared/core/conversations/conversations';
-import { defineEvent } from '@shared/lib/ipc/events';
-import type { AgentStatus, NotificationType } from '../providers/agentEvents';
-
-export const conversationChangedChannel = defineEvent<{
- conversationId: string;
- sessionId: string;
- projectId: string;
- changes: Partial<Pick<Conversation, 'lastInteractedAt' | 'title' | 'providerSessionId'>>;
-}>('conversation:changed');
-
-export const conversationCreatedChannel = defineEvent<{
- conversation: Conversation;
-}>('conversation:created');
-
-export const conversationAgentStatusChangedChannel = defineEvent<{
- conversationId: string;
- sessionId: string;
- projectId: string;
- status: AgentStatus;
- seen: boolean;
- soundEvent?: 'needs_attention' | 'session_complete';
- /**
- * For status changes driven by a notification hook, the specific kind. Lets
- * consumers distinguish an idle agent waiting at its prompt (`idle_prompt`)
- * from one genuinely blocked on a dialog (`permission_prompt`), which both map
- * to the `awaiting-input` status.
- */
- notificationType?: NotificationType;
-}>('conversation:agent-status-changed');
diff --git a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversations.ts b/dash/apps/switchdash-desktop/src/shared/core/conversations/conversations.ts
deleted file mode 100644
index e68209206..000000000
--- a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversations.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
-import type { AgentStatus } from '@shared/core/providers/agentEvents';
-
-export const MAX_CONVERSATION_TITLE_LENGTH = 100;
-
-export type Conversation = {
- id: string;
- projectId: string;
- sessionId: string;
- providerId: AgentProviderId;
- title: string;
- lastInteractedAt: string | null;
- resume?: boolean;
- autoApprove?: boolean;
- /** Provider-native session id captured at runtime for per-chat resume. */
- providerSessionId?: string;
- /** Set when this session runs as a Claude Code subagent (`--agent <name>`). */
- subagentName?: string;
- isInitialConversation: boolean | null;
- agentStatus?: AgentStatus | null;
- agentStatusSeen?: boolean;
-};
-
-export type RenameConversationParams = {
- conversationId: string;
- newTitle: string;
-};
-
-export type CreateConversationParams = {
- id: string;
- projectId: string;
- sessionId: string;
- provider: AgentProviderId;
- title: string;
- autoApprove?: boolean;
- isInitialConversation?: boolean;
- initialSize?: { cols: number; rows: number };
- initialPrompt?: string;
-};
diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
index d964f144e..ef5886f30 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-provider-registry.ts
@@ -73,11 +73,11 @@ export type AgentProviderDefinition = {
* CLI flag to assign a unique session ID per chat instance.
* Used to isolate session state when multiple chats of the same provider
* run in the same worktree. The flag receives a deterministic UUID
- * derived from the Switchdash conversation ID.
+ * derived from the Switchdash session ID.
* e.g. '--session-id' for Claude Code.
*/
sessionIdFlag?: string;
- newConversationFlag?: string;
+ newSessionFlag?: string;
sessionIdOnResumeOnly?: boolean;
/** Resume flag used when sessionIdOnResumeOnly is set but no provider session id is stored yet. */
resumeWithoutSessionFlag?: string;
@@ -109,7 +109,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [
// SessionStart hook that reports the rollout session id) without an interactive trust
// prompt. Automations always auto-approve and can't answer that prompt, so without this
// the session id is never captured and resume falls back to `codex resume --last`,
- // reattaching the globally-most-recent Codex session instead of this conversation.
+ // reattaching the globally-most-recent Codex session instead of this one.
autoApproveFlag:
'-c approval_policy="never" -c sandbox_mode="danger-full-access" --dangerously-bypass-hook-trust',
initialPromptFlag: '',
@@ -641,9 +641,9 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [
cli: 'letta',
autoApproveFlag: '--yolo',
initialPromptFlag: '',
- // Bare `letta` auto-resumes the cwd's last conversation; `--new` is
+ // Bare `letta` auto-resumes the cwd's last session; `--new` is
// required to start a fresh one when switchdash spins up a new chat.
- newConversationFlag: '--new',
+ newSessionFlag: '--new',
useKeystrokeInjection: true,
icon: 'letta.svg',
alt: 'Letta Code CLI',
diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-session.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-session.ts
index cd6720d00..7e1aca56d 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agent-session.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agent-session.ts
@@ -2,7 +2,6 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
export interface AgentSessionConfig {
sessionId: string;
- conversationId: string;
providerId: AgentProviderId;
command: string;
args: string[];
diff --git a/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts
index 2212a2604..fdcbea34f 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/providers/agentEvents.ts
@@ -27,7 +27,6 @@ export interface AgentEvent {
providerId?: string;
projectId: string;
sessionId: string;
- conversationId: string;
timestamp: number;
payload: {
notificationType?: NotificationType;
@@ -40,7 +39,6 @@ export interface AgentEvent {
export type SoundEvent = 'needs_attention' | 'session_complete';
export interface AgentSessionExited {
- conversationId: string;
sessionId: string;
}
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 df1992b44..458f55207 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/pty/ptyId.ts
@@ -1,18 +1,18 @@
import { AGENT_PROVIDER_IDS, type AgentProviderId } from '../providers/agent-provider-registry';
-const CONV_SEP = '-conv-';
+const SESSION_SEP = '-session-';
// Legacy separators — used only for snapshot migration fallback lookups.
const LEGACY_MAIN_SEP = '-main-';
const LEGACY_CHAT_SEP = '-chat-';
-export function makePtyId(provider: AgentProviderId | 'shell', conversationId: string): string {
- return `${provider}${CONV_SEP}${conversationId}`;
+export function makePtyId(provider: AgentProviderId | 'shell', sessionId: string): string {
+ return `${provider}${SESSION_SEP}${sessionId}`;
}
export function parsePtyId(id: string): {
providerId: AgentProviderId | 'shell';
- conversationId: string;
+ sessionId: string;
} | null {
// Try 'shell' sentinel first, then all known provider IDs longest-first to avoid prefix collisions.
const candidates: Array<AgentProviderId | 'shell'> = [
@@ -20,9 +20,9 @@ export function parsePtyId(id: string): {
...[...AGENT_PROVIDER_IDS].sort((a, b) => b.length - a.length),
];
for (const pid of candidates) {
- const prefix = pid + CONV_SEP;
+ const prefix = pid + SESSION_SEP;
if (id.startsWith(prefix)) {
- return { providerId: pid, conversationId: id.slice(prefix.length) };
+ return { providerId: pid, sessionId: id.slice(prefix.length) };
}
}
return null;
diff --git a/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts b/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts
index 32f38edc5..a9b1799e7 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/pty/ptySessionId.ts
@@ -1,14 +1,19 @@
/**
- * Deterministic PTY session ID.
+ * Deterministic PTY session IDs.
*
- * Format: `<projectId>:<scopeId>:<leafId>` where leafId is either a
- * conversationId (agent sessions) or a terminalId (shell sessions).
+ * Agent sessions use `<projectId>:<sessionId>` — the session IS the agent run
+ * (one agent PTY per session). Terminal-scoped PTYs (lifecycle scripts) use
+ * `<projectId>:<scopeId>:<leafId>` where scopeId is a workspace id and leafId
+ * a terminal id.
*
- * There is at most one active PTY per leaf entity. Using a deterministic ID
- * means the renderer can subscribe to ptyDataChannel BEFORE calling
- * rpc.conversations.startSession / rpc.terminals.createTerminal — no extra
- * round-trip is needed to learn the session ID.
+ * There is at most one active PTY per leaf entity. Using a deterministic ID
+ * means the renderer can subscribe to ptyDataChannel BEFORE the PTY spawns —
+ * no extra round-trip is needed to learn the session ID.
*/
+export function makeAgentPtySessionId(projectId: string, sessionId: string): string {
+ return `${projectId}:${sessionId}`;
+}
+
export function makePtySessionId(projectId: string, scopeId: string, leafId: string): string {
return `${projectId}:${scopeId}:${leafId}`;
}
@@ -21,6 +26,10 @@ export interface ParsedPtySessionId {
export function parsePtySessionId(id: string): ParsedPtySessionId | null {
const parts = id.split(':');
+ if (parts.length === 2 && parts[0] && parts[1]) {
+ // Agent PTY: the session id is both the scope and the leaf.
+ return { projectId: parts[0], scopeId: parts[1], leafId: parts[1] };
+ }
if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) return null;
return { projectId: parts[0], scopeId: parts[1], leafId: parts[2] };
}
diff --git a/dash/apps/switchdash-desktop/src/shared/core/search.ts b/dash/apps/switchdash-desktop/src/shared/core/search.ts
index e2ce62a73..6cff77031 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/search.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/search.ts
@@ -1,4 +1,4 @@
-export type SearchItemKind = 'session' | 'project' | 'conversation' | 'command' | 'file';
+export type SearchItemKind = 'session' | 'project' | 'command' | 'file';
export interface SearchItem {
kind: SearchItemKind;
diff --git a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.test.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.test.ts
similarity index 59%
rename from dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.test.ts
rename to dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.test.ts
index b54ef3a38..c51eb8358 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/conversations/conversation-config.test.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { conversationConfig, isDroidProviderSessionId } from './conversation-config';
+import { sessionConfig, isDroidProviderSessionId } from './session-config';
-describe('conversation-config', () => {
+describe('session-config', () => {
it('parses autoApprove and providerSessionId', () => {
- const result = conversationConfig.safeParse({
+ const result = sessionConfig.safeParse({
autoApprove: true,
providerSessionId: '31477a03-961a-4451-82d4-efded56947fc',
});
@@ -17,27 +17,27 @@ describe('conversation-config', () => {
});
it('returns invalid for non-object input', () => {
- expect(conversationConfig.safeParse('not-json')).toMatchObject({ status: 'invalid' });
- expect(conversationConfig.safeParse(null)).toMatchObject({ status: 'invalid' });
+ expect(sessionConfig.safeParse('not-json')).toMatchObject({ status: 'invalid' });
+ expect(sessionConfig.safeParse(null)).toMatchObject({ status: 'invalid' });
});
it('round-trips through parseJson and serialize', () => {
const config = { autoApprove: false, providerSessionId: 'abc' };
- const json = conversationConfig.serialize(config);
- expect(conversationConfig.parseJson(json)).toEqual(config);
+ const json = sessionConfig.serialize(config);
+ expect(sessionConfig.parseJson(json)).toEqual(config);
});
it('parseJson returns null for invalid JSON', () => {
- expect(conversationConfig.parseJson('not-json')).toBeNull();
+ expect(sessionConfig.parseJson('not-json')).toBeNull();
});
it('parseJson returns null for null input', () => {
- expect(conversationConfig.parseJson(null)).toBeNull();
+ expect(sessionConfig.parseJson(null)).toBeNull();
});
it('validates Droid session ids as UUIDs', () => {
expect(isDroidProviderSessionId('31477a03-961a-4451-82d4-efded56947fc')).toBe(true);
- expect(isDroidProviderSessionId('conv-1')).toBe(false);
+ expect(isDroidProviderSessionId('session-1')).toBe(false);
expect(isDroidProviderSessionId('')).toBe(false);
});
});
diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts
index 9cea9f597..6b3f12f60 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/session-config.ts
@@ -1,23 +1,28 @@
import z from 'zod';
import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';
-import { sessionLifecycleStatuses } from './sessions';
-const v1Schema = z.object({
- version: z.literal('1'),
- name: z.string(),
- initialConversation: z
- .object({
- id: z.string(),
- provider: z.string(),
- title: z.string().optional(),
- autoApprove: z.boolean().optional(),
- initialPrompt: z.string().optional(),
- })
- .optional(),
- initialStatus: sessionLifecycleStatuses.optional(),
+const DROID_SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export function isDroidProviderSessionId(value: string): boolean {
+ return DROID_SESSION_ID_PATTERN.test(value);
+}
+
+const sessionConfigV0Schema = z.object({
+ autoApprove: z.boolean().optional(),
+ /** Provider-native session id (e.g. Droid UUID) for resuming the correct chat. */
+ providerSessionId: z.string().optional(),
+ /** Initial prompt to deliver on the first spawn; cleared from config after the session starts. */
+ initialPrompt: z.string().optional(),
+ /**
+ * When set, this session runs as a Claude Code subagent of its (parent) agent:
+ * the CLI is launched with `--agent <subagentName>` and the subagent's own
+ * Switch credentials file, so it participates in rooms under the subagent's
+ * identity. The value is the bare subagent name (the `.claude/agents/<name>.md`
+ * file stem), which also names its `.claude/switch-subagents/<name>.settings.json`.
+ */
+ subagentName: z.string().optional(),
});
-export const sessionConfig = defineVersionedSchema().initial('1', v1Schema).build();
+export const sessionConfig = defineVersionedSchema().unversioned(sessionConfigV0Schema).build();
-export const sessionConfigSchema = sessionConfig.schema;
export type SessionConfig = typeof sessionConfig.Type;
diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts
index 4cad2c310..21b14a0da 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessionEvents.ts
@@ -1,8 +1,30 @@
+import type { AgentStatus, NotificationType } from '@shared/core/providers/agentEvents';
import type { Session } from '@shared/core/sessions/sessions';
import { defineEvent } from '@shared/lib/ipc/events';
export const sessionCreatedChannel = defineEvent<{ session: Session }>('session:created');
+export const sessionChangedChannel = defineEvent<{
+ sessionId: string;
+ projectId: string;
+ changes: Partial<Pick<Session, 'lastInteractedAt' | 'title' | 'providerSessionId'>>;
+}>('session:changed');
+
+export const sessionAgentStatusChangedChannel = defineEvent<{
+ sessionId: string;
+ projectId: string;
+ status: AgentStatus;
+ seen: boolean;
+ soundEvent?: 'needs_attention' | 'session_complete';
+ /**
+ * For status changes driven by a notification hook, the specific kind. Lets
+ * consumers distinguish an idle agent waiting at its prompt (`idle_prompt`)
+ * from one genuinely blocked on a dialog (`permission_prompt`), which both map
+ * to the `awaiting-input` status.
+ */
+ notificationType?: NotificationType;
+}>('session:agent-status-changed');
+
/**
* A session was removed by the main process out-of-band — i.e. NOT by this
* renderer initiating a delete (which updates its own store). Emitted when a
diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts
index f879ead43..1be1c832c 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts
@@ -35,6 +35,12 @@ export type Session = {
statusChangedAt: string;
/** Provider-native session id captured at runtime for resume. */
agentSessionId: string | null;
+ /**
+ * Provider-native chat id stored in the session's `config` JSON (e.g. the
+ * Codex rollout / Droid UUID) used to resume the correct chat. Distinct from
+ * `agentSessionId`, which is the `agent_session_id` column.
+ */
+ providerSessionId?: string;
agentStatus?: AgentStatus | null;
agentStatusSeen?: boolean;
isInitialSession: boolean | null;
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
index f6c05df15..482ed28f1 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switch-rooms.ts
@@ -5,8 +5,8 @@
* and is removed when it switches away or the session exits.
*/
export interface SessionRoomConnection {
- /** The switchdash session id (conversation id) the connection belongs to. */
- conversationId: string;
+ /** The switchdash session id the connection belongs to. */
+ sessionId: string;
/** The Switch room the session is currently connected to. */
roomId: string;
/** The Switch agent id that connected (from the agent's SWITCH_AGENT_ID). */
diff --git a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switchRoomEvents.ts b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switchRoomEvents.ts
index 54bf94d8c..f09cbfdf5 100644
--- a/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switchRoomEvents.ts
+++ b/dash/apps/switchdash-desktop/src/shared/core/switch-rooms/switchRoomEvents.ts
@@ -6,7 +6,7 @@ import { defineEvent } from '@shared/lib/ipc/events';
* or exited).
*/
export const sessionRoomChangedChannel = defineEvent<{
- conversationId: string;
+ sessionId: string;
roomId: string | null;
agentId: string | null;
}>('switch-room:session-room-changed');
@@ -21,7 +21,7 @@ export const sessionDeeplinkChannel = defineEvent<{
server: string;
agentId: string;
roomId: string;
- /** Shared conversation id, preferred for resolution (resolves on any client);
+ /** Shared session id, preferred for resolution (resolves on any client);
* empty string for links from older builds that only carried the room. */
- conversationId: string;
+ sessionId: string;
}>('switch-room:session-deeplink');
diff --git a/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts b/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts
index 0703260e2..3df55283d 100644
--- a/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts
+++ b/dash/apps/switchdash-desktop/src/shared/events/appEvents.ts
@@ -12,7 +12,6 @@ export const menuOpenSettingsChannel = defineEvent<void>('menu:open-settings');
export const menuCheckForUpdatesChannel = defineEvent<void>('menu:check-for-updates');
export const menuUndoChannel = defineEvent<void>('menu:undo');
export const menuRedoChannel = defineEvent<void>('menu:redo');
-export const menuCloseTabChannel = defineEvent<void>('menu:close-tab');
export const menuQuitRequestedChannel = defineEvent<void>('menu:quit-requested');
export const menuGiveFeedbackChannel = defineEvent<void>('menu:give-feedback');
@@ -28,7 +27,6 @@ export const tabNavigationShortcutChannel = defineEvent<{
export const notificationFocusSessionChannel = defineEvent<{
projectId: string;
sessionId: string;
- conversationId?: string;
}>('notification:focus-session');
export const ptyStartedChannel = defineEvent<{
@@ -52,16 +50,16 @@ export const ptyExitChannel = defineEvent<{
signal?: number;
}>('pty:exit');
-/** Emitted by main process when a PTY is definitively killed (e.g. on deleteSession/deleteConversation). */
+/** Emitted by main process when a PTY is definitively killed (e.g. on deleteSession). */
export const ptyKilledChannel = defineEvent<{ id: string }>('pty:killed');
/** Emitted by main process when a lifecycle/dev-server shell session is created.
- * These sessions are standalone PTYs — they are NOT backed by a DB conversation record.
- * The renderer uses sessionId (not conversationId) to connect to the PTY terminal.
+ * These sessions are standalone PTYs — they are NOT backed by a sessions-table row.
+ * The renderer uses sessionId to connect to the PTY terminal.
*/
export const shellSessionStartedChannel = defineEvent<{
sessionId: string;
- /** Opaque UUID identifying this PTY session — not a DB conversationId. */
+ /** Opaque UUID identifying this PTY session — not a sessions-table id. */
ptySessionId: string;
ptyId: string;
title: string;
diff --git a/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts b/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts
index 5b1d0afb2..a28c7d468 100644
--- a/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts
+++ b/dash/apps/switchdash-desktop/src/shared/lib/versioned-schema/versioned-schema.ts
@@ -337,7 +337,7 @@ export function defineVersionedSchema(versionField = 'version') {
*
* @example
* ```ts
- * const conversationConfig = defineVersionedSchema()
+ * const sessionConfig = defineVersionedSchema()
* .unversioned(v0Schema) // existing rows: no version field
* .version('1', v1Schema, (v0) => ...) // first versioned release
* .build();
diff --git a/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts b/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts
index 52c4f0fec..3796c1b6b 100644
--- a/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts
+++ b/dash/apps/switchdash-desktop/src/shared/resource-monitor.ts
@@ -5,8 +5,8 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
* on multi-core systems). `memory` is RSS in bytes. `pid` is undefined for
* remote (SSH) PTYs where the owning process runs on the remote host.
*
- * `providerId` is populated for agent-conversation PTYs. `title` is populated
- * for conversations and user-created shell terminals. They are sourced from
+ * `providerId` is populated for agent PTYs. `title` is populated
+ * for agent sessions and user-created shell terminals. They are sourced from
* the registry at register-time so the renderer can label entries even when
* the owning project isn't mounted (in which case the renderer-side store join
* would fail and the row would fall back to a leafId hex).
diff --git a/dash/apps/switchdash-desktop/src/shared/shortcuts.ts b/dash/apps/switchdash-desktop/src/shared/shortcuts.ts
index 0e05aec49..da313ca13 100644
--- a/dash/apps/switchdash-desktop/src/shared/shortcuts.ts
+++ b/dash/apps/switchdash-desktop/src/shared/shortcuts.ts
@@ -163,12 +163,6 @@ export const APP_SHORTCUTS = defineShortcuts({
description: 'Open the right sidebar to the Changes panel',
category: 'Session View',
},
- sidebarConversations: {
- defaultHotkey: 'Mod+Shift+3',
- label: 'View Conversations',
- description: 'Open the right sidebar to the Conversations panel',
- category: 'Session View',
- },
sidebarFiles: {
defaultHotkey: 'Mod+Shift+2',
label: 'View Files',
@@ -203,25 +197,6 @@ export const APP_SHORTCUTS = defineShortcuts({
category: 'Session View',
ignoreWhenMonacoFocused: true,
},
- tabClose: {
- defaultHotkey: 'Mod+W',
- label: 'Close Tab',
- description: 'Close the active tab',
- category: 'Tab Navigation',
- conflictBehavior: 'allow',
- },
- newConversation: {
- defaultHotkey: 'Mod+T',
- label: 'New Conversation',
- description: 'Create a new conversation in the current session',
- category: 'Session View',
- },
- newConversationSplitRight: {
- defaultHotkey: 'Mod+D',
- label: 'New Conversation in Right Split',
- description: 'Create a new conversation in a split pane to the right',
- category: 'Session View',
- },
newTerminal: {
defaultHotkey: 'Mod+Shift+T',
label: 'New Terminal',
diff --git a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
index 9e3b5ac78..c26ab5ff8 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.test.ts
@@ -26,14 +26,14 @@ function spec(overrides: Partial<AgentLaunchSpec> = {}): AgentLaunchSpec {
describe('materializeAgentCommand', () => {
it('substitutes the session id and initial prompt tokens', () => {
const cmd = materializeAgentCommand(spec(), {
- conversationId: 'conv-9',
+ sessionId: 'session-9',
initialPrompt: 'connect to switch room room-x',
extraEnv: {},
});
expect(cmd.command).toBe('/usr/bin/claude');
expect(cmd.args).toEqual([
'--session-id',
- 'conv-9',
+ 'session-9',
'--dangerously-skip-permissions',
'connect to switch room room-x',
]);
@@ -41,7 +41,7 @@ describe('materializeAgentCommand', () => {
it('merges per-spawn env over the base env', () => {
const cmd = materializeAgentCommand(spec({ env: { BASE: '1', SHARED: 'base' } }), {
- conversationId: 'c',
+ sessionId: 'c',
initialPrompt: 'p',
extraEnv: { SHARED: 'override', HOOK: 'x' },
});
@@ -51,7 +51,7 @@ describe('materializeAgentCommand', () => {
it('throws when the session-id token is missing', () => {
expect(() =>
materializeAgentCommand(spec({ args: [INITIAL_PROMPT_PLACEHOLDER] }), {
- conversationId: 'c',
+ sessionId: 'c',
initialPrompt: 'p',
extraEnv: {},
})
@@ -61,7 +61,7 @@ describe('materializeAgentCommand', () => {
it('throws when the initial-prompt token is missing', () => {
expect(() =>
materializeAgentCommand(spec({ args: ['--session-id', SESSION_ID_PLACEHOLDER] }), {
- conversationId: 'c',
+ sessionId: 'c',
initialPrompt: 'p',
extraEnv: {},
})
diff --git a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
index 4371c57ff..68a9716a0 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/agent-launch-spec.ts
@@ -5,7 +5,7 @@
* switchdash's plugin registry, so it cannot build a provider's launch command
* itself. Instead switchdash precomputes the command once (via the provider
* plugin's `buildCommand`) with placeholder tokens standing in for the two
- * per-spawn values — the conversation id and the initial prompt — and writes
+ * per-spawn values — the session id and the initial prompt — and writes
* this spec to the VM. The watcher then substitutes those tokens per spawn, so
* all provider knowledge stays in switchdash and the watcher is provider
* agnostic.
@@ -27,7 +27,7 @@ export interface AgentLaunchSpec {
deeplinkScheme: string;
}
-/** Argv token switchdash emits in place of the fresh session's conversation id. */
+/** Argv token switchdash emits in place of the fresh session's session id. */
export const SESSION_ID_PLACEHOLDER = '__SWITCHDASH_SESSION_ID__';
/** Argv token switchdash emits in place of the fresh session's initial prompt. */
@@ -45,15 +45,15 @@ export interface MaterializedAgentCommand {
* merging the per-spawn env (hook env) over the base env.
*
* Throws if either placeholder is missing from the spec's argv — a spec that
- * cannot carry the conversation id or prompt would silently spawn a session
+ * cannot carry the session id or prompt would silently spawn a session
* that never connects to the room, so we fail loud instead.
*/
export function materializeAgentCommand(
spec: AgentLaunchSpec,
- params: { conversationId: string; initialPrompt: string; extraEnv: Record<string, string> }
+ params: { sessionId: string; initialPrompt: string; extraEnv: Record<string, string> }
): MaterializedAgentCommand {
const substitutions: Record<string, string> = {
- [SESSION_ID_PLACEHOLDER]: params.conversationId,
+ [SESSION_ID_PLACEHOLDER]: params.sessionId,
[INITIAL_PROMPT_PLACEHOLDER]: params.initialPrompt,
};
diff --git a/dash/apps/switchdash-desktop/src/sidecar/index.ts b/dash/apps/switchdash-desktop/src/sidecar/index.ts
index f7db4cab4..6bf2cae30 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/index.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/index.ts
@@ -83,11 +83,11 @@ async function main(): Promise<void> {
return false;
}
};
- // Every live agent conversation pane on this host, whether or not its agent
+ // Every live agent session pane on this host, whether or not its agent
// joined a Switch room. Lets `/sessions` surface bare sessions so another
// client can discover and attach to them (CHOO-1181), not just room-attending
// ones. tmux only lists live sessions, so this never reports a dead pane.
- const listAgentConversationIds = async (): Promise<string[]> => {
+ const listAgentSessionIds = async (): Promise<string[]> => {
try {
const { stdout } = await execFileAsync('tmux', ['list-sessions', '-F', '#{session_name}']);
return stdout
@@ -130,7 +130,7 @@ async function main(): Promise<void> {
{
eventLog,
// Snapshot of live VM sessions (connected + just-launched, deduped by
- // conversation id) so switchdash can reconcile watcher-spawned sessions
+ // session id) so switchdash can reconcile watcher-spawned sessions
// into its UI. Connected sessions win — they carry the room the agent
// actually attends after connect_to_room.
sessionsProvider: async () => {
@@ -138,15 +138,15 @@ async function main(): Promise<void> {
// Every live agent pane THIS sidecar owns, room or not — so bare sessions
// are discoverable. Scope by hasSeen: tmux names carry no repo/agent, so
// the VM-wide enumeration must be filtered to this sidecar's sessions.
- for (const conversationId of await listAgentConversationIds()) {
- if (runtime.hasSeen(conversationId) && !byId.has(conversationId)) {
- byId.set(conversationId, null);
+ for (const sessionId of await listAgentSessionIds()) {
+ if (runtime.hasSeen(sessionId) && !byId.has(sessionId)) {
+ byId.set(sessionId, null);
}
}
// Room-attending / watcher-spawned sessions overwrite with their room id.
- for (const s of spawner?.spawnedSessions() ?? []) byId.set(s.conversationId, s.roomId);
- for (const s of runtime.connectedSessions()) byId.set(s.conversationId, s.roomId);
- return [...byId].map(([conversationId, roomId]) => ({ conversationId, roomId }));
+ for (const s of spawner?.spawnedSessions() ?? []) byId.set(s.sessionId, s.roomId);
+ for (const s of runtime.connectedSessions()) byId.set(s.sessionId, s.roomId);
+ return [...byId].map(([sessionId, roomId]) => ({ sessionId, roomId }));
},
// switchdash deleted a session: stop its room connection (ends the renew
// heartbeat keeping the agent live) and forget any watcher-launched entry.
@@ -154,14 +154,14 @@ async function main(): Promise<void> {
// client via a synthetic event on the shared /events log, so they tear down
// the session everywhere instead of leaving a ghost row that re-attaches
// into a blank tmux session.
- disconnectHandler: (conversationId, terminated) => {
- runtime.stopSession(conversationId);
- spawner?.drop(conversationId);
+ disconnectHandler: (sessionId, terminated) => {
+ runtime.stopSession(sessionId);
+ spawner?.drop(sessionId);
if (terminated) {
eventLog.append({
ptyId: '',
type: 'session-terminated',
- body: JSON.stringify({ conversationId }),
+ body: JSON.stringify({ sessionId }),
});
}
},
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 5965f3484..038d4f349 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.test.ts
@@ -84,13 +84,13 @@ describe('InProcessSessionSpawner.launch', () => {
});
describe('InProcessSessionSpawner.spawnedSessions', () => {
- it('reports a launched session with its minted conversation id while its pane is live', async () => {
+ it('reports a launched session with its minted session id while its pane is live', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
await spawner.launch('room-x');
const spawned = spawner.spawnedSessions();
expect(spawned).toHaveLength(1);
expect(spawned[0]!.roomId).toBe('room-x');
- expect(spawned[0]!.conversationId).toMatch(/[0-9a-f-]{36}/);
+ expect(spawned[0]!.sessionId).toMatch(/[0-9a-f-]{36}/);
});
it('omits a launched session whose pane has died (no ghost row)', async () => {
@@ -101,10 +101,10 @@ describe('InProcessSessionSpawner.spawnedSessions', () => {
});
describe('InProcessSessionSpawner.drop', () => {
- it('forgets a launched session by its conversation id', async () => {
+ it('forgets a launched session by its session id', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
await spawner.launch('room-x');
- const convId = spawner.spawnedSessions()[0]!.conversationId;
+ const convId = spawner.spawnedSessions()[0]!.sessionId;
spawner.drop(convId);
@@ -113,7 +113,7 @@ describe('InProcessSessionSpawner.drop', () => {
await expect(spawner.isRoomLive('room-x')).resolves.toBe(false);
});
- it('is a no-op for an unknown conversation id', async () => {
+ it('is a no-op for an unknown session id', async () => {
const { spawner } = makeSpawner({ isPaneLive: () => true });
await spawner.launch('room-x');
diff --git a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
index a131fedf2..18cddf577 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/session-spawner.ts
@@ -40,24 +40,24 @@ export class InProcessSessionSpawner implements SessionSpawner {
args: string[]
) => Promise<{ stdout: string; stderr: string }>;
/** Room id → the session we launched for it (its minted id + tmux target). */
- private readonly launched = new Map<string, { conversationId: string; tmuxTarget: string }>();
+ private readonly launched = new Map<string, { sessionId: string; tmuxTarget: string }>();
constructor(private readonly deps: InProcessSessionSpawnerDeps) {
this.exec = deps.exec ?? ((command, args) => execFileAsync(command, args));
}
/**
- * Forget a launched session by its conversation id (switchdash deleted it), so
+ * Forget a launched session by its session id (switchdash deleted it), so
* it is no longer reported as pending/spawned and a fresh room notification can
- * spawn a new one. No-op if we never launched this conversation.
+ * spawn a new one. No-op if we never launched this session.
*/
- drop(conversationId: string): void {
+ drop(sessionId: string): void {
for (const [roomId, session] of this.launched) {
- if (session.conversationId === conversationId) {
+ if (session.sessionId === sessionId) {
this.launched.delete(roomId);
this.deps.log.info('InProcessSessionSpawner: dropped launched session', {
roomId,
- conversationId,
+ sessionId,
});
return;
}
@@ -76,11 +76,11 @@ export class InProcessSessionSpawner implements SessionSpawner {
* learns of it. Only live panes are reported — a launched-then-dead session
* (crashed before connecting) is dropped so it doesn't surface as a ghost.
*/
- spawnedSessions(): Array<{ conversationId: string; roomId: string }> {
- const out: Array<{ conversationId: string; roomId: string }> = [];
+ spawnedSessions(): Array<{ sessionId: string; roomId: string }> {
+ const out: Array<{ sessionId: string; roomId: string }> = [];
for (const [roomId, session] of this.launched) {
if (this.deps.isPaneLive(session.tmuxTarget)) {
- out.push({ conversationId: session.conversationId, roomId });
+ out.push({ sessionId: session.sessionId, roomId });
}
}
return out;
@@ -99,26 +99,26 @@ export class InProcessSessionSpawner implements SessionSpawner {
async launch(roomId: string): Promise<void> {
const { spec, hookPort, hookToken, log } = this.deps;
- const conversationId = randomUUID();
- const tmuxTarget = makeAgentTmuxSessionName(conversationId);
+ const sessionId = randomUUID();
+ const tmuxTarget = makeAgentTmuxSessionName(sessionId);
const hookEnv = {
SWITCHDASH_HOOK_PORT: String(hookPort),
- SWITCHDASH_PTY_ID: makePtyId(spec.providerId, conversationId),
+ SWITCHDASH_PTY_ID: makePtyId(spec.providerId, sessionId),
SWITCHDASH_HOOK_TOKEN: hookToken,
SWITCH_CHANNEL_DISABLE_POLL: '1',
};
const command = materializeAgentCommand(spec, {
- conversationId,
+ sessionId,
initialPrompt: `connect to switch room ${roomId}`,
extraEnv: hookEnv,
});
await this.startDetachedTmux(tmuxTarget, spec.cwd, command.env, command.command, command.args);
- this.launched.set(roomId, { conversationId, tmuxTarget });
+ this.launched.set(roomId, { sessionId, tmuxTarget });
log.info('InProcessSessionSpawner: launched session for room', {
roomId,
- conversationId,
+ sessionId,
tmuxTarget,
});
}
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 b06c86041..f1eff9839 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.test.ts
@@ -53,8 +53,8 @@ function makeRuntime() {
return { runtime, created };
}
-const PTY_A = makePtyId('codex', 'conv-a');
-const PTY_B = makePtyId('codex', 'conv-b');
+const PTY_A = makePtyId('codex', 'session-a');
+const PTY_B = makePtyId('codex', 'session-b');
describe('SidecarRuntime (multi-session)', () => {
beforeEach(() => {
@@ -67,17 +67,17 @@ describe('SidecarRuntime (multi-session)', () => {
expect(created).toHaveLength(1);
expect(created[0].deps.roomId).toBe('room-1');
- expect(created[0].deps.conversationId).toBe('conv-a');
+ expect(created[0].deps.sessionId).toBe('session-a');
expect(created[0].conn.start).toHaveBeenCalledTimes(1);
});
it('records every hooked session (hasSeen) so /sessions can scope tmux to this agent', async () => {
const { runtime } = makeRuntime();
- expect(runtime.hasSeen('conv-a')).toBe(false);
+ expect(runtime.hasSeen('session-a')).toBe(false);
// A plain status hook (no room connect) still marks the session as owned.
await runtime.handleHook(statusHook('start', PTY_A));
- expect(runtime.hasSeen('conv-a')).toBe(true);
- expect(runtime.hasSeen('conv-b')).toBe(false);
+ expect(runtime.hasSeen('session-a')).toBe(true);
+ expect(runtime.hasSeen('session-b')).toBe(false);
});
it('serves two sessions concurrently, one connection each', async () => {
@@ -126,14 +126,14 @@ describe('SidecarRuntime (multi-session)', () => {
expect(runtime.hasLiveRoom('room-2')).toBe(false);
});
- it('lists connected sessions (conversation id + room) for reconciliation, live panes only', async () => {
+ it('lists connected sessions (session id + room) for reconciliation, live panes only', async () => {
const { runtime } = makeRuntime();
await runtime.handleHook(switchRoomHook('room-1', PTY_A));
await runtime.handleHook(switchRoomHook('room-2', PTY_B));
expect(runtime.connectedSessions()).toEqual([
- { conversationId: 'conv-a', roomId: 'room-1' },
- { conversationId: 'conv-b', roomId: 'room-2' },
+ { sessionId: 'session-a', roomId: 'room-1' },
+ { sessionId: 'session-b', roomId: 'room-2' },
]);
});
@@ -168,25 +168,25 @@ describe('SidecarRuntime (multi-session)', () => {
expect(created[0].conn.stop).toHaveBeenCalled();
});
- it('stopSession stops and forgets only that conversation', async () => {
+ it('stopSession stops and forgets only that session', async () => {
const { runtime, created } = makeRuntime();
await runtime.handleHook(switchRoomHook('room-1', PTY_A));
await runtime.handleHook(switchRoomHook('room-2', PTY_B));
- runtime.stopSession('conv-a');
+ runtime.stopSession('session-a');
expect(created[0].conn.stop).toHaveBeenCalledTimes(1);
expect(created[1].conn.stop).not.toHaveBeenCalled();
// Forgotten: no longer reported and its room is no longer live.
- expect(runtime.connectedSessions()).toEqual([{ conversationId: 'conv-b', roomId: 'room-2' }]);
+ expect(runtime.connectedSessions()).toEqual([{ sessionId: 'session-b', roomId: 'room-2' }]);
expect(runtime.hasLiveRoom('room-1')).toBe(false);
});
- it('stopSession is a no-op for an unknown conversation', async () => {
+ it('stopSession is a no-op for an unknown session', async () => {
const { runtime, created } = makeRuntime();
await runtime.handleHook(switchRoomHook('room-1', PTY_A));
- runtime.stopSession('conv-unknown');
+ runtime.stopSession('session-unknown');
expect(created[0].conn.stop).not.toHaveBeenCalled();
expect(runtime.connectedSessions()).toHaveLength(1);
diff --git a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
index b010a08cb..b2935d386 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/sidecar-runtime.ts
@@ -55,16 +55,16 @@ interface SessionConnection {
* RoomConnection injecting into that session's own pane. Multi-session — the
* single agent-scoped sidecar serves every session on the VM (the one switchdash
* started over SSH, and any the notification watcher auto-starts), each keyed by
- * its conversation id, so there is exactly one sidecar per agent rather than one
+ * its session id, so there is exactly one sidecar per agent rather than one
* per session.
*
* Runs entirely on the VM with no database or Electron — the agent's Switch
* credentials come from its `.claude/settings.local.json`.
*/
export class SidecarRuntime {
- /** conversationId → its live room connection. */
+ /** sessionId → its live room connection. */
private readonly sessions = new Map<string, SessionConnection>();
- /** Every conversation id that has posted a hook to this sidecar — i.e. the
+ /** Every session id that has posted a hook to this sidecar — i.e. the
* sessions it owns, used to scope the VM-wide tmux enumeration in `/sessions`. */
private readonly seen = new Set<string>();
private readonly resolveContext: ContextResolver;
@@ -74,8 +74,7 @@ export class SidecarRuntime {
const parsed = parsePtyId(ptyId);
if (!parsed) return null;
return {
- conversationId: parsed.conversationId,
- sessionId: parsed.conversationId,
+ sessionId: parsed.sessionId,
projectId: deps.projectId,
providerId: parsed.providerId,
ptyId,
@@ -86,12 +85,12 @@ export class SidecarRuntime {
/** Handle one raw hook callback from an agent CLI. Never throws. */
async handleHook(raw: RawHookRequest): Promise<void> {
// Every hook posted to THIS sidecar comes from a session it owns (the
- // session's hook env points here), so record its conversation id. This is
+ // session's hook env points here), so record its session id. This is
// how `/sessions` scopes the VM-wide tmux enumeration to this agent's own
// panes — tmux session names carry no repo/agent, so without this a sidecar
// would report other agents' sessions on the same host.
const pid = parsePtyId(raw.ptyId);
- if (pid) this.seen.add(pid.conversationId);
+ if (pid) this.seen.add(pid.sessionId);
let parsed: ParsedHookEvent;
try {
@@ -105,12 +104,7 @@ export class SidecarRuntime {
}
if (parsed.kind === 'switch-room') {
- this.connectRoom(
- parsed.ctx.conversationId,
- parsed.ctx.providerId,
- parsed.roomId,
- parsed.roomName
- );
+ this.connectRoom(parsed.ctx.sessionId, parsed.ctx.providerId, parsed.roomId, parsed.roomName);
return;
}
@@ -120,13 +114,13 @@ export class SidecarRuntime {
const notificationType =
parsed.event.type === 'notification' ? parsed.event.payload.notificationType : undefined;
// Route to the session the event came from — not every connection.
- const session = this.sessions.get(parsed.event.conversationId);
+ const session = this.sessions.get(parsed.event.sessionId);
session?.connection.onAgentStatusChange(status, notificationType);
return;
}
if (parsed.kind === 'activity') {
- const session = this.sessions.get(parsed.ctx.conversationId);
+ const session = this.sessions.get(parsed.ctx.sessionId);
session?.connection.reportActivity(parsed.detail);
return;
}
@@ -135,12 +129,12 @@ export class SidecarRuntime {
}
private connectRoom(
- conversationId: string,
+ sessionId: string,
providerId: string,
roomId: string,
roomName: string | null
): void {
- const existing = this.sessions.get(conversationId);
+ const existing = this.sessions.get(sessionId);
// A repeat connect to the same room by the same session is a no-op so the
// in-flight queue and renew loop are preserved.
if (existing && existing.roomId === roomId) return;
@@ -149,12 +143,12 @@ export class SidecarRuntime {
// connect_to_room re-targeting independently).
if (existing) existing.connection.stop();
- const tmuxTarget = makeAgentTmuxSessionName(conversationId);
+ const tmuxTarget = makeAgentTmuxSessionName(sessionId);
const connection = this.deps.createConnection({
creds: this.deps.creds,
roomId,
roomName,
- conversationId,
+ sessionId,
sink: new TmuxInjectionSink(tmuxTarget, this.deps.tmuxRun, () =>
this.deps.isPaneLive(tmuxTarget)
),
@@ -165,11 +159,11 @@ export class SidecarRuntime {
// keystrokes (those go through switchdash's main process over SSH), so it
// can't gate on human typing yet — a known follow-up for the attached case.
isHumanTyping: () => false,
- mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', conversationId),
+ mediaDir: path.join(os.tmpdir(), 'switchdash-switch-media', sessionId),
log: this.deps.log,
});
- this.sessions.set(conversationId, { connection, roomId, tmuxTarget });
- this.deps.log.debug('SidecarRuntime: room connected', { conversationId, roomId, roomName });
+ this.sessions.set(sessionId, { connection, roomId, tmuxTarget });
+ this.deps.log.debug('SidecarRuntime: room connected', { sessionId, roomId, roomName });
connection.start();
}
@@ -178,12 +172,12 @@ export class SidecarRuntime {
* poll + renew heartbeat that keeps the agent marked live) and forget it, so
* `/sessions` no longer reports it. Called when switchdash deletes the session.
*/
- stopSession(conversationId: string): void {
- const session = this.sessions.get(conversationId);
+ stopSession(sessionId: string): void {
+ const session = this.sessions.get(sessionId);
if (!session) return;
session.connection.stop();
- this.sessions.delete(conversationId);
- this.deps.log.debug('SidecarRuntime: session stopped', { conversationId });
+ this.sessions.delete(sessionId);
+ this.deps.log.debug('SidecarRuntime: session stopped', { sessionId });
}
/** Agent tmux targets the runtime is currently injecting into (for pane-liveness polling). */
@@ -196,20 +190,20 @@ export class SidecarRuntime {
* 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.
*/
- connectedSessions(): Array<{ conversationId: string; roomId: string }> {
- const out: Array<{ conversationId: string; roomId: string }> = [];
- for (const [conversationId, session] of this.sessions) {
+ 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({ conversationId, roomId: session.roomId });
+ out.push({ sessionId, roomId: session.roomId });
}
}
return out;
}
- /** Whether a conversation has ever posted a hook to this sidecar (i.e. it is
+ /** Whether a session has ever posted a hook to this sidecar (i.e. it is
* one of this agent's own sessions, not another agent's pane on the host). */
- hasSeen(conversationId: string): boolean {
- return this.seen.has(conversationId);
+ hasSeen(sessionId: string): boolean {
+ return this.seen.has(sessionId);
}
/** True when a live session is attending the room and its pane is up (watcher gate). */
diff --git a/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts b/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts
index be6a3aab6..e811cb870 100644
--- a/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts
+++ b/dash/apps/switchdash-desktop/src/sidecar/vm-tmux.ts
@@ -2,7 +2,7 @@
* Bundle-safe tmux helpers, replicated from switchdash's Electron-bound
* `tmux-session-name.ts` so the sidecar bundle stays free of the main-process
* logger. A spawned session's tmux name matches what switchdash would compute
- * for the same conversation, so a later attach reuses the pane.
+ * for the same session, so a later attach reuses the pane.
*/
/** tmux resolves a bare `-t name` by prefix; `=` forces an exact-name match. */
@@ -16,24 +16,23 @@ export function makeTmuxSessionName(sessionId: string): string {
}
/**
- * Agent conversation pane name, keyed on the shared conversationId alone.
- * Mirrors switchdash's `makeAgentTmuxSessionName` so the sidecar and every
- * attached client converge on ONE pane per conversation (CHOO-1181). Must not
- * fold in projectId — it is switchdash-instance-local and would diverge per
- * client.
+ * Agent pane name, keyed on the shared session id alone. Mirrors switchdash's
+ * `makeAgentTmuxSessionName` so the sidecar and every attached client converge
+ * on ONE pane per session (CHOO-1181). Must not fold in projectId — it is
+ * switchdash-instance-local and would diverge per client.
*/
-export function makeAgentTmuxSessionName(conversationId: string): string {
- return makeTmuxSessionName(`conv-${conversationId}`);
+export function makeAgentTmuxSessionName(sessionId: string): string {
+ return makeTmuxSessionName(`session-${sessionId}`);
}
-const AGENT_PANE_PREFIX = 'conv-';
+const AGENT_PANE_PREFIX = 'session-';
/**
- * Inverse of `makeAgentTmuxSessionName`: recover the conversationId from a tmux
- * session name, or null if the name isn't an agent conversation pane (the
- * sidecar's own `switchdash-sidecar-*` session, a terminal pane, or anything else).
- * Lets the sidecar enumerate live agent panes to report sessions that never
- * joined a room (CHOO-1181).
+ * Inverse of `makeAgentTmuxSessionName`: recover the session id from a tmux
+ * session name, or null if the name isn't an agent pane (the sidecar's own
+ * `switchdash-sidecar-*` session, a terminal pane, or anything else). Lets the
+ * sidecar enumerate live agent panes to report sessions that never joined a
+ * room (CHOO-1181).
*/
export function parseAgentTmuxSessionName(sessionName: string): string | null {
if (!sessionName.startsWith('switchdash-')) return null;
@@ -45,6 +44,6 @@ export function parseAgentTmuxSessionName(sessionName: string): string | null {
return null;
}
if (!decoded.startsWith(AGENT_PANE_PREFIX)) return null;
- const conversationId = decoded.slice(AGENT_PANE_PREFIX.length);
- return conversationId || null;
+ const sessionId = decoded.slice(AGENT_PANE_PREFIX.length);
+ return sessionId || null;
}
diff --git a/dash/packages/core/src/agents/plugins/capabilities/hooks-types.ts b/dash/packages/core/src/agents/plugins/capabilities/hooks-types.ts
index b9ae61fce..b2732fb3e 100644
--- a/dash/packages/core/src/agents/plugins/capabilities/hooks-types.ts
+++ b/dash/packages/core/src/agents/plugins/capabilities/hooks-types.ts
@@ -27,7 +27,7 @@ export type NotificationType =
* Normalised hook event produced by a plugin's parseHookEvent method.
*
* - kind: 'status' — maps to an agent lifecycle event (start/stop/error/notification)
- * - kind: 'session' — carries a provider session id to persist on the conversation
+ * - kind: 'session' — carries a provider session id to persist on the session
* - kind: 'activity' — a short line describing what the running turn is doing
* right now (e.g. a tool call); surfaced as incremental
* progress while the coarse status stays 'working'
diff --git a/dash/packages/core/src/agents/plugins/capabilities/prompt.ts b/dash/packages/core/src/agents/plugins/capabilities/prompt.ts
index 84564a6d8..47c42adef 100644
--- a/dash/packages/core/src/agents/plugins/capabilities/prompt.ts
+++ b/dash/packages/core/src/agents/plugins/capabilities/prompt.ts
@@ -6,7 +6,7 @@ export type CommandContext = {
extraArgs?: string[]; // user-configured in settings
autoApprove: boolean;
initialPrompt?: string;
- /** Switchdash conversation UUID — used as the session token for providers that track their
+ /** Switchdash session UUID — used as the session token for providers that track their
* own session across the switchdash lifetime (e.g. claude --session-id, opencode --session). */
sessionId?: string;
/** Provider-native session identifier stored by the agent classifier. When present, used
diff --git a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts b/dash/packages/core/src/agents/plugins/helpers/standard-command.ts
index 073009565..f620ec817 100644
--- a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts
+++ b/dash/packages/core/src/agents/plugins/helpers/standard-command.ts
@@ -46,11 +46,11 @@ export type StandardCommandSpec = {
sessionIdOnResumeOnly?: boolean;
/** Resume flag used when sessionIdOnResumeOnly=true but sessionId is absent (no stored session yet). */
resumeWithoutSessionFlag?: string;
- /** A flag appended when starting a fresh conversation (e.g. letta's --new). */
- newConversationFlag?: string;
+ /** A flag appended when starting a fresh session (e.g. letta's --new). */
+ newSessionFlag?: string;
/**
* When true, sessionIdFlag is injected on both fresh AND resume sessions.
- * Use for providers like Antigravity that identify conversations by ID on every invocation.
+ * Use for providers like Antigravity that identify sessions by ID on every invocation.
*/
sessionIdAlways?: boolean;
/** When true, skip auto-approve flag on resume (kimi special case). */
@@ -110,8 +110,8 @@ export function buildStandardCommand(ctx: CommandContext, spec: StandardCommandS
// Fresh session
if (spec.sessionIdFlag && !spec.sessionIdOnResumeOnly && ctx.sessionId) {
appendFlagValue(args, spec.sessionIdFlag, ctx.sessionId);
- } else if (spec.newConversationFlag) {
- args.push(spec.newConversationFlag);
+ } else if (spec.newSessionFlag) {
+ args.push(spec.newSessionFlag);
}
}
diff --git a/dash/packages/core/src/host-dependencies/runtime/types.ts b/dash/packages/core/src/host-dependencies/runtime/types.ts
index 2f0860ace..c99b8dd16 100644
--- a/dash/packages/core/src/host-dependencies/runtime/types.ts
+++ b/dash/packages/core/src/host-dependencies/runtime/types.ts
@@ -216,7 +216,7 @@ export type Installation = {
/**
* All installations of one agent on one host, plus which SelectedSource is
- * currently authoritative for conversation spawns.
+ * currently authoritative for agent spawns.
*/
export type HostDependency = {
hostId: string;
diff --git a/dash/packages/plugins/src/agents/impl/index.test.ts b/dash/packages/plugins/src/agents/impl/index.test.ts
index 2b6dff547..78222ccd0 100644
--- a/dash/packages/plugins/src/agents/impl/index.test.ts
+++ b/dash/packages/plugins/src/agents/impl/index.test.ts
@@ -156,7 +156,7 @@ describe('pluginRegistry', () => {
cli: 'grok',
autoApprove: true,
initialPrompt: 'Fix the bug',
- sessionId: 'conv-1',
+ sessionId: 'session-1',
isResuming: false,
model: '',
});
diff --git a/dash/packages/plugins/src/agents/impl/letta/index.ts b/dash/packages/plugins/src/agents/impl/letta/index.ts
index 9e5fdcfe0..bc085e69b 100644
--- a/dash/packages/plugins/src/agents/impl/letta/index.ts
+++ b/dash/packages/plugins/src/agents/impl/letta/index.ts
@@ -51,7 +51,7 @@ export const provider = registerPluginBehavior(plugin, {
buildCommand: (ctx) =>
buildStandardCommand(ctx, {
autoApproveFlag: '--yolo',
- newConversationFlag: '--new',
+ newSessionFlag: '--new',
}),
},
});