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(opencode): give OpenCode agents an advanced configuration (CHOO-2125) (#218)
Christian McDermott196e127678a3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f13e2b72..a0c2fa5e5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -502,6 +502,45 @@ version of their own to them without also giving them a release of their own.### [Unreleased]+#### Added++- **An OpenCode agent can be configured like a Codex one.** Its model,+ reasoning variant, temperature, top-p, step limit, web search and+ instructions can be set when the agent is created and changed afterwards from+ its Settings tab, and a change applies to the next session — or to a running+ one with Restart, which resumes the conversation.++ OpenCode's settings are not Codex's, so the per-agent configuration an agent+ stores is now keyed by what its own provider offers rather than by a fixed+ list. Existing Codex agents keep their settings; nothing needs re-entering.++ Its instructions are added to OpenCode's own, the way an `AGENTS.md` is,+ rather than replacing them.++- **You can pick a model instead of remembering it.** Switch Console asks the+ machine an OpenCode agent runs on which models it offers and lists them as you+ type, grouped by provider and annotated with the reasoning variants each+ accepts. Typing something not on the list still works — it is a shortcut, not+ a restriction.++- **The model and reasoning fields check themselves against the agent's own+ host.** A model name that host does not have is flagged as you type, and+ the reasoning variant becomes a menu of what the chosen model actually+ accepts — greyed out, with a reason, for a model that has none, as local+ models generally do. Both were places OpenCode would otherwise accept a value+ and silently never apply it.++ The check warns rather than blocks, since the list is a snapshot and a model+ can appear a moment later. If the host cannot be reached, or OpenCode is not+ installed on it, the fields say so and go back to plain text rather than+ flagging everything as wrong.++ An OpenCode agent can also be pointed at a **local model** — define the+ provider once in your OpenCode config and set the agent's model to it. The new+ utility-model setting is worth setting too if the point is to keep everything+ on one machine: it is what OpenCode uses for background work like naming a+ conversation, which otherwise goes wherever your own config sends it.+#### Fixed- Two Switch Console installs sharing an agent host no longer trade the sidecarback and forth when they are on the *same* release but carry different buildsdiff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.tsindex 8a49e472b..c2ce1ac55 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts@@ -6,9 +6,12 @@ import { prepareAgentLaunchProfile, resolveAgentLaunchProfile } from './agent-latype Plugin = ReturnType<typeof getPlugin>;-/** The real Codex plugin — the only one that takes specialization from a file. */+/** The real Codex plugin: specialization in a file, loaded with `--profile`. */const codexPlugin = pluginRegistry.get('codex')! as unknown as Plugin;+/** The real OpenCode plugin: specialization in files, loaded from the env. */+const opencodePlugin = pluginRegistry.get('opencode')! as unknown as Plugin;+/** A provider that takes its specialization on argv, as Claude's does. */const claudeLikePlugin = { behavior: { mcp: {} } } as unknown as Plugin;@@ -141,10 +144,13 @@ describe('resolveAgentLaunchProfile', () => {});describe('prepareAgentLaunchProfile', () => {+ const HOME = '/home/agent';+it('writes the profile under ~/.codex and returns the --profile argv', async () => {const fs = memoryFs();- const args = await prepareAgentLaunchProfile(codexPlugin, {+ const { args } = await prepareAgentLaunchProfile(codexPlugin, {homeFs: fs,+ homeDir: HOME,slug: 'codex-hoot',workingDir: WD,specialization: SPECIALIZED,@@ -155,8 +161,9 @@ describe('prepareAgentLaunchProfile', () => {it('writes the system prompt into the profile and no companion file', async () => {const fs = memoryFs();- const args = await prepareAgentLaunchProfile(codexPlugin, {+ const { args } = await prepareAgentLaunchProfile(codexPlugin, {homeFs: fs,+ homeDir: HOME,slug: 'codex-hoot',workingDir: WD,specialization: { instructions: 'be terse' },@@ -168,14 +175,16 @@ describe('prepareAgentLaunchProfile', () => {);});- it('writes nothing and returns [] for an agent that specializes nothing', async () => {+ it('writes nothing for an agent that specializes nothing', async () => {const fs = memoryFs();- const args = await prepareAgentLaunchProfile(codexPlugin, {- homeFs: fs,- slug: 'x',- workingDir: WD,- });- expect(args).toEqual([]);+ expect(+ await prepareAgentLaunchProfile(codexPlugin, {+ homeFs: fs,+ homeDir: HOME,+ slug: 'x',+ workingDir: WD,+ })+ ).toEqual({ args: [], env: {} });expect(fs.files.size).toBe(0);});@@ -184,11 +193,32 @@ describe('prepareAgentLaunchProfile', () => {expect(await prepareAgentLaunchProfile(claudeLikePlugin, {homeFs: fs,+ homeDir: HOME,slug: 'x',workingDir: WD,specialization: SPECIALIZED,})- ).toEqual([]);+ ).toEqual({ args: [], env: {} });expect(fs.files.size).toBe(0);});++ it("resolves the home placeholder in a profile's env and file content", async () => {+ // OpenCode names its config by absolute path in `OPENCODE_CONFIG`, and that+ // config names its instructions file the same way. Neither can be formed by+ // the pure profile builder, so both arrive with the placeholder in them.+ const fs = memoryFs();+ const { env } = await prepareAgentLaunchProfile(opencodePlugin, {+ homeFs: fs,+ homeDir: HOME,+ slug: 'oc-hoot',+ workingDir: WD,+ specialization: { model: 'anthropic/claude-sonnet-4-5', instructions: 'be terse' },+ });++ expect(env.OPENCODE_CONFIG?.startsWith(`${HOME}/.config/opencode/switch/`)).toBe(true);+ const config = fs.files.get(env.OPENCODE_CONFIG!.slice(HOME.length + 1));+ expect(config).toBeDefined();+ expect(config).not.toContain('__SWITCHDASH_');+ expect(JSON.parse(config!).instructions[0].startsWith(`${HOME}/`)).toBe(true);+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.tsindex 6953ea99b..a4afd51a4 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.ts@@ -3,6 +3,10 @@ import type {SwitchLaunchProfile,SwitchLaunchSpecialization,} from '@switch-console/core/agents/plugins';+import {+ resolveLaunchProfileEnv,+ resolveLaunchProfileHome,+} from '@switch-console/core/agents/plugins';import type { getPlugin } from '@main/core/providers/plugin-registry';/**@@ -33,14 +37,25 @@ export function resolveAgentLaunchProfile(return launchProfile({slug: params.slug,workingDir: params.workingDir,- ...params.specialization,+ values: params.specialization ?? {},});}+/** What a launch surface needs to apply a profile: argv, and env to merge. */+export type PreparedLaunchProfile = {+ args: string[];+ env: Record<string, string>;+};+/*** Apply a launching session's per-agent specialization by writing its launch* profile files into `homeFs` (rooted at the agent's home dir) and returning the- * argv that loads them. Returns `[]` when there is nothing to write.+ * argv and environment that load them. Both are empty when there is nothing to+ * write.+ *+ * `homeDir` is the absolute path `homeFs` is rooted at — the same directory,+ * named twice because the profile's files are addressed relative to it while its+ * env has to name one absolutely (see `LAUNCH_PROFILE_HOME_PLACEHOLDER`).** Used by the local and SSH runtimes, which write at launch. Remote auto-sessions* instead bake the files into their launch spec (see {@link@@ -50,16 +65,20 @@ export async function prepareAgentLaunchProfile(plugin: ReturnType<typeof getPlugin>,params: {homeFs: PluginFs;+ homeDir: string;slug: string;workingDir: string;specialization?: SwitchLaunchSpecialization;}-): Promise<string[]> {+): Promise<PreparedLaunchProfile> {const profile = resolveAgentLaunchProfile(plugin, params);- if (!profile) return [];+ if (!profile) return { args: [], env: {} };for (const file of profile.files) {- await params.homeFs.write(file.relativePath, file.content);+ await params.homeFs.write(+ file.relativePath,+ resolveLaunchProfileHome(file.content, params.homeDir)+ );}- return profile.args;+ return { args: profile.args, env: resolveLaunchProfileEnv(profile.env, params.homeDir) };}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.tsindex 29610f156..847fb4d37 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.test.ts@@ -305,7 +305,7 @@ describe('local agent runtime respawn state', () => {const exitHandlers: Array<(info: PtyExitInfo) => void> = [];spawnLocalPty.mockReturnValue(fakePty(exitHandlers));vi.mocked(getAgentById).mockResolvedValueOnce({- providerConfig: { model: 'gpt-5.6-terra' },+ providerConfig: { version: '2', providerId: 'codex', values: { model: 'gpt-5.6-terra' } },} as unknown as Awaited<ReturnType<typeof getAgentById>>);vi.mocked(readAgentSwitchEnvFromFs).mockResolvedValueOnce({SWITCH_API_ENDPOINT: 'https://switch.example.com',diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex 4ba1b366e..e856a9c1b 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -185,8 +185,9 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {// under `~/.codex` carrying model / effort / instructions, loaded with// `--profile <slug>`. The Switch MCP server is not written here — the// connector plugin registers it from its own bundled `.mcp.json`.- const launchProfileArgs = await prepareAgentLaunchProfile(plugin, {+ const launchProfile = await prepareAgentLaunchProfile(plugin, {homeFs: createPluginFs(homedir()),+ homeDir: homedir(),slug: agentCredsSlug(session),workingDir: this.sessionPath,specialization: toSwitchSpecialization(agentRecord?.providerConfig),@@ -201,7 +202,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {...(session.agentName && repoAgents? repoAgents.launchArgs(this.sessionPath, session.agentName): []),- ...launchProfileArgs,+ ...launchProfile.args,],autoApprove,initialPrompt: agentSession.isResuming ? undefined : initialPrompt,@@ -212,7 +213,11 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {});const customEnv = providerConfig?.env ?? {};- const providerVars: Record<string, string> = { ...agentCommand.env, ...customEnv };+ const providerVars: Record<string, string> = {+ ...agentCommand.env,+ ...launchProfile.env,+ ...customEnv,+ };const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.tsindex 75b4d8270..b4fe0ab15 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.test.ts@@ -340,7 +340,7 @@ describe('SshAgentRuntime', () => {vi.mocked(getAgentById).mockResolvedValueOnce({autoApprove: false,name: 'codex-hoot',- providerConfig: { model: 'gpt-5.6-terra' },+ providerConfig: { version: '2', providerId: 'codex', values: { model: 'gpt-5.6-terra' } },} as never);mockSpawn([]);diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex f99fc76f9..63451da3a 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -3,8 +3,14 @@ import type {PluginScope,SwitchLaunchSpecialization,} from '@switch-console/core/agents/plugins';+import {+ LAUNCH_PROFILE_HOME_PLACEHOLDER,+ resolveLaunchProfileEnv,+ resolveLaunchProfileHome,+} from '@switch-console/core/agents/plugins';import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';+import type { PreparedLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';import { resolveAgentLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';import type { AttachableRuntime } from '@main/core/agent-runtime/attachment/types';@@ -25,6 +31,7 @@ import { getTerminalColorEnv } from '@main/core/pty/terminal-color-scheme';import { killTmuxSession, makeAgentTmuxSessionName } from '@main/core/pty/tmux-session-name';import { sessionHooks } from '@main/core/sessions/session-hooks';import { providerOverrideSettings } from '@main/core/settings/provider-settings-service';+import { resolveRemoteHome } from '@main/core/ssh/lifecycle/remote-shell-profile';import type { SshClientProxy } from '@main/core/ssh/lifecycle/ssh-client-proxy';import { readAgentSwitchEnvFromFs } from '@main/core/switch-rooms/switch-credentials';import { events } from '@main/lib/events';@@ -360,25 +367,39 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime/*** Write the per-agent launch files of a provider that needs them under the* VM's home (Codex: a profile carrying model / effort / instructions).- * Returns the argv that loads them, or `[]` when there is nothing to write.+ * Returns the argv and environment that load them, both empty when there is+ * nothing to write.+ *+ * The VM's home is resolved only when the profile has env to place it in: the+ * files themselves are written through a home-rooted fs that expands `$HOME`+ * on the far side, so the common case still costs no extra round trip.*/private async writeRemoteLaunchProfile(plugin: ReturnType<typeof getPlugin>,slug: string,specialization: SwitchLaunchSpecialization | undefined- ): Promise<string[]> {+ ): Promise<PreparedLaunchProfile> {const profile = resolveAgentLaunchProfile(plugin, {slug,workingDir: this.sessionPath,specialization,});- if (!profile) return [];+ if (!profile) return { args: [], env: {} };++ // Only resolved when something actually carries the placeholder: the files+ // are written through a home-rooted fs that expands `$HOME` on the far side,+ // so a profile that needs no absolute path costs no extra round trip.+ const needsHome =+ profile.env !== undefined ||+ profile.files.some((file) => file.content.includes(LAUNCH_PROFILE_HOME_PLACEHOLDER));+ const homeDir = needsHome ? await resolveRemoteHome(this.ctx) : '';const homeFs = createRemoteHomePluginFs(this.ctx);for (const file of profile.files) {- await homeFs.write(file.relativePath, file.content);+ await homeFs.write(file.relativePath, resolveLaunchProfileHome(file.content, homeDir));}- return profile.args;++ return { args: profile.args, env: resolveLaunchProfileEnv(profile.env, homeDir) };}private async launchSidecar(session: Session): Promise<SidecarEndpoint> {@@ -700,7 +721,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime// Codex writes a profile under the VM's ~/.codex for model / effort /// instructions. The Switch MCP server comes from the connector plugin's// own `.mcp.json`, on the VM as locally.- const launchProfileArgs = await this.writeRemoteLaunchProfile(+ const launchProfile = await this.writeRemoteLaunchProfile(plugin,agentCredsSlug(session),toSwitchSpecialization(agentRecord?.providerConfig)@@ -718,7 +739,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime...(session.agentName && repoAgents? repoAgents.launchArgs(this.sessionPath, session.agentName): []),- ...launchProfileArgs,+ ...launchProfile.args,],autoApprove,initialPrompt: agentSession.isResuming ? undefined : initialPrompt,@@ -729,7 +750,11 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime});const customEnv = providerConfig?.env ?? {};- const providerEnv: Record<string, string> = { ...agentCommand.env, ...customEnv };+ const providerEnv: Record<string, string> = {+ ...agentCommand.env,+ ...launchProfile.env,+ ...customEnv,+ };const tmuxSessionName = this.tmux ? makeAgentTmuxSessionName(this.sessionId) : undefined;diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.tsindex a2017f75b..27c9ea9d8 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts@@ -34,6 +34,25 @@ export function getAgentAdvancedFields(providerId: AgentProviderId): RepoAgentFireturn behavior.mcp?.launchProfileFields?.() ?? [];}+/** Where a provider keeps its per-agent settings. */+export type AgentAdvancedSurface = 'definition' | 'launch-profile' | 'none';++/**+ * Which of the two surfaces a provider uses, for a caller that has to treat them+ * differently — the renderer offers a restart only for a launch profile, which is+ * read once at spawn and so cannot reach a session already running.+ *+ * Reported rather than inferred from the provider id: that check was `=== 'codex'`+ * for as long as Codex was the only provider with a profile, and silently+ * excluded the next one.+ */+export function getAgentAdvancedSurface(providerId: AgentProviderId): AgentAdvancedSurface {+ const behavior = getPlugin(providerId).behavior;+ if (behavior.repoAgents?.attributeFields()) return 'definition';+ if (behavior.mcp?.launchProfileFields) return 'launch-profile';+ return 'none';+}+/*** Current values for the form, or null when there is nothing stored yet — the* caller renders an empty form in that case.@@ -71,6 +90,6 @@ export async function updateAgentAdvancedConfig(params: {}return setAgentProviderConfig({agentId: params.agentId,- config: providerConfigFromAttributes(params.attributes),+ config: providerConfigFromAttributes(agent.providerId, params.attributes),});}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.tsnew file mode 100644index 000000000..150133bda--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts@@ -0,0 +1,123 @@+import type { LaunchProfileModel } from '@switch-console/core/agents/plugins';+import { isTransportFailure } from '@switch-console/core/exec';+import { resolveAgentExecutable } from '@main/core/agent-runtime/impl/resolve-agent-executable';+import { localDependencyManager } from '@main/core/dependencies/dependency-managers';+import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';+import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';+import { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';+import type { IExecutionContext } from '@main/core/execution-context/types';+import { locationTransport } from '@main/core/locations/location-transport';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import { log } from '@main/lib/logger';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++/**+ * The models a host offers, or why we could not find out.+ *+ * Two outcomes rather than an empty list, because they mean opposite things to+ * the form: `unavailable` leaves a model field as plain text and says why, while+ * an empty `available` would flag everything the user types as wrong. The+ * provider CLI not being installed on that host is the common case and is not an+ * error worth a dialog — it is a reason the field cannot check itself.+ */+export type AgentModelCatalogue =+ | { kind: 'available'; models: LaunchProfileModel[] }+ | { kind: 'unavailable'; reason: string };++/**+ * Ask a host which models it offers for a provider, and what reasoning variants+ * each accepts, for the advanced-configuration fields that declare a `catalogue`+ * binding.+ *+ * Keyed on the host rather than on an agent so the create-agent form can ask+ * before the agent exists, and so the answer comes from the machine that decides+ * it: a local agent and a remote one do not offer the same models, and a+ * locally-served model exists on exactly one of them.+ *+ * Never throws. Every failure becomes a reason the form shows.+ */+export async function getAgentModelCatalogue(params: {+ providerId: AgentProviderId;+ /** The location's SSH alias, or null for this machine. */+ sshHost: string | null;+ dir: string;+}): Promise<AgentModelCatalogue> {+ const plugin = getPlugin(params.providerId);+ const launchProfileModels = plugin.behavior.mcp?.launchProfileModels;+ if (!launchProfileModels) {+ return {+ kind: 'unavailable',+ reason: `${plugin.metadata.name} does not publish a model list.`,+ };+ }++ let ctx: IExecutionContext | null = null;+ try {+ const host = await resolveHost(params.sshHost, params.dir);+ ctx = host.ctx;++ const cli = await resolveAgentExecutable({+ providerId: params.providerId,+ binaryName: plugin.capabilities.hostDependency.binaryNames[0] ?? params.providerId,+ ctx: host.ctx,+ hostDependencyStore,+ // Skips a `which` when the local dependency probe already resolved it.+ // Absent for a remote host, whose probe is a different manager.+ cachedStatePath:+ params.sshHost === null+ ? localDependencyManager.get(params.providerId as never)?.path+ : undefined,+ connectionId: host.connectionId,+ });++ // The resolved binary replaces the one the provider named, so a user who+ // pinned a particular install is asked about that one rather than whatever+ // happens to be first on PATH.+ const execAt = host.ctx;+ const models = await launchProfileModels(async (_command, args) => execAt.exec(cli, args));+ return { kind: 'available', models };+ } catch (error) {+ const reason = describe(error, plugin.metadata.name, params.sshHost);+ log.info('getAgentModelCatalogue: could not read the host model catalogue', {+ providerId: params.providerId,+ sshHost: params.sshHost,+ reason,+ });+ return { kind: 'unavailable', reason };+ } finally {+ ctx?.dispose();+ }+}++/**+ * Say what went wrong in terms the person filling in the form can act on.+ *+ * A transport failure and a command failure look the same to a caller but call+ * for opposite responses — fix the connection, or install the CLI — so they are+ * distinguished rather than both reported as "could not read models".+ */+function describe(error: unknown, providerName: string, sshHost: string | null): string {+ if (isTransportFailure(error)) {+ return `Couldn't reach ${sshHost ?? 'this machine'}.`;+ }+ const detail = error instanceof Error ? error.message : String(error);+ return `Couldn't ask ${providerName} on ${sshHost ?? 'this machine'} for its models: ${detail}`;+}++/** An execution context on the machine a location lives on, local or remote. */+async function resolveHost(+ sshHost: string | null,+ dir: string+): Promise<{ ctx: IExecutionContext; connectionId?: string }> {+ const transport = locationTransport({ sshHost, dir });+ if (transport.kind === 'local') {+ return { ctx: new LocalExecutionContext({ root: dir }) };+ }++ const proxy = await ensureSshConnected(transport.connectionId, transport.host);+ return {+ ctx: new SshExecutionContext(proxy, { root: transport.dir }),+ connectionId: transport.connectionId,+ };+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.tsindex ec4e3ebc7..bae424dc1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts@@ -7,10 +7,12 @@ import { createRPCController } from '@shared/lib/ipc/rpc';import { addAgent, type AddAgentParams } from './add-agent';import {getAgentAdvancedFields,+ getAgentAdvancedSurface,readAgentAdvancedConfig,updateAgentAdvancedConfig,} from './agent-advanced-config';import { readAgentDefinition, updateAgentDefinition } from './agent-definition';+import { getAgentModelCatalogue } from './agent-model-catalogue';import { assignAgentServer } from './assignAgentServer';import {attachConfiguredAgents,@@ -51,6 +53,15 @@ export const agentsController = createRPCController({*/advancedFields: (params: { providerId: AgentProviderId }) =>Promise.resolve(getAgentAdvancedFields(params.providerId)),+ advancedSurface: (params: { providerId: AgentProviderId }) =>+ Promise.resolve(getAgentAdvancedSurface(params.providerId)),+ /**+ * The models the agent's own host offers, for the advanced-configuration+ * fields that declare a catalogue binding. Reports why it could not be read+ * rather than throwing: the form degrades to plain text and says so.+ */+ modelCatalogue: (params: { providerId: AgentProviderId; sshHost: string | null; dir: string }) =>+ getAgentModelCatalogue(params),readAdvancedConfig: (params: { agentId: string }) => readAgentAdvancedConfig(params.agentId),updateAdvancedConfig: (params: { agentId: string; attributes: RepoAgentAttributes }) =>updateAgentAdvancedConfig(params),diff --git a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.tsindex 23db26ad2..c8b28eecb 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.test.ts@@ -10,13 +10,15 @@ const launchArgs = vi.fn((dir: string, name: string) => [`${dir}/.switch/agents/${name}.json`,]);-const launchProfile = vi.fn((params: { slug: string; model?: string; instructions?: string }) =>- params.model || params.instructions- ? {- files: [{ relativePath: `.codex/${params.slug}.config.toml`, content: 'PROFILE' }],- args: ['--profile', params.slug],- }- : null+const launchProfile = vi.fn(+ (params: { slug: string; values: Record<string, string | undefined> }) =>+ params.values.model || params.values.instructions+ ? {+ files: [{ relativePath: `.codex/${params.slug}.config.toml`, content: 'PROFILE' }],+ args: ['--profile', params.slug],+ env: { PROFILE_PATH: `__SWITCHDASH_HOME__/.codex/${params.slug}.config.toml` },+ }+ : null);/** Set per test: whether the mocked provider takes specialization from a file. */let mcpBehavior: { launchProfile?: typeof launchProfile } | undefined;@@ -115,6 +117,22 @@ describe('generateAgentLaunchSpec', () => {]);});+ it("bakes a profile's env with the home placeholder left for the sidecar", async () => {+ // A provider that names its config through the environment (OpenCode) needs+ // an absolute path, and this runs on the desktop, which does not know the+ // VM's home. The placeholder survives into the spec deliberately; the+ // sidecar substitutes it where it writes the file.+ mcpBehavior = { launchProfile };++ const spec = await generateAgentLaunchSpec({+ ...baseParams,+ autoApprove: false,+ specialization: { model: 'gpt-5.6-terra' },+ });++ expect(spec.env.PROFILE_PATH).toBe('__SWITCHDASH_HOME__/.codex/hoot.config.toml');+ });+it('bakes a profile that carries no credential and registers no server', async () => {// The sidecar writes this file verbatim on the VM, so whatever is baked here// is what a remote session runs with — and a value baked in would be a secret@@ -226,6 +244,7 @@ describe('generateAgentLaunchSpec against real provider command builders', () =>sessionId: 's1',initialPrompt: 'connect to switch room room-x',extraEnv: {},+ homeDir: '/home/agent',});@@ -250,6 +269,7 @@ describe('generateAgentLaunchSpec against real provider command builders', () =>sessionId: 's1',initialPrompt: 'p',extraEnv: {},+ homeDir: '/home/agent',});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.tsindex 3ad823073..42822ece2 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/generate-agent-launch-spec.ts@@ -106,7 +106,10 @@ export async function generateAgentLaunchSpec(params: {return {command: agentCommand.command,args: agentCommand.args,- env: { ...agentCommand.env, ...(providerConfig?.env ?? {}) },+ // The profile's env may name one of its own files, which needs the VM's home+ // directory — unknown here. It carries the home placeholder instead and the+ // sidecar substitutes its own home when it materializes the command.+ env: { ...agentCommand.env, ...(switchProfile?.env ?? {}), ...(providerConfig?.env ?? {}) },cwd: remoteRepoDir,launchFiles: switchProfile?.files.map((file) => ({homeRelativePath: file.relativePath,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.tsindex 3eb277c02..a8a933a3a 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts@@ -47,7 +47,11 @@ vi.mock('./remove-launch-profile', () => ({import { setAgentProviderConfig } from './setAgentProviderConfig';-const CONFIG: AgentProviderConfig = { version: '1', model: 'gpt-5.6-terra', effort: 'high' };+const CONFIG: AgentProviderConfig = {+ version: '2',+ providerId: 'codex',+ values: { model: 'gpt-5.6-terra', effort: 'high' },+};describe('setAgentProviderConfig', () => {beforeEach(() => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex e92f9ac39..f72c13a40 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -54,9 +54,9 @@ import {import { basenameFromAnyPath } from '@shared/path-name';import { AgentAdvancedConfig } from './agent-advanced-config';import { AgentTypePicker } from './agent-type-picker';-import { CodexAgentConfig } from './codex-agent-config';import { ConfigureAgentPanel } from './configure-agent-panel';import { PickExistingPanel } from './content';+import { LaunchProfileConfig } from './launch-profile-config';import { useConfigureAgentForm, usePickMode } from './modes';import {type AdoptKind,@@ -189,11 +189,12 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocadvancedAttributesRef.current = attributes;}, []);- // Per-agent Codex config (model / effort / instructions), held in a ref for- // the same reason. Null when the user left the Codex section untouched.- const codexConfigRef = useRef<AgentProviderConfig | null>(null);- const onCodexConfigChange = useCallback((config: AgentProviderConfig | null) => {- codexConfigRef.current = config;+ // Per-agent launch-profile config (model, and whatever else the provider+ // exposes), held in a ref for the same reason. Null when the user left the+ // section untouched, or when the provider has no launch profile at all.+ const launchProfileConfigRef = useRef<AgentProviderConfig | null>(null);+ const onLaunchProfileConfigChange = useCallback((config: AgentProviderConfig | null) => {+ launchProfileConfigRef.current = config;}, []);const shouldCheckPathStatus = !isRemoteRun && pickState.path.trim().length > 0;@@ -620,7 +621,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocautoSession: form.autoSession,autoApprove: form.autoApprove,definitionAttributes: advancedAttributesRef.current,- providerConfig: codexConfigRef.current,+ providerConfig: launchProfileConfigRef.current,});if (result.kind !== 'created') {reportProvisionError(result);@@ -925,9 +926,12 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoconAddServer={() => showAddServerModal({})}/><AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} />- {pickState.providerId === 'codex' && (- <CodexAgentConfig onChange={onCodexConfigChange} />- )}+ <LaunchProfileConfig+ providerId={pickState.providerId}+ sshHost={discoverSshHost}+ dir={discoverDir}+ onChange={onLaunchProfileConfigChange}+ /></>)}{canDetailAgent && switchAgent && (@@ -994,9 +998,12 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLoconAddServer={() => showAddServerModal({})}/><AgentAdvancedConfig providerId={pickState.providerId} onChange={onAdvancedChange} />- {pickState.providerId === 'codex' && (- <CodexAgentConfig onChange={onCodexConfigChange} />- )}+ <LaunchProfileConfig+ providerId={pickState.providerId}+ sshHost={discoverSshHost}+ dir={discoverDir}+ onChange={onLaunchProfileConfigChange}+ /></>)}</DialogContentArea>diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsxdeleted file mode 100644index 26a14be08..000000000--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx+++ /dev/null@@ -1,86 +0,0 @@-import { useQuery } from '@tanstack/react-query';-import { ChevronRight } from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';-import { rpc } from '@renderer/lib/ipc';-import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';-import { cn } from '@renderer/utils/utils';-import {- type AgentProviderConfig,- providerConfigFromAttributes,-} from '@shared/core/agents/agent-provider-config';-import {- attributesFromForm,- DefinitionFieldInput,- emptyForm,- type FormState,- type FormValue,-} from '../agent-definition-fields';--/**- * Collapsed "Codex configuration" section. Reports the assembled per-agent- * provider config (or null when nothing is set) so the modal can pass it to- * `addAgent`, which persists it on the agent and folds it into the launch profile.- *- * The fields are the same ones the agent's Settings tab edits after creation —- * fetched over RPC from the codex plugin, so the two forms cannot drift.- */-export function CodexAgentConfig({- onChange,-}: {- onChange: (config: AgentProviderConfig | null) => void;-}) {- const [open, setOpen] = useState(false);-- const { data } = useQuery({- queryKey: ['agentAdvancedFields', 'codex'],- queryFn: () => rpc.agents.advancedFields({ providerId: 'codex' }),- });- const fields = useMemo(() => data ?? [], [data]);-- const [state, setState] = useState<FormState>({});- useEffect(() => {- setState(emptyForm(fields));- }, [fields]);-- useEffect(() => {- onChange(providerConfigFromAttributes(attributesFromForm(fields, state)));- }, [fields, state, onChange]);-- const setField = useCallback((key: string, value: FormValue) => {- setState((prev) => ({ ...prev, [key]: value }));- }, []);-- if (fields.length === 0) return null;-- return (- <div className="rounded-md border border-border">- <button- type="button"- className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"- onClick={() => setOpen((v) => !v)}- >- <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />- Codex configuration- </button>- {open && (- <div className="flex flex-col gap-4 border-t border-border px-3 py-3">- {fields.map((field) => (- <Field key={field.key}>- <FieldLabel htmlFor={`codex-config-${field.key}`}>- {field.label} (optional)- </FieldLabel>- <DefinitionFieldInput- field={field}- value={state[field.key] ?? ''}- onChange={(value) => setField(field.key, value)}- />- {field.help && (- <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>- )}- </Field>- ))}- </div>- )}- </div>- );-}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsxnew file mode 100644index 000000000..f97c88cf1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/launch-profile-config.tsx@@ -0,0 +1,137 @@+import { useQuery } from '@tanstack/react-query';+import { ChevronRight } from 'lucide-react';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { rpc } from '@renderer/lib/ipc';+import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';+import { cn } from '@renderer/utils/utils';+import {+ type AgentProviderConfig,+ providerConfigFromAttributes,+} from '@shared/core/agents/agent-provider-config';+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import {+ attributesFromForm,+ DefinitionFieldInput,+ emptyForm,+ type FormState,+ type FormValue,+} from '../agent-definition-fields';+import {+ fieldCatalogueState,+ fieldWithCatalogue,+ type ModelCatalogueResult,+} from '../agent-model-catalogue';++/**+ * Collapsed "Advanced configuration" section for a provider that keeps its+ * per-agent settings in a launch profile (Codex, OpenCode). Reports the assembled+ * per-agent provider config (or null when nothing is set) so the modal can pass+ * it to `addAgent`, which persists it on the agent and folds it into the profile.+ *+ * The fields are the same ones the agent's Settings tab edits after creation —+ * fetched over RPC from the provider's own plugin, so the two forms cannot drift,+ * and the section renders nothing for a provider that declares none. That empty+ * field list is the gate: no caller needs to know which providers have one.+ */+export function LaunchProfileConfig({+ providerId,+ sshHost,+ dir,+ onChange,+}: {+ providerId: AgentProviderId | null;+ /** The host the agent will run on: its SSH alias, or null for this machine. */+ sshHost: string | null;+ dir: string;+ onChange: (config: AgentProviderConfig | null) => void;+}) {+ const [open, setOpen] = useState(false);++ const { data } = useQuery({+ queryKey: ['agentAdvancedFields', providerId],+ queryFn: () => (providerId ? rpc.agents.advancedFields({ providerId }) : Promise.resolve([])),+ enabled: !!providerId,+ });+ const fields = useMemo(() => data ?? [], [data]);++ // The models that host offers, for the fields bound to it. Asked of the host+ // the agent will run on, since that is what decides the answer — and only once+ // a directory has been chosen, because before that there is no host to ask.+ const { data: catalogue } = useQuery({+ queryKey: ['agent-model-catalogue', providerId, sshHost ?? 'local', dir],+ queryFn: (): Promise<ModelCatalogueResult> =>+ providerId && dir.trim()+ ? rpc.agents.modelCatalogue({ providerId, sshHost, dir })+ : Promise.resolve({ kind: 'unavailable', reason: 'No host to ask yet.' }),+ enabled: !!providerId && dir.trim().length > 0,+ staleTime: 60_000,+ });++ const [state, setState] = useState<FormState>({});+ useEffect(() => {+ setState(emptyForm(fields));+ }, [fields]);++ useEffect(() => {+ onChange(+ providerId+ ? providerConfigFromAttributes(providerId, attributesFromForm(fields, state))+ : null+ );+ }, [providerId, fields, state, onChange]);++ const setField = useCallback((key: string, value: FormValue) => {+ setState((prev) => ({ ...prev, [key]: value }));+ }, []);++ if (!providerId || fields.length === 0) return null;++ return (+ <div className="rounded-md border border-border">+ <button+ type="button"+ className="flex w-full items-center gap-1.5 px-2 py-2 text-sm text-foreground-muted"+ onClick={() => setOpen((v) => !v)}+ >+ <ChevronRight className={cn('h-4 w-4 transition-transform', open && 'rotate-90')} />+ Advanced configuration+ </button>+ {open && (+ <div className="flex flex-col gap-4 border-t border-border px-3 py-3">+ {fields.map((field) => {+ const catalogueState = fieldCatalogueState(field, state, catalogue);+ const rendered = fieldWithCatalogue(field, catalogueState);+ return (+ <Field key={field.key}>+ <FieldLabel htmlFor={`launch-profile-${field.key}`}>+ {field.label} (optional)+ </FieldLabel>+ <DefinitionFieldInput+ field={rendered}+ value={state[field.key] ?? ''}+ disabled={catalogueState.disabled}+ suggestions={catalogueState.suggestions}+ onChange={(value) => setField(field.key, value)}+ />+ {field.help && (+ <FieldDescription className="text-foreground-muted">+ {field.help}+ </FieldDescription>+ )}+ {catalogueState.note && (+ <FieldDescription+ className={+ catalogueState.warning ? 'text-foreground-warning' : 'text-foreground-muted'+ }+ >+ {catalogueState.note}+ </FieldDescription>+ )}+ </Field>+ );+ })}+ </div>+ )}+ </div>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsxindex ec0ba1a6f..26185ae03 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-definition-fields.tsx@@ -1,4 +1,5 @@import type {+ LaunchProfileModel,RepoAgentAttributes,RepoAgentAttributeValue,RepoAgentField,@@ -13,6 +14,7 @@ import {} from '@renderer/lib/ui/select';import { Switch } from '@renderer/lib/ui/switch';import { Textarea } from '@renderer/lib/ui/textarea';+import { ModelCombobox } from './model-combobox';/** Sentinel for a select's "unset" choice (an empty string is not a valid item). */const UNSET = '__unset__';@@ -85,14 +87,37 @@ export function DefinitionFieldInput({field,value,onChange,+ disabled,+ suggestions,}: {field: RepoAgentField;value: FormValue;onChange: (value: FormValue) => void;+ /** Nothing to choose — the caller explains why beside the field. */+ disabled?: boolean;+ /**+ * Models the host offers. Renders the field as a combobox: typing filters+ * them, picking one fills the box, and anything else is still accepted.+ */+ suggestions?: LaunchProfileModel[];}) {const id = `agent-definition-${field.key}`;+ if (suggestions) {+ return (+ <ModelCombobox+ id={id}+ value={String(value)}+ models={suggestions}+ placeholder={field.placeholder}+ disabled={disabled}+ onChange={onChange}+ />+ );+ }if (field.type === 'boolean') {- return <Switch id={id} checked={value === true} onCheckedChange={onChange} />;+ return (+ <Switch id={id} checked={value === true} onCheckedChange={onChange} disabled={disabled} />+ );}if (field.type === 'textarea') {return (@@ -101,6 +126,7 @@ export function DefinitionFieldInput({value={String(value)}rows={5}placeholder={field.placeholder}+ disabled={disabled}onChange={(e) => onChange(e.target.value)}/>);@@ -114,6 +140,7 @@ export function DefinitionFieldInput({return (<Selectvalue={selected}+ disabled={disabled}onValueChange={(next) => onChange(next === UNSET ? '' : (next ?? ''))}><SelectTrigger id={id}>@@ -135,6 +162,7 @@ export function DefinitionFieldInput({type={field.type === 'number' ? 'number' : 'text'}value={String(value)}placeholder={field.placeholder}+ disabled={disabled}onChange={(e) => onChange(e.target.value)}/>);diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.test.tsnew file mode 100644index 000000000..29c405fbe--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.test.ts@@ -0,0 +1,185 @@+import type { RepoAgentField } from '@switch-console/core/agents/plugins';+import { describe, expect, it } from 'vitest';+import {+ fieldCatalogueState,+ fieldWithCatalogue,+ type ModelCatalogueResult,+} from './agent-model-catalogue';++const modelField: RepoAgentField = {+ key: 'model',+ label: 'Model',+ type: 'text',+ catalogue: { kind: 'model' },+};++const variantField: RepoAgentField = {+ key: 'variant',+ label: 'Reasoning variant',+ type: 'text',+ catalogue: { kind: 'model-variant', modelField: 'model' },+};++const plainField: RepoAgentField = { key: 'instructions', label: 'Instructions', type: 'textarea' };++const CATALOGUE: ModelCatalogueResult = {+ kind: 'available',+ models: [+ { id: 'ollama/gemma4:latest', variants: [] },+ { id: 'google/gemini-2.5-flash', variants: ['high', 'max'] },+ ],+};++describe('fieldCatalogueState', () => {+ it('leaves a field that declares no binding alone', () => {+ expect(fieldCatalogueState(plainField, { instructions: 'hi' }, CATALOGUE)).toEqual({});+ });++ it('says nothing while the catalogue is still loading', () => {+ expect(fieldCatalogueState(modelField, { model: 'anything' }, undefined)).toEqual({});+ });++ describe('the model field', () => {+ it('accepts a model the host offers without comment', () => {+ const state = fieldCatalogueState(modelField, { model: 'ollama/gemma4:latest' }, CATALOGUE);++ expect(state.note).toBeUndefined();+ expect(state.warning).toBeFalsy();+ });++ it('offers the host’s models whatever is currently typed', () => {+ // The list is a way to discover what this host has, not only a check on+ // what was typed, so it is offered for a valid, blank or unknown value.+ for (const model of ['ollama/gemma4:latest', '', 'ollama/typo']) {+ expect(fieldCatalogueState(modelField, { model }, CATALOGUE).suggestions).toEqual(+ CATALOGUE.kind === 'available' ? CATALOGUE.models : []+ );+ }+ });++ it('warns about a model the host does not offer, and still allows it', () => {+ // Warns rather than blocks: the catalogue is a snapshot of a machine that+ // changes without us, and the model may be about to exist.+ const state = fieldCatalogueState(modelField, { model: 'ollama/typo' }, CATALOGUE);++ expect(state.warning).toBe(true);+ expect(state.note).toContain('ollama/typo');+ expect(state.disabled).toBeFalsy();+ });++ it('stays quiet while a name is still being typed', () => {+ // The field is checked on every keystroke. Warning as soon as the value+ // stops matching would put a warning under the box for most of the time+ // the user spends typing a perfectly good name.+ for (const partial of ['g', 'google/', 'google/gemini-2.5-fl']) {+ const state = fieldCatalogueState(modelField, { model: partial }, CATALOGUE);+ expect(state.warning).toBeFalsy();+ expect(state.note).toBeUndefined();+ }+ });++ it('warns once the name can no longer become a real one', () => {+ const state = fieldCatalogueState(modelField, { model: 'google/gemini-9' }, CATALOGUE);+ expect(state.warning).toBe(true);+ });++ it('says nothing about a blank model, which means the host default', () => {+ const state = fieldCatalogueState(modelField, { model: ' ' }, CATALOGUE);++ expect(state.note).toBeUndefined();+ expect(state.warning).toBeFalsy();+ });+ });++ describe('the reasoning-variant field', () => {+ it('offers exactly the variants the chosen model accepts', () => {+ const state = fieldCatalogueState(+ variantField,+ { model: 'google/gemini-2.5-flash' },+ CATALOGUE+ );++ expect(state.options).toEqual([+ { value: '', label: 'Default' },+ { value: 'high', label: 'high' },+ { value: 'max', label: 'max' },+ ]);+ expect(state.disabled).toBeFalsy();+ });++ it('disables itself for a model with no variants, and says why', () => {+ // The Ollama case. OpenCode would accept a variant here and ignore it in+ // silence, so the field says so instead of looking configurable.+ const state = fieldCatalogueState(variantField, { model: 'ollama/gemma4:latest' }, CATALOGUE);++ expect(state.disabled).toBe(true);+ expect(state.note).toContain('no reasoning variants');+ });++ it('warns when a value left over from another model would be ignored', () => {+ const state = fieldCatalogueState(+ variantField,+ { model: 'google/gemini-2.5-flash', variant: 'xhigh' },+ CATALOGUE+ );++ expect(state.warning).toBe(true);+ expect(state.note).toContain('would be ignored');+ expect(state.options).toBeDefined();+ });++ it('asks for a model first rather than guessing which variants apply', () => {+ const state = fieldCatalogueState(variantField, { model: '' }, CATALOGUE);++ expect(state.note).toContain('Choose a model');+ expect(state.warning).toBeFalsy();+ });++ it('stays quiet when the model itself is the problem', () => {+ // The model field already flags it; two warnings for one mistake is noise.+ expect(fieldCatalogueState(variantField, { model: 'ollama/typo' }, CATALOGUE)).toEqual({});+ });+ });++ describe('when the host could not be asked', () => {+ const unavailable: ModelCatalogueResult = { kind: 'unavailable', reason: 'Ran out of coffee.' };++ it('says so on a bound field rather than pretending the value is checked', () => {+ const state = fieldCatalogueState(modelField, { model: 'whatever' }, unavailable);++ expect(state.note).toContain('Ran out of coffee.');+ expect(state.warning).toBeFalsy();+ });++ it('offers no suggestions, so the field stays a plain box', () => {+ expect(+ fieldCatalogueState(modelField, { model: 'x' }, unavailable).suggestions+ ).toBeUndefined();+ });++ it('leaves the field usable, with the type its provider declared', () => {+ const state = fieldCatalogueState(variantField, { model: 'x', variant: 'y' }, unavailable);++ expect(state.disabled).toBeFalsy();+ expect(fieldWithCatalogue(variantField, state).type).toBe('text');+ });+ });+});++describe('fieldWithCatalogue', () => {+ it('turns a field into a select once the catalogue supplies choices', () => {+ const state = fieldCatalogueState(+ variantField,+ { model: 'google/gemini-2.5-flash' },+ CATALOGUE+ );+ const rendered = fieldWithCatalogue(variantField, state);++ expect(rendered.type).toBe('select');+ expect(rendered.options).toEqual(state.options);+ });++ it('leaves the declared type in place when there are no choices to offer', () => {+ expect(fieldWithCatalogue(modelField, {})).toBe(modelField);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.tsnew file mode 100644index 000000000..c9203e123--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/agent-model-catalogue.ts@@ -0,0 +1,133 @@+import type { LaunchProfileModel, RepoAgentField } from '@switch-console/core/agents/plugins';+import type { FormState } from './agent-definition-fields';++/**+ * What the main process could tell us about the models an agent's host offers.+ * Mirrors `AgentModelCatalogue`.+ */+export type ModelCatalogueResult =+ | { kind: 'available'; models: LaunchProfileModel[] }+ | { kind: 'unavailable'; reason: string };++/** How a catalogue-bound field should render, once the catalogue is known. */+export type FieldCatalogueState = {+ /** Replaces the field's own options when the catalogue supplies them. */+ options?: { value: string; label: string }[];+ /**+ * Models to offer as you type. Suggestions rather than options: the field+ * stays free text, because the catalogue is a snapshot and a model may be+ * about to exist.+ */+ suggestions?: LaunchProfileModel[];+ /** Nothing can be chosen — shown disabled with `note` as the reason. */+ disabled?: boolean;+ /** Something the user should read: why a value looks wrong, or why we can't tell. */+ note?: string;+ /** True when `note` is a problem rather than an explanation. */+ warning?: boolean;+};++const UNSET_OPTION = { value: '', label: 'Default' };++/**+ * Work out how one field should behave against the host catalogue.+ *+ * Everything here warns rather than blocks. The catalogue is a snapshot of a+ * machine that changes without us — a model can be pulled or a provider added a+ * second after it was read — so a value we cannot vouch for is flagged and still+ * saved. Refusing it would make a stale reading worse than no reading.+ */+export function fieldCatalogueState(+ field: RepoAgentField,+ form: FormState,+ catalogue: ModelCatalogueResult | undefined+): FieldCatalogueState {+ if (!field.catalogue) return {};+ if (!catalogue) return {};++ if (catalogue.kind === 'unavailable') {+ // Degrade visibly. The field still works; it just cannot check itself, and+ // saying so beats silently accepting anything as if it had been verified.+ return {+ note: `Couldn't read this host's models, so this isn't checked. ${catalogue.reason}`,+ };+ }++ if (field.catalogue.kind === 'model') {+ return modelFieldState(String(form[field.key] ?? '').trim(), catalogue.models);+ }+ return variantFieldState(+ String(form[field.catalogue.modelField] ?? '').trim(),+ String(form[field.key] ?? '').trim(),+ catalogue.models+ );+}++function modelFieldState(value: string, models: LaunchProfileModel[]): FieldCatalogueState {+ // Offered whatever the current value is, so the list is a way to discover what+ // this host has rather than only a check on what was typed.+ const suggestions = { suggestions: models };+ if (!value) return suggestions;+ if (models.some((model) => model.id === value)) return suggestions;++ // Half-typed is not wrong. The field is checked on every keystroke, so warning+ // the moment the value stops matching would put a warning under the box for+ // most of the time the user spends typing a name that is perfectly good.+ if (models.some((model) => model.id.startsWith(value))) return suggestions;++ return {+ ...suggestions,+ warning: true,+ note: `This host doesn't currently offer "${value}". It'll be saved anyway — check the name, or add the model to your OpenCode config first.`,+ };+}++function variantFieldState(+ modelValue: string,+ value: string,+ models: LaunchProfileModel[]+): FieldCatalogueState {+ // No model chosen: the agent runs on whatever the host's own config selects,+ // and we cannot know which that is, so we cannot say which variants apply.+ if (!modelValue) {+ return { note: 'Choose a model above to see the reasoning variants it accepts.' };+ }++ const model = models.find((candidate) => candidate.id === modelValue);+ // The model itself is already flagged on its own field; not repeated here.+ if (!model) return {};++ if (model.variants.length === 0) {+ return {+ disabled: true,+ note: `${modelValue} has no reasoning variants — most local models don't.`,+ };+ }++ return {+ options: [+ UNSET_OPTION,+ ...model.variants.map((variant) => ({ value: variant, label: variant })),+ ],+ // A value carried over from a different model is not silently dropped: it is+ // still stored, and OpenCode would ignore it without saying so.+ ...(value && !model.variants.includes(value)+ ? { warning: true, note: `${modelValue} doesn't accept "${value}" — it would be ignored.` }+ : {}),+ };+}++/**+ * The field as it should render, with catalogue-supplied choices folded in.+ *+ * A field whose choices come from the catalogue becomes a select; without them+ * it keeps the type the provider declared, which is what makes the degraded+ * path the same code as the working one.+ */+export function fieldWithCatalogue(+ field: RepoAgentField,+ state: FieldCatalogueState+): RepoAgentField {+ if (!state.options) return field;+ return { ...field, type: 'select', options: state.options };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.test.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.test.tsnew file mode 100644index 000000000..77851f7e8--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';+import { groupByProvider } from './model-combobox';++const model = (id: string, variants: string[] = []) => ({ id, variants });++describe('groupByProvider', () => {+ it('groups models under the provider their id names', () => {+ expect(+ groupByProvider([+ model('google/gemini-2.5-flash', ['high']),+ model('ollama/gemma4:latest'),+ model('google/gemini-2.5-pro', ['high', 'max']),+ ])+ ).toEqual([+ { value: 'google', items: ['google/gemini-2.5-flash', 'google/gemini-2.5-pro'] },+ { value: 'ollama', items: ['ollama/gemma4:latest'] },+ ]);+ });++ it('keeps the host’s own ordering rather than sorting', () => {+ // The order OpenCode lists them in is its preference — the default model+ // first — and re-sorting would bury it.+ const groups = groupByProvider([model('z/one'), model('a/two')]);+ expect(groups.map((group) => group.value)).toEqual(['z', 'a']);+ });++ it('keeps a local provider as its own group beside the cloud ones', () => {+ // The point of the field is that a local model sits alongside the rest;+ // forty entries in one flat list hides that.+ const groups = groupByProvider([model('google/a'), model('ollama/b'), model('google/c')]);+ expect(groups).toHaveLength(2);+ });++ it('survives an id with no provider prefix rather than dropping it', () => {+ expect(groupByProvider([model('bare')])).toEqual([{ value: 'bare', items: ['bare'] }]);+ });++ it('yields plain id strings, which is what the combobox can stringify', () => {+ // The combobox fills the input by stringifying the item it was handed, via+ // the item's `label` or `value`. A `{id, variants}` object has neither, so+ // picking one wrote a serialized object into the field — and the wrapper+ // exposes no hook to correct that. The item has to be the string itself.+ for (const group of groupByProvider([model('a/one'), model('b/two', ['high'])])) {+ for (const item of group.items) expect(typeof item).toBe('string');+ }+ });++ it('returns nothing for nothing', () => {+ expect(groupByProvider([])).toEqual([]);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.tsxnew file mode 100644index 000000000..fb7776cf1--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/model-combobox.tsx@@ -0,0 +1,123 @@+import type { LaunchProfileModel } from '@switch-console/core/agents/plugins';+import { useMemo, useState } from 'react';+import {+ Combobox,+ ComboboxCollection,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxGroup,+ ComboboxInput,+ ComboboxItem,+ ComboboxLabel,+ ComboboxList,+} from '@renderer/lib/ui/combobox';++/** One provider's model ids, so a long list reads as a few short ones. */+type ProviderGroup = { value: string; items: string[] };++/**+ * A model field: type freely, or pick from what the host actually offers.+ *+ * A plain select would be wrong here. The catalogue is a snapshot of a machine+ * that changes without us — a model can be pulled a second after it was read —+ * so a model that is not in the list has to stay typeable, and is flagged+ * elsewhere rather than prevented. The list is a shortcut, not a constraint.+ *+ * Grouped by provider because the whole point of the field is that a local+ * provider sits alongside the cloud ones, and forty entries in one flat list+ * hides that.+ *+ * **The items are model id strings, not model objects.** The combobox fills the+ * input by stringifying whatever item it was handed, and it derives that string+ * from an item's `label` or `value` — a shape like `{id, variants}` has neither,+ * so picking one wrote a serialized object into the field and every later check+ * then failed to match it against the catalogue. The wrapper deliberately does+ * not expose `itemToStringLabel`, so there is no hook to correct it with; the+ * item has to be the string the field stores. Variants are looked up for display+ * instead of being carried in the item.+ */+export function ModelCombobox({+ id,+ value,+ models,+ placeholder,+ disabled,+ onChange,+}: {+ id: string;+ value: string;+ models: LaunchProfileModel[];+ placeholder?: string;+ disabled?: boolean;+ onChange: (value: string) => void;+}) {+ const groups = useMemo(() => groupByProvider(models), [models]);+ const variantsOf = useMemo(+ () => new Map(models.map((model) => [model.id, model.variants])),+ [models]+ );+ const [open, setOpen] = useState(false);++ return (+ <Combobox+ items={groups}+ // The typed text is the value: picking an item fills the box, and what is+ // in the box is what gets saved, listed or not.+ inputValue={value}+ onInputValueChange={(next: string) => {+ onChange(next);+ // Typing has to open the list, and does not on its own here: the input+ // value is controlled, so the combobox treats the change as programmatic+ // rather than as someone typing, and stays shut. Without this the list+ // only ever appeared via the chevron.+ setOpen(true);+ }}+ onValueChange={(next: string | null) => onChange(next ?? '')}+ open={open}+ onOpenChange={setOpen}+ openOnInputClick+ >+ <ComboboxInput id={id} placeholder={placeholder} disabled={disabled} />+ <ComboboxContent>+ <ComboboxList>+ {(group: ProviderGroup) => (+ <ComboboxGroup key={group.value} items={group.items}>+ <ComboboxLabel>{group.value}</ComboboxLabel>+ <ComboboxCollection>+ {(modelId: string) => (+ <ComboboxItem key={modelId} value={modelId}>+ <span className="truncate">{modelId}</span>+ {(variantsOf.get(modelId)?.length ?? 0) > 0 && (+ <span className="ml-auto shrink-0 pr-1 text-xs text-foreground-muted">+ {variantsOf.get(modelId)!.join(' · ')}+ </span>+ )}+ </ComboboxItem>+ )}+ </ComboboxCollection>+ </ComboboxGroup>+ )}+ </ComboboxList>+ {/* Not an error: a name that matches nothing is still allowed, and the+ field's own note says whether the host knows it. */}+ <ComboboxEmpty>No model of that name on this host.</ComboboxEmpty>+ </ComboboxContent>+ </Combobox>+ );+}++/**+ * Group model ids by their provider, each group's models in the order the host+ * listed them — that order is the host's own preference and is not ours to+ * re-sort.+ */+export function groupByProvider(models: LaunchProfileModel[]): ProviderGroup[] {+ const groups: ProviderGroup[] = [];+ for (const model of models) {+ const provider = model.id.split('/')[0] ?? '';+ const group = groups.find((candidate) => candidate.value === provider);+ if (group) group.items.push(model.id);+ else groups.push({ value: provider, items: [model.id] });+ }+ return groups;+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsxindex 828028b75..fbe8b3745 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx@@ -11,6 +11,11 @@ import {type FormState,type FormValue,} from '@renderer/features/locations/components/agent-definition-fields';+import {+ fieldCatalogueState,+ fieldWithCatalogue,+ type ModelCatalogueResult,+} from '@renderer/features/locations/components/agent-model-catalogue';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { isProvisioned } from '@renderer/features/sessions/stores/session-store';import { toast } from '@renderer/lib/hooks/use-toast';@@ -55,6 +60,35 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti});const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);+ // Where the provider keeps these settings, which decides whether a running+ // session can be brought onto them. Asked of the provider rather than inferred+ // from its id.+ const { data: surface } = useQuery({+ queryKey: ['agentAdvancedSurface', providerId],+ queryFn: () =>+ providerId ? rpc.agents.advancedSurface({ providerId }) : Promise.resolve('none' as const),+ enabled: !!providerId,+ });++ const { data: locations } = useQuery({+ queryKey: ['locations'],+ queryFn: () => rpc.locations.getLocations(),+ });+ const location = (locations ?? []).find((l) => l.id === locationId);++ // What the agent's own host offers, for the fields bound to it. Fetched per+ // host rather than per keystroke: it shells out to the provider CLI, over SSH+ // for a remote agent.+ const { data: catalogue } = useQuery({+ queryKey: ['agent-model-catalogue', providerId, location?.sshHost ?? 'local', location?.dir],+ queryFn: (): Promise<ModelCatalogueResult> =>+ providerId && location+ ? rpc.agents.modelCatalogue({ providerId, sshHost: location.sshHost, dir: location.dir })+ : Promise.resolve({ kind: 'unavailable', reason: 'No host to ask.' }),+ enabled: !!providerId && !!location && editable,+ staleTime: 60_000,+ });+const { data: current } = useQuery({queryKey: ['agent-advanced-config', agentId],queryFn: () => (agentId ? rpc.agents.readAdvancedConfig({ agentId }) : Promise.resolve(null)),@@ -153,11 +187,12 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetticonst setField = (key: string, value: FormValue) =>setForm((prev) => ({ ...prev, [key]: value }));- // Only Codex is offered a restart here. Its profile is provably read once, at- // spawn, and its resume is verified to carry the new profile. Claude reads its- // definition at launch too and very likely wants the same treatment, but that- // is a change to Claude's behaviour and is being raised on its own.- const restartable = providerId === 'codex';+ // A launch profile is read once, when the session starts, so a change cannot+ // reach a running session without one — and a resume carries the new profile,+ // which is what makes the restart safe to offer. A repo-agent definition+ // (Claude) reads at launch too and very likely wants the same treatment, but+ // that is a change to Claude's behaviour and is being raised on its own.+ const restartable = surface === 'launch-profile';const showStaleNotice = restartable && staleSessionIds.length > 0 && (dirty || save.isSuccess);return (@@ -167,22 +202,37 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSettiThe agent's model, reasoning effort, tools, and system prompt. The agent name is fixed.</FieldDescription><div className="flex flex-col gap-4 rounded-md border border-border px-3 py-3">- {fields.map((field) => (- <Field key={field.key}>- <FieldLabel htmlFor={`agent-advanced-${field.key}`}>- {field.label}- {field.required || field.type === 'boolean' ? '' : ' (optional)'}- </FieldLabel>- <DefinitionFieldInput- field={field}- value={form[field.key] ?? (field.type === 'boolean' ? false : '')}- onChange={(value) => setField(field.key, value)}- />- {field.help && (- <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>- )}- </Field>- ))}+ {fields.map((field) => {+ const catalogueState = fieldCatalogueState(field, form, catalogue);+ const rendered = fieldWithCatalogue(field, catalogueState);+ return (+ <Field key={field.key}>+ <FieldLabel htmlFor={`agent-advanced-${field.key}`}>+ {field.label}+ {field.required || field.type === 'boolean' ? '' : ' (optional)'}+ </FieldLabel>+ <DefinitionFieldInput+ field={rendered}+ value={form[field.key] ?? (field.type === 'boolean' ? false : '')}+ disabled={catalogueState.disabled}+ suggestions={catalogueState.suggestions}+ onChange={(value) => setField(field.key, value)}+ />+ {field.help && (+ <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>+ )}+ {catalogueState.note && (+ <FieldDescription+ className={+ catalogueState.warning ? 'text-foreground-warning' : 'text-foreground-muted'+ }+ >+ {catalogueState.note}+ </FieldDescription>+ )}+ </Field>+ );+ })}<div className="flex justify-end"><Buttontype="button"@@ -200,7 +250,7 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti{staleSessionIds.length === 1? 'A session is running': `${staleSessionIds.length} sessions are running`}{' '}- on the previous configuration — Codex reads this only when a session starts.{' '}+ on the previous configuration — it is read only when a session starts.{' '}{dirty? 'Save, then Restart to apply it now.': 'It applies to the next session — or use Restart to apply it now (the conversation is resumed).'}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox-select.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox-select.test.tsxnew file mode 100644index 000000000..2c4a4af61--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox-select.test.tsx@@ -0,0 +1,172 @@+import { act, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++import { ModelCombobox } from '@renderer/features/locations/components/model-combobox';++/**+ * Picking a model from the list has to put the model's id in the box.+ *+ * It did not: the list was built from model objects, and the combobox fills the+ * input by stringifying the item it was given, so choosing one wrote+ * `[object Object]`. Every subsequent check then failed to match it against the+ * catalogue, so the field warned about a model the user had just picked from+ * that same catalogue.+ */+const MODELS = [+ { id: 'ollama/gemma4:latest', variants: [] },+ { id: 'google/gemini-2.5-flash', variants: ['high', 'max'] },+];++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++/**+ * A harness that actually re-renders on change.+ *+ * The field is controlled, so a test that records changes without feeding them+ * back leaves the input showing its initial value and the combobox reacting to+ * a value the user never sees. That harness reported the list as broken when it+ * was not, and would equally have hidden a real break.+ */+function Harness({ onChange, initial }: { onChange: (value: string) => void; initial: string }) {+ const [value, setValue] = useState(initial);+ return (+ <ModelCombobox+ id="model"+ value={value}+ models={MODELS}+ onChange={(next) => {+ setValue(next);+ onChange(next);+ }}+ />+ );+}++async function renderCombobox(onChange: (value: string) => void, value = '') {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => {+ root!.render(<Harness onChange={onChange} initial={value} />);+ });+ return container;+}++/** Type into the field the way a person does, as one controlled change. */+async function typeInto(host: HTMLElement, text: string) {+ const input = host.querySelector('input')!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ window.HTMLInputElement.prototype,+ 'value'+ )!.set!;+ setter.call(input, text);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+ return input;+}++const shownItems = () =>+ Array.from(document.querySelectorAll('[data-slot="combobox-item"]')).map(+ (node) => node.textContent ?? ''+ );++/**+ * Open the popup the way a user does, and return its rendered options.+ *+ * A bare `.click()` is not enough — the combobox opens on the pointer sequence,+ * and a test that only clicks leaves it shut, then finds no items and concludes+ * nothing is wrong. That is how a broken list passed review.+ */+async function openList(host: HTMLElement): Promise<HTMLElement[]> {+ const trigger = host.querySelector('button')!;+ await act(async () => {+ for (const type of ['pointerdown', 'pointerup'] as const) {+ trigger.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0 }));+ }+ for (const type of ['mousedown', 'mouseup'] as const) {+ trigger.dispatchEvent(new MouseEvent(type, { bubbles: true, button: 0 }));+ }+ trigger.click();+ });++ const input = host.querySelector('input')!;+ expect(input.getAttribute('aria-expanded')).toBe('true');+ // The popup is portalled, so it is not inside `host`.+ return Array.from(document.querySelectorAll('[data-slot="combobox-item"]'));+}++describe('picking a model from the list', () => {+ it('puts the model id in the box, not the object behind it', async () => {+ const seen: string[] = [];+ const host = await renderCombobox((next) => seen.push(next));++ const items = await openList(host);+ expect(items.length).toBeGreaterThan(0);++ const gemma = items.find((item) => item.textContent?.includes('ollama/gemma4:latest'));+ expect(gemma).toBeDefined();+ await act(async () => gemma!.click());++ expect(seen).toContain('ollama/gemma4:latest');+ for (const value of seen) {+ expect(value).not.toContain('object Object');+ expect(value).not.toContain('{');+ }+ });++ it('lists every model the host offers', async () => {+ const host = await renderCombobox(() => {});+ const items = await openList(host);+ const text = items.map((item) => item.textContent ?? '').join('\n');++ for (const model of MODELS) expect(text).toContain(model.id);+ });++ it('shows what a model reasons with, so the variant choice is predictable', async () => {+ const host = await renderCombobox(() => {});+ const items = await openList(host);++ const flash = items.find((item) => item.textContent?.includes('google/gemini-2.5-flash'));+ expect(flash?.textContent).toContain('high');+ expect(flash?.textContent).toContain('max');+ });+});++describe('typing in the model field', () => {+ it('opens the list and narrows it to what matches', async () => {+ // This did not work: the field is controlled, so the combobox read a typed+ // change as programmatic and stayed shut. The list was reachable only via+ // the chevron, which is not where anyone looks.+ const host = await renderCombobox(() => {});+ const input = await typeInto(host, 'oll');++ expect(input.getAttribute('aria-expanded')).toBe('true');+ expect(shownItems()).toEqual(['ollama/gemma4:latest']);+ });++ it('keeps what was typed, even with nothing to match it', async () => {+ const host = await renderCombobox(() => {});+ const input = await typeInto(host, 'ollama/not-pulled-yet');++ expect(input.value).toBe('ollama/not-pulled-yet');+ expect(shownItems()).toEqual([]);+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox.test.tsxnew file mode 100644index 000000000..eff7a96a5--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/model-combobox.test.tsx@@ -0,0 +1,115 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';++// The combobox's siblings reach the renderer IPC bridge at import time, which+// only exists inside Electron. Hoisted so it is in place before those modules+// are evaluated. Nothing under test calls through it.+vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++import { DefinitionFieldInput } from '@renderer/features/locations/components/agent-definition-fields';++/**+ * The model field has to stay typeable.+ *+ * The host catalogue is a snapshot of a machine that changes without us — a+ * model can be pulled a second after it was read — so the list is a shortcut,+ * not a constraint. A `select` here would have made an unlisted model+ * unreachable, which is why this renders as a combobox and why that is worth+ * pinning in a real browser rather than asserting on props.+ */+const MODELS = [+ { id: 'ollama/gemma4:latest', variants: [] },+ { id: 'google/gemini-2.5-flash', variants: ['high', 'max'] },+];++const FIELD = {+ key: 'model',+ label: 'Model',+ type: 'text' as const,+ placeholder: 'e.g. anthropic/claude-sonnet-4-5',+};++let container: HTMLDivElement | null = null;+let root: Root | null = null;++async function render(node: React.ReactNode) {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(node));+ return container;+}++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++describe('the model field, given a host catalogue', () => {+ it('renders a text box you can type into, not a fixed list', async () => {+ const host = await render(+ <DefinitionFieldInput field={FIELD} value="" suggestions={MODELS} onChange={() => {}} />+ );++ const input = host.querySelector('input');+ expect(input).not.toBeNull();+ expect(input?.tagName).toBe('INPUT');+ expect(host.querySelector('select')).toBeNull();+ });++ it('shows a model the host does not offer, rather than clearing it', async () => {+ // A value typed before the catalogue was read, or one for a model about to+ // be pulled, must survive being displayed.+ const host = await render(+ <DefinitionFieldInput+ field={FIELD}+ value="ollama/not-pulled-yet"+ suggestions={MODELS}+ onChange={() => {}}+ />+ );++ expect(host.querySelector('input')?.value).toBe('ollama/not-pulled-yet');+ });++ it('reports what was typed, including a name not in the catalogue', async () => {+ const seen: unknown[] = [];+ const host = await render(+ <DefinitionFieldInput+ field={FIELD}+ value=""+ suggestions={MODELS}+ onChange={(next) => seen.push(next)}+ />+ );++ const input = host.querySelector('input')!;+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(+ window.HTMLInputElement.prototype,+ 'value'+ )!.set!;+ setter.call(input, 'ollama/brand-new');+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });++ expect(seen).toContain('ollama/brand-new');+ });++ it('falls back to a plain input when there is no catalogue to offer', async () => {+ const host = await render(+ <DefinitionFieldInput field={FIELD} value="typed" onChange={() => {}} />+ );++ expect(host.querySelector('input')?.value).toBe('typed');+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.tsindex 9eacdf300..6a2790b35 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts@@ -8,10 +8,39 @@ import {describe('agentProviderConfig schema', () => {it('parses a versioned config and rejects an unversioned one', () => {- const ok = agentProviderConfig.safeParse({ version: '1', model: 'gpt-5.6-terra' });- expect(ok).toEqual({ status: 'ok', data: { version: '1', model: 'gpt-5.6-terra' } });+ const config = { version: '2', providerId: 'codex', values: { model: 'gpt-5.6-terra' } };+ expect(agentProviderConfig.safeParse(config)).toEqual({ status: 'ok', data: config });- expect(agentProviderConfig.safeParse({ model: 'x' }).status).not.toBe('ok');+ expect(agentProviderConfig.safeParse({ values: { model: 'x' } }).status).not.toBe('ok');+ });++ it('upgrades a stored v1 row into the provider-keyed shape', () => {+ // Codex was the only provider with launch-profile fields when v1 was+ // written, so every v1 row is a Codex specialization — which is what lets+ // the upgrade name the provider rather than asking for it.+ const result = agentProviderConfig.safeParse({+ version: '1',+ model: 'o3',+ effort: 'high',+ webSearch: 'false',+ instructions: 'be terse',+ });++ expect(result).toEqual({+ status: 'ok',+ data: {+ version: '2',+ providerId: 'codex',+ values: { model: 'o3', effort: 'high', webSearch: 'false', instructions: 'be terse' },+ },+ });+ });++ it('upgrades a v1 row that set nothing, rather than failing it', () => {+ expect(agentProviderConfig.safeParse({ version: '1' })).toEqual({+ status: 'ok',+ data: { version: '2', providerId: 'codex', values: {} },+ });});});@@ -19,13 +48,16 @@ describe('toSwitchSpecialization', () => {it('passes every stored setting through under the key the profile writer reads', () => {expect(toSwitchSpecialization({- version: '1',- model: 'o3',- effort: 'high',- verbosity: 'low',- reasoningSummary: 'concise',- webSearch: 'true',- instructions: 'be terse',+ version: '2',+ providerId: 'codex',+ values: {+ model: 'o3',+ effort: 'high',+ verbosity: 'low',+ reasoningSummary: 'concise',+ webSearch: 'true',+ instructions: 'be terse',+ },})).toEqual({model: 'o3',@@ -37,54 +69,81 @@ describe('toSwitchSpecialization', () => {});});+ it('carries a provider whose keys are its own, not Codex’s', () => {+ expect(+ toSwitchSpecialization({+ version: '2',+ providerId: 'opencode',+ values: { variant: 'high', temperature: '0.2', topP: '0.9' },+ })+ ).toEqual({ variant: 'high', temperature: '0.2', topP: '0.9' });+ });+it('drops empty/whitespace fields so the base default stands', () => {expect(- toSwitchSpecialization({ version: '1', model: ' ', effort: '', instructions: 'x' })+ toSwitchSpecialization({+ version: '2',+ providerId: 'codex',+ values: { model: ' ', effort: '', instructions: 'x' },+ })).toEqual({ instructions: 'x' });});it('returns undefined when nothing is set or the config is absent', () => {expect(toSwitchSpecialization(null)).toBeUndefined();expect(toSwitchSpecialization(undefined)).toBeUndefined();- expect(toSwitchSpecialization({ version: '1' })).toBeUndefined();- expect(toSwitchSpecialization({ version: '1', model: ' ' })).toBeUndefined();+ expect(+ toSwitchSpecialization({ version: '2', providerId: 'codex', values: {} })+ ).toBeUndefined();+ expect(+ toSwitchSpecialization({ version: '2', providerId: 'codex', values: { model: ' ' } })+ ).toBeUndefined();});});describe('form attributes ↔ stored config', () => {it('round-trips every setting', () => {const config = {- version: '1' as const,- model: 'o3',- effort: 'none',- verbosity: 'high',- reasoningSummary: 'detailed',- webSearch: 'false',- instructions: 'be terse',+ version: '2' as const,+ providerId: 'codex',+ values: {+ model: 'o3',+ effort: 'none',+ verbosity: 'high',+ reasoningSummary: 'detailed',+ webSearch: 'false',+ instructions: 'be terse',+ },};- expect(providerConfigFromAttributes(attributesFromProviderConfig(config))).toEqual(config);+ expect(+ providerConfigFromAttributes(config.providerId, attributesFromProviderConfig(config))+ ).toEqual(config);});it('seeds a blank form from no config, and reads it back as nothing set', () => {const attributes = attributesFromProviderConfig(null);- expect(attributes).toEqual({- model: '',- effort: '',- verbosity: '',- reasoningSummary: '',- webSearch: '',- instructions: '',+ expect(attributes).toEqual({});+ expect(providerConfigFromAttributes('codex', attributes)).toBeNull();+ });++ it('stores a number field as a string rather than dropping it', () => {+ // The form hands numeric fields back as numbers (null when blank), so a+ // stored config that only took strings would silently lose them.+ expect(providerConfigFromAttributes('opencode', { temperature: 0.2, maxSteps: null })).toEqual({+ version: '2',+ providerId: 'opencode',+ values: { temperature: '0.2' },});- expect(providerConfigFromAttributes(attributes)).toBeNull();});it('keeps web search off as a stored value — unset and off are different', () => {- expect(providerConfigFromAttributes({ webSearch: 'false' })).toEqual({- version: '1',- webSearch: 'false',+ expect(providerConfigFromAttributes('codex', { webSearch: 'false' })).toEqual({+ version: '2',+ providerId: 'codex',+ values: { webSearch: 'false' },});- expect(providerConfigFromAttributes({ webSearch: '' })).toBeNull();+ expect(providerConfigFromAttributes('codex', { webSearch: '' })).toBeNull();});});diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.tsindex e43115c8d..613e29d50 100644--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts@@ -6,47 +6,58 @@ import z from 'zod';import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';/**- * Per-agent, provider-specific launch configuration. Today this carries the- * Codex specialization folded into the agent's Codex profile at launch — model,- * reasoning effort, verbosity, reasoning summary, web search, and a- * system-prompt/instructions body.+ * Per-agent, provider-specific launch configuration: the values folded into the+ * agent's launch profile at spawn.*- * Every field is optional and an unset one is omitted from the profile, leaving- * the provider's own configuration to decide. That is deliberate for the on/off- * settings too: `webSearch` unset is not `webSearch` off — the first defers to- * the user's `~/.codex/config.toml`, the second overrides it. That is why it is- * a string rather than a boolean, since a boolean has no "unset".+ * The keys are whatever the provider declares in `mcp.launchProfileFields()`, so+ * this schema does not name them. Two providers do not agree on what a per-agent+ * setting even is — Codex has a reasoning-effort enum, a verbosity and a+ * reasoning summary; OpenCode has none of those, and instead has a model-specific+ * variant, a temperature, a top-p and a step cap. A fixed field list would be one+ * provider's vocabulary imposed on the rest, growing a column of mostly-blank+ * slots with every provider added.+ *+ * Every value is a string and an unset one is omitted, leaving the provider's own+ * configuration to decide. That is deliberate for the on/off settings too: web+ * search unset is not web search off — the first defers to the user's base+ * config, the second overrides it. That is why such a setting is collected as a+ * select with a blank choice rather than a checkbox, which has no "unset".** Stored as a versioned JSON column on the agent so the shape can evolve without- * a migration per field, mirroring `sessions.config`. New fields are added as- * optional to the current version: a row written before they existed simply has- * none of them.+ * a migration per change, mirroring `sessions.config`.+ */+const agentProviderConfigV2 = z.object({+ version: z.literal('2'),+ /**+ * The provider whose field keys {@link values} are named for. Recorded so a row+ * is readable on its own and so the v1 upgrade can state what it assumed, not+ * to gate reading: a profile writer only consumes the keys it declares, so a+ * key it does not know is ignored either way.+ */+ providerId: z.string(),+ /** Field key → value, as declared by that provider's `launchProfileFields()`. */+ values: z.record(z.string(), z.string()),+});++/**+ * The original shape: Codex's six settings as named columns.+ *+ * Kept so stored rows still parse. Only Codex ever declared launch-profile+ * fields, so every v1 row is a Codex specialization — which is what the upgrade+ * below relies on.*/const agentProviderConfigV1 = z.object({version: z.literal('1'),- /** Provider model id, e.g. a Codex `model` override. */model: z.string().optional(),- /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` value. */effort: z.string().optional(),- /** How much prose the model writes, e.g. Codex `model_verbosity`. */verbosity: z.string().optional(),- /** How much reasoning is summarised back, e.g. Codex `model_reasoning_summary`. */reasoningSummary: z.string().optional(),- /** `"true"` / `"false"` / unset — e.g. Codex `tools.web_search`. */webSearch: z.string().optional(),- /** System-prompt/instructions body, carried in the agent's Codex profile as- * `developer_instructions` — additive to Codex's own instructions. */instructions: z.string().optional(),});-export const agentProviderConfig = defineVersionedSchema()- .initial('1', agentProviderConfigV1)- .build();--export type AgentProviderConfig = typeof agentProviderConfig.Type;--/** The stored keys, which are also the field keys the provider declares. */-const CONFIG_KEYS = [+/** The keys version 1 stored, in the order Codex declares them. */+const V1_KEYS = ['model','effort','verbosity',@@ -55,16 +66,38 @@ const CONFIG_KEYS = ['instructions',] as const;+/**+ * Normalise a collected form value to the stored string form, or `undefined` for+ * "not set".+ *+ * Number fields arrive as numbers (or `null` when blank) and on/off fields as+ * strings, so this coerces rather than requiring a string. `NaN` is dropped+ * rather than stored as `"NaN"`: an unparseable number is not a setting.+ */const clean = (value: unknown): string | undefined => {+ if (typeof value === 'number') return Number.isFinite(value) ? String(value) : undefined;const trimmed = typeof value === 'string' ? value.trim() : '';return trimmed ? trimmed : undefined;};+export const agentProviderConfig = defineVersionedSchema()+ .initial('1', agentProviderConfigV1)+ .version('2', agentProviderConfigV2, (v1) => ({+ version: '2' as const,+ // Codex is the only provider that could have written a v1 row.+ providerId: 'codex',+ values: Object.fromEntries(+ V1_KEYS.map((key) => [key, clean(v1[key])]).filter(([, value]) => value !== undefined)+ ) as Record<string, string>,+ }))+ .build();++export type AgentProviderConfig = typeof agentProviderConfig.Type;+/*** Map stored per-agent config to the launch-time specialization the profile- * builder consumes. Empty/whitespace values are dropped so the profile omits- * them and the base default stands. Returns `undefined` when nothing is set, so- * callers pass no specialization at all.+ * builder consumes. Returns `undefined` when nothing is set, so callers pass no+ * specialization at all and the agent gets no profile.*/export function toSwitchSpecialization(config: AgentProviderConfig | null | undefined@@ -72,38 +105,45 @@ export function toSwitchSpecialization(if (!config) return undefined;const specialization: SwitchLaunchSpecialization = {};- for (const key of CONFIG_KEYS) {- const value = clean(config[key]);- if (value !== undefined) specialization[key] = value;+ // `values` is defaulted rather than assumed: outside dev the versioned schema+ // trusts what was stored instead of re-validating it, so a row written by a+ // future version is a launch that should carry no specialization, not one that+ // throws on the way to spawning the agent.+ for (const [key, value] of Object.entries(config.values ?? {})) {+ const cleaned = clean(value);+ if (cleaned !== undefined) specialization[key] = cleaned;}return Object.keys(specialization).length > 0 ? specialization : undefined;}-/** Seed the advanced-configuration form from an agent's stored config. */+/**+ * Seed the advanced-configuration form from an agent's stored config. Only the+ * stored keys are returned; the form fills the rest from the provider's declared+ * fields, so a setting added after the row was written shows as blank rather+ * than missing.+ */export function attributesFromProviderConfig(config: AgentProviderConfig | null | undefined): RepoAgentAttributes {const attributes: RepoAgentAttributes = {};- for (const key of CONFIG_KEYS) attributes[key] = config?.[key] ?? '';+ for (const [key, value] of Object.entries(config?.values ?? {})) attributes[key] = value;return attributes;}/*** Build the stored config from submitted form attributes. Null when every field- * is blank: an agent that specializes nothing gets no profile and no `--profile`- * argv, rather than an empty one.+ * is blank: an agent that specializes nothing gets no profile at all, rather than+ * an empty one and the argv or environment that would load it.*/export function providerConfigFromAttributes(+ providerId: string,attributes: RepoAgentAttributes): AgentProviderConfig | null {- const config: AgentProviderConfig = { version: '1' };- let set = false;- for (const key of CONFIG_KEYS) {- const value = clean(attributes[key]);- if (value === undefined) continue;- config[key] = value;- set = true;+ const values: Record<string, string> = {};+ for (const [key, raw] of Object.entries(attributes)) {+ const value = clean(raw);+ if (value !== undefined) values[key] = value;}- return set ? config : null;+ return Object.keys(values).length > 0 ? { version: '2', providerId, values } : null;}diff --git a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.tsindex c16317c83..76db41ff8 100644--- a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts+++ b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.test.ts@@ -1,6 +1,8 @@+import { LAUNCH_PROFILE_HOME_PLACEHOLDER } from '@switch-console/core/agents/plugins';import { describe, expect, it } from 'vitest';import {type AgentLaunchSpec,+ HOME_PLACEHOLDER,INITIAL_PROMPT_PLACEHOLDER,materializeAgentCommand,SESSION_ID_PLACEHOLDER,@@ -29,6 +31,7 @@ describe('materializeAgentCommand', () => {sessionId: 'session-9',initialPrompt: 'connect to switch room room-x',extraEnv: {},+ homeDir: '/home/agent',});expect(cmd.command).toBe('/usr/bin/claude');expect(cmd.args).toEqual([@@ -44,6 +47,7 @@ describe('materializeAgentCommand', () => {sessionId: 'c',initialPrompt: 'p',extraEnv: { SHARED: 'override', HOOK: 'x' },+ homeDir: '/home/agent',});expect(cmd.env).toEqual({ BASE: '1', SHARED: 'override', HOOK: 'x' });});@@ -59,6 +63,7 @@ describe('materializeAgentCommand', () => {sessionId: 'c',initialPrompt: 'connect to switch room room-x',extraEnv: {},+ homeDir: '/home/agent',});@@ -71,6 +76,7 @@ describe('materializeAgentCommand', () => {sessionId: 'c',initialPrompt: 'p',extraEnv: {},+ homeDir: '/home/agent',})).toThrow(INITIAL_PROMPT_PLACEHOLDER);});@@ -83,8 +89,44 @@ describe('materializeAgentCommand', () => {sessionId: 's1',initialPrompt: 'p',extraEnv: {},+ homeDir: '/home/agent',})).toThrow(/unsubstituted placeholder/);});});++describe('HOME_PLACEHOLDER', () => {+ it('is the same token the plugin packages emit', () => {+ // The sidecar is a standalone bundle and deliberately imports nothing from+ // the plugin packages, so the token it substitutes is a second declaration+ // of the one plugins write. If they drift, a remote OpenCode session gets a+ // config path that was never completed.+ expect(HOME_PLACEHOLDER).toBe(LAUNCH_PROFILE_HOME_PLACEHOLDER);+ });++ it('resolves a profile env value naming a baked launch file', () => {+ const cmd = materializeAgentCommand(+ spec({ env: { OPENCODE_CONFIG: `${HOME_PLACEHOLDER}/.config/opencode/switch/a.json` } }),+ {+ sessionId: 's',+ initialPrompt: 'p',+ extraEnv: {},+ homeDir: '/home/agent',+ }+ );++ expect(cmd.env.OPENCODE_CONFIG).toBe('/home/agent/.config/opencode/switch/a.json');+ });++ it('fails the spawn rather than passing an unsubstituted placeholder to the agent', () => {+ expect(() =>+ materializeAgentCommand(spec({ env: { SOMETHING: '__SWITCHDASH_UNKNOWN__/x' } }), {+ sessionId: 's',+ initialPrompt: 'p',+ extraEnv: {},+ homeDir: '/home/agent',+ })+ ).toThrow(/unsubstituted placeholder in env SOMETHING/);+ });+});diff --git a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.tsindex f6b9ee41d..297b47255 100644--- a/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts+++ b/console/apps/switch-console-desktop/src/sidecar/agent-launch-spec.ts@@ -52,6 +52,20 @@ export const SESSION_ID_PLACEHOLDER = '__SWITCHDASH_SESSION_ID__';/** Argv token Switch Console emits in place of the fresh session's initial prompt. */export const INITIAL_PROMPT_PLACEHOLDER = '__SWITCHDASH_INITIAL_PROMPT__';+/**+ * Token a launch profile's env writes in place of the agent's home directory.+ *+ * A profile's files are home-relative, but a host that names its config through+ * the environment (OpenCode: `OPENCODE_CONFIG`) needs an absolute path, and+ * Switch Console bakes the spec without knowing the VM's home — the sidecar+ * resolves that when it writes {@link AgentLaunchSpec.launchFiles}.+ *+ * Declared here rather than imported because the sidecar is a standalone bundle+ * with no dependency on the plugin packages. `LAUNCH_PROFILE_HOME_PLACEHOLDER` in+ * `@switch-console/core` is the copy plugins emit, and a test pins the two equal.+ */+export const HOME_PLACEHOLDER = '__SWITCHDASH_HOME__';+/** Shared prefix of every launch-spec placeholder, used to catch leftovers. */const PLACEHOLDER_PREFIX = '__SWITCHDASH_';@@ -89,6 +103,8 @@ export function materializeAgentCommand(sessionId: string;initialPrompt: string;extraEnv: Record<string, string>;+ /** The VM's home directory, for env naming a baked launch file by absolute path. */+ homeDir: string;}): MaterializedAgentCommand {const substitutions: Record<string, string> = {@@ -107,5 +123,23 @@ export function materializeAgentCommand(throw new Error(`agent launch spec has an unsubstituted placeholder in argv: ${unresolved}`);}- return { command: spec.command, args, env: { ...spec.env, ...params.extraEnv } };+ // A launch profile's env may name one of the files the sidecar writes under+ // the home directory. Switch Console bakes the spec without knowing the VM's+ // home, so the path arrives with the home placeholder in it and is completed+ // here, where `launchFiles` are written.+ const env = Object.fromEntries(+ Object.entries({ ...spec.env, ...params.extraEnv }).map(([key, value]) => [+ key,+ value.split(HOME_PLACEHOLDER).join(params.homeDir),+ ])+ );++ const unresolvedEnv = Object.entries(env).find(([, value]) => value.includes(PLACEHOLDER_PREFIX));+ if (unresolvedEnv !== undefined) {+ throw new Error(+ `agent launch spec has an unsubstituted placeholder in env ${unresolvedEnv[0]}: ${unresolvedEnv[1]}`+ );+ }++ return { command: spec.command, args, env };}diff --git a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts b/console/apps/switch-console-desktop/src/sidecar/session-spawner.tsindex 4cb583474..602321f33 100644--- a/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts+++ b/console/apps/switch-console-desktop/src/sidecar/session-spawner.ts@@ -9,7 +9,11 @@ import { getPlugin } from '@main/core/providers/plugin-registry';import { quoteShellArg } from '@main/utils/shellEscape';import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';import { asPtyProviderId, makePtyId } from '@shared/core/pty/ptyId';-import { type AgentLaunchSpec, materializeAgentCommand } from './agent-launch-spec';+import {+ type AgentLaunchSpec,+ HOME_PLACEHOLDER,+ materializeAgentCommand,+} from './agent-launch-spec';import { atomicWriteFile } from './atomic-file';import type { SessionSpawner, WatcherLogger } from './notification-watcher';import { makeAgentTmuxSessionName } from './vm-tmux';@@ -182,6 +186,7 @@ export class InProcessSessionSpawner implements SessionSpawner {sessionId,initialPrompt: `connect to switch room ${roomId}`,extraEnv: hookEnv,+ homeDir: homedir(),});await this.writeLaunchFiles();@@ -204,7 +209,10 @@ export class InProcessSessionSpawner implements SessionSpawner {for (const file of this.spec.launchFiles ?? []) {const absPath = join(homedir(), file.homeRelativePath);await mkdir(dirname(absPath), { recursive: true });- await atomicWriteFile(absPath, file.content);+ // A baked file may name a sibling by absolute path (OpenCode's config+ // points at its instructions file), which Switch Console could not write+ // without knowing this VM's home.+ await atomicWriteFile(absPath, file.content.split(HOME_PLACEHOLDER).join(homedir()));}}diff --git a/console/packages/core/src/agents/plugins/capabilities/mcp.ts b/console/packages/core/src/agents/plugins/capabilities/mcp.tsindex cb41ecd39..9bf9a43f3 100644--- a/console/packages/core/src/agents/plugins/capabilities/mcp.ts+++ b/console/packages/core/src/agents/plugins/capabilities/mcp.ts@@ -12,48 +12,116 @@ export type SwitchLaunchProfileFile = {};/**- * A per-agent launch config — the files to write plus the argv that loads them —- * the result of {@link IMcpBehavior.launchProfile}. Pure data so it can be- * written directly (local/SSH runtimes) or baked into a precomputed launch spec- * and written by the headless VM sidecar, which has no plugin registry. A list- * rather than a single file so a host that needs the config split across several- * is not a change to this type; Codex today returns exactly one.+ * A per-agent launch config — what to write, what argv loads it, and what+ * environment it needs — the result of {@link IMcpBehavior.launchProfile}. Pure+ * data so it can be written directly (local/SSH runtimes) or baked into a+ * precomputed launch spec and written by the headless VM sidecar, which has no+ * plugin registry. A list rather than a single file so a host that needs the+ * config split across several is not a change to this type; Codex returns one+ * file, OpenCode two.*/export type SwitchLaunchProfile = {files: SwitchLaunchProfileFile[];/** Extra argv the launch command needs to load the profile. */args: string[];+ /**+ * Extra environment the launch command needs to load the profile, merged over+ * the provider's own launch env.+ *+ * Not every host can be pointed at a config file from the command line. Codex+ * takes `--profile <name>`; OpenCode has no equivalent flag at all and names+ * its extra config through `OPENCODE_CONFIG`, so for that host the environment+ * is the only way in. Values should stay short — the SSH and tmux paths render+ * the launch as a shell string — so a profile puts its content in a file and+ * uses this to point at it.+ *+ * A value naming one of the profile's own files writes+ * {@link LAUNCH_PROFILE_HOME_PLACEHOLDER} where the home directory belongs;+ * see that constant for why it cannot be resolved here.+ */+ env?: Record<string, string>;};/**- * Optional per-agent specialization folded into the launch profile.+ * Token a launch profile writes in place of the agent's home directory, in its+ * env values and in its file content, substituted by whichever launch surface+ * applies the profile.+ *+ * A profile's files are addressed relative to home, but a host that names one+ * absolutely — OpenCode's `OPENCODE_CONFIG`, and the instructions path inside+ * that config — needs the real directory, and the profile builder cannot form+ * one: it is pure, and for a remote auto-session it runs on the desktop, which+ * does not know the VM's home directory — the sidecar resolves that when it+ * writes the files. So the profile says "home" and each surface fills in its own.+ *+ * It shares the launch spec's placeholder prefix, so a substitution missed on the+ * remote path is caught by the spec's leftover-placeholder check rather than+ * reaching the agent as a literal.+ */+export const LAUNCH_PROFILE_HOME_PLACEHOLDER = '__SWITCHDASH_HOME__';++/** Replace {@link LAUNCH_PROFILE_HOME_PLACEHOLDER} in one profile string. */+export function resolveLaunchProfileHome(value: string, homeDir: string): string {+ return value.split(LAUNCH_PROFILE_HOME_PLACEHOLDER).join(homeDir);+}++/** Replace {@link LAUNCH_PROFILE_HOME_PLACEHOLDER} in a profile's env values. */+export function resolveLaunchProfileEnv(+ env: Record<string, string> | undefined,+ homeDir: string+): Record<string, string> {+ if (!env) return {};+ return Object.fromEntries(+ Object.entries(env).map(([key, value]) => [key, resolveLaunchProfileHome(value, homeDir)])+ );+}++/**+ * Optional per-agent specialization folded into the launch profile: the values+ * collected for the fields the provider declares in+ * {@link IMcpBehavior.launchProfileFields}, keyed by those fields' keys.*- * Every value is a string, and an absent or empty one means "not set" — the- * provider's own configuration decides. That matters for the on/off settings:- * omitting `webSearch` leaves the user's base config alone, which is not the- * same as setting it to `false`.+ * Deliberately open rather than a fixed set of names. Providers do not agree on+ * what a per-agent setting is — Codex's reasoning-effort enum, verbosity and+ * reasoning summary have no OpenCode equivalent, and OpenCode's model-specific+ * variant, temperature, top-p and step cap have no Codex one — so naming them+ * here would make one provider's vocabulary the type of all of them.*- * The keys are the field keys the provider declares in- * {@link IMcpBehavior.launchProfileFields}, so what the form collects and what- * the profile writer consumes are the same names end to end.+ * Every value is a string, and an absent or empty one means "not set": the+ * provider's own configuration decides. That matters for the on/off settings —+ * omitting a web-search value leaves the user's base config alone, which is not+ * the same as setting it off.*/-export type SwitchLaunchSpecialization = {- /** Model id, e.g. a Codex `model` override. */- model?: string;- /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` value. */- effort?: string;- /** How much prose the model writes (Codex: `model_verbosity`). */- verbosity?: string;- /** How much reasoning is summarised back (Codex: `model_reasoning_summary`). */- reasoningSummary?: string;- /** `"true"` / `"false"` / unset — whether the agent may search the web. */- webSearch?: string;- /** A system-prompt/instructions body, carried in the profile itself (Codex:- * `developer_instructions`), which adds to the host's own operating- * instructions rather than replacing them. */- instructions?: string;+export type SwitchLaunchSpecialization = Record<string, string | undefined>;++/**+ * A model the host offers, and the reasoning variants that model accepts.+ *+ * `id` is written the way the provider's model field is typed (OpenCode:+ * `provider/model`), so a typed value can be compared to the catalogue without+ * either side reformatting.+ *+ * `variants` is empty for a model with no reasoning control — every local model+ * seen so far, which is exactly the case the form needs to know about: an empty+ * list means the variant field has nothing to offer and should say so rather+ * than accept a value that will be ignored.+ */+export type LaunchProfileModel = {+ id: string;+ variants: string[];};+/**+ * Run a command on the host an agent runs on — the local machine or a remote+ * one — and return its stdout. Passed in rather than imported so a provider's+ * catalogue lookup works the same on both, and so it can be driven directly in a+ * test.+ */+export type LaunchProfileHostExec = (+ command: string,+ args: string[]+) => Promise<{ stdout: string }>;+export type IMcpBehavior = {readServers(fs: PluginFs): Promise<McpServerRegistration[]>;writeServers(fs: PluginFs, servers: McpServerRegistration[]): Promise<void>;@@ -72,18 +140,20 @@ export type IMcpBehavior = {* Claude Code leaves this undefined: it takes its specialization on argv.* Codex returns a per-agent profile (`~/.codex/<name>.config.toml`) and* `--profile <name>`, because free-form instructions cannot ride a command- * line that the SSH and tmux paths re-render as a shell string.+ * line that the SSH and tmux paths re-render as a shell string. OpenCode+ * returns a config file and the environment variable naming it, having no+ * profile flag to load it with.** Returns `null` when there is nothing to specialize.*/- launchProfile?(- params: {- slug: string;- /** The agent's working directory, mixed into the profile name so two agents- * that share a name in different directories get distinct profiles. */- workingDir: string;- } & SwitchLaunchSpecialization- ): SwitchLaunchProfile | null;+ launchProfile?(params: {+ slug: string;+ /** The agent's working directory, mixed into the profile name so two agents+ * that share a name in different directories get distinct profiles. */+ workingDir: string;+ /** Collected values, keyed by the provider's own field keys. */+ values: SwitchLaunchSpecialization;+ }): SwitchLaunchProfile | null;/*** Home-relative paths the launch profile occupies, so the agent's teardown* (delete/rename) can remove them. Pure and identity-shaped — same `(slug,@@ -105,6 +175,23 @@ export type IMcpBehavior = {* Undefined for a provider that writes no profile.*/launchProfileFields?(): RepoAgentField[];+ /**+ * The models this host offers for {@link launchProfileFields}'s model field,+ * with the reasoning variants each accepts.+ *+ * Optional, and the form works without it: a provider that does not implement+ * this gets a plain text model field, which is where both providers started.+ * Implementing it turns that field into one the app can check what was typed+ * against, and lets a variant field offer the values the *chosen model*+ * actually takes — which for OpenCode is the only correct answer, since the+ * list differs per model and an unrecognised one is ignored in silence.+ *+ * Throwing is meaningful: it means the host could not be asked (the CLI is not+ * installed there, the connection failed). The caller says so and falls back+ * to plain text rather than reporting that the host offers no models, which+ * would flag every valid model as wrong.+ */+ launchProfileModels?(exec: LaunchProfileHostExec): Promise<LaunchProfileModel[]>;};export type McpServerRegistration = {diff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex 896d5bdde..a9844fb21 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -63,6 +63,26 @@ export type RepoAgentFieldType = 'text' | 'textarea' | 'select' | 'list' | 'numbexport type RepoAgentFieldOption = { value: string; label: string };+/**+ * Ties a field to the host's model catalogue (`mcp.launchProfileModels`), for a+ * setting whose valid values live on the machine the agent runs on rather than+ * in this descriptor.+ *+ * - `model` — the field names a model. What was typed is checked against the+ * catalogue and flagged when it is not there.+ * - `model-variant` — the field's choices are the variants of the model named by+ * `modelField`, so choosing a model decides them. A model that declares none+ * leaves the field with nothing to offer, which is worth saying rather than+ * accepting a value the host will ignore.+ *+ * Declared rather than inferred so the renderer stays generic: it knows "this+ * field is a model" and "this one follows that one", not which providers or+ * which key names.+ */+export type RepoAgentFieldCatalogue =+ | { kind: 'model' }+ | { kind: 'model-variant'; modelField: string };+/*** One editable attribute of an agent, declared by the agent provider. The* renderer builds the create/edit form from these descriptors, so the set of@@ -80,6 +100,12 @@ export type RepoAgentField = {help?: string;/** Choices for `select`. Include an empty-value option to mean "unset". */options?: RepoAgentFieldOption[];+ /**+ * Bind this field to the host's model catalogue. The field keeps its declared+ * `type` as the fallback: when the catalogue cannot be read, it renders as+ * declared and says why, rather than blocking on values it cannot check.+ */+ catalogue?: RepoAgentFieldCatalogue;};/** A single attribute value; shape depends on the field's `type`. */diff --git a/console/packages/core/src/agents/plugins/index.ts b/console/packages/core/src/agents/plugins/index.tsindex 505189f18..02f5a4c68 100644--- a/console/packages/core/src/agents/plugins/index.ts+++ b/console/packages/core/src/agents/plugins/index.ts@@ -72,11 +72,18 @@ export type { IHostDependencyBehavior } from '../../host-dependencies/capabilityexport type { IHooksBehavior } from './capabilities/hooks';export type {IMcpBehavior,+ LaunchProfileHostExec,+ LaunchProfileModel,McpServerRegistration,SwitchLaunchProfile,SwitchLaunchProfileFile,SwitchLaunchSpecialization,} from './capabilities/mcp';+export {+ LAUNCH_PROFILE_HOME_PLACEHOLDER,+ resolveLaunchProfileEnv,+ resolveLaunchProfileHome,+} from './capabilities/mcp';export type { IPlugins, PluginScope } from './capabilities/plugins';export type { ISessionsBehavior } from './capabilities/sessions';export {@@ -91,6 +98,7 @@ export type {RepoAgentAttributeValue,RepoAgentDefinition,RepoAgentField,+ RepoAgentFieldCatalogue,RepoAgentFieldOption,RepoAgentFieldType,RepoAgentsDescriptor,diff --git a/console/packages/plugins/src/agents/impl/codex/profile.test.ts b/console/packages/plugins/src/agents/impl/codex/profile.test.tsindex 5e2965829..f42101666 100644--- a/console/packages/plugins/src/agents/impl/codex/profile.test.ts+++ b/console/packages/plugins/src/agents/impl/codex/profile.test.ts@@ -104,7 +104,7 @@ describe('codexLaunchProfile', () => {const profile = codexLaunchProfile({slug: 'codex-hoot',workingDir: WD,- model: 'gpt-5.6-terra',+ values: { model: 'gpt-5.6-terra' },});expect(profile).not.toBeNull();expect(profile!.args).toEqual(['--profile', codexProfileName('codex-hoot', WD)]);@@ -127,7 +127,7 @@ describe('codexLaunchProfile', () => {const profile = codexLaunchProfile({slug: 'codex-hoot',workingDir: WD,- instructions,+ values: { instructions },})!;expect(profile.files).toHaveLength(1);@@ -139,7 +139,11 @@ describe('codexLaunchProfile', () => {});it('returns a profile for specialization alone', () => {- const profile = codexLaunchProfile({ slug: 'a', workingDir: WD, model: 'gpt-5.6-terra' });+ const profile = codexLaunchProfile({+ slug: 'a',+ workingDir: WD,+ values: { model: 'gpt-5.6-terra' },+ });expect(profile).not.toBeNull();expect(profile!.files[0].content).toContain('model = "gpt-5.6-terra"');expect(profile!.files[0].content).not.toContain('mcp_servers');@@ -148,7 +152,7 @@ describe('codexLaunchProfile', () => {it('returns null when there is nothing to specialize, rather than an empty profile', () => {// An agent on the defaults needs no file. Writing an empty one would still// put `--profile <name>` on the command line, pointing at nothing.- expect(codexLaunchProfile({ slug: 'a', workingDir: WD })).toBeNull();+ expect(codexLaunchProfile({ slug: 'a', workingDir: WD, values: {} })).toBeNull();});it('exposes the stable reasoning-effort levels', () => {@@ -182,7 +186,7 @@ describe('codexProfileName', () => {const profile = codexLaunchProfile({slug,workingDir: WD,- instructions: 'be terse',+ values: { instructions: 'be terse' },})!;const name = codexProfileName(slug, WD);diff --git a/console/packages/plugins/src/agents/impl/codex/profile.ts b/console/packages/plugins/src/agents/impl/codex/profile.tsindex 08ce634ad..1e4112b38 100644Binary files a/console/packages/plugins/src/agents/impl/codex/profile.ts and b/console/packages/plugins/src/agents/impl/codex/profile.ts differdiff --git a/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-google.txt b/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-google.txtnew file mode 100644index 000000000..e319a1aed--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-google.txt@@ -0,0 +1,126 @@+google/gemini-2.5-flash+{+ "id": "gemini-2.5-flash",+ "providerID": "google",+ "name": "Gemini 2.5 Flash",+ "family": "gemini-flash",+ "api": {+ "id": "gemini-2.5-flash",+ "url": "",+ "npm": "@ai-sdk/google"+ },+ "status": "active",+ "headers": {},+ "options": {},+ "cost": {+ "input": 0.3,+ "output": 2.5,+ "cache": {+ "read": 0.03,+ "write": 0+ }+ },+ "limit": {+ "context": 1048576,+ "output": 65536+ },+ "capabilities": {+ "temperature": true,+ "reasoning": true,+ "attachment": true,+ "toolcall": true,+ "input": {+ "text": true,+ "audio": true,+ "image": true,+ "video": true,+ "pdf": true+ },+ "output": {+ "text": true,+ "audio": false,+ "image": false,+ "video": false,+ "pdf": false+ },+ "interleaved": false+ },+ "release_date": "2025-06-17",+ "variants": {+ "high": {+ "thinkingConfig": {+ "includeThoughts": true,+ "thinkingBudget": 12288+ }+ },+ "max": {+ "thinkingConfig": {+ "includeThoughts": true,+ "thinkingBudget": 24576+ }+ }+ }+}+google/gemini-2.5-flash-lite+{+ "id": "gemini-2.5-flash-lite",+ "providerID": "google",+ "name": "Gemini 2.5 Flash-Lite",+ "family": "gemini-flash-lite",+ "api": {+ "id": "gemini-2.5-flash-lite",+ "url": "",+ "npm": "@ai-sdk/google"+ },+ "status": "active",+ "headers": {},+ "options": {},+ "cost": {+ "input": 0.1,+ "output": 0.4,+ "cache": {+ "read": 0.01,+ "write": 0+ }+ },+ "limit": {+ "context": 1048576,+ "output": 65536+ },+ "capabilities": {+ "temperature": true,+ "reasoning": true,+ "attachment": true,+ "toolcall": true,+ "input": {+ "text": true,+ "audio": true,+ "image": true,+ "video": true,+ "pdf": true+ },+ "output": {+ "text": true,+ "audio": false,+ "image": false,+ "video": false,+ "pdf": false+ },+ "interleaved": false+ },+ "release_date": "2025-06-17",+ "variants": {+ "high": {+ "thinkingConfig": {+ "includeThoughts": true,+ "thinkingBudget": 12288+ }+ },+ "max": {+ "thinkingConfig": {+ "includeThoughts": true,+ "thinkingBudget": 24576+ }+ }+ }+}diff --git a/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-ollama.txt b/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-ollama.txtnew file mode 100644index 000000000..7fee33722--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/__fixtures__/models-verbose-ollama.txt@@ -0,0 +1,50 @@+ollama/gemma4:latest+{+ "id": "gemma4:latest",+ "api": {+ "id": "gemma4:latest",+ "npm": "@ai-sdk/openai-compatible",+ "url": ""+ },+ "status": "active",+ "name": "gemma4",+ "providerID": "ollama",+ "capabilities": {+ "temperature": false,+ "reasoning": false,+ "attachment": false,+ "toolcall": true,+ "input": {+ "text": true,+ "audio": false,+ "image": false,+ "video": false,+ "pdf": false+ },+ "output": {+ "text": true,+ "audio": false,+ "image": false,+ "video": false,+ "pdf": false+ },+ "interleaved": false+ },+ "cost": {+ "input": 0,+ "output": 0,+ "cache": {+ "read": 0,+ "write": 0+ }+ },+ "options": {},+ "limit": {+ "context": 0,+ "output": 0+ },+ "headers": {},+ "family": "",+ "release_date": "",+ "variants": {}+}diff --git a/console/packages/plugins/src/agents/impl/opencode/index.ts b/console/packages/plugins/src/agents/impl/opencode/index.tsindex fe6b8022b..8c128f773 100644--- a/console/packages/plugins/src/agents/impl/opencode/index.ts+++ b/console/packages/plugins/src/agents/impl/opencode/index.ts@@ -7,7 +7,13 @@ import {} from '@switch-console/core/agents/plugins/helpers';import { buildOpencodeHookBehavior } from './hooks';import { icon } from './icon';+import { opencodeLaunchProfileModels } from './models';import { OPENCODE_PLUGIN_CONTENT } from './plugin-file';+import {+ opencodeLaunchProfile,+ opencodeLaunchProfileFields,+ opencodeProfilePaths,+} from './profile';import { buildOpencodeSwitchConnector } from './switch-connector';const OPENCODE_PLUGIN_PATH = '.opencode/plugins/switchdash-notifications.js';@@ -120,7 +126,23 @@ export const provider = registerPluginBehavior(plugin, {sessions: { validateSessionId },hooks: buildOpencodeHookBehavior(),switchSetup: { files: buildOpencodeSwitchConnector() },- mcp: opencodeMcpAdapter(),+ mcp: {+ ...opencodeMcpAdapter(),+ // The profile carries per-agent model / variant / sampling / instructions in+ // a config file under `~/.config/opencode/switch`, loaded with+ // `OPENCODE_CONFIG` because OpenCode has no flag that would load it. It+ // registers no MCP server: the global config the connector writes does that,+ // for every OpenCode session rather than only Switch Console's, and+ // OpenCode merges the two.+ launchProfile: opencodeLaunchProfile,+ launchProfilePaths: opencodeProfilePaths,+ launchProfileFields: opencodeLaunchProfileFields,+ // A variant is whatever the chosen model declares, so the only correct list+ // is the one the installed OpenCode reports. Asking also lets a typed model+ // be checked, which matters because OpenCode accepts an unknown one in+ // silence and only fails when the agent tries to answer.+ launchProfileModels: opencodeLaunchProfileModels,+ },plugins: createFileDropPlugin({relativePath: OPENCODE_PLUGIN_PATH,content: OPENCODE_PLUGIN_CONTENT,diff --git a/console/packages/plugins/src/agents/impl/opencode/models-behavior.test.ts b/console/packages/plugins/src/agents/impl/opencode/models-behavior.test.tsnew file mode 100644index 000000000..dece75809--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/models-behavior.test.ts@@ -0,0 +1,52 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import { OPENCODE_MODELS_ARGS, opencodeLaunchProfileModels } from './models';++const fixture = (name: string) =>+ readFileSync(join(__dirname, '__fixtures__', `models-verbose-${name}.txt`), 'utf8');++describe('opencodeLaunchProfileModels', () => {+ it('asks the host for models and their variants', async () => {+ const exec = vi.fn(async () => ({ stdout: fixture('google') }));++ await expect(opencodeLaunchProfileModels(exec)).resolves.toEqual([+ { id: 'google/gemini-2.5-flash', variants: ['high', 'max'] },+ { id: 'google/gemini-2.5-flash-lite', variants: ['high', 'max'] },+ ]);+ expect(exec).toHaveBeenCalledWith('opencode', OPENCODE_MODELS_ARGS);+ });++ it('asks verbosely, which is what carries the variants', () => {+ // Without `--verbose` the output is bare `provider/model` lines and the+ // variant field would have nothing to offer for any model.+ expect(OPENCODE_MODELS_ARGS).toContain('--verbose');+ });++ it('reports a local model as having no variants rather than as unknown', async () => {+ const exec = vi.fn(async () => ({ stdout: fixture('ollama') }));++ await expect(opencodeLaunchProfileModels(exec)).resolves.toEqual([+ { id: 'ollama/gemma4:latest', variants: [] },+ ]);+ });++ it('fails rather than reporting a host with no models', async () => {+ // An empty list would flag every model the user types as wrong. "We could+ // not ask" and "there is nothing here" are different answers and the caller+ // shows them differently.+ const exec = vi.fn(async () => ({ stdout: '' }));++ await expect(opencodeLaunchProfileModels(exec)).rejects.toThrow(/no models/);+ });++ it('lets a failure to run the command through to the caller', async () => {+ // OpenCode not being installed on that host is exactly the case the form+ // degrades for, so it must not be swallowed into an empty catalogue.+ const exec = vi.fn(async () => {+ throw new Error('command not found: opencode');+ });++ await expect(opencodeLaunchProfileModels(exec)).rejects.toThrow(/command not found/);+ });+});diff --git a/console/packages/plugins/src/agents/impl/opencode/models.test.ts b/console/packages/plugins/src/agents/impl/opencode/models.test.tsnew file mode 100644index 000000000..bf4e08b0b--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/models.test.ts@@ -0,0 +1,68 @@+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { parseOpencodeModels } from './models';++/**+ * Real `opencode models --verbose` output, captured from opencode 1.18.18.+ *+ * Fixtures rather than hand-written samples because the format is the one thing+ * here we do not control: OpenCode has no machine-readable flag for this, so an+ * upgrade that reshapes the output is what would break the catalogue, and a+ * sample written to match the parser could not catch that.+ */+const fixture = (name: string) =>+ readFileSync(join(__dirname, '__fixtures__', `models-verbose-${name}.txt`), 'utf8');++describe('parseOpencodeModels', () => {+ it('reads a local model, which declares no variants', () => {+ // The Ollama case: this is what makes the variant field inert for a local+ // model, and it is reported rather than guessed.+ expect(parseOpencodeModels(fixture('ollama'))).toEqual([+ { id: 'ollama/gemma4:latest', variants: [] },+ ]);+ });++ it('reads the variants a cloud model actually accepts', () => {+ expect(parseOpencodeModels(fixture('google'))).toEqual([+ { id: 'google/gemini-2.5-flash', variants: ['high', 'max'] },+ { id: 'google/gemini-2.5-flash-lite', variants: ['high', 'max'] },+ ]);+ });++ it('keys models the way the model field is typed', () => {+ // The field takes `provider/model`, so a typed value can be compared to the+ // catalogue without either side reformatting.+ for (const model of parseOpencodeModels(fixture('google'))) {+ expect(model.id).toMatch(/^[^/]+\/.+$/);+ }+ });++ it('is not fooled by the nested objects inside a model', () => {+ // Blocks are delimited by a brace alone on a line, which the pretty-printer+ // only emits at the top level — `api`, `cost` and `variants` are indented.+ const models = parseOpencodeModels(fixture('google'));+ expect(models).toHaveLength(2);+ });++ it('skips a block cut off at the end rather than losing the whole catalogue', () => {+ const truncated = `${fixture('ollama')}google/half-written\n{\n "id": "half-written",\n`;+ expect(parseOpencodeModels(truncated)).toEqual([{ id: 'ollama/gemma4:latest', variants: [] }]);+ });++ it('skips a block that is not valid JSON, keeping the ones that are', () => {+ const broken = `google/bad\n{\n not json\n}\n${fixture('ollama')}`;+ expect(parseOpencodeModels(broken)).toEqual([{ id: 'ollama/gemma4:latest', variants: [] }]);+ });++ it('skips a model missing the ids the field is keyed on', () => {+ expect(parseOpencodeModels('x\n{\n "name": "no ids"\n}\n')).toEqual([]);+ });++ it('returns nothing for output it cannot read at all', () => {+ // The caller treats an empty catalogue as unavailable and says so, rather+ // than reporting that the host offers no models.+ expect(parseOpencodeModels('')).toEqual([]);+ expect(parseOpencodeModels('command not found: opencode\n')).toEqual([]);+ });+});diff --git a/console/packages/plugins/src/agents/impl/opencode/models.ts b/console/packages/plugins/src/agents/impl/opencode/models.tsnew file mode 100644index 000000000..45c576ec2--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/models.ts@@ -0,0 +1,102 @@+import type {+ LaunchProfileHostExec,+ LaunchProfileModel,+} from '@switch-console/core/agents/plugins';++/**+ * Ask the installed OpenCode what models this agent can use.+ *+ * `--verbose` is what carries each model's variants, which is the whole reason+ * for asking: a variant is not a fixed list, it is whatever the chosen model+ * declares, so the only way to offer the right ones is to read them off the+ * host. The command also honours `OPENCODE_CONFIG`, so pointing it at an agent's+ * own config reports what *that* agent can reach, including a provider only it+ * declares.+ */+export const OPENCODE_MODELS_ARGS = ['models', '--verbose'];++/**+ * Parse `opencode models --verbose`.+ *+ * The output is a `provider/model` line followed by a pretty-printed JSON object+ * per model, not a JSON document — OpenCode has no machine-readable flag for+ * this. Blocks are delimited by a `{` and a `}` alone on a line, which is what+ * the pretty-printer emits at the top level and never for a nested object, since+ * those are indented.+ *+ * The header line is ignored in favour of the `providerID` and `id` inside the+ * block: the same information, from the part of the output that is structured.+ *+ * Deliberately tolerant. A block that does not parse, or that is cut off at the+ * end, is skipped rather than failing the whole catalogue — a model we cannot+ * read is one we cannot offer, which is not a reason to stop offering the rest.+ * A caller that gets nothing back should treat the catalogue as unavailable and+ * say so, rather than concluding the host has no models.+ */+/**+ * The models this host offers, with each one's reasoning variants.+ *+ * Throws when the output yields nothing usable. That is the honest reading: the+ * command not being there, failing, or printing something this cannot parse are+ * all "we could not ask", and none of them mean the host has no models — which+ * is what an empty list would say, and would flag every valid model as wrong.+ */+export async function opencodeLaunchProfileModels(+ exec: LaunchProfileHostExec+): Promise<LaunchProfileModel[]> {+ const { stdout } = await exec('opencode', OPENCODE_MODELS_ARGS);+ const models = parseOpencodeModels(stdout);+ if (models.length === 0) {+ throw new Error('`opencode models --verbose` returned no models this app could read.');+ }+ return models;+}++export function parseOpencodeModels(stdout: string): LaunchProfileModel[] {+ const models: LaunchProfileModel[] = [];+ let block: string[] | null = null;++ for (const line of stdout.split('\n')) {+ if (line === '{') {+ block = [line];+ continue;+ }+ if (block === null) continue;++ block.push(line);+ if (line !== '}') continue;++ const model = readModel(block.join('\n'));+ if (model) models.push(model);+ block = null;+ }++ return models;+}++function readModel(raw: string): LaunchProfileModel | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }++ const { providerID, id, variants } = parsed as {+ providerID?: unknown;+ id?: unknown;+ variants?: unknown;+ };+ if (typeof providerID !== 'string' || typeof id !== 'string') return null;+ if (!providerID || !id) return null;++ return {+ // The form's model field takes `provider/model`, so the catalogue is keyed+ // the same way and a typed value can be compared to it directly.+ id: `${providerID}/${id}`,+ variants:+ typeof variants === 'object' && variants !== null && !Array.isArray(variants)+ ? Object.keys(variants)+ : [],+ };+}diff --git a/console/packages/plugins/src/agents/impl/opencode/profile.test.ts b/console/packages/plugins/src/agents/impl/opencode/profile.test.tsnew file mode 100644index 000000000..9a3196408--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/profile.test.ts@@ -0,0 +1,283 @@+import { describe, expect, it } from 'vitest';+import {+ buildOpencodeConfig,+ opencodeLaunchProfile,+ opencodeLaunchProfileFields,+ opencodeProfileName,+ opencodeProfilePaths,+} from './profile';++/** An agent working directory; folded into the profile name for uniqueness. */+const WD = '/home/agent/repo';++const HOME = '__SWITCHDASH_HOME__';++const parse = (content: string) => JSON.parse(content) as Record<string, any>;++/** The config file of a profile, parsed. */+function configOf(profile: NonNullable<ReturnType<typeof opencodeLaunchProfile>>) {+ const file = profile.files.find((f) => f.relativePath.endsWith('.json'))!;+ return parse(file.content);+}++describe('opencodeLaunchProfileFields', () => {+ it('declares exactly the keys the config builder consumes', () => {+ expect(opencodeLaunchProfileFields().map((field) => field.key)).toEqual([+ 'model',+ 'variant',+ 'temperature',+ 'topP',+ 'maxSteps',+ 'webSearch',+ 'smallModel',+ 'instructions',+ ]);+ });++ it('offers no Codex-only setting, which OpenCode has no key for', () => {+ // Verbosity and reasoning summary exist for Codex and simply do not exist in+ // OpenCode's config; offering them would collect a value that goes nowhere.+ const keys = opencodeLaunchProfileFields().map((field) => field.key);+ expect(keys).not.toContain('verbosity');+ expect(keys).not.toContain('reasoningSummary');+ expect(keys).not.toContain('effort');+ });++ it('declares no fixed list of reasoning variants, because there is not one', () => {+ // The accepted values come from the chosen model's own capabilities, so any+ // list hardcoded here would be wrong for most models — and flatly empty for+ // every local one.+ const variant = opencodeLaunchProfileFields().find((field) => field.key === 'variant')!;+ expect(variant.options).toBeUndefined();+ });++ it('binds the variant to the model above, so the choices follow it', () => {+ const variant = opencodeLaunchProfileFields().find((field) => field.key === 'variant')!;+ expect(variant.catalogue).toEqual({ kind: 'model-variant', modelField: 'model' });+ });++ it('binds both model fields to the host catalogue, so a typo can be caught', () => {+ // OpenCode accepts a model it does not have without complaint and only fails+ // when the agent tries to answer, so the check has to happen here.+ for (const key of ['model', 'smallModel']) {+ const field = opencodeLaunchProfileFields().find((f) => f.key === key)!;+ expect(field.catalogue).toEqual({ kind: 'model' });+ }+ });++ it('names a field the variant can follow', () => {+ // The renderer resolves the binding by key, so a rename that missed one side+ // would silently leave the variant with no choices.+ const fields = opencodeLaunchProfileFields();+ const variant = fields.find((field) => field.key === 'variant')!;+ const bound = variant.catalogue as { kind: string; modelField: string };+ expect(fields.some((field) => field.key === bound.modelField)).toBe(true);+ });+});++describe('buildOpencodeConfig', () => {+ it('writes the utility model at the config root, where OpenCode reads it', () => {+ // OpenCode has no per-agent utility model, so this is the one setting that+ // applies to the session rather than to the agent. The config file is+ // per-agent, so writing it at the root is still per-agent.+ const config = parse(buildOpencodeConfig({ smallModel: 'ollama/gemma4:latest' }, null)!);++ expect(config.small_model).toBe('ollama/gemma4:latest');+ expect(config.agent).toBeUndefined();+ });++ it('keeps the utility model out of the agent object', () => {+ const config = parse(buildOpencodeConfig({ model: 'ollama/a', smallModel: 'ollama/b' }, null)!);++ expect(config.agent.build).toEqual({ model: 'ollama/a' });+ expect(config.small_model).toBe('ollama/b');+ });++ it('writes settings onto the default agent, which needs no --agent to select', () => {+ const config = parse(+ buildOpencodeConfig({ model: 'anthropic/claude-sonnet-4-5', variant: 'high' }, null)!+ );++ expect(config.agent.build).toEqual({+ model: 'anthropic/claude-sonnet-4-5',+ variant: 'high',+ });+ });++ it('writes sampling settings as numbers, not the strings the form collects', () => {+ const config = parse(+ buildOpencodeConfig({ temperature: '0.2', topP: '0.9', maxSteps: '40' }, null)!+ );++ expect(config.agent.build).toEqual({ temperature: 0.2, top_p: 0.9, maxSteps: 40 });+ });++ it('drops a numeric setting that is not a number rather than writing null', () => {+ // OpenCode ignores a value it cannot use without saying so, so a junk number+ // would be silently inert either way; leaving the key out at least matches+ // what a blank field does.+ expect(buildOpencodeConfig({ temperature: 'hot' }, null)).toBeNull();+ });++ it('writes web search as a tool permission, which is what OpenCode calls it', () => {+ expect(parse(buildOpencodeConfig({ webSearch: 'true' }, null)!).agent.build).toEqual({+ permission: { websearch: 'allow' },+ });+ expect(parse(buildOpencodeConfig({ webSearch: 'false' }, null)!).agent.build).toEqual({+ permission: { websearch: 'deny' },+ });+ });++ it('omits an unset setting so the user’s own config decides', () => {+ // Unset is not off: omitting the key defers to `~/.config/opencode/opencode.json`,+ // writing one overrides it.+ const config = parse(buildOpencodeConfig({ model: 'x', webSearch: '', variant: ' ' }, null)!);+ expect(config.agent.build).toEqual({ model: 'x' });+ });++ it('ignores a value stored under a key OpenCode does not declare', () => {+ // OpenCode drops a config section containing a key it does not recognise —+ // silently, and whole — so a Codex key surviving into an OpenCode config+ // could take the rest of the agent settings with it.+ expect(buildOpencodeConfig({ reasoningSummary: 'detailed', effort: 'high' }, null)).toBeNull();+ });++ it('registers no MCP server: the global config already has the Switch one', () => {+ // OpenCode merges what OPENCODE_CONFIG names onto the config it already+ // loaded, so restating the Switch server here would be a second copy of the+ // runtime pin, free to drift from the one the connector writes.+ const config = parse(buildOpencodeConfig({ model: 'x' }, null)!);+ expect(config.mcp).toBeUndefined();+ });++ it('returns null when nothing is set, so no config file is written', () => {+ expect(buildOpencodeConfig({}, null)).toBeNull();+ expect(buildOpencodeConfig({ model: ' ' }, null)).toBeNull();+ });++ it('references an instructions file rather than inlining a system prompt', () => {+ // OpenCode's per-agent `prompt` supplies the agent's system prompt rather+ // than adding to it, which for a coding agent means losing the operating+ // instructions it needs. Top-level `instructions` is the additive path.+ const config = parse(buildOpencodeConfig({ instructions: 'be terse' }, '/home/a/inst.md')!);++ expect(config.instructions).toEqual(['/home/a/inst.md']);+ expect(config.agent?.build?.prompt).toBeUndefined();+ });+});++describe('opencodeLaunchProfile', () => {+ it('loads the config from the environment, having no flag that would load it', () => {+ const profile = opencodeLaunchProfile({+ slug: 'oc-hoot',+ workingDir: WD,+ values: { model: 'anthropic/claude-sonnet-4-5' },+ })!;++ expect(profile.args).toEqual([]);+ expect(profile.env).toEqual({+ OPENCODE_CONFIG: `${HOME}/.config/opencode/switch/${opencodeProfileName('oc-hoot', WD)}.json`,+ });+ });++ it('keeps a system prompt in a file, off the command line', () => {+ // The argv and env are re-rendered as a shell string on the SSH and tmux+ // paths, so a free-form body there would be mangled or executed.+ const instructions = 'be terse\n$(whoami) and "quotes"';+ const profile = opencodeLaunchProfile({+ slug: 'oc-hoot',+ workingDir: WD,+ values: { instructions },+ })!;++ const file = profile.files.find((f) => f.relativePath.endsWith('.instructions.md'))!;+ expect(file.content).toBe(instructions);+ expect(JSON.stringify(profile.env)).not.toContain('whoami');+ expect(profile.args).toEqual([]);+ });++ it('points the config at the instructions file by absolute path', () => {+ // The config is read from the home directory while the session runs in the+ // repo, so a relative path would resolve against the wrong root.+ const profile = opencodeLaunchProfile({+ slug: 'oc-hoot',+ workingDir: WD,+ values: { instructions: 'be terse' },+ })!;++ const instructionsPath = configOf(profile).instructions[0] as string;+ expect(instructionsPath.startsWith(`${HOME}/`)).toBe(true);+ expect(instructionsPath).toBe(+ `${HOME}/.config/opencode/switch/${opencodeProfileName('oc-hoot', WD)}.instructions.md`+ );+ expect(profile.files.some((f) => f.relativePath === instructionsPath.slice(HOME.length + 1)));+ });++ it('writes no instructions file when there is no system prompt', () => {+ const profile = opencodeLaunchProfile({+ slug: 'oc-hoot',+ workingDir: WD,+ values: { model: 'x' },+ })!;++ expect(profile.files).toHaveLength(1);+ expect(configOf(profile).instructions).toBeUndefined();+ });++ it('returns null when there is nothing to specialize, rather than an empty config', () => {+ // An agent on the defaults needs no file. Writing an empty one would still+ // put OPENCODE_CONFIG in the environment, pointing at nothing.+ expect(opencodeLaunchProfile({ slug: 'a', workingDir: WD, values: {} })).toBeNull();+ });+});++describe('opencodeProfileName', () => {+ it('gives two agents that share a name in different dirs distinct configs', () => {+ // Agent names are unique only within a location, so the working dir must+ // discriminate — otherwise the second launch overwrites the first's config.+ expect(opencodeProfileName('hoot', '/dir/one')).not.toBe(+ opencodeProfileName('hoot', '/dir/two')+ );+ });++ it('is stable for the same (slug, dir)', () => {+ expect(opencodeProfileName('hoot', WD)).toBe(opencodeProfileName('hoot', WD));+ });++ it('keeps slugs that differ only in rewritten characters on distinct configs', () => {+ expect(opencodeProfileName('a.b', WD)).not.toBe(opencodeProfileName('a-b', WD));+ });++ it('rewrites a dotted Switch agent name into a plain filename stem', () => {+ const name = opencodeProfileName('opencode.yak.cmcdermott', WD);+ expect(name).toMatch(/^[A-Za-z0-9_-]+$/);+ expect(name).toContain('opencode-yak-cmcdermott');+ });+});++describe('opencodeProfilePaths', () => {+ it('names both files so teardown takes the instructions with the config', () => {+ const name = opencodeProfileName('oc-hoot', WD);+ expect(opencodeProfilePaths({ slug: 'oc-hoot', workingDir: WD })).toEqual([+ `.config/opencode/switch/${name}.json`,+ `.config/opencode/switch/${name}.instructions.md`,+ ]);+ });++ it('covers every file the profile can write', () => {+ const profile = opencodeLaunchProfile({+ slug: 'oc-hoot',+ workingDir: WD,+ values: { model: 'x', instructions: 'be terse' },+ })!;+ const paths = opencodeProfilePaths({ slug: 'oc-hoot', workingDir: WD });++ for (const file of profile.files) expect(paths).toContain(file.relativePath);+ });++ it('keeps Switch-owned files in their own directory, not among the user’s', () => {+ for (const path of opencodeProfilePaths({ slug: 'oc-hoot', workingDir: WD })) {+ expect(path.startsWith('.config/opencode/switch/')).toBe(true);+ }+ });+});diff --git a/console/packages/plugins/src/agents/impl/opencode/profile.ts b/console/packages/plugins/src/agents/impl/opencode/profile.tsnew file mode 100644index 000000000..78886987f--- /dev/null+++ b/console/packages/plugins/src/agents/impl/opencode/profile.ts@@ -0,0 +1,321 @@+import type {+ RepoAgentField,+ SwitchLaunchProfile,+ SwitchLaunchSpecialization,+} from '@switch-console/core/agents/plugins';+import { LAUNCH_PROFILE_HOME_PLACEHOLDER } from '@switch-console/core/agents/plugins';++/**+ * The agent an OpenCode session runs as by default, and therefore the one a+ * per-agent setting has to land on.+ *+ * OpenCode's per-agent settings live under `agent.<name>`, and a fresh `opencode`+ * with no `--agent` runs `build`. Overriding `build` rather than defining a new+ * agent keeps the launch command unchanged — there is no name to pass — and+ * leaves the agent list the user sees as it was. Every key set here is one+ * OpenCode's own schema declares for an agent, so the override is a narrowing of+ * the built-in rather than a replacement of it.+ */+const OPENCODE_TARGET_AGENT = 'build';++/**+ * Where an agent's OpenCode config and instructions live, under the same+ * `.config/opencode` directory as the global config they layer over. Kept in+ * their own `switch/` subdirectory so it is obvious which files Switch Console+ * owns, and so removing an agent cannot take a user's file with it.+ */+const OPENCODE_PROFILE_DIR = '.config/opencode/switch';++/**+ * The profile name an agent maps to, used as the config filename stem.+ *+ * A Switch agent name is unique only *within a location*: two agents can share a+ * name in different directories, so the name alone would collide onto one file+ * and whichever launched second would overwrite the first's settings. The name+ * therefore carries a digest of `(workingDir, slug)` — the same `(dir, slug)` key+ * the Codex profile and `agentSidecarTmuxName` use — which also keeps `a.b` and+ * `a-b` distinct.+ */+export function opencodeProfileName(slug: string, workingDir: string): string {+ const plain = slug.replace(/[^A-Za-z0-9_-]/g, '-');+ return `${plain}-${profileDigest(workingDir, slug)}`;+}++/** FNV-1a over `workingDir\0slug`, base36 — short, stable, and dependency-free. */+function profileDigest(workingDir: string, slug: string): string {+ let hash = 0x811c9dc5;+ const input = `${workingDir} ${slug}`;+ for (let i = 0; i < input.length; i++) {+ hash = Math.imul(hash ^ input.charCodeAt(i), 0x01000193) >>> 0;+ }+ return hash.toString(36);+}++/** Home-relative path of an agent's OpenCode config. */+function opencodeConfigRelativePath(slug: string, workingDir: string): string {+ return `${OPENCODE_PROFILE_DIR}/${opencodeProfileName(slug, workingDir)}.json`;+}++/** Home-relative path of an agent's instructions file, when it has one. */+function opencodeInstructionsRelativePath(slug: string, workingDir: string): string {+ return `${OPENCODE_PROFILE_DIR}/${opencodeProfileName(slug, workingDir)}.instructions.md`;+}++/** Home-relative files an agent's OpenCode profile occupies, for delete/rename teardown. */+export function opencodeProfilePaths(params: { slug: string; workingDir: string }): string[] {+ return [+ opencodeConfigRelativePath(params.slug, params.workingDir),+ opencodeInstructionsRelativePath(params.slug, params.workingDir),+ ];+}++/**+ * Values OpenCode accepts for a tool permission. Only the two ends are offered+ * per setting below; `ask` would stall an unattended session on a prompt nobody+ * is there to answer.+ */+const ALLOW = 'allow';+const DENY = 'deny';++/**+ * How each per-agent setting is collected and where it goes in the config.+ *+ * One declaration serves the form and the writer, so a new setting is one entry+ * here rather than a field list and a writer that can disagree.+ *+ * `path` is a dotted path, absent for a setting handled specially+ * (`instructions`, which is a file rather than a value). `scope` says what it is+ * relative to: the agent's own object (`agent.build.…`) for most, or the config+ * root for the few OpenCode keys that have no per-agent form. Everything is+ * collected as a string or a number, and blank means the key is omitted so the+ * user's own `opencode.json` decides — which is not the same as writing a+ * default-looking value over it.+ */+type OpencodeSetting = {+ field: RepoAgentField;+ path?: string;+ scope?: 'agent' | 'config';+ toValue?: (raw: string) => unknown;+};++/**+ * Parse a numeric setting, dropping anything that is not a finite number.+ *+ * OpenCode ignores config keys it does not recognise and does not complain about+ * a value it cannot use, so a junk number would be silently inert. Leaving the+ * key out instead is the same outcome the user gets from a blank field, and does+ * not put `null` into a config that claims to be a number.+ */+const numeric = (raw: string): unknown => {+ const value = Number(raw);+ return Number.isFinite(value) ? value : undefined;+};++const OPENCODE_SETTINGS: OpencodeSetting[] = [+ {+ field: {+ key: 'model',+ label: 'Model',+ type: 'text',+ placeholder: 'e.g. anthropic/claude-sonnet-4-5 — blank uses the OpenCode default',+ help: 'Overrides the model for this agent only, as provider/model. Includes a local model: define the provider once in your OpenCode config and an agent can run against it.',+ catalogue: { kind: 'model' },+ },+ path: 'model',+ },+ {+ field: {+ key: 'variant',+ label: 'Reasoning variant',+ type: 'text',+ placeholder: 'e.g. high — blank uses the model default',+ help: "OpenCode's reasoning-effort control. Which values a model takes is the model's own business, so the choices follow the model above; most local models have none.",+ catalogue: { kind: 'model-variant', modelField: 'model' },+ },+ path: 'variant',+ },+ {+ field: {+ key: 'temperature',+ label: 'Temperature',+ type: 'number',+ placeholder: 'e.g. 0.2',+ help: 'How much randomness the model is allowed. Blank leaves it to the model.',+ },+ path: 'temperature',+ toValue: numeric,+ },+ {+ field: {+ key: 'topP',+ label: 'Top-p',+ type: 'number',+ placeholder: 'e.g. 0.9',+ help: 'Nucleus-sampling cutoff. Blank leaves it to the model.',+ },+ path: 'top_p',+ toValue: numeric,+ },+ {+ field: {+ key: 'maxSteps',+ label: 'Step limit',+ type: 'number',+ placeholder: 'e.g. 40',+ help: 'How many tool-calling steps the agent may take before it has to answer.',+ },+ path: 'maxSteps',+ toValue: numeric,+ },+ {+ field: {+ key: 'webSearch',+ label: 'Web search',+ type: 'select',+ options: [+ { value: '', label: 'Default' },+ { value: 'true', label: 'On' },+ { value: 'false', label: 'Off' },+ ],+ help: 'Whether this agent may search the web.',+ },+ // Web search is not a setting in OpenCode, it is a tool the agent is allowed+ // or denied. Written as a permission rather than under `tools`, which+ // OpenCode normalises into exactly this.+ path: 'permission.websearch',+ toValue: (raw) => (raw === 'true' ? ALLOW : DENY),+ },+ {+ field: {+ key: 'smallModel',+ label: 'Utility model',+ type: 'text',+ placeholder: 'e.g. ollama/gemma4:latest — blank uses your OpenCode default',+ help: 'The cheaper model OpenCode uses for background work like naming the conversation. Worth setting to match the model above when the point is to keep everything on one machine — otherwise that background work goes wherever your own config sends it.',+ catalogue: { kind: 'model' },+ },+ path: 'small_model',+ // Top-level: OpenCode has no per-agent utility model, so this is the one+ // setting here that applies to the session rather than to the agent. The+ // config file is per-agent, so writing it at the root is still per-agent.+ scope: 'config',+ },+ {+ field: {+ key: 'instructions',+ label: 'Instructions',+ type: 'textarea',+ placeholder: "Extra guidance for this agent, e.g. 'You are a careful reviewer…'",+ help: "Added to OpenCode's own instructions, the way an AGENTS.md is. Blank keeps OpenCode defaults.",+ },+ },+];++/** The fields the "advanced configuration" form renders for an OpenCode agent. */+export function opencodeLaunchProfileFields(): RepoAgentField[] {+ return OPENCODE_SETTINGS.map((setting) => setting.field);+}++/** Set a dotted path within an object, creating the intermediate objects. */+function assign(target: Record<string, unknown>, path: string, value: unknown): void {+ const segments = path.split('.');+ const leaf = segments.pop() as string;+ let cursor = target;+ for (const segment of segments) {+ if (typeof cursor[segment] !== 'object' || cursor[segment] === null) cursor[segment] = {};+ cursor = cursor[segment] as Record<string, unknown>;+ }+ cursor[leaf] = value;+}++/**+ * Build an agent's OpenCode config.+ *+ * The result is layered over the user's global `~/.config/opencode/opencode.json`+ * rather than replacing it: OpenCode deep-merges what `OPENCODE_CONFIG` names+ * onto what it already loaded, so the Switch MCP server registered there survives+ * without being restated here. That is also why nothing in this file registers+ * it — restating it would put a second copy of the runtime pin somewhere it could+ * drift.+ *+ * `instructionsPath`, when the agent has an instructions body, is the absolute+ * path of the file holding it. It is absolute because the config is read from the+ * home directory while the session runs in the repo, so a relative path would+ * resolve against the wrong root.+ *+ * Returns `null` when nothing is set, so an agent on the defaults gets no config+ * file and no `OPENCODE_CONFIG` pointing at one.+ */+export function buildOpencodeConfig(+ values: SwitchLaunchSpecialization,+ instructionsPath: string | null+): string | null {+ const agent: Record<string, unknown> = {};+ const config: Record<string, unknown> = {};++ // Driven off OpenCode's own settings rather than the collected keys, so a value+ // stored under a key OpenCode does not declare is left out rather than written.+ // That matters more here than elsewhere: OpenCode drops a config section+ // containing a key it does not recognise, silently and whole.+ for (const setting of OPENCODE_SETTINGS) {+ if (!setting.path) continue;+ const raw = values[setting.field.key];+ if (typeof raw !== 'string' || raw.trim() === '') continue;++ const value = setting.toValue ? setting.toValue(raw.trim()) : raw.trim();+ if (value === undefined) continue;+ assign(setting.scope === 'config' ? config : agent, setting.path, value);+ }++ if (instructionsPath) config.instructions = [instructionsPath];+ if (Object.keys(agent).length > 0) config.agent = { [OPENCODE_TARGET_AGENT]: agent };+ if (Object.keys(config).length === 0) return null;++ // OpenCode adds `$schema` to a config that lacks one; writing it avoids that+ // showing up as a change to a file Switch Console owns.+ return `${JSON.stringify({ $schema: 'https://opencode.ai/config.json', ...config }, null, 2)}\n`;+}++/**+ * Compute an agent's OpenCode launch profile: the files to write under the home+ * directory and the environment that loads them.+ *+ * Unlike Codex there is no argv to return. OpenCode has no `--profile` or+ * `--config` flag; the only way to add a config file to a session is+ * `OPENCODE_CONFIG`, so the profile's whole contribution is an environment+ * variable naming the file it just wrote. The value has to be absolute and this+ * function is pure, so the home directory arrives as a placeholder the launch+ * surface fills in.+ *+ * An instructions body is a second file rather than a value in the config.+ * OpenCode's per-agent `prompt` takes text directly, but it *supplies* that+ * agent's system prompt rather than adding to it, which for a coding agent means+ * losing the operating instructions it needs to work. Top-level `instructions` is+ * the additive path — the same one an AGENTS.md takes — and it names files.+ */+export function opencodeLaunchProfile(params: {+ slug: string;+ workingDir: string;+ values: SwitchLaunchSpecialization;+}): SwitchLaunchProfile | null {+ const { slug, workingDir, values } = params;++ const instructions = values.instructions?.trim() ? values.instructions : null;+ const instructionsRelativePath = opencodeInstructionsRelativePath(slug, workingDir);+ const instructionsPath = instructions+ ? `${LAUNCH_PROFILE_HOME_PLACEHOLDER}/${instructionsRelativePath}`+ : null;++ const content = buildOpencodeConfig(values, instructionsPath);+ if (!content) return null;++ const configRelativePath = opencodeConfigRelativePath(slug, workingDir);+ return {+ files: [+ { relativePath: configRelativePath, content },+ ...(instructions ? [{ relativePath: instructionsRelativePath, content: instructions }] : []),+ ],+ args: [],+ env: { OPENCODE_CONFIG: `${LAUNCH_PROFILE_HOME_PLACEHOLDER}/${configRelativePath}` },+ };+}diff --git a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts b/console/packages/plugins/src/agents/impl/opencode/skill-file.tsindex bff923aea..1c2748e23 100644--- a/console/packages/plugins/src/agents/impl/opencode/skill-file.ts+++ b/console/packages/plugins/src/agents/impl/opencode/skill-file.ts@@ -233,6 +233,11 @@ local operator is explicitly steering you outside the room conversation.- Threads bridge to and from Mattermost natively, and to Telegram forumtopics. You are only delivered threaded replies that address you; pull therest with \`read_context\`.+- **Mattermost only — post at the root unless you were asked in a thread.**+ Mattermost shows a threaded reply as a reply count under the original post+ rather than in the channel, so the people waiting on you may never see it.+ \`connect_to_room\` names the platform a room is bridged to. Everywhere else,+ thread as described above.## Sending and receiving attachments