Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Merge origin/main into feat/switchdash-lazy-pty-attach-lru
amaudruz6562ad084a46
diff --cc dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 6f063ebed,72f0d084d..67d785415--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@@ -5,7 -7,8 +7,9 @@@ import type { SshClientProxy } from '@mimport { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import type { Session } from '@shared/core/sessions/sessions';+ import { SWITCH_RUNTIME_REQUIRED_ENV } from '@shared/core/switch-rooms/switch-agent-runtime';+ import { SidecarHttpStatusError } from './sidecar-http';+import { sidecarRelayRegistry } from './sidecar-relay-registry';import { SshAgentRuntime } from './ssh-agent-runtime';const openSsh2Pty = vi.hoisted(() => vi.fn());@@@ -204,16 -249,16 +250,20 @@@ describe('SshAgentRuntime', () =>openSsh2Pty.mockReset();buildCommandMock.mockReset();buildCommandMock.mockReturnValue({ command: 'agent', args: [], env: {} });+ vi.mocked(getPlugin).mockImplementation(defaultGetPlugin as never);resolveSshCommand.mockClear();deployAndLaunch.mockClear();+ remoteNpmRegistryAuthEnv.mockClear();sidecarStop.mockClear();httpPostJsonOverChannel.mockClear();+ httpPostForJsonOverChannel.mockReset();+ httpPostForJsonOverChannel.mockResolvedValue({ connectionId: 'conn-remote-1' });vi.mocked(events.emit).mockClear();connectionListeners.length = 0;+ // The relay registry is a module singleton keyed by host+dir+agent, so a+ // relay acquired by one test would otherwise be reused by the next and its+ // fresh proxy never polled.+ sidecarRelayRegistry.stopAll();ptySessionRegistry.unregister('location-1:session-1');});@@@ -329,6 -550,113 +555,151 @@@expect(env.SWITCH_CHANNEL_DISABLE_POLL).toBe('1');});+ // A session's room is claimed on the connection whose id it carries, and on a+ // remote host only the sidecar reads that connection. Left to mint its own,+ // the session is addressable by nobody: an @-mention reaches silence and the+ // session shows no room, while the identical local session works.+ it('opens a connection on the sidecar and hands its id to the remote session', async () => {+ mockSpawn([]);++ await sshProvider({ tmux: true }).start(session());++ expect(httpPostForJsonOverChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ path: '/connection',+ body: { sessionId: 'session-1', providerId: 'codex' },+ })+ );+ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;+ expect(env.SWITCH_CONNECTION_ID).toBe('conn-remote-1');+ });+++ // `ensureAttachable` brings the sidecar up at provision time, so by the first++ // attach the sidecar is long since ready. Deciding "is this a re-attach?" from++ // the sidecar would therefore skip the connection hand-off on the very launch++ // that needs it, and the agent would come up addressable by nobody.++ it('still hands over a connection id when the sidecar was readied before the first attach', async () => {++ mockSpawn([]);++ const provider = sshProvider({ tmux: true });++ const item = session();++++ await provider.ensureAttachable(item);++ expect(resolveSshCommand).not.toHaveBeenCalled();++++ await provider.start(item);++++ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;++ expect(env.SWITCH_CONNECTION_ID).toBe('conn-remote-1');++ });++++ // The hand-off opens a connection the sidecar renews, so repeating it per++ // attach would leak one per eviction cycle and leave the agent showing `live`++ // in rooms with no session behind it (CHOO-1106).++ it('opens the sidecar connection once per pane, not once per attach', async () => {++ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];++ mockSpawn(exitHandlers);++ const provider = sshProvider({ tmux: true });++++ await provider.start(session());++ expect(httpPostForJsonOverChannel).toHaveBeenCalledTimes(1);++++ await provider.detachForEviction();++ await provider.attach();++++ expect(openSsh2Pty).toHaveBeenCalledTimes(2);++ expect(httpPostForJsonOverChannel).toHaveBeenCalledTimes(1);++ });+++ // A sidecar predating the endpoint 404s. Starting anyway would put the session+ // back in exactly the silence the hand-off exists to prevent, so the start has+ // to fail and say which upgrade fixes it.+ it('fails the start when the sidecar has no /connection endpoint', async () => {+ mockSpawn([]);+ httpPostForJsonOverChannel.mockRejectedValue(+ new SidecarHttpStatusError(404, 'POST /connection returned status 404')+ );++ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(+ /did not open a Switch connection.*restart it to upgrade/s+ );+ expect(openSsh2Pty).not.toHaveBeenCalled();+ });++ // An unreachable host is a different fault with a different fix, so it must+ // not be reported as an out-of-date sidecar.+ it('does not blame the sidecar version when the connection call simply fails', async () => {+ mockSpawn([]);+ httpPostForJsonOverChannel.mockRejectedValue(new Error('POST /connection timed out'));++ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(+ /did not open a Switch connection/+ );+ await expect(sshProvider({ tmux: true }).start(session())).rejects.not.toThrow(+ /restart it to upgrade/+ );+ });++ // Left open the connection keeps renewing, so the agent shows `live` in its+ // room with no session behind it — the CHOO-1106 ghost, now reachable through+ // a launch that dies between opening the connection and starting the pane.+ it('hands the connection back when the launch fails after opening it', async () => {+ openSsh2Pty.mockResolvedValue({ success: false, error: new Error('channel refused') });++ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow('channel refused');++ expect(httpPostJsonOverChannel).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ path: '/disconnect',+ body: { sessionId: 'session-1', terminated: false },+ })+ );+ });++ it('rejects a /connection reply carrying no id rather than launching without one', async () => {+ mockSpawn([]);+ httpPostForJsonOverChannel.mockResolvedValue({} as never);++ await expect(sshProvider({ tmux: true }).start(session())).rejects.toThrow(/no connection id/);+ });++ // The runtime is fetched with `npx` from a private registry, so without this+ // the remote session comes up with no MCP server and npm reports a 404 that+ // names neither the registry nor the missing credential.+ it('gives a freshly launched remote session its registry access', async () => {+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);++ await sshProvider({ tmux: true }).start(session());++ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);+ const env = (resolveSshCommand.mock.calls[0] as unknown[])[2] as Record<string, string>;+ expect(env.npm_config_userconfig).toBe('/repo/.switchdash/npmrc');+ expect(env.SWITCHDASH_GITHUB_TOKEN).toBe('remote-tok');+ });+- // Re-attach must be decided before the launch branch runs, because- // `launchSidecar()` assigns `this.relay`. Read afterwards, every fresh launch- // looks like a re-attach and silently loses its registry config.++ // Re-attach is decided from whether this runtime has already opened the pane,++ // not from the sidecar being up: with on-demand attachment the sidecar is++ // running long before the first PTY, so reading it would make every first++ // attach look like a re-attach and silently lose its registry config.+ it('does not recompute registry access when re-attaching', async () => {+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);++ const provider = sshProvider({ tmux: true });+- await sshProvider({ tmux: true }).start(session());++ await provider.start(session());+ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);++ for (const handler of exitHandlers[0] ?? []) handler({ exitCode: 1 });- emitReconnected('ssh-1');- await vi.waitFor(() => expect(openSsh2Pty).toHaveBeenCalledTimes(2));++ await provider.attach();++ expect(openSsh2Pty).toHaveBeenCalledTimes(2);++ // The pane still has the environment it was created with; tmux applies+ // `-e` only at creation, so recomputing would cost round trips for nothing.+ expect(remoteNpmRegistryAuthEnv).toHaveBeenCalledTimes(1);+ });+it('starts the hook-event relay against the sidecar endpoint when tmux is on', async () => {const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];mockSpawn(exitHandlers);diff --cc dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 58c6ecd43,de9a97f12..279d17a1a--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@@ -1,9 -1,11 +1,12 @@@+ import type { PluginFs, SwitchLaunchSpecialization } from '@switchdash/core/agents/plugins';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';+ import { resolveAgentLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';+import type { AttachableRuntime } from '@main/core/agent-runtime/attachment/types';import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';+ import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';import { getAgentById } from '@main/core/agents/getAgentById';import { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';@@@ -18,7 -20,11 +21,9 @@@ import { getTerminalColorEnv } from '@mimport { 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 { remoteNpmRegistryAuthEnv } from '@main/core/switch-rooms/npm-registry-auth';+ import { readAgentSwitchEnvFromFs } from '@main/core/switch-rooms/switch-credentials';import { events } from '@main/lib/events';import { runWithLogContext } from '@main/lib/log-context';import { log } from '@main/lib/logger';@@@ -29,13 -35,19 +34,19 @@@ import { buildAgentHookEnv } from '@shaimport { makePtyId } from '@shared/core/pty/ptyId';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';import type { Session } from '@shared/core/sessions/sessions';+ import { SIDECAR_VERSION } from '../../../../sidecar/sidecar-version';import { ensureAgentSidecar, probeAgentSidecar } from './ensure-agent-sidecar';import { scheduleInitialPromptInjection } from './keystroke-injection';+ import { createRemoteHomePluginFs } from './remote-home-plugin-fs';-import { RemoteHookEventRelay } from './remote-hook-event-relay';import { createRemotePluginFs } from './remote-plugin-fs';import type { SidecarEndpoint, SidecarHost } from './remote-sidecar-launcher';import { resolveAgentExecutable } from './resolve-agent-executable';- import { httpPostJsonOverChannel } from './sidecar-http';+ import {+ httpPostForJsonOverChannel,+ httpPostJsonOverChannel,+ SidecarHttpStatusError,+ } from './sidecar-http';+import { sidecarRelayKey, sidecarRelayRegistry } from './sidecar-relay-registry';const DEFAULT_COLS = 80;const DEFAULT_ROWS = 24;@@@ -81,12 -66,7 +93,16 @@@ export class SshAgentRuntime implementprivate known = false;/** The session this runtime last started — kept for reconnect rehydration. */private session: Session | null = null;- private relay: RemoteHookEventRelay | null = null;+ /** Key of the shared sidecar relay this session subscribes to, when joined. */+ private relayKey: string | null = null;+ /** True once the sidecar is up and the relay joined — the `ensureAttachable` guard. */+ private sidecarReady = false;++ /** True once this runtime has opened the tmux pane, so a later attach lands on++ * an existing agent rather than creating one. Survives eviction (the pane++ * outlives the PTY); cleared only when the session is torn down. */++ private launched = false;+ /** Hook env pointing the agent at its sidecar; resolved by `ensureAttachable`. */+ private hookEnv: Record<string, string> = {};/** Last resolved sidecar endpoint (agent-scoped, shared by all sessions on the* VM), captured at launch so a delete can POST /disconnect without re-ensuring. */private sidecarEndpoint: SidecarEndpoint | null = null;@@@ -241,15 -184,29 +257,32 @@@}/**- * Install the provider's agent hooks into the remote workspace's- * `.claude/settings.local.json` (or equivalent) over SFTP, mirroring what+ * Where a provider's hook config lives on the VM. A workspace-scoped provider+ * (Claude's `.claude/settings.local.json`) writes under the repo dir over+ * SFTP; a global-scoped one (Codex's `~/.codex/hooks.json`) writes under the+ * VM's home, which `this.fs` cannot reach at all.+ */+ private remoteHookFs(scope: 'global' | 'workspace'): PluginFs {+ if (scope === 'global') return createRemoteHomePluginFs(this.ctx);+ if (scope === 'workspace') return createRemotePluginFs(this.fs);+ throw new Error(+ `SshAgentRuntime: no remote hook root for scope '${String(scope)}' — the session would ` ++ 'run with no hooks, reporting neither its provider session id nor when it stops'+ );+ }++ /**+ * Install the provider's agent hooks onto the VM, mirroring what* `ensureHooksInstalled` does for local sessions. The remote agent is spawned- * with the `SWITCHDASH_HOOK_*` env vars, but those only matter if the settings- * actually register the hook commands — otherwise the agent posts no room/- * status events to the sidecar. Best-effort: a failure is logged, not fatal.+ * with the `SWITCHDASH_HOOK_*` env vars, but those only matter if its config+ * actually registers the hook commands — otherwise the agent posts no+ * lifecycle events to the sidecar, so its provider session id is never+ * captured (every resume silently starts a new conversation) and the room's+ * "working on it" never clears. Writing is best-effort: a failure is logged,+ * not fatal.+ *- * The settings file is per workspace, not per session, so concurrent installs- * from every session in a dir are coalesced onto one write.++ * The config file is per workspace (or per host), not per session, so++ * concurrent installs from every session in a dir are coalesced onto one write.*/private async installRemoteHooks(providerId: string): Promise<void> {const plugin = getPlugin(providerId);@@@ -262,17 -219,17 +295,25 @@@});return;}+ const writeHooks = plugin.behavior.hooks.writeHooks;+ const fs = this.remoteHookFs(hooks.scope);++ // A global-scope write targets the VM's home, so it is shared by every dir++ // on the host; keying it on the dir would let one write per dir through.++ const scopeKey = hooks.scope === 'global' ? '~' : this.sessionPath;try {- await plugin.behavior.hooks.writeHooks(fs, []);+ await dedupeInFlight(+ remoteHookInstallsInFlight,- `${this.connectionId}::${this.sessionPath}::${providerId}`,- () => writeHooks(createRemotePluginFs(this.fs), [])++ `${this.connectionId}::${scopeKey}::${providerId}`,++ () => writeHooks(fs, [])+ );- log.info('SshAgentRuntime: installed remote agent hooks', { providerId });+ log.info('SshAgentRuntime: installed remote agent hooks', {+ providerId,+ scope: hooks.scope,+ });} catch (error) {- log.warn('SshAgentRuntime: failed to install remote agent hooks', {+ log.error('SshAgentRuntime: failed to install remote agent hooks', {providerId,+ scope: hooks.scope,error: String(error),});}@@@ -291,25 -267,18 +351,26 @@@// the agent's bypass-permissions setting (not this UI session's).const agent = await getAgentById(session.agentId);const host = this.createSidecarHost();- const credsSlug = this.credsSlugFor(session, agent);- const endpoint = await ensureAgentSidecar({- providerId: session.providerId,- repoDir: this.sessionPath,- deeplinkScheme: DEEPLINK_SCHEME,- autoApprove: agent?.autoApprove ?? false,- credsSlug: agentCredsSlug(session),- agentName: agent?.name ?? session.agentName ?? null,- specialization: toSwitchSpecialization(agent?.providerConfig),- ctx: this.ctx,- connectionId: this.connectionId,- host,- });++ const credsSlug = agentCredsSlug(session);+ // Every session in this dir would otherwise re-run the same deploy+launch on+ // startup; coalesce so one host sees one ensure, not one per session.+ const endpoint = await dedupeInFlight(+ sidecarEnsuresInFlight,+ sidecarRelayKey({ connectionId: this.connectionId, repoDir: this.sessionPath, credsSlug }),+ () =>+ ensureAgentSidecar({+ providerId: session.providerId,+ repoDir: this.sessionPath,+ deeplinkScheme: DEEPLINK_SCHEME,+ autoApprove: agent?.autoApprove ?? false,+ credsSlug,+ agentName: agent?.name ?? session.agentName ?? null,++ specialization: toSwitchSpecialization(agent?.providerConfig),+ ctx: this.ctx,+ connectionId: this.connectionId,+ host,+ })+ );// Drop any sidecar left in this directory by an earlier generation of the// agent's name — it is still polling Switch and no other path can see it.if (agent) await reapStaleSidecarsForAgent(agent, host, this.sessionPath);@@@ -410,8 -412,9 +520,9 @@@repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,- credsSlug: agentCredsSlug(session),+ credsSlug,agentName: agent?.name ?? session.agentName ?? null,+ specialization: toSwitchSpecialization(agent?.providerConfig),ctx: this.ctx,connectionId: this.connectionId,host: this.createSidecarHost(),@@@ -575,16 -612,38 +711,42 @@@// switchdash is closed; it injects room messages into the agent's tmux pane.// It therefore requires tmux, must be up before the agent so the agent's// hook env can point at it, and shares the tmux session as its inject target.- // Decided before the branch below, not inside it: `launchSidecar()`- // assigns `this.relay`, so once it has run a fresh launch is- // indistinguishable from a re-attach.- const reattaching = Boolean(tmuxSessionName && this.relay);+ //+ // `ensureAttachable` is idempotent, so this is a no-op when the session was+ // already made attachable at provision time. Passing the hook env on every+ // attach is safe: `buildTmuxShellLine` supplies it via `tmux new-session -e`,+ // which tmux applies only when it creates the session — an existing pane is+ // reused untouched.++ //++ // `reattaching` cannot be read off the sidecar being up: with on-demand++ // attachment the sidecar is running long before the first PTY. It tracks++ // whether this runtime has already opened the pane, which is what governs++ // the two steps that must happen once per pane rather than once per++ // attach — opening this session's sidecar connection, and resolving the++ // npm auth env.++ const reattaching = Boolean(tmuxSessionName && this.launched);+let hookEnv: Record<string, string> = {};- if (reattaching) {- // Re-attach path (e.g. after an SSH reconnect): the agent is still- // running in its tmux pane and the sidecar + its self-healing relay are- // already live, so re-open the PTY onto the existing pane and skip the- // hook install + sidecar launch. The running agent keeps its original- // hook env, so we need not re-supply it.- log.info('SshAgentRuntime: re-attaching to running tmux session + sidecar', {- sessionId: this.sessionId,- });- } else if (tmuxSessionName) {- const ptyId = makePtyId(session.providerId, this.sessionId);- // Install the agent's hooks into the remote workspace before launch so- // the hook env below actually has commands to run — without this the- // remote agent posts nothing to the sidecar (local sessions get this via- // ensureHooksInstalled).- await this.installRemoteHooks(session.providerId);- const endpoint = await this.launchSidecar(session);- hookEnv = buildAgentHookEnv({- port: endpoint.port,- ptyId,- token: endpoint.token,- endpointFile: endpoint.endpointFile,- });- switchEnv = {- SWITCH_CONNECTION_ID: await this.openSidecarConnection(endpoint, session.providerId),- };+ if (tmuxSessionName) {+ await this.ensureAttachable(session);+ hookEnv = this.hookEnv;++ if (reattaching) {++ // The agent is still running in its tmux pane and its sidecar++ // connection is still open, so re-opening the PTY is all that is left.++ log.info('SshAgentRuntime: re-attaching to running tmux session + sidecar', {++ sessionId: this.sessionId,++ });++ } else {++ const endpoint = this.sidecarEndpoint;++ if (!endpoint) {++ throw new Error(++ 'SshAgentRuntime: sidecar reported ready with no endpoint — refusing to launch an agent that cannot reach Switch'++ );++ }++ switchEnv = {++ SWITCH_CONNECTION_ID: await this.openSidecarConnection(endpoint, session.providerId),++ };++ }} else {log.warn('SshAgentRuntime: tmux disabled — remote agent will not stay connected to Switch while detached',@@@ -671,6 -745,6 +848,7 @@@},});this.pty = pty;++ this.launched = true;scheduleInitialPromptInjection({pty,session,@@@ -733,6 -807,6 +914,7 @@@killTmux: boolean;}): Promise<void> {this.known = false;++ this.launched = false;this.session = null;if (this.tmux && opts.disconnectSidecar) {await this.disconnectSidecarSession(this.sessionId, true);diff --cc dash/apps/switchdash-desktop/src/renderer/App.tsxindex e803ee39f,ec96c4de7..9c36f6c44--- a/dash/apps/switchdash-desktop/src/renderer/App.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/App.tsx@@@ -1,8 -1,8 +1,9 @@@import { QueryClientProvider } from '@tanstack/react-query';import { AppMenuEvents } from './app/app-menu-events';import { Workspace } from './app/workspace';+import { SessionFocusReporter } from './features/sessions/session-focus-reporter-mount';import { SessionDeeplinkListener } from './features/switch-rooms/session-deeplink-listener';+ import { SwitchToolsUnavailableListener } from './features/switch-rooms/switch-tools-unavailable-listener';import { WorkspaceLayoutContextProvider } from './lib/layout/layout-provider';import { WorkspaceViewProvider } from './lib/layout/provider';import { ModalRenderer } from './lib/modal/modal-renderer';@@@ -19,8 -19,8 +20,9 @@@ function AppContent()<TerminalPoolProvider><WorkspaceViewProvider><AppMenuEvents />+ <SessionFocusReporter /><SessionDeeplinkListener />+ <SwitchToolsUnavailableListener /><RightSidebarProvider><ThemeProvider><ModalRenderer />