A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat: manage the assistant's own profiles from the app, with a one-time Gentle Shell import
Alan Buscagliafd95ee7c6af1
diff --git a/e2e/serve.ts b/e2e/serve.tsindex 57677d9..42bbdac 100644--- a/e2e/serve.ts+++ b/e2e/serve.ts@@ -1,17 +1,21 @@// Starts the daemon for Playwright with the fake agent, a fresh data dir, and a known token.import { mkdirSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";-import { E2E_TOKEN } from "./token.ts";+import { E2E_COMMANDS_FILE, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";-const dataDir = join(tmpdir(), "gentle-dot-e2e");+const dataDir = E2E_DATA_DIR;rmSync(dataDir, { recursive: true, force: true });mkdirSync(dataDir, { recursive: true });writeFileSync(join(dataDir, "token"), `${E2E_TOKEN}\n`, { mode: 0o600 });// Provider keys in the developer's environment would mark accounts as connected.delete process.env.OPENAI_API_KEY;+// Never offer to import the developer's own profiles.+process.env.GENTLE_PI_CONFIG_HOME = join(dataDir, "no-shell-profiles");+// Profiles are applied to <dataDir>/agent; the fake agent records the live model switch.+delete process.env.GENTLE_DOT_AGENT_HOME;+process.env.FAKE_AGENT_COMMANDS_FILE = E2E_COMMANDS_FILE;process.env.GENTLE_DOT_DATA_DIR = dataDir;process.env.GENTLE_DOT_WORKSPACE = dataDir;process.env.GENTLE_DOT_AGENT_BIN = process.execPath;diff --git a/e2e/token.ts b/e2e/token.tsindex 5eed954..b0ab198 100644--- a/e2e/token.ts+++ b/e2e/token.ts@@ -1 +1,8 @@+import { tmpdir } from "node:os";+import { join } from "node:path";+export const E2E_TOKEN = "e2e-token-0123456789abcdefghijklmnopqrstuv";+/** The daemon's data dir during e2e runs (see serve.ts). */+export const E2E_DATA_DIR = join(tmpdir(), "gentle-dot-e2e");+/** The fake agent appends every model command it receives here. */+export const E2E_COMMANDS_FILE = join(E2E_DATA_DIR, "agent-commands.jsonl");diff --git a/e2e/web.spec.ts b/e2e/web.spec.tsindex 83266a9..4358a9f 100644--- a/e2e/web.spec.ts+++ b/e2e/web.spec.ts@@ -1,5 +1,17 @@+import { existsSync, readFileSync } from "node:fs";+import { join } from "node:path";import { expect, type Page, test } from "@playwright/test";-import { E2E_TOKEN } from "./token.ts";+import { E2E_COMMANDS_FILE, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";++const readJson = (path: string) =>+ existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as unknown) : undefined;+const agentCommands = () =>+ existsSync(E2E_COMMANDS_FILE)+ ? readFileSync(E2E_COMMANDS_FILE, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as unknown)+ : [];async function open(page: Page) {await page.goto(`/#token=${E2E_TOKEN}`);@@ -87,6 +99,54 @@ test("opens accounts with /login and connects and disconnects an API key", asyncawait expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();});+test("creates a profile with /profiles, edits a role, and switches to it", async ({ page }) => {+ await open(page);+ await say(page, "/profiles");+ const profiles = page.getByRole("region", { name: "Profiles" });+ await expect(profiles).toBeVisible();+ await expect(profiles.getByText("No profiles yet.")).toBeVisible();+ await expect(profiles.getByRole("button", { name: "Import my Gentle Shell profiles" })).toBeHidden();++ await profiles.getByRole("button", { name: "New profile" }).click();+ await profiles.getByRole("textbox", { name: "Profile name" }).fill("e2e-focus");+ await profiles.getByRole("combobox", { name: "Main assistant model" }).selectOption({ label: "Fake Fast" });+ await profiles.getByRole("button", { name: "Save" }).click();+ const item = profiles.getByRole("listitem").filter({ has: page.getByText("e2e-focus", { exact: true }) });+ await expect(item).toContainText("Main assistant: Fake Fast");++ await item.getByRole("button", { name: "Edit" }).click();+ await profiles.getByRole("combobox", { name: "Main assistant thinking" }).selectOption("high");+ await profiles.getByRole("button", { name: "Save" }).click();+ await expect(item).toContainText("Main assistant: Fake Fast · High");++ expect(agentCommands()).toEqual([]);+ await item.getByRole("button", { name: "Use" }).click();+ await expect(item.getByText("In use")).toBeVisible();+ await expect(item.getByRole("button", { name: "Use" })).toBeHidden();++ const roles = { orchestrator: { model: "fake/fake-fast", thinking: "high" } };+ expect(readJson(join(E2E_DATA_DIR, "gentle-ai", "profiles.json"))).toEqual({+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: { "e2e-focus": roles },+ active: "e2e-focus",+ });+ expect(readJson(join(E2E_DATA_DIR, "gentle-ai", "models.json"))).toEqual(roles);+ expect(readJson(join(E2E_DATA_DIR, "agent", "settings.json"))).toEqual({+ defaultProvider: "fake",+ defaultModel: "fake-fast",+ defaultThinkingLevel: "high",+ });+ await expect.poll(agentCommands).toEqual([+ { type: "set_model", provider: "fake", modelId: "fake-fast", busy: false },+ { type: "set_thinking_level", level: "high", busy: false },+ ]);++ await profiles.getByRole("button", { name: "Close profiles" }).click();+ await page.getByRole("button", { name: "Profiles" }).click();+ await expect(page.getByRole("region", { name: "Profiles" }).getByText("In use")).toBeVisible();+});+test("explains a rejected access key", async ({ page }) => {await page.goto("/#token=wrong-token");await expect(page.getByRole("status")).toContainText("This link is not valid anymore");diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 37bb963..3a7d59e 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -1,5 +1,12 @@import { join } from "node:path";-import type { AgentState, Ask, ClientMessage, ServerPayload } from "@gentle-dot/protocol";+import {+ type AgentState,+ type Ask,+ type ClientMessage,+ isThinkingLevel,+ type RoleRoute,+ type ServerPayload,+} from "@gentle-dot/protocol";import type { AuthManager } from "./auth.ts";import {conversationIdOf,@@ -8,6 +15,13 @@ import {resolveConversation,} from "./conversations.ts";import { describeTool, textOf } from "./presentation.ts";+import {+ LiveModelSwitch,+ ProfileError,+ type ProfileStore,+ type SwitchOutcome,+ toModelOptions,+} from "./profiles.ts";import type { AgentRecord, AgentSupervisor, SupervisorEvent } from "./supervisor.ts";import { isBlockedInput, presentText, shouldShowToast } from "./white-label.ts";@@ -19,8 +33,23 @@ export interface BridgeOptions {dataDir: string;log?: (line: string) => void;auth?: AuthManager;+ profiles?: ProfileStore;}+type ProfileCommand = Extract<+ ClientMessage,+ {+ type:+ | "profile_save"+ | "profile_rename"+ | "profile_duplicate"+ | "profile_delete"+ | "profile_apply"+ | "profile_import"+ | "profile_save_current";+ }+>;+const DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);/** An open dialog; `options` keeps the agent's original option strings for the answer. */@@ -45,10 +74,12 @@ export class DotBridge {private nextMessage = 0;private assistantId: string | undefined;private restartPending = false;+ private readonly liveSwitch: LiveModelSwitch;constructor(supervisor: AgentSupervisor, options: BridgeOptions) {this.supervisor = supervisor;this.options = options;+ this.liveSwitch = new LiveModelSwitch(supervisor, (line) => this.log(line));this.sessionDir = join(options.dataDir, "sessions");supervisor.onEvent((event) => this.onAgentEvent(event));if (options.auth) options.auth.onCredentialsChanged = () => this.afterCredentialsChange();@@ -109,6 +140,10 @@ export class DotBridge {await this.sendProviders(client, true);return;}+ if (/^\s*\/profiles\s*$/i.test(message.text)) {+ await this.sendProfiles(client, true);+ return;+ }this.interrupted = false;const busy = this.supervisor.busy;await this.supervisor.request(@@ -197,6 +232,18 @@ export class DotBridge {case "auth_logout":await this.requireAuth().logout(message.providerId);return;+ case "profiles_list":+ await this.sendProfiles(client);+ return;+ case "profile_save":+ case "profile_rename":+ case "profile_duplicate":+ case "profile_delete":+ case "profile_apply":+ case "profile_import":+ case "profile_save_current":+ await this.profileCommand(client, message);+ return;case "get_history":this.deliver(client, {type: "history",@@ -217,6 +264,101 @@ export class DotBridge {this.deliver(client, { type: "auth_providers", providers, ...(open ? { open: true } : {}) });}+ private requireProfiles(): ProfileStore {+ if (!this.options.profiles) throw new Error("profiles are not available");+ return this.options.profiles;+ }++ private async sendProfiles(client: BridgeClient, open = false): Promise<void> {+ try {+ this.deliver(client, { ...(await this.profilesPayload()), ...(open ? { open: true } : {}) });+ } catch (error) {+ if (!(error instanceof ProfileError)) throw error;+ this.deliver(client, { type: "error", code: error.code, message: error.message });+ }+ }++ private async profilesPayload(): Promise<Extract<ServerPayload, { type: "profiles" }>> {+ const store = this.requireProfiles();+ const { profiles, active } = store.list();+ const models = await this.supervisor.request({ type: "get_available_models" }).then(+ (response) => toModelOptions(response.data),+ () => [],+ );+ return {+ type: "profiles",+ profiles,+ ...(active ? { active } : {}),+ roles: store.roles(),+ models,+ importable: store.importable(),+ };+ }++ /** Runs one profile change; every window gets the new list, errors go to the window that asked. */+ private async profileCommand(client: BridgeClient, message: ProfileCommand): Promise<void> {+ const store = this.requireProfiles();+ try {+ switch (message.type) {+ case "profile_save":+ await store.save(message.name, message.roles);+ // Editing the profile in use takes effect right away.+ if (store.list().active === message.name) await this.applyProfile(message.name);+ break;+ case "profile_rename":+ await store.rename(message.from, message.to);+ break;+ case "profile_duplicate":+ await store.duplicate(message.from, message.to);+ break;+ case "profile_delete":+ await store.remove(message.name);+ break;+ case "profile_apply":+ await this.applyProfile(message.name);+ break;+ case "profile_save_current":+ await store.saveCurrent(message.name, await this.runningRoute());+ break;+ case "profile_import": {+ const providers = await (this.options.auth?.providers() ?? Promise.resolve([])).catch(() => []);+ this.deliver(client, { type: "profiles_imported", ...(await store.import(providers)) });+ break;+ }+ }+ } catch (error) {+ if (!(error instanceof ProfileError)) throw error;+ this.deliver(client, { type: "error", code: error.code, message: error.message });+ return;+ }+ this.broadcast(await this.profilesPayload());+ }++ private async applyProfile(name: string): Promise<void> {+ const orchestrator = await this.requireProfiles().apply(name);+ if (orchestrator) this.reportSwitch(await this.liveSwitch.switchTo(orchestrator));+ }++ private reportSwitch(outcome: SwitchOutcome): void {+ if (outcome !== "failed") return;+ this.broadcast({+ type: "toast",+ level: "warning",+ message:+ "Profile applied. The main assistant keeps its current model until that model's account is connected.",+ });+ }++ /** The main assistant's model and thinking level in the running conversation. */+ private async runningRoute(): Promise<RoleRoute | undefined> {+ const response = await this.supervisor.request({ type: "get_state" });+ const state = response.data as { model?: { provider?: unknown; id?: unknown }; thinkingLevel?: unknown };+ if (typeof state?.model?.provider !== "string" || typeof state.model.id !== "string") return undefined;+ const route: RoleRoute = { model: `${state.model.provider}/${state.model.id}` };+ if (isThinkingLevel(state.thinkingLevel)) route.thinking = state.thinkingLevel;+ return route;+ }+/** New credentials: refresh every window, and restart the agent once it is idle so it sees new models. */private afterCredentialsChange(): void {void this.requireAuth()@@ -235,6 +377,11 @@ export class DotBridge {this.supervisor.restart().catch((error: Error) => this.log(`agent restart failed: ${error.message}`));}+ /** A profile applied while the assistant was busy switches the model now. */+ private settleModelSwitch(): void {+ void this.liveSwitch.settle().then((outcome) => this.reportSwitch(outcome));+ }+private afterConversationChange(messages: unknown[]): void {this.interrupted = false;this.assistantId = undefined;@@ -265,6 +412,7 @@ export class DotBridge {switch (event.type) {case "supervisor_state":if (event.state !== "ready") this.clearRun();+ else this.settleModelSwitch();break;case "interrupted":this.interrupted = true;@@ -288,6 +436,7 @@ export class DotBridge {this.assistantId = undefined;// The title of a new conversation comes from its first message.this.broadcast(this.conversationsPayload());+ this.settleModelSwitch();if (this.restartPending) this.restartAgent();break;case "extension_ui_request":diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex a542cff..73ead06 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -7,6 +7,7 @@ import { type ClientMessage, CloseCode, PROTOCOL_VERSION, parseClientMessage } fimport { type WebSocket, WebSocketServer } from "ws";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";+import { defaultImportPath, ProfileStore } from "./profiles.ts";import { AgentSupervisor } from "./supervisor.ts";import { identityArgs } from "./white-label.ts";@@ -23,6 +24,8 @@ export interface DaemonOptions {agentEnv?: NodeJS.ProcessEnv;/** The assistant's own Gentle Shell home (`--home`); profiles go next to it. */agentHome?: string;+ /** Another setup's `profiles.json` offered for a one-time import; defaults to the user's Gentle Shell store. */+ profilesImportPath?: string;/** Creates the sign-in runtime; defaults to Pi's ModelRuntime on the agent home. */authRuntime?: () => Promise<AuthRuntime>;/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */@@ -86,17 +89,17 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(options.backoffMs ? { backoffMs: options.backoffMs } : {}),log: (line) => log(`[agent] ${line}`),});+ const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);const auth = new AuthManager({- runtime:- options.authRuntime ??- (() =>- createModelAuthRuntime(- options.agentHome ?? resolveAgentHome(process.env, options.dataDir),- options.workspace,- )),+ runtime: options.authRuntime ?? (() => createModelAuthRuntime(agentHome, options.workspace)),log,});- const bridge = new DotBridge(supervisor, { dataDir: options.dataDir, log, auth });+ const profiles = new ProfileStore({+ configHome: join(options.dataDir, "gentle-ai"),+ agentHome,+ importPath: options.profilesImportPath ?? defaultImportPath(process.env),+ });+ const bridge = new DotBridge(supervisor, { dataDir: options.dataDir, log, auth, profiles });const server = createServer((req, res) => handleHttp(req, res, options.uiDir, bridge));const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });diff --git a/packages/daemon/src/profiles.ts b/packages/daemon/src/profiles.tsnew file mode 100644index 0000000..a6f6ea2--- /dev/null+++ b/packages/daemon/src/profiles.ts@@ -0,0 +1,611 @@+import { randomUUID } from "node:crypto";+import {+ closeSync,+ constants,+ existsSync,+ mkdirSync,+ openSync,+ readdirSync,+ readFileSync,+ renameSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { homedir } from "node:os";+import { basename, dirname, join } from "node:path";+import {+ type AuthProvider,+ isThinkingLevel,+ isValidProfileName,+ type ModelOption,+ type Profile,+ type ProfileRole,+ type ProfileRoles,+ parseProfileRoles,+ type RoleRoute,+} from "@gentle-dot/protocol";+import { presentText } from "./white-label.ts";++// The engine's profile store format (gentle-pi lib/agent-profiles.ts), reimplemented+// so the assistant can manage profiles without the terminal-only `/gentle:profiles`.+const PROFILES_KIND = "gentle-pi.agent_model_profiles";+const PROFILES_VERSION = 1;+const ORCHESTRATOR = "orchestrator";+/** Review roles route through models.json only; they are never written to subagents.json. */+const REVIEW_ROLES = ["review-refuter", "review-validator"];+const ROLE_NAME = /^[A-Za-z0-9._:@/+%-]+$/;+const MODEL_ID = /^[A-Za-z0-9._~:@/+%-]+$/;+const LOCK_STALE_MS = 10_000;+const LOCK_RETRY_MS = 20;+const LOCK_ATTEMPTS = 250;++export interface ProfilesFile {+ active?: string;+ profiles: Record<string, ProfileRoles>;+}++export type ProfileErrorCode =+ | "invalid_name"+ | "duplicate_name"+ | "missing_profile"+ | "active_profile"+ | "store_invalid"+ | "settings_invalid"+ | "nothing_to_import";++const MESSAGES: Record<ProfileErrorCode, string> = {+ invalid_name:+ "Profile names use 1-64 letters, numbers, dots, dashes, or underscores, starting with a letter or number.",+ duplicate_name: "A profile with that name already exists.",+ missing_profile: "That profile does not exist anymore.",+ active_profile: "That profile is in use. Switch to another one before deleting it.",+ store_invalid: "The saved profiles could not be read, so nothing was changed.",+ settings_invalid: "The assistant's settings could not be read, so the profile was not applied.",+ nothing_to_import: "There are no profiles to import.",+};++/** A profile operation the user can fix; `message` is safe to show. */+export class ProfileError extends Error {+ readonly code: ProfileErrorCode;++ constructor(code: ProfileErrorCode) {+ super(MESSAGES[code]);+ this.name = "ProfileError";+ this.code = code;+ }+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && !Array.isArray(value);++/** One route as the engine normalizes it: a bare string is a model, `effort` aliases `thinking`. */+function normalizeRoute(value: unknown): RoleRoute | undefined {+ if (typeof value === "string") {+ const model = value.trim();+ return model && MODEL_ID.test(model) ? { model } : undefined;+ }+ if (!isRecord(value)) return undefined;+ const model =+ typeof value.model === "string" && MODEL_ID.test(value.model.trim()) ? value.model.trim() : undefined;+ const thinking = isThinkingLevel(value.thinking)+ ? value.thinking+ : isThinkingLevel(value.effort)+ ? value.effort+ : undefined;+ if (!model && !thinking) return Object.keys(value).length === 0 ? {} : undefined;+ const route: RoleRoute = {};+ if (model) route.model = model;+ if (thinking) route.thinking = thinking;+ return route;+}++function normalizeRoles(value: unknown): ProfileRoles | undefined {+ if (!isRecord(value)) return undefined;+ const roles: ProfileRoles = {};+ for (const [role, raw] of Object.entries(value)) {+ if (!ROLE_NAME.test(role)) continue;+ const route = normalizeRoute(raw);+ if (route) roles[role] = route;+ }+ return roles;+}++/** Parses a profile store; undefined when it is not one. Invalid entries are dropped like the engine does. */+export function parseProfilesFile(text: string): ProfilesFile | undefined {+ let value: unknown;+ try {+ value = JSON.parse(text);+ } catch {+ return undefined;+ }+ if (!isRecord(value) || value.kind !== PROFILES_KIND || value.version !== PROFILES_VERSION)+ return undefined;+ if (!isRecord(value.profiles)) return undefined;+ const profiles: Record<string, ProfileRoles> = {};+ for (const [name, raw] of Object.entries(value.profiles)) {+ const roles = isValidProfileName(name) ? normalizeRoles(raw) : undefined;+ if (roles) profiles[name] = roles;+ }+ const file: ProfilesFile = { profiles };+ if (typeof value.active === "string" && Object.hasOwn(profiles, value.active)) file.active = value.active;+ return file;+}++/** Serializes in the engine's key order: kind, version, profiles, active. */+export function serializeProfilesFile(file: ProfilesFile): string {+ const payload: Record<string, unknown> = {+ kind: PROFILES_KIND,+ version: PROFILES_VERSION,+ profiles: file.profiles,+ };+ if (file.active !== undefined) payload.active = file.active;+ return `${JSON.stringify(payload, null, 2)}\n`;+}++const jsonText = (value: unknown) => `${JSON.stringify(value, null, 2)}\n`;++/** Replaces a file through a sibling temp file (mode 0600) and a rename, so readers never see a partial file. */+export function writeFileAtomic(path: string, text: string): void {+ mkdirSync(dirname(path), { recursive: true });+ const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);+ try {+ writeFileSync(fd, text);+ } finally {+ closeSync(fd);+ }+ try {+ renameSync(temporary, path);+ } catch (error) {+ rmSync(temporary, { force: true });+ throw error;+ }+}++function readText(path: string): string | undefined {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return undefined;+ }+}++/** Reads a JSON object file; missing is `{}`, anything else that is not an object throws `code`. */+function readObject(path: string, code: ProfileErrorCode): Record<string, unknown> {+ const text = readText(path);+ if (text === undefined) return {};+ try {+ const value: unknown = JSON.parse(text);+ if (isRecord(value)) return value;+ } catch {}+ throw new ProfileError(code);+}++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/**+ * Runs `fn` holding the same lock Pi's settings storage takes (proper-lockfile:+ * a `<file>.lock` directory, stale after 10 seconds), so the engine never+ * interleaves its own settings write with ours.+ */+async function withFileLock<T>(path: string, fn: () => T): Promise<T> {+ mkdirSync(dirname(path), { recursive: true });+ const lock = `${path}.lock`;+ for (let attempt = 0; ; attempt++) {+ try {+ mkdirSync(lock);+ break;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;+ let stale = false;+ try {+ stale = Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS;+ } catch {}+ if (stale) rmSync(lock, { recursive: true, force: true });+ else if (attempt >= LOCK_ATTEMPTS) throw new Error(`${path} stayed locked`);+ else await sleep(LOCK_RETRY_MS);+ }+ }+ try {+ return fn();+ } finally {+ rmSync(lock, { recursive: true, force: true });+ }+}++function splitModel(model: string): { provider: string; modelId: string } | undefined {+ const at = model.indexOf("/");+ if (at <= 0 || at === model.length - 1) return undefined;+ return { provider: model.slice(0, at), modelId: model.slice(at + 1) };+}++/** The user's own Gentle Shell profile store, from the daemon's environment (never the engine child's). */+export function defaultImportPath(env: NodeJS.ProcessEnv = process.env): string {+ return join(env.GENTLE_PI_CONFIG_HOME || join(homedir(), ".pi", "gentle-ai"), "profiles.json");+}++export interface ProfileStoreOptions {+ /** The assistant's profile store directory (`GENTLE_PI_CONFIG_HOME` of its engine). */+ configHome: string;+ /** The assistant's engine home (`--home`). */+ agentHome: string;+ /** Another setup's `profiles.json`, only ever read, for the one-time import. */+ importPath: string;+}++export interface ImportResult {+ imported: { from: string; to: string }[];+ /** Accounts the imported profiles use that are not connected yet. */+ missingProviders: string[];+}++/**+ * The assistant's own profiles: the engine's store format and the files the+ * engine reads when it routes models. Every write goes through one queue.+ */+export class ProfileStore {+ private readonly options: ProfileStoreOptions;+ private queue: Promise<unknown> = Promise.resolve();++ constructor(options: ProfileStoreOptions) {+ this.options = options;+ }++ private get storePath(): string {+ return join(this.options.configHome, "profiles.json");+ }++ private get modelsPath(): string {+ return join(this.options.configHome, "models.json");+ }++ private get subagentsPath(): string {+ return join(this.options.agentHome, "subagents.json");+ }++ private get settingsPath(): string {+ return join(this.options.agentHome, "settings.json");+ }++ list(): { profiles: Profile[]; active?: string } {+ const file = this.read();+ const profiles = Object.entries(file.profiles)+ .map(([name, roles]) => ({ name, roles }))+ .sort((a, b) => a.name.localeCompare(b.name));+ return file.active === undefined ? { profiles } : { profiles, active: file.active };+ }++ /** Roles the user can route, including any a saved profile routes without an agent file. */+ roles(): ProfileRole[] {+ const routed = Object.values(this.read().profiles).flatMap((roles) => Object.keys(roles));+ return discoverRoles(this.options.agentHome, routed);+ }++ /** Creates or replaces a profile. */+ save(name: string, roles: ProfileRoles): Promise<void> {+ return this.mutate((file) => {+ requireName(name);+ file.profiles[name] = cleanRoles(roles);+ });+ }++ rename(from: string, to: string): Promise<void> {+ return this.mutate((file) => {+ requireExisting(file, from);+ requireFree(file, to);+ file.profiles = Object.fromEntries(+ Object.entries(file.profiles).map(([name, roles]) => [name === from ? to : name, roles]),+ );+ if (file.active === from) file.active = to;+ });+ }++ duplicate(from: string, to: string): Promise<void> {+ return this.mutate((file) => {+ const roles = requireExisting(file, from);+ requireFree(file, to);+ file.profiles[to] = structuredClone(roles);+ });+ }++ remove(name: string): Promise<void> {+ return this.mutate((file) => {+ requireExisting(file, name);+ if (file.active === name) throw new ProfileError("active_profile");+ delete file.profiles[name];+ });+ }++ /** Saves the routing in effect now; `orchestrator` comes from the running assistant. */+ saveCurrent(name: string, orchestrator?: RoleRoute): Promise<void> {+ return this.mutate((file) => {+ requireFree(file, name);+ const roles: ProfileRoles = {};+ const modelProfiles = readObject(this.subagentsPath, "settings_invalid").model_profiles;+ for (const [agent, raw] of Object.entries(isRecord(modelProfiles) ? modelProfiles : {})) {+ const route = isRecord(raw) ? normalizeRoute(raw) : undefined;+ if (route && ROLE_NAME.test(agent)) roles[agent] = route;+ }+ const models = readObject(this.modelsPath, "settings_invalid");+ for (const role of REVIEW_ROLES) {+ const route = normalizeRoute(models[role]);+ if (route) roles[role] = route;+ }+ if (orchestrator) roles[ORCHESTRATOR] = orchestrator;+ file.profiles[name] = cleanRoles(roles);+ });+ }++ /**+ * Applies a profile the way the engine does: the active marker, then+ * models.json, then subagents.json `model_profiles` (omitted agents cleared),+ * then the main assistant's defaults in settings.json. Agent files are never+ * rewritten. Any failure restores all four files. Returns the main assistant+ * route when the profile sets its model.+ */+ apply(name: string): Promise<RoleRoute | undefined> {+ return this.enqueue(async () => {+ const file = this.read();+ const roles = requireExisting(file, name);+ const paths = [this.storePath, this.modelsPath, this.subagentsPath, this.settingsPath];+ const before = paths.map(readText);+ try {+ writeFileAtomic(this.storePath, serializeProfilesFile({ ...file, active: name }));+ writeFileAtomic(this.modelsPath, jsonText(roles));+ this.writeAgentRoutes(roles);+ const orchestrator = roles[ORCHESTRATOR];+ if (!orchestrator?.model) return undefined;+ await this.writeOrchestrator(orchestrator);+ return { ...orchestrator };+ } catch (error) {+ paths.forEach((path, i) => {+ const text = before[i];+ if (text === undefined) rmSync(path, { force: true });+ else writeFileAtomic(path, text);+ });+ throw error;+ }+ });+ }++ /** True when the other setup has at least one profile to bring over. */+ importable(): boolean {+ if (this.options.importPath === this.storePath) return false;+ const source = this.readSource();+ return source !== undefined && Object.keys(source.profiles).length > 0;+ }++ /**+ * Copies the other setup's profiles into the assistant's store. Names that are+ * taken get `-imported`, `-imported-2`, …; identical copies are skipped, and+ * the other setup's active marker is not copied.+ */+ import(providers: AuthProvider[] = []): Promise<ImportResult> {+ return this.enqueue(() => {+ const source = this.importable() ? this.readSource() : undefined;+ if (!source) throw new ProfileError("nothing_to_import");+ const file = this.read();+ const imported: ImportResult["imported"] = [];+ const used = new Set<string>();+ for (const [name, roles] of Object.entries(source.profiles)) {+ const target = importName(file, name, roles);+ if (!target) continue;+ file.profiles[target] = roles;+ imported.push({ from: name, to: target });+ for (const route of Object.values(roles)) {+ const provider = route.model ? splitModel(route.model)?.provider : undefined;+ if (provider) used.add(provider);+ }+ }+ if (imported.length > 0) writeFileAtomic(this.storePath, serializeProfilesFile(file));+ const missingProviders = [...used]+ .filter((id) => !providers.some((p) => p.id === id && p.configured))+ .map((id) => providers.find((p) => p.id === id)?.name ?? id)+ .sort();+ return { imported, missingProviders };+ });+ }++ private writeAgentRoutes(roles: ProfileRoles): void {+ const config = readObject(this.subagentsPath, "settings_invalid");+ const modelProfiles: Record<string, Record<string, string>> = {};+ for (const [agent, route] of Object.entries(roles)) {+ if (agent === ORCHESTRATOR || REVIEW_ROLES.includes(agent)) continue;+ const entry: Record<string, string> = {};+ if (route.model) entry.model = route.model;+ if (route.thinking) entry.effort = route.thinking;+ if (Object.keys(entry).length > 0) modelProfiles[agent] = entry;+ }+ const next = { ...config };+ if (Object.keys(modelProfiles).length > 0) next.model_profiles = modelProfiles;+ else delete next.model_profiles;+ writeFileAtomic(this.subagentsPath, jsonText(next));+ }++ private writeOrchestrator(route: RoleRoute): Promise<void> {+ const target = route.model ? splitModel(route.model) : undefined;+ if (!target) throw new ProfileError("settings_invalid");+ return withFileLock(this.settingsPath, () => {+ const settings = readObject(this.settingsPath, "settings_invalid");+ const next: Record<string, unknown> = {+ ...settings,+ defaultProvider: target.provider,+ defaultModel: target.modelId,+ };+ if (route.thinking) next.defaultThinkingLevel = route.thinking;+ else delete next.defaultThinkingLevel;+ writeFileAtomic(this.settingsPath, jsonText(next));+ });+ }++ private read(): ProfilesFile {+ const text = readText(this.storePath);+ if (text === undefined) return { profiles: {} };+ const file = parseProfilesFile(text);+ if (!file) throw new ProfileError("store_invalid");+ return file;+ }++ private readSource(): ProfilesFile | undefined {+ const text = readText(this.options.importPath);+ return text === undefined ? undefined : parseProfilesFile(text);+ }++ private mutate(change: (file: ProfilesFile) => void): Promise<void> {+ return this.enqueue(() => {+ const file = this.read();+ change(file);+ writeFileAtomic(this.storePath, serializeProfilesFile(file));+ });+ }++ private enqueue<T>(task: () => T | Promise<T>): Promise<T> {+ const run = this.queue.then(task, task);+ this.queue = run.catch(() => {});+ return run;+ }+}++function requireName(name: string): void {+ if (!isValidProfileName(name)) throw new ProfileError("invalid_name");+}++function requireExisting(file: ProfilesFile, name: string): ProfileRoles {+ requireName(name);+ const roles = Object.hasOwn(file.profiles, name) ? file.profiles[name] : undefined;+ if (!roles) throw new ProfileError("missing_profile");+ return roles;+}++function requireFree(file: ProfilesFile, name: string): void {+ requireName(name);+ if (Object.hasOwn(file.profiles, name)) throw new ProfileError("duplicate_name");+}++function cleanRoles(roles: ProfileRoles): ProfileRoles {+ return parseProfileRoles(roles) ?? {};+}++/** The free name for an imported profile, or undefined when an identical copy is already saved. */+function importName(file: ProfilesFile, name: string, roles: ProfileRoles): string | undefined {+ const same = (other: string) => JSON.stringify(file.profiles[other]) === JSON.stringify(roles);+ for (let n = 0; ; n++) {+ const suffix = n === 0 ? "" : n === 1 ? "-imported" : `-imported-${n}`;+ const candidate = `${name.slice(0, 64 - suffix.length)}${suffix}`;+ if (!Object.hasOwn(file.profiles, candidate)) return candidate;+ if (same(candidate)) return undefined;+ }+}++const ROLE_LABELS: Record<string, string> = {+ [ORCHESTRATOR]: "Main assistant",+ "gentle-ai-explore": "Researcher",+ "gentle-ai-worker": "Builder",+ "gentle-ai-verify": "Checker",+ "review-refuter": "Reviewer: challenger",+ "review-validator": "Reviewer: validator",+ "jd-judge-a": "Second opinion A",+ "jd-judge-b": "Second opinion B",+ "jd-fix-agent": "Second opinion fixer",+};++/** A plain-language, white-labeled name for a role id. */+export function roleLabel(id: string): string {+ const known = ROLE_LABELS[id];+ if (known) return known;+ const review = /^review-(.+)$/.exec(id);+ if (review?.[1]) return `Reviewer: ${review[1].replace(/[-_]+/g, " ")}`;+ const words = id+ .replace(/^gentle[-_]?(?:ai|pi|shell)?[-_]/i, "")+ .replace(/[-_.]+/g, " ")+ .trim();+ const label = presentText(words.charAt(0).toUpperCase() + words.slice(1));+ return label || "Helper";+}++/** Agent names the engine discovers in `<home>/agents` and `<home>/subagents` (top-level `.md`, frontmatter `name:`). */+function agentNames(agentHome: string): string[] {+ const names: string[] = [];+ for (const dir of [join(agentHome, "agents"), join(agentHome, "subagents")]) {+ if (!existsSync(dir)) continue;+ for (const entry of readdirSync(dir).sort()) {+ if (!entry.toLowerCase().endsWith(".md") || entry.toLowerCase().endsWith(".chain.md")) continue;+ const text = readText(join(dir, entry)) ?? "";+ const name =+ /^name:\s*["']?([^"'\n]+)["']?\s*$/m.exec(text)?.[1]?.trim() || entry.replace(/\.md$/i, "");+ if (ROLE_NAME.test(name)) names.push(name);+ }+ }+ return names;+}++/** The roles a profile can route: the main assistant first, then agents and review roles by label. */+export function discoverRoles(agentHome: string, extra: string[] = []): ProfileRole[] {+ const ids = new Set([...agentNames(agentHome), ...REVIEW_ROLES, ...extra]);+ ids.delete(ORCHESTRATOR);+ const roles = [...ids]+ .map((id) => ({ id, label: roleLabel(id) }))+ .sort((a, b) => a.label.localeCompare(b.label));+ return [{ id: ORCHESTRATOR, label: roleLabel(ORCHESTRATOR) }, ...roles];+}++/** Models from `get_available_models`, reduced to what the UI needs: never endpoints, headers, or costs. */+export function toModelOptions(data: unknown): ModelOption[] {+ const models = isRecord(data) && Array.isArray(data.models) ? data.models : [];+ return models.flatMap((raw): ModelOption[] => {+ if (!isRecord(raw) || typeof raw.provider !== "string" || typeof raw.id !== "string") return [];+ const name = typeof raw.name === "string" && raw.name ? raw.name : raw.id;+ return [+ { provider: raw.provider, id: raw.id, name: presentText(name), reasoning: raw.reasoning === true },+ ];+ });+}++/** The part of the supervisor the live switch needs. */+export interface LiveAgent {+ busy: boolean;+ state: string;+ request(command: { type: string; [key: string]: unknown }): Promise<unknown>;+}++export type SwitchOutcome = "switched" | "deferred" | "failed" | "none";++/**+ * The running conversation keeps the model it started with, so applying a+ * profile also switches it live (`set_model`, `set_thinking_level`); while the+ * assistant is busy the switch waits for `settle()`.+ */+export class LiveModelSwitch {+ private readonly agent: LiveAgent;+ private readonly log: (line: string) => void;+ private pending: RoleRoute | undefined;++ constructor(agent: LiveAgent, log: (line: string) => void = () => {}) {+ this.agent = agent;+ this.log = log;+ }++ switchTo(route: RoleRoute): Promise<SwitchOutcome> {+ this.pending = route;+ return this.settle("deferred");+ }++ /** Runs a waiting switch once the assistant is ready and idle. */+ async settle(waiting: SwitchOutcome = "none"): Promise<SwitchOutcome> {+ const route = this.pending;+ if (!route) return "none";+ if (this.agent.busy || this.agent.state !== "ready") return waiting;+ this.pending = undefined;+ const target = route.model ? splitModel(route.model) : undefined;+ if (!target) return "none";+ try {+ await this.agent.request({ type: "set_model", ...target });+ if (route.thinking) await this.agent.request({ type: "set_thinking_level", level: route.thinking });+ return "switched";+ } catch (error) {+ this.log(`could not switch the running model: ${(error as Error).message}`);+ return "failed";+ }+ }+}diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex a1f1321..8d1a8ed 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -12,6 +12,9 @@// FAKE_AGENT_ARGS_FILE write argv as JSON to this file// FAKE_AGENT_BRANDING emit branded startup UI records// FAKE_AGENT_ENV_FILE write selected environment variables as JSON to this file+// FAKE_AGENT_COMMANDS_FILE append every model command (set_model, set_thinking_level) as JSONL+// get_available_models lists MODELS; set_model and set_thinking_level change what+// get_state reports, so tests can read the last values back.import { randomUUID } from "node:crypto";import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";@@ -19,6 +22,23 @@ import { join } from "node:path";type Rec = Record<string, unknown>;type Message = { role: "user" | "assistant"; content: string };+const MODELS: Rec[] = [+ {+ id: "fake-model",+ name: "Fake Model",+ provider: "fake",+ reasoning: true,+ // Real models may carry credentials in headers; they must never reach a client.+ headers: { Authorization: "Bearer fake-secret-header" },+ baseUrl: "https://internal.fake.example",+ cost: { input: 1, output: 2 },+ },+ { id: "fake-fast", name: "Fake Fast", provider: "fake", reasoning: false },+ { id: "big", name: "Other Big", provider: "other", reasoning: true },+];+let model = MODELS[0] as Rec;+let thinkingLevel = "medium";+const argv = process.argv.slice(2);if (process.env.FAKE_AGENT_ARGS_FILE) writeFileSync(process.env.FAKE_AGENT_ARGS_FILE, JSON.stringify(argv));if (process.env.FAKE_AGENT_ENV_FILE) {@@ -43,6 +63,13 @@ function argValue(name: string): string | undefined {return i >= 0 ? argv[i + 1] : undefined;}+function recordCommand(rec: Rec): void {+ const file = process.env.FAKE_AGENT_COMMANDS_FILE;+ if (!file) return;+ const { id: _id, ...command } = rec;+ appendFileSync(file, `${JSON.stringify({ ...command, busy })}\n`);+}+function out(rec: Rec): void {process.stdout.write(`${JSON.stringify(rec)}\n`);}@@ -152,8 +179,8 @@ function handle(rec: Rec) {switch (type) {case "get_state":return respond(id, "get_state", {- model: { id: "fake-model", name: "Fake Model", provider: "fake" },- thinkingLevel: "medium",+ model: { id: model.id, name: model.name, provider: model.provider },+ thinkingLevel,isStreaming: busy,sessionFile,sessionId,@@ -191,6 +218,25 @@ function handle(rec: Rec) {return respond(id, "switch_session", undefined, "Session not found");}return respond(id, "switch_session", { cancelled: false });+ case "get_available_models":+ return respond(id, type, { models: MODELS });+ case "set_model": {+ recordCommand(rec);+ const found = MODELS.find((m) => m.provider === rec.provider && m.id === rec.modelId);+ if (!found)+ return respond(+ id,+ type,+ undefined,+ `Model not found: ${String(rec.provider)}/${String(rec.modelId)}`,+ );+ model = found;+ return respond(id, type, found);+ }+ case "set_thinking_level":+ recordCommand(rec);+ thinkingLevel = String(rec.level);+ return respond(id, type);case "noreply":return;case "extension_ui_response": {diff --git a/packages/daemon/test/profiles-gateway.test.ts b/packages/daemon/test/profiles-gateway.test.tsnew file mode 100644index 0000000..888762c--- /dev/null+++ b/packages/daemon/test/profiles-gateway.test.ts@@ -0,0 +1,296 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import type { ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { HIDDEN_NAMES } from "../src/white-label.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++async function setup() {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const shellHome = join(tempDir(), "shell-gentle-ai");+ const commandsFile = join(dataDir, "commands.jsonl");+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ writeFileSync(+ join(agentHome, "agents", "gentle-ai-worker.md"),+ "---\nname: gentle-ai-worker\n---\nWorker\n",+ );+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: dataDir,+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentEnv: { ...process.env, FAKE_AGENT_COMMANDS_FILE: commandsFile },+ agentHome,+ profilesImportPath: join(shellHome, "profiles.json"),+ backoffMs: [50],+ authRuntime: async () => fakeAuthRuntime().runtime,+ });+ daemons.push(d);+ const json = (path: string) => JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+ const commands = () =>+ existsSync(commandsFile)+ ? readFileSync(commandsFile, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as Record<string, unknown>)+ : [];+ return {+ d,+ json,+ commands,+ shellHome,+ profilesPath: join(dataDir, "gentle-ai", "profiles.json"),+ modelsPath: join(dataDir, "gentle-ai", "models.json"),+ subagentsPath: join(agentHome, "subagents.json"),+ settingsPath: join(agentHome, "settings.json"),+ agentFile: join(agentHome, "agents", "gentle-ai-worker.md"),+ };+}++async function connect(d: DotDaemon) {+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ /** Waits for a matching message; `after` skips messages received before that index. */+ function find<T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ after = 0,+ ) {+ return waitFor(() =>+ messages+ .slice(after)+ .find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+ }+ return { ws, messages, send, find };+}++describe("profiles over the gateway", () => {+ it("lists profiles with plain role names and models stripped of endpoints and headers", async () => {+ const { d } = await setup();+ const client = await connect(d);+ client.send({ type: "profiles_list" });+ const list = await client.find("profiles");+ expect(list).toMatchObject({ profiles: [], importable: false });+ expect(list.active).toBeUndefined();+ expect(list.open).toBeUndefined();+ expect(list.roles).toEqual([+ { id: "orchestrator", label: "Main assistant" },+ { id: "gentle-ai-worker", label: "Builder" },+ { id: "review-refuter", label: "Reviewer: challenger" },+ { id: "review-validator", label: "Reviewer: validator" },+ ]);+ expect(list.models).toEqual([+ { provider: "fake", id: "fake-model", name: "Fake Model", reasoning: true },+ { provider: "fake", id: "fake-fast", name: "Fake Fast", reasoning: false },+ { provider: "other", id: "big", name: "Other Big", reasoning: true },+ ]);+ const raw = JSON.stringify(client.messages);+ expect(raw).not.toContain("fake-secret-header");+ expect(raw).not.toContain("internal.fake.example");+ expect(raw).not.toContain("cost");+ for (const role of list.roles) for (const name of HIDDEN_NAMES) expect(role.label).not.toMatch(name);+ });++ it("opens the profiles screen when the user types /profiles", async () => {+ const { d } = await setup();+ const client = await connect(d);+ client.send({ type: "send", text: " /profiles " });+ const list = await client.find("profiles");+ expect(list.open).toBe(true);+ expect(client.messages.some((m) => m.type === "user_message")).toBe(false);+ });++ it("creates and applies a profile: files written, every window refreshed, and the running model switched", async () => {+ const { d, json, commands, profilesPath, modelsPath, subagentsPath, settingsPath, agentFile } =+ await setup();+ const a = await connect(d);+ const b = await connect(d);+ const roles = {+ orchestrator: { model: "fake/fake-fast", thinking: "low" },+ "gentle-ai-worker": { model: "other/big", thinking: "high" },+ };+ a.send({ type: "profile_save", name: "quick", roles });+ const saved = await b.find("profiles", (m) => m.profiles.length === 1);+ expect(saved.profiles).toEqual([{ name: "quick", roles }]);+ expect(saved.active).toBeUndefined();+ expect(commands()).toEqual([]);++ a.send({ type: "profile_apply", name: "quick" });+ const applied = await b.find("profiles", (m) => m.active === "quick");+ expect(applied.profiles).toEqual([{ name: "quick", roles }]);+ expect(json(profilesPath).active).toBe("quick");+ expect(json(modelsPath)).toEqual(roles);+ expect(json(subagentsPath)).toEqual({+ model_profiles: { "gentle-ai-worker": { model: "other/big", effort: "high" } },+ });+ expect(json(settingsPath)).toEqual({+ defaultProvider: "fake",+ defaultModel: "fake-fast",+ defaultThinkingLevel: "low",+ });+ expect(readFileSync(agentFile, "utf8")).toBe("---\nname: gentle-ai-worker\n---\nWorker\n");+ expect(commands()).toEqual([+ { type: "set_model", provider: "fake", modelId: "fake-fast", busy: false },+ { type: "set_thinking_level", level: "low", busy: false },+ ]);+ expect(a.messages.some((m) => m.type === "error")).toBe(false);+ });++ it("waits for the running answer to finish before switching the model", async () => {+ const { d, json, commands, settingsPath } = await setup();+ const client = await connect(d);+ client.send({ type: "profile_save", name: "main", roles: { orchestrator: { model: "other/big" } } });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "send", text: "hang" });+ await client.find("agent_state", (m) => m.state === "thinking");+ client.send({ type: "profile_apply", name: "main" });+ await client.find("profiles", (m) => m.active === "main");+ expect(json(settingsPath)).toEqual({ defaultProvider: "other", defaultModel: "big" });+ expect(commands()).toEqual([]);+ client.send({ type: "abort" });+ await waitFor(() => commands().length === 1);+ expect(commands()).toEqual([{ type: "set_model", provider: "other", modelId: "big", busy: false }]);+ });++ it("re-applies the profile in use when it is edited", async () => {+ const { d, json, commands, settingsPath } = await setup();+ const client = await connect(d);+ client.send({ type: "profile_save", name: "main", roles: { orchestrator: { model: "fake/fake-fast" } } });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "profile_apply", name: "main" });+ await client.find("profiles", (m) => m.active === "main");+ client.send({+ type: "profile_save",+ name: "main",+ roles: { orchestrator: { model: "other/big", thinking: "xhigh" } },+ });+ await client.find("profiles", (m) => m.profiles[0]?.roles.orchestrator?.model === "other/big");+ expect(json(settingsPath)).toMatchObject({ defaultModel: "big", defaultThinkingLevel: "xhigh" });+ expect(commands().map((c) => [c.type, c.modelId ?? c.level])).toEqual([+ ["set_model", "fake-fast"],+ ["set_model", "big"],+ ["set_thinking_level", "xhigh"],+ ]);+ });++ it("warns when the running conversation cannot use the profile's model", async () => {+ const { d, json, settingsPath } = await setup();+ const client = await connect(d);+ client.send({ type: "profile_save", name: "ghost", roles: { orchestrator: { model: "ghost/none" } } });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "profile_apply", name: "ghost" });+ const toast = await client.find("toast");+ expect(toast).toMatchObject({+ level: "warning",+ message:+ "Profile applied. The main assistant keeps its current model until that model's account is connected.",+ });+ expect(json(settingsPath)).toEqual({ defaultProvider: "ghost", defaultModel: "none" });+ });++ it("renames, duplicates, and deletes, with plain-language errors", async () => {+ const { d, json, profilesPath } = await setup();+ const client = await connect(d);+ client.send({ type: "profile_save", name: "a", roles: {} });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "profile_duplicate", from: "a", to: "b" });+ await client.find("profiles", (m) => m.profiles.length === 2);+ client.send({ type: "profile_rename", from: "b", to: "c" });+ await client.find("profiles", (m) => m.profiles.map((p) => p.name).join() === "a,c");+ client.send({ type: "profile_apply", name: "a" });+ await client.find("profiles", (m) => m.active === "a");+ client.send({ type: "profile_delete", name: "a" });+ const error = await client.find("error");+ expect(error).toEqual({+ type: "error",+ code: "active_profile",+ message: "That profile is in use. Switch to another one before deleting it.",+ seq: error.seq,+ });+ const before = client.messages.length;+ client.send({ type: "profile_delete", name: "c" });+ await client.find("profiles", (m) => m.profiles.length === 1, before);+ expect(Object.keys(json(profilesPath).profiles as object)).toEqual(["a"]);+ client.send({ type: "profile_rename", from: "missing", to: "x" });+ expect((await client.find("error", (m) => m.code !== "active_profile")).code).toBe("missing_profile");+ });++ it("saves the current setup with the running model and thinking level", async () => {+ const { d, json, profilesPath, subagentsPath } = await setup();+ writeFileSync(+ subagentsPath,+ JSON.stringify({ model_profiles: { "gentle-ai-worker": { model: "other/big" } } }),+ );+ const client = await connect(d);+ client.send({ type: "profile_save_current", name: "now" });+ const list = await client.find("profiles", (m) => m.profiles.length === 1);+ const roles = {+ orchestrator: { model: "fake/fake-model", thinking: "medium" },+ "gentle-ai-worker": { model: "other/big" },+ };+ expect(list.profiles).toEqual([{ name: "now", roles }]);+ expect((json(profilesPath).profiles as Record<string, unknown>).now).toEqual(roles);+ });++ it("imports another setup's profiles once, reporting renames and accounts to connect", async () => {+ const { d, json, shellHome, profilesPath } = await setup();+ mkdirSync(shellHome, { recursive: true });+ const source = `${JSON.stringify(+ {+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: {+ quick: { orchestrator: { model: "anthropic/claude-sonnet-4" } },+ local: { "gentle-ai-worker": { model: "fake/fake-fast" } },+ },+ active: "quick",+ },+ null,+ 2,+ )}\n`;+ writeFileSync(join(shellHome, "profiles.json"), source);+ const client = await connect(d);+ client.send({ type: "profile_save", name: "quick", roles: {} });+ const listed = await client.find("profiles", (m) => m.profiles.length === 1);+ expect(listed.importable).toBe(true);++ client.send({ type: "profile_import" });+ const result = await client.find("profiles_imported");+ expect(result).toMatchObject({+ imported: [+ { from: "quick", to: "quick-imported" },+ { from: "local", to: "local" },+ ],+ missingProviders: ["Anthropic", "fake"],+ });+ const list = await client.find("profiles", (m) => m.profiles.length === 3);+ expect(list.active).toBeUndefined();+ expect(Object.keys(json(profilesPath).profiles as object).sort()).toEqual([+ "local",+ "quick",+ "quick-imported",+ ]);+ expect(readFileSync(join(shellHome, "profiles.json"), "utf8")).toBe(source);+ });+});diff --git a/packages/daemon/test/profiles.test.ts b/packages/daemon/test/profiles.test.tsnew file mode 100644index 0000000..c03f8e0--- /dev/null+++ b/packages/daemon/test/profiles.test.ts@@ -0,0 +1,482 @@+import {+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ rmdirSync,+ statSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";+import type { AuthProvider } from "@gentle-dot/protocol";+import { describe, expect, it } from "vitest";+import {+ discoverRoles,+ LiveModelSwitch,+ ProfileError,+ ProfileStore,+ parseProfilesFile,+ serializeProfilesFile,+ toModelOptions,+} from "../src/profiles.ts";+import { HIDDEN_NAMES } from "../src/white-label.ts";+import { tempDir } from "./helpers.ts";++function setup() {+ const root = tempDir();+ const configHome = join(root, "gentle-ai");+ const agentHome = join(root, "agent");+ const shellHome = join(root, "shell");+ const store = new ProfileStore({ configHome, agentHome, importPath: join(shellHome, "profiles.json") });+ const json = (path: string) => JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;+ const write = (path: string, value: unknown) => {+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+ };+ return {+ store,+ configHome,+ agentHome,+ shellHome,+ json,+ write,+ profilesPath: join(configHome, "profiles.json"),+ modelsPath: join(configHome, "models.json"),+ subagentsPath: join(agentHome, "subagents.json"),+ settingsPath: join(agentHome, "settings.json"),+ };+}++// Bytes as the engine's serializeProfilesFile writes them (lib/agent-profiles.ts).+const ENGINE_FILE = `${JSON.stringify(+ {+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: {+ "deep-work": {+ orchestrator: { model: "anthropic/claude-opus-4", thinking: "high" },+ "gentle-ai-worker": { model: "openai/gpt-5", thinking: "medium" },+ "review-refuter": { thinking: "low" },+ },+ fast: { "gentle-ai-explore": { model: "openai/gpt-5-mini" } },+ },+ active: "deep-work",+ },+ null,+ 2,+)}\n`;++describe("profile file format", () => {+ it("round-trips a store written by the engine byte for byte", () => {+ const file = parseProfilesFile(ENGINE_FILE);+ expect(file?.active).toBe("deep-work");+ expect(file?.profiles.fast).toEqual({ "gentle-ai-explore": { model: "openai/gpt-5-mini" } });+ expect(serializeProfilesFile(file ?? { profiles: {} })).toBe(ENGINE_FILE);+ });++ it("normalizes like the engine: string routes, effort alias, invalid names and stale active dropped", () => {+ const file = parseProfilesFile(+ JSON.stringify({+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: {+ legacy: { worker: "openai/gpt-5", checker: { effort: "low" }, broken: { model: "bad model" } },+ "bad name": { worker: { thinking: "low" } },+ constructor: {},+ },+ active: "gone",+ }),+ );+ expect(file).toEqual({+ profiles: { legacy: { worker: { model: "openai/gpt-5" }, checker: { thinking: "low" } } },+ });+ expect(parseProfilesFile('{"kind":"other","version":1,"profiles":{}}')).toBeUndefined();+ expect(parseProfilesFile("{nope")).toBeUndefined();+ });+});++describe("profile store", () => {+ it("creates, updates, duplicates, renames, and deletes profiles", async () => {+ const { store, json, profilesPath } = setup();+ expect(store.list()).toEqual({ profiles: [] });+ await store.save("fast", { orchestrator: { model: "fake/fake-fast" } });+ await store.save("fast", { orchestrator: { model: "fake/fake-model", thinking: "low" } });+ await store.duplicate("fast", "copy");+ await store.rename("copy", "deep");+ expect(store.list().profiles.map((p) => p.name)).toEqual(["deep", "fast"]);+ expect(json(profilesPath)).toEqual({+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: {+ fast: { orchestrator: { model: "fake/fake-model", thinking: "low" } },+ deep: { orchestrator: { model: "fake/fake-model", thinking: "low" } },+ },+ });+ await store.remove("deep");+ expect(Object.keys(json(profilesPath).profiles as object)).toEqual(["fast"]);+ });++ it("refuses invalid names, duplicates, missing profiles, and deleting the profile in use", async () => {+ const { store } = setup();+ await store.save("a", {});+ await store.save("b", {});+ await store.apply("a");+ const code = (promise: Promise<unknown>) =>+ promise.then(+ () => "resolved",+ (error: ProfileError) => error.code,+ );+ expect(await code(store.save("bad name", {}))).toBe("invalid_name");+ expect(await code(store.save("constructor", {}))).toBe("invalid_name");+ expect(await code(store.rename("a", "b"))).toBe("duplicate_name");+ expect(await code(store.duplicate("missing", "c"))).toBe("missing_profile");+ expect(await code(store.remove("a"))).toBe("active_profile");+ expect(await code(store.saveCurrent("b"))).toBe("duplicate_name");+ const error = await store.remove("a").catch((e: ProfileError) => e);+ expect((error as ProfileError).message).toBe(+ "That profile is in use. Switch to another one before deleting it.",+ );+ });++ it("moves the in-use marker when the active profile is renamed", async () => {+ const { store } = setup();+ await store.save("a", {});+ await store.apply("a");+ await store.rename("a", "renamed");+ expect(store.list().active).toBe("renamed");+ });++ it("writes the store atomically with mode 0600 and leaves no temp files", async () => {+ const { store, configHome, profilesPath } = setup();+ await store.save("a", { orchestrator: { model: "fake/fake-model" } });+ expect(statSync(profilesPath).mode & 0o777).toBe(0o600);+ expect(readdirSync(configHome)).toEqual(["profiles.json"]);+ });++ it("serializes concurrent writes so none is lost", async () => {+ const { store } = setup();+ await Promise.all(["a", "b", "c", "d", "e"].map((name) => store.save(name, {})));+ expect(store.list().profiles.map((p) => p.name)).toEqual(["a", "b", "c", "d", "e"]);+ });++ it("reports an unreadable store instead of replacing it", async () => {+ const { store, configHome, profilesPath } = setup();+ mkdirSync(configHome, { recursive: true });+ writeFileSync(profilesPath, "{broken");+ expect(() => store.list()).toThrow(ProfileError);+ await expect(store.save("a", {})).rejects.toMatchObject({ code: "store_invalid" });+ expect(readFileSync(profilesPath, "utf8")).toBe("{broken");+ });+});++describe("applying a profile", () => {+ it("writes the active marker, models.json, subagents.json, and settings.json, keeping other keys", async () => {+ const { store, json, write, agentHome, profilesPath, modelsPath, subagentsPath, settingsPath } = setup();+ const agentFile = join(agentHome, "agents", "gentle-ai-worker.md");+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ writeFileSync(agentFile, "---\nname: gentle-ai-worker\nmodel: old/model\n---\nBody\n");+ write(subagentsPath, {+ parallel: 3,+ model_profiles: {+ "gentle-ai-explore": { model: "old/explore" },+ "gentle-ai-worker": { effort: "low" },+ },+ });+ write(settingsPath, {+ theme: "dark",+ defaultProvider: "old",+ defaultModel: "m",+ defaultThinkingLevel: "low",+ });+ await store.save("deep", {+ orchestrator: { model: "anthropic/claude-opus-4" },+ "gentle-ai-worker": { model: "openai/gpt-5", thinking: "high" },+ "review-refuter": { model: "openai/gpt-5-mini" },+ });++ const orchestrator = await store.apply("deep");++ expect(orchestrator).toEqual({ model: "anthropic/claude-opus-4" });+ expect(json(profilesPath).active).toBe("deep");+ expect(json(modelsPath)).toEqual({+ orchestrator: { model: "anthropic/claude-opus-4" },+ "gentle-ai-worker": { model: "openai/gpt-5", thinking: "high" },+ "review-refuter": { model: "openai/gpt-5-mini" },+ });+ // Omitted roles are cleared; review roles and the orchestrator never land here.+ expect(json(subagentsPath)).toEqual({+ parallel: 3,+ model_profiles: { "gentle-ai-worker": { model: "openai/gpt-5", effort: "high" } },+ });+ // No thinking level in the profile: the key goes away.+ expect(json(settingsPath)).toEqual({+ theme: "dark",+ defaultProvider: "anthropic",+ defaultModel: "claude-opus-4",+ });+ expect(statSync(modelsPath).mode & 0o777).toBe(0o600);+ expect(readFileSync(agentFile, "utf8")).toBe(+ "---\nname: gentle-ai-worker\nmodel: old/model\n---\nBody\n",+ );+ });++ it("sets the thinking level and drops model_profiles when the profile routes no agent", async () => {+ const { store, json, write, subagentsPath, settingsPath } = setup();+ write(subagentsPath, { model_profiles: { "gentle-ai-explore": { model: "old/explore" } } });+ await store.save("main", { orchestrator: { model: "fake/fake-model", thinking: "max" } });+ expect(await store.apply("main")).toEqual({ model: "fake/fake-model", thinking: "max" });+ expect(json(subagentsPath)).toEqual({});+ expect(json(settingsPath)).toEqual({+ defaultProvider: "fake",+ defaultModel: "fake-model",+ defaultThinkingLevel: "max",+ });+ });++ it("leaves settings.json alone when the profile has no main assistant model", async () => {+ const { store, write, settingsPath } = setup();+ write(settingsPath, { defaultProvider: "keep", defaultModel: "me" });+ const before = readFileSync(settingsPath, "utf8");+ await store.save("agents-only", { "gentle-ai-worker": { thinking: "low" } });+ expect(await store.apply("agents-only")).toBeUndefined();+ expect(readFileSync(settingsPath, "utf8")).toBe(before);+ });++ it("restores every file when a step fails", async () => {+ const { store, profilesPath, modelsPath, subagentsPath, settingsPath } = setup();+ await store.save("a", { "gentle-ai-worker": { model: "x/a" } });+ await store.save("b", { orchestrator: { model: "x/b" }, "gentle-ai-worker": { model: "x/b" } });+ await store.apply("a");+ writeFileSync(settingsPath, "{not json");+ const before = [profilesPath, modelsPath, subagentsPath, settingsPath].map((p) =>+ readFileSync(p, "utf8"),+ );+ await expect(store.apply("b")).rejects.toMatchObject({ code: "settings_invalid" });+ expect(+ [profilesPath, modelsPath, subagentsPath, settingsPath].map((p) => readFileSync(p, "utf8")),+ ).toEqual(before);+ });++ it("waits for the engine's settings lock and takes over a stale one", async () => {+ const { store, write, json, settingsPath } = setup();+ write(settingsPath, { theme: "dark" });+ await store.save("main", { orchestrator: { model: "fake/fake-model" } });+ const lock = `${settingsPath}.lock`;+ mkdirSync(lock);+ let done = false;+ const applying = store.apply("main").then(() => {+ done = true;+ });+ await new Promise((resolve) => setTimeout(resolve, 60));+ expect(done).toBe(false);+ // Released the way the engine's lock library does it: by removing the directory.+ rmdirSync(lock);+ await applying;+ expect(json(settingsPath).defaultModel).toBe("fake-model");+ expect(existsSync(lock)).toBe(false);++ mkdirSync(lock);+ const old = new Date(Date.now() - 60_000);+ utimesSync(lock, old, old);+ await store.save("other", { orchestrator: { model: "fake/fake-fast" } });+ await store.apply("other");+ expect(json(settingsPath).defaultModel).toBe("fake-fast");+ expect(existsSync(lock)).toBe(false);+ });+});++describe("saving the current setup", () => {+ it("captures agent routes, review roles, and the main assistant", async () => {+ const { store, write, json, profilesPath, subagentsPath, modelsPath } = setup();+ write(subagentsPath, {+ parallel: 2,+ model_profiles: { "gentle-ai-worker": { model: "openai/gpt-5", effort: "high" }, odd: "skip" },+ });+ write(modelsPath, {+ "review-validator": { model: "openai/gpt-5-mini", thinking: "low" },+ "gentle-ai-worker": { model: "ignored/here" },+ });+ await store.saveCurrent("mine", { model: "fake/fake-model", thinking: "medium" });+ expect((json(profilesPath).profiles as Record<string, unknown>).mine).toEqual({+ orchestrator: { model: "fake/fake-model", thinking: "medium" },+ "gentle-ai-worker": { model: "openai/gpt-5", thinking: "high" },+ "review-validator": { model: "openai/gpt-5-mini", thinking: "low" },+ });+ });+});++describe("importing profiles", () => {+ const providers: AuthProvider[] = [+ { id: "anthropic", name: "Anthropic", methods: ["oauth"], configured: true },+ { id: "openai", name: "OpenAI", methods: ["api_key"], configured: false },+ ];++ it("offers import only when the other store has at least one profile", () => {+ const { store, shellHome } = setup();+ expect(store.importable()).toBe(false);+ mkdirSync(shellHome, { recursive: true });+ writeFileSync(+ join(shellHome, "profiles.json"),+ '{"kind":"gentle-pi.agent_model_profiles","version":1,"profiles":{}}',+ );+ expect(store.importable()).toBe(false);+ writeFileSync(join(shellHome, "profiles.json"), ENGINE_FILE);+ expect(store.importable()).toBe(true);+ });++ it("copies profiles once, renames collisions, skips the active marker, and names missing accounts", async () => {+ const { store, shellHome, json, profilesPath } = setup();+ mkdirSync(shellHome, { recursive: true });+ const source = join(shellHome, "profiles.json");+ writeFileSync(source, ENGINE_FILE);+ const sourceStat = statSync(source);+ await store.save("fast", { orchestrator: { model: "fake/fake-model" } });+ await store.save("fast-imported", { orchestrator: { model: "fake/other" } });++ const result = await store.import(providers);++ expect(result).toEqual({+ imported: [+ { from: "deep-work", to: "deep-work" },+ { from: "fast", to: "fast-imported-2" },+ ],+ missingProviders: ["OpenAI"],+ });+ const saved = json(profilesPath);+ expect(saved.active).toBeUndefined();+ expect((saved.profiles as Record<string, unknown>)["fast-imported-2"]).toEqual({+ "gentle-ai-explore": { model: "openai/gpt-5-mini" },+ });+ expect(readFileSync(source, "utf8")).toBe(ENGINE_FILE);+ expect(statSync(source).mtimeMs).toBe(sourceStat.mtimeMs);++ // A second import finds nothing new.+ expect(await store.import(providers)).toEqual({ imported: [], missingProviders: [] });+ });++ it("reports providers it does not know by id", async () => {+ const { store, shellHome } = setup();+ mkdirSync(shellHome, { recursive: true });+ writeFileSync(+ join(shellHome, "profiles.json"),+ JSON.stringify({+ kind: "gentle-pi.agent_model_profiles",+ version: 1,+ profiles: { local: { orchestrator: { model: "ollama/llama3" } } },+ }),+ );+ expect(await store.import(providers)).toEqual({+ imported: [{ from: "local", to: "local" }],+ missingProviders: ["ollama"],+ });+ });++ it("refuses to import when there is nothing to import", async () => {+ const { store } = setup();+ await expect(store.import(providers)).rejects.toMatchObject({ code: "nothing_to_import" });+ });+});++describe("roles and models", () => {+ it("lists the main assistant, discovered agents, and review roles with plain labels", () => {+ const { agentHome } = setup();+ mkdirSync(join(agentHome, "agents"), { recursive: true });+ mkdirSync(join(agentHome, "subagents"), { recursive: true });+ writeFileSync(join(agentHome, "agents", "gentle-ai-worker.md"), "---\nname: gentle-ai-worker\n---\n");+ writeFileSync(join(agentHome, "agents", "x.md"), '---\nname: "gentle-ai-explore"\n---\n');+ writeFileSync(join(agentHome, "agents", "jd-judge-a.md"), "---\nname: jd-judge-a\n---\n");+ writeFileSync(join(agentHome, "agents", "flow.chain.md"), "---\nname: chain\n---\n");+ writeFileSync(join(agentHome, "subagents", "gentle-ai-helper.md"), "no frontmatter\n");+ writeFileSync(join(agentHome, "subagents", "review-risk.md"), "---\nname: review-risk\n---\n");+ const roles = discoverRoles(agentHome);+ expect(roles).toEqual([+ { id: "orchestrator", label: "Main assistant" },+ { id: "gentle-ai-worker", label: "Builder" },+ { id: "gentle-ai-helper", label: "Helper" },+ { id: "gentle-ai-explore", label: "Researcher" },+ { id: "review-refuter", label: "Reviewer: challenger" },+ { id: "review-risk", label: "Reviewer: risk" },+ { id: "review-validator", label: "Reviewer: validator" },+ { id: "jd-judge-a", label: "Second opinion A" },+ ]);+ for (const { label } of roles) for (const name of HIDDEN_NAMES) expect(label).not.toMatch(name);+ });++ it("keeps roles a profile routes even when no agent file defines them", () => {+ const { agentHome } = setup();+ expect(discoverRoles(agentHome, ["sdd-apply"]).map((r) => r.id)).toContain("sdd-apply");+ });++ it("forwards only provider, id, name, and reasoning", () => {+ expect(+ toModelOptions({+ models: [+ {+ provider: "fake",+ id: "fake-model",+ name: "Fake Model",+ reasoning: true,+ headers: { Authorization: "Bearer secret" },+ baseUrl: "https://internal.example",+ cost: { input: 1 },+ },+ { provider: "fake", id: "fake-fast" },+ { id: "no-provider" },+ ],+ }),+ ).toEqual([+ { provider: "fake", id: "fake-model", name: "Fake Model", reasoning: true },+ { provider: "fake", id: "fake-fast", name: "fake-fast", reasoning: false },+ ]);+ expect(toModelOptions(undefined)).toEqual([]);+ });+});++describe("live model switch", () => {+ function agent(busy = false) {+ const sent: Record<string, unknown>[] = [];+ const fake = {+ busy,+ state: "ready",+ async request(command: Record<string, unknown>) {+ sent.push(command);+ if (command.provider === "nobody") throw new Error("No API key for nobody");+ return {};+ },+ };+ return { fake, sent };+ }++ it("switches the running conversation's model and thinking level", async () => {+ const { fake, sent } = agent();+ const live = new LiveModelSwitch(fake);+ expect(await live.switchTo({ model: "anthropic/claude-opus-4", thinking: "high" })).toBe("switched");+ expect(sent).toEqual([+ { type: "set_model", provider: "anthropic", modelId: "claude-opus-4" },+ { type: "set_thinking_level", level: "high" },+ ]);+ });++ it("only sets the model when the profile has no thinking level", async () => {+ const { fake, sent } = agent();+ await new LiveModelSwitch(fake).switchTo({ model: "fake/a/b" });+ expect(sent).toEqual([{ type: "set_model", provider: "fake", modelId: "a/b" }]);+ });++ it("waits until the assistant is done before switching", async () => {+ const { fake, sent } = agent(true);+ const live = new LiveModelSwitch(fake);+ expect(await live.switchTo({ model: "fake/fake-fast", thinking: "low" })).toBe("deferred");+ expect(sent).toEqual([]);+ fake.busy = false;+ expect(await live.settle()).toBe("switched");+ expect(sent.map((c) => c.type)).toEqual(["set_model", "set_thinking_level"]);+ expect(await live.settle()).toBe("none");+ });++ it("reports a model the assistant cannot use", async () => {+ const { fake } = agent();+ expect(await new LiveModelSwitch(fake).switchTo({ model: "nobody/x" })).toBe("failed");+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 2902635..54c58b4 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -70,6 +70,75 @@ export type AuthEvent =| { kind: "device_code"; userCode: string; verificationUri: string; expiresInSeconds?: number }| { kind: "progress"; message: string };+/** Reasoning effort levels the engine accepts. */+export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;+export type ThinkingLevel = (typeof THINKING_LEVELS)[number];++/** The model and thinking level one role uses; an empty route means "Default". */+export interface RoleRoute {+ /** `provider/model-id`. */+ model?: string;+ thinking?: ThinkingLevel;+}++/** Routes keyed by role id (`orchestrator`, an agent name, or a review role). */+export type ProfileRoles = Record<string, RoleRoute>;++export interface Profile {+ name: string;+ roles: ProfileRoles;+}++/** A role the user can route, with a plain-language label. */+export interface ProfileRole {+ id: string;+ label: string;+}++/** A model the assistant can use; never carries endpoints, headers, or costs. */+export interface ModelOption {+ provider: string;+ id: string;+ name: string;+ reasoning: boolean;+}++const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;+const RESERVED_NAMES = new Set(["__proto__", "constructor", "prototype"]);+const ROLE_ID = /^[A-Za-z0-9._:@/+%-]{1,128}$/;+const MODEL_ID = /^[A-Za-z0-9._~:@/+%-]{1,256}$/;+const MAX_ROLES = 200;++/** Profile names follow the engine's rule: 1-64 letters, numbers, `.`, `_`, `-`, starting with a letter or number. */+export function isValidProfileName(value: unknown): value is string {+ return typeof value === "string" && PROFILE_NAME.test(value) && !RESERVED_NAMES.has(value);+}++export function isThinkingLevel(value: unknown): value is ThinkingLevel {+ return typeof value === "string" && (THINKING_LEVELS as readonly string[]).includes(value);+}++/** Validates a role map; empty routes are dropped. Returns undefined when anything is malformed. */+export function parseProfileRoles(value: unknown): ProfileRoles | undefined {+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;+ const entries = Object.entries(value as Record<string, unknown>);+ if (entries.length > MAX_ROLES) return undefined;+ const roles: ProfileRoles = {};+ for (const [role, raw] of entries) {+ if (!ROLE_ID.test(role) || RESERVED_NAMES.has(role)) return undefined;+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return undefined;+ const { model, thinking, ...rest } = raw as Record<string, unknown>;+ if (Object.keys(rest).length > 0) return undefined;+ if (model !== undefined && !(typeof model === "string" && MODEL_ID.test(model))) return undefined;+ if (thinking !== undefined && !isThinkingLevel(thinking)) return undefined;+ const route: RoleRoute = {};+ if (model !== undefined) route.model = model;+ if (thinking !== undefined) route.thinking = thinking;+ if (route.model !== undefined || route.thinking !== undefined) roles[role] = route;+ }+ return roles;+}+export type ClientMessage =| { type: "hello"; token: string; protocol: number }| { type: "send"; text: string; requestId?: string }@@ -83,7 +152,15 @@ export type ClientMessage =| { type: "auth_list" }| { type: "auth_login"; providerId: string; method: AuthMethod }| { type: "auth_reply"; flowId: string; value?: string; cancelled?: boolean }- | { type: "auth_logout"; providerId: string };+ | { type: "auth_logout"; providerId: string }+ | { type: "profiles_list" }+ | { type: "profile_save"; name: string; roles: ProfileRoles }+ | { type: "profile_rename"; from: string; to: string }+ | { type: "profile_duplicate"; from: string; to: string }+ | { type: "profile_delete"; name: string }+ | { type: "profile_apply"; name: string }+ | { type: "profile_import" }+ | { type: "profile_save_current"; name: string };export type ServerPayload =| { type: "ready"; agentState: AgentState; conversationId?: string; model?: string }@@ -102,7 +179,19 @@ export type ServerPayload =| { type: "auth_providers"; providers: AuthProvider[]; open?: boolean }| { type: "auth_prompt"; prompt: AuthPrompt }| { type: "auth_event"; flowId: string; event: AuthEvent }- | { type: "auth_done"; flowId: string; providerId: string; ok: boolean; message?: string };+ | { type: "auth_done"; flowId: string; providerId: string; ok: boolean; message?: string }+ | {+ type: "profiles";+ profiles: Profile[];+ active?: string;+ roles: ProfileRole[];+ models: ModelOption[];+ /** True when an existing setup with profiles can be imported. */+ importable: boolean;+ /** Set when the user typed `/profiles`. */+ open?: boolean;+ }+ | { type: "profiles_imported"; imported: { from: string; to: string }[]; missingProviders: string[] };/** Every daemon message carries a per-connection, monotonic `seq`. */export type ServerMessage = ServerPayload & { seq: number };@@ -165,6 +254,21 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {return isString(m.conversationId)? { type: "open_conversation", conversationId: m.conversationId }: undefined;+ case "profile_save": {+ const roles = parseProfileRoles(m.roles);+ return isValidProfileName(m.name) && roles ? { type: "profile_save", name: m.name, roles } : undefined;+ }+ case "profile_rename":+ case "profile_duplicate":+ return isValidProfileName(m.from) && isValidProfileName(m.to)+ ? { type: m.type, from: m.from, to: m.to }+ : undefined;+ case "profile_delete":+ case "profile_apply":+ case "profile_save_current":+ return isValidProfileName(m.name) ? { type: m.type, name: m.name } : undefined;+ case "profiles_list":+ case "profile_import":case "abort":case "new_conversation":case "list_conversations":diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.tsindex c83bcd9..5be0cf2 100644--- a/packages/protocol/test/protocol.test.ts+++ b/packages/protocol/test/protocol.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { PROTOCOL_VERSION, parseClientMessage } from "../src/index.ts";+import { isValidProfileName, PROTOCOL_VERSION, parseClientMessage, THINKING_LEVELS } from "../src/index.ts";describe("protocol", () => {it("exposes version 1", () => {@@ -56,3 +56,92 @@ describe("protocol", () => {}});});++describe("profile messages", () => {+ const parse = (value: object) => parseClientMessage(JSON.stringify(value));++ it("accepts every profile command", () => {+ expect(parse({ type: "profiles_list" })).toEqual({ type: "profiles_list" });+ expect(parse({ type: "profile_import" })).toEqual({ type: "profile_import" });+ expect(parse({ type: "profile_apply", name: "deep-work" })).toEqual({+ type: "profile_apply",+ name: "deep-work",+ });+ expect(parse({ type: "profile_delete", name: "a.b_c" })).toEqual({+ type: "profile_delete",+ name: "a.b_c",+ });+ expect(parse({ type: "profile_rename", from: "a", to: "b" })).toEqual({+ type: "profile_rename",+ from: "a",+ to: "b",+ });+ expect(parse({ type: "profile_duplicate", from: "a", to: "b" })).toEqual({+ type: "profile_duplicate",+ from: "a",+ to: "b",+ });+ expect(parse({ type: "profile_save_current", name: "mine" })).toEqual({+ type: "profile_save_current",+ name: "mine",+ });+ });++ it("keeps only valid routes when saving a profile and drops empty ones", () => {+ expect(+ parse({+ type: "profile_save",+ name: "fast",+ roles: {+ orchestrator: { model: "anthropic/claude-sonnet-4", thinking: "high" },+ "gentle-ai-worker": { thinking: "low" },+ "gentle-ai-explore": {},+ },+ }),+ ).toEqual({+ type: "profile_save",+ name: "fast",+ roles: {+ orchestrator: { model: "anthropic/claude-sonnet-4", thinking: "high" },+ "gentle-ai-worker": { thinking: "low" },+ },+ });+ });++ it("rejects bad profile names, roles, models, and thinking levels", () => {+ for (const bad of [+ { type: "profile_apply" },+ { type: "profile_apply", name: "" },+ { type: "profile_apply", name: "-starts-with-dash" },+ { type: "profile_apply", name: "has space" },+ { type: "profile_apply", name: "x".repeat(65) },+ { type: "profile_apply", name: "constructor" },+ { type: "profile_delete", name: "prototype" },+ { type: "profile_rename", from: "a" },+ { type: "profile_duplicate", from: "a", to: "../b" },+ { type: "profile_save", name: "ok" },+ { type: "profile_save", name: "ok", roles: [] },+ { type: "profile_save", name: "ok", roles: { worker: "anthropic/x" } },+ { type: "profile_save", name: "ok", roles: { worker: { model: "bad model" } } },+ { type: "profile_save", name: "ok", roles: { worker: { thinking: "extreme" } } },+ { type: "profile_save", name: "ok", roles: { "bad role": { thinking: "low" } } },+ { type: "profile_save", name: "ok", roles: { worker: { model: 3 } } },+ { type: "profile_save_current", name: "__proto__" },+ ]) {+ expect(parse(bad), JSON.stringify(bad)).toBeUndefined();+ }+ expect(+ parseClientMessage('{"type":"profile_save","name":"ok","roles":{"__proto__":{"thinking":"low"}}}'),+ ).toBeUndefined();+ });++ it("validates profile names like the engine does", () => {+ expect(isValidProfileName("deep-work.v2_A")).toBe(true);+ expect(isValidProfileName("9lives")).toBe(true);+ expect(isValidProfileName("x".repeat(64))).toBe(true);+ for (const name of ["", "_x", ".x", "x".repeat(65), "a/b", "constructor", "prototype", "__proto__", 3]) {+ expect(isValidProfileName(name), String(name)).toBe(false);+ }+ expect(THINKING_LEVELS).toEqual(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);+ });+});diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex bc4714b..53c9b3f 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -5,6 +5,7 @@ import { AccountsPanel } from "./AccountsPanel.tsx";import { AskCard } from "./AskCard.tsx";import { Composer } from "./Composer.tsx";import { MessageList } from "./MessageList.tsx";+import { ProfilesPanel } from "./ProfilesPanel.tsx";import { newRequestId, type Send } from "./types.ts";interface ChatSurfaceProps {@@ -45,7 +46,12 @@ export function ChatSurface({send({ type: "auth_list" });dispatch({ type: "accounts", open: true });};+ const openProfiles = () => {+ send({ type: "profiles_list" });+ dispatch({ type: "profiles", open: true });+ };const [showConversations, setShowConversations] = useState(false);+ const covered = state.auth.open || state.profiles.open;const status = statusText(state);const ready =state.connection === "open" && state.agentState !== "restarting" && state.agentState !== "starting";@@ -70,6 +76,9 @@ export function ChatSurface({<button type="button" className="icon" aria-label="Accounts" onClick={openAccounts}>⚿</button>+ <button type="button" className="icon" aria-label="Profiles" onClick={openProfiles}>+ ◐+ </button><buttontype="button"className="icon"@@ -125,7 +134,18 @@ export function ChatSurface({</main>) : null}- {!state.auth.open && needsAccount(state) ? (+ {state.profiles.open && !state.auth.open ? (+ <main className="chat-body">+ <ProfilesPanel+ profiles={state.profiles}+ send={send}+ dispatch={dispatch}+ {...(state.auth.providers ? { providers: state.auth.providers } : {})}+ />+ </main>+ ) : null}++ {!covered && needsAccount(state) ? (<div className="onboarding"><p>To start, connect the AI service you use (a subscription or an API key).</p><button type="button" className="primary" onClick={openAccounts}>@@ -134,7 +154,7 @@ export function ChatSurface({</div>) : null}- <main className="chat-body" hidden={state.auth.open}>+ <main className="chat-body" hidden={covered}><MessageList messages={state.messages} />{state.interrupted ? (<div className="interrupted">diff --git a/packages/ui/src/components/ProfilesPanel.tsx b/packages/ui/src/components/ProfilesPanel.tsxnew file mode 100644index 0000000..f122615--- /dev/null+++ b/packages/ui/src/components/ProfilesPanel.tsx@@ -0,0 +1,416 @@+import {+ type AuthProvider,+ isValidProfileName,+ type ModelOption,+ type Profile,+ type ProfileRole,+ type ProfileRoles,+ type RoleRoute,+ THINKING_LEVELS,+ type ThinkingLevel,+} from "@gentle-dot/protocol";+import { type FormEvent, useState } from "react";+import type { DotAction, ProfilesState } from "../store.ts";+import type { Send } from "./types.ts";+import "../profiles.css";++interface ProfilesPanelProps {+ profiles: ProfilesState;+ /** Account names, used to label model groups. */+ providers?: AuthProvider[];+ send: Send;+ dispatch: (action: DotAction) => void;+}++type Mode =+ | { kind: "list" }+ | { kind: "edit"; profile?: Profile }+ | { kind: "name"; action: "rename" | "duplicate" | "save_current"; from?: string }+ | { kind: "delete"; name: string };++const THINKING_LABELS: Record<ThinkingLevel, string> = {+ off: "Off",+ minimal: "Minimal",+ low: "Low",+ medium: "Medium",+ high: "High",+ xhigh: "Extra high",+ max: "Max",+};++const NAME_HINT =+ "Use letters, numbers, dots, dashes, or underscores (up to 64), starting with a letter or number.";++/** Names a profile, or explains why the name cannot be used. */+function nameProblem(name: string, taken: string[]): string | undefined {+ if (!name) return undefined;+ if (!isValidProfileName(name)) return NAME_HINT;+ if (taken.includes(name)) return "A profile with that name already exists.";+ return undefined;+}++/** Profiles pick the model each part of the assistant uses; managed here without a terminal. */+export function ProfilesPanel({ profiles, providers = [], send, dispatch }: ProfilesPanelProps) {+ const [mode, setMode] = useState<Mode>({ kind: "list" });+ const list = profiles.list ?? [];+ const names = list.map((p) => p.name);+ const back = () => setMode({ kind: "list" });++ return (+ <section className="profiles" aria-label="Profiles">+ <header className="profiles-header">+ <h2>Profiles</h2>+ <button+ type="button"+ className="icon"+ aria-label="Close profiles"+ onClick={() => dispatch({ type: "profiles", open: false })}+ >+ ×+ </button>+ </header>++ {mode.kind === "edit" ? (+ <ProfileEditor+ profile={mode.profile}+ roles={profiles.roles}+ models={profiles.models}+ providers={providers}+ taken={names}+ onCancel={back}+ onSave={(name, roles) => {+ send({ type: "profile_save", name, roles });+ back();+ }}+ />+ ) : mode.kind === "name" ? (+ <NameForm+ mode={mode}+ taken={names}+ onCancel={back}+ onSubmit={(name) => {+ const from = mode.from ?? "";+ if (mode.action === "save_current") send({ type: "profile_save_current", name });+ else if (mode.action === "rename") send({ type: "profile_rename", from, to: name });+ else send({ type: "profile_duplicate", from, to: name });+ back();+ }}+ />+ ) : (+ <>+ <p className="muted">+ A profile chooses the AI model each part of the assistant uses. Switch profiles any time.+ </p>+ {profiles.lastImport ? (+ <ImportResult+ result={profiles.lastImport}+ openAccounts={() => {+ send({ type: "auth_list" });+ dispatch({ type: "accounts", open: true });+ }}+ />+ ) : null}+ {profiles.list === undefined ? <p className="muted">Loading…</p> : null}+ {profiles.list?.length === 0 ? <p className="muted">No profiles yet.</p> : null}+ <ul className="profile-list">+ {list.map((profile) => {+ const inUse = profile.name === profiles.active;+ const deleting = mode.kind === "delete" && mode.name === profile.name;+ return (+ <li key={profile.name} className={inUse ? "in-use" : undefined}>+ <div className="profile-name">+ <b>{profile.name}</b>+ {inUse ? <span className="chip ok">In use</span> : null}+ </div>+ <p className="profile-summary">{summary(profile, profiles.roles, profiles.models)}</p>+ {deleting ? (+ <div className="profile-confirm" role="alertdialog" aria-label="Delete profile">+ <p>{`Delete “${profile.name}”? This cannot be undone.`}</p>+ <button+ type="button"+ className="primary danger"+ onClick={() => {+ send({ type: "profile_delete", name: profile.name });+ back();+ }}+ >+ Delete+ </button>+ <button type="button" onClick={back}>+ Keep it+ </button>+ </div>+ ) : (+ <div className="profile-actions">+ {inUse ? null : (+ <button+ type="button"+ className="primary"+ onClick={() => send({ type: "profile_apply", name: profile.name })}+ >+ Use+ </button>+ )}+ <button type="button" onClick={() => setMode({ kind: "edit", profile })}>+ Edit+ </button>+ <button+ type="button"+ onClick={() => setMode({ kind: "name", action: "duplicate", from: profile.name })}+ >+ Duplicate+ </button>+ <button+ type="button"+ onClick={() => setMode({ kind: "name", action: "rename", from: profile.name })}+ >+ Rename+ </button>+ <button+ type="button"+ className="link"+ disabled={inUse}+ title={inUse ? "Switch to another profile before deleting this one." : undefined}+ onClick={() => setMode({ kind: "delete", name: profile.name })}+ >+ Delete+ </button>+ </div>+ )}+ </li>+ );+ })}+ </ul>+ <div className="profiles-footer">+ <button type="button" className="primary" onClick={() => setMode({ kind: "edit" })}>+ New profile+ </button>+ <button type="button" onClick={() => setMode({ kind: "name", action: "save_current" })}>+ Save my current setup+ </button>+ {profiles.importable ? (+ <button type="button" onClick={() => send({ type: "profile_import" })}>+ Import my Gentle Shell profiles+ </button>+ ) : null}+ </div>+ </>+ )}+ </section>+ );+}++function modelLabel(model: string | undefined, models: ModelOption[]): string {+ if (!model) return "Default";+ return models.find((m) => `${m.provider}/${m.id}` === model)?.name ?? model;+}++/** One line per routed role the screen knows, for example "Main assistant: Fake Model · High". */+function summary(profile: Profile, roles: ProfileRole[], models: ModelOption[]): string {+ const lines = roles.flatMap((role) => {+ const route = profile.roles[role.id];+ if (!route) return [];+ const thinking = route.thinking ? ` · ${THINKING_LABELS[route.thinking]}` : "";+ return [`${role.label}: ${modelLabel(route.model, models)}${thinking}`];+ });+ return lines.length > 0 ? lines.join(", ") : "Uses the default model everywhere.";+}++function ProfileEditor({+ profile,+ roles,+ models,+ providers,+ taken,+ onSave,+ onCancel,+}: {+ profile?: Profile;+ roles: ProfileRole[];+ models: ModelOption[];+ providers: AuthProvider[];+ taken: string[];+ onSave: (name: string, roles: ProfileRoles) => void;+ onCancel: () => void;+}) {+ const [name, setName] = useState("");+ // Starts from every saved route, so roles this screen does not show are kept.+ const [routes, setRoutes] = useState<ProfileRoles>(() => structuredClone(profile?.roles ?? {}));+ const problem = profile ? undefined : nameProblem(name, taken);+ const valid = profile !== undefined || (name !== "" && problem === undefined);+ const groups = new Map<string, ModelOption[]>();+ for (const model of models) groups.set(model.provider, [...(groups.get(model.provider) ?? []), model]);+ const providerName = (id: string) => providers.find((p) => p.id === id)?.name ?? id;++ const update = (role: string, change: Partial<RoleRoute>) =>+ setRoutes((current) => {+ const next: RoleRoute = { ...current[role], ...change };+ if (!next.model) delete next.model;+ if (!next.thinking) delete next.thinking;+ const { [role]: _removed, ...others } = current;+ return next.model || next.thinking ? { ...current, [role]: next } : others;+ });++ const submit = (event: FormEvent) => {+ event.preventDefault();+ if (valid) onSave(profile?.name ?? name, routes);+ };++ return (+ <form+ className="profile-editor"+ aria-label={profile ? `Edit ${profile.name}` : "New profile"}+ onSubmit={submit}+ >+ {profile ? (+ <h3>{profile.name}</h3>+ ) : (+ <label className="profile-field">+ <span>Name</span>+ <input+ type="text"+ aria-label="Profile name"+ autoComplete="off"+ placeholder="for example deep-work"+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ {problem ? <small className="profile-problem">{problem}</small> : null}+ </label>+ )}+ <div className="role-routes">+ {roles.map((role) => {+ const route = routes[role.id] ?? {};+ const known = !route.model || models.some((m) => `${m.provider}/${m.id}` === route.model);+ return (+ <div className="role-route" key={role.id}>+ <span className="role-label">{role.label}</span>+ <select+ aria-label={`${role.label} model`}+ value={route.model ?? ""}+ onChange={(event) => update(role.id, { model: event.target.value })}+ >+ <option value="">Default</option>+ {[...groups].map(([provider, options]) => (+ <optgroup key={provider} label={providerName(provider)}>+ {options.map((m) => (+ <option key={m.id} value={`${m.provider}/${m.id}`}>+ {m.name}+ </option>+ ))}+ </optgroup>+ ))}+ {known ? null : <option value={route.model}>{`${route.model} (not available)`}</option>}+ </select>+ <select+ aria-label={`${role.label} thinking`}+ value={route.thinking ?? ""}+ onChange={(event) =>+ update(role.id, {+ thinking: (event.target.value || undefined) as ThinkingLevel | undefined,+ })+ }+ >+ <option value="">Default</option>+ {THINKING_LEVELS.map((level) => (+ <option key={level} value={level}>+ {THINKING_LABELS[level]}+ </option>+ ))}+ </select>+ </div>+ );+ })}+ </div>+ <div className="profile-form-actions">+ <button type="submit" className="primary" disabled={!valid}>+ Save+ </button>+ <button type="button" onClick={onCancel}>+ Cancel+ </button>+ </div>+ </form>+ );+}++const NAME_FORMS = {+ rename: { label: "New name", submit: "Rename" },+ duplicate: { label: "Name for the copy", submit: "Duplicate" },+ save_current: { label: "Name for your current setup", submit: "Save" },+} as const;++function NameForm({+ mode,+ taken,+ onSubmit,+ onCancel,+}: {+ mode: Extract<Mode, { kind: "name" }>;+ taken: string[];+ onSubmit: (name: string) => void;+ onCancel: () => void;+}) {+ const initial = mode.action === "duplicate" ? `${mode.from}-copy` : (mode.from ?? "");+ const [name, setName] = useState(initial);+ const text = NAME_FORMS[mode.action];+ const problem = name === mode.from ? undefined : nameProblem(name, taken);+ const valid = name !== "" && name !== mode.from && problem === undefined;+ return (+ <form+ className="profile-editor"+ aria-label={text.label}+ onSubmit={(event) => {+ event.preventDefault();+ if (valid) onSubmit(name);+ }}+ >+ <label className="profile-field">+ <span>{text.label}</span>+ <input+ type="text"+ aria-label={text.label}+ autoComplete="off"+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ {problem ? <small className="profile-problem">{problem}</small> : null}+ </label>+ <div className="profile-form-actions">+ <button type="submit" className="primary" disabled={!valid}>+ {text.submit}+ </button>+ <button type="button" onClick={onCancel}>+ Cancel+ </button>+ </div>+ </form>+ );+}++function ImportResult({+ result,+ openAccounts,+}: {+ result: NonNullable<ProfilesState["lastImport"]>;+ openAccounts: () => void;+}) {+ const renamed = result.imported.filter((i) => i.from !== i.to);+ const count = result.imported.length;+ return (+ <div className="profiles-import" role="status">+ <p>{count === 0 ? "Nothing new to import." : `Imported ${count} profile${count === 1 ? "" : "s"}.`}</p>+ {renamed.length > 0 ? (+ <p>{`Renamed because the name was taken: ${renamed.map((r) => `${r.from} → ${r.to}`).join(", ")}.`}</p>+ ) : null}+ {result.missingProviders.length > 0 ? (+ <p>+ {`Connect these accounts to use them: ${result.missingProviders.join(", ")}. `}+ <button type="button" className="link" onClick={openAccounts}>+ Open accounts+ </button>+ </p>+ ) : null}+ </div>+ );+}diff --git a/packages/ui/src/profiles.css b/packages/ui/src/profiles.cssnew file mode 100644index 0000000..2d82ac7--- /dev/null+++ b/packages/ui/src/profiles.css@@ -0,0 +1,131 @@+/* Profiles screen (ProfilesPanel). Uses the shared tokens and button styles from styles.css. */++.profiles-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.profiles h2 {+ margin: 0;+ font-size: 16px;+}++.profiles h3 {+ margin: 4px 0 12px;+ font-size: 15px;+}++.profiles .muted {+ margin: 4px 0 12px;+}++.profile-list {+ list-style: none;+ margin: 12px 0 0;+ padding: 0;+}++.profile-list li {+ padding: 10px 0;+ border-bottom: 1px solid var(--line);+}++.profile-name {+ display: flex;+ align-items: center;+ gap: 8px;+}++.profile-summary {+ margin: 4px 0 8px;+ font-size: 12px;+ color: var(--muted);+}++.profile-actions,+.profile-confirm,+.profile-form-actions,+.profiles-footer {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+}++.profile-confirm p {+ flex: 1 1 100%;+ margin: 0;+}++button.danger {+ background: var(--danger);+ border-color: var(--danger);+}++.profiles-footer {+ margin-top: 14px;+}++.profiles-import {+ padding: 10px 12px;+ border-radius: 14px;+ border: 1px solid var(--line);+ background: var(--raised);+}++.profiles-import p {+ margin: 0 0 6px;+}++.profiles-import p:last-child {+ margin-bottom: 0;+}++.profile-editor {+ display: flex;+ flex-direction: column;+ gap: 12px;+ margin-top: 8px;+}++.profile-field {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.profile-field input,+.role-route select {+ padding: 7px 10px;+ border-radius: 10px;+ border: 1px solid var(--line);+ background: var(--raised);+ color: inherit;+ font: inherit;+}++.profile-problem {+ color: var(--danger);+}++.role-routes {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.role-route {+ display: grid;+ grid-template-columns: minmax(110px, 1fr) minmax(0, 2fr) minmax(0, 1fr);+ align-items: center;+ gap: 8px;+}++.role-label {+ font-size: 13px;+}++.role-route select {+ min-width: 0;+}diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex d48bae3..c98ee1a 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -6,6 +6,9 @@ import type {AuthPrompt,AuthProvider,ConversationSummary,+ ModelOption,+ Profile,+ ProfileRole,ServerMessage,} from "@gentle-dot/protocol";@@ -24,6 +27,18 @@ export interface AuthState {flow?: AuthFlowState;}+export interface ProfilesState {+ open: boolean;+ /** Undefined until the first list arrives. */+ list?: Profile[];+ active?: string;+ roles: ProfileRole[];+ models: ModelOption[];+ importable: boolean;+ /** The last import's result, shown until the screen closes. */+ lastImport?: { imported: { from: string; to: string }[]; missingProviders: string[] };+}+export type ConnectionStatus = "connecting" | "open" | "closed" | "unauthorized";export interface ChatMessage {@@ -51,6 +66,7 @@ export interface DotState {interrupted: boolean;notices: Notice[];auth: AuthState;+ profiles: ProfilesState;}export type DotAction =@@ -58,6 +74,7 @@ export type DotAction =| { type: "connection"; status: ConnectionStatus }| { type: "dismiss"; id: number }| { type: "accounts"; open: boolean }+ | { type: "profiles"; open: boolean }| { type: "auth_started"; providerId: string };export const initialState: DotState = {@@ -69,6 +86,7 @@ export const initialState: DotState = {interrupted: false,notices: [],auth: { open: false },+ profiles: { open: false, roles: [], models: [], importable: false },};let nextNotice = 0;@@ -87,10 +105,12 @@ export function reduce(state: DotState, action: DotAction): DotState {// Closing drops the flow; reopening keeps a running one and leaves a finished one.const keep = action.open && state.auth.flow !== undefined && state.auth.flow.done === undefined;return {- ...state,+ ...closeProfiles(state, action.open),auth: { ...state.auth, open: action.open, flow: keep ? state.auth.flow : undefined },};}+ case "profiles":+ return openProfiles(state, action.open);case "auth_started":return {...state,@@ -164,9 +184,25 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {return { ...state, interrupted: true };case "auth_providers":return {- ...state,+ ...closeProfiles(state, message.open === true),auth: { ...state.auth, providers: message.providers, open: message.open ? true : state.auth.open },};+ case "profiles": {+ const { type: _type, seq: _seq, open, profiles, active, ...rest } = message;+ const next = { ...state.profiles, ...rest, list: profiles };+ if (active === undefined) delete next.active;+ else next.active = active;+ const updated = { ...state, profiles: next };+ return open ? openProfiles(updated, true) : updated;+ }+ case "profiles_imported":+ return {+ ...state,+ profiles: {+ ...state.profiles,+ lastImport: { imported: message.imported, missingProviders: message.missingProviders },+ },+ };case "auth_event":return updateFlow(state, message.flowId, (f) => ({ ...f, events: [...f.events, message.event] }));case "auth_prompt":@@ -186,6 +222,20 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {}}+/** Profiles and accounts share the screen: opening one closes the other. */+function openProfiles(state: DotState, open: boolean): DotState {+ const { lastImport: _lastImport, ...rest } = state.profiles;+ return {+ ...state,+ auth: open ? { ...state.auth, open: false } : state.auth,+ profiles: open ? { ...state.profiles, open } : { ...rest, open },+ };+}++function closeProfiles(state: DotState, when: boolean): DotState {+ return when && state.profiles.open ? openProfiles(state, false) : state;+}+function updateFlow(state: DotState, flowId: string, update: (f: AuthFlowState) => AuthFlowState): DotState {const flow = state.auth.flow;if (!flow || (flow.flowId && flow.flowId !== flowId)) return state;diff --git a/packages/ui/test/profiles.test.tsx b/packages/ui/test/profiles.test.tsxnew file mode 100644index 0000000..5c62199--- /dev/null+++ b/packages/ui/test/profiles.test.tsx@@ -0,0 +1,270 @@+import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { ProfilesPanel } from "../src/components/ProfilesPanel.tsx";+import { type DotState, initialState, reduce } from "../src/store.ts";++const roles = [+ { id: "orchestrator", label: "Main assistant" },+ { id: "gentle-ai-worker", label: "Builder" },+];+const models = [+ { provider: "fake", id: "fake-model", name: "Fake Model", reasoning: true },+ { provider: "fake", id: "fake-fast", name: "Fake Fast", reasoning: false },+ { provider: "other", id: "big", name: "Other Big", reasoning: true },+];+const profilesPayload: ServerPayload = {+ type: "profiles",+ profiles: [+ {+ name: "deep",+ roles: {+ orchestrator: { model: "fake/fake-model", thinking: "high" },+ "custom-agent": { model: "x/y" },+ },+ },+ { name: "quick", roles: { orchestrator: { model: "fake/fake-fast" } } },+ ],+ active: "quick",+ roles,+ models,+ importable: true,+};++function apply(state: DotState, ...payloads: ServerPayload[]): DotState {+ return payloads.reduce(+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: 1 } as ServerMessage }),+ state,+ );+}++function base(): DotState {+ return apply({ ...initialState, connection: "open", agentState: "idle" }, profilesPayload);+}++function panel(state = base()) {+ const send = vi.fn();+ const dispatch = vi.fn();+ render(+ <ProfilesPanel+ profiles={state.profiles}+ providers={[{ id: "fake", name: "Fake Cloud", methods: ["api_key"], configured: true }]}+ send={send}+ dispatch={dispatch}+ />,+ );+ return { send, dispatch };+}++const item = (name: string) =>+ screen.getAllByRole("listitem").find((li) => within(li).queryByText(name, { exact: true })) as HTMLElement;++describe("profiles state", () => {+ it("keeps the list, the profile in use, roles, models, and whether import is offered", () => {+ const s = base();+ expect(s.profiles).toEqual({+ open: false,+ list: (profilesPayload as { profiles: unknown }).profiles,+ active: "quick",+ roles,+ models,+ importable: true,+ });+ });++ it("opens on /profiles, closes accounts, and accounts close profiles in turn", () => {+ let s = reduce(base(), { type: "accounts", open: true });+ s = apply(s, { ...profilesPayload, open: true });+ expect([s.profiles.open, s.auth.open]).toEqual([true, false]);+ s = reduce(s, { type: "accounts", open: true });+ expect([s.profiles.open, s.auth.open]).toEqual([false, true]);+ s = reduce(s, { type: "profiles", open: true });+ expect([s.profiles.open, s.auth.open]).toEqual([true, false]);+ });++ it("drops the profile in use when the list has none", () => {+ const s = apply(base(), { ...profilesPayload, active: undefined });+ expect(s.profiles.active).toBeUndefined();+ });++ it("shows an import result until the screen closes", () => {+ let s = apply(base(), {+ type: "profiles_imported",+ imported: [{ from: "quick", to: "quick-imported" }],+ missingProviders: ["Anthropic"],+ });+ expect(s.profiles.lastImport).toEqual({+ imported: [{ from: "quick", to: "quick-imported" }],+ missingProviders: ["Anthropic"],+ });+ s = reduce(s, { type: "profiles", open: false });+ expect(s.profiles.lastImport).toBeUndefined();+ });+});++describe("ProfilesPanel", () => {+ it("lists profiles, marks the one in use, and switches with Use", async () => {+ const { send } = panel();+ expect(within(item("quick")).getByText("In use")).toBeInTheDocument();+ expect(within(item("quick")).queryByRole("button", { name: "Use" })).toBeNull();+ expect(within(item("quick")).getByRole("button", { name: "Delete" })).toBeDisabled();+ expect(within(item("deep")).getByText("Main assistant: Fake Model · High")).toBeInTheDocument();+ await userEvent.click(within(item("deep")).getByRole("button", { name: "Use" }));+ expect(send).toHaveBeenCalledWith({ type: "profile_apply", name: "deep" });+ });++ it("edits a profile per role with models grouped by provider and keeps routes it does not show", async () => {+ const { send } = panel();+ await userEvent.click(within(item("deep")).getByRole("button", { name: "Edit" }));+ const model = screen.getByRole("combobox", { name: "Builder model" });+ const groups = [...model.querySelectorAll("optgroup")].map((g) => g.label);+ expect(groups).toEqual(["Fake Cloud", "other"]);+ expect(within(model).getByRole("option", { name: "Default" })).toBeInTheDocument();+ await userEvent.selectOptions(model, "other/big");+ await userEvent.selectOptions(screen.getByRole("combobox", { name: "Builder thinking" }), "low");+ await userEvent.selectOptions(screen.getByRole("combobox", { name: "Main assistant thinking" }), "");+ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(send).toHaveBeenCalledWith({+ type: "profile_save",+ name: "deep",+ roles: {+ orchestrator: { model: "fake/fake-model" },+ "custom-agent": { model: "x/y" },+ "gentle-ai-worker": { model: "other/big", thinking: "low" },+ },+ });+ expect(screen.getByRole("list")).toBeInTheDocument();+ });++ it("keeps a model that is not available so saving does not lose it", async () => {+ const state = apply(base(), {+ ...profilesPayload,+ profiles: [{ name: "gone", roles: { orchestrator: { model: "anthropic/opus" } } }],+ });+ panel(state);+ await userEvent.click(within(item("gone")).getByRole("button", { name: "Edit" }));+ expect(screen.getByRole("combobox", { name: "Main assistant model" })).toHaveValue("anthropic/opus");+ expect(screen.getByRole("option", { name: "anthropic/opus (not available)" })).toBeInTheDocument();+ });++ it("creates a new profile only with a valid, unused name", async () => {+ const { send } = panel();+ await userEvent.click(screen.getByRole("button", { name: "New profile" }));+ const name = screen.getByRole("textbox", { name: "Profile name" });+ const save = screen.getByRole("button", { name: "Save" });+ expect(save).toBeDisabled();+ await userEvent.type(name, "has space");+ expect(save).toBeDisabled();+ expect(screen.getByText(/letters, numbers, dots, dashes, or underscores/)).toBeInTheDocument();+ await userEvent.clear(name);+ await userEvent.type(name, "quick");+ expect(screen.getByText("A profile with that name already exists.")).toBeInTheDocument();+ await userEvent.clear(name);+ await userEvent.type(name, "focus");+ await userEvent.selectOptions(+ screen.getByRole("combobox", { name: "Main assistant model" }),+ "fake/fake-fast",+ );+ await userEvent.click(save);+ expect(send).toHaveBeenCalledWith({+ type: "profile_save",+ name: "focus",+ roles: { orchestrator: { model: "fake/fake-fast" } },+ });+ });++ it("duplicates and renames through a name form", async () => {+ const { send } = panel();+ await userEvent.click(within(item("deep")).getByRole("button", { name: "Duplicate" }));+ expect(screen.getByRole("textbox", { name: "Name for the copy" })).toHaveValue("deep-copy");+ await userEvent.click(screen.getByRole("button", { name: "Duplicate" }));+ expect(send).toHaveBeenCalledWith({ type: "profile_duplicate", from: "deep", to: "deep-copy" });++ await userEvent.click(within(item("deep")).getByRole("button", { name: "Rename" }));+ const name = screen.getByRole("textbox", { name: "New name" });+ await userEvent.clear(name);+ await userEvent.type(name, "deeper");+ await userEvent.click(screen.getByRole("button", { name: "Rename" }));+ expect(send).toHaveBeenLastCalledWith({ type: "profile_rename", from: "deep", to: "deeper" });+ });++ it("asks before deleting", async () => {+ const { send } = panel();+ await userEvent.click(within(item("deep")).getByRole("button", { name: "Delete" }));+ const confirm = screen.getByRole("alertdialog", { name: "Delete profile" });+ expect(confirm).toHaveTextContent("Delete “deep”? This cannot be undone.");+ await userEvent.click(within(confirm).getByRole("button", { name: "Keep it" }));+ expect(send).not.toHaveBeenCalled();+ await userEvent.click(within(item("deep")).getByRole("button", { name: "Delete" }));+ await userEvent.click(+ within(screen.getByRole("alertdialog", { name: "Delete profile" })).getByRole("button", {+ name: "Delete",+ }),+ );+ expect(send).toHaveBeenCalledWith({ type: "profile_delete", name: "deep" });+ });++ it("saves the current setup under a new name", async () => {+ const { send } = panel();+ await userEvent.click(screen.getByRole("button", { name: "Save my current setup" }));+ await userEvent.type(screen.getByRole("textbox", { name: "Name for your current setup" }), "today");+ await userEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(send).toHaveBeenCalledWith({ type: "profile_save_current", name: "today" });+ });++ it("imports when offered and explains renames and accounts to connect", async () => {+ const { send, dispatch } = panel(+ apply(base(), {+ type: "profiles_imported",+ imported: [+ { from: "quick", to: "quick-imported" },+ { from: "solo", to: "solo" },+ ],+ missingProviders: ["Anthropic"],+ }),+ );+ await userEvent.click(screen.getByRole("button", { name: "Import my Gentle Shell profiles" }));+ expect(send).toHaveBeenCalledWith({ type: "profile_import" });+ const result = screen.getByRole("status");+ expect(result).toHaveTextContent("Imported 2 profiles.");+ expect(result).toHaveTextContent("Renamed because the name was taken: quick → quick-imported.");+ expect(result).toHaveTextContent("Connect these accounts to use them: Anthropic.");+ await userEvent.click(within(result).getByRole("button", { name: "Open accounts" }));+ expect(send).toHaveBeenCalledWith({ type: "auth_list" });+ expect(dispatch).toHaveBeenCalledWith({ type: "accounts", open: true });+ });++ it("hides import when there is nothing to import", () => {+ panel(apply(base(), { ...profilesPayload, importable: false }));+ expect(screen.queryByRole("button", { name: "Import my Gentle Shell profiles" })).toBeNull();+ });++ it("closes", async () => {+ const { dispatch } = panel();+ await userEvent.click(screen.getByRole("button", { name: "Close profiles" }));+ expect(dispatch).toHaveBeenCalledWith({ type: "profiles", open: false });+ });+});++describe("ChatSurface profiles", () => {+ it("opens profiles from the header", async () => {+ const send = vi.fn();+ const dispatch = vi.fn();+ render(<ChatSurface variant="web" state={base()} send={send} dismiss={vi.fn()} dispatch={dispatch} />);+ await userEvent.click(screen.getByRole("button", { name: "Profiles" }));+ expect(send).toHaveBeenCalledWith({ type: "profiles_list" });+ expect(dispatch).toHaveBeenCalledWith({ type: "profiles", open: true });+ });++ it("shows the profiles screen instead of the chat while open", () => {+ const state = reduce(apply(base(), { type: "user_message", messageId: "u1", text: "earlier question" }), {+ type: "profiles",+ open: true,+ });+ render(<ChatSurface variant="web" state={state} send={vi.fn()} dismiss={vi.fn()} />);+ expect(screen.getByRole("region", { name: "Profiles" })).toBeInTheDocument();+ expect(screen.getByText("earlier question")).not.toBeVisible();+ });+});