Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(codex): Codex provider groundwork — env-driven sandbox/approval, unconditional per-agent credentials, explicit known-agent type (CHOO-1436) (#91)
Christian McDermott358473494ab6
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.ymlindex a140fcd6e..bf9e3db53 100644--- a/.github/workflows/pr-ci.yml+++ b/.github/workflows/pr-ci.yml@@ -13,10 +13,19 @@ name: PR CI# Path filtering: a `changes` job (dorny/paths-filter) detects which trees a PR# touched; each tree's job is gated on its filter, so a backend-only PR skips# the dash/gateway jobs entirely. Shared files (workflows, root config) fan out-# to everything, since a change there can affect any tree.+# to everything, since a change there can affect any tree. On a push to main+# every tree runs regardless: the filter resolves its base differently outside a+# PR, and a main run that quietly skipped the tree it should have checked would+# report the same green as one that verified it.+#+# Main is verified on push as well as per-PR, because a PR merged while red+# leaves main red with nothing to say so — the next branch to merge main+# inherits the failure and pays for it (CHOO-1430 reached main exactly this way).on:pull_request:+ push:+ branches: [main]# Cancel a PR's in-flight CI when a new commit is pushed to the same ref.concurrency:@@ -64,7 +73,7 @@ jobs:backend:name: Backend (core)needs: changes- if: ${{ needs.changes.outputs.backend == 'true' }}+ if: ${{ needs.changes.outputs.backend == 'true' || github.event_name == 'push' }}runs-on: ubuntu-lateststeps:- name: Checkout@@ -98,7 +107,7 @@ jobs:dash:name: Switchdash (dash)needs: changes- if: ${{ needs.changes.outputs.dash == 'true' }}+ if: ${{ needs.changes.outputs.dash == 'true' || github.event_name == 'push' }}runs-on: ubuntu-latestdefaults:run:@@ -145,7 +154,7 @@ jobs:gateway:name: Gateway UIneeds: changes- if: ${{ needs.changes.outputs.gateway == 'true' }}+ if: ${{ needs.changes.outputs.gateway == 'true' || github.event_name == 'push' }}runs-on: ubuntu-latestdefaults:run:@@ -170,6 +179,11 @@ jobs:gitleaks:name: Secret scan (gitleaks)+ # Scans a PR's commit range, which only exists on a pull_request event: on a+ # push the base/head SHAs below are empty and the scan would cover nothing+ # while still reporting success. Every commit reaching main has been scanned+ # by its own PR.+ if: ${{ github.event_name == 'pull_request' }}runs-on: ubuntu-lateststeps:- name: Checkoutdiff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.pyindex 72782b7fb..44f42a11f 100644--- a/core/switch_core/gateway/known_agents.py+++ b/core/switch_core/gateway/known_agents.py@@ -297,8 +297,132 @@ class ClaudeCodeKnownAgent(KnownAgent):)+class CodexOptions(KnownAgentOptions):+ auto_session: bool = False+ """When True, the operator's connector (switchdash) watches every room this+ agent belongs to and auto-spawns a Codex session — connected to the room and+ wired to the agent's identity — the moment the agent is addressed in a room+ where it has no live session. The registered profile becomes `auto_session`.+ Codex has no plugin-channel of its own; switchdash delivers inbound room+ messages by injecting them into the session's terminal (CHOO-1436)."""++ repo_dir: str | None = None+ """Absolute path to the directory the operator runs Codex from. Used to+ generate a ready-to-paste `cd <repo_dir> && codex "connect to switch room …"`+ command shown when the agent is addressed with no live session. None → a+ `<codex-dir>` placeholder is shown instead."""++ notify_user: str | None = None+ """Username (on the room's bridged platform) to `@`-mention in the+ unavailable-session message so the operator gets a notification. Bare name,+ no leading `@`. None → post without a mention."""++ # No `channels_enabled`: switchdash sends it for every provider, but Codex+ # has no connector channel of its own, so nothing here could act on it.+ # `KnownAgentOptions` ignores unknown keys, so the shared registration path+ # still works — and the schema-driven gateway form does not render a control+ # that silently does nothing.++ @field_validator("repo_dir", "notify_user", mode="before")+ @classmethod+ def _blank_string_to_none(cls, value: object) -> object:+ if isinstance(value, str) and value.strip() == "":+ return None+ return value+++class CodexKnownAgent(KnownAgent):+ connector_type = "Codex CLI"+ options_schema = CodexOptions+ tools = [+ ToolSpec(name="Shell", description="Executes shell commands"),+ ToolSpec(name="ApplyPatch", description="Applies patches to files"),+ ToolSpec(name="Read", description="Reads file contents"),+ ]+ models: ClassVar[list[ModelSpec]] = []++ @classmethod+ def build_profile(cls, options: KnownAgentOptions) -> IntegrationProfile:+ assert isinstance(options, CodexOptions)+ # switchdash watches + auto-spawns when auto_session; otherwise it keeps a+ # session live and delivers messages by terminal injection, which is the+ # session_addressable model. Codex does not report per-tool events or+ # mediate tool calls (it runs auto-approved), so those lists stay empty —+ # unlike Claude Code, whose PostToolUse hooks report tool activity.+ connection_model = (+ "auto_session" if options.auto_session else "session_addressable"+ )+ return IntegrationProfile(+ connection_model=connection_model,+ message_exchange=True,+ pre_invocation_mediation=[],+ post_invocation_mediation=[],+ event_reporting=[],+ task_protocol=TaskProtocolConfig(can_delegate=True, can_accept=True),+ # Same story as Claude Code: Codex is a TUI, so reset / compact /+ # interrupt only work when switchdash is driving the session and can+ # inject keystrokes. A standalone `codex` can't be controlled, so all+ # three resolve per live session via AgentRuntimeState.+ command_capabilities=CommandCapabilities(+ reset="session_dependent",+ compact="session_dependent",+ interrupt="session_dependent",+ ),+ )++ @classmethod+ def start_session_instructions(+ cls,+ options: KnownAgentOptions,+ agent: Agent,+ room_name: str,+ assume_role: str | None = None,+ other_room_names: list[str] | None = None,+ connected_not_live: bool = False,+ ) -> str | None:+ """Build the room-facing onboarding message for a Codex agent.++ Mirrors the Claude Code shape but emits a `codex "…"` command (never a+ `claude` one) and omits Claude-specific flags. Codex sessions are normally+ auto-managed by switchdash, so this fallback is shown mainly when no+ connector is watching.+ """+ assert isinstance(options, CodexOptions)+ dir_token = options.repo_dir if options.repo_dir else "<codex-dir>"+ prompt = f"connect to switch room {room_name}"+ if assume_role:+ prompt += f" and assume the role {assume_role}"+ cmd = f'cd "{dir_token}" && codex "{prompt}"'++ prefix = f"@{options.notify_user}\n\n" if options.notify_user else ""+ if connected_not_live:+ opening = (+ "I have a session connected to this room, but it isn't reporting "+ "as live, so I'm not receiving messages. Relaunch it, or start a "+ "fresh session, with:"+ )+ elif other_room_names:+ where = ", ".join(f"**{name}**" for name in other_room_names)+ opening = (+ f"I don't have a session connected to this room right now, but I "+ f"do have other session(s) connected to {where}. Either ask me in "+ "one of those rooms to come here, or start a new session connected "+ "to this room — my operator should run:"+ )+ else:+ opening = (+ "I don't have a session connected to this room. To set up a new "+ "session connected to this room, my operator should run:"+ )+ return (+ f"{prefix}{opening}\n\n```\n{cmd}\n```\n\n(or start Codex manually and "+ "ask me to connect to the room.)"+ )++KNOWN_AGENTS: dict[str, type[KnownAgent]] = {"claude-code": ClaudeCodeKnownAgent,+ "codex": CodexKnownAgent,}diff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.pyindex 63b400967..6896d9eb8 100644--- a/core/tests/switch_core/gateway/test_known_agents.py+++ b/core/tests/switch_core/gateway/test_known_agents.py@@ -3,8 +3,11 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom switch_core.gateway.known_agents import (+ KNOWN_AGENTS,ClaudeCodeKnownAgent,ClaudeCodeOptions,+ CodexKnownAgent,+ CodexOptions,known_agent_for,)@@ -232,6 +235,148 @@ class TestStartSessionInstructions:assert "I don't have a session connected to this room." in msg+class TestCodexKnownAgent:+ def test_registered_under_codex_key(self) -> None:+ assert KNOWN_AGENTS.get("codex") is CodexKnownAgent+ assert CodexKnownAgent.connector_type == "Codex CLI"++ def test_default_profile_is_session_addressable(self) -> None:+ profile = CodexKnownAgent.build_profile(CodexOptions())+ assert profile.connection_model == "session_addressable"++ def test_auto_session_sets_auto_session_model(self) -> None:+ profile = CodexKnownAgent.build_profile(CodexOptions(auto_session=True))+ assert profile.connection_model == "auto_session"++ def test_no_tool_call_mediation_or_reporting(self) -> None:+ # Codex runs auto-approved and reports lifecycle hooks only (not per-tool+ # events), unlike Claude Code.+ profile = CodexKnownAgent.build_profile(CodexOptions())+ assert profile.pre_invocation_mediation == []+ assert profile.event_reporting == []++ def test_can_delegate_and_accept_tasks(self) -> None:+ profile = CodexKnownAgent.build_profile(CodexOptions())+ assert profile.task_protocol.can_delegate is True+ assert profile.task_protocol.can_accept is True++ def test_commands_are_session_dependent(self) -> None:+ # Codex is a TUI driven by switchdash keystroke injection, same as Claude+ # Code — so reset/compact/interrupt depend on a live managed session.+ # Must stay in step with `BY_PROVIDER.codex` in switchdash's+ # `main/core/switch-rooms/session-control.ts`; declaring a command here+ # that switchdash cannot execute yields a worse message than "unsupported".+ caps = CodexKnownAgent.build_profile(CodexOptions()).command_capabilities+ assert caps.reset == "session_dependent"+ assert caps.compact == "session_dependent"+ assert caps.interrupt == "session_dependent"++ def test_start_session_instructions_emit_codex_not_claude(self) -> None:+ opts = CodexOptions(repo_dir="/Users/x/repo")+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")+ assert msg is not None+ # The path is quoted so a repo_dir with spaces still produces a valid+ # paste command.+ assert 'cd "/Users/x/repo" && codex "connect to switch room hub"' in msg+ # It must NOT suggest a claude command or Claude-specific flags.+ assert "claude" not in msg+ assert "--dangerously-load-development-channels" not in msg+ # The footer must not falsely promise auto-start (this message only shows+ # when no session is being auto-spawned); it points at a manual start.+ assert "auto-starts one when I'm addressed" not in msg+ assert "start Codex manually" in msg++ def test_repo_dir_with_spaces_stays_quoted(self) -> None:+ opts = CodexOptions(repo_dir="/Users/alice/my project")+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")+ assert msg is not None+ assert 'cd "/Users/alice/my project" && codex' in msg++ def test_connected_not_live_opening(self) -> None:+ opts = CodexOptions(repo_dir="/r")+ msg = CodexKnownAgent.start_session_instructions(+ opts, _agent({}), "ops", connected_not_live=True+ )+ assert msg is not None+ assert "isn't reporting" in msg+ assert "I don't have a session connected to this room." not in msg+ assert "claude" not in msg++ def test_other_room_names_branch(self) -> None:+ opts = CodexOptions(repo_dir="/r")+ msg = CodexKnownAgent.start_session_instructions(+ opts, _agent({}), "ops", other_room_names=["hub", "triage"]+ )+ assert msg is not None+ assert "**hub**" in msg+ assert "**triage**" in msg+ assert "claude" not in msg++ def test_assume_role_folded_into_prompt(self) -> None:+ opts = CodexOptions(repo_dir="/r")+ msg = CodexKnownAgent.start_session_instructions(+ opts, _agent({}), "ops", assume_role="reviewer"+ )+ assert msg is not None+ assert 'codex "connect to switch room ops and assume the role reviewer"' in msg++ def test_empty_string_repo_dir_normalised_to_placeholder(self) -> None:+ opts = CodexOptions(repo_dir="")+ assert opts.repo_dir is None+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "triage")+ assert msg is not None+ assert 'cd "<codex-dir>"' in msg++ def test_empty_string_notify_user_normalised_to_none(self) -> None:+ opts = CodexOptions(notify_user="")+ assert opts.notify_user is None+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")+ assert msg is not None+ assert not msg.startswith("@")++ def test_no_repo_dir_uses_codex_placeholder(self) -> None:+ msg = CodexKnownAgent.start_session_instructions(+ CodexOptions(repo_dir=None), _agent({}), "triage"+ )+ assert msg is not None+ assert 'cd "<codex-dir>"' in msg++ def test_notify_user_prepended_as_at_mention(self) -> None:+ opts = CodexOptions(repo_dir="/x", notify_user="cmcd")+ msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub")+ assert msg is not None+ assert msg.startswith("@cmcd\n\n")++ def test_channels_enabled_is_dropped_not_offered_as_an_option(self) -> None:+ # switchdash sends channels_enabled for every provider, so registration+ # must still accept it — but Codex has no channel, so it is not a field.+ # The gateway renders the options form from this schema; a declared field+ # would be an interactive control that changes nothing.+ assert "channels_enabled" not in CodexOptions.model_json_schema()["properties"]++ opts = CodexOptions.model_validate({"channels_enabled": False})+ assert "channels_enabled" not in opts.model_dump()+ assert (+ CodexKnownAgent.build_profile(opts).connection_model+ == "session_addressable"+ )++ def test_known_agent_for_round_trips_codex(self) -> None:+ agent = _agent(+ {+ "known_agent_type": "codex",+ "known_agent_options": {"auto_session": True, "repo_dir": "/tmp/r"},+ }+ )+ result = known_agent_for(agent)+ assert result is not None+ spec, options = result+ assert spec is CodexKnownAgent+ assert isinstance(options, CodexOptions)+ assert options.auto_session is True+ assert options.repo_dir == "/tmp/r"++class TestKnownAgentFor:def test_round_trips_claude_code_options(self) -> None:agent = _agent(diff --git a/dash/AGENTS.md b/dash/AGENTS.mdindex e05c811e1..7fc446880 100644--- a/dash/AGENTS.md+++ b/dash/AGENTS.md@@ -442,9 +442,8 @@ pnpm run test`.switchdash.json`.- Optional environment variables:`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,- `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`,- `SWITCHDASH_FAKE_UPDATE`, `CODEX_SANDBOX_MODE`,- and `CODEX_APPROVAL_POLICY`.+ `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`, and+ `SWITCHDASH_FAKE_UPDATE`.- App updates in dev: the update service is inert outside packaged builds, so the"update available" UI cannot be exercised by `pnpm run dev` alone. Set`SWITCHDASH_FAKE_UPDATE` to replay the lifecycle against a simulated release —diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.tsindex d14be4844..6f4147976 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts@@ -59,7 +59,7 @@ vi.mock('@main/core/switch-rooms/switch-notification-poller', () => ({}));vi.mock('@main/core/switch-rooms/switch-credentials', () => ({- readAgentSwitchEnv: vi.fn(async () => ({})),+ readAgentSwitchEnvFromFs: vi.fn(async () => ({})),}));// Reads the app's userData path and shells out to `gh`; neither exists here,@@ -163,6 +163,7 @@ vi.mock('@main/core/settings/settings-service', () => ({}));const { events } = await import('@main/lib/events');+const { readAgentSwitchEnvFromFs } = await import('@main/core/switch-rooms/switch-credentials');const { agentHookService } = await import('@main/core/agent-hooks/agent-hook-service');const { appSettingsService } = await import('@main/core/settings/settings-service');@@ -204,6 +205,7 @@ function session(): Session {return {id: 'session-1',agentId: 'agent-1',+ agentName: 'codex-hoot',providerId: 'codex',title: 'Session 1',shellId: 'system',@@ -258,6 +260,30 @@ describe('local agent runtime respawn state', () => {ptySessionRegistry.unregister('location-1:session-1');});+ it('reads the identity file keyed by the agent row name, not the session id', async () => {+ // Every writer keys `.switch/agents/<slug>.json` by the agent's name; a+ // reader that keyed by id would silently fall back to the shared+ // settings.local.json identity (CHOO-1440).+ const exitHandlers: Array<(info: PtyExitInfo) => void> = [];+ spawnLocalPty.mockReturnValue(fakePty(exitHandlers));+ vi.mocked(readAgentSwitchEnvFromFs).mockResolvedValueOnce({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ });++ await localProvider().start(session());++ expect(readAgentSwitchEnvFromFs).toHaveBeenCalledWith(+ expect.anything(),+ 'codex-hoot',+ expect.anything()+ );+ const request = spawnLocalPty.mock.calls[0][0] as { env: Record<string, string> };+ expect(request.env.SWITCH_API_TOKEN).toBe('tok-123');+ expect(request.env.SWITCH_AGENT_ID).toBe('sw-1');+ });+it('passes global editor variables to local agent sessions', async () => {const previousEditor = process.env.EDITOR;const previousShell = process.env.SHELL;diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex aed5be977..2a2e630b3 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -5,7 +5,7 @@ import { ensureHooksInstalled } from '@main/core/agent-hooks/hook-config-serviceimport { 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 { agentSettingsPath } from '@main/core/agents/switch-settings-paths';+import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';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';@@ -21,7 +21,7 @@ import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-simport { sessionHooks } from '@main/core/sessions/session-hooks';import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';import { npmRegistryAuthEnv } from '@main/core/switch-rooms/npm-registry-auth';-import { readAgentSwitchEnv } from '@main/core/switch-rooms/switch-credentials';+import { readAgentSwitchEnvFromFs } from '@main/core/switch-rooms/switch-credentials';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';@@ -185,14 +185,14 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {// to sit in `.claude/settings.local.json`. Real env vars outrank every// settings file and reach the spawned MCP server, so inject the agent's// identity last (highest precedence): a subagent from its definition creds,- // and a plain agent from its provider-neutral `.switch/agents/<id>.json`- // (empty when absent — the session then falls back to settings.local.json,- // which Claude reads natively). Lets agents sharing a location keep distinct- // identities (CHOO-1440).- const subagentVars =+ // and a plain agent from its provider-neutral `.switch/agents/<slug>.json`+ // (empty when absent — only Claude then recovers, by reading+ // settings.local.json natively; any other provider launches unidentified).+ const workspaceFs = createPluginFs(this.sessionPath);+ const identityVars =session.agentName && repoAgents- ? await repoAgents.readLaunchEnv(createPluginFs(this.sessionPath), session.agentName)- : await readAgentSwitchEnv(agentSettingsPath(this.sessionPath, session.agentId), log);+ ? await repoAgents.readLaunchEnv(workspaceFs, session.agentName)+ : await readAgentSwitchEnvFromFs(workspaceFs, agentCredsSlug(session), log);// Open this session's Switch connection before the session exists, and// hand it the id. Its tool calls then arrive on the connection switchdash@@ -226,7 +226,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {}),...colorEnv,...this.sessionEnvVars,- ...subagentVars,+ ...identityVars,...npmAuthEnv,...(switchConnectionId ? { SWITCH_CONNECTION_ID: switchConnectionId } : {}),};diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 8b37279f7..494ed84d2 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { FileSystemError, FileSystemErrorCodes } from '@main/core/fs/types';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';@@ -148,14 +149,31 @@ function makeCtx(): ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'] {return { exec: vi.fn(async () => ({ stdout: '', stderr: '' })) } as never;}+/** A remote filesystem holding `files` (keyed by repo-relative path); anything+ * else reads as NOT_FOUND, matching SshFileSystem. */+function makeRemoteFs(files: Record<string, string> = {}) {+ return {+ copyLocalFile: vi.fn(async () => {}),+ read: vi.fn(async (relPath: string) => {+ const content = files[relPath];+ if (content === undefined) {+ throw new FileSystemError(`no such file: ${relPath}`, FileSystemErrorCodes.NOT_FOUND);+ }+ return { content };+ }),+ } as never;+}+function sshProvider({proxy = makeProxy(),tmux = false,ctx = makeCtx(),+ fs = makeRemoteFs(),}: {proxy?: SshClientProxy;tmux?: boolean;ctx?: ConstructorParameters<typeof SshAgentRuntime>[0]['ctx'];+ fs?: ConstructorParameters<typeof SshAgentRuntime>[0]['fs'];} = {}) {return new SshAgentRuntime({locationId: 'location-1',@@ -163,7 +181,7 @@ function sshProvider({sessionPath: '/repo',tmux,ctx,- fs: { copyLocalFile: vi.fn(async () => {}) } as never,+ fs,proxy,connectionId: 'ssh-1',});@@ -174,6 +192,7 @@ function session(): Session {return {id: 'session-1',agentId: 'agent-1',+ agentName: 'codex-hoot',providerId: 'codex',title: 'Session 1',shellId: 'system',@@ -240,6 +259,37 @@ describe('SshAgentRuntime', () => {expect(ptySessionRegistry.get(sessionId)).toBeDefined();});+ it('injects the agent identity from its neutral creds file for a provider without repo-agents', async () => {+ // Codex has no `repoAgents` behavior, so there is no `readLaunchEnv` hook to+ // go through — the runtime must still read `.switch/agents/<name>.json` from+ // the VM, or the remote session authenticates to Switch as nobody.+ const exitHandlers: Array<Array<(info: PtyExitInfo) => void>> = [];+ mockSpawn(exitHandlers);++ await sshProvider({+ fs: makeRemoteFs({+ '.switch/agents/codex-hoot.json': JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ },+ }),+ }),+ }).start(session());++ expect(resolveSshCommand).toHaveBeenCalledWith(+ 'agent',+ expect.anything(),+ expect.objectContaining({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ }),+ expect.anything()+ );+ });+it('propagates a failed SSH channel open as an error', async () => {openSsh2Pty.mockResolvedValue({ success: false, error: new Error('channel refused') });diff --git a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex bc81bf7a3..0ce86ae51 100644--- a/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -3,6 +3,7 @@ import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';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 { 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';@@ -21,6 +22,7 @@ import { sshConnectionManager } from '@main/core/ssh/lifecycle/production-ssh-coimport 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';@@ -214,8 +216,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,- credsSlug: agent?.name ?? session.agentName ?? session.agentId,- agentName: agent?.name ?? session.agentName ?? null,+ credsSlug: agentCredsSlug(session),+ agentName: session.agentName ?? null,ctx: this.ctx,connectionId: this.connectionId,host,@@ -304,8 +306,8 @@ export class SshAgentRuntime implements AgentRuntimeProvider {repoDir: this.sessionPath,deeplinkScheme: DEEPLINK_SCHEME,autoApprove: agent?.autoApprove ?? false,- credsSlug: agent?.name ?? session.agentName ?? session.agentId,- agentName: agent?.name ?? session.agentName ?? null,+ credsSlug: agentCredsSlug(session),+ agentName: session.agentName ?? null,ctx: this.ctx,connectionId: this.connectionId,host: this.createSidecarHost(),@@ -452,13 +454,14 @@ export class SshAgentRuntime implements AgentRuntimeProvider {const providerEnv: Record<string, string> = { ...agentCommand.env, ...customEnv };// The agent's Switch identity as real env vars (highest precedence): read- // from its neutral `.switch/agents/<name>.json` on the VM. A `--settings`+ // from its neutral `.switch/agents/<slug>.json` on the VM. A `--settings`// file's env block is not reliably propagated to the spawned MCP server, so// inject it directly, matching the local runtime.+ const remoteFs = createRemotePluginFs(this.fs);const identityVars =session.agentName && repoAgents- ? await repoAgents.readLaunchEnv(createRemotePluginFs(this.fs), session.agentName)- : {};+ ? await repoAgents.readLaunchEnv(remoteFs, session.agentName)+ : await readAgentSwitchEnvFromFs(remoteFs, agentCredsSlug(session), log);const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.tsnew file mode 100644index 000000000..4608b1225--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.test.ts@@ -0,0 +1,159 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { agentSettingsRelativePath } from './switch-settings-paths';++/** In-memory {@link PluginFs} keyed by the exact relative paths the writers use. */+function fakeFs(seed: Record<string, string> = {}): PluginFs {+ const files = new Map<string, string>(Object.entries(seed));+ return {+ read: (p) => Promise.resolve(files.has(p) ? (files.get(p) as string) : null),+ write: (p, c) => {+ files.set(p, c);+ return Promise.resolve();+ },+ delete: (p) => {+ files.delete(p);+ return Promise.resolve();+ },+ exists: (p) => Promise.resolve(files.has(p)),+ list: () => Promise.resolve([...files.keys()]),+ };+}++// `repoAgents` is what `getPlugin` returns — set it to null in a test to+// simulate a provider without repo-agent definitions (e.g. Codex).+const h = vi.hoisted(() => {+ const writeDefinition = vi.fn(async () => {});+ const state: { workspace: PluginFs | null; repoAgents: object | null } = {+ workspace: null,+ repoAgents: { writeDefinition },+ };+ return {+ state,+ writeDefinition,+ registerAgentIdentity: vi.fn(async () => ({+ kind: 'created' as const,+ id: 'sw-1',+ apiKey: 'tok-123',+ })),+ createAgent: vi.fn(async (input: Record<string, unknown>) => ({ ...input })),+ };+});++vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),+}));+vi.mock('./register-agent-identity', () => ({ registerAgentIdentity: h.registerAgentIdentity }));+vi.mock('./createAgent', () => ({ createAgent: h.createAgent }));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: vi.fn(async () => ({+ fs: h.state.workspace as PluginFs,+ close: vi.fn(),+ })),+}));+vi.mock('@main/core/switch-servers/servers-store', () => ({+ getServer: vi.fn(async () => ({ id: 'srv-1', apiUrl: 'https://switch.example.com' })),+}));+vi.mock('@main/core/locations/store', () => ({+ ensureLocation: vi.fn(async () => ({ id: 'loc-1' })),+}));+vi.mock('@main/core/locations/path-utils', () => ({ checkIsValidDirectory: () => true }));+vi.mock('@main/core/locations/location-manager', () => ({+ locationManager: { openLocation: vi.fn(async () => {}) },+}));+vi.mock('./setAgentAutoSession', () => ({+ reconcileAgentAutoSessionFromGateway: vi.fn(async () => {}),+}));+vi.mock('./agent-events', () => ({ agentEvents: { _emit: vi.fn() } }));+vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));++const { addAgent } = await import('./add-agent');++function params(overrides: Record<string, unknown> = {}) {+ return {+ sshHost: null,+ dir: '/repo',+ name: 'codex-hoot',+ providerId: 'codex' as const,+ serverId: 'srv-1',+ description: 'Codex running in repo',+ autoSession: false,+ autoApprove: false,+ definitionAttributes: {},+ ...overrides,+ };+}++function credsOf(fs: PluginFs, slug: string): Promise<Record<string, string>> {+ return fs+ .read(agentSettingsRelativePath(slug))+ .then((raw) => (JSON.parse(raw as string) as { env: Record<string, string> }).env);+}++describe('addAgent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.state.repoAgents = { writeDefinition: h.writeDefinition };+ h.state.workspace = fakeFs();+ h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });+ });++ it('writes name-keyed credentials for a provider with no repo-agent definitions', async () => {+ // Codex has no `repoAgents` behavior. Before the credential write became+ // unconditional it got no credentials on disk at all, so its sessions+ // authenticated to Switch as whatever was in settings.local.json.+ h.state.repoAgents = null;+ const fs = h.state.workspace as PluginFs;++ const result = await addAgent(params());++ expect(result.kind).toBe('created');+ expect(await credsOf(fs, 'codex-hoot')).toEqual({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ });+ expect(h.writeDefinition).not.toHaveBeenCalled();+ });++ it('writes both credentials and an on-disk definition for a repo-agents provider', async () => {+ const fs = h.state.workspace as PluginFs;++ await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));++ expect((await credsOf(fs, 'cc-hoot')).SWITCH_API_TOKEN).toBe('tok-123');+ expect(h.writeDefinition).toHaveBeenCalledWith(+ fs,+ expect.objectContaining({ name: 'cc-hoot', description: 'Codex running in repo' })+ );+ });++ it('git-ignores the credentials directory so the token never enters VCS', async () => {+ const fs = h.state.workspace as PluginFs;+ await addAgent(params());+ expect(await fs.read('.switch/agents/.gitignore')).toBe('*\n');+ });++ it('registers under the gateway known-agent type derived from the provider', async () => {+ await addAgent(params());+ expect(h.registerAgentIdentity).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ name: 'codex-hoot', agentType: 'codex' })+ );++ await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));+ expect(h.registerAgentIdentity).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({ agentType: 'claude-code' })+ );+ });++ it('writes nothing to the workspace when registration fails', async () => {+ h.registerAgentIdentity.mockResolvedValue({ kind: 'name-conflict' } as never);+ const fs = h.state.workspace as PluginFs;++ expect((await addAgent(params())).kind).toBe('name-conflict');+ expect(await fs.read(agentSettingsRelativePath('codex-hoot'))).toBeNull();+ expect(h.createAgent).not.toHaveBeenCalled();+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.tsindex 1515d1da4..1d033e24a 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/add-agent.ts@@ -12,8 +12,10 @@ import { basenameFromAnyPath } from '@shared/path-name';import { agentEvents } from './agent-events';import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { createAgent } from './createAgent';+import { knownAgentTypeForProvider } from './known-agent-type';import { registerAgentIdentity } from './register-agent-identity';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';+import { writeNeutralAgentSettingsFs } from './write-switch-settings';export type AddAgentParams = {id?: string;@@ -71,24 +73,30 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>description: params.description,repoDir: params.dir,autoSession: params.autoSession,+ agentType: knownAgentTypeForProvider(params.providerId),});if (registered.kind !== 'created') return registered;const behavior = getPlugin(params.providerId).behavior.repoAgents;const workspace = await resolveWorkspaceFsFor(params.sshHost, params.dir);try {+ // Writing the per-agent Switch credentials is unconditional core behavior for+ // every provider, keyed by the agent's `name` — the single key-space every+ // reader (launch path, auto-session watcher, notification poller) uses+ // (CHOO-1440). Providers with repo-agent definitions (Claude) layer their+ // on-disk definition on top; that's the only provider-specific extra.+ await writeNeutralAgentSettingsFs(workspace.fs, {+ slug: params.name,+ apiEndpoint: server.apiUrl,+ apiToken: registered.apiKey,+ agentId: registered.id,+ });if (behavior) {await behavior.writeDefinition(workspace.fs, {...params.definitionAttributes,name: params.name,description: params.description,});- await behavior.writeCredentials(workspace.fs, {- agentName: params.name,- apiEndpoint: server.apiUrl,- apiToken: registered.apiKey,- agentId: registered.id,- });}} finally {workspace.close();diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-creds-slug.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-creds-slug.tsnew file mode 100644index 000000000..1cd352adb--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-creds-slug.ts@@ -0,0 +1,19 @@+import type { Session } from '@shared/core/sessions/sessions';++/**+ * The per-agent key its Switch credentials live under: `.switch/agents/<slug>.json`+ * (CHOO-1440). Every writer keys by the agent's `name`, so every reader must too.+ *+ * `session.agentName` is the agent row's live `name`, joined on every session load+ * rather than frozen into the row, so it already follows a rename — re-reading the+ * agent here could only return the same value. The agent id is a last-resort+ * fallback for a session built without a name.+ *+ * This is the derivation for readers that hold a session: the launch paths, the+ * sidecar and the remote preflight. Readers that hold an agent row instead (the+ * auto-session watcher, the notification poller) take the same key from `name`+ * directly — the key-space is shared even though the input differs.+ */+export function agentCredsSlug(session: Session): string {+ return session.agentName ?? session.agentId;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.test.tsindex f36a419a3..866612f9e 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.test.ts@@ -21,9 +21,17 @@ describe('slugifyAgentNamePart', () => {describe('suggestAgentDefaults', () => {it('builds a claude-code.<repo>.<user> name and matches the agent-name pattern', () => {- const { name, description } = suggestAgentDefaults('/Users/someone/My Repo');+ const { name, description } = suggestAgentDefaults('/Users/someone/My Repo', 'claude');expect(name.startsWith('claude-code.my-repo')).toBe(true);expect(name).toMatch(/^[a-z0-9][a-z0-9._-]*$/);expect(description).toBe('Claude Code running in My Repo');});++ it('prefixes the name and description with the chosen provider (Codex)', () => {+ const { name, description } = suggestAgentDefaults('/Users/someone/My Repo', 'codex');+ expect(name.startsWith('codex.my-repo')).toBe(true);+ expect(name).not.toContain('claude-code');+ expect(name).toMatch(/^[a-z0-9][a-z0-9._-]*$/);+ expect(description).toBe('Codex running in My Repo');+ });});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.tsindex eef97ed76..e194dd865 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-defaults.ts@@ -1,5 +1,6 @@import os from 'node:os';import path from 'node:path';+import { getProvider, type AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type { AgentDefaults } from '@shared/core/switch-servers/switch-servers';/**@@ -17,13 +18,18 @@ export function slugifyAgentNamePart(value: string): string {}/**- * Suggest a default name and description for a new Claude Code agent in `dir`.- * The name is `claude-code.<repo-slug>.<user-slug>` — the per-user suffix keeps- * two developers registering from the same repo from colliding (see the- * `configure` skill). Falls back to a bare `claude-code` if both parts slug to- * empty.+ * Suggest a default name and description for a new agent of `providerId` in+ * `dir`. The name is `<provider-slug>.<repo-slug>.<user-slug>`, where the prefix+ * is the provider's display name slugified — `codex`, `claude-code`, `grok`, etc.+ * — so the default reflects the chosen agent type (CHOO-1436). The per-user+ * suffix keeps two developers registering from the same repo from colliding (see+ * the `configure` skill). Falls back to the bare provider slug if the repo/user+ * parts both slug to empty.*/-export function suggestAgentDefaults(dir: string): AgentDefaults {+export function suggestAgentDefaults(dir: string, providerId: AgentProviderId): AgentDefaults {+ const providerName = getProvider(providerId)?.name ?? providerId;+ const providerSlug =+ slugifyAgentNamePart(providerName) || slugifyAgentNamePart(providerId) || 'agent';const repoSlug = slugifyAgentNamePart(path.basename(dir));let userSlug = '';try {@@ -32,8 +38,8 @@ export function suggestAgentDefaults(dir: string): AgentDefaults {userSlug = '';}- const parts = ['claude-code', repoSlug, userSlug].filter((p) => p.length > 0);- const name = parts.length > 1 ? parts.join('.') : 'claude-code';+ const parts = [providerSlug, repoSlug, userSlug].filter((p) => p.length > 0);+ const name = parts.length > 1 ? parts.join('.') : providerSlug;const repoLabel = path.basename(dir) || 'this directory';- return { name, description: `Claude Code running in ${repoLabel}` };+ return { name, description: `${providerName} running in ${repoLabel}` };}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.db.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.db.test.tsnew file mode 100644index 000000000..2d5899bbb--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.db.test.ts@@ -0,0 +1,76 @@+import { openFixture } from '@tooling/utils/db';+import { eq, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AppDb } from '@main/db/client';+import { kv } from '@main/db/schema';+import {+ AGENT_STORAGE_MIGRATION_GENERATION,+ completedAgentStorageMigrationGeneration,+ markAgentStorageMigrationComplete,+} from './agent-storage-migration-marker';++const mocks = vi.hoisted(() => ({+ db: undefined as AppDb | undefined,+}));++vi.mock('@main/db/client', () => ({+ get db() {+ if (!mocks.db) throw new Error('Test database not initialized');+ return mocks.db;+ },+}));++const MARKER_KEY = 'agentStorageMigrationComplete';++describe('agent storage migration marker', () => {+ let fixture: Awaited<ReturnType<typeof openFixture>>;++ beforeEach(async () => {+ fixture = await openFixture('empty');+ mocks.db = fixture.db;+ });++ afterEach(() => {+ fixture.close();+ mocks.db = undefined;+ });++ it('reports incomplete when no marker has been written', async () => {+ expect(await completedAgentStorageMigrationGeneration()).toBeLessThan(+ AGENT_STORAGE_MIGRATION_GENERATION+ );+ });++ it('reports complete after a clean pass latches it', async () => {+ await markAgentStorageMigrationComplete();+ expect(await completedAgentStorageMigrationGeneration()).toBe(+ AGENT_STORAGE_MIGRATION_GENERATION+ );+ });++ it('reports incomplete for a marker latched by an earlier migration generation', async () => {+ // Generation 1 skipped every provider without a `repoAgents` behavior. An+ // install that latched it must still run the broadened pass, or the change+ // that broadened it does nothing at all for existing users.+ await fixture.db+ .insert(kv)+ .values({ key: MARKER_KEY, value: '1', updatedAt: sql`CURRENT_TIMESTAMP` });++ expect(await completedAgentStorageMigrationGeneration()).toBeLessThan(+ AGENT_STORAGE_MIGRATION_GENERATION+ );+ });++ it('upgrades a stale marker in place rather than inserting a second row', async () => {+ await fixture.db+ .insert(kv)+ .values({ key: MARKER_KEY, value: '1', updatedAt: sql`CURRENT_TIMESTAMP` });++ await markAgentStorageMigrationComplete();++ expect(await completedAgentStorageMigrationGeneration()).toBe(+ AGENT_STORAGE_MIGRATION_GENERATION+ );+ expect(await fixture.db.select().from(kv).where(eq(kv.key, MARKER_KEY))).toHaveLength(1);+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.tsindex 40593d1e1..534f8f6ec 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/agent-storage-migration-marker.ts@@ -3,21 +3,43 @@ import { db } from '@main/db/client';import { kv } from '@main/db/schema';/**- * Persisted marker recording that the CHOO-1440 agent-storage migration has- * completed a full, error-free pass. Once set, {@link migrateAgentStorage}- * short-circuits at boot instead of re-opening every agent's workspace- * filesystem (an SSH/SFTP round trip per remote agent) on every launch.+ * Persisted marker recording which generation of the CHOO-1440 agent-storage+ * migration has completed a full, error-free pass. Once current,+ * {@link migrateAgentStorage} short-circuits at boot instead of re-opening every+ * agent's workspace filesystem (an SSH/SFTP round trip per remote agent, and a+ * 20s connect timeout per unreachable host) on every launch.*/const MARKER_KEY = 'agentStorageMigrationComplete';-export async function isAgentStorageMigrationComplete(): Promise<boolean> {+/**+ * Generations of the migration:+ *+ * - `1` — the original pass. Providers without a `repoAgents` behavior returned+ * "complete" without being looked at, so only Claude agents were migrated.+ * - `2` — the credential collapse runs for every provider.+ *+ * Bump this whenever the migration learns to fix something it previously+ * skipped, so installs that latched an earlier generation run the new pass+ * exactly once instead of short-circuiting on a marker that no longer means what+ * it says. Then teach `migrateAgentStorage` which agents the new generation can+ * actually change, so the re-run does not re-open workspaces it cannot fix.+ */+export const AGENT_STORAGE_MIGRATION_GENERATION = 2;++/** The generation last completed on this install; 0 when it has never run. */+export async function completedAgentStorageMigrationGeneration(): Promise<number> {const [row] = await db.select().from(kv).where(eq(kv.key, MARKER_KEY)).limit(1);- return row?.value === '1';+ const generation = Number.parseInt(row?.value ?? '', 10);+ return Number.isFinite(generation) ? generation : 0;}export async function markAgentStorageMigrationComplete(): Promise<void> {+ const value = String(AGENT_STORAGE_MIGRATION_GENERATION);await db.insert(kv)- .values({ key: MARKER_KEY, value: '1', updatedAt: sql`CURRENT_TIMESTAMP` })- .onConflictDoUpdate({ target: kv.key, set: { value: '1', updatedAt: sql`CURRENT_TIMESTAMP` } });+ .values({ key: MARKER_KEY, value, updatedAt: sql`CURRENT_TIMESTAMP` })+ .onConflictDoUpdate({+ target: kv.key,+ set: { value, updatedAt: sql`CURRENT_TIMESTAMP` },+ });}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.test.tsnew file mode 100644index 000000000..42327a65d--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.test.ts@@ -0,0 +1,36 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { log } from '@main/lib/logger';+import { knownAgentTypeForProvider } from './known-agent-type';++vi.mock('@main/lib/logger', () => ({+ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));++describe('knownAgentTypeForProvider', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('maps codex to its own gateway known-agent type', () => {+ expect(knownAgentTypeForProvider('codex')).toBe('codex');+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('maps claude to claude-code', () => {+ expect(knownAgentTypeForProvider('claude')).toBe('claude-code');+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('warns when a provider has no gateway known-agent type, then falls back visibly', () => {+ // Only claude-code and codex exist server-side, so anything else registers+ // as a type it is not. That is a disclosed fallback, never a silent one.+ for (const id of ['grok', 'gemini', 'cursor', 'droid'] as const) {+ vi.clearAllMocks();+ expect(knownAgentTypeForProvider(id)).toBe('claude-code');+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('no gateway known-agent type'),+ expect.objectContaining({ providerId: id, registeringAs: 'claude-code' })+ );+ }+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.ts b/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.tsnew file mode 100644index 000000000..7d531479f--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/known-agent-type.ts@@ -0,0 +1,37 @@+import { log } from '@main/lib/logger';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++/**+ * A gateway known-agent type. The union is closed to the keys of `KNOWN_AGENTS`+ * in `switch_core/gateway/known_agents.py` — a value outside it is rejected at+ * registration, so it is worth catching at the call site instead.+ */+export type KnownAgentType = 'claude-code' | 'codex';++const KNOWN_AGENT_TYPE_BY_PROVIDER: Partial<Record<AgentProviderId, KnownAgentType>> = {+ claude: 'claude-code',+ codex: 'codex',+};++const FALLBACK_KNOWN_AGENT_TYPE: KnownAgentType = 'claude-code';++/**+ * Map a switchdash provider to the gateway known-agent type it registers as.+ *+ * A provider outside the two server-side types has no faithful representation.+ * It still registers as `claude-code` — the generic switchdash-managed shape —+ * because switchdash drives the session itself and the type mainly determines+ * the connector label and the hand-onboarding command an operator is shown. That+ * mismatch is real (an operator onboarding a Gemini agent by hand is told to run+ * `claude`), so it is warned about rather than passed over silently.+ */+export function knownAgentTypeForProvider(providerId: AgentProviderId): KnownAgentType {+ const known = KNOWN_AGENT_TYPE_BY_PROVIDER[providerId];+ if (known) return known;++ log.warn(+ 'knownAgentTypeForProvider: provider has no gateway known-agent type; registering as the generic switchdash-managed shape',+ { providerId, registeringAs: FALLBACK_KNOWN_AGENT_TYPE }+ );+ return FALLBACK_KNOWN_AGENT_TYPE;+}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.tsindex 9b907f356..09e35036f 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.test.ts@@ -41,52 +41,52 @@ function credsJson(agentId: string): string {// Shared mock state + spies. Hoisted so the vi.mock factories (which are lifted// above imports) can reference them. `agents`/`workspace` are set per test.+// `repoAgents` is the behavior `getPlugin` returns — set it to null in a test to+// simulate a provider without repo-agent definitions (e.g. Codex).const h = vi.hoisted(() => {- const state: { agents: Array<Record<string, unknown>>; workspace: PluginFs | null } = {+ const readLaunchEnv = vi.fn(async (fs: PluginFs, name: string) => {+ const raw =+ (await fs.read(`.switch/agents/${name}.json`)) ??+ (await fs.read(`.claude/switch-subagents/${name}.settings.json`));+ return raw ? ((JSON.parse(raw).env ?? {}) as Record<string, string>) : {};+ });+ const readDefinition = vi.fn((fs: PluginFs, name: string) =>+ fs.read(`.claude/agents/${name}.md`).then((c) => (c === null ? null : { name }))+ );+ const writeDefinition = vi.fn((fs: PluginFs, attrs: { name: string }) =>+ fs.write(`.claude/agents/${attrs.name}.md`, `# ${attrs.name}`)+ );+ const discoverLocal = vi.fn(async () => []);+ const defaultRepoAgents = {+ readLaunchEnv,+ readDefinition,+ writeDefinition,+ discoverLocal,+ };+ const state: {+ agents: Array<Record<string, unknown>>;+ workspace: PluginFs | null;+ repoAgents: object | null;+ } = {agents: [],workspace: null,+ repoAgents: defaultRepoAgents,};return {state,- writeCredentials: vi.fn((fs: PluginFs, creds: { agentName: string }) =>- fs.write(- `.switch/agents/${creds.agentName}.json`,- JSON.stringify({- env: { SWITCH_API_ENDPOINT: 'x', SWITCH_API_TOKEN: 'x', SWITCH_AGENT_ID: 'x' },- })- )- ),- readLaunchEnv: vi.fn(async (fs: PluginFs, name: string) => {- const raw =- (await fs.read(`.switch/agents/${name}.json`)) ??- (await fs.read(`.claude/switch-subagents/${name}.settings.json`));- return raw ? ((JSON.parse(raw).env ?? {}) as Record<string, string>) : {};- }),- readDefinition: vi.fn((fs: PluginFs, name: string) =>- fs.read(`.claude/agents/${name}.md`).then((c) => (c === null ? null : { name }))- ),- writeDefinition: vi.fn((fs: PluginFs, attrs: { name: string }) =>- fs.write(`.claude/agents/${attrs.name}.md`, `# ${attrs.name}`)- ),- discoverLocal: vi.fn(async () => []),+ defaultRepoAgents,+ readLaunchEnv,+ readDefinition,+ writeDefinition,+ discoverLocal,updateAgent: vi.fn(async () => undefined),- isComplete: vi.fn(async () => false),+ completedGeneration: vi.fn(async () => 0),markComplete: vi.fn(async () => undefined),};});vi.mock('@main/core/providers/plugin-registry', () => ({- getPlugin: () => ({- behavior: {- repoAgents: {- writeCredentials: h.writeCredentials,- readLaunchEnv: h.readLaunchEnv,- readDefinition: h.readDefinition,- writeDefinition: h.writeDefinition,- discoverLocal: h.discoverLocal,- },- },- }),+ getPlugin: () => ({ behavior: { repoAgents: h.state.repoAgents } }),}));vi.mock('@main/core/locations/store', () => ({getLocationById: vi.fn(async () => ({ id: 'loc', sshHost: null, dir: '/repo' })),@@ -104,7 +104,8 @@ vi.mock('@main/core/switch-servers/gateway-client', () => ({ fetchAgentDetail: vvi.mock('@main/core/switch-servers/servers-store', () => ({ getServer: vi.fn() }));vi.mock('@main/lib/logger', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));vi.mock('./agent-storage-migration-marker', () => ({- isAgentStorageMigrationComplete: h.isComplete,+ AGENT_STORAGE_MIGRATION_GENERATION: 2,+ completedAgentStorageMigrationGeneration: h.completedGeneration,markAgentStorageMigrationComplete: h.markComplete,}));@@ -124,6 +125,7 @@ describe('migrateAgentStorage', () => {beforeEach(() => {vi.clearAllMocks();h.state.agents = [{ ...baseAgent }];+ h.state.repoAgents = h.defaultRepoAgents;});it('recovers creds from a stale id-keyed neutral file, writes the name-keyed file, and removes the stale one', async () => {@@ -135,12 +137,33 @@ describe('migrateAgentStorage', () => {await migrateAgentStorage();- expect(h.writeCredentials).toHaveBeenCalledWith(- ws,- expect.objectContaining({ agentName: 'cc-hoot-main', apiToken: 'tok-123', agentId: 'sw-1' })- );expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(true);+ const written = JSON.parse((await ws.read('.switch/agents/cc-hoot-main.json')) as string);+ expect(written.env.SWITCH_API_TOKEN).toBe('tok-123');+ expect(written.env.SWITCH_AGENT_ID).toBe('sw-1');+ expect(await ws.exists('.switch/agents/agent-id-1.json')).toBe(false);+ });++ it('migrates a provider without repo-agents (Codex): id-keyed creds → name-keyed, id file removed, no definition written', async () => {+ // Codex has no repoAgents behavior; the pre-rework scheme keyed its neutral+ // creds file by agent id. The migration must still collapse it onto the+ // name-keyed key-space, or the agent silently loses its (unrecoverable) token.+ h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];+ h.state.repoAgents = null;+ const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });+ h.state.workspace = ws;++ await migrateAgentStorage();++ // Name-keyed file written via the unconditional neutral writer (not the+ // behavior hook, which does not exist for Codex), token preserved.+ expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(true);+ const written = JSON.parse((await ws.read('.switch/agents/codex-hoot.json')) as string);+ expect(written.env.SWITCH_API_TOKEN).toBe('tok-123');+ expect(written.env.SWITCH_AGENT_ID).toBe('sw-1');+ // Stale id-keyed file removed; no definition written (no behavior).expect(await ws.exists('.switch/agents/agent-id-1.json')).toBe(false);+ expect(h.writeDefinition).not.toHaveBeenCalled();});it('falls back to .claude/settings.local.json when no neutral file exists', async () => {@@ -152,23 +175,27 @@ describe('migrateAgentStorage', () => {await migrateAgentStorage();- expect(h.writeCredentials).toHaveBeenCalledWith(- ws,- expect.objectContaining({ agentName: 'cc-hoot-main', agentId: 'sw-1' })- );+ const written = JSON.parse((await ws.read('.switch/agents/cc-hoot-main.json')) as string);+ expect(written.env.SWITCH_AGENT_ID).toBe('sw-1');});it('does nothing when the name-keyed file already exists and the definition is present', async () => {- h.state.workspace = fakeFs({+ // Observe the files themselves, not spies: the credential step goes through+ // the real `writeNeutralAgentSettingsFs`, so a spy on the behavior hook+ // cannot see it re-derive and rewrite the token on every boot.+ const seed = {'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),'.claude/agents/cc-hoot-main.md': '# def',- });+ };+ const ws = fakeFs({ ...seed });+ h.state.workspace = ws;await migrateAgentStorage();- expect(h.writeCredentials).not.toHaveBeenCalled();+ for (const [path, content] of Object.entries(seed)) {+ expect(await ws.read(path)).toBe(content);+ }expect(h.writeDefinition).not.toHaveBeenCalled();- expect(h.updateAgent).not.toHaveBeenCalled();});it('writes no credentials when none exist anywhere (unrecoverable token)', async () => {@@ -177,21 +204,44 @@ describe('migrateAgentStorage', () => {await migrateAgentStorage();- expect(h.writeCredentials).not.toHaveBeenCalled();expect(await ws.exists('.switch/agents/cc-hoot-main.json')).toBe(false);});- it('skips the whole pass (no workspace opened) once the marker is set', async () => {- h.isComplete.mockResolvedValueOnce(true);+ it('skips the whole pass (no workspace opened) once the current generation is latched', async () => {+ h.completedGeneration.mockResolvedValueOnce(2);const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;await migrateAgentStorage();expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();- expect(h.writeCredentials).not.toHaveBeenCalled();expect(h.markComplete).not.toHaveBeenCalled();});+ it('re-running for generation 2 opens no workspace for a provider generation 1 already did', async () => {+ // Generation 2 only broadened the credential step to providers WITHOUT a+ // behavior, so re-opening a Claude agent's workspace — an SSH connect and an+ // SFTP channel for a remote one — could not change anything.+ h.completedGeneration.mockResolvedValueOnce(1);+ const resolveWorkspaceFsFor = (await import('./agent-workspace-fs')).resolveWorkspaceFsFor;++ await migrateAgentStorage();++ expect(resolveWorkspaceFsFor).not.toHaveBeenCalled();+ expect(h.markComplete).toHaveBeenCalledTimes(1);+ });++ it('re-running for generation 2 still migrates a provider generation 1 skipped', async () => {+ h.completedGeneration.mockResolvedValueOnce(1);+ h.state.agents = [{ ...baseAgent, providerId: 'codex', name: 'codex-hoot' }];+ h.state.repoAgents = null;+ const ws = fakeFs({ '.switch/agents/agent-id-1.json': credsJson('sw-1') });+ h.state.workspace = ws;++ await migrateAgentStorage();++ expect(await ws.exists('.switch/agents/codex-hoot.json')).toBe(true);+ });+it('latches the marker after a clean pass', async () => {h.state.workspace = fakeFs({'.switch/agents/cc-hoot-main.json': credsJson('sw-1'),diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.tsindex 7d2c588c2..0f580d454 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/migrate-agent-storage.ts@@ -4,12 +4,14 @@ import { parseSwitchAgentCredentials } from '@main/core/switch-rooms/switch-credimport { log } from '@main/lib/logger';import type { Agent } from '@shared/core/agents/agents';import {- isAgentStorageMigrationComplete,+ AGENT_STORAGE_MIGRATION_GENERATION,+ completedAgentStorageMigrationGeneration,markAgentStorageMigrationComplete,} from './agent-storage-migration-marker';import { resolveWorkspaceFsFor } from './agent-workspace-fs';import { getAgents } from './getAgents';import { agentSettingsRelativePath, SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import { writeNeutralAgentSettingsFs } from './write-switch-settings';/*** Migrate existing switchdash-managed agents to the current storage/definition@@ -29,16 +31,15 @@ export async function migrateAgentStorage(): Promise<void> {// Once a full pass has migrated every agent, never re-run: the steady-state// migration re-opens each agent's workspace filesystem (an SSH/SFTP round trip// per remote agent) on every boot for no benefit.- if (await isAgentStorageMigrationComplete()) return;+ const completed = await completedAgentStorageMigrationGeneration();+ if (completed >= AGENT_STORAGE_MIGRATION_GENERATION) return;const agents = await getAgents();let migrated = 0;let allComplete = true;for (const agent of agents) {try {- const result = await migrateOne(agent);- if (result.changed) migrated += 1;- if (!result.complete) allComplete = false;+ if (await migrateOne(agent, completed)) migrated += 1;} catch (error) {allComplete = false;log.warn('migrateAgentStorage: failed to migrate agent', {@@ -56,20 +57,29 @@ export async function migrateAgentStorage(): Promise<void> {if (allComplete) await markAgentStorageMigrationComplete();}-interface MigrateResult {- /** Whether this pass wrote anything for the agent. */- changed: boolean;- /** Whether the agent is now fully in the new layout (nothing left to retry). */- complete: boolean;-}--/** Migrate one agent (local or remote). */-async function migrateOne(agent: Agent): Promise<MigrateResult> {+/**+ * Migrate one agent (local or remote). Returns whether anything was written.+ *+ * `completedGeneration` is the generation this install already finished, so a+ * re-run can skip agents the new generation cannot change — the check happens+ * before the workspace filesystem is opened, which for a remote agent is an SSH+ * connect and an SFTP channel.+ */+async function migrateOne(agent: Agent, completedGeneration: number): Promise<boolean> {+ // A provider may have no repo-agent behavior (e.g. Codex): it has no on-disk+ // definition and no `readLaunchEnv` hook, but its provider-neutral credentials+ // still need collapsing onto the one name-keyed key-space. So the credential+ // migration runs for every provider; only the definition step (2) is+ // behavior-gated.const behavior = getPlugin(agent.providerId).behavior.repoAgents;- if (!behavior) return { changed: false, complete: true };++ // Generation 2 only broadened step 1 to providers WITHOUT a behavior; for one+ // that has it, every step is what generation 1 already ran. Skipping here is+ // what keeps the generation bump from re-opening a workspace per Claude agent.+ if (completedGeneration >= 1 && behavior) return false;const location = await getLocationById(agent.locationId);- if (!location) return { changed: false, complete: true };+ if (!location) return false;const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);try {@@ -84,9 +94,11 @@ async function migrateOne(agent: Agent): Promise<MigrateResult> {// 1. Credentials: if the name-keyed neutral file is absent, adopt whatever// complete credentials already exist on disk, in priority order:// a. a stale ID-keyed neutral file `.switch/agents/<agentId>.json` — an- // earlier layout keyed the neutral file by agent id, not name;+ // earlier layout keyed the neutral file by agent id, not name (this+ // includes Codex agents added on the pre-rework id-keyed scheme);// b. the legacy per-agent file (via readLaunchEnv: name-keyed neutral- // then `.claude/switch-subagents/<name>.settings.json`);+ // then `.claude/switch-subagents/<name>.settings.json`) — behavior+ // providers only;// c. the shared `.claude/settings.local.json` (legacy "main" agent).// The token is minted once and lives only on disk, so this is the only way// to recover it — nothing can reconstruct it from the gateway.@@ -95,15 +107,12 @@ async function migrateOne(agent: Agent): Promise<MigrateResult> {const neutral = name === agent.id ? null : await workspace.fs.read(namedRelPath);if (neutral === null) {const creds =- parseSwitchAgentCredentials((await workspace.fs.read(idKeyedRelPath)) ?? '', log) ??- toCreds(await behavior.readLaunchEnv(workspace.fs, name)) ??- parseSwitchAgentCredentials(- (await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH)) ?? '',- log- );+ parseSwitchAgentCredentials(await workspace.fs.read(idKeyedRelPath), log) ??+ (behavior ? toCreds(await behavior.readLaunchEnv(workspace.fs, name)) : null) ??+ parseSwitchAgentCredentials(await workspace.fs.read(SWITCH_SETTINGS_RELATIVE_PATH), log);if (creds) {- await behavior.writeCredentials(workspace.fs, {- agentName: name,+ await writeNeutralAgentSettingsFs(workspace.fs, {+ slug: name,apiEndpoint: creds.apiEndpoint,apiToken: creds.token,agentId: creds.agentId,@@ -123,13 +132,14 @@ async function migrateOne(agent: Agent): Promise<MigrateResult> {}// 2. Definition: ensure the provider has an on-disk definition for this agent- // so it runs as a named repository-defined agent.- if ((await behavior.readDefinition(workspace.fs, name)) === null) {+ // so it runs as a named repository-defined agent. Behavior providers only —+ // a provider without definitions (Codex) has nothing to write here.+ if (behavior && (await behavior.readDefinition(workspace.fs, name)) === null) {await behavior.writeDefinition(workspace.fs, { name, description });changed = true;}- return { changed, complete: true };+ return changed;} finally {workspace.close();}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.tsindex bccf9fb69..87c6103eb 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-agent.ts@@ -141,17 +141,18 @@ export async function onboardAgent(params: OnboardAgentParams): Promise<OnboardA});// Mirror the agent's credentials into its provider-neutral per-agent file- // (`.switch/agents/<agentId>.json`), the authoritative identity switchdash- // injects at launch so agents sharing a location don't collide on the single- // `.claude/settings.local.json` identity (CHOO-1440). Local agents only — a- // remote agent's dir lives on its VM. Best-effort: the launch/poller fall back- // to `settings.local.json`, so a failure here does not break onboarding.+ // (`.switch/agents/<name>.json`), the authoritative identity switchdash injects+ // at launch so agents sharing a location don't collide on the single+ // `.claude/settings.local.json` identity (CHOO-1440). Keyed by `name` — the one+ // key-space every reader uses. Local agents only — a remote agent's dir lives on+ // its VM. Best-effort: the launch/poller fall back to `settings.local.json`, so+ // a failure here does not break onboarding.if (sshHost === null) {const creds = await readSwitchAgentCredentials(params.dir, log);if (creds) {await writeAgentNeutralSettings({dir: params.dir,- slug: agent.id,+ slug: agent.name,apiEndpoint: creds.apiEndpoint,apiToken: creds.token,agentId: creds.agentId,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.tsindex 7e97cdc62..5c0919719 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/onboard-location-agents.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { err, ok } from '@switchdash/shared';import type { Result } from '@switchdash/shared';+import { knownAgentTypeForProvider } from '@main/core/agents/known-agent-type';import { locationManager } from '@main/core/locations/location-manager';import { checkIsValidDirectory } from '@main/core/locations/path-utils';import { ensureLocation } from '@main/core/locations/store';@@ -19,6 +20,7 @@ import { createAgent } from './createAgent';import { getAgents } from './getAgents';import { registerAgentIdentity } from './register-agent-identity';import { reconcileAgentAutoSessionFromGateway } from './setAgentAutoSession';+import { writeNeutralAgentSettingsFs } from './write-switch-settings';export type OnboardLocationParams = {sshHost: string | null;@@ -39,8 +41,6 @@ export type OnboardLocationResult = Result<Agent[], OnboardAgentError>;/** The Switch identity an onboarded definition should run under. */type ResolvedIdentity = { switchAgentId: string; apiEndpoint: string };-type RepoAgentsBehavior = NonNullable<ReturnType<typeof getPlugin>['behavior']['repoAgents']>;-/** Map a recoverable registration failure to an onboard error. */function registrationError(kind: 'unauthenticated' | 'name-conflict' | 'invalid-name' | 'error',@@ -76,7 +76,6 @@ async function resolveIdentity(description: string | null,ctx: {server: SwitchServer;- behavior: RepoAgentsBehavior;workspace: WorkspaceFs;credsByName: Map<string, { switchAgentId: string | null; apiEndpoint: string | null }>;dir: string;@@ -114,6 +113,9 @@ async function resolveIdentity(description: description ?? `Claude Code agent ${name}`,repoDir: ctx.dir,autoSession: true,+ // This path onboards `.claude/agents/*.md` definitions, so the identity is a+ // Claude Code one by construction.+ agentType: knownAgentTypeForProvider('claude'),});if (registered.kind !== 'created') {const message = 'message' in registered ? registered.message : '';@@ -123,8 +125,8 @@ async function resolveIdentity(};}- await ctx.behavior.writeCredentials(ctx.workspace.fs, {- agentName: name,+ await writeNeutralAgentSettingsFs(ctx.workspace.fs, {+ slug: name,apiEndpoint: ctx.server.apiUrl,apiToken: registered.apiKey,agentId: registered.id,@@ -209,7 +211,6 @@ export async function onboardLocationAgents(for (const def of selected) {const resolved = await resolveIdentity(def.name, def.description, {server,- behavior,workspace,credsByName,dir: params.dir,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.ts b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.tsindex 3fe2df075..31ae7c8a9 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/propagate-server-api-url.ts@@ -16,11 +16,6 @@ import { updateAgent } from './updateAgent';import { mapAgentRowToAgent } from './utils';import { mergeSwitchApiEndpoint } from './write-switch-settings';-// Remote hosts are POSIX; use a forward-slash literal rather than the-// platform-dependent SWITCH_SETTINGS_RELATIVE_PATH (which emits backslashes when-// switchdash runs on Windows). Matches write-remote-switch-settings.ts.-const REMOTE_SETTINGS_PATH = '.claude/settings.local.json';-/*** Rewrite one local agent's `SWITCH_API_ENDPOINT`, preserving its token and* every other key. Returns whether the file was updated (false = not a@@ -59,7 +54,7 @@ async function propagateRemote(try {let existingRaw: string | null = null;try {- ({ content: existingRaw } = await fs.read(REMOTE_SETTINGS_PATH));+ ({ content: existingRaw } = await fs.read(SWITCH_SETTINGS_RELATIVE_PATH));} catch (error) {// Absent file -> unprovisioned agent. A transport failure (dead SSH// connection) must propagate rather than look like "no config".@@ -70,7 +65,7 @@ async function propagateRemote(const merged = mergeSwitchApiEndpoint(existingRaw, apiEndpoint);if (merged === null) return false;- const result = await fs.write(REMOTE_SETTINGS_PATH, merged);+ const result = await fs.write(SWITCH_SETTINGS_RELATIVE_PATH, merged);if (!result.success) {throw new Error(`failed to write remote Switch settings: ${result.error ?? 'unknown error'}`);}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.ts b/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.tsindex e90d8c896..147f1e03d 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/register-agent-identity.ts@@ -1,3 +1,4 @@+import type { KnownAgentType } from '@main/core/agents/known-agent-type';import { GatewayError, registerKnownAgent } from '@main/core/switch-servers/gateway-client';import type { ProvisionAgentResult } from '@shared/core/switch-servers/switch-servers';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';@@ -7,6 +8,10 @@ export type RegisterAgentInput = {description: string;repoDir: string;autoSession?: boolean;+ /** Gateway known-agent type; derive from the provider via+ * `knownAgentTypeForProvider`. Required — an omitted type would silently+ * register the agent as Claude Code whatever it actually runs (CHOO-1436). */+ agentType: KnownAgentType;};/**@@ -34,6 +39,7 @@ export async function registerAgentIdentity(const registered = await registerKnownAgent(server, {name: input.name,description: input.description,+ agentType: input.agentType,options: {channels_enabled: true,repo_dir: input.repoDir,diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.tsindex 233aa9409..a88931bcb 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/remove-switch-settings.ts@@ -1,13 +1,8 @@import type { PluginFs } from '@switchdash/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';+import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';import { removeSwitchSettings } from './write-switch-settings';-// Rooted at the agent's working dir and used against both local and remote-// (SFTP) PluginFs, so use a forward-slash literal rather than the-// platform-dependent SWITCH_SETTINGS_RELATIVE_PATH (which emits backslashes on-// Windows and would not resolve on a POSIX host).-const SWITCH_SETTINGS_POSIX_PATH = '.claude/settings.local.json';-/*** Reverse the default `.claude/settings.local.json` provisioning: strip the* `SWITCH_*` env block and connector allow-rules, deleting the file if it was@@ -16,14 +11,14 @@ const SWITCH_SETTINGS_POSIX_PATH = '.claude/settings.local.json';* directory and a remote SSH host.*/async function removeDefaultSwitchCredentials(fs: PluginFs): Promise<void> {- const existing = await fs.read(SWITCH_SETTINGS_POSIX_PATH);+ const existing = await fs.read(SWITCH_SETTINGS_RELATIVE_PATH);const result = removeSwitchSettings(existing);if (result.kind === 'skip') return;if (result.kind === 'delete') {- await fs.delete(SWITCH_SETTINGS_POSIX_PATH);+ await fs.delete(SWITCH_SETTINGS_RELATIVE_PATH);return;}- await fs.write(SWITCH_SETTINGS_POSIX_PATH, result.content);+ await fs.write(SWITCH_SETTINGS_RELATIVE_PATH, result.content);}/**diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.test.tsnew file mode 100644index 000000000..a5e3b09f0--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';+import {+ agentSettingsRelativePath,+ SWITCH_AGENTS_DIR_RELATIVE,+ SWITCH_AGENTS_GITIGNORE_RELATIVE,+ SWITCH_SETTINGS_RELATIVE_PATH,+ SWITCH_SUBAGENTS_DIR_RELATIVE,+} from './switch-settings-paths';++// These relative paths are handed to a `PluginFs` that may be a remote POSIX+// host over SFTP, so they must never carry a Windows separator. `path.join`+// would, when switchdash itself runs on Windows.+describe('relative Switch settings paths', () => {+ const relatives = {+ SWITCH_SETTINGS_RELATIVE_PATH,+ SWITCH_SUBAGENTS_DIR_RELATIVE,+ SWITCH_AGENTS_DIR_RELATIVE,+ SWITCH_AGENTS_GITIGNORE_RELATIVE,+ 'agentSettingsRelativePath()': agentSettingsRelativePath('some-agent'),+ };++ for (const [name, value] of Object.entries(relatives)) {+ it(`${name} uses forward slashes only`, () => {+ expect(value).not.toContain('\\');+ });+ }++ it('resolves to the documented POSIX layout', () => {+ expect(SWITCH_SETTINGS_RELATIVE_PATH).toBe('.claude/settings.local.json');+ expect(SWITCH_SUBAGENTS_DIR_RELATIVE).toBe('.claude/switch-subagents');+ expect(SWITCH_AGENTS_DIR_RELATIVE).toBe('.switch/agents');+ expect(SWITCH_AGENTS_GITIGNORE_RELATIVE).toBe('.switch/agents/.gitignore');+ expect(agentSettingsRelativePath('cc-hoot-main')).toBe('.switch/agents/cc-hoot-main.json');+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.tsindex 034d70f99..8f8ef197b 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/switch-settings-paths.ts@@ -5,6 +5,12 @@ import path from 'node:path';* leaf module (only `node:path`) so the credentials reader — and through it the* remote sidecar bundle — can use them without pulling in the Electron-bound* agent-detection module.+ *+ * Every *relative* path here is a forward-slash literal, never `path.join`: these+ * are handed to a `PluginFs`, which is either the local disk or a remote POSIX+ * host over SFTP, and `path.join` emits backslashes when switchdash runs on+ * Windows. The *absolute* helpers below still use `path.join`, which normalises a+ * forward-slash tail correctly on every platform.*//**@@ -12,7 +18,7 @@ import path from 'node:path';* file that the switch-connector `configure` skill writes the `SWITCH_*` env* block into for a per-location agent.*/-export const SWITCH_SETTINGS_RELATIVE_PATH = path.join('.claude', 'settings.local.json');+export const SWITCH_SETTINGS_RELATIVE_PATH = '.claude/settings.local.json';/*** Directory, relative to an agent's working directory, where the switch-connector@@ -20,7 +26,7 @@ export const SWITCH_SETTINGS_RELATIVE_PATH = path.join('.claude', 'settings.loca* (`<subagent_name>.settings.json`). switchdash discovers a parent agent's* launchable Claude Code subagents by scanning this directory.*/-export const SWITCH_SUBAGENTS_DIR_RELATIVE = path.join('.claude', 'switch-subagents');+export const SWITCH_SUBAGENTS_DIR_RELATIVE = '.claude/switch-subagents';/** Absolute path to a subagent's Switch credentials file under `dir`. */export function subagentSettingsPath(dir: string, agentName: string): string {@@ -36,14 +42,14 @@ export function subagentSettingsPath(dir: string, agentName: string): string {* (CHOO-1440). The `.claude/agents/<name>.md` *definition* stays under `.claude`* because it is Claude-specific; only the Switch credentials move here.*/-export const SWITCH_AGENTS_DIR_RELATIVE = path.join('.switch', 'agents');+export const SWITCH_AGENTS_DIR_RELATIVE = '.switch/agents';/*** Relative path to the `.gitignore` that keeps the per-agent credentials files* (which contain `SWITCH_API_TOKEN`) out of version control. Its content is `*`* so the whole directory is ignored.*/-export const SWITCH_AGENTS_GITIGNORE_RELATIVE = path.join(SWITCH_AGENTS_DIR_RELATIVE, '.gitignore');+export const SWITCH_AGENTS_GITIGNORE_RELATIVE = `${SWITCH_AGENTS_DIR_RELATIVE}/.gitignore`;/*** Relative path (from a location dir) to an agent's provider-neutral Switch@@ -51,7 +57,7 @@ export const SWITCH_AGENTS_GITIGNORE_RELATIVE = path.join(SWITCH_AGENTS_DIR_RELA* definition name for a subagent-derived agent, or its stable name otherwise.*/export function agentSettingsRelativePath(slug: string): string {- return path.join(SWITCH_AGENTS_DIR_RELATIVE, `${slug}.json`);+ return `${SWITCH_AGENTS_DIR_RELATIVE}/${slug}.json`;}/** Absolute path to an agent's provider-neutral Switch credentials file under `dir`. */diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.tsindex 9dfdadc0d..60a07b3d9 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-remote-switch-settings.ts@@ -3,13 +3,10 @@ import {FileSystemErrorCodes,type FileSystemProvider,} from '@main/core/fs/types';+import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';import { mergeSwitchSettings, type SwitchSettingsCredentials } from './write-switch-settings';-// Remote hosts are POSIX; use forward-slash literals rather than the-// platform-dependent path.join constant (which would emit backslashes when-// switchdash runs on Windows).const REMOTE_SETTINGS_DIR = '.claude';-const REMOTE_SETTINGS_PATH = '.claude/settings.local.json';/*** Write the agent's `SWITCH_*` credentials into the remote working directory's@@ -29,7 +26,7 @@ export async function writeRemoteSwitchSettings(): Promise<void> {let existingRaw: string | null = null;try {- const result = await fs.read(REMOTE_SETTINGS_PATH);+ const result = await fs.read(SWITCH_SETTINGS_RELATIVE_PATH);existingRaw = result.content;} catch (error) {// Start fresh only when the file is genuinely absent. A transport failure@@ -42,7 +39,7 @@ export async function writeRemoteSwitchSettings(const merged = mergeSwitchSettings(existingRaw, creds);await fs.mkdir(REMOTE_SETTINGS_DIR, { recursive: true });- const result = await fs.write(REMOTE_SETTINGS_PATH, merged);+ const result = await fs.write(SWITCH_SETTINGS_RELATIVE_PATH, merged);if (!result.success) {throw new Error(`failed to write remote Switch settings: ${result.error ?? 'unknown error'}`);}diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.tsindex 1bc199834..c1d2441a5 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.test.ts@@ -2,12 +2,19 @@ import { promises as fs } from 'node:fs';import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createPluginFs } from '@main/core/providers/plugin-fs';import { detectSwitchAgent } from './detect';-import { SWITCH_SETTINGS_RELATIVE_PATH } from './switch-settings-paths';+import {+ agentSettingsRelativePath,+ SWITCH_AGENTS_GITIGNORE_RELATIVE,+ SWITCH_SETTINGS_RELATIVE_PATH,+} from './switch-settings-paths';import {mergeSwitchApiEndpoint,mergeSwitchSettings,removeSwitchSettings,+ writeAgentNeutralSettings,+ writeNeutralAgentSettingsFs,writeSwitchSettings,} from './write-switch-settings';@@ -92,6 +99,111 @@ describe('writeSwitchSettings', () => {});});+describe('writeNeutralAgentSettingsFs', () => {+ it('writes the provider-neutral per-agent creds keyed by slug, with a gitignore', async () => {+ await writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'switch-agent-1',+ });++ const raw = await fs.readFile(path.join(dir, agentSettingsRelativePath('agent-abc')), 'utf8');+ const settings = JSON.parse(raw) as Record<string, unknown>;+ expect(settings.env).toEqual({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'switch-agent-1',+ });++ // The credentials directory is git-ignored so the token never enters VCS.+ const ignore = await fs.readFile(path.join(dir, SWITCH_AGENTS_GITIGNORE_RELATIVE), 'utf8');+ expect(ignore).toBe('*\n');+ });++ it('merges into an existing per-agent file, preserving unrelated env keys and allow rules', async () => {+ const relPath = agentSettingsRelativePath('agent-abc');+ await fs.mkdir(path.dirname(path.join(dir, relPath)), { recursive: true });+ await fs.writeFile(+ path.join(dir, relPath),+ JSON.stringify({+ permissions: { allow: ['Bash'] },+ env: { EXISTING: 'keep', SWITCH_API_TOKEN: 'old' },+ }),+ 'utf8'+ );++ await writeNeutralAgentSettingsFs(createPluginFs(dir), {+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'new-token',+ agentId: 'switch-agent-1',+ });++ const settings = JSON.parse(await fs.readFile(path.join(dir, relPath), 'utf8')) as Record<+ string,+ unknown+ >;+ expect(settings.env).toEqual({+ EXISTING: 'keep',+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'new-token',+ SWITCH_AGENT_ID: 'switch-agent-1',+ });+ // The connector's MCP tools are auto-approved on top of whatever the agent+ // already allowed, so a Switch agent never has to ask to reach its room.+ expect(settings.permissions).toEqual({+ allow: [+ 'Bash',+ 'mcp__plugin_switch-connector_switch',+ 'mcp__plugin_switch-connector_switch-channel',+ ],+ });+ });++ it('writes the gitignore before the token file, so a crash never leaves a tracked token', async () => {+ const writes: string[] = [];+ const recordingFs = createPluginFs(dir);+ const write = recordingFs.write.bind(recordingFs);+ recordingFs.write = async (p, c) => {+ writes.push(p);+ return write(p, c);+ };++ await writeNeutralAgentSettingsFs(recordingFs, {+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'switch-agent-1',+ });++ expect(writes).toEqual([+ SWITCH_AGENTS_GITIGNORE_RELATIVE,+ agentSettingsRelativePath('agent-abc'),+ ]);+ });+});++describe('writeAgentNeutralSettings', () => {+ it('produces the same file as the PluginFs writer, for a plain directory path', async () => {+ await writeAgentNeutralSettings({+ dir,+ slug: 'agent-abc',+ apiEndpoint: 'https://switch.example.com',+ apiToken: 'secret-token',+ agentId: 'switch-agent-1',+ });++ const raw = await fs.readFile(path.join(dir, agentSettingsRelativePath('agent-abc')), 'utf8');+ expect((JSON.parse(raw) as { env: Record<string, string> }).env).toEqual({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'secret-token',+ SWITCH_AGENT_ID: 'switch-agent-1',+ });+ expect(await fs.readFile(path.join(dir, SWITCH_AGENTS_GITIGNORE_RELATIVE), 'utf8')).toBe('*\n');+ });+});+describe('mergeSwitchApiEndpoint', () => {it('rewrites only SWITCH_API_ENDPOINT, preserving token, id, and other keys', () => {const existing = JSON.stringify({diff --git a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.tsindex 96f6c0379..090e85968 100644--- a/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts+++ b/dash/apps/switchdash-desktop/src/main/core/agents/write-switch-settings.ts@@ -1,6 +1,8 @@import { promises as fs } from 'node:fs';import path from 'node:path';import { SWITCH_CONNECTOR_TOOL_RULES } from '@switchdash/core/agents/plugins';+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { createPluginFs } from '@main/core/providers/plugin-fs';import {agentSettingsRelativePath,SWITCH_AGENTS_GITIGNORE_RELATIVE,@@ -257,30 +259,31 @@ export async function writeSwitchSettings(params: {* the renderer or logged. A `.gitignore` keeps the directory out of version* control.*/-export async function writeAgentNeutralSettings(params: {- dir: string;- slug: string;- apiEndpoint: string;- apiToken: string;- agentId: string;-}): Promise<void> {- const settingsPath = path.join(params.dir, agentSettingsRelativePath(params.slug));- const gitignorePath = path.join(params.dir, SWITCH_AGENTS_GITIGNORE_RELATIVE);-- let existingRaw: string | null = null;- try {- existingRaw = await fs.readFile(settingsPath, 'utf8');- } catch (error) {- const code = (error as NodeJS.ErrnoException).code;- if (code !== 'ENOENT' && code !== 'ENOTDIR') throw error;- }+export async function writeAgentNeutralSettings(+ params: { dir: string; slug: string } & SwitchSettingsCredentials+): Promise<void> {+ await writeNeutralAgentSettingsFs(createPluginFs(params.dir), params);+}- const merged = mergeSwitchSettings(existingRaw, params);- await fs.mkdir(path.dirname(settingsPath), { recursive: true });- await fs.writeFile(settingsPath, merged, 'utf8');- try {- await fs.access(gitignorePath);- } catch {- await fs.writeFile(gitignorePath, '*\n', 'utf8');+/**+ * Write an agent's provider-neutral per-agent Switch credentials over a+ * {@link PluginFs} (local disk or a remote repo dir via SFTP), keyed by `slug`+ * (the agent name) — the authoritative identity switchdash injects at launch+ * (`agentSettingsPath`). This is the single per-agent credential writer for every+ * provider and every transport; providers with repo-agent definitions (Claude)+ * layer their definition on top.+ *+ * The `.gitignore` is written first: it is what keeps `SWITCH_API_TOKEN` out of+ * version control, so it must already be in place before the token reaches disk.+ */+export async function writeNeutralAgentSettingsFs(+ workspaceFs: PluginFs,+ params: { slug: string } & SwitchSettingsCredentials+): Promise<void> {+ if (!(await workspaceFs.exists(SWITCH_AGENTS_GITIGNORE_RELATIVE))) {+ await workspaceFs.write(SWITCH_AGENTS_GITIGNORE_RELATIVE, '*\n');}+ const relPath = agentSettingsRelativePath(params.slug);+ const merged = mergeSwitchSettings(await workspaceFs.read(relPath), params);+ await workspaceFs.write(relPath, merged);}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.tsindex a283a567f..f22016c71 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,4 +1,4 @@-import { getAgentById } from '@main/core/agents/getAgentById';+import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';import {agentSettingsRelativePath,SWITCH_SETTINGS_RELATIVE_PATH,@@ -110,15 +110,14 @@ export async function buildSessionFromRuntime();// The remote preflight verifies the session's own creds file, keyed by the- // agent's NAME (`.switch/agents/<name>.json`). Resolve it from the agent row —- // the source of truth — falling back to the session's denormalised agentName.- // The agent-id path and the legacy shared `.claude/settings.local.json` are- // last-resort fallbacks for agents not yet migrated (CHOO-1440).- const agent = await getAgentById(session.agentId);- const slug = agent?.name ?? session.agentName;+ // agent's NAME (`.switch/agents/<name>.json`). The agent-id path and the legacy+ // shared `.claude/settings.local.json` are last-resort fallbacks for agents not+ // yet migrated (CHOO-1440).const credsRelPaths = [- ...(slug ? [agentSettingsRelativePath(slug)] : []),- agentSettingsRelativePath(session.agentId),+ ...new Set([+ agentSettingsRelativePath(agentCredsSlug(session)),+ agentSettingsRelativePath(session.agentId),+ ]),SWITCH_SETTINGS_RELATIVE_PATH,];diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.test.tsnew file mode 100644index 000000000..69f98eab4--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest';+import { resolveSessionControl, type SessionControlContext } from './session-control';++const ESC = '\x1b';++const ctx: SessionControlContext = {+ room: 'hub',+ role: 'reviewer',+ threadId: 'msg-1',+ user: 'ada',+};++describe('resolveSessionControl', () => {+ it('reports no support for a provider switchdash cannot drive', () => {+ const control = resolveSessionControl('gemini');+ expect(control.capabilities).toEqual({ reset: false, compact: false, interrupt: false });+ expect(control.plan('interrupt', ctx)).toBeNull();+ });++ it.each(['claude', 'codex'])('supports all three commands for %s', (providerId) => {+ expect(resolveSessionControl(providerId).capabilities).toEqual({+ reset: true,+ compact: true,+ interrupt: true,+ });+ });++ it.each(['claude', 'codex'])('interrupts %s with a bare ESC and no submit', (providerId) => {+ // Ctrl+C would exit the CLI rather than the turn, so the recipe must stay+ // ESC-only — and `raw` so no Enter is appended.+ expect(resolveSessionControl(providerId).plan('interrupt', ctx)).toEqual([+ { kind: 'raw', data: ESC },+ ]);+ });++ it.each(['claude', 'codex'])('returns null for an unknown command on %s', (providerId) => {+ expect(resolveSessionControl(providerId).plan('explode', ctx)).toBeNull();+ });++ it.each(['claude', 'codex'])(+ 'reconnects and re-assumes the role after %s reset',+ (providerId) => {+ const steps = resolveSessionControl(providerId).plan('reset', ctx);+ expect(steps).not.toBeNull();++ // `/clear` drops the context, so the follow-up must put the agent back in+ // the room, back in its role, and tell the asker in their thread.+ const announce = steps!.at(-1);+ expect(announce).toMatchObject({ kind: 'prompt' });+ const text = (announce as { text: string }).text;+ expect(text).toContain('connect to switch room "hub"');+ expect(text).toContain('assume the role reviewer');+ expect(text).toContain('send a targeted message to ada');+ expect(text).toContain('as a threaded reply to message msg-1');+ expect(text).toContain('session has been reset');+ }+ );++ // Codex gates both slash commands behind `available_during_task()` and drops+ // them outright mid-turn, so each has to interrupt first — otherwise the+ // command is discarded and the follow-up announces work that never happened.+ it.each([+ ['reset', '/clear'],+ ['compact', '/compact'],+ ])('interrupts before %s on codex, which drops slash commands mid-turn', (command, slash) => {+ expect(resolveSessionControl('codex').plan(command, ctx)?.slice(0, 2)).toEqual([+ { kind: 'raw', data: ESC },+ { kind: 'prompt', text: slash },+ ]);+ });++ // Claude queues a slash command typed mid-turn, so it needs no interrupt.+ it('compacts claude with /compact and no preceding interrupt', () => {+ expect(resolveSessionControl('claude').plan('compact', ctx)?.[0]).toEqual({+ kind: 'prompt',+ text: '/compact',+ });+ });++ it.each(['claude', 'codex'])('announces the compaction back to the room on %s', (providerId) => {+ const steps = resolveSessionControl(providerId).plan('compact', ctx);+ expect(steps).not.toBeNull();+ expect((steps!.at(-1) as { text: string }).text).toContain('context has been compacted');+ });++ it('omits the role and thread clauses when there is neither', () => {+ const steps = resolveSessionControl('codex').plan('reset', {+ room: 'hub',+ role: null,+ threadId: null,+ user: null,+ });+ const text = (steps!.at(-1) as { text: string }).text;+ expect(text).not.toContain('assume the role');+ expect(text).not.toContain('threaded reply');+ expect(text).toContain('post a short message');+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.tsindex f417f10bb..140593a8e 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/session-control.ts@@ -96,6 +96,42 @@ const CLAUDE_CONTROL: SessionControl = {},};+/**+ * Codex: also a TUI. ESC interrupts the current turn (Ctrl+C would exit the+ * session instead), `/clear` starts a fresh chat, `/compact` summarises the+ * transcript.+ *+ * Both slash commands are gated behind Codex's `available_during_task()`, which+ * rejects them outright while a turn is running — the command is dropped with an+ * error cell, not queued. The follow-up step would still run and announce work+ * that never happened, so each is preceded by an interrupt. Kept as its own+ * object rather than aliasing CLAUDE_CONTROL: the two CLIs are free to diverge,+ * and a shared reference would make a Claude-only change silently apply here.+ */+const CODEX_CONTROL: SessionControl = {+ capabilities: { reset: true, compact: true, interrupt: true },+ plan(command, ctx) {+ switch (command) {+ case 'interrupt':+ return [{ kind: 'raw', data: ESC }];+ case 'compact':+ return [+ { kind: 'raw', data: ESC },+ { kind: 'prompt', text: '/compact' },+ { kind: 'prompt', text: reconnectAndAnnounce(ctx, 'context has been compacted') },+ ];+ case 'reset':+ return [+ { kind: 'raw', data: ESC },+ { kind: 'prompt', text: '/clear' },+ { kind: 'prompt', text: reconnectAndAnnounce(ctx, 'session has been reset') },+ ];+ default:+ return null;+ }+ },+};+const NO_CONTROL: SessionControl = {capabilities: { reset: false, compact: false, interrupt: false },plan: () => null,@@ -103,6 +139,7 @@ const NO_CONTROL: SessionControl = {const BY_PROVIDER: Record<string, SessionControl> = {claude: CLAUDE_CONTROL,+ codex: CODEX_CONTROL,};/** Resolve the session-control support + recipes for a provider. */diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.test.tsnew file mode 100644index 000000000..1628abaa6--- /dev/null+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.test.ts@@ -0,0 +1,95 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { agentSettingsRelativePath } from '@main/core/agents/switch-settings-paths';+import { parseSwitchAgentCredentials, readAgentSwitchEnvFromFs } from './switch-credentials';++const log = { warn: vi.fn() };++function credsJson(overrides: Record<string, unknown> = {}): string {+ return JSON.stringify({+ env: {+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ ...overrides,+ },+ });+}++function memoryFs(files: Record<string, string> = {}): PluginFs {+ const store = new Map(Object.entries(files));+ return {+ read: async (p) => store.get(p) ?? null,+ write: async (p, c) => void store.set(p, c),+ delete: async (p) => void store.delete(p),+ exists: async (p) => store.has(p),+ list: async () => [...store.keys()],+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('parseSwitchAgentCredentials', () => {+ it('parses a complete env block', () => {+ expect(parseSwitchAgentCredentials(credsJson(), log)).toEqual({+ apiEndpoint: 'https://switch.example.com',+ token: 'tok-123',+ agentId: 'sw-1',+ });+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('treats an absent file as "not provisioned here", without warning', () => {+ // The migration probes several candidate paths per agent; a missing one is+ // the ordinary answer, not a malformed file.+ expect(parseSwitchAgentCredentials(null, log)).toBeNull();+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('warns and returns null for text it cannot parse', () => {+ expect(parseSwitchAgentCredentials('{', log)).toBeNull();+ expect(log.warn).toHaveBeenCalledTimes(1);+ });++ it('returns null without warning when a value is missing or blank', () => {+ expect(parseSwitchAgentCredentials(credsJson({ SWITCH_API_TOKEN: ' ' }), log)).toBeNull();+ expect(parseSwitchAgentCredentials(JSON.stringify({}), log)).toBeNull();+ expect(log.warn).not.toHaveBeenCalled();+ });+});++describe('readAgentSwitchEnvFromFs', () => {+ it('reads the slug-keyed neutral file and returns it as launch env', async () => {+ const fs = memoryFs({ [agentSettingsRelativePath('codex-hoot')]: credsJson() });++ expect(await readAgentSwitchEnvFromFs(fs, 'codex-hoot', log)).toEqual({+ SWITCH_API_ENDPOINT: 'https://switch.example.com',+ SWITCH_API_TOKEN: 'tok-123',+ SWITCH_AGENT_ID: 'sw-1',+ });+ expect(log.warn).not.toHaveBeenCalled();+ });++ it('warns when the agent has no neutral file, rather than launching quietly unidentified', async () => {+ // Only Claude recovers from an empty env (it reads settings.local.json+ // natively); every other provider silently authenticates as nobody, so the+ // miss has to be visible in the log.+ expect(await readAgentSwitchEnvFromFs(memoryFs(), 'codex-hoot', log)).toEqual({});+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('no Switch identity'),+ expect.objectContaining({ slug: 'codex-hoot', path: '.switch/agents/codex-hoot.json' })+ );+ });++ it('warns when the file exists but its credential block is incomplete', async () => {+ const fs = memoryFs({ [agentSettingsRelativePath('codex-hoot')]: JSON.stringify({ env: {} }) });++ expect(await readAgentSwitchEnvFromFs(fs, 'codex-hoot', log)).toEqual({});+ expect(log.warn).toHaveBeenCalledWith(+ expect.stringContaining('no Switch identity'),+ expect.objectContaining({ slug: 'codex-hoot' })+ );+ });+});diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.tsindex fd44a05f9..91af7d29e 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-rooms/switch-credentials.ts@@ -1,6 +1,10 @@import { promises as fs } from 'node:fs';import path from 'node:path';-import { SWITCH_SETTINGS_RELATIVE_PATH } from '@main/core/agents/switch-settings-paths';+import type { PluginFs } from '@switchdash/core/agents/plugins';+import {+ agentSettingsRelativePath,+ SWITCH_SETTINGS_RELATIVE_PATH,+} from '@main/core/agents/switch-settings-paths';export interface SwitchAgentCredentials {agentId: string;@@ -64,35 +68,69 @@ export async function readSwitchAgentCredentialsFromSettings(return parseSwitchAgentCredentials(raw, log);}+/** The `SWITCH_*` env vars a launched session needs to act as the agent. */+function credentialsAsEnv(creds: SwitchAgentCredentials | null): Record<string, string> {+ if (!creds) return {};+ return {+ SWITCH_API_ENDPOINT: creds.apiEndpoint,+ SWITCH_API_TOKEN: creds.token,+ SWITCH_AGENT_ID: creds.agentId,+ };+}+/*** Read an agent's Switch credentials from a settings file and return them as the* `SWITCH_*` env vars a launched session needs, or `{}` when the file is* missing/incomplete. Used to inject an agent's identity at launch from its- * provider-neutral `.switch/agents/<id>.json` (CHOO-1440).+ * provider-neutral `.switch/agents/<name>.json` (CHOO-1440).*/export async function readAgentSwitchEnv(settingsPath: string,log: CredentialsLogger): Promise<Record<string, string>> {- const creds = await readSwitchAgentCredentialsFromSettings(settingsPath, log);- if (!creds) return {};- return {- SWITCH_API_ENDPOINT: creds.apiEndpoint,- SWITCH_API_TOKEN: creds.token,- SWITCH_AGENT_ID: creds.agentId,- };+ return credentialsAsEnv(await readSwitchAgentCredentialsFromSettings(settingsPath, log));}/**- * Parse Switch agent credentials from the raw text of a `.claude/settings.local.json`.- * Transport-agnostic (no filesystem): used by both the local readers above and- * the remote preflight, which fetches the file over SFTP. Returns null when the- * text is unparseable or any of the three values is absent.+ * The {@link readAgentSwitchEnv} equivalent over a {@link PluginFs} rooted at the+ * agent's working directory, so the local and remote (SFTP) launch paths inject+ * the same identity from the same `.switch/agents/<slug>.json`.+ *+ * An empty result is a degraded launch, not a neutral one: the session starts+ * without a Switch identity, and only Claude recovers by reading+ * `.claude/settings.local.json` natively. Every other provider silently is not+ * the agent, so the miss is warned about here rather than at each call site.+ */+export async function readAgentSwitchEnvFromFs(+ workspaceFs: PluginFs,+ slug: string,+ log: CredentialsLogger+): Promise<Record<string, string>> {+ const relPath = agentSettingsRelativePath(slug);+ const env = credentialsAsEnv(parseSwitchAgentCredentials(await workspaceFs.read(relPath), log));+ if (Object.keys(env).length === 0) {+ log.warn(+ 'readAgentSwitchEnvFromFs: no Switch identity for agent; session will not authenticate as it',+ { slug, path: relPath }+ );+ }+ return env;+}++/**+ * Parse Switch agent credentials from the raw text of a settings file, or `null`+ * for an absent one. Transport-agnostic (no filesystem): used by both the local+ * readers above and the remote preflight, which fetches the file over SFTP.+ * Returns null when the file is absent, the text is unparseable, or any of the+ * three values is missing — but only warns for text it could not parse, since an+ * absent file is an ordinary "this agent isn't provisioned here" answer.*/export function parseSwitchAgentCredentials(- raw: string,+ raw: string | null,log: CredentialsLogger): SwitchAgentCredentials | null {+ if (raw === null) return null;+let env: ClaudeSettingsEnv | undefined;try {env = (JSON.parse(raw) as { env?: ClaudeSettingsEnv })?.env;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.tsindex c5537f018..655b2c2d2 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts@@ -1,5 +1,6 @@import type { Result } from '@switchdash/shared';import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';+import { knownAgentTypeForProvider } from '@main/core/agents/known-agent-type';import { propagateServerApiUrl } from '@main/core/agents/propagate-server-api-url';import { registerAgentIdentity } from '@main/core/agents/register-agent-identity';import { resolveAgentServers } from '@main/core/agents/resolve-servers';@@ -14,6 +15,7 @@ import {} from '@main/core/managed-switch-server/managed-server-status';import { HostUnreachableError } from '@main/core/remote-hosts/host-reachability-service';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import type {AddressingPolicy,AddServerParams,@@ -278,16 +280,17 @@ export const switchServersController = createRPCController({}},- suggestAgentDefaults: async (params: { dir: string }): Promise<AgentDefaults> =>- suggestAgentDefaults(params.dir),+ suggestAgentDefaults: async (params: {+ dir: string;+ providerId: AgentProviderId;+ }): Promise<AgentDefaults> => suggestAgentDefaults(params.dir, params.providerId),/**- * Register a new Claude Code agent on the chosen server (owned by the- * signed-in user) and write its credentials into the directory's- * `.claude/settings.local.json`. This is the desktop equivalent of running- * the switch-connector `configure` skill. Recoverable gateway failures are- * mapped to a typed result; the minted token is written to disk and never- * returned.+ * Register a new agent on the chosen server (owned by the signed-in user) and+ * write its credentials into the directory's `.claude/settings.local.json`.+ * This is the desktop equivalent of running the switch-connector `configure`+ * skill. Recoverable gateway failures are mapped to a typed result; the minted+ * token is written to disk and never returned.*/provisionAgent: async (params: ProvisionAgentParams): Promise<ProvisionAgentResult> => {const server = await requireServer(params.serverId);@@ -297,6 +300,9 @@ export const switchServersController = createRPCController({description: params.description,repoDir: params.dir,autoSession: params.autoSession,+ // Provisioning writes `.claude/settings.local.json` — this is the Claude+ // Code path by construction, not a fallback.+ agentType: knownAgentTypeForProvider('claude'),});if (registered.kind !== 'created') return registered;@@ -328,6 +334,8 @@ export const switchServersController = createRPCController({description: params.description,repoDir: params.remoteRepoDir,autoSession: params.autoSession,+ // Remote provisioning likewise writes `.claude/settings.local.json`.+ agentType: knownAgentTypeForProvider('claude'),});if (registered.kind !== 'created') return registered;diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.tsindex 103e27857..eb76f1c19 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts@@ -7,7 +7,7 @@ const reauthenticateManagedServer = vi.hoisted(() => vi.fn());vi.mock('./servers-store', () => ({ getSessionCookie }));vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));-const { createRoom, fetchBridges, fetchMe } = await import('./gateway-client');+const { createRoom, fetchBridges, fetchMe, registerKnownAgent } = await import('./gateway-client');const SERVER = {id: 'srv-1',@@ -222,6 +222,50 @@ function bodyOf(call: unknown[]): Record<string, unknown> {return JSON.parse(init.body) as Record<string, unknown>;}+describe('registerKnownAgent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ getSessionCookie.mockResolvedValue(makeJwt(24 * 60 * 60));+ fetchMock.mockImplementation(+ async () =>+ ({+ status: 200,+ ok: true,+ json: async () => ({ id: 'sw-1', api_key: 'tok-123' }),+ headers: { getSetCookie: () => [] },+ text: async () => '',+ }) as unknown as Response+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('sends the caller-supplied agent_type rather than a hardcoded default', async () => {+ // The type governs the connector label and the hand-onboarding command the+ // gateway shows, so a default here would silently mislabel every non-Claude+ // agent (CHOO-1436).+ const registered = await registerKnownAgent(SERVER, {+ name: 'codex-hoot',+ description: 'Codex running in repo',+ agentType: 'codex',+ options: { channels_enabled: true, repo_dir: '/repo' },+ });++ expect(registered).toEqual({ id: 'sw-1', apiKey: 'tok-123' });+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, { body: string }];+ expect(JSON.parse(init.body)).toEqual({+ agent_type: 'codex',+ name: 'codex-hoot',+ description: 'Codex running in repo',+ options: { channels_enabled: true, repo_dir: '/repo' },+ overwrite: false,+ });+ });+});+describe('room creation', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.tsindex 78bee5e5f..a1855b789 100644--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts@@ -1,3 +1,4 @@+import type { KnownAgentType } from '@main/core/agents/known-agent-type';import type {AddressingPolicy,RemoteAgentRoom,@@ -215,7 +216,9 @@ export async function fetchMe(server: SwitchServer): Promise<SwitchUser> {}/** Options for `registerKnownAgent`, matching the gateway's- * `RegisterKnownAgentRequest.options` for the `claude-code` known-agent type. */+ * `RegisterKnownAgentRequest.options`. The gateway validates these against the+ * options schema of the `agent_type` being registered and ignores keys that type+ * does not declare (Codex has no channel, so it drops `channels_enabled`). */export type RegisterKnownAgentOptions = {channels_enabled: boolean;repo_dir?: string;@@ -234,20 +237,28 @@ export type RegisteredAgent = {};/**- * Register a new Claude Code agent on `server`, owned by the signed-in user- * (session-authed `POST /gateway/agents/register`). Returns the new agent id+ * Register a new known agent of `agentType` on `server`, owned by the signed-in+ * user (session-authed `POST /gateway/agents/register`). Returns the new agent id* and its API key. A 409 (name already taken) and 400 (invalid name) surface* as `GatewayError` with the matching `status` so the caller can react.*/export async function registerKnownAgent(server: SwitchServer,- params: { name: string; description: string; options: RegisterKnownAgentOptions }+ params: {+ name: string;+ description: string;+ options: RegisterKnownAgentOptions;+ /** Gateway known-agent type. Required — derive it from the provider via+ * `knownAgentTypeForProvider` rather than letting a call site fall back to+ * Claude Code's shape by omission (CHOO-1436). */+ agentType: KnownAgentType;+ }): Promise<RegisteredAgent> {const res = await gatewayFetch(server, '/agents/register', {authenticated: true,method: 'POST',body: {- agent_type: 'claude-code',+ agent_type: params.agentType,name: params.name,description: params.description,options: params.options,diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 8be0de954..3d74d4de3 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -76,7 +76,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst showAddServerModal = useShowModal('addServerModal');const pickState = usePickMode();- const configureForm = useConfigureAgentForm(pickState.path, false);+ const configureForm = useConfigureAgentForm(pickState.path, false, pickState.providerId);// Run location: 'local' (default) or an onboarded remote host's SSH alias. A// remote agent runs its sessions on the host and needs a remote working dir.@@ -90,7 +90,11 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocconst [remoteRepoDirDraft, setRemoteRepoDirDraft] = useState('');// Configure form for onboarding a brand-new agent in the remote dir. Defaults// (name/description) are derived from the remote dir just like a local agent.- const remoteConfigureForm = useConfigureAgentForm(remoteRepoDir.trim(), true);+ const remoteConfigureForm = useConfigureAgentForm(+ remoteRepoDir.trim(),+ true,+ pickState.providerId+ );const { data: remoteHosts } = useQuery({queryKey: ['remote-hosts'],queryFn: () => rpc.remoteHosts.listHosts(),diff --git a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsindex bdaa04744..4e552c26d 100644--- a/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts+++ b/dash/apps/switchdash-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts@@ -54,7 +54,11 @@ export type PickModeState = ReturnType<typeof usePickMode>;* the agent as a managed, session-addressable identity — there is no run-mode or* notify-handle choice (CHOO-1440).*/-export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean) {+export function useConfigureAgentForm(+ dir: string,+ defaultAutoApprove: boolean,+ providerId: AgentProviderId | null+) {const [agentName, setAgentNameRaw] = useState('');const [agentNameTouched, setAgentNameTouched] = useState(false);const [description, setDescriptionRaw] = useState('');@@ -70,9 +74,12 @@ export function useConfigureAgentForm(dir: string, defaultAutoApprove: boolean)// the local user — pure, no filesystem read — so it works identically for a// local path or a remote working dir, giving remote agents the same defaults.const defaultsQuery = useQuery({- queryKey: ['agentDefaults', trimmedDir],- queryFn: () => rpc.switchServers.suggestAgentDefaults({ dir: trimmedDir }),- enabled: trimmedDir.length > 0,+ queryKey: ['agentDefaults', trimmedDir, providerId],+ queryFn: () => {+ if (providerId === null) throw new Error('providerId is required for agent defaults');+ return rpc.switchServers.suggestAgentDefaults({ dir: trimmedDir, providerId });+ },+ enabled: trimmedDir.length > 0 && providerId !== null,});const defaults = defaultsQuery.data;diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/browser/home-drag-region.test.tsx b/dash/apps/switchdash-desktop/src/renderer/tests/browser/home-drag-region.test.tsxindex 9e60a977a..1b9c0f3c2 100644--- a/dash/apps/switchdash-desktop/src/renderer/tests/browser/home-drag-region.test.tsx+++ b/dash/apps/switchdash-desktop/src/renderer/tests/browser/home-drag-region.test.tsx@@ -1,8 +1,8 @@import { act } from 'react';import { createRoot } from 'react-dom/client';-import { afterEach, beforeAll, describe, expect, it } from 'vitest';-import type * as HomeView from '@renderer/app/home-view';-import type * as ThemeProvider from '@renderer/lib/providers/theme-provider';+import { afterEach, describe, expect, it } from 'vitest';+import { HomeMainPanel } from '@renderer/app/home-view';+import { ThemeContext } from '@renderer/lib/providers/theme-provider';/*** The home view is the one screen that registers no `TitlebarSlot`, so it has@@ -13,29 +13,13 @@ import type * as ThemeProvider from '@renderer/lib/providers/theme-provider';* Electron is the only place a drag region actually does anything, so these* assertions are on the markup rather than on behaviour: they exist to catch a* restyle or refactor silently dropping the utility classes again.+ *+ * The imports above must stay static; `setup-electron-bridge.ts` exists so they+ * can be, and explains what importing this module at runtime does to React.*/-let ThemeContext: typeof ThemeProvider.ThemeContext;-let HomeMainPanel: typeof HomeView.HomeMainPanel;let container: HTMLDivElement | null = null;-beforeAll(async () => {- // `lib/ipc` reads the preload bridge at module scope and the home view pulls- // it in transitively, so the bridge has to exist before the import runs.- Object.defineProperty(window, 'electronAPI', {- configurable: true,- value: {- invoke: async () => undefined,- eventSend: () => {},- eventOn: () => () => {},- },- });- ({ HomeMainPanel } = await import('@renderer/app/home-view'));- // The real ThemeProvider resolves the theme over RPC; the panel only reads- // `effectiveTheme` to pick logo colours, so feed the context directly.- ({ ThemeContext } = await import('@renderer/lib/providers/theme-provider'));-});-async function renderHome(): Promise<HTMLDivElement> {container = document.createElement('div');document.body.appendChild(container);diff --git a/dash/apps/switchdash-desktop/src/renderer/tests/browser/setup-electron-bridge.ts b/dash/apps/switchdash-desktop/src/renderer/tests/browser/setup-electron-bridge.tsnew file mode 100644index 000000000..456a4eacd--- /dev/null+++ b/dash/apps/switchdash-desktop/src/renderer/tests/browser/setup-electron-bridge.ts@@ -0,0 +1,24 @@+/**+ * Installs the preload bridge before any browser test module is evaluated.+ *+ * `renderer/lib/ipc.ts` reads `window.electronAPI.invoke` at module scope, so+ * importing renderer code without a bridge throws on the import itself. Supplying+ * it here, rather than from a test's `beforeAll`, is what allows those imports to+ * stay static.+ *+ * They have to. A runtime `await import()` of app code is the first thing to pull+ * in the renderer's dependency tree, so Vite re-optimizes deps in the middle of+ * the run; modules loaded either side of that boundary resolve through different+ * `?v=` hashes and React is instantiated twice. react-dom then renders with one+ * copy while the component reads hooks from the other, whose dispatcher was never+ * installed — every hook call dies on `Cannot read properties of null`. A warm+ * cache hides it and CI, always cold, does not (CHOO-1430).+ */+Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ invoke: async () => undefined,+ eventSend: () => {},+ eventOn: () => () => {},+ },+});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.tsindex 75d22d0a0..472eacf9b 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@@ -99,7 +99,7 @@ export const AGENT_PROVIDERS: AgentProviderDefinition[] = [id: 'codex',name: 'Codex',description:- 'CLI that connects to OpenAI models for location-aware code assistance and terminal workflows.',+ 'CLI that connects to OpenAI models for project-aware code assistance and terminal workflows.',docUrl: 'https://github.com/openai/codex',installCommand: 'npm install -g @openai/codex',commands: ['codex'],diff --git a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.tsindex a441e8fa1..ffdcc2c41 100644--- a/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts+++ b/dash/apps/switchdash-desktop/src/shared/core/sessions/sessions.ts@@ -48,7 +48,8 @@ export type Session = {archivedAt?: string;lastInteractedAt?: string;autoApprove?: boolean;- /** Set when this session runs as a Claude Code subagent of its agent. */+ /** The session's agent's name, read live from the agent row on every load+ * (so it follows a rename). Absent only for a row that predates named agents. */agentName?: string;createdAt: string;updatedAt: string;diff --git a/dash/apps/switchdash-desktop/vitest.config.ts b/dash/apps/switchdash-desktop/vitest.config.tsindex b3ee12eab..a0cd1e11b 100644--- a/dash/apps/switchdash-desktop/vitest.config.ts+++ b/dash/apps/switchdash-desktop/vitest.config.ts@@ -84,6 +84,18 @@ export default defineConfig({// Renderer terminal tests that need a real browser environment// (real CSS layout, ResizeObserver, requestAnimationFrame, WebGL).extends: true,+ // Crawl the browser tests when deps are first optimized. Without this+ // their imports are only discovered once the page loads them, so Vite+ // re-optimizes and reloads mid-run — which vitest reports as flaky and+ // which, before the tests imported statically, split React in two.+ // A glob rather than a dependency list: a new import is picked up here,+ // an inventory would go stale.+ // `react/jsx-dev-runtime` is named explicitly because the JSX transform+ // injects it rather than any file importing it, so crawling cannot find it.+ optimizeDeps: {+ entries: ['src/renderer/tests/browser/**/*.test.{ts,tsx}'],+ include: ['react/jsx-dev-runtime'],+ },test: {name: 'browser',browser: {@@ -93,6 +105,10 @@ export default defineConfig({instances: [{ browser: 'chromium' }],},include: ['src/renderer/tests/browser/**/*.test.{ts,tsx}'],+ // Supplies the preload bridge before a test module is evaluated, so+ // renderer imports can be static. See the file's docblock for why a+ // dynamic import of app code breaks React here.+ setupFiles: ['./src/renderer/tests/browser/setup-electron-bridge.ts'],},},],diff --git a/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 7e027798e..a6f8bee37 100644--- a/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/dash/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -28,14 +28,6 @@ export type RepoAgentDefinition = {registered: boolean;};-/** Credentials written for an agent so its sessions act under its own identity. */-export type RepoAgentCredentials = {- agentName: string;- apiEndpoint: string;- apiToken: string;- agentId: string;-};-/*** The MCP permission rules that keep a Switch agent connected to the platform:* the connector's two MCP servers. Used both as `tools` allowlist entries (so an@@ -109,8 +101,6 @@ export type IRepoAgentsBehavior = {launchArgs(workingDir: string, agentName: string): string[];/** The named agent's Switch credentials as env vars, for the launched session. */readLaunchEnv(workspaceFs: PluginFs, agentName: string): Promise<Record<string, string>>;- /** Write a named agent's credentials so it is immediately runnable. */- writeCredentials(workspaceFs: PluginFs, credentials: RepoAgentCredentials): Promise<void>;/** The attribute fields this provider supports, in display order. Drives the* create/edit form; the first two are always `name` and `description`. */attributeFields(): RepoAgentField[];diff --git a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts b/dash/packages/core/src/agents/plugins/helpers/standard-command.tsindex 7a7eb012d..820b0fc61 100644--- a/dash/packages/core/src/agents/plugins/helpers/standard-command.ts+++ b/dash/packages/core/src/agents/plugins/helpers/standard-command.ts@@ -101,7 +101,7 @@ export function buildStandardCommand(ctx: CommandContext, spec: StandardCommandS// Use switchdash UUIDargs.push(spec.resumeFlag, ctx.sessionId!);} else if (spec.resumeWithoutSessionFlag) {- args.push(spec.resumeWithoutSessionFlag);+ args.push(...splitFlag(spec.resumeWithoutSessionFlag));} else {args.push(spec.resumeFlag);}diff --git a/dash/packages/core/src/agents/plugins/index.ts b/dash/packages/core/src/agents/plugins/index.tsindex bd4108ee8..2a185ac22 100644--- a/dash/packages/core/src/agents/plugins/index.ts+++ b/dash/packages/core/src/agents/plugins/index.ts@@ -77,7 +77,6 @@ export type {LocalRepoAgent,RepoAgentAttributes,RepoAgentAttributeValue,- RepoAgentCredentials,RepoAgentDefinition,RepoAgentField,RepoAgentFieldOption,diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 8a16fa775..689ecc252 100644--- a/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -31,7 +31,6 @@ function fakeFs(files: Record<string, string>): PluginFs {const settingsRel = (name: string) =>path.join(CLAUDE_SUBAGENTS.dirRelative, `${name}${CLAUDE_SUBAGENTS.settingsSuffix}`);/** Provider-neutral per-agent credentials file (the current write location). */-const neutralRel = (name: string) => path.join('.switch', 'agents', `${name}.json`);const defRel = (name: string) => path.join(CLAUDE_SUBAGENTS.definitionsDirRelative, `${name}.md`);describe('claudeRepoAgentsBehavior.launchArgs', () => {@@ -220,51 +219,3 @@ describe('claudeRepoAgentsBehavior.removeLocal', () => {expect(await workspaceFs.exists(settingsRel('reviewer'))).toBe(false);});});--describe('claudeRepoAgentsBehavior.writeSettings', () => {- it('writes the credentials JSON, permissions.allow, and a gitignore', async () => {- const workspaceFs = fakeFs({});- await claudeRepoAgentsBehavior.writeCredentials(workspaceFs, {- agentName: 'reviewer',- apiEndpoint: 'https://s',- apiToken: 'secret',- agentId: 'a1',- });-- const written = await workspaceFs.read(neutralRel('reviewer'));- expect(JSON.parse(written!)).toEqual({- permissions: {- allow: [- 'mcp__plugin_switch-connector_switch',- 'mcp__plugin_switch-connector_switch-channel',- ],- },- env: { SWITCH_API_ENDPOINT: 'https://s', SWITCH_API_TOKEN: 'secret', SWITCH_AGENT_ID: 'a1' },- });- expect(await workspaceFs.read(path.join('.switch', 'agents', '.gitignore'))).toBe('*\n');- });-- it('preserves existing permissions and env, unioning the Switch rules', async () => {- const workspaceFs = fakeFs({- [neutralRel('reviewer')]: JSON.stringify({- permissions: { allow: ['Bash'] },- env: { KEEP: 'me' },- }),- });- await claudeRepoAgentsBehavior.writeCredentials(workspaceFs, {- agentName: 'reviewer',- apiEndpoint: 'https://s',- apiToken: 'secret',- agentId: 'a1',- });-- const settings = JSON.parse((await workspaceFs.read(neutralRel('reviewer')))!);- expect(settings.permissions.allow).toEqual([- 'Bash',- 'mcp__plugin_switch-connector_switch',- 'mcp__plugin_switch-connector_switch-channel',- ]);- expect(settings.env.KEEP).toBe('me');- expect(settings.env.SWITCH_AGENT_ID).toBe('a1');- });-});diff --git a/dash/packages/plugins/src/agents/impl/claude/subagents.ts b/dash/packages/plugins/src/agents/impl/claude/subagents.tsindex e37e2b8c0..62bafa867 100644--- a/dash/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/dash/packages/plugins/src/agents/impl/claude/subagents.ts@@ -4,7 +4,6 @@ import {type LocalRepoAgent,type PluginFs,type RepoAgentAttributes,- type RepoAgentCredentials,type RepoAgentDefinition,type RepoAgentField,SWITCH_AGENT_SETTINGS_DIR,@@ -460,42 +459,6 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return result;},- async writeCredentials(workspaceFs, credentials: RepoAgentCredentials): Promise<void> {- // Keep the tokens out of git — `*` ignores everything in the directory.- const gitignoreRel = path.join(SWITCH_AGENT_SETTINGS_DIR, '.gitignore');- if (!(await workspaceFs.exists(gitignoreRel))) {- await workspaceFs.write(gitignoreRel, '*\n');- }-- const relPath = neutralSettingsRelPath(credentials.agentName);- const existing = parseSettingsObject(await workspaceFs.read(relPath));- const currentEnv = (existing.env ?? {}) as Record<string, unknown>;- const currentPerms =- existing.permissions && typeof existing.permissions === 'object'- ? (existing.permissions as Record<string, unknown>)- : {};- const currentAllow = Array.isArray(currentPerms.allow)- ? (currentPerms.allow as unknown[]).map(String)- : [];-- const settings = {- ...existing,- // Auto-approve the Switch connector tools so the subagent never has to ask- // ("don't ask"), on top of whatever the file already allowed.- permissions: {- ...currentPerms,- allow: dedupe([...currentAllow, ...SWITCH_CONNECTOR_TOOL_RULES]),- },- env: {- ...currentEnv,- SWITCH_API_ENDPOINT: credentials.apiEndpoint,- SWITCH_API_TOKEN: credentials.apiToken,- SWITCH_AGENT_ID: credentials.agentId,- },- };- await workspaceFs.write(relPath, `${JSON.stringify(settings, null, 2)}\n`);- },-attributeFields(): RepoAgentField[] {return CLAUDE_SUBAGENT_FIELDS;},diff --git a/dash/packages/plugins/src/agents/impl/codex/command.test.ts b/dash/packages/plugins/src/agents/impl/codex/command.test.tsnew file mode 100644index 000000000..2ea0f38e5--- /dev/null+++ b/dash/packages/plugins/src/agents/impl/codex/command.test.ts@@ -0,0 +1,82 @@+import type { CommandContext } from '@switchdash/core/agents/plugins';+import { describe, expect, it } from 'vitest';+import { provider } from './index';++function build(ctx: CommandContext) {+ return provider.behavior.prompt!.buildCommand(ctx);+}++const base: CommandContext = {+ cli: 'codex',+ autoApprove: false,+ isResuming: false,+ sessionId: 'switchdash-session',+ model: '',+};++// The auto-approve flag, split the way buildStandardCommand splits it on+// whitespace.+const AUTO_FLAGS = [+ '-c',+ 'approval_policy="never"',+ '-c',+ 'sandbox_mode="danger-full-access"',+ '--dangerously-bypass-hook-trust',+];++describe('codex buildCommand', () => {+ it('starts a fresh session with auto-approve flags then the positional prompt', () => {+ const cmd = build({ ...base, autoApprove: true, initialPrompt: 'Fix the bug' });++ expect(cmd.command).toBe('codex');+ // sessionIdOnResumeOnly → the switchdash UUID is never injected on a fresh run.+ // Full structural check: auto-approve flags in order, prompt last.+ expect(cmd.args).toEqual([...AUTO_FLAGS, 'Fix the bug']);+ });++ it('omits auto-approve args when autoApprove is false', () => {+ const cmd = build({ ...base, initialPrompt: 'hello' });+ expect(cmd.args).not.toContain('--dangerously-bypass-hook-trust');+ expect(cmd.args).toEqual(['hello']);+ });++ it('resumes with the captured rollout session id', () => {+ const cmd = build({ ...base, isResuming: true, providerSessionId: 'rollout-9' });+ expect(cmd.args[0]).toBe('resume');+ expect(cmd.args[1]).toBe('rollout-9');+ // No positional prompt is added on resume.+ expect(cmd.args).not.toContain('Fix the bug');+ });++ it('orders resume subcommand + id BEFORE the auto-approve flags on resume', () => {+ const cmd = build({+ ...base,+ isResuming: true,+ providerSessionId: 'rollout-9',+ autoApprove: true,+ });+ // Regression guard on arg order: `resume <id>` must precede the -c flags,+ // and no positional prompt is appended on resume.+ expect(cmd.args).toEqual(['resume', 'rollout-9', ...AUTO_FLAGS]);+ });++ it('falls back to `resume --last` as split args when no rollout id was captured', () => {+ const cmd = build({ ...base, isResuming: true });+ // Regression guard: the multi-token fallback must be two argv elements,+ // not a single "resume --last" string.+ expect(cmd.args.slice(0, 2)).toEqual(['resume', '--last']);+ });++ it('deduplicates the bypass-approvals-and-sandbox singleton flag', () => {+ const cmd = build({+ ...base,+ extraArgs: [+ '--dangerously-bypass-approvals-and-sandbox',+ '--dangerously-bypass-approvals-and-sandbox',+ ],+ });+ expect(cmd.args.filter((a) => a === '--dangerously-bypass-approvals-and-sandbox')).toHaveLength(+ 1+ );+ });+});diff --git a/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts b/dash/packages/plugins/src/agents/impl/codex/hooks.test.tsnew file mode 100644index 000000000..d103c0ef0--- /dev/null+++ b/dash/packages/plugins/src/agents/impl/codex/hooks.test.ts@@ -0,0 +1,187 @@+import type { PluginFs } from '@switchdash/core/agents/plugins';+import { describe, expect, it } from 'vitest';+import { CODEX_CONFIG_PATH, CODEX_HOOKS_PATH, buildCodexHookConfig } from './hooks';++function createMemoryFs(initial: Record<string, string> = {}): PluginFs {+ const files = new Map(Object.entries(initial));+ return {+ async read(path) {+ return files.get(path) ?? null;+ },+ async write(path, content) {+ files.set(path, content);+ },+ async delete(path) {+ files.delete(path);+ },+ async exists(path) {+ return files.has(path);+ },+ async list(path) {+ return [...files.keys()].filter((file) => file.startsWith(path));+ },+ };+}++describe('buildCodexHookConfig.parseHookEvent', () => {+ const { parseHookEvent } = buildCodexHookConfig();++ it('captures the rollout session id from session-start', () => {+ expect(parseHookEvent('session-start', { session_id: 'abc123' })).toEqual({+ kind: 'session',+ providerSessionId: 'abc123',+ });+ });++ it('falls back through resource_id / resourceId / sessionId', () => {+ expect(parseHookEvent('session-start', { resource_id: 'r1' })).toEqual({+ kind: 'session',+ providerSessionId: 'r1',+ });+ expect(parseHookEvent('session-start', { resourceId: 'r2' })).toEqual({+ kind: 'session',+ providerSessionId: 'r2',+ });+ expect(parseHookEvent('session-start', { sessionId: 'r3' })).toEqual({+ kind: 'session',+ providerSessionId: 'r3',+ });+ });++ it('trims the id and ignores a blank or missing session id', () => {+ expect(parseHookEvent('session-start', { session_id: ' x ' })).toEqual({+ kind: 'session',+ providerSessionId: 'x',+ });+ expect(parseHookEvent('session-start', { session_id: ' ' })).toEqual({ kind: 'ignore' });+ expect(parseHookEvent('session-start', {})).toEqual({ kind: 'ignore' });+ });++ it('maps an idle_prompt notification to a stop status', () => {+ expect(parseHookEvent('notification', { notification_type: 'idle_prompt' })).toEqual({+ kind: 'status',+ type: 'stop',+ });+ });++ it('maps agent-turn-complete (no notification_type) to a stop status', () => {+ expect(parseHookEvent('notification', { type: 'agent-turn-complete' })).toEqual({+ kind: 'status',+ type: 'stop',+ });+ });++ it('maps a permission_prompt notification to a notification status', () => {+ expect(parseHookEvent('notification', { notification_type: 'permission_prompt' })).toEqual({+ kind: 'status',+ type: 'notification',+ notificationType: 'permission_prompt',+ });+ });++ it('defers unrelated events to the default parser', () => {+ expect(parseHookEvent('stop', {})).toMatchObject({ kind: 'status', type: 'stop' });+ expect(parseHookEvent('totally-unknown', {})).toEqual({ kind: 'ignore' });+ });++ it('handles an empty notification body without a stop/permission misclassification', () => {+ // nt undefined and no `type: agent-turn-complete` → falls to the default+ // parser, which yields a plain notification status (not a spurious stop).+ expect(parseHookEvent('notification', {})).toMatchObject({+ kind: 'status',+ type: 'notification',+ });+ });+});++describe('buildCodexHookConfig install/read/delete', () => {+ it('installs Stop / PermissionRequest / SessionStart hooks and reports the written path', async () => {+ const fs = createMemoryFs();+ const paths = await buildCodexHookConfig().writeHooks(fs, []);++ expect(paths).toEqual([CODEX_HOOKS_PATH]);+ const config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {+ hooks: Record<string, unknown[]>;+ };+ for (const key of ['Stop', 'PermissionRequest', 'SessionStart']) {+ expect(config.hooks[key]).toHaveLength(1);+ expect(JSON.stringify(config.hooks[key][0])).toContain('SWITCHDASH_HOOK_PORT');+ }+ });++ it('reflects installation state through getHooksInstalled + readHooks', async () => {+ const fs = createMemoryFs();+ const cfg = buildCodexHookConfig();++ expect(await cfg.getHooksInstalled(fs)).toBe(false);+ expect(await cfg.readHooks(fs)).toEqual([]);++ await cfg.writeHooks(fs, []);++ expect(await cfg.getHooksInstalled(fs)).toBe(true);+ expect(await cfg.readHooks(fs)).toEqual([+ { event: 'switchdash', command: 'SWITCHDASH_HOOK_PORT' },+ ]);+ });++ it('preserves user hooks and removes only switchdash entries on delete', async () => {+ const userEntry = { hooks: [{ type: 'command', command: 'echo hi' }] };+ const fs = createMemoryFs({+ [CODEX_HOOKS_PATH]: JSON.stringify({ hooks: { Stop: [userEntry] } }),+ });+ const cfg = buildCodexHookConfig();++ await cfg.writeHooks(fs, []);+ let config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as {+ hooks: Record<string, unknown[]>;+ };+ // The user's own Stop hook survives alongside the injected switchdash one.+ expect(config.hooks.Stop).toHaveLength(2);++ await cfg.deleteHooks(fs);+ config = JSON.parse((await fs.read(CODEX_HOOKS_PATH))!) as { hooks: Record<string, unknown[]> };+ expect(config.hooks.Stop).toEqual([userEntry]);+ expect(await cfg.getHooksInstalled(fs)).toBe(false);+ });++ it('migrates away a legacy config.toml notify command on write', async () => {+ const configToml = [+ 'notify = ["powershell.exe", "-NoProfile", "-File", "/tmp/switchdash-codex-notify.ps1"]',+ 'model = "gpt-5"',+ '',+ ].join('\n');+ const fs = createMemoryFs({ [CODEX_CONFIG_PATH]: configToml });++ await buildCodexHookConfig().writeHooks(fs, []);++ const rewritten = (await fs.read(CODEX_CONFIG_PATH))!;+ expect(rewritten).not.toContain('notify');+ // Unrelated config is left intact.+ expect(rewritten).toContain('gpt-5');+ });++ it('refuses to install hooks over an unparseable hooks file', async () => {+ // Rewriting from scratch would silently discard every hook the user has+ // configured, so a file we cannot parse must stop the install.+ const fs = createMemoryFs({ [CODEX_HOOKS_PATH]: '{ not json' });++ await expect(buildCodexHookConfig().writeHooks(fs, [])).rejects.toThrow(/not valid JSON/);+ expect(await fs.read(CODEX_HOOKS_PATH)).toBe('{ not json');+ });++ it('refuses to delete hooks from an unparseable hooks file', async () => {+ const fs = createMemoryFs({ [CODEX_HOOKS_PATH]: '{ not json' });++ await expect(buildCodexHookConfig().deleteHooks(fs)).rejects.toThrow(/not valid JSON/);+ expect(await fs.read(CODEX_HOOKS_PATH)).toBe('{ not json');+ });++ it('propagates a failed hooks-file read instead of rewriting from scratch', async () => {+ const fs = createMemoryFs();+ fs.read = async () => {+ throw new Error('transport failure');+ };++ await expect(buildCodexHookConfig().writeHooks(fs, [])).rejects.toThrow('transport failure');+ });+});diff --git a/dash/packages/plugins/src/agents/impl/codex/hooks.ts b/dash/packages/plugins/src/agents/impl/codex/hooks.tsindex c405012a6..5db78456e 100644--- a/dash/packages/plugins/src/agents/impl/codex/hooks.ts+++ b/dash/packages/plugins/src/agents/impl/codex/hooks.ts@@ -1,19 +1,15 @@import type { PluginFs } from '@switchdash/core/agents/plugins';import type { CanonicalHookEvent, HookRegistration } from '@switchdash/core/agents/plugins';import {- SWITCHDASH_MARKER,- buildNestedEntry,+ buildNestedJsonHookConfig,defaultHookEventParser,- filterUserHooks,makeHookPostCommand,makeNotificationHookCommand,- readJsonConfig,- writeJsonConfig,} from '@switchdash/core/agents/plugins/helpers';import * as toml from 'smol-toml';export const CODEX_HOOKS_PATH = '.codex/hooks.json';-const CODEX_CONFIG_PATH = '.codex/config.toml';+export const CODEX_CONFIG_PATH = '.codex/config.toml';const LEGACY_CODEX_NOTIFY_COMMAND = ['bash',@@ -94,53 +90,18 @@ function parseCodexHookEvent(eventType: string, body: Record<string, unknown>):}export function buildCodexHookConfig() {- const stopCmd = makeNotificationHookCommand('idle_prompt');- const permCmd = makeNotificationHookCommand('permission_prompt');- const sessionCmd = makeCodexSessionStartCommand();+ const base = buildNestedJsonHookConfig(CODEX_HOOKS_PATH, [+ { hookKey: 'Stop', command: makeNotificationHookCommand('idle_prompt') },+ { hookKey: 'PermissionRequest', command: makeNotificationHookCommand('permission_prompt') },+ { hookKey: 'SessionStart', command: makeCodexSessionStartCommand() },+ ]);return {- async readHooks(fs: PluginFs): Promise<HookRegistration[]> {- const config = await readJsonConfig(fs, CODEX_HOOKS_PATH);- const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;- const installed = ['Stop', 'PermissionRequest', 'SessionStart'].some((k) => {- const entries = Array.isArray(hooks[k]) ? hooks[k] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));- });- return installed ? [{ event: 'switchdash', command: SWITCHDASH_MARKER }] : [];- },- async writeHooks(fs: PluginFs, _hooks: HookRegistration[]): Promise<string[]> {- const config = await readJsonConfig(fs, CODEX_HOOKS_PATH);- const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;- for (const [key, cmd] of [- ['Stop', stopCmd],- ['PermissionRequest', permCmd],- ['SessionStart', sessionCmd],- ] as [string, string][]) {- const existing = Array.isArray(hooks[key]) ? hooks[key] : [];- hooks[key] = [- ...filterUserHooks(existing as Record<string, unknown>[]),- buildNestedEntry(cmd),- ];- }- await writeJsonConfig(fs, CODEX_HOOKS_PATH, { ...config, hooks });- await removeLegacyCodexNotify(fs).catch(() => {});- return [CODEX_HOOKS_PATH];- },- async deleteHooks(fs: PluginFs): Promise<void> {- const config = await readJsonConfig(fs, CODEX_HOOKS_PATH);- const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;- for (const key of Object.keys(hooks)) {- hooks[key] = filterUserHooks(hooks[key] as Record<string, unknown>[]);- }- await writeJsonConfig(fs, CODEX_HOOKS_PATH, { ...config, hooks });- },- async getHooksInstalled(fs: PluginFs): Promise<boolean> {- const config = await readJsonConfig(fs, CODEX_HOOKS_PATH);- const hooks = (config.hooks ?? {}) as Record<string, unknown[]>;- return ['Stop', 'PermissionRequest', 'SessionStart'].some((k) => {- const entries = Array.isArray(hooks[k]) ? hooks[k] : [];- return entries.some((e) => JSON.stringify(e).includes(SWITCHDASH_MARKER));- });+ ...base,+ async writeHooks(fs: PluginFs, hooks: HookRegistration[]): Promise<string[]> {+ const paths = await base.writeHooks(fs, hooks);+ await removeLegacyCodexNotify(fs);+ return paths;},parseHookEvent: parseCodexHookEvent,};