Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(modes): let users edit builtin modes; drop the Goal budget setting
vastsaac93a0ff75cb
diff --git a/apps/desktop/electron/main/runtime/mode-catalog.ts b/apps/desktop/electron/main/runtime/mode-catalog.tsindex a57338426..e182e716b 100644--- a/apps/desktop/electron/main/runtime/mode-catalog.ts+++ b/apps/desktop/electron/main/runtime/mode-catalog.ts@@ -4,7 +4,9 @@* Electron main owns the user's global `~/.pi/modes` directory: it reads the* documents, hands them to the agent-runtime loader for strict validation, and* keeps the parsed catalog for the renderer and for the snapshots it attaches- * to `session.configure`. Workspaces never provide modes.+ * to `session.configure`. Workspaces never provide modes. A builtin is+ * edited by writing `<dir>/<builtin>/mode.md`; removing that file restores+ * the shipped definition.*/import { mkdir, readdir, readFile, rm, rmdir, stat, writeFile } from "node:fs/promises";import { homedir } from "node:os";@@ -25,6 +27,10 @@ import {} from "@pi-desktop/shared";export const MODE_DOCUMENT_NAME = "mode.md";++function isBuiltinId(id: string): boolean {+ return (BUILTIN_MODE_IDS as readonly string[]).includes(id);+}const TEMPLATE_DIR = "templates";const MAX_USER_MODE_DIRECTORIES = 64;@@ -149,6 +155,11 @@ export function createModeCatalogService(options: {): Promise<{ modeDir: string; known: boolean; occupiedBy?: string }> {if (rescan) cache = null;const { catalog } = await current();+ if (isBuiltinId(id)) {+ // A builtin's override always lives in the folder named after it.+ const builtin = catalog.modes.find((entry) => entry.id === id && entry.source === "builtin");+ return { modeDir: join(dir, id), known: builtin?.customized === true };+ }const entries = catalog.modes.filter((entry) => entry.id === id && entry.source === "user" && !entry.reserved && entry.filePath);const entry = entries.find((candidate) => candidate.available) ?? entries[0];if (entry?.filePath) return { modeDir: dirname(entry.filePath), known: true };@@ -163,16 +174,10 @@ export function createModeCatalogService(options: {if (!isModeId(id)) {throw modeError("MODE_ID_INVALID", "Mode ids use lowercase letters, digits and dashes and start with a letter");}- if ((BUILTIN_MODE_IDS as readonly string[]).includes(id)) {- throw modeError("MODE_ID_RESERVED", `"${id}" is a builtin mode; save a copy under another id`);- }}async function validate(id: string, source: string): Promise<ModeDocumentValidation> {if (!isModeId(id)) return { ok: false, errors: ["name: invalid mode id"], warnings: [] };- if ((BUILTIN_MODE_IDS as readonly string[]).includes(id)) {- return { ok: false, errors: [`name: "${id}" is a builtin mode`], warnings: [] };- }if (Buffer.byteLength(source) > MODE_LIMITS.fileBytes) {return { ok: false, errors: [`file: larger than ${MODE_LIMITS.fileBytes} bytes`], warnings: [] };}@@ -191,6 +196,7 @@ export function createModeCatalogService(options: {const diagnostic = result.diagnostics.find((entry) => entry.modeId === id);const errors = diagnostic?.errors ?? [];const warnings = diagnostic?.warnings ?? [];+ // An override loads in place of the builtin, under the builtin's id.const loaded = result.definitions.some((definition) => definition.id === id && definition.source === "user");if (!loaded) return { ok: false, errors: errors.length ? errors : ["mode could not be loaded"], warnings };return { ok: errors.length === 0, errors, warnings };@@ -215,14 +221,14 @@ export function createModeCatalogService(options: {},async read(id: string): Promise<ModeDocumentReadResult> {const builtin = builtinModeSource(id);- if (builtin !== undefined) return { id, source: builtin, builtin: true };- if (!isModeId(id)) throw modeError("MODE_ID_INVALID", "invalid mode id");+ if (builtin === undefined && !isModeId(id)) throw modeError("MODE_ID_INVALID", "invalid mode id");const filePath = join((await locate(id, true)).modeDir, MODE_DOCUMENT_NAME);try {- return { id, source: await readFile(filePath, "utf8"), filePath, builtin: false };+ return { id, source: await readFile(filePath, "utf8"), filePath, builtin: builtin !== undefined };} catch (error) {- if (isMissing(error)) throw modeError("MODE_NOT_FOUND", `Mode "${id}" does not exist`);- throw error;+ if (!isMissing(error)) throw error;+ if (builtin !== undefined) return { id, source: builtin, builtin: true };+ throw modeError("MODE_NOT_FOUND", `Mode "${id}" does not exist`);}},validate,@@ -241,6 +247,7 @@ export function createModeCatalogService(options: {options.logger?.app("settings", "info", "mode definition saved", { data: { id } });return refresh();},+ /** For a builtin, deletes its override and restores the shipped definition. */async remove(id: string): Promise<ModeCatalog> {assertWritableId(id);const { modeDir, known } = await locate(id, true);diff --git a/apps/desktop/electron/main/runtime/mode-runs.ts b/apps/desktop/electron/main/runtime/mode-runs.tsindex 9c5469bcd..0b334c2ed 100644--- a/apps/desktop/electron/main/runtime/mode-runs.ts+++ b/apps/desktop/electron/main/runtime/mode-runs.ts@@ -112,8 +112,10 @@ export function createModeRunCoordinator(deps: {return {async definitionForPrompt(modeId: string): Promise<ModeDefinition | undefined> {- if (isPlainMode(modeId)) return undefined;const definition = await deps.catalog.definition(modeId);+ // Agent and Plan use the runtime's builtin instructions unless the user+ // overrides them; the Host never needs a snapshot for either.+ if (isPlainMode(modeId)) return definition?.source === "user" ? definition : undefined;if (!definition && modeId !== "agent" && modeId !== "plan") {throw Object.assign(new Error("Mode is not available"), { errorCode: "MODE_NOT_FOUND" });}diff --git a/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsx b/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsxdeleted file mode 100644index c41cf2cee..000000000--- a/apps/desktop/src/features/modes/GoalBudgetSettingsRow.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { useEffect, useState, type KeyboardEvent } from "react";-import { useTranslation } from "react-i18next";-import type { AppSettings, ModeRunBudget } from "@pi-desktop/shared";-import { Input } from "../../components/ui";-import { SettingsRow } from "../settings/primitives";-import { modeBudgetFieldText, parseModeBudgetField } from "./mode-run-model";-import "../../styles/modes.css";--/** Builtin Goal budget (`goal` mode definition), used when the setting is absent. */-export const GOAL_DEFAULT_BUDGET: ModeRunBudget = { maxTurns: 20, maxTokens: null };--export function goalBudgetSetting(settings: Pick<AppSettings, "goalBudget">): ModeRunBudget {- return settings.goalBudget ?? GOAL_DEFAULT_BUDGET;-}--/**- * Settings → Agent behavior: the budget a new Goal run starts with. A field- * saves on blur or Enter; empty is unlimited, an out-of-range value reverts.- * Runs already open keep their own budget (edit those from the run bar).- */-export function GoalBudgetSettingsRow({- settings,- saveSettings,-}: {- settings: AppSettings;- saveSettings: (patch: Partial<AppSettings>) => Promise<void>;-}) {- const { t } = useTranslation();- const saved = goalBudgetSetting(settings);- const [text, setText] = useState(() => ({- maxTurns: modeBudgetFieldText(saved.maxTurns),- maxTokens: modeBudgetFieldText(saved.maxTokens),- }));- useEffect(() => {- setText({ maxTurns: modeBudgetFieldText(saved.maxTurns), maxTokens: modeBudgetFieldText(saved.maxTokens) });- }, [saved.maxTurns, saved.maxTokens]);-- const commit = (field: keyof ModeRunBudget) => {- const value = parseModeBudgetField(text[field], field);- if (value === undefined) {- setText((current) => ({ ...current, [field]: modeBudgetFieldText(saved[field]) }));- return;- }- if (value === saved[field]) return;- void saveSettings({ goalBudget: { ...saved, [field]: value } });- };- const onKeyDown = (field: keyof ModeRunBudget) => (event: KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Enter") {- event.preventDefault();- commit(field);- }- };-- return (- <SettingsRow title={t("settings.goalBudget")} description={t("settings.goalBudgetDesc")}>- <div className="settings-goal-budget">- {(["maxTurns", "maxTokens"] as const).map((field) => {- const label = t(field === "maxTurns" ? "settings.goalBudgetTurns" : "settings.goalBudgetTokens");- return (- <label key={field} className="settings-goal-budget-field">- <span className="settings-goal-budget-label">{label}</span>- <Input- className="settings-goal-budget-input"- inputMode="numeric"- placeholder={t("modes.run.unlimited")}- value={text[field]}- onChange={(event) => setText((current) => ({ ...current, [field]: event.target.value }))}- onBlur={() => commit(field)}- onKeyDown={onKeyDown(field)}- />- </label>- );- })}- </div>- </SettingsRow>- );-}diff --git a/apps/desktop/src/features/modes/ModesSettingsPage.tsx b/apps/desktop/src/features/modes/ModesSettingsPage.tsxindex 8f3da25ab..623cc0bcb 100644--- a/apps/desktop/src/features/modes/ModesSettingsPage.tsx+++ b/apps/desktop/src/features/modes/ModesSettingsPage.tsx@@ -36,9 +36,10 @@ const ID_PROBLEM_KEYS: Record<NewModeIdProblem, string> = {/*** Settings → Modes (ADR mode-definitions): every mode in the catalog, the- * definitions folder, and a source editor. Builtins are read-only and can be- * duplicated under a new id; user documents are validated while typing and- * saved or deleted through Electron main.+ * definitions folder, and a source editor. Every mode is validated while+ * typing and saved through Electron main. Saving a builtin writes its+ * override file and Restore default deletes it; user documents can also be+ * deleted. Any mode can be duplicated under a new id.*/export function ModesSettingsPage() {const { t } = useTranslation();@@ -50,7 +51,9 @@ export function ModesSettingsPage() {const [busy, setBusy] = useState(false);const readTicket = useRef(0);const { armed, setArmed } = useArmedDelete();- const editable = !!open && !open.builtin;+ const editable = !!open;+ // A builtin's file is its override: deleting it restores the shipped one.+ const removable = !!open && open.saved && (!open.builtin || !!open.filePath);const dirty = !!open && (!open.saved || draft !== open.savedSource);const { validation, pending, record } = useModeSourceValidation(open?.id ?? null, draft, editable);@@ -102,14 +105,17 @@ export function ModesSettingsPage() {};const save = async () => {- if (!open || open.builtin || busy) return;+ if (!open || busy) return;const source = draft;setBusy(true);try {const next = await modesApi.write({ id: open.id, source });if (next) setModeCatalog(next);+ const filePath = next?.modes.find((entry) => entry.id === open.id && !entry.reserved)?.filePath;setOpen((current) =>- current?.id === open.id ? { ...current, savedSource: source, saved: true } : current,+ current?.id === open.id+ ? { ...current, savedSource: source, saved: true, ...(filePath ? { filePath } : {}) }+ : current,);showToast(t("modes.settings.saved"), { variant: "success" });} catch (error) {@@ -122,7 +128,7 @@ export function ModesSettingsPage() {};const remove = async () => {- if (!open || open.builtin || busy) return;+ if (!open || !removable || busy) return;if (armed !== open.id) {setArmed(open.id);return;@@ -132,10 +138,20 @@ export function ModesSettingsPage() {try {const next = await modesApi.remove(open.id);if (next) setModeCatalog(next);- readTicket.current += 1;- setOpen(null);- setDraft("");- showToast(t("modes.settings.deleted"), { variant: "success" });+ const ticket = ++readTicket.current;+ if (open.builtin) {+ // Show the shipped definition the builtin is back to.+ const document = await modesApi.read(open.id);+ if (ticket === readTicket.current) {+ setOpen({ id: document.id, builtin: true, savedSource: document.source, saved: true });+ setDraft(document.source);+ }+ showToast(t("modes.settings.restored"), { variant: "success" });+ } else {+ setOpen(null);+ setDraft("");+ showToast(t("modes.settings.deleted"), { variant: "success" });+ }} catch (error) {showToast(modeErrorMessage(t, error), { variant: "error" });} finally {@@ -198,6 +214,7 @@ export function ModesSettingsPage() {</span><span className="modes-settings-row-badges"><Badge>{t(entry.source === "builtin" ? "modes.settings.builtin" : "modes.settings.user")}</Badge>+ {entry.customized ? <Badge>{t("modes.settings.customized")}</Badge> : null}{entry.staged ? <Badge>{t("modes.settings.staged")}</Badge> : null}{entry.reserved ? (<Badge tone="warning">{t("modes.settings.reserved")}</Badge>@@ -221,9 +238,11 @@ export function ModesSettingsPage() {<Button size="sm" variant="ghost" disabled={busy} onClick={() => setIdForm({ purpose: "duplicate", value: "" })}>{t("modes.settings.duplicate")}</Button>- {editable && open.saved ? (+ {removable ? (<Button size="sm" variant="ghost" disabled={busy} onClick={() => void remove()}>- {armed === open.id ? t("modes.settings.deleteConfirm") : t("modes.settings.delete")}+ {open.builtin+ ? t(armed === open.id ? "modes.settings.restoreConfirm" : "modes.settings.restore")+ : t(armed === open.id ? "modes.settings.deleteConfirm" : "modes.settings.delete")}</Button>) : null}{editable ? (@@ -233,11 +252,10 @@ export function ModesSettingsPage() {) : null}</div></div>- {open.builtin ? <p className="modes-settings-hint">{t("modes.settings.readOnly")}</p> : null}+ {open.builtin ? <p className="modes-settings-hint">{t("modes.settings.builtinHint", { id: open.id })}</p> : null}<TextareaclassName="modes-settings-source"value={draft}- readOnly={open.builtin}aria-label={t("modes.settings.source")}onChange={(event) => setDraft(event.target.value)}/>diff --git a/apps/desktop/src/features/modes/mode-run-model.ts b/apps/desktop/src/features/modes/mode-run-model.tsindex ef61d3841..3d41c3087 100644--- a/apps/desktop/src/features/modes/mode-run-model.ts+++ b/apps/desktop/src/features/modes/mode-run-model.ts@@ -143,7 +143,6 @@ const MODE_ERROR_KEYS: Record<string, string> = {MODE_RUN_ACTIVE: "modes.errors.runActive",MODE_NOT_FOUND: "modes.errors.notFound",MODE_DEFINITION_INVALID: "modes.errors.definitionInvalid",- MODE_ID_RESERVED: "modes.errors.idReserved",MODE_ID_INVALID: "modes.errors.idInvalid",MODE_REVISION_CONFLICT: "modes.errors.revisionConflict",MODE_NOT_AWAITING_APPROVAL: "modes.errors.notAwaitingApproval",diff --git a/apps/desktop/src/features/modes/modes-api.ts b/apps/desktop/src/features/modes/modes-api.tsindex d559f3ebb..020e940a6 100644--- a/apps/desktop/src/features/modes/modes-api.ts+++ b/apps/desktop/src/features/modes/modes-api.ts@@ -72,6 +72,7 @@ export function parseModeCatalog(value: unknown): ModeCatalog | null {staged: mode.staged === true,available: mode.available,...(mode.reserved === true ? { reserved: true } : {}),+ ...(mode.customized === true ? { customized: true } : {}),...(typeof mode.filePath === "string" ? { filePath: mode.filePath } : {}),});}diff --git a/apps/desktop/src/features/modes/modes-settings-model.ts b/apps/desktop/src/features/modes/modes-settings-model.tsindex 71d51e236..332d5694f 100644--- a/apps/desktop/src/features/modes/modes-settings-model.ts+++ b/apps/desktop/src/features/modes/modes-settings-model.ts@@ -31,10 +31,15 @@ export function modeEntryKey(entry: Pick<ModeCatalogEntry, "id" | "source">): stexport function modeEntryDiagnostic(catalog: ModeCatalog | null | undefined,- entry: Pick<ModeCatalogEntry, "id" | "source">,+ entry: Pick<ModeCatalogEntry, "id" | "source" | "customized" | "filePath">,): { errors: string[]; warnings: string[] } {- if (!catalog || entry.source !== "user") return { errors: [], warnings: [] };- const diagnostic = catalog.diagnostics.find((item) => item.modeId === entry.id);+ if (!catalog) return { errors: [], warnings: [] };+ // A builtin reports only problems of its override file; a reserved+ // document shares the builtin's id, so the file path tells them apart.+ if (entry.source !== "user" && !entry.customized) return { errors: [], warnings: [] };+ const diagnostic = catalog.diagnostics.find(+ (item) => item.modeId === entry.id && (!entry.filePath || !item.filePath || item.filePath === entry.filePath),+ );return { errors: diagnostic?.errors ?? [], warnings: diagnostic?.warnings ?? [] };}diff --git a/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx b/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsxindex f4ba9f312..1b0ececdd 100644--- a/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx+++ b/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx@@ -12,7 +12,6 @@ import { useTranslation } from "react-i18next";import { SegmentedControl, SettingsToggle } from "../../../components/ui";import { SettingsMenuSelect } from "../../../components/settings/SettingsMenuSelect";import { ComputerUseSettings } from "../computer-use/ComputerUseSettings";-import { GoalBudgetSettingsRow } from "../../modes/GoalBudgetSettingsRow";import { CommandShellRow, SettingsCard, SettingsRow } from "../primitives";export function AgentBehaviorSettings({@@ -42,7 +41,6 @@ export function AgentBehaviorSettings({role="group"/></SettingsRow>- <GoalBudgetSettingsRow settings={settings} saveSettings={saveSettings} /><SettingsRowtitle={t("settings.permissionMode")}description={t("settings.permissionModeDesc")}diff --git a/apps/desktop/src/styles/modes.css b/apps/desktop/src/styles/modes.cssindex 8af33d67e..880b541e6 100644--- a/apps/desktop/src/styles/modes.css+++ b/apps/desktop/src/styles/modes.css@@ -311,47 +311,3 @@gap: 2px;padding: 8px 12px;}--/* Settings → Agent behavior: Goal default budget. */-.settings-row:has(> .settings-row-control > .settings-goal-budget) {- flex-wrap: wrap;- gap: 8px 24px;-}--.settings-row:has(> .settings-row-control > .settings-goal-budget) > .settings-row-copy {- flex-basis: max-content;-}--.settings-row-control:has(> .settings-goal-budget) {- max-width: 100%;-}--.settings-goal-budget {- display: flex;- min-width: 0;- max-width: 100%;- flex-wrap: nowrap;- align-items: center;- gap: 8px;-}--.settings-goal-budget-field {- display: flex;- min-width: 0;- flex: 1 1 auto;- align-items: center;- gap: 6px;- color: var(--ds-text-muted);- font-size: var(--text-xs-plus);-}--.settings-goal-budget-label {- flex: 0 0 auto;- white-space: nowrap;-}--.settings-goal-budget .settings-goal-budget-input.field-input {- width: 96px;- min-width: 0;- flex: 0 1 96px;-}diff --git a/apps/desktop/test/mode-definitions-user-path.test.mjs b/apps/desktop/test/mode-definitions-user-path.test.mjsindex ab21f062c..6fa5efc60 100644--- a/apps/desktop/test/mode-definitions-user-path.test.mjs+++ b/apps/desktop/test/mode-definitions-user-path.test.mjs@@ -38,6 +38,8 @@ const GOAL_SOURCE = "---\nname: goal\nlabel: Goal\nbudget: { maxTurns: 20 }\n---const calls = [];const listeners = new Map();const userDocs = new Map();+const GOAL_OVERRIDE_PATH = "/home/user/.pi/modes/goal/mode.md";+let goalOverride;let run = {id: "run-1", sessionId: "session-1", modeId: "review", snapshotHash: "h", input: "go",stageId: "design", state: "waiting", waitReason: "approval", revision: 3,@@ -55,7 +57,10 @@ function catalog() {modes: [entry("agent", { source: "builtin", label: "Agent" }),entry("plan", { source: "builtin", label: "Plan" }),- entry("goal", { source: "builtin", label: "Goal", staged: true }),+ entry("goal", {+ source: "builtin", label: "Goal", staged: true,+ ...(goalOverride === undefined ? {} : { customized: true, filePath: GOAL_OVERRIDE_PATH }),+ }),entry("review", { label: "Code review", description: "Review the current diff", staged: true }),entry("broken", { label: "Broken mode", available: false }),entry("plan", { label: "Shadow plan", available: false, reserved: true }),@@ -87,17 +92,23 @@ window.piDesktop = {case IPC.invoke.modesCatalog:return ok(catalog());case IPC.invoke.modesRead:- if (input === "goal") return ok({ id: "goal", source: GOAL_SOURCE, builtin: true });+ if (input === "goal") {+ return ok(goalOverride === undefined+ ? { id: "goal", source: GOAL_SOURCE, builtin: true }+ : { id: "goal", source: goalOverride, filePath: GOAL_OVERRIDE_PATH, builtin: true });+ }return ok({ id: input, source: userDocs.get(input), filePath: "/home/user/.pi/modes/" + input + "/mode.md", builtin: false });case IPC.invoke.modesValidate:return ok(/^bogus:/m.test(input.source)? { ok: false, errors: ["bogus: unknown key"], warnings: [] }: { ok: true, errors: [], warnings: [] });case IPC.invoke.modesWrite:- userDocs.set(input.id, input.source);+ if (input.id === "goal") goalOverride = input.source;+ else userDocs.set(input.id, input.source);return ok(catalog());case IPC.invoke.modesDelete:- userDocs.delete(input);+ if (input === "goal") goalOverride = undefined;+ else userDocs.delete(input);return ok(catalog());case IPC.invoke.modesRunGet:return ok({ run });@@ -165,8 +176,11 @@ async function waitFor(predicate, message) {throw new Error(message + " — body: " + document.body.innerText.slice(0, 600));}const text = () => document.body.innerText;+// Icon-only run controls carry their name in aria-label.function button(label) {- return [...document.querySelectorAll("button")].find((candidate) => candidate.textContent.trim() === label);+ return [...document.querySelectorAll("button")].find(+ (candidate) => candidate.textContent.trim() === label || candidate.getAttribute("aria-label") === label,+ );}function typeInto(element, value) {const proto = element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;@@ -251,7 +265,8 @@ window.modesProbe = async () => {result.resolveRequests = sent(IPC.invoke.modesRunResolve);result.controlRequests = sent(IPC.invoke.modesRunControl);- // 3) Settings → Modes: builtin read-only, duplicate, validate, save, delete.+ // 3) Settings → Modes: edit and restore a builtin, then duplicate,+ // validate, save and delete a user mode.flushSync(() => window.__view("settings"));await waitFor(() => document.querySelector('[data-testid="modes-directory"]'), "settings list missing");result.directory = document.querySelector('[data-testid="modes-directory"]').textContent;@@ -259,7 +274,19 @@ window.modesProbe = async () => {flushSync(() => document.querySelector('.modes-settings-row[data-mode-id="goal"]').click());const source = () => document.querySelector(".modes-settings-source");await waitFor(() => source()?.value === GOAL_SOURCE, "builtin source not opened");- result.builtinReadOnly = source().readOnly && !button("Save") && !button("Delete");+ result.builtinEditable = !source().readOnly && !!button("Save") && !button("Restore default") && !button("Delete")+ && text().includes("~/.pi/modes/goal/mode.md");+ typeInto(source(), GOAL_SOURCE.replace("maxTurns: 20", "maxTurns: 50"));+ await waitFor(() => text().includes("No problems found") && !button("Save").disabled, "builtin edit not confirmed");+ flushSync(() => button("Save").click());+ await waitFor(() => button("Restore default"), "restore default not offered after saving a builtin");+ result.customizedBadge = document.querySelector('.modes-settings-row[data-mode-id="goal"]').textContent.includes("Customized");+ result.overrideWrites = sent(IPC.invoke.modesWrite);+ flushSync(() => button("Restore default").click());+ await waitFor(() => button("Click again to restore"), "restore did not arm");+ flushSync(() => button("Click again to restore").click());+ await waitFor(() => source()?.value === GOAL_SOURCE && !button("Restore default"), "shipped source not restored");+ result.overrideDeletes = sent(IPC.invoke.modesDelete);flushSync(() => button("Duplicate").click());const idInput = await waitFor(() => document.querySelector(".modes-settings-new input"), "id prompt missing");typeInto(idInput, "plan");@@ -282,7 +309,7 @@ window.modesProbe = async () => {flushSync(() => button("Click again to delete").click());await waitFor(() => !document.querySelector('.modes-settings-row[data-mode-id="my-goal"]'), "deleted mode still listed");result.deletes = sent(IPC.invoke.modesDelete);- result.validations = sent(IPC.invoke.modesValidate).every((input) => input.id === "my-goal");+ result.validations = sent(IPC.invoke.modesValidate).every((input) => input.id === "my-goal" || input.id === "goal");stopSync();return result;@@ -416,19 +443,25 @@ app.whenReady().then(async () => {// Settings → Modes.assert.equal(result.directory, "/home/user/.pi/modes");assert.deepEqual(result.rows, ["agent", "plan", "goal", "broken", "plan", "review"]);- assert.equal(result.builtinReadOnly, true);+ assert.equal(result.builtinEditable, true);+ assert.equal(result.customizedBadge, true);+ assert.deepEqual(result.overrideWrites, [+ { id: "goal", source: "---\nname: goal\nlabel: Goal\nbudget: { maxTurns: 50 }\n---\nWork until the objective is verified.\n" },+ ]);+ assert.deepEqual(result.overrideDeletes, ["goal"]);assert.equal(result.duplicateSource,"---\nname: my-goal\nlabel: Goal\nbudget: { maxTurns: 20 }\n---\nWork until the objective is verified.\n",);assert.equal(result.saveBlockedByErrors, true);assert.deepEqual(result.writes, [+ ...result.overrideWrites,{id: "my-goal",source: "---\nname: my-goal\nlabel: My goal\nbudget: { maxTurns: 20 }\n---\nWork until the objective is verified.\n",},]);- assert.deepEqual(result.deletes, ["my-goal"]);+ assert.deepEqual(result.deletes, ["goal", "my-goal"]);assert.equal(result.validations, true);} finally {await rm(temp, { recursive: true, force: true });diff --git a/apps/desktop/test/mode-run-elapsed.test.mjs b/apps/desktop/test/mode-run-elapsed.test.mjsindex 2effc3b19..ce04587f7 100644--- a/apps/desktop/test/mode-run-elapsed.test.mjs+++ b/apps/desktop/test/mode-run-elapsed.test.mjs@@ -19,7 +19,6 @@ await build({import { createInstance } from "i18next";import { I18nextProvider } from "react-i18next";import { ModeRunStatusPanel } from "./src/features/modes/ModeRunStatusBar";- import { GoalBudgetSettingsRow } from "./src/features/modes/GoalBudgetSettingsRow";export { modeRunElapsedMs, formatModeRunElapsed } from "./src/features/modes/mode-run-elapsed";export { default as EN_TRANSLATION } from "../../packages/i18n/src/locales/en/index";export { default as ZH_TRANSLATION } from "../../packages/i18n/src/locales/zh-CN/index";@@ -29,12 +28,6 @@ await build({return renderToStaticMarkup(createElement(I18nextProvider, { i18n },createElement(ModeRunStatusPanel, { run })));}- export async function renderBudget(translation) {- const i18n = createInstance();- await i18n.init({ lng: "zh-CN", resources: { "zh-CN": { translation } } });- return renderToStaticMarkup(createElement(I18nextProvider, { i18n },- createElement(GoalBudgetSettingsRow, { settings: {}, saveSettings: async () => {} })));- }`,resolveDir: join(root, "apps/desktop"),loader: "tsx",@@ -50,11 +43,11 @@ await build({logLevel: "silent",});const require = createRequire(import.meta.url);-const { modeRunElapsedMs, formatModeRunElapsed, renderPanel, renderBudget, EN_TRANSLATION, ZH_TRANSLATION } = require(entry);+const { modeRunElapsedMs, formatModeRunElapsed, renderPanel, EN_TRANSLATION, ZH_TRANSLATION } = require(entry);const EN_UNITS = { day: "d", hour: "h", minute: "m", second: "s" };const ZH_UNITS = { day: "天", hour: "小时", minute: "分", second: "秒" };const translation = (units) => ({- settings: { modeGoal: "Goal", goalBudgetTurns: "轮数", goalBudgetTokens: "令牌" },+ settings: { modeGoal: "Goal" },modes: { run: {rounds: "Rounds {{completed}}/{{max}}",elapsed: EN_TRANSLATION.modes.run.elapsed,@@ -165,25 +158,9 @@ test("a reported blocker renders the existing Resume icon without Pause or approassert.ok(!buttons.some(([, attrs]) => attrs.includes(`aria-label="${EN_TRANSLATION.modes.run.pause}"`)));});-test("Goal budget keeps two labeled shared inputs in the same control", async () => {- const html = await renderBudget(translation(ZH_UNITS));- assert.match(html, /class="settings-goal-budget"/);- assert.equal((html.match(/class="settings-goal-budget-field"/g) ?? []).length, 2);- assert.equal((html.match(/class="field-input settings-goal-budget-input"/g) ?? []).length, 2);- assert.match(html, /class="settings-goal-budget-label">轮数<\/span><input/);- assert.match(html, /class="settings-goal-budget-label">令牌<\/span><input/);-});--test("Goal layout rules beat generic input widths and constrain wrapping metadata", async () => {+test("Goal layout rules constrain wrapping metadata", async () => {const css = await readFile(join(root, "apps/desktop/src/styles/modes.css"), "utf8");const rules = new Map([...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map((match) => [match[1].trim(), match[2]]));- const input = rules.get(".settings-goal-budget .settings-goal-budget-input.field-input");- assert.ok(input, "Goal input specificity must exceed .settings-row-control .field-input");- assert.match(input, /width:\s*96px/);- assert.match(input, /min-width:\s*0/);- assert.match(rules.get(".settings-goal-budget"), /flex-wrap:\s*nowrap/);- assert.match(rules.get(".settings-goal-budget-label"), /white-space:\s*nowrap/);- assert.match(rules.get(".settings-row-control:has(> .settings-goal-budget)"), /max-width:\s*100%/);assert.match(rules.get(".mode-run-actions"), /max-width:\s*100%/);assert.match(rules.get(".mode-run-elapsed"), /overflow-wrap:\s*anywhere/);});diff --git a/apps/desktop/test/mode-runs-main.test.mjs b/apps/desktop/test/mode-runs-main.test.mjsindex 7e3d517ba..e1d4742ec 100644--- a/apps/desktop/test/mode-runs-main.test.mjs+++ b/apps/desktop/test/mode-runs-main.test.mjs@@ -109,12 +109,19 @@ test("simple custom modes resolve their definition for prompt dispatch", async (await assert.rejects(coordinator.definitionForPrompt("missing"), { errorCode: "MODE_NOT_FOUND" });});-test("Agent and Plan dispatch use builtin runtime instructions without a snapshot", async () => {- const coordinator = createModeRunCoordinator({- catalog: { definition: async () => assert.fail("plain modes need no catalog snapshot") },+test("Agent and Plan dispatch use builtin runtime instructions unless the user overrides them", async () => {+ const shipped = createModeRunCoordinator({+ catalog: { definition: async (id) => ({ ...staged, id, stages: [], source: "builtin" }) },+ });+ assert.equal(await shipped.definitionForPrompt("agent"), undefined);+ assert.equal(await shipped.definitionForPrompt("plan"), undefined);++ const override = { ...staged, id: "plan", stages: [], permission: "contract", prompt: "Plan my way.", source: "user" };+ const customized = createModeRunCoordinator({+ catalog: { definition: async (id) => (id === "plan" ? override : undefined) },});- assert.equal(await coordinator.definitionForPrompt("agent"), undefined);- assert.equal(await coordinator.definitionForPrompt("plan"), undefined);+ assert.equal(await customized.definitionForPrompt("plan"), override);+ assert.equal(await customized.definitionForPrompt("agent"), undefined);});test("a user turn in a simple mode claims nothing", async () => {@@ -287,7 +294,8 @@ test("the catalog reads, validates, writes and deletes user modes in its own dirassert.equal((await catalog.validate("review", source)).ok, true);const invalid = await catalog.validate("review", "---\nname: review\ntools: [Read]\n---\n");assert.equal(invalid.ok, false);- await assert.rejects(catalog.write("plan", source), { errorCode: "MODE_ID_RESERVED" });+ // A builtin's folder only accepts that builtin, in its own shape.+ await assert.rejects(catalog.write("plan", source), { errorCode: "MODE_DEFINITION_INVALID" });await assert.rejects(catalog.write("review", "---\nname: review\npermission: auto\n---\n"), { errorCode: "MODE_DEFINITION_INVALID" });const written = await catalog.write("review", source);@@ -299,13 +307,34 @@ test("the catalog reads, validates, writes and deletes user modes in its own dirassert.equal(await catalog.snapshotFor("plan"), undefined);await assert.rejects(catalog.snapshotFor("missing"), { errorCode: "MODE_NOT_FOUND" });- // A user document that claims a builtin id is reported, never loaded.+ // Editing a builtin writes its override; deleting it restores the shipped one.+ const shippedGoal = (await catalog.read("goal")).source;+ const goal = shippedGoal.replace("maxTurns: 20", "maxTurns: 50");+ assert.equal((await catalog.validate("goal", goal)).ok, true);+ const customized = await catalog.write("goal", goal);+ assert.equal(await readFile(join(dir, "goal", "mode.md"), "utf8"), goal);+ assert.ok(customized.modes.some((mode) => mode.id === "goal" && mode.source === "builtin" && mode.customized));+ assert.deepEqual(await catalog.read("goal"), { id: "goal", source: goal, filePath: join(dir, "goal", "mode.md"), builtin: true });+ assert.equal((await catalog.snapshotFor("goal")).budget.maxTurns, 50);+ await catalog.remove("goal");+ assert.deepEqual(await catalog.read("goal"), { id: "goal", source: shippedGoal, builtin: true });+ assert.equal((await catalog.definition("goal")).source, "builtin");+ await assert.rejects(catalog.remove("goal"), { errorCode: "MODE_NOT_FOUND" });++ // A broken override is reported and the shipped builtin keeps running.await mkdir(join(dir, "goal"), { recursive: true });await writeFile(join(dir, "goal", "mode.md"), "---\nname: goal\n---\nmine\n");const refreshed = await catalog.refresh();- assert.ok(refreshed.modes.some((mode) => mode.id === "goal" && mode.reserved));+ assert.ok(refreshed.modes.some((mode) => mode.id === "goal" && mode.customized && mode.available));+ assert.ok(refreshed.diagnostics.some((item) => item.modeId === "goal" && item.errors.length > 0));assert.equal((await catalog.definition("goal")).source, "builtin");+ // Outside its own folder a builtin id is still reserved.+ await mkdir(join(dir, "shadow"), { recursive: true });+ await writeFile(join(dir, "shadow", "mode.md"), "---\nname: plan\n---\nmine\n");+ assert.ok((await catalog.refresh()).modes.some((mode) => mode.id === "plan" && mode.reserved));+ assert.equal(await catalog.snapshotFor("plan"), undefined);+const removed = await catalog.remove("review");assert.ok(!removed.modes.some((mode) => mode.id === "review"));assert.ok(changes.length >= 3);diff --git a/crates/host-core/src/mode_runs.rs b/crates/host-core/src/mode_runs.rsindex b4a5d72cc..d6b4fdc16 100644--- a/crates/host-core/src/mode_runs.rs+++ b/crates/host-core/src/mode_runs.rs@@ -21,7 +21,6 @@ mod repository;mod return_mode;mod snapshot;-pub use budget::validate_goal_budget_setting;pub use engine::{claim_turn, configure_session_mode, control, open_run, prepare_session_mode, recover,reset_goal_input, resolve, settle_turn, start, start_goal, store_session_snapshot, update,diff --git a/crates/host-core/src/mode_runs/budget.rs b/crates/host-core/src/mode_runs/budget.rsindex 43cd7ecb8..74856784b 100644--- a/crates/host-core/src/mode_runs/budget.rs+++ b/crates/host-core/src/mode_runs/budget.rs@@ -1,18 +1,11 @@-//! Run budgets the user sets outside a mode definition: the Goal default in-//! the app settings (`goalBudget`) and a per-run change through-//! `modes.update`. Both use the same range as a definition's `budget`.+//! A per-run budget change through `modes.update`. It uses the same range as+//! a definition's `budget`; a new run always starts with its definition's.use serde::Deserialize;-use serde_json::Value;use super::model::MAX_SAFE_INTEGER;use super::snapshot::{MAX_TURNS, MIN_TOKENS};-/// The builtin mode whose new runs take the `goalBudget` setting.-pub const GOAL_MODE_ID: &str = "goal";-/// App settings field (`AppSettings.goalBudget`).-pub const GOAL_BUDGET_SETTING: &str = "goalBudget";-/// `{ maxTurns, maxTokens }`; `null` is unlimited. Both fields are required/// so a client never clears a limit by omitting it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]@@ -45,67 +38,3 @@ impl RunBudget {Ok(())}}--fn parse(value: &Value) -> Result<RunBudget, String> {- let budget: RunBudget =- serde_json::from_value(value.clone()).map_err(|error| error.to_string())?;- budget.validate()?;- Ok(budget)-}--/// `settings.set` check for `goalBudget`: absent, `null`, or a valid budget.-pub fn validate_goal_budget_setting(settings: &Value) -> Result<(), String> {- match settings.get(GOAL_BUDGET_SETTING) {- None | Some(Value::Null) => Ok(()),- Some(value) => parse(value)- .map(|_| ())- .map_err(|error| format!("{GOAL_BUDGET_SETTING}: {error}")),- }-}--/// The Goal default stored in the app settings, when it is set and valid.-/// An invalid stored value is ignored: the definition budget applies.-pub fn goal_budget_from_settings(settings: Option<&Value>) -> Option<RunBudget> {- let value = settings?.get(GOAL_BUDGET_SETTING)?;- if value.is_null() {- return None;- }- parse(value).ok()-}--#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn settings_budget_accepts_limits_and_unlimited() {- let settings = json!({ "goalBudget": { "maxTurns": 5, "maxTokens": null } });- assert!(validate_goal_budget_setting(&settings).is_ok());- assert_eq!(- goal_budget_from_settings(Some(&settings)),- Some(RunBudget {- max_turns: Some(5),- max_tokens: None- })- );- assert!(validate_goal_budget_setting(&json!({})).is_ok());- assert!(validate_goal_budget_setting(&json!({ "goalBudget": null })).is_ok());- }-- #[test]- fn settings_budget_rejects_out_of_range_and_partial_values() {- for value in [- json!({ "maxTurns": 0, "maxTokens": null }),- json!({ "maxTurns": 10_001, "maxTokens": null }),- json!({ "maxTurns": null, "maxTokens": 999 }),- json!({ "maxTurns": 3 }),- json!({ "maxTurns": "3", "maxTokens": null }),- json!({ "maxTurns": 3, "maxTokens": null, "extra": 1 }),- ] {- let settings = json!({ "goalBudget": value });- assert!(validate_goal_budget_setting(&settings).is_err(), "{value}");- assert_eq!(goal_budget_from_settings(Some(&settings)), None);- }- }-}diff --git a/crates/host-core/src/mode_runs/edit_tests.rs b/crates/host-core/src/mode_runs/edit_tests.rsindex 43f5d99d0..9111fb3c0 100644--- a/crates/host-core/src/mode_runs/edit_tests.rs+++ b/crates/host-core/src/mode_runs/edit_tests.rs@@ -164,8 +164,10 @@ fn per_run_budget_change_limits_and_unblocks_host_turns() {}#[test]-fn goal_runs_take_the_settings_budget_and_other_modes_do_not() {+fn goal_runs_take_the_definition_budget_and_ignore_a_legacy_setting() {let fx = fixture();+ // A `goalBudget` left in the app settings by an older release has no+ // effect: the budget comes from the mode definition only.fx.db.set_setting("app",@@ -174,29 +176,6 @@ fn goal_runs_take_the_settings_budget_and_other_modes_do_not() {.unwrap();let sid = goal_session(&fx);let run = start_run(&fx, &sid, "t1").run;- assert_eq!((run.max_turns, run.max_tokens), (Some(3), Some(50_000)));-- let other = session(&fx, "agent");- let def = super::tests::definition(- "grind",- "agent",- json!([{ "id": "work", "permission": "agent", "loop": true, "exit": [] }]),- );- configure(&fx.db, &other, "grind", Some(&def)).unwrap();- let run = start_run(&fx, &other, "t2").run;- assert_eq!(- (run.max_turns, run.max_tokens),- (Some(20), None),- "a user mode keeps its own budget"- );-- // An invalid stored value falls back to the definition budget.- fx.db- .set_setting("app", &json!({ "goalBudget": { "maxTurns": -1 } }))- .unwrap();- let third = session(&fx, "agent");- configure(&fx.db, &third, "goal", Some(&goal_snapshot())).unwrap();- let run = start_run(&fx, &third, "t3").run;assert_eq!((run.max_turns, run.max_tokens), (Some(20), None));}diff --git a/crates/host-core/src/mode_runs/engine.rs b/crates/host-core/src/mode_runs/engine.rsindex 2fef3c4dc..410543a33 100644--- a/crates/host-core/src/mode_runs/engine.rs+++ b/crates/host-core/src/mode_runs/engine.rs@@ -12,7 +12,7 @@ use rusqlite::Connection;use serde_json::Value;use super::artifacts;-use super::budget::{self, RunBudget, GOAL_MODE_ID};+use super::budget::RunBudget;use super::model::{ClaimParams, ClaimResult, ContinueResult, ControlAction, ControlParams, ModeRun, Origin,ResolveAction, ResolveParams, RunState, SettleParams, StartParams, TurnOutcome, UpdateParams,@@ -23,6 +23,9 @@ use super::snapshot::{self, ModeDefinition, Snapshot};use super::{mode_error, mode_error_detail};use crate::db::{now_ms, Database};+/// The builtin Goal mode id.+const GOAL_MODE_ID: &str = "goal";+/// Where a passed stage leads.pub(super) enum Transition {Advanced(String),@@ -145,17 +148,12 @@ fn start_with_snapshot(return Err(mode_error("MODE_RUN_ACTIVE"));}let definition = &snapshot.definition;- // The Goal default from settings replaces the builtin's budget for new- // runs; a running run keeps the budget it started with.- let budget = if definition.id == GOAL_MODE_ID {- budget::goal_budget_from_settings(db.get_setting("app")?.as_ref())- } else {- None- }- .unwrap_or(RunBudget {+ // A new run starts with its definition's budget; `modes.update` changes+ // an open run's.+ let budget = RunBudget {max_turns: definition.budget.max_turns,max_tokens: definition.budget.max_tokens,- });+ };let first = definition.stages.first()diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 2cf49bf47..b72249e8c 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -1182,9 +1182,6 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {}}}- if let Err(message) = crate::mode_runs::validate_goal_budget_setting(value) {- return Err(rpc_err(1002, message, "INVALID_PARAMS"));- }if let Some(infinite_retry) = object.get("infiniteProviderRetry") {if !infinite_retry.is_boolean() {return Err(rpc_err(@@ -8270,31 +8267,6 @@ mod tests {.unwrap();assert_eq!(retry_settings["infiniteProviderRetry"], true);- handle_request(- state.clone(),- "settings.set",- json!({ "goalBudget": { "maxTurns": 40, "maxTokens": null } }),- tx.clone(),- )- .await- .unwrap();- let goal_settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())- .await- .unwrap();- assert_eq!(- goal_settings["goalBudget"],- json!({ "maxTurns": 40, "maxTokens": null })- );- let invalid_goal = handle_request(- state.clone(),- "settings.set",- json!({ "goalBudget": { "maxTurns": 0, "maxTokens": null } }),- tx.clone(),- )- .await- .unwrap_err();- assert_eq!(invalid_goal.data.unwrap()["errorCode"], "INVALID_PARAMS");-handle_request(state.clone(),"settings.set",diff --git a/docs/adr/mode-definitions.md b/docs/adr/mode-definitions.mdindex c5011e06f..6b17d081d 100644--- a/docs/adr/mode-definitions.md+++ b/docs/adr/mode-definitions.md@@ -24,9 +24,14 @@ global-only discovery (D202).`~/.pi/modes/<name>/mode.md` holds YAML frontmatter and a Markdown body that is theshared system prompt, with optional artifact templates in `templates/`; builtins-`agent`, `plan` and `goal` use the same format, and their reserved ids make a user-document using one reported in settings and not loaded. Discovery is global only, and-settings re-read the directory on each catalog load. A simple mode is a prompt and a+`agent`, `plan` and `goal` use the same format. A document in a builtin's own folder+(`~/.pi/modes/goal/mode.md`) overrides that builtin: Settings → Modes edits it in+place and Restore default deletes the file. An override must keep the shape the+builtin's id-keyed behavior relies on (Agent and Plan stay simple at `agent` and+`contract`; Goal stays staged and returns to `agent`); an invalid one is reported and+the shipped definition stays in effect. Any other document that claims a builtin id+is reported and not loaded. Discovery is global only, and settings re-read the+directory on each catalog load. A simple mode is a prompt and apermission level, without stages or a run:```markdown@@ -169,15 +174,18 @@ stage, gate index, action, result, evidence and timestamp, and existing### 9. Builtins and compatibility-- `agent`: a simple mode.+- `agent`: a simple mode. Agent and Plan prompts come from the runtime builtins unless+ an override is in effect, in which case its definition is sent with the turn; the+ Host never needs a snapshot for either.- `plan`: a simple `contract` mode keeping the ADR 0053 proposal pipeline unchanged(EnterPlanMode, SubmitPlan, approval, queued execution) with the same behavior, toolnames and stored approvals; a staged Plan would rewrite a released approval flow.- `goal`: stage `work` (`agent`, `loop`, artifact `goal` from a template seeded with`{{run.input}}`, `inject` on compaction, gate `require: artifact:goal` with headingsObjective, Acceptance criteria and Evidence), completion staying a model self-report,- with a new run taking its budget from the valid `goalBudget` setting or else the- definition. The legacy `EnterGoalMode` / `SubmitGoal` negotiation is no longer offered+ with a new run taking the definition budget. The default budget is edited in the+ Goal override file; there is no separate settings value, and an open run's budget+ is edited through `modes.update`. The legacy `EnterGoalMode` / `SubmitGoal` negotiation is no longer offeredand the Host rejects new proposals with `PLAN_GOAL_ACTIVATION_DISABLED`, while oldapproval rows stay readable; accepted Goal input returns the composer preference toAgent without changing the run, its snapshot or its claim.diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex 39c578833..ff03f312e 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -431,14 +431,6 @@ Card order is **Session defaults → Execution → Computer use**.anchored-menu surface rather than a platform-drawn `<select>` popup, so everySettings picker opens the same way. The closed trigger sizes to the currentlabel, capped by the settings control column.-- The **Goal budget** row sits under the default mode in Session defaults: two- horizontally aligned numeric fields (turns, tokens), each with a non-wrapping- label and flexible input width, persisted as optional- `AppSettings.goalBudget { maxTurns, maxTokens }`. A field saves on blur or- Enter; empty is unlimited and an out-of-range value (turns 1–10000, tokens- at least 1000) reverts to the saved one. Absent keeps the builtin Goal- budget (20 turns, unlimited tokens). Only new Goal runs use it; an open run- is edited from its status bar.- **Execution** card: the infinite provider retry switch and the app-wide**Scheduled tasks** switch. The retry switch is off by default and explainsthat network/transient provider failures keep retrying until success; Stopdiff --git a/docs/spec/06-delivery/e2e/plans-goals-automation.md b/docs/spec/06-delivery/e2e/plans-goals-automation.mdindex 2079b1f5e..b10b4d8de 100644--- a/docs/spec/06-delivery/e2e/plans-goals-automation.md+++ b/docs/spec/06-delivery/e2e/plans-goals-automation.md@@ -663,10 +663,10 @@ compaction injection.before queue release, and a distinct new run starts with the second input.Stop it, and verify no further continuation. Restored transcript assistantrows retain distinct turn ids and contain only the two actual user inputs.-- `scripts/e2e-goal-layout.mjs` renders production status/budget controls with+- `scripts/e2e-goal-layout.mjs` renders the production run status bar withthe built stylesheet in isolated Electron. Check English/Chinese layouts at320, 480, 720 and 1120 pixels, long objectives/day durations, metadata order,- nonoverlap and horizontal budget inputs. Duration uses `d`, `h`, `m`, `s`+ and nonoverlap. Duration uses `d`, `h`, `m`, `s`with exactly one ASCII space after each number, including `0 s`, in bothlanguages. Resume/Pause/Edit/Remove are icon-only with localized accessiblenames; native clicks still resume/pause, open/cancel editing and arm/cancel@@ -690,7 +690,7 @@ the key; only the machine key and that one secret file are copied). It calls apaid model API and needs the account owner's authorization. Real pieces: anisolated Host, the production runtime loop and Electron main's run coordinator.-1. With `goalBudget { maxTurns: 6 }` set, a Goal run starts with 6 turns, does+1. A Goal run starts with the builtin definition budget (20 turns), doesthe work, calls `CompleteStage` with the three-heading artifact, finishes,and the session returns to Agent.2. During the first turn, Edit the objective and budget, then Pause: the turndiff --git a/packages/agent-runtime/src/mode-definitions.test.ts b/packages/agent-runtime/src/mode-definitions.test.tsindex f2c92b43d..9a684a882 100644--- a/packages/agent-runtime/src/mode-definitions.test.ts+++ b/packages/agent-runtime/src/mode-definitions.test.ts@@ -144,10 +144,37 @@ describe("loadModeDefinitions", () => {]);});- it("never lets a user document replace a builtin", () => {+ it("lets a document in a builtin's folder override it, keeping its shape", () => {+ const goal = builtinModeSource("goal")!.replace("maxTurns: 20", "maxTurns: 50");+ const result = loadModeDefinitions({+ userDocuments: [+ userDocument("goal", goal),+ userDocument("plan", "---\nname: plan\nlabel: My plan\npermission: contract\n---\nPlan my way.\n"),+ ],+ });++ expect(result.definitions.map((definition) => [definition.id, definition.source])).toEqual([+ ["agent", "builtin"],+ ["plan", "user"],+ ["goal", "user"],+ ]);+ expect(result.definitions[1].prompt).toBe("Plan my way.");+ expect(result.definitions[2].budget).toEqual({ maxTurns: 50, maxTokens: null });+ expect(result.catalog.slice(0, 3)).toEqual([+ expect.not.objectContaining({ customized: true }),+ expect.objectContaining({ id: "plan", source: "builtin", customized: true, available: true, label: "My plan", filePath: "/home/user/.pi/modes/plan/mode.md" }),+ expect.objectContaining({ id: "goal", source: "builtin", customized: true, available: true, staged: true, filePath: "/home/user/.pi/modes/goal/mode.md" }),+ ]);+ expect(result.catalog).toHaveLength(3);+ expect(result.diagnostics).toEqual([]);+ });++ it("keeps the shipped builtin when its override is invalid or changes its shape", () => {const result = loadModeDefinitions({userDocuments: [userDocument("agent", "---\nlabel: Mine\npermission: contract\n---\nMine\n"),+ userDocument("goal", "---\nname: goal\n---\nno stages\n"),+ userDocument("plan", "---\nname: plan\npermission: nope\n---\n"),userDocument("other", "---\nname: plan\npermission: agent\n---\nMine\n"),],});@@ -158,13 +185,24 @@ describe("loadModeDefinitions", () => {["goal", "builtin"],]);expect(result.definitions[0].permission).toBe("agent");- expect(result.definitions[1].permission).toBe("contract");- const reserved = result.catalog.filter((entry) => entry.reserved);- expect(reserved).toEqual([- expect.objectContaining({ id: "agent", reserved: true, available: false, source: "user" }),- expect.objectContaining({ id: "plan", reserved: true, available: false, source: "user" }),+ expect(result.definitions[2].budget.maxTurns).toBe(20);+ for (const id of ["agent", "plan", "goal"]) {+ expect(result.catalog.find((entry) => entry.id === id && entry.source === "builtin")).toMatchObject({+ available: true,+ customized: true,+ filePath: `/home/user/.pi/modes/${id}/mode.md`,+ });+ }+ const errors = (id: string, filePath: string) =>+ result.diagnostics.find((item) => item.modeId === id && item.filePath === filePath)?.errors ?? [];+ expect(errors("agent", "/home/user/.pi/modes/agent/mode.md")).toEqual([expect.stringContaining('must keep "agent"')]);+ expect(errors("goal", "/home/user/.pi/modes/goal/mode.md")).toEqual([expect.stringContaining("at least one stage")]);+ expect(errors("plan", "/home/user/.pi/modes/plan/mode.md").length).toBeGreaterThan(0);+ // Outside the builtin's own folder, a builtin id is still reserved.+ expect(result.catalog.filter((entry) => entry.reserved)).toEqual([+ expect.objectContaining({ id: "plan", reserved: true, available: false, source: "user", filePath: "/home/user/.pi/modes/other/mode.md" }),]);- expect(result.diagnostics.map((diagnostic) => diagnostic.modeId)).toEqual(["agent", "plan"]);+ expect(errors("plan", "/home/user/.pi/modes/other/mode.md")).toEqual([expect.stringContaining("is a builtin mode")]);});it("refuses a duplicate id and caps the number of user modes", () => {diff --git a/packages/agent-runtime/src/mode-definitions.ts b/packages/agent-runtime/src/mode-definitions.tsindex 6ba518b0f..6ddd7e0bf 100644--- a/packages/agent-runtime/src/mode-definitions.ts+++ b/packages/agent-runtime/src/mode-definitions.ts@@ -4,9 +4,11 @@* Two sources, mirroring `subagent-definitions.ts`: the modes PI-Desktop* ships, inline as Markdown documents, and the user's global* `~/.pi/modes/<dir>/mode.md` documents, which Electron main reads and hands- * in. Workspaces never provide modes. Builtin ids are reserved: a user- * document that claims one is reported in the catalog and never loaded, so a- * copy has to live under a new name.+ * in. Workspaces never provide modes. A document in a builtin's own folder+ * (`~/.pi/modes/goal/mode.md`) overrides that builtin when it is valid and+ * keeps the structure the builtin's Host semantics rely on; an invalid one+ * is reported and the shipped definition stays in effect. Any other document+ * that claims a builtin id is reported and never loaded.** Both sources go through the same strict reader: YAML frontmatter is parsed* with unique keys and the core schema, and anchors, aliases, explicit tags@@ -105,7 +107,7 @@ function isBuiltinModeId(id: string): id is (typeof BUILTIN_MODE_IDS)[number] {return (BUILTIN_MODE_IDS as readonly string[]).includes(id);}-/** Markdown source of a builtin mode, for read-only display; undefined otherwise. */+/** Shipped Markdown source of a builtin mode; undefined otherwise. */export function builtinModeSource(id: string): string | undefined {return isBuiltinModeId(id) ? BUILTIN_MODE_SOURCES[id] : undefined;}@@ -196,6 +198,26 @@ function parseModeDocument(return { ok: true, definition: parsed.definition, warnings: [...warnings, ...parsed.warnings] };}+/**+ * What an override must keep from its builtin. Agent and Plan stay simple+ * modes at their permission level, and Goal stays a staged mode that returns+ * to Agent: the Host, Electron main and the renderer key those behaviors on+ * the id, so a different shape could not run as the user expects.+ */+export function builtinOverrideProblems(id: string, definition: ModeDefinition): string[] {+ const errors: string[] = [];+ if (definition.id !== id) errors.push(`name: a document in the "${id}" folder must keep name: ${id}`);+ if (id === "goal") {+ if (definition.stages.length === 0) errors.push(`stages: the builtin "goal" mode must keep at least one stage`);+ if (definition.returnTo !== "agent") errors.push(`returnTo: the builtin "goal" mode must return to "agent"`);+ return errors;+ }+ const permission = id === "agent" ? "agent" : "contract";+ if (definition.stages.length > 0) errors.push(`stages: the builtin "${id}" mode cannot declare stages`);+ if (definition.permission !== permission) errors.push(`permission: the builtin "${id}" mode must keep "${permission}"`);+ return errors;+}+function catalogEntry(definition: ModeDefinition, filePath?: string): ModeCatalogEntry {return {id: definition.id,@@ -212,22 +234,29 @@ function unavailableEntry(id: string, filePath: string, extra: Partial<ModeCatalreturn { id, label: id, description: "", source: "user", staged: false, available: false, filePath, ...extra };}+type BuiltinSlot = {+ definition?: ModeDefinition;+ entry?: ModeCatalogEntry;+};+/*** Builtins plus every valid user mode. Load failures degrade to catalog* entries marked unavailable and diagnostics: one malformed document must- * not cost the user their other modes.+ * not cost the user their other modes, and a broken override never costs+ * the user the builtin itself.*/export function loadModeDefinitions(options: { userDocuments: readonly UserModeDocument[] }): LoadedModeDefinitions {- const definitions: ModeDefinition[] = [];- const catalog: ModeCatalogEntry[] = [];+ const userDefinitions: ModeDefinition[] = [];+ const userCatalog: ModeCatalogEntry[] = [];const diagnostics: ModeDiagnostic[] = [];+ const builtins = new Map<string, BuiltinSlot>();for (const id of BUILTIN_MODE_IDS) {const parsed = parseModeDocument(BUILTIN_MODE_SOURCES[id], { source: "builtin", fallbackName: id });if (parsed.ok) {- definitions.push(parsed.definition);- catalog.push(catalogEntry(parsed.definition));+ builtins.set(id, { definition: parsed.definition, entry: catalogEntry(parsed.definition) });} else {+ builtins.set(id, {});diagnostics.push({ modeId: id, errors: parsed.errors, warnings: parsed.warnings });}}@@ -236,8 +265,12 @@ export function loadModeDefinitions(options: { userDocuments: readonly UserModeDlet userModes = 0;for (const document of options.userDocuments) {const { dirName, filePath } = document;+ if (isBuiltinModeId(dirName)) {+ applyBuiltinOverride(builtins.get(dirName), document, diagnostics);+ continue;+ }if (!document.source) {- catalog.push(unavailableEntry(dirName, filePath));+ userCatalog.push(unavailableEntry(dirName, filePath));diagnostics.push({modeId: dirName,filePath,@@ -252,9 +285,8 @@ export function loadModeDefinitions(options: { userDocuments: readonly UserModeDtemplates: document.templates,});const id = parsed.ok ? parsed.definition.id : parsed.declaredName ?? dirName;- const reservedId = isBuiltinModeId(dirName) ? dirName : isBuiltinModeId(id) ? id : undefined;- if (reservedId !== undefined) {- catalog.push(unavailableEntry(reservedId, filePath, {+ if (isBuiltinModeId(id)) {+ userCatalog.push(unavailableEntry(id, filePath, {reserved: true,...(parsed.ok ? {label: parsed.definition.label,@@ -263,15 +295,15 @@ export function loadModeDefinitions(options: { userDocuments: readonly UserModeD} : {}),}));diagnostics.push({- modeId: reservedId,+ modeId: id,filePath,- errors: [`name: "${reservedId}" is a builtin mode; copy it under another name to customize it`],+ errors: [`name: "${id}" is a builtin mode; edit it in ~/.pi/modes/${id}/mode.md or copy it under another name`],warnings: [],});continue;}if (!parsed.ok) {- catalog.push(unavailableEntry(id, filePath));+ userCatalog.push(unavailableEntry(id, filePath));diagnostics.push({ modeId: id, filePath, errors: parsed.errors, warnings: parsed.warnings });continue;}@@ -280,19 +312,71 @@ export function loadModeDefinitions(options: { userDocuments: readonly UserModeDif (loadedIds.has(definition.id)) refusal = `name: another mode already uses the id "${definition.id}"`;else if (userModes >= MAX_USER_MODES) refusal = `at most ${MAX_USER_MODES} user modes are loaded`;if (refusal) {- catalog.push({ ...catalogEntry(definition, filePath), available: false });+ userCatalog.push({ ...catalogEntry(definition, filePath), available: false });diagnostics.push({ modeId: definition.id, filePath, errors: [refusal], warnings: parsed.warnings });continue;}loadedIds.add(definition.id);userModes += 1;- definitions.push(definition);- catalog.push(catalogEntry(definition, filePath));+ userDefinitions.push(definition);+ userCatalog.push(catalogEntry(definition, filePath));if (parsed.warnings.length) {diagnostics.push({ modeId: definition.id, filePath, errors: [], warnings: parsed.warnings });}}- return { definitions, catalog, diagnostics };+ const definitions: ModeDefinition[] = [];+ const catalog: ModeCatalogEntry[] = [];+ for (const id of BUILTIN_MODE_IDS) {+ const slot = builtins.get(id);+ if (slot?.definition) definitions.push(slot.definition);+ if (slot?.entry) catalog.push(slot.entry);+ }+ return {+ definitions: [...definitions, ...userDefinitions],+ catalog: [...catalog, ...userCatalog],+ diagnostics,+ };+}++/**+ * `~/.pi/modes/<builtin>/mode.md`: a valid document replaces the shipped+ * definition; an invalid one is reported against the builtin, which keeps+ * running as shipped. Either way the entry records the override file.+ */+function applyBuiltinOverride(+ slot: BuiltinSlot | undefined,+ document: UserModeDocument,+ diagnostics: ModeDiagnostic[],+): void {+ const { dirName: id, filePath } = document;+ if (!slot?.entry) return;+ slot.entry = { ...slot.entry, customized: true, filePath };+ if (!document.source) {+ diagnostics.push({+ modeId: id,+ filePath,+ errors: [`mode.md: unreadable or larger than ${MODE_LIMITS.fileBytes} bytes`],+ warnings: [],+ });+ return;+ }+ const parsed = parseModeDocument(document.source, { source: "user", fallbackName: id, templates: document.templates });+ if (!parsed.ok) {+ diagnostics.push({ modeId: id, filePath, errors: parsed.errors, warnings: parsed.warnings });+ return;+ }+ const problems = builtinOverrideProblems(id, parsed.definition);+ if (problems.length) {+ diagnostics.push({ modeId: id, filePath, errors: problems, warnings: parsed.warnings });+ return;+ }+ slot.definition = parsed.definition;+ slot.entry = {+ ...catalogEntry(parsed.definition, filePath),+ source: "builtin",+ customized: true,+ };+ if (parsed.warnings.length) diagnostics.push({ modeId: id, filePath, errors: [], warnings: parsed.warnings });}/** Parsed builtin definition, or undefined for a non-builtin id. */diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 6fa6ec862..ef5ff82c3 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -903,7 +903,6 @@ export const de = {"runActive": "In diesem Chat läuft ein Modus. Stoppe ihn, bevor du zu einem anderen Modus mit Phasen wechselst.","notFound": "Dieser Modus ist nicht verfügbar. Prüfe ihn unter Einstellungen → Modi.","definitionInvalid": "Die Modusdefinition enthält Fehler:",- "idReserved": "Diese ID gehört zu einem integrierten Modus. Wähle eine andere ID.","idInvalid": "Modus-IDs bestehen aus Kleinbuchstaben, Ziffern und Bindestrichen und beginnen mit einem Buchstaben.","revisionConflict": "Der Lauf hat sich inzwischen geändert. Prüfe seinen aktuellen Stand und versuche es erneut.","notAwaitingApproval": "Dieser Lauf wartet nicht mehr auf Freigabe.",@@ -931,12 +930,16 @@ export const de = {"saving": "Wird gespeichert…","saved": "Modus gespeichert","source": "Definitionsquelle",- "readOnly": "Integrierte Modi sind schreibgeschützt. Dupliziere einen, um eine eigene Version zu erstellen.",+ "builtinHint": "Beim Speichern wird deine Version in ~/.pi/modes/{{id}}/mode.md geschrieben und ersetzt den integrierten Modus. „Standard wiederherstellen“ löscht diese Datei.",+ "customized": "Angepasst",+ "restore": "Standard wiederherstellen",+ "restoreConfirm": "Zum Wiederherstellen erneut klicken",+ "restored": "Standard wiederhergestellt","builtin": "Integriert","user": "Eigener","staged": "Mit Phasen","reserved": "Reservierte ID",- "reservedHint": "Diese Datei nutzt die ID eines integrierten Modus und wird daher nicht geladen. Benenne ihren Ordner um, um sie zu verwenden.",+ "reservedHint": "Diese Datei beansprucht außerhalb des Ordners des Modus eine integrierte Modus-ID und wird daher nicht geladen. Benenne sie um oder bearbeite den integrierten Modus in seinem eigenen Ordner.","unavailable": "Nicht verfügbar","validating": "Wird geprüft…","valid": "Keine Probleme gefunden",@@ -1725,10 +1728,6 @@ sklm: {"largePasteThresholdDesc": "Nur-Text-Einfügungen, die länger als diese Anzahl von Zeichen sind, werden zu einer temporären Sitzungsdatei.","largePasteThresholdSaveError": "Der Einfügeschwellenwert konnte nicht gespeichert werden.","modeDesc": "Modus für neue Sitzungen.",- "goalBudget": "Goal-Budget",- "goalBudgetDesc": "Grenzen für neue Goal-Läufe. Ein leeres Feld ist unbegrenzt.",- "goalBudgetTurns": "Züge",- "goalBudgetTokens": "Tokens","modeAgent": "Agent","modePlan": "Plan","modeGoal": "Ziel",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 9185afc25..b1aa525b8 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -915,7 +915,6 @@ deleteRunningSessionBlocked: "Stop the running session before deleting it.",runActive: "A mode run is active in this chat. Stop it before switching to another staged mode.",notFound: "This mode is not available. Check it in Settings → Modes.",definitionInvalid: "The mode definition has errors:",- idReserved: "That id belongs to a built-in mode. Choose another id.",idInvalid: "Mode ids use lowercase letters, digits, and dashes, and start with a letter.",revisionConflict: "The run changed in the meantime. Check its current state and try again.",notAwaitingApproval: "This run is no longer waiting for approval.",@@ -943,12 +942,16 @@ deleteRunningSessionBlocked: "Stop the running session before deleting it.",saving: "Saving…",saved: "Mode saved",source: "Definition source",- readOnly: "Built-in modes are read-only. Duplicate one to make your own version.",+ builtinHint: "Saving writes your version to ~/.pi/modes/{{id}}/mode.md, which replaces the built-in. Restore default deletes that file.",+ customized: "Customized",+ restore: "Restore default",+ restoreConfirm: "Click again to restore",+ restored: "Default restored",builtin: "Built-in",user: "Custom",staged: "Staged",reserved: "Reserved id",- reservedHint: "This file uses a built-in mode id, so it is not loaded. Rename its folder to use it.",+ reservedHint: "This file claims a built-in mode id outside that mode's folder, so it is not loaded. Rename it, or edit the built-in in its own folder.",unavailable: "Unavailable",validating: "Checking…",valid: "No problems found",@@ -1740,10 +1743,6 @@ sklm: {"Text-only pastes longer than this many characters become a temporary session file.",largePasteThresholdSaveError: "Couldn't save the paste threshold.",modeDesc: "Mode for new sessions.",- goalBudget: "Goal budget",- goalBudgetDesc: "Limits for new Goal runs. Leave a field empty for unlimited.",- goalBudgetTurns: "Turns",- goalBudgetTokens: "Tokens",modeAgent: "Agent",modePlan: "Plan",modeGoal: "Goal",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 0e4c803a2..3db77876c 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -903,7 +903,6 @@ export const es = {"runActive": "Hay una ejecución de modo activa en este chat. Detenla antes de cambiar a otro modo por etapas.","notFound": "Este modo no está disponible. Revísalo en Configuración → Modos.","definitionInvalid": "La definición del modo tiene errores:",- "idReserved": "Ese id pertenece a un modo integrado. Elige otro id.","idInvalid": "Los id de modo usan minúsculas, dígitos y guiones, y empiezan por una letra.","revisionConflict": "La ejecución cambió mientras tanto. Revisa su estado actual y vuelve a intentarlo.","notAwaitingApproval": "Esta ejecución ya no espera aprobación.",@@ -931,12 +930,16 @@ export const es = {"saving": "Guardando…","saved": "Modo guardado","source": "Código de la definición",- "readOnly": "Los modos integrados son de solo lectura. Duplica uno para crear tu propia versión.",+ "builtinHint": "Al guardar, tu versión se escribe en ~/.pi/modes/{{id}}/mode.md y reemplaza al modo integrado. Restaurar predeterminado elimina ese archivo.",+ "customized": "Personalizado",+ "restore": "Restaurar predeterminado",+ "restoreConfirm": "Haz clic de nuevo para restaurar",+ "restored": "Predeterminado restaurado","builtin": "Integrado","user": "Personalizado","staged": "Por etapas","reserved": "Id reservado",- "reservedHint": "Este archivo usa el id de un modo integrado, así que no se carga. Cambia el nombre de su carpeta para usarlo.",+ "reservedHint": "Este archivo reclama el id de un modo integrado fuera de la carpeta de ese modo, así que no se carga. Cámbiale el nombre o edita el modo integrado en su propia carpeta.","unavailable": "No disponible","validating": "Comprobando…","valid": "No se encontraron problemas",@@ -1725,10 +1728,6 @@ sklm: {"largePasteThresholdDesc": "Los pegados de solo texto de más de esta cantidad de caracteres se convierten en un archivo de sesión temporal.","largePasteThresholdSaveError": "No se pudo guardar el umbral de pegado.","modeDesc": "Modo para nuevas sesiones.",- "goalBudget": "Presupuesto de Goal",- "goalBudgetDesc": "Límites para nuevas ejecuciones de Goal. Deja un campo vacío para sin límite.",- "goalBudgetTurns": "Turnos",- "goalBudgetTokens": "Tokens","modeAgent": "Agente","modePlan": "Plan","modeGoal": "Meta",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 62c17ecdf..4f761e807 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -903,7 +903,6 @@ export const fr = {"runActive": "Une exécution de mode est active dans cette conversation. Arrêtez-la avant de passer à un autre mode par étapes.","notFound": "Ce mode n'est pas disponible. Vérifiez-le dans Paramètres → Modes.","definitionInvalid": "La définition du mode contient des erreurs :",- "idReserved": "Cet identifiant appartient à un mode intégré. Choisissez-en un autre.","idInvalid": "Les identifiants de mode utilisent des minuscules, des chiffres et des tirets, et commencent par une lettre.","revisionConflict": "L'exécution a changé entre-temps. Vérifiez son état actuel et réessayez.","notAwaitingApproval": "Cette exécution n'attend plus d'approbation.",@@ -931,12 +930,16 @@ export const fr = {"saving": "Enregistrement…","saved": "Mode enregistré","source": "Source de la définition",- "readOnly": "Les modes intégrés sont en lecture seule. Dupliquez-en un pour créer votre propre version.",+ "builtinHint": "L’enregistrement écrit votre version dans ~/.pi/modes/{{id}}/mode.md, qui remplace le mode intégré. Restaurer par défaut supprime ce fichier.",+ "customized": "Personnalisé",+ "restore": "Restaurer par défaut",+ "restoreConfirm": "Cliquez à nouveau pour restaurer",+ "restored": "Valeurs par défaut restaurées","builtin": "Intégré","user": "Personnalisé","staged": "Par étapes","reserved": "Identifiant réservé",- "reservedHint": "Ce fichier utilise l'identifiant d'un mode intégré ; il n'est donc pas chargé. Renommez son dossier pour l'utiliser.",+ "reservedHint": "Ce fichier revendique l’id d’un mode intégré hors du dossier de ce mode ; il n’est donc pas chargé. Renommez-le ou modifiez le mode intégré dans son propre dossier.","unavailable": "Indisponible","validating": "Vérification…","valid": "Aucun problème détecté",@@ -1725,10 +1728,6 @@ sklm: {"largePasteThresholdDesc": "Les collages de texte uniquement dépassant ce nombre de caractères deviennent un fichier de session temporaire.","largePasteThresholdSaveError": "Impossible d'enregistrer le seuil de collage.","modeDesc": "Mode pour les nouvelles sessions.",- "goalBudget": "Budget Goal",- "goalBudgetDesc": "Limites des nouvelles exécutions Goal. Laissez un champ vide pour illimité.",- "goalBudgetTurns": "Tours",- "goalBudgetTokens": "Tokens","modeAgent": "Agent","modePlan": "Plan","modeGoal": "Objectif",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 16c7e062a..acf427373 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -912,7 +912,6 @@ export const ko = {runActive: "이 대화에서 모드 실행이 진행 중입니다. 다른 단계형 모드로 전환하기 전에 중지하세요.",notFound: "이 모드를 사용할 수 없습니다. 설정 → 모드에서 확인하세요.",definitionInvalid: "모드 정의에 오류가 있습니다:",- idReserved: "이 ID는 기본 제공 모드의 ID입니다. 다른 ID를 선택하세요.",idInvalid: "모드 ID는 소문자, 숫자, 하이픈만 사용하며 문자로 시작해야 합니다.",revisionConflict: "그동안 실행 상태가 바뀌었습니다. 현재 상태를 확인하고 다시 시도하세요.",notAwaitingApproval: "이 실행은 더 이상 승인을 기다리지 않습니다.",@@ -940,12 +939,16 @@ export const ko = {saving: "저장 중…",saved: "모드를 저장했습니다",source: "정의 소스",- readOnly: "기본 제공 모드는 읽기 전용입니다. 복제해서 나만의 버전을 만드세요.",+ builtinHint: "저장하면 내 버전이 ~/.pi/modes/{{id}}/mode.md에 기록되어 기본 제공 모드를 대체합니다. 기본값 복원은 이 파일을 삭제합니다.",+ customized: "사용자 지정됨",+ restore: "기본값 복원",+ restoreConfirm: "다시 클릭하여 복원",+ restored: "기본값을 복원했습니다",builtin: "기본 제공",user: "사용자",staged: "단계형",reserved: "예약된 ID",- reservedHint: "이 파일은 기본 제공 모드의 ID를 사용하므로 로드되지 않습니다. 사용하려면 폴더 이름을 바꾸세요.",+ reservedHint: "이 파일은 해당 모드의 폴더 밖에서 기본 제공 모드 ID를 사용하므로 로드되지 않습니다. 이름을 바꾸거나 해당 모드의 폴더에서 편집하세요.",unavailable: "사용 불가",validating: "확인 중…",valid: "문제가 없습니다",@@ -1736,10 +1739,6 @@ sklm: {"이 글자 수보다 긴 텍스트만 붙여넣으면 임시 세션 파일이 됩니다.",largePasteThresholdSaveError: "붙여넣기 기준을 저장할 수 없습니다.",modeDesc: "새 세션의 모드입니다.",- goalBudget: "Goal 예산",- goalBudgetDesc: "새 Goal 실행의 한도입니다. 비워 두면 무제한입니다.",- goalBudgetTurns: "턴",- goalBudgetTokens: "토큰",modeAgent: "에이전트",modePlan: "계획",modeGoal: "목표",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex c3e88f509..08337258a 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -902,7 +902,6 @@ export const ptBR = {runActive: "Há uma execução de modo ativa nesta conversa. Pare-a antes de mudar para outro modo em etapas.",notFound: "Este modo não está disponível. Verifique em Configurações → Modos.",definitionInvalid: "A definição do modo tem erros:",- idReserved: "Esse id pertence a um modo integrado. Escolha outro id.",idInvalid: "Ids de modo usam letras minúsculas, dígitos e hífens, e começam com uma letra.",revisionConflict: "A execução mudou nesse meio-tempo. Verifique o estado atual e tente de novo.",notAwaitingApproval: "Esta execução não está mais aguardando aprovação.",@@ -930,12 +929,16 @@ export const ptBR = {saving: "Salvando…",saved: "Modo salvo",source: "Código da definição",- readOnly: "Modos integrados são somente leitura. Duplique um para criar sua própria versão.",+ builtinHint: "Salvar grava sua versão em ~/.pi/modes/{{id}}/mode.md, que substitui o modo integrado. Restaurar padrão exclui esse arquivo.",+ customized: "Personalizado",+ restore: "Restaurar padrão",+ restoreConfirm: "Clique novamente para restaurar",+ restored: "Padrão restaurado",builtin: "Integrado",user: "Personalizado",staged: "Em etapas",reserved: "Id reservado",- reservedHint: "Este arquivo usa o id de um modo integrado, então não é carregado. Renomeie a pasta dele para usá-lo.",+ reservedHint: "Este arquivo usa o id de um modo integrado fora da pasta desse modo, então não é carregado. Renomeie-o ou edite o modo integrado na própria pasta dele.",unavailable: "Indisponível",validating: "Verificando…",valid: "Nenhum problema encontrado",@@ -1698,10 +1701,6 @@ export const ptBR = {largePasteThresholdDesc: "Textos colados que ultrapassarem este limite de caracteres serão salvos como um arquivo temporário da sessão.",largePasteThresholdSaveError: "Não foi possível salvar o limite de colagem grande.",modeDesc: "Modo usado em novas sessões.",- goalBudget: "Orçamento do Goal",- goalBudgetDesc: "Limites para novas execuções do Goal. Deixe um campo vazio para ilimitado.",- goalBudgetTurns: "Turnos",- goalBudgetTokens: "Tokens",modeAgent: "Agente",modePlan: "Plano",modeGoal: "Meta",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 2f1fcf071..3c3cbf6ea 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -912,7 +912,6 @@ export const tr = {runActive: "Bu sohbette etkin bir mod çalışması var. Başka bir aşamalı moda geçmeden önce durdurun.",notFound: "Bu mod kullanılamıyor. Ayarlar → Modlar bölümünden kontrol edin.",definitionInvalid: "Mod tanımında hatalar var:",- idReserved: "Bu kimlik yerleşik bir moda ait. Başka bir kimlik seçin.",idInvalid: "Mod kimlikleri küçük harf, rakam ve kısa çizgi içerir ve bir harfle başlar.",revisionConflict: "Çalışma bu arada değişti. Güncel durumunu kontrol edip yeniden deneyin.",notAwaitingApproval: "Bu çalışma artık onay beklemiyor.",@@ -940,12 +939,16 @@ export const tr = {saving: "Kaydediliyor…",saved: "Mod kaydedildi",source: "Tanım kaynağı",- readOnly: "Yerleşik modlar salt okunurdur. Kendi sürümünüzü oluşturmak için birini çoğaltın.",+ builtinHint: "Kaydetmek sürümünüzü ~/.pi/modes/{{id}}/mode.md dosyasına yazar ve yerleşik modun yerini alır. Varsayılana dön bu dosyayı siler.",+ customized: "Özelleştirildi",+ restore: "Varsayılana dön",+ restoreConfirm: "Geri yüklemek için tekrar tıklayın",+ restored: "Varsayılan geri yüklendi",builtin: "Yerleşik",user: "Özel",staged: "Aşamalı",reserved: "Ayrılmış kimlik",- reservedHint: "Bu dosya yerleşik bir modun kimliğini kullandığı için yüklenmez. Kullanmak için klasörünü yeniden adlandırın.",+ reservedHint: "Bu dosya, modun kendi klasörü dışında yerleşik bir mod kimliği kullandığı için yüklenmez. Yeniden adlandırın veya yerleşik modu kendi klasöründe düzenleyin.",unavailable: "Kullanılamıyor",validating: "Denetleniyor…",valid: "Sorun bulunamadı",@@ -1730,10 +1733,6 @@ sklm: {"Bu karakter sayısından uzun salt metin yapıştırmalar geçici bir oturum dosyası olur.",largePasteThresholdSaveError: "Yapıştırma eşiği kaydedilemedi.",modeDesc: "Yeni oturumların kipi.",- goalBudget: "Goal bütçesi",- goalBudgetDesc: "Yeni Goal çalışmalarının sınırları. Sınırsız için alanı boş bırakın.",- goalBudgetTurns: "Tur",- goalBudgetTokens: "Token",modeAgent: "Ajan",modePlan: "Plan",modeGoal: "Hedef",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 0e898aeea..793decd49 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -908,7 +908,6 @@ deleteRunningSessionBlocked: "请先停止运行中的会话,再删除它。",runActive: "此对话中有正在进行的模式运行。切换到其他分阶段模式前,请先停止它。",notFound: "此模式不可用。请在“设置 → 模式”中检查。",definitionInvalid: "模式定义有错误:",- idReserved: "该 ID 属于内置模式,请换一个 ID。",idInvalid: "模式 ID 只能包含小写字母、数字和连字符,并以字母开头。",revisionConflict: "运行状态已发生变化。请查看当前状态后重试。",notAwaitingApproval: "此运行已不再等待批准。",@@ -936,12 +935,16 @@ deleteRunningSessionBlocked: "请先停止运行中的会话,再删除它。",saving: "正在保存…",saved: "模式已保存",source: "定义源码",- readOnly: "内置模式为只读。复制一份即可创建你自己的版本。",+ builtinHint: "保存会把你的版本写入 ~/.pi/modes/{{id}}/mode.md,替换内置定义;恢复默认会删除该文件。",+ customized: "已自定义",+ restore: "恢复默认",+ restoreConfirm: "再次点击以恢复",+ restored: "已恢复默认",builtin: "内置",user: "自定义",staged: "分阶段",reserved: "保留 ID",- reservedHint: "此文件使用了内置模式的 ID,因此不会被加载。重命名其文件夹后即可使用。",+ reservedHint: "此文件在内置模式自己的文件夹之外声明了内置 id,因此不会加载。请改名,或在该模式自己的文件夹中编辑。",unavailable: "不可用",validating: "正在检查…",valid: "未发现问题",@@ -1720,10 +1723,6 @@ sklm: {"纯文本粘贴超过此字符数后,会转换为当前会话的临时文件。",largePasteThresholdSaveError: "无法保存粘贴阈值。",modeDesc: "新会话模式。",- goalBudget: "Goal 预算",- goalBudgetDesc: "新 Goal 运行的上限,留空为不限。",- goalBudgetTurns: "轮数",- goalBudgetTokens: "Token",modeAgent: "智能体",modePlan: "规划",modeGoal: "目标",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 27dfa85c0..ea7c1f7cc 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -908,7 +908,6 @@ deleteRunningSessionBlocked: "請先停止執行中的會話,再刪除它。",runActive: "此對話中有進行中的模式執行。切換到其他分階段模式前,請先停止它。",notFound: "此模式無法使用。請在「設定 → 模式」中檢查。",definitionInvalid: "模式定義有錯誤:",- idReserved: "此 ID 屬於內建模式,請換一個 ID。",idInvalid: "模式 ID 只能包含小寫字母、數字和連字號,並以字母開頭。",revisionConflict: "執行狀態已變更。請查看目前狀態後再試一次。",notAwaitingApproval: "此執行已不再等待核准。",@@ -936,12 +935,16 @@ deleteRunningSessionBlocked: "請先停止執行中的會話,再刪除它。",saving: "正在儲存…",saved: "模式已儲存",source: "定義原始碼",- readOnly: "內建模式為唯讀。複製一份即可建立你自己的版本。",+ builtinHint: "儲存會把你的版本寫入 ~/.pi/modes/{{id}}/mode.md,取代內建定義;還原預設會刪除該檔案。",+ customized: "已自訂",+ restore: "還原預設",+ restoreConfirm: "再次點擊以還原",+ restored: "已還原預設",builtin: "內建",user: "自訂",staged: "分階段",reserved: "保留 ID",- reservedHint: "此檔案使用了內建模式的 ID,因此不會載入。重新命名其資料夾後即可使用。",+ reservedHint: "此檔案在內建模式自己的資料夾之外宣告了內建 id,因此不會載入。請改名,或在該模式自己的資料夾中編輯。",unavailable: "無法使用",validating: "正在檢查…",valid: "未發現問題",@@ -1720,10 +1723,6 @@ sklm: {"純文本貼上超過此字元數後,會轉換為當前會話的臨時檔案。",largePasteThresholdSaveError: "無法儲存貼上閾值。",modeDesc: "新會話模式。",- goalBudget: "Goal 預算",- goalBudgetDesc: "新 Goal 執行的上限,留空為不限。",- goalBudgetTurns: "輪數",- goalBudgetTokens: "Token",modeAgent: "智慧體",modePlan: "規劃",modeGoal: "目標",diff --git a/packages/shared/src/types/mode-runs.ts b/packages/shared/src/types/mode-runs.tsindex ed5391b30..78b6a6f3b 100644--- a/packages/shared/src/types/mode-runs.ts+++ b/packages/shared/src/types/mode-runs.ts@@ -139,8 +139,13 @@ export type ModeCatalogEntry = {source: "builtin" | "user";staged: boolean;available: boolean;- /** A user document with a builtin id is reported, not loaded. */+ /** A user document outside a builtin's folder that claims its id; reported, not loaded. */reserved?: boolean;+ /**+ * A builtin with an override document at `filePath`. The override is in+ * effect unless the catalog reports errors for that file.+ */+ customized?: boolean;filePath?: string;};@@ -151,6 +156,10 @@ export type ModeCatalog = {directory: string;};+/**+ * `builtin` marks a builtin id. Its `source` is the override document when+ * `filePath` is set, and the shipped definition otherwise.+ */export type ModeDocumentReadResult = { id: string; source: string; filePath?: string; builtin: boolean };export type ModeDocumentValidation = {diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.tsindex 97cd4f868..92f667271 100644--- a/packages/shared/src/types/settings.ts+++ b/packages/shared/src/types/settings.ts@@ -75,12 +75,6 @@ export type AppSettings = {/** Granted native application control (ADR 0342); off and unbound by default. */computerUse?: import("../computer-use.js").ComputerUseSettings;defaultMode: Mode;- /**- * Budget a new builtin Goal run starts with. Absent or null keeps the- * builtin default (20 turns, unlimited tokens); a null field is unlimited.- * A running run keeps its own budget.- */- goalBudget?: import("./mode-runs.js").ModeRunBudget | null;/*** Keep retryable provider/network failures retrying until the request succeeds.* Absent and false use the bounded ten-retry policy.diff --git a/scripts/e2e-goal-layout.mjs b/scripts/e2e-goal-layout.mjsindex 8a7314017..3c07bbf43 100644--- a/scripts/e2e-goal-layout.mjs+++ b/scripts/e2e-goal-layout.mjs@@ -91,19 +91,6 @@ app.whenReady().then(async () => {window.webContents.sendInputEvent({ type: "mouseUp", button: "left", clickCount: 1, ...point });if (action) await call("after", key);}- async function typeBudget(index, value) {- await click("budget:" + index, false);- await call("inputReady", index);- const modifiers = process.platform === "darwin" ? ["meta"] : ["control"];- window.webContents.sendInputEvent({ type: "keyDown", keyCode: "A", modifiers });- window.webContents.sendInputEvent({ type: "keyUp", keyCode: "A", modifiers });- await call("inputSelected", index);- await window.webContents.insertText(String(value));- await call("inputEdited", index, value);- window.webContents.sendInputEvent({ type: "keyDown", keyCode: "Return" });- window.webContents.sendInputEvent({ type: "keyUp", keyCode: "Return" });- await call("inputSaved", index, value);- }for (const language of ["en", "zh-CN"]) for (const width of [320, 480, 720, 1120]) {const entry = { language, width };try {@@ -118,8 +105,6 @@ app.whenReady().then(async () => {await click(key);if (key === "edit") fs.writeFileSync(path.join(__dirname, language + "-" + width + "-objective.png"), (await window.webContents.capturePage()).toPNG());}- await typeBudget(0, 37);- await typeBudget(1, 123456);await call("clockStart");await click("pause");await call("frozen");diff --git a/scripts/e2e-goal-live.mjs b/scripts/e2e-goal-live.mjsindex 5aefdb7ed..acd243b97 100644--- a/scripts/e2e-goal-live.mjs+++ b/scripts/e2e-goal-live.mjs@@ -171,8 +171,7 @@ const timeout = setTimeout(() => {}, 25 * 60_000);try {- // A) Settings budget -> autonomous turns -> verified completion -> Agent.- await host.call("settings.set", { goalBudget: { maxTurns: 6, maxTokens: null } });+ // A) Definition budget -> autonomous turns -> verified completion -> Agent.const a = await openGoalSession("complete");a.onEvent = track;await runTurn(a, "user", "In the workspace, create the file notes/hello.txt containing exactly the line `hello goal`, then verify its content with a shell command.");@@ -190,7 +189,7 @@ try {hello: await readFile(join(a.workspace, "notes/hello.txt"), "utf8").catch(() => null),artifactHeadings: ["# Objective", "# Acceptance criteria", "# Evidence"].map((heading) => artifact.includes(heading)),};- assert.equal(startedBudget, 6, "a new Goal run takes the settings budget");+ assert.equal(startedBudget, 20, "a new Goal run takes the definition budget");assert.equal(aRun, null, "the Goal run finished");assert.equal(report.complete.sessionMode, "agent");assert.equal(report.complete.hello?.trim(), "hello goal");diff --git a/scripts/e2e/goal-layout.tsx b/scripts/e2e/goal-layout.tsxindex b3cc09423..c464e9fbd 100644--- a/scripts/e2e/goal-layout.tsx+++ b/scripts/e2e/goal-layout.tsx@@ -1,13 +1,10 @@-import { useState } from "react";import { createRoot } from "react-dom/client";import { flushSync } from "react-dom";import { createInstance } from "i18next";import { I18nextProvider } from "react-i18next";import { catalogs } from "@pi-desktop/i18n";-import { IPC, type AppSettings, type ModeControlRequest, type ModeRun } from "@pi-desktop/shared";+import { IPC, type ModeControlRequest, type ModeRun } from "@pi-desktop/shared";import { ModeRunStatusBar } from "../../apps/desktop/src/features/modes/ModeRunStatusBar";-import { GoalBudgetSettingsRow } from "../../apps/desktop/src/features/modes/GoalBudgetSettingsRow";-import { SettingsCard } from "../../apps/desktop/src/features/settings/primitives";import { startModesSync } from "../../apps/desktop/src/features/modes/modes-sync";import { goalLayoutServices } from "./fixtures/goal-layout-store";@@ -73,7 +70,6 @@ let run: ModeRun = {};const listeners = new Map<string, Set<(...args: unknown[]) => void>>();const requests: ModeControlRequest[] = [];-const saves: Partial<AppSettings>[] = [];function emit() {for (const listener of listeners.get(IPC.event.modesChanged) ?? []) listener({ sessionId: run.sessionId, run });}@@ -118,17 +114,8 @@ document.body.append(host);const root = createRoot(host);let disposeSync: (() => void) | undefined;function Fixture() {- const [settings, setSettings] = useState<AppSettings>({- defaultMode: "goal", theme: "dark", enterToSend: true, onboardingDismissed: true,- goalBudget: { maxTurns: 20, maxTokens: null },- });return <main data-testid="goal-layout" style={{ width: "100%", height: "100%", padding: 8, overflow: "auto" }}><ModeRunStatusBar sessionId={run.sessionId} />- <div className="settings-content-inner" style={{ marginTop: 24 }}>- <SettingsCard><GoalBudgetSettingsRow settings={settings} saveSettings={async (patch) => {- saves.push(patch); setSettings((current) => ({ ...current, ...patch }));- }} /></SettingsCard>- </div></main>;}function label(key: string) { return i18n.t(`modes.run.${key}`); }@@ -186,27 +173,6 @@ function geometry(phase: string) {}measurements.push({ phase, rounds: r, elapsed: e, actions: actions.map((item) => ({ name: item.getAttribute("aria-label") ?? item.textContent, ...box(item) })) });}-function budgetGeometry() {- const fields = [...document.querySelectorAll<HTMLElement>(".settings-goal-budget-field")];- check(fields.length === 2, "Goal budget must expose two fields");- const rects = fields.map(box);- check(Math.abs(rects[0].top - rects[1].top) <= 1 && rects[1].left >= rects[0].right - 0.5, "Goal budget fields are not horizontal");- bounded(element(".settings-goal-budget"), "Goal budget");- bounded(element(".settings-row"), "Goal settings row");- for (const field of fields) {- const caption = field.querySelector<HTMLElement>(".settings-goal-budget-label");- const input = field.querySelector<HTMLInputElement>("input");- if (!caption || !input) throw new Error("Budget shared label/input missing");- const c = box(caption), i = box(input);- const range = document.createRange(); range.selectNodeContents(caption);- const lineTops = [...range.getClientRects()].map((rect) => Math.round(rect.top));- check(new Set(lineTops).size === 1 && caption.scrollWidth <= caption.clientWidth + 1, `Budget label wraps glyphs: ${caption.textContent}`);- check(i.left >= c.right - 0.5 && Math.abs((i.top + i.bottom) / 2 - (c.top + c.bottom) / 2) <= 1, "Budget label/input is not horizontal");- check(i.width >= 60 && input.classList.contains("field-input") && input.inputMode === "numeric", "Budget input is not usable/shared numeric control");- bounded(field, "Budget field"); target(input);- measurements.push({ phase: "budget", label: caption.textContent, caption: c, input: i, labelLines: lineTops });- }-}function elapsedText() { return element(".mode-run-elapsed").textContent; }function seconds(value: number) { return `${value} s`; }@@ -221,16 +187,13 @@ const probe = {flushSync(() => root.render(<I18nextProvider i18n={i18n}><Fixture /></I18nextProvider>));await until(() => Boolean(document.querySelector(".mode-run-elapsed")), "Mode run did not load through IPC");await document.fonts.ready; await settle();- geometry("paused"); budgetGeometry();+ geometry("paused");check(intervals.size === 0, "Paused run owns a ticking interval");return { viewport: [innerWidth, innerHeight], objectiveLength: objective.length };},async target(key: string) {await settle();- const node = key.startsWith("budget:")- ? element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${Number(key.split(":")[1]) + 1}) input`)- : button(key);- return target(node);+ return target(button(key));},async after(key: string) {if (key === "resume" || key === "pause") {@@ -253,28 +216,6 @@ const probe = {check(!document.querySelector(".mode-run-confirm"), "Confirmation cancel failed");}},- async inputReady(index: number) {- const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);- await until(() => document.activeElement === input, `Budget ${index}: native click did not focus the input`);- },- async inputSelected(index: number) {- const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);- await until(() => input.selectionStart === 0 && input.selectionEnd === input.value.length, `Budget ${index}: select-all did not settle`);- },- async inputEdited(index: number, value: number) {- const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);- await until(() => input.value === String(value), `Budget ${index}: native text insertion did not settle`);- await settle();- check(input.value === String(value), `Budget ${index}: controlled render lost inserted text`);- },- async inputSaved(index: number, value: number) {- await until(() => (index === 0 ? saves.at(-1)?.goalBudget?.maxTurns : saves.at(-1)?.goalBudget?.maxTokens) === value, "Budget native input/Enter did not save");- await settle();- const input = element<HTMLInputElement>(`.settings-goal-budget-field:nth-child(${index + 1}) input`);- check(input.value === String(value) && document.activeElement === input, "Budget value/focus lost after save");- check(input.labels?.length === 1 && Boolean(input.labels[0].textContent?.trim()), "Budget input has no accessible label");- budgetGeometry();- },async clockStart() {push({ state: "running", elapsedMs: 5000, activeSinceMs: now }); await settle();check(elapsedText() === seconds(5) && intervals.size === 1, "Active timer did not initialize");@@ -303,7 +244,7 @@ const probe = {check([...listeners.values()].every((set) => set.size === 0), "Mode sync listeners survived disposal");check(goalLayoutServices.toasts.length === 0, `Unexpected errors: ${goalLayoutServices.toasts.join("; ")}`);Date.now = realNow; window.setInterval = realSetInterval; window.clearInterval = realClearInterval;- return { checks, failures, measurements, requests, saves, timerCallbacks: callbacks };+ return { checks, failures, measurements, requests, timerCallbacks: callbacks };},};Object.assign(globalThis, { goalLayout: probe });