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(console): model agent instructions as a main agent attribute (CHOO-2228) (#261)
Louis Amaudruz1852984215e1
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 847fb4d37..872c5a6e7 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@@ -1,7 +1,7 @@import { pluginRegistry } from '@switch-console/plugins/agents';import { beforeEach, describe, expect, it, vi } from 'vitest';import { AGENT_FRESH_RECOVERY_GRACE_MS } from '@main/core/agent-runtime/agent-runtime-supervisor';-import { getAgentById } from '@main/core/agents/getAgentById';+import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';import type { Pty, PtyExitInfo } from '@main/core/pty/pty';import { ptySessionRegistry } from '@main/core/pty/pty-session-registry';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';@@ -71,6 +71,13 @@ vi.mock('@main/core/agents/getAgentById', () => ({getAgentById: vi.fn(async () => null),}));+// What to launch with is read from the agent's config file in its working+// directory, which means resolving its location out of the database — and+// these tests have no database. A test that cares states the values directly.+vi.mock('@main/core/agents/agent-launch-config', () => ({+ agentLaunchSpecialization: vi.fn(async () => undefined),+}));+// Reads the app's userData path and shells out to `gh`; neither exists here,// and these tests are about the spawn, not the registry.vi.mock('@main/core/switch-rooms/npm-registry-auth', () => ({@@ -304,9 +311,7 @@ describe('local agent runtime respawn state', () => {it('writes the Codex profile to the home dir and loads it on argv', async () => {const exitHandlers: Array<(info: PtyExitInfo) => void> = [];spawnLocalPty.mockReturnValue(fakePty(exitHandlers));- vi.mocked(getAgentById).mockResolvedValueOnce({- providerConfig: { version: '2', providerId: 'codex', values: { model: 'gpt-5.6-terra' } },- } as unknown as Awaited<ReturnType<typeof getAgentById>>);+ vi.mocked(agentLaunchSpecialization).mockResolvedValueOnce({ model: 'gpt-5.6-terra' });vi.mocked(readAgentSwitchEnvFromFs).mockResolvedValueOnce({SWITCH_API_ENDPOINT: 'https://switch.example.com',SWITCH_API_TOKEN: 'tok-123',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 a9a07f08b..07ec1c3b0 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@@ -7,6 +7,7 @@ import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-simport { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';+import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';import { getAgentById } from '@main/core/agents/getAgentById';import { localDependencyManager } from '@main/core/dependencies/dependency-managers';import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';@@ -29,7 +30,6 @@ import type { ResolvedShellProfile } from '@main/core/terminal-shell/types';import { events } from '@main/lib/events';import { runWithLogContext } from '@main/lib/log-context';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';import { makePtyId } from '@shared/core/pty/ptyId';import { makeAgentPtySessionId } from '@shared/core/pty/ptySessionId';@@ -191,7 +191,7 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {homeDir: homedir(),slug: agentCredsSlug(session),workingDir: this.sessionPath,- specialization: toSwitchSpecialization(agentRecord?.providerConfig),+ specialization: await agentLaunchSpecialization(session.agentId),});const agentCommand = plugin.behavior.prompt!.buildCommand({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 ecc066bab..0301fe0a3 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@@ -87,6 +87,13 @@ vi.mock('@main/core/agents/getAgentById', () => ({getAgentById: vi.fn(async () => ({ autoApprove: false })),}));+// What to launch with is read from the agent's config file in its working+// directory, which means resolving its location out of the database — and+// these tests have no database. A test that cares states the values directly.+vi.mock('@main/core/agents/agent-launch-config', () => ({+ agentLaunchSpecialization: vi.fn(async () => undefined),+}));+// Same reason: this install's deployer identity is persisted in the DB, and the// sidecar launch path reads it to stamp whatever sidecar it starts.vi.mock('@main/core/sidecar/deployer-identity', () => ({@@ -142,6 +149,7 @@ function emitReconnected(connectionId: string): void {const { events } = await import('@main/lib/events');const { getAgentById } = await import('@main/core/agents/getAgentById');+const { agentLaunchSpecialization } = await import('@main/core/agents/agent-launch-config');const { getPlugin } = await import('@main/core/providers/plugin-registry');type ProviderState = {@@ -341,10 +349,10 @@ describe('SshAgentRuntime', () => {},}) as never);+ vi.mocked(agentLaunchSpecialization).mockResolvedValue({ model: 'gpt-5.6-terra' });vi.mocked(getAgentById).mockResolvedValueOnce({autoApprove: false,name: 'codex-hoot',- 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 e6defbc77..13dcd589c 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@@ -17,6 +17,7 @@ import type { AttachableRuntime } from '@main/core/agent-runtime/attachment/typeimport { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';import { agentCredsSlug } from '@main/core/agents/agent-creds-slug';+import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';import { getAgentById } from '@main/core/agents/getAgentById';import { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';import { hostDependencyStore } from '@main/core/dependencies/host-dependency-store';@@ -37,7 +38,6 @@ import { readAgentSwitchEnvFromFs } from '@main/core/switch-rooms/switch-credentimport { events } from '@main/lib/events';import { runWithLogContext } from '@main/lib/log-context';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import type { AgentSessionConfig } from '@shared/core/providers/agent-session';import { agentSessionExitedChannel } from '@shared/core/providers/agentEvents';import { buildAgentHookEnv } from '@shared/core/pty/hookEnv';@@ -411,6 +411,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimeconst agent = await getAgentById(session.agentId);const host = this.createSidecarHost();const credsSlug = agentCredsSlug(session);+ const specialization = await agentLaunchSpecialization(session.agentId);// Every session in this dir would otherwise re-run the same deploy+launch on// startup; coalesce so one host sees one ensure, not one per session.const endpoint = await dedupeInFlight(@@ -424,7 +425,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimeautoApprove: agent?.autoApprove ?? false,credsSlug,agentName: agent?.name ?? session.agentName ?? null,- specialization: toSwitchSpecialization(agent?.providerConfig),+ specialization,ctx: this.ctx,connectionId: this.connectionId,host,@@ -581,7 +582,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimeautoApprove: agent?.autoApprove ?? false,credsSlug,agentName: agent?.name ?? session.agentName ?? null,- specialization: toSwitchSpecialization(agent?.providerConfig),+ specialization: await agentLaunchSpecialization(session.agentId),ctx: this.ctx,connectionId: this.connectionId,host: this.createSidecarHost(),@@ -724,7 +725,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimeconst launchProfile = await this.writeRemoteLaunchProfile(plugin,agentCredsSlug(session),- toSwitchSpecialization(agentRecord?.providerConfig)+ await agentLaunchSpecialization(session.agentId));const agentCommand = plugin.behavior.prompt!.buildCommand({diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.tsindex 012a03585..9ab263d21 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.test.ts@@ -24,17 +24,30 @@ function fakeFs(seed: Record<string, string> = {}): PluginFs {// simulate a provider without repo-agent definitions (e.g. Codex).const h = vi.hoisted(() => {const writeDefinition = vi.fn(async () => {});+ // A faithful-enough stand-in for a repo-agents provider: the config sync+ // renders the definition and writes it through the workspace fs, so the mock+ // has to answer where it goes and what it looks like.+ const repoAgents = {+ writeDefinition,+ definitionPath: (name: string) => `.claude/agents/${name}.md`,+ renderDefinition: (attributes: Record<string, unknown>) =>+ `---\nname: ${String(attributes.name)}\ndescription: ${String(attributes.description)}\n---\n\n${String(+ attributes.instructions || attributes.description+ )}\n`,+ readDefinition: async () => null,+ };const state: {workspace: PluginFs | null;repoAgents: object | null;nameTaken: boolean;} = {workspace: null,- repoAgents: { writeDefinition },+ repoAgents,nameTaken: false,};return {state,+ repoAgents,writeDefinition,agentNameTaken: vi.fn(async () => state.nameTaken),registerAgentIdentity: vi.fn(async () => ({@@ -88,6 +101,7 @@ function params(overrides: Record<string, unknown> = {}) {iconUrl: null,autoSession: false,autoApprove: false,+ instructions: '',definitionAttributes: {},...overrides,};@@ -103,7 +117,7 @@ describe('addAgent', () => {beforeEach(() => {vi.clearAllMocks();h.state.nameTaken = false;- h.state.repoAgents = { writeDefinition: h.writeDefinition };+ h.state.repoAgents = h.repoAgents;h.state.workspace = fakeFs();h.registerAgentIdentity.mockResolvedValue({ kind: 'created', id: 'sw-1', apiKey: 'tok-123' });});@@ -123,7 +137,7 @@ describe('addAgent', () => {SWITCH_API_TOKEN: 'tok-123',SWITCH_AGENT_ID: 'sw-1',});- expect(h.writeDefinition).not.toHaveBeenCalled();+ expect(await fs.read('.claude/agents/codex-hoot.md')).toBeNull();});it('writes both credentials and an on-disk definition for a repo-agents provider', async () => {@@ -132,10 +146,20 @@ describe('addAgent', () => {await addAgent(params({ providerId: 'claude', name: 'cc-hoot' }));expect((await credsOf(fs, 'cc-hoot')).SWITCH_API_TOKEN).toBe('tok-123');- expect(h.writeDefinition).toHaveBeenCalledWith(- fs,- expect.objectContaining({ name: 'cc-hoot', description: 'Codex running in repo' })- );+ const definition = await fs.read('.claude/agents/cc-hoot.md');+ expect(definition).toContain('name: cc-hoot');+ expect(definition).toContain('description: Codex running in repo');+ });++ it('records the agent’s instructions in its committed config file', async () => {+ const fs = h.state.workspace as PluginFs;++ await addAgent(params({ providerId: 'claude', name: 'cc-hoot', instructions: 'Be careful.' }));++ const config = JSON.parse((await fs.read('.switch/config/cc-hoot.json')) ?? '{}');+ expect(config.instructions).toBe('Be careful.');+ // And it reaches the provider's own file, which is what actually runs.+ expect(await fs.read('.claude/agents/cc-hoot.md')).toContain('Be careful.');});it('git-ignores the credentials directory so the token never enters VCS', async () => {diff --git a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.tsindex 2b599339d..b7c69ea74 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/add-agent.ts@@ -11,6 +11,8 @@ import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-conimport type { Agent } from '@shared/core/agents/agents';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';import { basenameFromAnyPath } from '@shared/path-name';+import { writeAgentConfigFile } from './agent-config-file';+import { syncAgentConfig } from './agent-config-sync';import { foreignCredentialsOwner } from './agent-credentials-slot';import { agentEvents } from './agent-events';import { agentNameTaken } from './agent-name-taken';@@ -41,9 +43,13 @@ export type AddAgentParams = {iconUrl: string | null;autoSession: boolean;autoApprove: boolean;- /** Provider-specific definition attributes (model, effort, tools, prompt, …),- * keyed by the provider's attribute fields. `name`/`description` are set from- * the params above. */+ /** The agent's system prompt, provider-agnostic. Rendered into whatever the+ * provider reads — a Claude Code subagent body, Codex's developer+ * instructions. Empty for an agent with none. */+ instructions: string;+ /** Provider-specific definition attributes (model, effort, tools, …), keyed+ * by the provider's attribute fields. `name`/`description` are set from the+ * params above, and the system prompt is `instructions`. */definitionAttributes: RepoAgentAttributes;/** Per-agent provider config folded into the agent's launch (Codex model /* effort / instructions). Distinct from `definitionAttributes`, which is the@@ -126,13 +132,18 @@ export async function addAgent(params: AddAgentParams): Promise<AddAgentResult>apiToken: registered.apiKey,agentId: registered.id,});- if (behavior) {- await behavior.writeDefinition(workspace.fs, {- ...params.definitionAttributes,- name: params.name,- description: params.description,- });- }+ // The config file is the agent's configuration; the provider's own file is+ // generated from it, here and on every later edit.+ await writeAgentConfigFile(workspace.fs, params.name, {+ instructions: params.instructions,+ settings: params.definitionAttributes,+ });+ await syncAgentConfig({+ workspaceFs: workspace.fs,+ repoAgents: behavior ?? null,+ name: params.name,+ description: params.description,+ });} finally {workspace.close();}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 27c9ea9d8..a55b21458 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@@ -1,29 +1,24 @@import type { RepoAgentAttributes, RepoAgentField } from '@switch-console/core/agents/plugins';import { getPlugin } from '@main/core/providers/plugin-registry';-import {- attributesFromProviderConfig,- providerConfigFromAttributes,-} from '@shared/core/agents/agent-provider-config';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';-import { readAgentDefinition, updateAgentDefinition } from './agent-definition';+import { readAgentConfig, setAgentSettings } from './agent-config';import { getAgentById } from './getAgentById';-import { setAgentProviderConfig } from './setAgentProviderConfig';/*** An agent's "advanced configuration" — its per-agent model, reasoning effort,* system prompt and whatever else its provider exposes — read and written* without the caller knowing where the provider keeps it.*- * There are two places it can live, and they are not interchangeable:- * - A **repo-agent definition** on disk (Claude Code: `.claude/agents/<name>.md`),- * edited by rewriting the file.- * - A **launch profile** built at spawn from the agent row (Codex:- * `~/.codex/<name>.config.toml`), edited by writing `providerConfig`.+ * All of it is stored in one place — the agent's committed config file — and+ * rendered from there into whatever the provider actually reads: a repo-agent+ * definition on disk (Claude Code: `.claude/agents/<name>.md`), or a launch+ * profile built at spawn (Codex: `~/.codex/<name>.config.toml`). Which of those+ * a provider uses still matters to the caller, because only the second is read+ * once at spawn and so cannot reach a running session, but it is no longer+ * where the values live.*- * Both are per-agent settings collected as the same `RepoAgentField[]` and shown- * in the same form, so the storage split is an implementation detail rather than- * two features. A provider with neither has no advanced configuration and the- * section renders nothing.+ * A provider with neither has no advanced configuration and the section renders+ * nothing.*//** The fields this provider exposes, from whichever surface it keeps them in. */@@ -60,19 +55,14 @@ export function getAgentAdvancedSurface(providerId: AgentProviderId): AgentAdvanexport async function readAgentAdvancedConfig(agentId: string): Promise<RepoAgentAttributes | null> {- const agent = await getAgentById(agentId);- if (!agent) throw new Error(`No agent with id ${agentId}`);-- if (getPlugin(agent.providerId).behavior.repoAgents) {- return readAgentDefinition(agentId);- }- return attributesFromProviderConfig(agent.providerConfig);+ const config = await readAgentConfig(agentId);+ return config.settings ?? {};}/**- * Save new values. Routed to the provider's own surface: a definition rewrite,- * or the agent row plus the side effects a profile change needs (see- * {@link setAgentProviderConfig}).+ * Save new values into the agent's config file, then regenerate whatever its+ * provider reads — including, for a launch-profile provider, the launch spec a+ * remote agent's sidecar holds. See `setAgentSettings`.*/export async function updateAgentAdvancedConfig(params: {agentId: string;@@ -82,14 +72,9 @@ export async function updateAgentAdvancedConfig(params: {if (!agent) throw new Error(`No agent with id ${params.agentId}`);const behavior = getPlugin(agent.providerId).behavior;- if (behavior.repoAgents) {- return updateAgentDefinition(params);- }- if (!behavior.mcp?.launchProfileFields) {+ if (!behavior.repoAgents && !behavior.mcp?.launchProfileFields) {throw new Error(`Agent ${params.agentId} has no editable advanced configuration.`);}- return setAgentProviderConfig({- agentId: params.agentId,- config: providerConfigFromAttributes(agent.providerId, params.attributes),- });++ await setAgentSettings({ agentId: params.agentId, settings: params.attributes });}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.tsnew file mode 100644index 000000000..f5d3bf15d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.test.ts@@ -0,0 +1,210 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createPluginFs } from '@main/core/providers/plugin-fs';+import {+ decideArtifactSync,+ fingerprintArtifact,+ parseAgentConfigFile,+ readAgentConfigFile,+ serialiseAgentConfigFile,+ writeAgentConfigFile,+} from './agent-config-file';+import { agentConfigRelativePath, SWITCH_AGENTS_DIR_RELATIVE } from './switch-settings-paths';++let dir: string;++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'switch-console-agent-config-'));+});++afterEach(async () => {+ await fs.rm(dir, { recursive: true, force: true });+});++async function readRaw(slug: string): Promise<string> {+ return fs.readFile(path.join(dir, agentConfigRelativePath(slug)), 'utf8');+}++describe('agent config file location', () => {+ it('sits outside the gitignored credentials directory', () => {+ // The credentials directory is ignored wholesale because its files carry+ // the agent's token; config written inside it could never be committed,+ // which is the whole point of this file.+ expect(agentConfigRelativePath('coder').startsWith(`${SWITCH_AGENTS_DIR_RELATIVE}/`)).toBe(+ false+ );+ expect(agentConfigRelativePath('coder')).toBe('.switch/config/coder.json');+ });+});++describe('serialiseAgentConfigFile', () => {+ it('omits instructions that were never set', () => {+ expect(JSON.parse(serialiseAgentConfigFile({}))).toEqual({});+ });++ it('omits instructions cleared back to empty, rather than writing a blank', () => {+ // Absent means "not specified", which leaves the provider's own default in+ // force — a blank string pinned into the file would not.+ expect(JSON.parse(serialiseAgentConfigFile({ instructions: '' }))).toEqual({});+ });++ it('writes the prompt exactly as given, whitespace included', () => {+ const instructions = ' You review code.\n\n Be terse.\n';+ expect(JSON.parse(serialiseAgentConfigFile({ instructions }))).toEqual({ instructions });+ });++ it('keeps keys it does not model, so a newer app’s settings survive an older one', () => {+ const out = JSON.parse(+ serialiseAgentConfigFile({ instructions: 'hi' }, { futureSetting: { a: 1 } })+ );+ expect(out).toEqual({ futureSetting: { a: 1 }, instructions: 'hi' });+ });+});++describe('parseAgentConfigFile', () => {+ it('reads instructions', () => {+ expect(parseAgentConfigFile('{"instructions":"be terse"}')).toEqual({+ instructions: 'be terse',+ });+ });++ it('treats a file with no instructions as none set', () => {+ expect(parseAgentConfigFile('{}')).toEqual({});+ });++ it('throws on malformed JSON rather than reading as empty', () => {+ // Silently reading as empty would launch the agent with no prompt and+ // overwrite the user's file on the next write.+ expect(() => parseAgentConfigFile('{not json')).toThrow(/not valid JSON/);+ });++ it('throws when the file is not an object', () => {+ expect(() => parseAgentConfigFile('["nope"]')).toThrow(/JSON object/);+ });++ it('ignores an instructions value of the wrong type', () => {+ expect(parseAgentConfigFile('{"instructions":42}')).toEqual({});+ });+});++describe('readAgentConfigFile / writeAgentConfigFile', () => {+ it('reads back what it wrote', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, 'coder', { instructions: 'You review code.' });++ expect(await readAgentConfigFile(pluginFs, 'coder')).toEqual({+ instructions: 'You review code.',+ });+ });++ it('reads null for an agent that has no config file', async () => {+ expect(await readAgentConfigFile(createPluginFs(dir), 'nobody')).toBeNull();+ });++ it('preserves unmodelled keys across a write', async () => {+ const pluginFs = createPluginFs(dir);+ await pluginFs.write(+ agentConfigRelativePath('coder'),+ JSON.stringify({ instructions: 'old', somethingElse: true })+ );++ await writeAgentConfigFile(pluginFs, 'coder', { instructions: 'new' });++ expect(JSON.parse(await readRaw('coder'))).toEqual({+ somethingElse: true,+ instructions: 'new',+ });+ });++ it('drops instructions from the file when they are cleared', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, 'coder', { instructions: 'temporary' });++ await writeAgentConfigFile(pluginFs, 'coder', { instructions: '' });++ expect(JSON.parse(await readRaw('coder'))).toEqual({});+ expect(await readAgentConfigFile(pluginFs, 'coder')).toEqual({});+ });++ it('writes no credentials into the file', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, 'coder', { instructions: 'You review code.' });++ expect(await readRaw('coder')).not.toMatch(/token|api_key|apiKey/i);+ });+});++describe('settings', () => {+ it('keeps a false or zero value, which are choices, not absences', () => {+ const out = JSON.parse(+ serialiseAgentConfigFile({ settings: { background: false, maxTurns: 0 } })+ );+ expect(out.settings).toEqual({ background: false, maxTurns: 0 });+ });++ it('drops blanks, empty lists and nulls, which are not choices', () => {+ const out = JSON.parse(+ serialiseAgentConfigFile({ settings: { model: '', tools: [], effort: null, keep: 'yes' } })+ );+ expect(out.settings).toEqual({ keep: 'yes' });+ });++ it('omits the settings key entirely when nothing is set', () => {+ expect(JSON.parse(serialiseAgentConfigFile({ settings: { model: '' } }))).toEqual({});+ });++ it('round-trips through parse', () => {+ const config = { instructions: 'be terse', settings: { model: 'opus', tools: ['Read'] } };+ expect(parseAgentConfigFile(serialiseAgentConfigFile(config))).toEqual(config);+ });+});++describe('decideArtifactSync', () => {+ const generated = 'GENERATED';++ it('writes when the artifact does not exist yet', () => {+ expect(decideArtifactSync({ current: null, generated, lastRendered: undefined })).toBe('write');+ });++ it('reports in-sync when the artifact already matches', () => {+ expect(+ decideArtifactSync({+ current: generated,+ generated,+ lastRendered: fingerprintArtifact(generated),+ })+ ).toBe('in-sync');+ });++ it('writes when the artifact is exactly what we last generated', () => {+ // The config moved on; nothing local would be lost by regenerating.+ const previous = 'WHAT WE WROTE LAST TIME';+ expect(+ decideArtifactSync({+ current: previous,+ generated,+ lastRendered: fingerprintArtifact(previous),+ })+ ).toBe('write');+ });++ it('adopts when the artifact was edited since we generated it', () => {+ expect(+ decideArtifactSync({+ current: 'SOMEONE EDITED THIS BY HAND',+ generated,+ lastRendered: fingerprintArtifact('WHAT WE WROTE LAST TIME'),+ })+ ).toBe('adopt');+ });++ it('adopts an existing artifact we have never generated', () => {+ // An agent set up before this existed, or by someone else. Treating it as+ // ours to overwrite would discard a prompt this app never wrote.+ expect(+ decideArtifactSync({ current: 'HAND WRITTEN', generated, lastRendered: undefined })+ ).toBe('adopt');+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.tsnew file mode 100644index 000000000..e47817de3--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-file.ts@@ -0,0 +1,222 @@+import { createHash } from 'node:crypto';+import type { PluginFs, RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import { agentConfigRelativePath } from './switch-settings-paths';++/**+ * An agent's committed, secret-free config file (CHOO-2228).+ *+ * The file that already exists per agent — `.switch/agents/<slug>.json` —+ * carries the agent's API token and is gitignored for that reason, so it can+ * never be the home for settings meant to travel. This is its counterpart: no+ * credentials, checked in alongside the code the agent works on, so a second+ * machine opening the same working directory sees the same agent.+ *+ * **Sparse by construction.** Only values someone actually set are written. A+ * key that is absent means "not specified", which is not the same as an empty+ * value — it leaves the provider's own default in force. Writing defaults out+ * explicitly would freeze today's defaults into every user's repository and+ * make a later change to them invisible.+ *+ * This is the source of truth for an agent's configuration. Each provider's+ * own file — a Claude Code subagent definition, a Codex profile, an OpenCode+ * config — is generated from it, so those are outputs rather than places to+ * edit. The one exception is deliberate: a hand-edited Claude Code definition+ * is read back in rather than overwritten, which `rendered` below is what+ * makes decidable.+ */+export type AgentConfigFile = {+ /** The agent's provider-agnostic system prompt. Absent when none is set. */+ instructions?: string;+ /**+ * The agent's remaining settings, keyed by the field keys the provider+ * declares. Provider-specific by nature — Codex has a reasoning effort,+ * Claude Code has a tool list — so this is a map rather than a modelled+ * shape, and a key the provider no longer declares is carried rather than+ * dropped.+ */+ settings?: RepoAgentAttributes;+ /**+ * Fingerprint of the provider artifact as this app last generated it, keyed+ * by the artifact's path relative to the working directory.+ *+ * This is what makes the round trip decidable. Comparing an artifact to what+ * the config would generate right now cannot distinguish "the config+ * changed" from "someone edited the file"; comparing it to what was last+ * written can. A match means the file is untouched and the config should be+ * written out; a mismatch means it was hand-edited and those edits should be+ * read back in.+ */+ rendered?: Record<string, string>;+};++/**+ * Parse an agent config file's text.+ *+ * A file that is unreadable JSON, or holds something other than an object, is+ * reported as such rather than silently treated as empty: the alternative is a+ * read-modify-write that quietly discards whatever the user had, and an agent+ * launching with no instructions when it should have had some.+ */+export function parseAgentConfigFile(raw: string): AgentConfigFile {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (cause) {+ throw new Error(`Agent config file is not valid JSON`, { cause });+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error(`Agent config file must contain a JSON object`);+ }++ const record = parsed as Record<string, unknown>;+ const config: AgentConfigFile = {};+ if (typeof record.instructions === 'string') config.instructions = record.instructions;+ if (isPlainObject(record.settings)) config.settings = record.settings as RepoAgentAttributes;+ if (isPlainObject(record.rendered)) {+ const rendered: Record<string, string> = {};+ for (const [path, digest] of Object.entries(record.rendered)) {+ if (typeof digest === 'string') rendered[path] = digest;+ }+ config.rendered = rendered;+ }+ return config;+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/**+ * Serialise a config file, dropping anything unset.+ *+ * `unknownKeys` are keys read from an existing file that this version does not+ * model; they are written back untouched so a newer Switch Console's settings+ * survive an older one editing the same repository.+ */+export function serialiseAgentConfigFile(+ config: AgentConfigFile,+ unknownKeys: Record<string, unknown> = {}+): string {+ const out: Record<string, unknown> = { ...unknownKeys };+ delete out.instructions;+ delete out.settings;+ delete out.rendered;++ // Blank is how the owner says "none", and none is the absent state — the+ // value itself is written exactly as given, never trimmed, because trimming+ // would quietly reshape a system prompt whose whitespace is deliberate.+ if (config.instructions !== undefined && config.instructions !== '') {+ out.instructions = config.instructions;+ }++ const settings = pruneUnsetSettings(config.settings ?? {});+ if (Object.keys(settings).length > 0) out.settings = settings;++ if (config.rendered && Object.keys(config.rendered).length > 0) out.rendered = config.rendered;++ return `${JSON.stringify(out, null, 2)}\n`;+}++/**+ * Drop settings nobody chose, so the file records decisions rather than a+ * snapshot of today's defaults. Empty strings, empty lists and nulls all mean+ * "not set"; `false` and `0` are real choices and are kept.+ */+function pruneUnsetSettings(settings: RepoAgentAttributes): RepoAgentAttributes {+ const out: RepoAgentAttributes = {};+ for (const [key, value] of Object.entries(settings)) {+ if (value === null || value === undefined) continue;+ if (typeof value === 'string' && value === '') continue;+ if (Array.isArray(value) && value.length === 0) continue;+ out[key] = value;+ }+ return out;+}++/**+ * Read an agent's config file, or null when it has none.+ *+ * A missing file is the ordinary state for an agent nobody has configured, so+ * it reads as null. Anything else — a malformed file, an unreadable one —+ * throws, because continuing would mean launching the agent without+ * instructions its owner believes it has.+ */+export async function readAgentConfigFile(+ fs: PluginFs,+ slug: string+): Promise<AgentConfigFile | null> {+ const raw = await fs.read(agentConfigRelativePath(slug));+ if (raw === null) return null;+ return parseAgentConfigFile(raw);+}++/**+ * Write an agent's config file, preserving keys this version does not model.+ *+ * Read-modify-write rather than clobber: the file is checked in and may have+ * been written by a different version of the app.+ */+export async function writeAgentConfigFile(+ fs: PluginFs,+ slug: string,+ config: AgentConfigFile+): Promise<void> {+ const relativePath = agentConfigRelativePath(slug);+ const existingRaw = await fs.read(relativePath);++ let unknownKeys: Record<string, unknown> = {};+ if (existingRaw !== null) {+ const parsed: unknown = JSON.parse(existingRaw);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {+ unknownKeys = parsed as Record<string, unknown>;+ }+ }++ await fs.write(relativePath, serialiseAgentConfigFile(config, unknownKeys));+}++/**+ * Fingerprint of a generated artifact's exact bytes.+ *+ * Only ever compared against another fingerprint from this same function, so+ * the algorithm is an implementation detail — but it is written into a+ * committed file, so changing it would make every artifact look hand-edited+ * once. Truncated because a collision here means "we failed to notice an edit",+ * not a security boundary.+ */+export function fingerprintArtifact(content: string): string {+ return createHash('sha256').update(content).digest('hex').slice(0, 32);+}++/**+ * What to do about one provider artifact, given the config, the artifact as it+ * currently sits on disk, and the fingerprint of the last generated version.+ *+ * - `write` — the artifact is missing, or it is exactly what was last+ * generated. Nothing local was lost, so generate from the config.+ * - `adopt` — the artifact differs from what was last generated. Somebody+ * edited it by hand; read those edits back into the config rather than+ * overwriting them.+ * - `in-sync` — the artifact already is what the config generates.+ *+ * The distinction `write` vs `adopt` rests entirely on the recorded+ * fingerprint. With no fingerprint — an agent that predates this, or one+ * someone else set up — an existing artifact is treated as hand-authored,+ * because assuming otherwise silently discards a prompt this app never wrote.+ */+export type ArtifactSyncAction = 'write' | 'adopt' | 'in-sync';++export function decideArtifactSync(params: {+ /** The artifact as it is on disk, or null when there is none. */+ current: string | null;+ /** What generating from the current config produces right now. */+ generated: string;+ /** Fingerprint recorded when this app last generated it, if ever. */+ lastRendered: string | undefined;+}): ArtifactSyncAction {+ const { current, generated, lastRendered } = params;+ if (current === null) return 'write';+ if (current === generated) return 'in-sync';+ if (lastRendered === undefined) return 'adopt';+ return fingerprintArtifact(current) === lastRendered ? 'write' : 'adopt';+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.tsnew file mode 100644index 000000000..8066db2c1--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.test.ts@@ -0,0 +1,159 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createPluginFs } from '@main/core/providers/plugin-fs';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { readAgentConfigFile, writeAgentConfigFile } from './agent-config-file';+import { syncAgentConfig } from './agent-config-sync';++let dir: string;++beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'switch-console-config-sync-'));+});++afterEach(async () => {+ await fs.rm(dir, { recursive: true, force: true });+});++const NAME = 'reviewer';+const DESCRIPTION = 'Reviews diffs';+const DEF_PATH = '.claude/agents/reviewer.md';++const claudeRepoAgents = getPlugin('claude').behavior.repoAgents ?? null;++function sync(pluginFs = createPluginFs(dir)) {+ return syncAgentConfig({+ workspaceFs: pluginFs,+ repoAgents: claudeRepoAgents,+ name: NAME,+ description: DESCRIPTION,+ });+}++async function readDefinition(): Promise<string> {+ return fs.readFile(path.join(dir, DEF_PATH), 'utf8');+}++describe('syncAgentConfig', () => {+ it('does nothing for a provider whose files are rebuilt at launch', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, { instructions: 'be terse' });++ const result = await syncAgentConfig({+ workspaceFs: pluginFs,+ repoAgents: null,+ name: NAME,+ description: DESCRIPTION,+ });++ expect(result.action).toBe('not-applicable');+ expect(result.config.instructions).toBe('be terse');+ });++ it('generates the definition from the config', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, {+ instructions: 'Be careful.',+ settings: { model: 'opus' },+ });++ const result = await sync(pluginFs);++ expect(result.action).toBe('written');+ const definition = await readDefinition();+ expect(definition).toContain('model: opus');+ expect(definition).toContain('Be careful.');+ });++ it('reports in-sync on a second run, rather than rewriting', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Be careful.' });+ await sync(pluginFs);++ expect((await sync(pluginFs)).action).toBe('in-sync');+ });++ it('regenerates when the config changed and nobody touched the definition', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, { instructions: 'First.' });+ await sync(pluginFs);++ const config = (await readAgentConfigFile(pluginFs, NAME)) ?? {};+ await writeAgentConfigFile(pluginFs, NAME, { ...config, instructions: 'Second.' });+ const result = await sync(pluginFs);++ expect(result.action).toBe('written');+ expect(await readDefinition()).toContain('Second.');+ });++ it('reads a hand-edited definition back into the config instead of overwriting it', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Generated.' });+ await sync(pluginFs);++ // Somebody edits the subagent file directly, as they always could.+ await pluginFs.write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\nmodel: haiku\n---\n\nHand written.\n`+ );+ const result = await sync(pluginFs);++ expect(result.action).toBe('adopted');+ expect(result.config.instructions).toBe('Hand written.');+ expect(result.config.settings).toMatchObject({ model: 'haiku' });+ expect(await readDefinition()).toContain('Hand written.');+ });++ it('settles after adopting, rather than reporting a hand edit forever', async () => {+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, { instructions: 'Generated.' });+ await sync(pluginFs);+ await pluginFs.write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\n---\n\nHand written.\n`+ );++ expect((await sync(pluginFs)).action).toBe('adopted');+ expect((await sync(pluginFs)).action).toBe('in-sync');+ });++ it('adopts a definition that already existed before this app ever wrote one', async () => {+ // An agent onboarded from a directory someone else set up. Overwriting it+ // would discard a prompt this app never wrote.+ const pluginFs = createPluginFs(dir);+ await pluginFs.write(+ DEF_PATH,+ `---\nname: ${NAME}\ndescription: ${DESCRIPTION}\n---\n\nTheirs, not ours.\n`+ );++ const result = await sync(pluginFs);++ expect(result.action).toBe('adopted');+ expect(result.config.instructions).toBe('Theirs, not ours.');+ });++ it('picks up the config an agent already carries when onboarded elsewhere', async () => {+ // The whole point of the file being committed: a second machine opening the+ // same working directory gets the same agent.+ const pluginFs = createPluginFs(dir);+ await writeAgentConfigFile(pluginFs, NAME, {+ instructions: 'Set on another machine.',+ settings: { model: 'opus' },+ });++ const result = await sync(pluginFs);++ expect(result.config.instructions).toBe('Set on another machine.');+ expect(await readDefinition()).toContain('Set on another machine.');+ });++ it('writes the definition when there is no config at all', async () => {+ const result = await sync();++ expect(result.action).toBe('written');+ // No instructions set, so the description stands in as the prompt.+ expect(await readDefinition()).toContain(DESCRIPTION);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.tsnew file mode 100644index 000000000..bff18ec81--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config-sync.ts@@ -0,0 +1,147 @@+import type {+ IRepoAgentsBehavior,+ PluginFs,+ RepoAgentAttributes,+} from '@switch-console/core/agents/plugins';+import type { AgentConfigFile } from './agent-config-file';+import {+ decideArtifactSync,+ fingerprintArtifact,+ readAgentConfigFile,+ writeAgentConfigFile,+} from './agent-config-file';++/**+ * Reconcile an agent's config file with the provider definition generated from+ * it (CHOO-2228).+ *+ * The config file is the source of truth, so normally the definition is+ * generated from it. The exception is deliberate: Claude Code's subagent file+ * is a normal repository file that people edit directly, and those edits are+ * read back into the config rather than overwritten.+ *+ * Which of the two happened is decided by the fingerprint recorded the last+ * time this app generated the definition — see `decideArtifactSync`. Comparing+ * the file against what the config generates *now* cannot tell the two apart.+ *+ * Providers whose per-agent files are rebuilt from scratch at every launch+ * (Codex, OpenCode) have nothing to reconcile: their files live outside the+ * repository and are outputs only, so this is a no-op for them.+ */+export type AgentConfigSyncResult = {+ /** The config after reconciliation — what callers should read from. */+ config: AgentConfigFile;+ /** What was done, for logging and for telling the user when edits were taken+ * from the definition rather than written to it. */+ action: 'written' | 'adopted' | 'in-sync' | 'not-applicable';+};++export async function syncAgentConfig(params: {+ workspaceFs: PluginFs;+ /** Null for a provider with no repository definitions (Codex, OpenCode). */+ repoAgents: IRepoAgentsBehavior | null;+ /** The agent's name, which is both its config-file key and its definition stem. */+ name: string;+ /** The agent's description, which the definition carries in its frontmatter. */+ description: string;+}): Promise<AgentConfigSyncResult> {+ const { workspaceFs, repoAgents, name, description } = params;++ const config = (await readAgentConfigFile(workspaceFs, name)) ?? {};+ if (!repoAgents) return { config, action: 'not-applicable' };++ const definitionPath = repoAgents.definitionPath(name);+ const generated = repoAgents.renderDefinition(+ definitionAttributes({ config, name, description })+ );+ const current = await workspaceFs.read(definitionPath);++ const action = decideArtifactSync({+ current,+ generated,+ lastRendered: config.rendered?.[definitionPath],+ });++ if (action === 'in-sync') return { config, action };++ if (action === 'adopt') {+ const adopted = await adoptDefinition({ workspaceFs, repoAgents, name, config });+ return { config: adopted, action: 'adopted' };+ }++ await workspaceFs.write(definitionPath, generated);+ const written: AgentConfigFile = {+ ...config,+ rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },+ };+ await writeAgentConfigFile(workspaceFs, name, written);+ return { config: written, action: 'written' };+}++/**+ * Take a hand-edited definition as the new truth: read it back into the config,+ * then regenerate so the two agree again and the fingerprint matches.+ *+ * Regenerating rather than leaving the file alone matters — the definition may+ * hold things the config cannot express (frontmatter this app does not model),+ * and writing the round-tripped version is what makes the next comparison+ * meaningful instead of reporting a hand edit forever.+ */+async function adoptDefinition(params: {+ workspaceFs: PluginFs;+ repoAgents: IRepoAgentsBehavior;+ name: string;+ config: AgentConfigFile;+}): Promise<AgentConfigFile> {+ const { workspaceFs, repoAgents, name, config } = params;++ const attributes = await repoAgents.readDefinition(workspaceFs, name);+ if (attributes === null) {+ throw new Error(`Agent ${name} has a definition that could not be read back.`);+ }++ const { name: _name, description, instructions, ...settings } = attributes;+ const adopted: AgentConfigFile = {+ ...config,+ instructions: typeof instructions === 'string' ? instructions : '',+ settings,+ };++ const definitionPath = repoAgents.definitionPath(name);+ const generated = repoAgents.renderDefinition(+ definitionAttributes({+ config: adopted,+ name,+ description: typeof description === 'string' ? description : '',+ })+ );+ await workspaceFs.write(definitionPath, generated);++ const result: AgentConfigFile = {+ ...adopted,+ rendered: { ...config.rendered, [definitionPath]: fingerprintArtifact(generated) },+ };+ await writeAgentConfigFile(workspaceFs, name, result);+ return result;+}++/**+ * The attribute map a provider renders from: the agent's settings, plus the+ * three things that are the agent's own rather than a setting.+ *+ * `instructions` is passed under that name for every provider — each renders it+ * into whatever mechanism it has, so the key is canonical here and provider+ * -specific only inside the provider.+ */+export function definitionAttributes(params: {+ config: AgentConfigFile;+ name: string;+ description: string;+}): RepoAgentAttributes {+ return {+ ...params.config.settings,+ name: params.name,+ description: params.description,+ instructions: params.config.instructions ?? '',+ };+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.tsnew file mode 100644index 000000000..e8a5c332d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.test.ts@@ -0,0 +1,110 @@+import type { PluginFs } from '@switch-console/core/agents/plugins';+/**+ * Changing an agent's configuration has to reach the thing that launches it —+ * which, for a remote agent, is a launch spec sitting on the VM (CHOO-2228).+ *+ * Writing the config file alone is enough for a provider whose CLI reads its+ * definition at every spawn (Claude Code), and not enough for one whose+ * settings are handed over as a generated profile: there the spec has to be+ * rebuilt, or an auto-started session keeps running on the previous+ * instructions while the app shows the new ones.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++const setAgentProviderConfig = vi.hoisted(() => vi.fn(async (_params: unknown) => {}));+const state = vi.hoisted(() => ({+ providerId: 'codex',+ files: new Map<string, string>(),+}));++const fakeFs = vi.hoisted(+ () => (): PluginFs => ({+ read: async (path: string) => state.files.get(path) ?? null,+ write: async (path: string, content: string) => {+ state.files.set(path, content);+ },+ delete: async (path: string) => {+ state.files.delete(path);+ },+ exists: async (path: string) => state.files.has(path),+ list: async () => [],+ })+);++vi.mock('./getAgentById', () => ({+ getAgentById: async (agentId: string) => ({+ id: agentId,+ name: 'agent-one',+ providerId: state.providerId,+ locationId: 'loc-1',+ }),+}));+vi.mock('./agent-location', () => ({+ getAgentLocation: async () => ({ id: 'loc-1', dir: '/repo', sshHost: 'vm-1' }),+}));+vi.mock('./agent-workspace-fs', () => ({+ resolveWorkspaceFsFor: async () => ({ fs: fakeFs(), close: () => {} }),+}));+vi.mock('./setAgentProviderConfig', () => ({+ setAgentProviderConfig: (params: unknown) => setAgentProviderConfig(params),+}));+vi.mock('@main/core/providers/plugin-registry', () => ({+ getPlugin: (id: string) => ({+ behavior:+ id === 'claude'+ ? {+ repoAgents: {+ definitionPath: (name: string) => `.claude/agents/${name}.md`,+ renderDefinition: (attributes: Record<string, unknown>) =>+ `---\nname: ${String(attributes.name)}\n---\n\n${String(attributes.instructions)}\n`,+ readDefinition: async () => null,+ },+ }+ : { mcp: { launchProfileFields: () => [] } },+ }),+}));++import { setAgentInstructions } from './agent-config';++beforeEach(() => {+ setAgentProviderConfig.mockClear();+ state.files.clear();+ state.providerId = 'codex';+});++describe('setAgentInstructions', () => {+ it('rebuilds the launch profile for a provider that reads one', async () => {+ // Codex takes its instructions as a generated profile file, baked into the+ // remote launch spec. Without this the VM keeps the old prompt.+ await setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' });++ expect(setAgentProviderConfig).toHaveBeenCalledTimes(1);+ expect(setAgentProviderConfig.mock.calls[0]?.[0]).toMatchObject({+ agentId: 'agent-1',+ config: { values: { instructions: 'Be careful.' } },+ });+ });++ it('does not for a provider whose CLI reads the definition itself', async () => {+ // Claude Code launches with `--agent <name>` and reads the definition file+ // fresh each time, which the write above already updated.+ state.providerId = 'claude';++ await setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' });++ expect(setAgentProviderConfig).not.toHaveBeenCalled();+ });++ it('carries a cleared prompt through too, not just a set one', async () => {+ await setAgentInstructions({ agentId: 'agent-1', instructions: 'Be careful.' });+ setAgentProviderConfig.mockClear();++ await setAgentInstructions({ agentId: 'agent-1', instructions: '' });++ expect(setAgentProviderConfig).toHaveBeenCalledTimes(1);+ expect(setAgentProviderConfig.mock.calls[0]?.[0]).toMatchObject({+ agentId: 'agent-1',+ config: null,+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.tsnew file mode 100644index 000000000..96905fb50--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-config.ts@@ -0,0 +1,160 @@+import type { PluginFs, RepoAgentAttributes } from '@switch-console/core/agents/plugins';+import { getPlugin } from '@main/core/providers/plugin-registry';+import { providerConfigFromAttributes } from '@shared/core/agents/agent-provider-config';+import type { Agent } from '@shared/core/agents/agents';+import type { AgentConfigFile } from './agent-config-file';+import { writeAgentConfigFile } from './agent-config-file';+import { syncAgentConfig } from './agent-config-sync';+import { withAgentWorkspace } from './agent-launch-config';+import { getAgentById } from './getAgentById';+import { setAgentProviderConfig } from './setAgentProviderConfig';++/**+ * An agent's configuration, read and written where it actually lives: the+ * committed config file in its working directory (CHOO-2228).+ *+ * Every caller goes through here rather than touching the file, so the+ * reconciliation with the provider's own generated file happens on every read+ * — which is what makes a hand-edited Claude Code subagent definition show up+ * in the app rather than being quietly replaced the next time anything saves.+ *+ * The working directory is where the agent runs, so the file is reachable+ * whenever launching is possible, including over SFTP for a remote agent.+ */++/**+ * The agent's current configuration, reconciled with its provider definition.+ *+ * Reading has a side effect by design: if the definition was edited by hand the+ * edits are adopted into the config, and if the config moved on the definition+ * is regenerated. Doing this on read is what keeps the app from showing a value+ * that is not what the agent will actually launch with.+ */+export async function readAgentConfig(agentId: string): Promise<AgentConfigFile> {+ return withAgentWorkspace(agentId, (agent, fs) => reconcile(agent, fs));+}++/**+ * Replace the agent's configuration and regenerate whatever its provider reads.+ *+ * Write-then-generate, in that order: the config file is the record of what the+ * user chose, and the provider's file is derived from it. A failure part-way+ * leaves the choice recorded and the generated file stale, which the next read+ * repairs — the other order would lose the choice.+ */+export async function writeAgentConfig(params: {+ agentId: string;+ config: AgentConfigFile;+}): Promise<AgentConfigFile> {+ return withAgentWorkspace(params.agentId, async (agent, fs) => {+ await writeAgentConfigFile(fs, agent.name, params.config);+ return reconcile(agent, fs);+ });+}++/** The agent's instructions, or empty when it has none. */+export async function readAgentInstructions(agentId: string): Promise<string> {+ return (await readAgentConfig(agentId)).instructions ?? '';+}++/**+ * Set or clear the agent's instructions, leaving its other settings alone.+ *+ * An empty string clears them, which is a real state — the agent then has no+ * instructions of its own rather than instructions that happen to be blank.+ */+export async function setAgentInstructions(params: {+ agentId: string;+ instructions: string;+}): Promise<AgentConfigFile> {+ return updateAgentConfig(params.agentId, (config) => ({+ ...config,+ instructions: params.instructions,+ }));+}++/** Set the agent's non-instruction settings, leaving its instructions alone. */+export async function setAgentSettings(params: {+ agentId: string;+ settings: RepoAgentAttributes;+}): Promise<AgentConfigFile> {+ return updateAgentConfig(params.agentId, (config) => ({+ ...config,+ settings: params.settings,+ }));+}++/**+ * Read, change, write — in one workspace session.+ *+ * Not read-then-write through the public helpers: over SSH that opens the+ * working directory twice, and it would reconcile twice for one edit.+ */+async function updateAgentConfig(+ agentId: string,+ change: (config: AgentConfigFile) => AgentConfigFile+): Promise<AgentConfigFile> {+ const config = await withAgentWorkspace(agentId, async (agent, fs) => {+ const current = await reconcile(agent, fs);+ await writeAgentConfigFile(fs, agent.name, change(current));+ return reconcile(agent, fs);+ });++ await propagateToLaunchProfile(agentId, config);+ return config;+}++/**+ * Carry a config change into the launch profile, for the providers that read+ * one.+ *+ * A provider with repository definitions (Claude Code) needs nothing here: its+ * CLI reads the definition file itself at every spawn, and the write above+ * already put it in place — on a remote host too, over SFTP.+ *+ * The others do. Their settings reach a session as a generated profile file,+ * and on a remote host that file is baked into the launch spec the on-VM+ * sidecar holds. Writing the config file alone would leave that spec stale, so+ * an auto-started session would keep running on the previous instructions while+ * the app showed the new ones. This is what rewrites it.+ *+ * Done for every write rather than by each caller, so a new way to change the+ * config cannot forget it and quietly reintroduce that gap.+ */+async function propagateToLaunchProfile(agentId: string, config: AgentConfigFile): Promise<void> {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error(`No agent with id ${agentId}`);++ const behavior = getPlugin(agent.providerId).behavior;+ if (behavior.repoAgents || !behavior.mcp?.launchProfileFields) return;++ await setAgentProviderConfig({+ agentId,+ config: providerConfigFromAttributes(agent.providerId, {+ ...config.settings,+ instructions: config.instructions ?? '',+ }),+ });+}++/**+ * Bring the config file and the provider's generated file into agreement.+ *+ * The description comes from the definition rather than from the agent's Switch+ * server: it is the server's to own, and this must not blank it when the server+ * is unreachable. It round-trips through the definition anyway, so reading it+ * from there is both correct and one fewer thing that can fail at launch.+ */+async function reconcile(agent: Agent, fs: PluginFs): Promise<AgentConfigFile> {+ const repoAgents = getPlugin(agent.providerId).behavior.repoAgents ?? null;+ const existing = repoAgents ? await repoAgents.readDefinition(fs, agent.name) : null;+ const description = typeof existing?.description === 'string' ? existing.description : '';++ const { config } = await syncAgentConfig({+ workspaceFs: fs,+ repoAgents,+ name: agent.name,+ description,+ });+ return config;+}diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.tsnew file mode 100644index 000000000..5f6a7fe44--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-launch-config.ts@@ -0,0 +1,87 @@+import type { PluginFs, SwitchLaunchSpecialization } from '@switch-console/core/agents/plugins';+import { log } from '@main/lib/logger';+import type { Agent } from '@shared/core/agents/agents';+import type { AgentConfigFile } from './agent-config-file';+import { readAgentConfigFile } from './agent-config-file';+import { getAgentLocation } from './agent-location';+import { resolveWorkspaceFsFor } from './agent-workspace-fs';+import { getAgentById } from './getAgentById';++/**+ * Reading an agent's configuration in order to launch it (CHOO-2228).+ *+ * Split from the read/write module deliberately. Saving configuration has to+ * reach a remote agent's launch spec, which means depending on the sidecar+ * machinery — and that machinery in turn wants to know what to launch with, so+ * keeping both in one module makes a cycle. The launch side needs none of it:+ * it only reads a file.+ */++/**+ * The agent's stored configuration, without reconciling it against the+ * provider's generated file.+ *+ * For the paths that only need to know what to launch with — spawning a+ * session, building a remote launch spec, reporting sidecar diagnostics. Those+ * run in the background and on a timer, and the reconciling read writes files+ * as part of reading, which is not something a status poll should do.+ *+ * Returns an empty config when the agent has no file yet, and when the working+ * directory cannot be reached: an agent that has never been configured and one+ * whose host is down both mean "nothing to specialize with", and failing the+ * launch over a missing optional file would be worse than launching with the+ * provider's own defaults. The failure is logged rather than swallowed.+ */+export async function readAgentConfigForLaunch(agentId: string): Promise<AgentConfigFile> {+ try {+ return await withAgentWorkspace(+ agentId,+ async (agent, fs) => (await readAgentConfigFile(fs, agent.name)) ?? {}+ );+ } catch (error) {+ log.warn('Could not read agent config; launching with provider defaults', {+ event: 'agent_config_read_failed',+ agentId,+ error: error instanceof Error ? error.message : String(error),+ });+ return {};+ }+}++/**+ * The values a provider's launch profile is built from: the agent's settings+ * plus its instructions, under the canonical key every provider renders.+ */+export async function agentLaunchSpecialization(+ agentId: string+): Promise<SwitchLaunchSpecialization | undefined> {+ const config = await readAgentConfigForLaunch(agentId);+ const specialization: SwitchLaunchSpecialization = {};++ for (const [key, value] of Object.entries(config.settings ?? {})) {+ if (value === null || value === undefined) continue;+ const text = Array.isArray(value) ? value.join(',') : String(value);+ if (text.trim() === '') continue;+ specialization[key] = text;+ }+ if (config.instructions) specialization.instructions = config.instructions;++ return Object.keys(specialization).length > 0 ? specialization : undefined;+}++/** Run `run` against the agent's working directory, local or over SFTP. */+export async function withAgentWorkspace<T>(+ agentId: string,+ run: (agent: Agent, fs: PluginFs) => Promise<T>+): Promise<T> {+ const agent = await getAgentById(agentId);+ if (!agent) throw new Error(`No agent with id ${agentId}`);++ const location = await getAgentLocation(agent);+ const workspace = await resolveWorkspaceFsFor(location.sshHost, location.dir);+ try {+ return await run(agent, workspace.fs);+ } finally {+ workspace.close();+ }+}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 bae424dc1..770f8f667 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@@ -11,6 +11,7 @@ import {readAgentAdvancedConfig,updateAgentAdvancedConfig,} from './agent-advanced-config';+import { readAgentInstructions, setAgentInstructions } from './agent-config';import { readAgentDefinition, updateAgentDefinition } from './agent-definition';import { getAgentModelCatalogue } from './agent-model-catalogue';import { assignAgentServer } from './assignAgentServer';@@ -62,6 +63,15 @@ export const agentsController = createRPCController({*/modelCatalogue: (params: { providerId: AgentProviderId; sshHost: string | null; dir: string }) =>getAgentModelCatalogue(params),+ /**+ * The agent's instructions — its system prompt, held in the committed config+ * file in its working directory and rendered into whatever its provider+ * reads. Separate from `readAdvancedConfig` because it is a main attribute of+ * the agent rather than one of its provider's settings.+ */+ readInstructions: (params: { agentId: string }) => readAgentInstructions(params.agentId),+ updateInstructions: (params: { agentId: string; instructions: string }): Promise<void> =>+ setAgentInstructions(params).then(() => undefined),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/remote-session-reconciler.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.tsindex f7d75d648..29a0ce2c1 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-session-reconciler.ts@@ -14,11 +14,11 @@ import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { makePtyId } from '@shared/core/pty/ptyId';import { HostUnreachableError } from '@shared/core/remote-hosts/reachability';import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';+import { agentLaunchSpecialization } from './agent-launch-config';import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';import { getAgentById } from './getAgentById';@@ -435,7 +435,7 @@ class RemoteSessionReconciler {autoApprove: agent.autoApprove,credsSlug: agent.name ?? agent.id,agentName: agent.name ?? null,- specialization: toSwitchSpecialization(agent.providerConfig),+ specialization: await agentLaunchSpecialization(agent.id),ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.tsindex d30f965d5..39bc45339 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/remote-watcher.ts@@ -3,7 +3,7 @@ import { ensureAgentSidecar } from '@main/core/agent-runtime/impl/ensure-agent-simport { writeWatchEnabled } from '@main/core/agent-runtime/impl/remote-sidecar-launcher';import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';+import { agentLaunchSpecialization } from './agent-launch-config';import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';import { getAgentById } from './getAgentById';@@ -118,7 +118,7 @@ export async function ensureRemoteWatcher(agentId: string): Promise<void> {autoApprove: agent.autoApprove,credsSlug: agent.name ?? agent.id,agentName: agent.name ?? null,- specialization: toSwitchSpecialization(agent.providerConfig),+ specialization: await agentLaunchSpecialization(agent.id),ctx,connectionId,host,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.tsindex bc2593582..98b927717 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/reset-remote-agent.ts@@ -14,9 +14,9 @@ import { db } from '@main/db/client';import { sessions } from '@main/db/schema';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { sessionDeletedChannel } from '@shared/core/sessions/sessionEvents';+import { agentLaunchSpecialization } from './agent-launch-config';import { getRemoteAgentLocation } from './agent-location';import { connectRemoteAgent } from './connect-remote-agent';import { getAgentById } from './getAgentById';@@ -49,7 +49,7 @@ async function fetchSidecarSessionIds(agent: Agent, conn: RemoteConn): Promise<sautoApprove: agent.autoApprove,credsSlug: agent.name ?? agent.id,agentName: agent.name ?? null,- specialization: toSwitchSpecialization(agent.providerConfig),+ specialization: await agentLaunchSpecialization(agent.id),ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/switch-settings-paths.ts b/console/apps/switch-console-desktop/src/main/core/agents/switch-settings-paths.tsindex 550d3c7ab..d8e6f3aba 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/switch-settings-paths.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/switch-settings-paths.ts@@ -64,3 +64,29 @@ export function agentSettingsRelativePath(slug: string): string {export function agentSettingsPath(dir: string, slug: string): string {return path.join(dir, agentSettingsRelativePath(slug));}++/**+ * Directory, relative to a location's working directory, holding one committed+ * config file per agent (CHOO-2228). Deliberately a sibling of+ * {@link SWITCH_AGENTS_DIR_RELATIVE} rather than a file inside it: that+ * directory is gitignored wholesale because its files carry+ * `SWITCH_API_TOKEN`, so anything written there cannot travel with the+ * repository. This one holds no secrets and is meant to be committed, which is+ * what lets an agent's instructions follow its working directory to another+ * machine instead of living only in one Switch Console's database.+ */+export const SWITCH_AGENT_CONFIG_DIR_RELATIVE = '.switch/config';++/**+ * Relative path (from a location dir) to an agent's committed config file.+ * `slug` is the same per-agent key as {@link agentSettingsRelativePath}, so an+ * agent's credentials and its config are found by one name.+ */+export function agentConfigRelativePath(slug: string): string {+ return `${SWITCH_AGENT_CONFIG_DIR_RELATIVE}/${slug}.json`;+}++/** Absolute path to an agent's committed config file under `dir`. */+export function agentConfigPath(dir: string, slug: string): string {+ return path.join(dir, agentConfigRelativePath(slug));+}diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/controller.tsindex a93a10f24..e2cf209c1 100644--- a/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/controller.ts@@ -7,13 +7,13 @@ import {restartAgentSidecar,stopAgentSidecar,} from '@main/core/agent-runtime/impl/ensure-agent-sidecar';+import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';import { getAgentById } from '@main/core/agents/getAgentById';import { reapStaleSidecarsForAgent } from '@main/core/agents/reap-stale-sidecars';import { events } from '@main/lib/events';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';import { type AgentSidecarStatus, sidecarStatusChannel } from '@shared/events/sidecarEvents';import { createRPCController } from '@shared/lib/ipc/rpc';@@ -47,7 +47,7 @@ async function paramsForAgent(agent: Agent): Promise<AgentSidecarParams> {autoApprove: agent.autoApprove,credsSlug: agent.name ?? agent.id,agentName: agent.name ?? null,- specialization: toSwitchSpecialization(agent.providerConfig),+ specialization: await agentLaunchSpecialization(agent.id),ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,diff --git a/console/apps/switch-console-desktop/src/main/core/sidecar/sidecar-diagnostics.ts b/console/apps/switch-console-desktop/src/main/core/sidecar/sidecar-diagnostics.tsindex 522f01f53..8e4740f3c 100644--- a/console/apps/switch-console-desktop/src/main/core/sidecar/sidecar-diagnostics.ts+++ b/console/apps/switch-console-desktop/src/main/core/sidecar/sidecar-diagnostics.ts@@ -1,11 +1,11 @@import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { readAgentSidecarLog } from '@main/core/agent-runtime/impl/ensure-agent-sidecar';+import { agentLaunchSpecialization } from '@main/core/agents/agent-launch-config';import { getRemoteAgentLocation } from '@main/core/agents/agent-location';import { connectRemoteAgent } from '@main/core/agents/connect-remote-agent';import { getAgents } from '@main/core/agents/getAgents';import { registerDiagnosticSection } from '@main/lib/file-logger';import { log } from '@main/lib/logger';-import { toSwitchSpecialization } from '@shared/core/agents/agent-provider-config';import type { Agent } from '@shared/core/agents/agents';const DIAGNOSTIC_TAIL_LINES = 200;@@ -55,7 +55,7 @@ async function collectForAgent(agent: Agent): Promise<string> {autoApprove: agent.autoApprove,credsSlug: agent.name ?? agent.id,agentName: agent.name ?? null,- specialization: toSwitchSpecialization(agent.providerConfig),+ specialization: await agentLaunchSpecialization(agent.id),ctx: conn.ctx,connectionId: conn.connectionId,host: conn.host,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 f71ad5023..64c19e491 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@@ -285,6 +285,7 @@ export const AddAgentModal = observer(function AddAgentModal({ onClose }: AddLocproviderId: pickState.providerId,serverId: pickState.serverId,description: form.description.trim(),+ instructions: form.instructions,iconUrl: form.iconUrl,autoSession: form.autoSession,autoApprove: form.autoApprove,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsxindex e54d55f1f..9ecf96744 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/configure-agent-panel.tsx@@ -14,6 +14,7 @@ import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';import { Field, FieldGroup, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';import { Input } from '@renderer/lib/ui/input';import { Switch } from '@renderer/lib/ui/switch';+import { Textarea } from '@renderer/lib/ui/textarea';import { policyNamesOwner } from '@shared/core/switch-servers/owner-policy';import type { ConfigureAgentFormState } from './modes';@@ -233,6 +234,7 @@ export const AgentSettingsSection = observer(function AgentSettingsSection({export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState }) {const nameId = useId();const descriptionId = useId();+ const instructionsId = useId();return (<FieldGroup>{/* Above the name, because it is the first thing the finished agent is@@ -291,6 +293,19 @@ export function AgentIdentityFields({ form }: { form: ConfigureAgentFormState })Helps other people and agents understand what this agent is for.</span></Field>++ <Field>+ <FieldLabel htmlFor={instructionsId}>+ Agent instructions <span className="text-foreground-muted">(optional)</span>+ </FieldLabel>+ <Textarea+ id={instructionsId}+ rows={4}+ placeholder="How this agent should work"+ value={form.instructions}+ onChange={(e) => form.setInstructions(e.target.value)}+ />+ </Field></FieldGroup>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.tsindex 991eefba1..811b6c8e8 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/modes.ts@@ -45,6 +45,10 @@ export type PickModeState = ReturnType<typeof usePickMode>;export function useConfigureAgentForm() {const [agentName, setAgentName] = useState('');const [description, setDescription] = useState('');+ // What the agent is for, in its own words (CHOO-2228). Optional: an agent+ // with none runs on its provider's defaults, and the description stands in+ // where a provider needs a prompt.+ const [instructions, setInstructions] = useState('');const [autoSession, setAutoSession] = useState(true);const [autoApprove, setAutoApproveRaw] = useState(false);const [autoApproveTouched, setAutoApproveTouched] = useState(false);@@ -89,6 +93,8 @@ export function useConfigureAgentForm() {nameIsValid,description,setDescription,+ instructions,+ setInstructions,autoSession,setAutoSession,autoApprove,diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsxindex 476aad280..413005502 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/active-location.tsx@@ -1,5 +1,7 @@import { observer } from 'mobx-react-lite';+import { AgentEditsProvider } from '@renderer/features/locations/components/main-panel/agent-edits';import { AgentPageHeader } from '@renderer/features/locations/components/main-panel/agent-page-header';+import { AgentSaveBar } from '@renderer/features/locations/components/main-panel/agent-save-bar';import { SessionList } from '@renderer/features/locations/components/session-view/session-list';import { SettingsPanel } from '@renderer/features/locations/components/settings-view/settings-panel';import { SidecarPanel } from '@renderer/features/locations/components/settings-view/sidecar-panel';@@ -29,13 +31,20 @@ export const ActiveLocation = observer(function ActiveLocation() {const isRemote = store.data.sshHost !== null;return (- <div className="min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto">- <div className="mx-auto flex w-full max-w-[820px] flex-col gap-10 px-8 pb-20">- <AgentPageHeader />- <SettingsPanel />- {isRemote && <SidecarPanel />}- <SessionList />+ <AgentEditsProvider>+ <div className="flex min-h-0 w-full flex-1 flex-col">+ <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">+ <div className="mx-auto flex w-full max-w-[820px] flex-col gap-10 px-8 pb-20">+ <AgentPageHeader />+ <SettingsPanel />+ {isRemote && <SidecarPanel />}+ <SessionList />+ </div>+ </div>+ {/* Outside the scroll area: an edit made at the top of the page should+ not need scrolling to the bottom before it can be saved. */}+ <AgentSaveBar /></div>- </div>+ </AgentEditsProvider>);});diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-edits.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-edits.tsxnew file mode 100644index 000000000..c872e8e6f--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-edits.tsx@@ -0,0 +1,158 @@+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';++/**+ * One save bar for the several editors on an agent page (CHOO-2228).+ *+ * The agent's instructions and its advanced configuration are edited in+ * different places on the page but are one set of pending changes to the+ * person making them, and they write to the same file. So they share a bar:+ * each editor says whether it is dirty and how to save or discard itself, and+ * the bar drives them together.+ *+ * Editors register rather than being listed here, so the bar does not have to+ * know what is on the page — a new editable section joins by calling+ * {@link useAgentEdit}.+ */++/** How to commit or discard one editor's pending changes. */+export type AgentEditHandle = {+ save: () => Promise<void>;+ revert: () => void;+};++type Registration = {+ order: number;+ handle: { current: AgentEditHandle };+};++type AgentEditsValue = {+ register: (id: string, order: number, handle: { current: AgentEditHandle }) => () => void;+ markDirty: (id: string, dirty: boolean) => void;+ dirty: boolean;+ saving: boolean;+ saveAll: () => Promise<void>;+ revertAll: () => void;+};++const AgentEditsContext = createContext<AgentEditsValue | null>(null);++export function AgentEditsProvider({ children }: { children: React.ReactNode }) {+ const registrations = useRef(new Map<string, Registration>());+ const [dirtyIds, setDirtyIds] = useState<ReadonlySet<string>>(() => new Set());+ const [saving, setSaving] = useState(false);++ const register = useCallback(+ (id: string, order: number, handle: { current: AgentEditHandle }) => {+ registrations.current.set(id, { order, handle });+ return () => {+ registrations.current.delete(id);+ setDirtyIds((prev) => {+ if (!prev.has(id)) return prev;+ const next = new Set(prev);+ next.delete(id);+ return next;+ });+ };+ },+ []+ );++ const markDirty = useCallback((id: string, dirty: boolean) => {+ setDirtyIds((prev) => {+ if (prev.has(id) === dirty) return prev;+ const next = new Set(prev);+ if (dirty) next.add(id);+ else next.delete(id);+ return next;+ });+ }, []);++ const saveAll = useCallback(async () => {+ // Sequentially, in registration order. The editors read-modify-write the+ // same config file, so saving them at once would have each overwrite what+ // the other just wrote.+ const pending = [...registrations.current.entries()]+ .filter(([id]) => dirtyIds.has(id))+ .sort(([, a], [, b]) => a.order - b.order);++ setSaving(true);+ try {+ for (const [, registration] of pending) {+ await registration.handle.current.save();+ }+ } finally {+ setSaving(false);+ }+ }, [dirtyIds]);++ const revertAll = useCallback(() => {+ for (const registration of registrations.current.values()) {+ registration.handle.current.revert();+ }+ }, []);++ const value = useMemo(+ () => ({ register, markDirty, dirty: dirtyIds.size > 0, saving, saveAll, revertAll }),+ [register, markDirty, dirtyIds, saving, saveAll, revertAll]+ );++ return <AgentEditsContext.Provider value={value}>{children}</AgentEditsContext.Provider>;+}++/** The bar's own view of the page: whether anything is pending, and how to act. */+export function useAgentEdits(): Pick<+ AgentEditsValue,+ 'dirty' | 'saving' | 'saveAll' | 'revertAll'+> {+ const context = useContext(AgentEditsContext);+ if (!context) {+ throw new Error('useAgentEdits must be used inside an AgentEditsProvider');+ }+ return context;+}++/**+ * Join this editor to the page's save bar.+ *+ * `order` decides the order saves run in when several are pending — lower+ * first. `handle` is read at save time rather than captured, so a save always+ * commits what is on screen now and not what was there when the editor last+ * re-registered.+ *+ * Outside a provider this is inert, so an editor can also be rendered somewhere+ * with no bar (a modal, say) and keep whatever save affordance it has itself.+ */+export function useAgentEdit(params: {+ id: string;+ order: number;+ dirty: boolean;+ save: () => Promise<void>;+ revert: () => void;+}): void {+ const context = useContext(AgentEditsContext);+ const { id, order, dirty } = params;++ const handle = useRef<AgentEditHandle>({ save: params.save, revert: params.revert });+ handle.current = { save: params.save, revert: params.revert };++ const register = context?.register;+ const markDirty = context?.markDirty;++ useEffect(() => {+ if (!register) return;+ return register(id, order, handle);+ }, [register, id, order]);++ useEffect(() => {+ if (!markDirty) return;+ markDirty(id, dirty);+ }, [markDirty, id, dirty]);+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsxnew file mode 100644index 000000000..34da36601--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-instructions-section.tsx@@ -0,0 +1,100 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { useCallback, useEffect, useId, useState } from 'react';+import { describeFailure } from '@renderer/lib/errors/describe-failure';+import { toast } from '@renderer/lib/hooks/use-toast';+import { rpc } from '@renderer/lib/ipc';+import { Field, FieldLabel } from '@renderer/lib/ui/field';+import { Textarea } from '@renderer/lib/ui/textarea';+import { log } from '@renderer/utils/logger';+import { useAgentEdit } from './agent-edits';++/**+ * The agent's instructions — what it is for, in its own words (CHOO-2228).+ *+ * A main attribute of the agent rather than one of its provider's settings, so+ * it sits with the name and description at the top of the page instead of+ * inside advanced configuration. One box for every provider: whichever the+ * agent runs on renders it into whatever that provider actually reads.+ *+ * Saving goes through the page's shared bar rather than a button of its own,+ * so an edit here and an edit to advanced configuration are one save.+ */+export function AgentInstructionsSection({+ locationId,+ agentId,+}: {+ locationId: string;+ agentId: string | undefined;+}) {+ const queryClient = useQueryClient();+ const fieldId = useId();++ const { data: saved } = useQuery({+ queryKey: ['agent-instructions', agentId],+ queryFn: () =>+ agentId ? rpc.agents.readInstructions({ agentId }) : Promise.resolve<string>(''),+ enabled: !!agentId,+ });++ const savedValue = saved ?? '';+ const [value, setValue] = useState('');++ // Re-seed when the stored value changes — after a save, and when the page+ // swaps to a different agent without remounting. No refetch fires while+ // editing, so this does not overwrite what is being typed.+ useEffect(() => {+ setValue(savedValue);+ }, [savedValue]);++ const save = useMutation({+ mutationFn: (instructions: string) =>+ rpc.agents.updateInstructions({ agentId: agentId as string, instructions }),+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: ['agent-instructions', agentId] });+ // The instructions are written into the same file as the advanced+ // settings, and saving them regenerates the provider's own file.+ void queryClient.invalidateQueries({ queryKey: ['agent-advanced-config', agentId] });+ void queryClient.invalidateQueries({ queryKey: ['location-agents', locationId] });+ },+ onError: (error) => {+ log.error('Failed to save agent instructions', { agentId, error });+ const { headline, detail } = describeFailure(error, 'Could not save the instructions.');+ toast({ title: headline, description: detail ?? undefined, variant: 'destructive' });+ void queryClient.invalidateQueries({ queryKey: ['agent-instructions', agentId] });+ },+ });++ const saveMutation = save.mutateAsync;+ const onSave = useCallback(async () => {+ await saveMutation(value);+ }, [saveMutation, value]);++ const onRevert = useCallback(() => setValue(savedValue), [savedValue]);++ useAgentEdit({+ id: 'agent-instructions',+ // Before the advanced settings: both rewrite the same config file, and this+ // is the one the page leads with.+ order: 0,+ dirty: !!agentId && value !== savedValue,+ save: onSave,+ revert: onRevert,+ });++ if (!agentId) return null;++ return (+ <Field>+ <FieldLabel htmlFor={fieldId}>+ Agent instructions <span className="text-foreground-muted">(optional)</span>+ </FieldLabel>+ <Textarea+ id={fieldId}+ rows={4}+ placeholder="How this agent should work"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ </Field>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsxnew file mode 100644index 000000000..19950db8d--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/main-panel/agent-save-bar.tsx@@ -0,0 +1,59 @@+import { useHotkey } from '@tanstack/react-hotkeys';+import { useRef } from 'react';+import {+ getEffectiveHotkey,+ getHotkeyRegistration,+} from '@renderer/lib/hooks/useKeyboardShortcuts';+import { Button } from '@renderer/lib/ui/button';+import { BoundShortcut } from '@renderer/lib/ui/shortcut';+import { useAgentEdits } from './agent-edits';++/**+ * The agent page's pending changes, and what to do about them (CHOO-2228).+ *+ * Shown only when something is actually unsaved, so the page is not permanently+ * wearing a bar it has no use for. It sits outside the scrolling content rather+ * than at the end of it: an edit made at the top of a long page would otherwise+ * be saveable only by scrolling to the bottom to find out it could be.+ */+export function AgentSaveBar() {+ const { dirty, saving, saveAll, revertAll } = useAgentEdits();+ const saveRef = useRef<HTMLButtonElement>(null);++ // Bound here rather than globally: ⌘S means "save these edits" only while+ // there are edits to save, and typing in the instructions box is exactly when+ // someone reaches for it — so this must fire with a textarea focused.+ useHotkey(+ getHotkeyRegistration('saveChanges'),+ (event) => {+ event.preventDefault();+ saveRef.current?.click();+ },+ { enabled: dirty && !saving && getEffectiveHotkey('saveChanges') !== null }+ );++ if (!dirty) return null;++ return (+ <div className="flex shrink-0 items-center justify-between gap-4 border-t border-border bg-background px-8 py-4">+ <span className="text-sm text-foreground-muted">Unsaved changes</span>+ <div className="flex items-center gap-2">+ <Button type="button" size="sm" variant="outline" disabled={saving} onClick={revertAll}>+ Revert+ </Button>+ <Button+ ref={saveRef}+ type="button"+ size="sm"+ disabled={saving}+ onClick={() => void saveAll()}+ >+ <span className="flex items-center gap-2">+ {saving ? 'Saving…' : 'Save'}+ <BoundShortcut settingsKey="saveChanges" />+ </span>+ </Button>+ </div>+ </div>+ );+}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 c010b76ef..5499f7491 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@@ -1,7 +1,7 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { Loader2, RefreshCw } from 'lucide-react';import { observer } from 'mobx-react-lite';-import { useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import {advancedFields,attributesFromForm,@@ -16,6 +16,7 @@ import {fieldWithCatalogue,type ModelCatalogueResult,} from '@renderer/features/locations/components/agent-model-catalogue';+import { useAgentEdit } from '@renderer/features/locations/components/main-panel/agent-edits';import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';import { isProvisioned } from '@renderer/features/sessions/stores/session-store';import { describeFailure } from '@renderer/lib/errors/describe-failure';@@ -147,6 +148,12 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSettiresetSave();}, [agentId, resetSave]);+ const saveMutation = save.mutateAsync;+ const onSave = useCallback(async () => {+ await saveMutation();+ }, [saveMutation]);+ const onRevert = useCallback(() => setForm(savedForm), [savedForm]);+const [restartFailed, setRestartFailed] = useState<string[]>([]);const restart = useMutation({mutationFn: async () => {@@ -184,15 +191,27 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti},});- if (!editable || fields.length === 0) return null;-const dirty =+ editable &&+ fields.length > 0 &&JSON.stringify(attributesFromForm(fields, form)) !==- JSON.stringify(attributesFromForm(fields, savedForm));+ JSON.stringify(attributesFromForm(fields, savedForm));const setField = (key: string, value: FormValue) =>setForm((prev) => ({ ...prev, [key]: value }));+ // Saved from the page's bar rather than a button here: an edit to these and an+ // edit to the instructions above are one set of pending changes to the reader.+ useAgentEdit({+ id: 'agent-advanced-config',+ order: 1,+ dirty,+ save: onSave,+ revert: onRevert,+ });++ if (!editable || fields.length === 0) return null;+// 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@@ -212,8 +231,8 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti/><div className={cn('flex flex-col gap-4 pt-3', !open && 'hidden')}><FieldDescription className="text-foreground-muted">- The agent's model, reasoning effort, tools, and system prompt. The agent name is- fixed.+ The agent's model, reasoning effort and tools. Its instructions are above, and its+ name is fixed.</FieldDescription>{fields.map((field) => {const catalogueState = fieldCatalogueState(field, form, catalogue);@@ -246,17 +265,6 @@ export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSetti</Field>);})}- <div className="flex justify-end">- <Button- type="button"- size="sm"- disabled={!dirty || save.isPending}- onClick={() => save.mutate()}- >- {save.isPending ? 'Saving...' : 'Save'}- </Button>- </div>-{showStaleNotice && (<div className="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3"><p className="text-xs text-foreground-muted">diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsxindex 5950c44f8..edbcc4a48 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx@@ -1,5 +1,6 @@import { useQuery } from '@tanstack/react-query';import { observer } from 'mobx-react-lite';+import { AgentInstructionsSection } from '@renderer/features/locations/components/main-panel/agent-instructions-section';import { SectionLabel } from '@renderer/features/locations/components/main-panel/agent-page-section';import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';import { AgentAdvancedSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section';@@ -40,6 +41,7 @@ export const SettingsPanel = observer(function SettingsPanel() {return (<div className="flex flex-col gap-10">+ <AgentInstructionsSection locationId={locationId} agentId={agentId} /><section className="flex flex-col gap-6"><SectionLabel>General</SectionLabel><AutoSessionSettingsSection locationId={locationId} agentId={agentId} />diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsxnew file mode 100644index 000000000..d31df1076--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-instructions-save.test.tsx@@ -0,0 +1,165 @@+/**+ * Editing an agent's instructions from its page (CHOO-2228).+ *+ * The instructions are a main attribute of the agent, so they sit at the top of+ * the page rather than inside advanced configuration — and they are saved from+ * a bar shared with the other editors on the page, not a button of their own.+ * These pin what that bar owes the reader: it appears only when something is+ * genuinely unsaved, nothing is written until Save, and Revert puts back what+ * was stored rather than clearing the field.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const readInstructions = vi.hoisted(() => vi.fn());+const updateInstructions = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ events: { on: vi.fn() },+ rpc: {+ agents: { readInstructions, updateInstructions },+ },+}));++import { AgentEditsProvider } from '@renderer/features/locations/components/main-panel/agent-edits';+import { AgentInstructionsSection } from '@renderer/features/locations/components/main-panel/agent-instructions-section';+import { AgentSaveBar } from '@renderer/features/locations/components/main-panel/agent-save-bar';++const STORED = 'Answer in French.';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ readInstructions.mockReset();+ readInstructions.mockResolvedValue(STORED);+ updateInstructions.mockReset();+ updateInstructions.mockResolvedValue(undefined);+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function renderPage(): Promise<HTMLDivElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <AgentEditsProvider>+ <AgentInstructionsSection locationId="loc-1" agentId="agent-1" />+ <AgentSaveBar />+ </AgentEditsProvider>+ </QueryClientProvider>+ )+ );+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());+ return container;+}++function field(el: HTMLElement): HTMLTextAreaElement {+ return el.querySelector<HTMLTextAreaElement>('textarea')!;+}++function button(el: HTMLElement, label: RegExp): HTMLButtonElement | undefined {+ return [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ label.test(b.textContent?.trim() ?? '')+ );+}++/** Type into a controlled textarea the way React will notice. */+async function type(target: HTMLTextAreaElement, value: string) {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;+ await act(async () => {+ setter.call(target, value);+ target.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++describe('an agent’s instructions', () => {+ it('shows what is stored', async () => {+ const el = await renderPage();++ expect(field(el).value).toBe(STORED);+ });++ it('offers no save bar until something is edited', async () => {+ const el = await renderPage();++ expect(el.textContent).not.toContain('Unsaved changes');+ expect(button(el, /^Save/)).toBeUndefined();+ });++ it('says there are unsaved changes once edited', async () => {+ const el = await renderPage();+ await type(field(el), 'Answer in Portuguese.');++ expect(el.textContent).toContain('Unsaved changes');+ expect(button(el, /^Save/)).toBeDefined();+ });++ it('writes nothing until Save is pressed', async () => {+ const el = await renderPage();+ const target = field(el);+ await type(target, 'Answer in Portuguese.');+ await act(async () => target.dispatchEvent(new FocusEvent('blur', { bubbles: true })));++ expect(updateInstructions).not.toHaveBeenCalled();+ });++ it('saves the edit, then has nothing left to save', async () => {+ const el = await renderPage();+ await type(field(el), 'Answer in Portuguese.');+ readInstructions.mockResolvedValue('Answer in Portuguese.');++ await act(async () => button(el, /^Save/)!.click());+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());++ expect(updateInstructions).toHaveBeenCalledWith({+ agentId: 'agent-1',+ instructions: 'Answer in Portuguese.',+ });+ expect(el.textContent).not.toContain('Unsaved changes');+ });++ it('reverts to what is stored rather than emptying the box', async () => {+ const el = await renderPage();+ await type(field(el), 'Answer in Portuguese.');++ await act(async () => button(el, /^Revert/)!.click());++ expect(field(el).value).toBe(STORED);+ expect(updateInstructions).not.toHaveBeenCalled();+ expect(el.textContent).not.toContain('Unsaved changes');+ });++ it('saves an emptied box, which is how instructions are cleared', async () => {+ // Empty is a real state — the agent then has none — so it has to be+ // savable rather than read as "nothing to do".+ const el = await renderPage();+ await type(field(el), '');+ readInstructions.mockResolvedValue('');++ expect(el.textContent).toContain('Unsaved changes');+ await act(async () => button(el, /^Save/)!.click());+ for (let i = 0; i < 5; i++) await act(async () => await Promise.resolve());++ expect(updateInstructions).toHaveBeenCalledWith({ agentId: 'agent-1', instructions: '' });+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/shortcuts.ts b/console/apps/switch-console-desktop/src/shared/shortcuts.tsindex 02ecd3ebe..1316c1d72 100644--- a/console/apps/switch-console-desktop/src/shared/shortcuts.ts+++ b/console/apps/switch-console-desktop/src/shared/shortcuts.ts@@ -227,6 +227,12 @@ export const APP_SHORTCUTS = defineShortcuts({description: 'Confirm the current dialog action',category: 'Navigation',},+ saveChanges: {+ defaultHotkey: 'Mod+S',+ label: 'Save Changes',+ description: 'Save the unsaved edits on the current page',+ category: 'Navigation',+ },navigateBack: {defaultHotkey: 'Mod+[',label: 'Go Back',diff --git a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts b/console/packages/core/src/agents/plugins/capabilities/repo-agents.tsindex a9844fb21..15a3d1f94 100644--- a/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts+++ b/console/packages/core/src/agents/plugins/capabilities/repo-agents.ts@@ -140,6 +140,17 @@ export type IRepoAgentsBehavior = {/** The attribute fields this provider supports, in display order. Drives the* create/edit form; the first two are always `name` and `description`. */attributeFields(): RepoAgentField[];+ /**+ * The definition file's exact text for these attributes, without writing it.+ *+ * Must be deterministic: the same attributes always produce the same bytes.+ * The config-file sync tells "someone hand-edited the definition" from "the+ * config moved on" by comparing the file against what was last generated, so+ * a render that varied run to run would report every file as hand-edited.+ */+ renderDefinition(attributes: RepoAgentAttributes): string;+ /** The definition file's path, relative to the working directory. */+ definitionPath(name: string): string;/** Create or overwrite a named agent's on-disk definition from its attributes* (workspace scope). `attributes.name` selects the agent. */writeDefinition(workspaceFs: PluginFs, attributes: RepoAgentAttributes): Promise<void>;diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts b/console/packages/plugins/src/agents/impl/claude/subagents.test.tsindex 6f6a48e8f..6af8d5dcf 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.test.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.test.ts@@ -138,7 +138,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {name: 'reviewer',description: 'Reviews diffs',model: 'opus',- prompt: 'You are a careful reviewer.',+ instructions: 'You are a careful reviewer.',});const raw = await workspaceFs.read(defRel('reviewer'));@@ -153,18 +153,63 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {name: 'reviewer',description: 'Reviews diffs',model: 'opus',- prompt: 'You are a careful reviewer.',+ instructions: 'You are a careful reviewer.',tools: [],});});+ it('falls back to the description for the body when there are no instructions', async () => {+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ name: 'reviewer',+ description: 'Reviews diffs',+ });++ // Claude Code reads the body as the system prompt, so it cannot be empty.+ expect(await workspaceFs.read(defRel('reviewer'))).toBe(+ '---\nname: reviewer\ndescription: Reviews diffs\n---\n\nReviews diffs\n'+ );+ });++ it('does not read the description stand-in back as instructions', async () => {+ // Otherwise the round trip invents a prompt the user never wrote, and the+ // next write pins it as if they had.+ const workspaceFs = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {+ name: 'reviewer',+ description: 'Reviews diffs',+ });++ const attrs = await claudeRepoAgentsBehavior.readDefinition(workspaceFs, 'reviewer');+ expect(attrs?.instructions).toBe('');+ });++ it('generates the same bytes for the same attributes', async () => {+ // The two-way sync tells "someone edited this" from "the config moved on"+ // by comparing bytes against what was last generated, so generating has to+ // be repeatable or every write looks like a hand edit.+ const attributes = {+ name: 'reviewer',+ description: 'Reviews diffs',+ model: 'opus',+ tools: ['Read', 'Grep'],+ instructions: 'Be careful.',+ };+ const first = fakeFs({});+ const second = fakeFs({});+ await claudeRepoAgentsBehavior.writeDefinition(first, attributes);+ await claudeRepoAgentsBehavior.writeDefinition(second, attributes);++ expect(await first.read(defRel('reviewer'))).toBe(await second.read(defRel('reviewer')));+ });+it('always merges the Switch connector tools into a non-empty tools list', async () => {const workspaceFs = fakeFs({});await claudeRepoAgentsBehavior.writeDefinition(workspaceFs, {name: 'reviewer',description: 'Reviews diffs',tools: ['Read', 'Grep'],- prompt: 'body',+ instructions: 'body',});const raw = (await workspaceFs.read(defRel('reviewer'))) ?? '';@@ -208,7 +253,7 @@ describe('claudeRepoAgentsBehavior.writeDefinition / readDefinition', () => {maxTurns: 5,background: true,permissionMode: '',- prompt: 'do work',+ instructions: 'do work',});const raw = (await workspaceFs.read(defRel('worker'))) ?? '';diff --git a/console/packages/plugins/src/agents/impl/claude/subagents.ts b/console/packages/plugins/src/agents/impl/claude/subagents.tsindex 830f23d2e..e2dac8029 100644--- a/console/packages/plugins/src/agents/impl/claude/subagents.ts+++ b/console/packages/plugins/src/agents/impl/claude/subagents.ts@@ -45,16 +45,24 @@ const SWITCH_RULES: readonly string[] = RECOGNISED_SWITCH_CONNECTOR_TOOL_RULES;const MD_SUFFIX = '.md';-/** The `prompt` attribute is the markdown body (system prompt), not frontmatter. */-const BODY_KEY = 'prompt';+/**+ * The markdown body is the subagent's system prompt, and it is written from+ * the agent's provider-agnostic `instructions` (CHOO-2228) rather than from a+ * Claude-specific field. Every provider renders that one attribute into+ * whatever it reads — for Claude Code, this body; for Codex, its developer+ * instructions — so the key here is the canonical one, not `prompt`.+ */+const BODY_KEY = 'instructions';const LIST_KEYS = new Set(['tools', 'disallowedTools']);const NUMBER_KEYS = new Set(['maxTurns']);const BOOLEAN_KEYS = new Set(['background']);/** Attribute fields Claude Code subagents support, in form display order. The- * field keys match the `.claude/agents/<name>.md` frontmatter keys verbatim- * (`prompt` being the body). hooks / mcpServers / skills are intentionally- * omitted — they are nested/block-list YAML, edit the `.md` directly for those. */+ * field keys match the `.claude/agents/<name>.md` frontmatter keys verbatim.+ * The system prompt is not among them: it is the agent's `instructions`, a+ * main attribute alongside name and description rather than an advanced+ * setting. hooks / mcpServers / skills are intentionally omitted — they are+ * nested/block-list YAML, edit the `.md` directly for those. */const CLAUDE_SUBAGENT_FIELDS: RepoAgentField[] = [{key: 'name',@@ -73,13 +81,6 @@ const CLAUDE_SUBAGENT_FIELDS: RepoAgentField[] = [placeholder: 'Reviews diffs for correctness and style.',help: 'When the parent should delegate to this subagent.',},- {- key: 'prompt',- label: 'System prompt',- type: 'textarea',- placeholder: 'Defaults to the description. Add instructions to specialise the subagent.',- help: "The subagent's system prompt (the markdown body).",- },{key: 'model',label: 'Model',@@ -304,6 +305,10 @@ function serializeDefinition(attributes: RepoAgentAttributes): string {}lines.push('---');+ // An agent with no instructions still needs a body — Claude Code reads it as+ // the system prompt — so the description stands in, as it always has. The+ // read-back below undoes exactly this, so the substitution never comes back+ // as instructions the user never wrote.const body = toScalar(attributes[BODY_KEY]) || description;return body.length > 0 ? `${lines.join('\n')}\n\n${body}\n` : `${lines.join('\n')}\n`;}@@ -476,6 +481,14 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {return CLAUDE_SUBAGENT_FIELDS;},+ renderDefinition(attributes: RepoAgentAttributes): string {+ return serializeDefinition(attributes);+ },++ definitionPath(name: string): string {+ return definitionRelPath(name);+ },+async writeDefinition(workspaceFs, attributes: RepoAgentAttributes): Promise<void> {const name = toScalar(attributes.name);await workspaceFs.write(definitionRelPath(name), serializeDefinition(attributes));@@ -486,10 +499,16 @@ export const claudeRepoAgentsBehavior: IRepoAgentsBehavior = {if (content === null) return null;const fields = parseFrontmatterFields(content);+ const description = fields.description ?? '';+ // A body that is just the description is the stand-in `serializeDefinition`+ // writes for an agent with no instructions of its own. Reading it back as+ // instructions would invent a prompt on the round trip, and then pin it.+ const body = extractBody(content);+const attributes: RepoAgentAttributes = {name: fields.name ?? name,- description: fields.description ?? '',- [BODY_KEY]: extractBody(content),+ description,+ [BODY_KEY]: body === description ? '' : body,};for (const key of FRONTMATTER_FIELD_KEYS) {const raw = fields[key.toLowerCase()];diff --git a/console/packages/plugins/src/agents/impl/codex/profile.test.ts b/console/packages/plugins/src/agents/impl/codex/profile.test.tsindex f42101666..b697fb78c 100644--- a/console/packages/plugins/src/agents/impl/codex/profile.test.ts+++ b/console/packages/plugins/src/agents/impl/codex/profile.test.ts@@ -2,6 +2,7 @@ import { parse as parseTOML } from 'smol-toml';import { describe, expect, it } from 'vitest';import {buildCodexProfileToml,+ CODEX_PROFILE_SETTING_KEYS,CODEX_REASONING_EFFORTS,CODEX_REASONING_SUMMARIES,CODEX_VERBOSITY_LEVELS,@@ -197,17 +198,24 @@ describe('codexProfileName', () => {});describe('codexLaunchProfileFields', () => {- it('declares exactly the keys the profile builder consumes', () => {+ it('declares exactly the advanced keys the profile builder consumes', () => {expect(codexLaunchProfileFields().map((field) => field.key)).toEqual(['model','effort','verbosity','reasoningSummary','webSearch',- 'instructions',]);});+ it('does not offer instructions as an advanced setting', () => {+ // Instructions are a main attribute of the agent, collected once for every+ // provider. Offering them here too would be two boxes for one value.+ expect(codexLaunchProfileFields().map((field) => field.key)).not.toContain('instructions');+ // Still written into the profile, since Codex reads only its own file.+ expect(CODEX_PROFILE_SETTING_KEYS).toContain('instructions');+ });+it('offers every reasoning effort the profile accepts, plus an unset default', () => {const effort = codexLaunchProfileFields().find((field) => field.key === 'effort');@@ -217,12 +225,9 @@ describe('codexLaunchProfileFields', () => {]);});- it('writes every declared field, so a field cannot be collected and then dropped', () => {+ it('writes every declared setting, so one cannot be collected and then dropped', () => {const filled = Object.fromEntries(- codexLaunchProfileFields().map((field) => [- field.key,- field.key === 'webSearch' ? 'true' : 'x',- ])+ CODEX_PROFILE_SETTING_KEYS.map((key) => [key, key === 'webSearch' ? 'true' : 'x']));const toml = parseTOML(buildCodexProfileToml(filled));diff --git a/console/packages/plugins/src/agents/impl/codex/profile.ts b/console/packages/plugins/src/agents/impl/codex/profile.tsindex 1e4112b38..80b2823d6 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/profile.test.ts b/console/packages/plugins/src/agents/impl/opencode/profile.test.tsindex 9a3196408..66d4a8813 100644--- a/console/packages/plugins/src/agents/impl/opencode/profile.test.ts+++ b/console/packages/plugins/src/agents/impl/opencode/profile.test.ts@@ -21,7 +21,7 @@ function configOf(profile: NonNullable<ReturnType<typeof opencodeLaunchProfile>>}describe('opencodeLaunchProfileFields', () => {- it('declares exactly the keys the config builder consumes', () => {+ it('declares exactly the advanced keys the config builder consumes', () => {expect(opencodeLaunchProfileFields().map((field) => field.key)).toEqual(['model','variant',@@ -30,10 +30,15 @@ describe('opencodeLaunchProfileFields', () => {'maxSteps','webSearch','smallModel',- 'instructions',]);});+ it('does not offer instructions as an advanced setting', () => {+ // Instructions are a main attribute of the agent, collected once for every+ // provider. Offering them here too would be two boxes for one value.+ expect(opencodeLaunchProfileFields().map((field) => field.key)).not.toContain('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.diff --git a/console/packages/plugins/src/agents/impl/opencode/profile.ts b/console/packages/plugins/src/agents/impl/opencode/profile.tsindex 78886987f..f4bed856b 100644--- a/console/packages/plugins/src/agents/impl/opencode/profile.ts+++ b/console/packages/plugins/src/agents/impl/opencode/profile.ts@@ -93,6 +93,13 @@ const DENY = 'deny';*/type OpencodeSetting = {field: RepoAgentField;+ /**+ * True for a setting that is a main attribute of the agent rather than an+ * advanced one. It is still rendered into the profile — OpenCode only reads+ * its own files — but it is collected once, provider-agnostically, so it is+ * not offered again in this provider's advanced form.+ */+ topLevel?: boolean;path?: string;scope?: 'agent' | 'config';toValue?: (raw: string) => unknown;@@ -208,12 +215,13 @@ const OPENCODE_SETTINGS: OpencodeSetting[] = [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.",},+ topLevel: true,},];/** The fields the "advanced configuration" form renders for an OpenCode agent. */export function opencodeLaunchProfileFields(): RepoAgentField[] {- return OPENCODE_SETTINGS.map((setting) => setting.field);+ return OPENCODE_SETTINGS.filter((setting) => !setting.topLevel).map((setting) => setting.field);}/** Set a dotted path within an object, creating the intermediate objects. */