From dbfca1e6703e042f2baa1b50ad56327e3ff10fd8 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:23:07 +0100 Subject: [PATCH 1/5] feat(web): Settings page "Fork" with the fork's agent and review settings, and usage pacing rows Every fork setting gets one Settings page, Fork (/settings/fork), next to Threads in the Agents nav group. Its top lists each fork feature as on or off (the fork report's rules). Group Agents holds Waits, Wait checks and Agent slots, moved here from Settings > Threads (the Threads page is upstream's again), and the new Usage pacing section; group Reviews holds Review rules. A project screen shows only what a project may override (wait checks, review rules). Usage pacing had no screen: the gate (off, advise, enforce), the lower-effort map as pairs like high=medium, and one row per provider account by its display name with its reserve percent and its spend-first and no-limits switches. An entry for an account that is gone is listed with Remove; a stored entry has a reset. Every row is in the settings search. Co-Authored-By: Claude Opus 5.5 --- .github/fork-seams.json | 28 +- FORK_CHANGES.md | 2 +- .../components/settings/SettingsPanels.tsx | 5 - .../settings/SettingsSidebarNav.tsx | 2 + .../settings/fork/ForkSettingsPanel.tsx | 79 +++++ .../fork/UsagePacingSettings.browser.test.tsx | 162 ++++++++++ .../settings/fork/UsagePacingSettings.tsx | 291 ++++++++++++++++++ .../settings/fork/forkStatus.logic.test.ts | 50 +++ .../settings/fork/forkStatus.logic.ts | 65 ++++ .../fork/usagePacingSettings.logic.test.ts | 95 ++++++ .../fork/usagePacingSettings.logic.ts | 114 +++++++ .../settings/forkSettingsSearchItems.ts | 71 ++++- .../src/components/settings/settingsSearch.ts | 8 +- apps/web/src/routeTree.gen.ts | 21 ++ apps/web/src/routes/_chat.settings.fork.tsx | 6 + docs/fork/README.md | 25 +- 16 files changed, 980 insertions(+), 44 deletions(-) create mode 100644 apps/web/src/components/settings/fork/ForkSettingsPanel.tsx create mode 100644 apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx create mode 100644 apps/web/src/components/settings/fork/UsagePacingSettings.tsx create mode 100644 apps/web/src/components/settings/fork/forkStatus.logic.test.ts create mode 100644 apps/web/src/components/settings/fork/forkStatus.logic.ts create mode 100644 apps/web/src/components/settings/fork/usagePacingSettings.logic.test.ts create mode 100644 apps/web/src/components/settings/fork/usagePacingSettings.logic.ts create mode 100644 apps/web/src/routes/_chat.settings.fork.tsx diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 231c84f8c3b1b..d87b5963d0cdb 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -170,28 +170,17 @@ "apps/web/src/components/settings/settingsSearch.ts": { "why": "The fork's Settings page \"Fork\" (/settings/fork) is one more SettingsPath, so it needs its label, its place in the nav (the Agents group) and its search scope here; its rows are the fork's own search items (forkSettingsSearchItems.ts), spread in at one place. The import and the spread predate the list (they were \"pending\").", "added": [ - "import { FORK_SETTINGS_SEARCH_ITEMS } from \"./forkSettingsSearchItems\"; // Fork", - "...FORK_SETTINGS_SEARCH_ITEMS, // Fork: waits and agent slots." - ], - "announced": { - "since": "2026-11-19", - "added": [ - "import { FORK_SETTINGS_LABEL, FORK_SETTINGS_SEARCH_ITEMS } from \"./forkSettingsSearchItems\"; // Fork", - "| \"/settings/fork\" // Fork", - "\"/settings/fork\": FORK_SETTINGS_LABEL, // Fork", - "\"/settings/fork\", // Fork", - "\"/settings/fork\": null, // Fork", - "...FORK_SETTINGS_SEARCH_ITEMS, // Fork: the rows of the Fork page." - ] - } + "import { FORK_SETTINGS_LABEL, FORK_SETTINGS_SEARCH_ITEMS } from \"./forkSettingsSearchItems\"; // Fork", + "| \"/settings/fork\" // Fork", + "\"/settings/fork\": FORK_SETTINGS_LABEL, // Fork", + "\"/settings/fork\", // Fork", + "\"/settings/fork\": null, // Fork", + "...FORK_SETTINGS_SEARCH_ITEMS, // Fork: the rows of the Fork page." + ] }, "apps/web/src/components/settings/SettingsSidebarNav.tsx": { "why": "The fork's Settings page \"Fork\" (/settings/fork) needs its icon in the nav's icon table, which every SettingsPath must have.", - "added": [], - "announced": { - "since": "2026-11-19", - "added": ["GitForkIcon,", "\"/settings/fork\": GitForkIcon, // Fork"] - } + "added": ["GitForkIcon,", "\"/settings/fork\": GitForkIcon, // Fork"] } }, "//pending": "Upstream files whose fork lines predate counting every upstream file, each with its ceiling: the most fork lines it may hold against upstream (counted from upstream, as fork-follow runs the check). To move into fork files or pin as seams; lower a ceiling when lines move out and take a file off when none are left. A pull request may change them but not grow them.", @@ -238,7 +227,6 @@ "apps/web/src/components/ChatMarkdown.tsx": 39, "apps/web/src/components/chat/MarkdownFileLink.tsx": 32, "apps/web/src/components/media/mediaContent.ts": 8, - "apps/web/src/components/settings/SettingsPanels.tsx": 4, "apps/web/src/components/settings/scopedSettings.test.ts": 153, "apps/web/src/components/settings/scopedSettings.ts": 9, "apps/web/src/components/settings/useScopedSettings.ts": 27, diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index a87e13667c849..bfa644f502644 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -23,7 +23,7 @@ setting is missing here or a setting named here does not exist. | The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | | Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | off; rule only observes | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | | Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | -| Settings pages for waits, wait checks and agent slots. | Switch these on without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | +| The Settings page **Fork** (`/settings/fork`): every fork setting in one place, with one line per feature at the top saying whether it is on. So far: waits, wait checks, agent slots, usage pacing (per account by name) and review rules. | Change every fork setting without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots`, `server.usagePacing`, `server.usagePacingGate`, `server.usagePacingLowerEffort`, `server.reviewRules` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | | The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | | The fork's service layers in the server are wired from one fork file (`apps/server/src/fork/forkLayers.ts`). | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#384](https://github.com/scuttletoby/t3code/pull/384) | | A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index eee39d849d745..e0a12417848fa 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -85,8 +85,6 @@ import { usePrimaryEnvironmentId, } from "../../state/environments"; import { EMPTY_SERVER_PROVIDERS } from "../../state/server"; -import { WaitsAndSlotsSettings } from "./WaitsAndSlotsSettings"; -import { ReviewRulesSettings } from "./ReviewRulesSettings"; import { Button } from "../ui/button"; import { DraftInput } from "../ui/draft-input"; import { Input } from "../ui/input"; @@ -2027,9 +2025,6 @@ export function ThreadsSettingsPanel() { /> - {hasServerTargets ? : null} - {hasServerTargets ? : null} - {hasServerTargets ? ( + + + + + ); + } + return ( + + + + + {isProjectScope ? null : } + + + + + + ); +} + +function ForkStatusSection() { + const searchableSetting = useSearchableSetting(); + const statuses = forkFeatureStatuses(useScopedSettings()); + return ( + + +
    + {statuses.map((status) => ( +
  • + {status.label} + + {status.detail} + +
  • + ))} +
+
+
+ ); +} + +function ForkGroup({ title, children }: { readonly title: string; readonly children: ReactNode }) { + return ( +
+

+ {title} +

+ {children} +
+ ); +} diff --git a/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx b/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx new file mode 100644 index 0000000000000..ca4c3ebaabe57 --- /dev/null +++ b/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx @@ -0,0 +1,162 @@ +import { type ManagedPolicySummary, ServerSettings } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../../test/render"; + +type Settings = ServerSettings; +type UpdateOptions = { readonly onFailed?: () => void; readonly onSaved?: () => void }; + +const state = vi.hoisted(() => ({ + settings: {} as Settings, + environments: [] as Array<{ + environmentId: string; + providers: Array<{ instanceId: string; displayName: string }>; + managedPolicy?: ManagedPolicySummary; + }>, + update: vi.fn((_patch: unknown, _options?: UpdateOptions) => {}), +})); + +function scope() { + const environments = state.environments.map(({ environmentId, managedPolicy }) => ({ + environmentId, + label: environmentId, + connection: { phase: "connected" }, + serverConfig: { + settings: state.settings, + environment: { capabilities: {}, platform: { os: "linux", arch: "x64", machine: "server" } }, + ...(managedPolicy ? { managedPolicy } : {}), + }, + })); + return { + scope: { + kind: "all", + label: "All", + members: [], + environmentIds: environments.map(({ environmentId }) => environmentId), + }, + environments, + connectedEnvironments: environments, + environment: environments[0] ?? null, + targets: environments.map(({ environmentId }) => ({ + environmentId, + label: environmentId, + projectId: null, + settings: state.settings, + sources: {}, + })), + target: null, + }; +} + +vi.mock(import("../SettingsScopeContext"), async (original) => ({ + ...(await original()), + useSettingsScope: scope as never, + useOptionalSettingsScope: scope as never, +})); +vi.mock(import("../useScopedSettings"), async (original) => ({ + ...(await original()), + useScopedSettings: ((select: (settings: Settings) => unknown) => select(state.settings)) as never, + useScopedSettingsMixed: () => false, + useScopedSettingsWriteAllowed: () => true, + useUpdateScopedSettings: (() => state.update) as never, + useClearScopedSettings: (() => vi.fn()) as never, + useClearProjectOverrides: (() => vi.fn()) as never, +})); +vi.mock(import("../../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironmentProviders: (() => + new Map( + state.environments.map(({ environmentId, providers }) => [environmentId, providers]), + )) as never, +})); +vi.mock(import("../../../state/session"), async (original) => ({ + ...(await original()), + useEnvironmentsWithScope: ((environments: ReadonlyArray<{ environmentId: string }>) => + new Set(environments.map(({ environmentId }) => environmentId))) as never, +})); + +import { UsagePacingSettings } from "./UsagePacingSettings"; + +const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings); + +/** The settings a server reads from `file`, so an old or empty file is tested as it loads. */ +function setup(file: object) { + state.settings = decodeServerSettings(file); + state.environments = [ + { + environmentId: "env-a", + providers: [ + { instanceId: "claude-a", displayName: "Claude A" }, + { instanceId: "codex-b", displayName: "Codex B" }, + ], + }, + ]; + state.update.mockReset(); +} + +describe("UsagePacingSettings", () => { + it("lists each account by name from an empty settings file, and writes one account's reserve", async () => { + setup({}); + await using screen = await render(); + + await expect.element(screen.getByText("Reserve on Claude A")).toBeVisible(); + await expect.element(screen.getByText("Reserve on Codex B")).toBeVisible(); + const reserve = screen.getByRole("textbox", { name: "Reserve on Codex B in percent" }); + await expect.element(reserve).toHaveValue("0"); + await userEvent.clear(reserve); + await userEvent.type(reserve, "20{Enter}"); + expect(state.update.mock.calls[0]![0]).toEqual({ + usagePacing: { "codex-b": { reservePercent: 20 } }, + }); + + await userEvent.click(screen.getByRole("switch", { name: "Spend Claude A first" })); + expect(state.update.mock.calls[1]![0]).toEqual({ + usagePacing: { "claude-a": { burnFirst: true } }, + }); + }); + + it("reads a stored entry, resets it, and removes one for an account that was removed", async () => { + setup({ + usagePacing: { "claude-a": { reservePercent: 15, noLimits: true }, old_account: {} }, + }); + await using screen = await render(); + + await expect + .element(screen.getByRole("textbox", { name: "Reserve on Claude A in percent" })) + .toHaveValue("15"); + await expect + .element(screen.getByRole("switch", { name: "Claude A has no usage limits" })) + .toBeChecked(); + await userEvent.click( + screen.getByRole("button", { name: "Reset usage pacing for Claude A to default" }), + ); + expect(state.update.mock.calls[0]![0]).toEqual({ usagePacing: { "claude-a": null } }); + + await expect.element(screen.getByText("Reserve on old_account")).toBeVisible(); + await userEvent.click( + screen.getByRole("button", { name: "Remove usage pacing for old_account" }), + ); + expect(state.update.mock.calls[1]![0]).toEqual({ usagePacing: { old_account: null } }); + }); + + it("writes the gate and the lower effort map, and refuses effort text it cannot read", async () => { + setup({}); + await using screen = await render(); + + await userEvent.click(screen.getByRole("combobox", { name: "Usage pacing gate" })); + await userEvent.click(screen.getByRole("option", { name: "Advise" })); + expect(state.update.mock.calls[0]![0]).toEqual({ usagePacingGate: "advise" }); + + const effort = screen.getByRole("textbox", { name: "Lower effort when ahead of pace" }); + await userEvent.type(effort, "high{Enter}"); + await expect.element(screen.getByRole("alert")).toBeVisible(); + expect(state.update).toHaveBeenCalledTimes(1); + await userEvent.type(effort, "=medium{Enter}"); + expect(state.update.mock.calls[1]![0]).toEqual({ + usagePacingLowerEffort: { high: "medium" }, + }); + }); +}); diff --git a/apps/web/src/components/settings/fork/UsagePacingSettings.tsx b/apps/web/src/components/settings/fork/UsagePacingSettings.tsx new file mode 100644 index 0000000000000..d5ec8860e0772 --- /dev/null +++ b/apps/web/src/components/settings/fork/UsagePacingSettings.tsx @@ -0,0 +1,291 @@ +/** + * Fork: usage pacing (`usagePacingGate`, `usagePacingLowerEffort`, `usagePacing`). Server-wide, so + * a project screen does not show it. Every write is an ordinary settings patch from the person at + * the screen; agents cannot change it. + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: this panel is the fork's own and its text is English only; upstream's translation catalogs hold no fork keys. */ +import { + DEFAULT_SERVER_SETTINGS, + type ServerSettingsPatch, + type UsagePacingGateMode, + type UsagePacingInstanceSettingsPatch, +} from "@t3tools/contracts"; +import { useState } from "react"; + +import { useEnvironmentProviders } from "../../../state/environments"; +import { EMPTY_SERVER_PROVIDERS } from "../../../state/server"; +import { Button } from "../../ui/button"; +import { Input } from "../../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../../ui/select"; +import { Switch } from "../../ui/switch"; +import { IntervalSecondsField } from "../IntervalSecondsField"; +import { useSettingsScope } from "../SettingsScopeContext"; +import { SettingResetButton, SettingsRow, SettingsSection } from "../settingsLayout"; +import { useSearchableSetting } from "../settingsSearch"; +import { targetsDiffer } from "../waitsAndSlotsSettings.logic"; +import { useScopedSettings, useUpdateScopedSettings } from "../useScopedSettings"; +import { + USAGE_PACING_GATE_OPTIONS, + formatLowerEffort, + parseLowerEffort, + usagePacingAccountRows, + usagePacingAccountSummary, +} from "./usagePacingSettings.logic"; + +type UpdateSettings = ReturnType; + +const MIXED = "The selected environments have different values. Select one environment to edit it."; + +export function UsagePacingSettings() { + const updateSettings = useUpdateScopedSettings(); + return ( + + + + + + ); +} + +function GateRow({ updateSettings }: { readonly updateSettings: UpdateSettings }) { + const searchableSetting = useSearchableSetting(); + const gate = useScopedSettings((settings) => settings.usagePacingGate); + const { targets } = useSettingsScope(); + const mixed = targetsDiffer(targets, (settings) => settings.usagePacingGate); + const option = USAGE_PACING_GATE_OPTIONS.find((candidate) => candidate.value === gate); + const save = (value: UsagePacingGateMode) => updateSettings({ usagePacingGate: value }); + return ( + save(DEFAULT_SERVER_SETTINGS.usagePacingGate)} + /> + ) : null + } + control={ + + } + /> + ); +} + +function LowerEffortRow({ updateSettings }: { readonly updateSettings: UpdateSettings }) { + const searchableSetting = useSearchableSetting(); + const stored = useScopedSettings((settings) => settings.usagePacingLowerEffort); + const { targets } = useSettingsScope(); + const mixed = targetsDiffer(targets, (settings) => settings.usagePacingLowerEffort); + const storedText = formatLowerEffort(stored); + const [draft, setDraft] = useState({ saved: storedText, text: storedText }); + const [error, setError] = useState(null); + if (draft.saved !== storedText) setDraft({ saved: storedText, text: storedText }); + + const commit = () => { + if (draft.text === storedText) return; + const parsed = parseLowerEffort(draft.text); + if ("error" in parsed) { + setError(parsed.error); + return; + } + setError(null); + updateSettings( + { usagePacingLowerEffort: parsed.value }, + { onFailed: () => setDraft({ saved: storedText, text: storedText }) }, + ); + }; + + return ( + updateSettings({ usagePacingLowerEffort: {} })} + /> + ) : null + } + control={ + mixed ? null : ( + { + setError(null); + setDraft({ ...draft, text: event.target.value }); + }} + onBlur={commit} + onKeyDown={(event) => { + if (event.key === "Enter") commit(); + }} + /> + ) + } + > + {error !== null ? ( +

+ {error} +

+ ) : null} +
+ ); +} + +function AccountRows({ updateSettings }: { readonly updateSettings: UpdateSettings }) { + const searchableSetting = useSearchableSetting(); + const usagePacing = useScopedSettings((settings) => settings.usagePacing); + const { targets, environment, connectedEnvironments } = useSettingsScope(); + const providersByEnvironment = useEnvironmentProviders(); + // Every selected environment's accounts, the primary's first, as the agent slots rows list them. + const providers = [ + ...(environment ? [environment] : []), + ...connectedEnvironments.filter( + (candidate) => candidate.environmentId !== environment?.environmentId, + ), + ].flatMap( + (candidate) => providersByEnvironment.get(candidate.environmentId) ?? EMPTY_SERVER_PROVIDERS, + ); + const mixed = targetsDiffer(targets, (settings) => settings.usagePacing); + const rows = usagePacingAccountRows(providers, usagePacing); + const patch = (instanceId: string, value: UsagePacingInstanceSettingsPatch | null) => + ({ usagePacing: { [instanceId]: value } }) satisfies ServerSettingsPatch; + + return ( + <> + + {mixed + ? null + : rows.map((row) => ( + updateSettings(patch(row.instanceId, null))} + /> + ) : null + } + control={ + row.known ? ( +
+ + updateSettings( + patch(row.instanceId, { reservePercent: Math.min(100, value) }), + options, + ) + } + /> + % +
+ ) : ( + + ) + } + > + {row.known ? ( +
+ + +
+ ) : null} +
+ ))} + + ); +} diff --git a/apps/web/src/components/settings/fork/forkStatus.logic.test.ts b/apps/web/src/components/settings/fork/forkStatus.logic.test.ts new file mode 100644 index 0000000000000..f376b212cebb9 --- /dev/null +++ b/apps/web/src/components/settings/fork/forkStatus.logic.test.ts @@ -0,0 +1,50 @@ +import { ServerSettings } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { forkFeatureStatuses } from "./forkStatus.logic"; + +const fromFile = Schema.decodeUnknownSync(ServerSettings); +const lines = (file: unknown) => + forkFeatureStatuses(fromFile(file)).map((status) => `${status.label}: ${status.detail}`); + +describe("forkFeatureStatuses", () => { + it("reads every feature as off from an empty settings file", () => { + expect(lines({})).toEqual([ + "Waits: Off", + "Agent slots: Off", + "Usage pacing: Off", + "Review rules: Off", + "Automatic updates: Off", + "Handoff: Off", + "Playtest: Off", + ]); + }); + + it("reads each switch as the server does", () => { + const statuses = lines({ + waitFor: { enabled: true }, + agentSlots: { enabled: true }, + usagePacingGate: "advise", + reviewRules: { preset: "recommended" }, + automaticUpdates: true, + handoff: { mode: "compact", threads: { "thread-1": "handoff", "thread-2": "compact" } }, + }); + expect(statuses).toEqual([ + "Waits: On", + "Agent slots: On", + "Usage pacing: On: advise", + "Review rules: On", + "Automatic updates: On", + "Handoff: On for 1 thread", + "Playtest: Off", + ]); + }); + + it("reads an unreadable hand-edited value as off, never half on", () => { + expect(lines({ reviewRules: { preset: "newer-preset" }, handoff: { mode: 7 } })).toContain( + "Review rules: Off", + ); + expect(lines({ handoff: { mode: 7 } })).toContain("Handoff: Off"); + }); +}); diff --git a/apps/web/src/components/settings/fork/forkStatus.logic.ts b/apps/web/src/components/settings/fork/forkStatus.logic.ts new file mode 100644 index 0000000000000..9b213bc714c52 --- /dev/null +++ b/apps/web/src/components/settings/fork/forkStatus.logic.ts @@ -0,0 +1,65 @@ +/** + * Fork: one line per fork feature for the top of the Fork page, on or off as the selected scope + * reads its settings. Same rules as the fork report (apps/server/src/golive/forkReport.ts). + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ +import { type ServerSettings, effectiveReviewRules } from "@t3tools/contracts"; + +export interface ForkFeatureStatus { + readonly key: string; + readonly label: string; + readonly on: boolean; + readonly detail: string; +} + +type StatusSettings = Pick< + ServerSettings, + | "waitFor" + | "agentSlots" + | "usagePacingGate" + | "reviewRules" + | "automaticUpdates" + | "handoff" + | "playtest" +>; + +export function forkFeatureStatuses(settings: StatusSettings): ReadonlyArray { + const handoffThreads = Object.values(settings.handoff.threads).filter( + (mode) => mode === "handoff", + ).length; + const handoffOn = settings.handoff.mode === "handoff" || handoffThreads > 0; + const reviewRulesOn = effectiveReviewRules(settings.reviewRules).preset !== "off"; + return [ + onOff("waitFor", "Waits", settings.waitFor.enabled), + onOff("agentSlots", "Agent slots", settings.agentSlots.enabled), + { + key: "usagePacingGate", + label: "Usage pacing", + on: settings.usagePacingGate !== "off", + detail: { off: "Off", advise: "On: advise", enforce: "On: enforce" }[ + settings.usagePacingGate + ], + }, + onOff("reviewRules", "Review rules", reviewRulesOn), + onOff("automaticUpdates", "Automatic updates", settings.automaticUpdates), + { + key: "handoff", + label: "Handoff", + on: handoffOn, + detail: + settings.handoff.mode === "handoff" + ? "On" + : handoffThreads > 0 + ? `On for ${handoffThreads} thread${handoffThreads === 1 ? "" : "s"}` + : "Off", + }, + onOff("playtest", "Playtest", settings.playtest.enabled), + ]; +} + +const onOff = (key: string, label: string, on: boolean): ForkFeatureStatus => ({ + key, + label, + on, + detail: on ? "On" : "Off", +}); diff --git a/apps/web/src/components/settings/fork/usagePacingSettings.logic.test.ts b/apps/web/src/components/settings/fork/usagePacingSettings.logic.test.ts new file mode 100644 index 0000000000000..a83ceb3823c5a --- /dev/null +++ b/apps/web/src/components/settings/fork/usagePacingSettings.logic.test.ts @@ -0,0 +1,95 @@ +import { type ProviderInstanceId, ServerSettings } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + formatLowerEffort, + parseLowerEffort, + usagePacingAccountRows, + usagePacingAccountSummary, +} from "./usagePacingSettings.logic"; + +const id = (value: string) => value as ProviderInstanceId; +const fromFile = Schema.decodeUnknownSync(ServerSettings); + +describe("usagePacingAccountRows", () => { + it("lists every account by its name with the defaults when the file names none", () => { + const rows = usagePacingAccountRows( + [ + { instanceId: id("codex"), displayName: "Codex" }, + { instanceId: id("codex_work"), displayName: "Codex (work)" }, + { instanceId: id("codex"), displayName: "Codex again" }, + ], + fromFile({}).usagePacing, + ); + expect(rows.map((row) => [row.label, row.settings.reservePercent, row.stored])).toEqual([ + ["Codex", 0, false], + ["Codex (work)", 0, false], + ]); + }); + + it("reads each account's own entry, and keeps one for an account that was removed", () => { + const rows = usagePacingAccountRows( + [{ instanceId: id("claudeAgent") }], + fromFile({ + usagePacing: { + claudeAgent: { reservePercent: 20 }, + gone_account: { burnFirst: true }, + }, + }).usagePacing, + ); + expect(rows).toEqual([ + { + instanceId: "claudeAgent", + label: "claudeAgent", + settings: { reservePercent: 20, burnFirst: false, noLimits: false }, + stored: true, + known: true, + }, + { + instanceId: "gone_account", + label: "gone_account", + settings: { reservePercent: 0, burnFirst: true, noLimits: false }, + stored: true, + known: false, + }, + ]); + }); + + it("says what each account's entry does", () => { + const summary = (file: object) => + usagePacingAccountSummary(Object.values(fromFile(file).usagePacing)[0]!); + expect(summary({ usagePacing: { a: {} } })).toBe("No reserve"); + expect(summary({ usagePacing: { a: { reservePercent: 15, burnFirst: true } } })).toBe( + "15% kept free, spent first", + ); + expect(summary({ usagePacing: { a: { reservePercent: 15, noLimits: true } } })).toBe( + "No usage limits", + ); + }); +}); + +describe("lower effort field", () => { + it("shows the stored map and reads it back unchanged", () => { + const stored = fromFile({ + usagePacingLowerEffort: { medium: "low", high: "medium" }, + }).usagePacingLowerEffort; + const text = formatLowerEffort(stored); + expect(text).toBe("high=medium, medium=low"); + expect(parseLowerEffort(text)).toEqual({ value: stored }); + expect(formatLowerEffort(fromFile({}).usagePacingLowerEffort)).toBe(""); + }); + + it("reads pairs split by commas or lines, and empty as no lowering", () => { + expect(parseLowerEffort(" high = medium,\nxhigh=high ,")).toEqual({ + value: { high: "medium", xhigh: "high" }, + }); + expect(parseLowerEffort(" ")).toEqual({ value: {} }); + }); + + it("refuses text that is not a list of pairs", () => { + expect(parseLowerEffort("high")).toEqual({ error: '"high" is not a pair like high=medium.' }); + expect(parseLowerEffort("high=medium=low")).toHaveProperty("error"); + expect(parseLowerEffort("high=low, high=medium")).toEqual({ error: "high is listed twice." }); + }); +}); diff --git a/apps/web/src/components/settings/fork/usagePacingSettings.logic.ts b/apps/web/src/components/settings/fork/usagePacingSettings.logic.ts new file mode 100644 index 0000000000000..73dcf70a28547 --- /dev/null +++ b/apps/web/src/components/settings/fork/usagePacingSettings.logic.ts @@ -0,0 +1,114 @@ +/** Fork: the pure parts of the usage pacing panel (`usagePacing`, `usagePacingGate`, `usagePacingLowerEffort`). */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ +import { + DEFAULT_USAGE_PACING_INSTANCE_SETTINGS, + type ProviderInstanceId, + type UsagePacingGateMode, + type UsagePacingInstanceSettings, + type UsagePacingLowerEffort, +} from "@t3tools/contracts"; + +export interface UsagePacingAccountRow { + readonly instanceId: ProviderInstanceId; + readonly label: string; + readonly settings: UsagePacingInstanceSettings; + /** Stored in the settings file: a reset or a removal then has something to clear. */ + readonly stored: boolean; + /** On this server now; an entry for an account that was removed is still listed, to clear it. */ + readonly known: boolean; +} + +/** One row per provider account on the server, by its display name, then any stored entry left over. */ +export function usagePacingAccountRows( + providers: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly displayName?: string | undefined; + }>, + usagePacing: Readonly>, +): ReadonlyArray { + const rows: Array = []; + const seen = new Set(); + for (const provider of providers) { + if (seen.has(provider.instanceId)) continue; + seen.add(provider.instanceId); + const stored = usagePacing[provider.instanceId]; + rows.push({ + instanceId: provider.instanceId, + label: provider.displayName ?? provider.instanceId, + settings: stored ?? DEFAULT_USAGE_PACING_INSTANCE_SETTINGS, + stored: stored !== undefined, + known: true, + }); + } + for (const [instanceId, settings] of Object.entries(usagePacing).toSorted(([a], [b]) => + a.localeCompare(b), + )) { + if (seen.has(instanceId)) continue; + rows.push({ + instanceId: instanceId as ProviderInstanceId, + label: instanceId, + settings, + stored: true, + known: false, + }); + } + return rows; +} + +export function usagePacingAccountSummary(settings: UsagePacingInstanceSettings): string { + if (settings.noLimits) return "No usage limits"; + const reserve = + settings.reservePercent > 0 ? `${settings.reservePercent}% kept free` : "No reserve"; + return settings.burnFirst ? `${reserve}, spent first` : reserve; +} + +export const USAGE_PACING_GATE_OPTIONS: ReadonlyArray<{ + readonly value: UsagePacingGateMode; + readonly label: string; + readonly description: string; +}> = [ + { + value: "off", + label: "Off", + description: "Agents start tasks as asked; the pace is not read.", + }, + { + value: "advise", + label: "Advise", + description: + "Tasks start as asked, and the agent is told when an account is ahead of its pace.", + }, + { + value: "enforce", + label: "Enforce", + description: + "A task on an account ahead of its pace moves to another account of the same provider, runs at a lower effort, or waits.", + }, +]; + +/** `high=medium, medium=low`, sorted by level, as the effort field shows a map. */ +export function formatLowerEffort(map: UsagePacingLowerEffort): string { + return Object.entries(map) + .toSorted(([a], [b]) => a.localeCompare(b)) + .map(([from, to]) => `${from}=${to}`) + .join(", "); +} + +/** The map typed in the effort field, or why it cannot be read. Empty clears it. */ +export function parseLowerEffort( + text: string, +): { readonly value: UsagePacingLowerEffort } | { readonly error: string } { + const value: Record = {}; + for (const part of text.split(/[,\n]/)) { + const pair = part.trim(); + if (pair === "") continue; + const match = /^([^=\s]+)\s*=\s*([^=\s]+)$/.exec(pair); + if (match === null) { + return { error: `"${pair}" is not a pair like high=medium.` }; + } + const [, from, to] = match as unknown as [string, string, string]; + if (Object.hasOwn(value, from)) return { error: `${from} is listed twice.` }; + value[from] = to; + } + return { value }; +} diff --git a/apps/web/src/components/settings/forkSettingsSearchItems.ts b/apps/web/src/components/settings/forkSettingsSearchItems.ts index ac643c93bc1bb..daa0bf8909d0d 100644 --- a/apps/web/src/components/settings/forkSettingsSearchItems.ts +++ b/apps/web/src/components/settings/forkSettingsSearchItems.ts @@ -1,19 +1,40 @@ -// Fork: the fork's own entries in the settings search (waits and agent slots). settingsSearch.ts -// spreads them into upstream's list at their place. +// Fork: the label of the fork's Settings page and its rows in the settings search. settingsSearch.ts +// spreads them into upstream's list at one place. /* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ +import { AGENT_SLOTS_NUMBER_FIELDS, WAIT_FOR_NUMBER_FIELDS } from "./waitsAndSlotsSettings.logic"; + +export const FORK_SETTINGS_LABEL = "Fork"; + +const FORK_PAGE = "/settings/fork" as const; + export const FORK_SETTINGS_SEARCH_ITEMS = [ + { + id: "fork-status", + title: "Fork features on or off", + to: FORK_PAGE, + searchTerms: ["fork overview status enabled report"], + environmentOnly: true, + }, { id: "wait-for", title: "Let agents wait for events", - to: "/settings/threads", + to: FORK_PAGE, searchTerms: ["wait_for wake pull request checks merged file service unit timeout"], environmentOnly: true, scope: "environment-defaults", }, + ...WAIT_FOR_NUMBER_FIELDS.map((field) => ({ + id: `waitFor-${field.key}` as const, + title: field.title, + to: FORK_PAGE, + searchTerms: ["wait_for waits"], + environmentOnly: true, + scope: "environment-defaults" as const, + })), { id: "wait-checks", title: "Wait checks", - to: "/settings/threads", + to: FORK_PAGE, searchTerms: ["wait_for check command exit code poll condition"], environmentOnly: true, scope: "project-defaults", @@ -21,9 +42,49 @@ export const FORK_SETTINGS_SEARCH_ITEMS = [ { id: "agent-slots", title: "Limit running agents", - to: "/settings/threads", + to: FORK_PAGE, searchTerms: ["agent slots delegate_task subagents limit memory per account machine"], environmentOnly: true, scope: "environment-defaults", }, + ...AGENT_SLOTS_NUMBER_FIELDS.map((field) => ({ + id: `agentSlots-${field.key}` as const, + title: field.title, + to: FORK_PAGE, + searchTerms: ["agent slots delegate_task"], + environmentOnly: true, + scope: "environment-defaults" as const, + })), + { + id: "usage-pacing-gate", + title: "Usage pacing gate", + to: FORK_PAGE, + searchTerms: ["usagePacingGate delegate_task usage limits pace advise enforce"], + environmentOnly: true, + scope: "environment-defaults", + }, + { + id: "usage-pacing-lower-effort", + title: "Lower effort when ahead of pace", + to: FORK_PAGE, + searchTerms: ["usagePacingLowerEffort reasoning effort high medium"], + environmentOnly: true, + scope: "environment-defaults", + }, + { + id: "usage-pacing", + title: "Usage reserve per account", + to: FORK_PAGE, + searchTerms: ["usagePacing reservePercent burn first no limits api key provider account"], + environmentOnly: true, + scope: "environment-defaults", + }, + { + id: "review-rules", + title: "Review rules", + to: FORK_PAGE, + searchTerms: ["reviewRules review lens runner model effort state question preset"], + environmentOnly: true, + scope: "project-defaults", + }, ] as const; diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 7845cb9a75af0..b5c70e992b1ea 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -16,7 +16,7 @@ import { writeLocalStorageValue } from "../../hooks/useLocalStorage"; import type { MessageResolver } from "../../i18n/messages"; import { commandLabel } from "./KeybindingsSettings.logic"; import type { ResolvedSettingsScope } from "./settingsScope"; -import { FORK_SETTINGS_SEARCH_ITEMS } from "./forkSettingsSearchItems"; // Fork +import { FORK_SETTINGS_LABEL, FORK_SETTINGS_SEARCH_ITEMS } from "./forkSettingsSearchItems"; // Fork export type SettingsPath = | "/settings/projects" @@ -40,6 +40,7 @@ export type SettingsPath = | "/settings/secrets" | "/settings/maintenance" | "/settings/labs" + | "/settings/fork" // Fork | "/settings/about" | "/settings/archived"; @@ -115,6 +116,7 @@ export const SETTINGS_SECTION_LABELS: Readonly> = { "/settings/secrets": msg("Secrets"), "/settings/maintenance": msg("Maintenance"), "/settings/labs": msg("Labs"), + "/settings/fork": FORK_SETTINGS_LABEL, // Fork "/settings/about": msg("About"), "/settings/voice": msg("Voice"), "/settings/archived": msg("Archive"), @@ -156,6 +158,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ "/settings/browser", "/settings/devices", "/settings/scheduled-tasks", + "/settings/fork", // Fork ], }, { @@ -482,7 +485,7 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/threads", searchTerms: [msg("usage quota rate limit reset recover continue")], }, - ...FORK_SETTINGS_SEARCH_ITEMS, // Fork: waits and agent slots. + ...FORK_SETTINGS_SEARCH_ITEMS, // Fork: the rows of the Fork page. { id: "working-shelf", title: msg("Working section"), @@ -1484,6 +1487,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly ChatSettingsRoute, } as any) +const ChatSettingsForkRoute = ChatSettingsForkRouteImport.update({ + id: '/fork', + path: '/fork', + getParentRoute: () => ChatSettingsRoute, +} as any) const ChatSettingsDiffsRoute = ChatSettingsDiffsRouteImport.update({ id: '/diffs', path: '/diffs', @@ -307,6 +313,7 @@ export interface FileRoutesByFullPath { '/settings/devices': typeof ChatSettingsDevicesRoute '/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/settings/diffs': typeof ChatSettingsDiffsRoute + '/settings/fork': typeof ChatSettingsForkRoute '/settings/general': typeof ChatSettingsGeneralRoute '/settings/integrations': typeof ChatSettingsIntegrationsRoute '/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -352,6 +359,7 @@ export interface FileRoutesByTo { '/settings/devices': typeof ChatSettingsDevicesRoute '/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/settings/diffs': typeof ChatSettingsDiffsRoute + '/settings/fork': typeof ChatSettingsForkRoute '/settings/general': typeof ChatSettingsGeneralRoute '/settings/integrations': typeof ChatSettingsIntegrationsRoute '/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -399,6 +407,7 @@ export interface FileRoutesById { '/_chat/settings/devices': typeof ChatSettingsDevicesRoute '/_chat/settings/diagnostics': typeof ChatSettingsDiagnosticsRoute '/_chat/settings/diffs': typeof ChatSettingsDiffsRoute + '/_chat/settings/fork': typeof ChatSettingsForkRoute '/_chat/settings/general': typeof ChatSettingsGeneralRoute '/_chat/settings/integrations': typeof ChatSettingsIntegrationsRoute '/_chat/settings/keybindings': typeof ChatSettingsKeybindingsRoute @@ -446,6 +455,7 @@ export interface FileRouteTypes { | '/settings/devices' | '/settings/diagnostics' | '/settings/diffs' + | '/settings/fork' | '/settings/general' | '/settings/integrations' | '/settings/keybindings' @@ -491,6 +501,7 @@ export interface FileRouteTypes { | '/settings/devices' | '/settings/diagnostics' | '/settings/diffs' + | '/settings/fork' | '/settings/general' | '/settings/integrations' | '/settings/keybindings' @@ -537,6 +548,7 @@ export interface FileRouteTypes { | '/_chat/settings/devices' | '/_chat/settings/diagnostics' | '/_chat/settings/diffs' + | '/_chat/settings/fork' | '/_chat/settings/general' | '/_chat/settings/integrations' | '/_chat/settings/keybindings' @@ -787,6 +799,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatSettingsGeneralRouteImport parentRoute: typeof ChatSettingsRoute } + '/_chat/settings/fork': { + id: '/_chat/settings/fork' + path: '/fork' + fullPath: '/settings/fork' + preLoaderRoute: typeof ChatSettingsForkRouteImport + parentRoute: typeof ChatSettingsRoute + } '/_chat/settings/diffs': { id: '/_chat/settings/diffs' path: '/diffs' @@ -893,6 +912,7 @@ interface ChatSettingsRouteChildren { ChatSettingsDevicesRoute: typeof ChatSettingsDevicesRoute ChatSettingsDiagnosticsRoute: typeof ChatSettingsDiagnosticsRoute ChatSettingsDiffsRoute: typeof ChatSettingsDiffsRoute + ChatSettingsForkRoute: typeof ChatSettingsForkRoute ChatSettingsGeneralRoute: typeof ChatSettingsGeneralRoute ChatSettingsIntegrationsRoute: typeof ChatSettingsIntegrationsRoute ChatSettingsKeybindingsRoute: typeof ChatSettingsKeybindingsRoute @@ -923,6 +943,7 @@ const ChatSettingsRouteChildren: ChatSettingsRouteChildren = { ChatSettingsDevicesRoute: ChatSettingsDevicesRoute, ChatSettingsDiagnosticsRoute: ChatSettingsDiagnosticsRoute, ChatSettingsDiffsRoute: ChatSettingsDiffsRoute, + ChatSettingsForkRoute: ChatSettingsForkRoute, ChatSettingsGeneralRoute: ChatSettingsGeneralRoute, ChatSettingsIntegrationsRoute: ChatSettingsIntegrationsRoute, ChatSettingsKeybindingsRoute: ChatSettingsKeybindingsRoute, diff --git a/apps/web/src/routes/_chat.settings.fork.tsx b/apps/web/src/routes/_chat.settings.fork.tsx new file mode 100644 index 0000000000000..32aa2fd7a0391 --- /dev/null +++ b/apps/web/src/routes/_chat.settings.fork.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from "@tanstack/react-router"; +import { ForkSettingsPanel } from "../components/settings/fork/ForkSettingsPanel"; + +export const Route = createFileRoute("/_chat/settings/fork")({ + component: ForkSettingsPanel, +}); diff --git a/docs/fork/README.md b/docs/fork/README.md index f9bb384c46ea7..142305ed39ff3 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -11,8 +11,8 @@ fork switch is off by default, except one read-only refresh of usage limits. Server settings are in `settings.json` in the server's `userdata` folder (by default `~/.t3/userdata/settings.json`). The server reads the file again when it changes; no restart is -needed. Some fork settings also have a row in the app's **Settings** pages (named below). A -project's overrides are set in **Settings** with that project chosen at the top ("Applying settings +needed. Fork settings also have rows on the app's own **Settings → Fork** page (named below), with +one line per feature at the top saying whether it is on. A project's overrides are set in **Settings** with that project chosen at the top ("Applying settings for …", see [project settings](../user/project-settings.md)). An agent's tools cannot change any fork setting. @@ -143,7 +143,9 @@ Set in `settings.json`: { "usagePacing": { "": { "reservePercent": 20 } } } ``` -The key is the provider instance id, for example `codex` or `codex_work`. There is no Settings row for it yet. +The key is the provider instance id, for example `codex` or `codex_work`. In the app: **Settings → +Fork**, section Usage pacing, one row per account by its name (an entry for an account that is gone +is listed with **Remove**). ### `server.usagePacingGate` @@ -152,8 +154,8 @@ What happens when an agent starts a task with `delegate_task`. `"off"`: nothing, on an account that is ahead of its pace moves to another account of the same provider, runs at a lower effort (`usagePacingLowerEffort`), or is refused for now and the agent asks again later. -Switch on in `settings.json`: `"usagePacingGate": "advise"` (try `advise` before `enforce`). There -is no Settings row for it yet. +Switch on: **Settings → Fork**, section Usage pacing, "Usage pacing gate", or in `settings.json`: +`"usagePacingGate": "advise"` (try `advise` before `enforce`). ### `server.usagePacingLowerEffort` @@ -161,7 +163,8 @@ For `"enforce"`: what each effort level turns into while an account is ahead of account has room, for example `{ "high": "medium", "medium": "medium" }`. A task at a level not listed is held instead. Empty: no effort is ever lowered. -Set in `settings.json`: `"usagePacingLowerEffort": { "high": "medium" }`. +Set: **Settings → Fork**, "Lower effort when ahead of pace" (pairs like `high=medium`), or in +`settings.json`: `"usagePacingLowerEffort": { "high": "medium" }`. ### `server.waitFor` @@ -171,7 +174,7 @@ woken with the result. `wait_list` and `wait_cancel` list and end them. While of judged nor delivered; listing and cancelling still work. Other fields set deadlines, limits per thread and how often each kind is checked. -Switch on: **Settings → Threads**, section Waits (shown while a server is connected), "Let agents wait for events", or in `settings.json`: +Switch on: **Settings → Fork**, section Waits (shown while a server is connected), "Let agents wait for events", or in `settings.json`: `"waitFor": { "enabled": true }`. ### `server.waitChecks` @@ -181,7 +184,7 @@ fixed arguments, no shell; exit 0 means the event happened. It runs unsandboxed with the server's environment, so use fixed programs that run no files from the repository (no test runners or build scripts). Only the person can add one; agents cannot. -Add one: **Settings → Threads**, section Wait checks, **Add check**, or in `settings.json`: +Add one: **Settings → Fork**, section Wait checks, **Add check**, or in `settings.json`: ```json { "waitChecks": { "build-done": { "argv": ["test", "-f", "/tmp/build.done"] } } } @@ -255,7 +258,7 @@ valid (an unknown preset or key from a newer build, a bad runner) reads as off, a warning in the server log; it is kept as written, and saves of other settings write it back unchanged until the person saves this setting. -In the app: Settings, Threads, Review rules shows whether the rules are on and the values a lens +In the app: Settings, Fork, Review rules shows whether the rules are on and the values a lens would run with (each marked as the preset's or set by hand), with "Use recommended review rules" and "Turn off" buttons; it asks first before a button drops hand-set fields or an unreadable value. @@ -305,7 +308,7 @@ above `maxPerAccount` per provider account, or below `minFreeMemoryMb` of free m started in other ways are counted but never refused. With `waitFor` on, an agent can wait for a slot instead of retrying. -Switch on: **Settings → Threads**, section Agent slots, "Limit running agents", or in `settings.json`: +Switch on: **Settings → Fork**, section Agent slots, "Limit running agents", or in `settings.json`: `"agentSlots": { "enabled": true, "maxPerMachine": 4 }`. With `enabled` and no limits set, nothing is refused. @@ -417,7 +420,7 @@ server log), never as `handoff`. A project's own list of wait checks. It replaces the server's list for that project as a whole (a project lists every check it uses). Not set: the project uses the server's checks. -Set: **Settings**, choose the project at the top, then **Wait checks**. +Set: **Settings → Fork**, choose the project at the top, then **Wait checks**. ### `projectOverride.playtest` From 2a3b832dd0f9de74cf0f83f2ce126ec5eabfab2a Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:05 +0100 Subject: [PATCH 2/5] test(web): the reserve field saves on blur, as upstream's number field does Co-Authored-By: Claude Opus 5.5 --- .../settings/fork/UsagePacingSettings.browser.test.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx b/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx index ca4c3ebaabe57..e748bcfc1697c 100644 --- a/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx +++ b/apps/web/src/components/settings/fork/UsagePacingSettings.browser.test.tsx @@ -106,8 +106,9 @@ describe("UsagePacingSettings", () => { await expect.element(screen.getByText("Reserve on Codex B")).toBeVisible(); const reserve = screen.getByRole("textbox", { name: "Reserve on Codex B in percent" }); await expect.element(reserve).toHaveValue("0"); - await userEvent.clear(reserve); - await userEvent.type(reserve, "20{Enter}"); + // The number field saves when it loses focus. + await userEvent.type(reserve, "{Backspace}20"); + await userEvent.tab(); expect(state.update.mock.calls[0]![0]).toEqual({ usagePacing: { "codex-b": { reservePercent: 20 } }, }); From 92866ff8d1f83e8c9efaf86349415ec314852900 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:03:44 +0100 Subject: [PATCH 3/5] fix(web): Fork page rows lock every control, Overview follows the fork report, and a model policy row Fix round for the review of #543: - A managed-policy lock or a missing write permission now makes every control of a Fork row inert (the switches and lists below the title too), through a fork row wrapper; upstream's row only greys its main control. - The Overview reads where each feature is on with the fork report's own rules, now shared from the contracts (forkFeatures.ts): a project's override or one thread's handoff entry counts on a server screen, a project screen reads its effective value, and selected servers that differ show "Mixed". The fork report uses the same function, and the Overview's labels are typed by every feature, so the two cannot drift. - A reserve typed above 100 is saved as 100 and the field shows 100 again (the field restarts when the bound changes the number). - The lower-effort map refuses a level no model on the server offers (a typo such as hgih=medium). - Model policy (#268): a section in the Agents group after Usage pacing, server only: the mode, the allowed rows edited as JSON and checked as the server's save checks them, a warning with the kept text when the stored value cannot be read, an Overview line and search items. Co-Authored-By: Claude Opus 5.5 --- FORK_CHANGES.md | 60 ++--- apps/server/src/golive/forkReport.ts | 78 +----- .../src/components/settings/fork/ForkRow.tsx | 72 ++++++ .../settings/fork/ForkSettingsPanel.tsx | 11 +- .../settings/fork/ModelPolicySettings.tsx | 233 ++++++++++++++++++ .../fork/UsagePacingSettings.browser.test.tsx | 81 +++++- .../settings/fork/UsagePacingSettings.tsx | 62 +++-- .../settings/fork/forkStatus.logic.test.ts | 82 ++++-- .../settings/fork/forkStatus.logic.ts | 149 +++++++---- .../fork/modelPolicySettings.logic.test.ts | 47 ++++ .../fork/modelPolicySettings.logic.ts | 73 ++++++ .../fork/usagePacingSettings.logic.test.ts | 51 +++- .../fork/usagePacingSettings.logic.ts | 50 +++- .../settings/forkSettingsSearchItems.ts | 16 ++ docs/fork/README.md | 11 +- packages/contracts/src/forkFeatures.ts | 102 ++++++++ packages/contracts/src/forkSettings.ts | 1 + 17 files changed, 968 insertions(+), 211 deletions(-) create mode 100644 apps/web/src/components/settings/fork/ForkRow.tsx create mode 100644 apps/web/src/components/settings/fork/ModelPolicySettings.tsx create mode 100644 apps/web/src/components/settings/fork/modelPolicySettings.logic.test.ts create mode 100644 apps/web/src/components/settings/fork/modelPolicySettings.logic.ts create mode 100644 packages/contracts/src/forkFeatures.ts diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index bfa644f502644..c99b0ea304364 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -12,36 +12,36 @@ setting is missing here or a setting named here does not exist. ## In T3 Code itself -| Change | Why | Setting | Default | PR | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | -| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | -| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | -| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | -| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | -| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | -| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | -| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | off; rule only observes | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | -| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | -| The Settings page **Fork** (`/settings/fork`): every fork setting in one place, with one line per feature at the top saying whether it is on. So far: waits, wait checks, agent slots, usage pacing (per account by name) and review rules. | Change every fork setting without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots`, `server.usagePacing`, `server.usagePacingGate`, `server.usagePacingLowerEffort`, `server.reviewRules` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | -| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | -| The fork's service layers in the server are wired from one fork file (`apps/server/src/fork/forkLayers.ts`). | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#384](https://github.com/scuttletoby/t3code/pull/384) | -| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | -| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | -| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on, and where. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | -| A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | -| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | -| Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | -| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude applies the outside servers and refuses a turn when its profile cannot. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528) | -| Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | -| Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | -| Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | -| Handoff instead of compaction, part 1: the setting and the pure "should this thread hand off now?" decision. Nothing acts on it yet. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#282](https://github.com/scuttletoby/t3code/pull/282) | -| Review rules, part 1: the setting for how this machine runs a review lens (runner, state question), off by default; `{"preset": "recommended"}` turns the fork's defaults on. A bad hand edit reads as off and is kept. Nothing reads it yet. | The repo says what a pull request needs and CI enforces it; the machine says how reviews run. | `server.reviewRules`, `projectOverride.reviewRules` | off | [#291](https://github.com/scuttletoby/t3code/pull/291) | -| An interval setting the settings file cannot hold (negative, not finite, too large) is refused when saved; one already in the file reads as its default instead of resetting every setting. A test finds every interval setting from the schema. | A `1e400` saved as `null` made the next start reject the whole settings file. | none | always | [#323](https://github.com/scuttletoby/t3code/pull/323) | -| Handoff instead of compaction, part 2: the handoff service hands a big or idle thread to a fresh session in the same thread, with T3's state and the recent conversation, only while the thread is quiet and still at the run that triggered it. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#320](https://github.com/scuttletoby/t3code/pull/320) | -| A task delegated to a linked environment is still followed if the delegating call is cut off, and still delivers its reply when that environment runs another T3 version. | Its parent was never told: the task stayed running here and its result never arrived. | none | always | [#412](https://github.com/scuttletoby/t3code/pull/412), [#540](https://github.com/scuttletoby/t3code/pull/540) | -| Model policy, part 1: the setting for which models (and efforts) agents may pick, per provider driver: off, advise or enforce, and the allowed rows. A bad hand edit reads as nothing allowed. Nothing reads the setting yet. | Agents should use the models the person chose for each kind of work. | `server.modelPolicy` | off | [#268](https://github.com/scuttletoby/t3code/pull/268) | +| Change | Why | Setting | Default | PR | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | +| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | +| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | +| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | +| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | +| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | +| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | +| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | off; rule only observes | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | +| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | +| The Settings page **Fork** (`/settings/fork`): every fork setting in one place, with one line per feature at the top saying whether it is on. So far: waits, wait checks, agent slots, usage pacing (per account by name), model policy and review rules. | Change every fork setting without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots`, `server.usagePacing`, `server.usagePacingGate`, `server.usagePacingLowerEffort`, `server.reviewRules`, `server.modelPolicy` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | +| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | +| The fork's service layers in the server are wired from one fork file (`apps/server/src/fork/forkLayers.ts`). | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#384](https://github.com/scuttletoby/t3code/pull/384) | +| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | +| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | +| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on, and where. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | +| A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | +| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | +| Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | +| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude applies the outside servers and refuses a turn when its profile cannot. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528) | +| Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | +| Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | +| Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | +| Handoff instead of compaction, part 1: the setting and the pure "should this thread hand off now?" decision. Nothing acts on it yet. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#282](https://github.com/scuttletoby/t3code/pull/282) | +| Review rules, part 1: the setting for how this machine runs a review lens (runner, state question), off by default; `{"preset": "recommended"}` turns the fork's defaults on. A bad hand edit reads as off and is kept. Nothing reads it yet. | The repo says what a pull request needs and CI enforces it; the machine says how reviews run. | `server.reviewRules`, `projectOverride.reviewRules` | off | [#291](https://github.com/scuttletoby/t3code/pull/291) | +| An interval setting the settings file cannot hold (negative, not finite, too large) is refused when saved; one already in the file reads as its default instead of resetting every setting. A test finds every interval setting from the schema. | A `1e400` saved as `null` made the next start reject the whole settings file. | none | always | [#323](https://github.com/scuttletoby/t3code/pull/323) | +| Handoff instead of compaction, part 2: the handoff service hands a big or idle thread to a fresh session in the same thread, with T3's state and the recent conversation, only while the thread is quiet and still at the run that triggered it. | Long threads keep their children, PRs and waits instead of compacting. | `server.handoff`, `projectOverride.handoff` | off | [#320](https://github.com/scuttletoby/t3code/pull/320) | +| A task delegated to a linked environment is still followed if the delegating call is cut off, and still delivers its reply when that environment runs another T3 version. | Its parent was never told: the task stayed running here and its result never arrived. | none | always | [#412](https://github.com/scuttletoby/t3code/pull/412), [#540](https://github.com/scuttletoby/t3code/pull/540) | +| Model policy, part 1: the setting for which models (and efforts) agents may pick, per provider driver: off, advise or enforce, and the allowed rows. A bad hand edit reads as nothing allowed. Nothing reads the setting yet. | Agents should use the models the person chose for each kind of work. | `server.modelPolicy` | off | [#268](https://github.com/scuttletoby/t3code/pull/268) | ## Repository, CI and releases diff --git a/apps/server/src/golive/forkReport.ts b/apps/server/src/golive/forkReport.ts index 455c99050c812..71a631e5a1134 100644 --- a/apps/server/src/golive/forkReport.ts +++ b/apps/server/src/golive/forkReport.ts @@ -6,12 +6,9 @@ import * as NodeSqlite from "node:sqlite"; import * as NodeURL from "node:url"; import { - effectiveReviewRules, - FORK_PROJECT_SCOPED_KEYS, + FORK_REPORT_PROJECT_FEATURES, FORK_SERVER_SETTING_KEYS, - type HandoffSettings, - type PlaytestSettings, - type ReviewRules, + forkFeaturesWhere, type ServerSettings, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -534,75 +531,14 @@ function readSettings( } type ForkReportFeature = keyof ForkReport["fork"]["features"]; -type ForkProjectScopedKey = (typeof FORK_PROJECT_SCOPED_KEYS)[number]; -/** - * The counted features a project's override can switch on: the report reads each one's override in - * every project. A test holds it to every counted feature that is also a project-scoped setting. - */ -export const FORK_REPORT_PROJECT_FEATURES = [ - "reviewRules", - "handoff", - "playtest", -] as const satisfies ReadonlyArray; -type ForkReportProjectFeature = (typeof FORK_REPORT_PROJECT_FEATURES)[number]; +/** The counted features a project's override can switch on (the rules live in the contracts). */ +export { FORK_REPORT_PROJECT_FEATURES }; -/** Where each counted feature is on in `settings`: `server`, `project:` or a thread's entry. */ -function whereEachFeature( +/** Where each counted feature is on in `settings`, by the rules the Fork settings page reads too. */ +const whereEachFeature = ( settings: ServerSettings, -): Record> { - // A project's override replaces the server's value for that project, so it can switch a feature - // on while the server's is off. A bad value already reads as off (the settings decode). - const overrides = (key: K) => - Object.entries(settings.projectSettingsOverrides).map( - ([projectId, project]) => [projectId, project[key]] as const, - ); - const server = (on: boolean) => (on ? ["server"] : []); - const perProject = { - reviewRules: whereOn(settings.reviewRules, overrides("reviewRules"), reviewRulesOn), - handoff: whereOn(settings.handoff, overrides("handoff"), handoffWhere), - playtest: whereOn(settings.playtest, overrides("playtest"), playtestOn), - } satisfies Record>; - return { - agentSlots: server(settings.agentSlots.enabled), - waitFor: server(settings.waitFor.enabled), - usagePacingGate: server(settings.usagePacingGate !== "off"), - automaticUpdates: server(settings.automaticUpdates), - ...perProject, - modelPolicy: server(settings.modelPolicy.mode !== "off"), - activityProbe: server(settings.activityProbe), - }; -} - -/** Where a value switches its feature on, below `at` (`server` or `project:`). */ -type WhereOn = (value: T, at: string) => ReadonlyArray; -const when = - (isOn: (value: T) => boolean): WhereOn => - (value, at) => - isOn(value) ? [at] : []; -const reviewRulesOn = when((value: ReviewRules) => effectiveReviewRules(value).preset !== "off"); -const playtestOn = when((value: PlaytestSettings) => value.enabled); -/** The value's own mode, and each thread whose entry is `handoff` (it wins over the mode). */ -const handoffWhere: WhereOn = (value, at) => [ - ...(value.mode === "handoff" ? [at] : []), - ...Object.entries(value.threads) - .filter(([, mode]) => mode === "handoff") - .map(([threadId]) => `${at === "server" ? "" : `${at}/`}thread:${threadId}`), -]; - -/** Where the server's value and each project's (not set or null: the server's) is on. */ -function whereOn( - server: T, - projects: ReadonlyArray, - where: WhereOn, -): ReadonlyArray { - return [ - ...where(server, "server"), - ...projects.flatMap(([projectId, value]) => - value == null ? [] : where(value, `project:${projectId}`), - ), - ]; -} +): Record> => forkFeaturesWhere(settings); /** The report as the command prints it: indented JSON. */ export const formatForkReport = (report: ForkReport): string => JSON.stringify(report, null, 2); diff --git a/apps/web/src/components/settings/fork/ForkRow.tsx b/apps/web/src/components/settings/fork/ForkRow.tsx new file mode 100644 index 0000000000000..11f3fb1216d69 --- /dev/null +++ b/apps/web/src/components/settings/fork/ForkRow.tsx @@ -0,0 +1,72 @@ +/** + * Fork: a settings row whose every control follows the row's lock. Upstream's row greys out only its + * main control under an administrator's lock, and its sub-controls only when it is server-scoped; + * the Fork page's rows keep switches, lists and text boxes below the title, so those are made inert + * too. The server refuses such a write anyway; this only keeps a click from ending in an error. + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ +import { isManagedSettingPath } from "@t3tools/contracts"; +import { type ComponentProps, useState } from "react"; + +import { IntervalSecondsField } from "../IntervalSecondsField"; +import { useSettingsScope } from "../SettingsScopeContext"; +import { SettingsRow } from "../settingsLayout"; +import { useScopedSettingsWriteAllowed } from "../useScopedSettings"; + +/** Why the row's setting cannot be changed here: an administrator's lock or no write permission. */ +function useForkRowLock(paths: ReadonlyArray): string | undefined { + const { connectedEnvironments } = useSettingsScope(); + const writeAllowed = useScopedSettingsWriteAllowed(); + const organization = connectedEnvironments + .map((environment) => environment.serverConfig?.managedPolicy) + .find( + (policy) => policy !== undefined && paths.some((path) => isManagedSettingPath(policy, path)), + )?.organization; + if (organization !== undefined) return `Managed by ${organization}.`; + if (!writeAllowed) return "This connection lacks permission to change settings here."; + return undefined; +} + +/** A settings row locked by `lockPaths` (setting keys or dot paths): its control and children alike. */ +export function ForkRow({ + lockPaths, + children, + ...props +}: ComponentProps & { readonly lockPaths: ReadonlyArray }) { + const lock = useForkRowLock(lockPaths); + return ( + + {lock === undefined || !children ? ( + children + ) : ( +
+ {children} +
+ )} +
+ ); +} + +/** + * Upstream's number field, with the value bounded before it is saved. When the bound changes the + * typed number, the field starts again from the saved value; otherwise it would keep showing the + * typed number, as the saved value (and so the field's prop) may not change. + */ +export function BoundedNumberField({ + bound, + onCommit, + ...props +}: ComponentProps & { readonly bound: (value: number) => number }) { + const [resets, setResets] = useState(0); + return ( + { + const bounded = bound(value); + if (bounded !== value) setResets((count) => count + 1); + onCommit(bounded, options); + }} + /> + ); +} diff --git a/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx b/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx index 4aa101d3e51a7..95a3da387ea91 100644 --- a/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx +++ b/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx @@ -3,15 +3,16 @@ * mounts the fork's own panels; a project screen shows only the settings a project may override. */ /* oxlint-disable t3code/no-untranslated-copy -- Fork: this page is the fork's own and its text is English only; upstream's translation catalogs hold no fork keys. */ +import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; import type { ReactNode } from "react"; import { ReviewRulesSettings } from "../ReviewRulesSettings"; import { useSettingsScope } from "../SettingsScopeContext"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "../settingsLayout"; import { useSearchableSetting } from "../settingsSearch"; -import { useScopedSettings } from "../useScopedSettings"; import { WaitsAndSlotsSettings } from "../WaitsAndSlotsSettings"; import { forkFeatureStatuses } from "./forkStatus.logic"; +import { ModelPolicySettings } from "./ModelPolicySettings"; import { UsagePacingSettings } from "./UsagePacingSettings"; export function ForkSettingsPanel() { @@ -35,6 +36,7 @@ export function ForkSettingsPanel() { {isProjectScope ? null : } + {isProjectScope ? null : } @@ -45,12 +47,15 @@ export function ForkSettingsPanel() { function ForkStatusSection() { const searchableSetting = useSearchableSetting(); - const statuses = forkFeatureStatuses(useScopedSettings()); + const { targets } = useSettingsScope(); + const statuses = forkFeatureStatuses( + targets.length > 0 ? targets : [{ projectId: null, settings: DEFAULT_SERVER_SETTINGS }], + ); return (
    {statuses.map((status) => ( diff --git a/apps/web/src/components/settings/fork/ModelPolicySettings.tsx b/apps/web/src/components/settings/fork/ModelPolicySettings.tsx new file mode 100644 index 0000000000000..e2dd9d813d266 --- /dev/null +++ b/apps/web/src/components/settings/fork/ModelPolicySettings.tsx @@ -0,0 +1,233 @@ +/** + * Fork: the model policy (`modelPolicy`), which models agents may pick. Server-wide (a project cannot + * override it), so a project screen does not show it. A save sends the whole value, `mode` and + * `allow`, as the server requires. Every write is an ordinary settings patch from the person at the + * screen; agents cannot change it. + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: this panel is the fork's own and its text is English only; upstream's translation catalogs hold no fork keys. */ +import { + DEFAULT_MODEL_POLICY, + type ModelPolicy, + type ModelPolicyMode, + type ModelPolicyPatch, +} from "@t3tools/contracts"; +import { useState } from "react"; + +import { Button } from "../../ui/button"; +import { + Dialog, + DialogDescription, + DialogFooter, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, +} from "../../ui/dialog"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../../ui/select"; +import { Textarea } from "../../ui/textarea"; +import { useSettingsScope } from "../SettingsScopeContext"; +import { SettingResetButton, SettingsSection } from "../settingsLayout"; +import { useSearchableSetting } from "../settingsSearch"; +import { useScopedSettings, useUpdateScopedSettings } from "../useScopedSettings"; +import { targetsDiffer } from "../waitsAndSlotsSettings.logic"; +import { ForkRow } from "./ForkRow"; +import { + MODEL_POLICY_MODE_OPTIONS, + modelPolicyAllowText, + modelPolicyRowLine, + unreadableModelPolicyText, + withModelPolicyAllow, +} from "./modelPolicySettings.logic"; + +const MIXED = "The selected environments have different values. Select one environment to edit it."; + +function AllowDialog({ + value, + onOpenChange, + onSave, +}: { + readonly value: ModelPolicy; + readonly onOpenChange: (open: boolean) => void; + readonly onSave: (next: ModelPolicyPatch, onSaved: () => void, onFailed: () => void) => void; +}) { + const [text, setText] = useState(() => modelPolicyAllowText(value)); + const [error, setError] = useState(null); + const [saving, setSaving] = useState(false); + const save = () => { + if (saving) return; + const result = withModelPolicyAllow(value.mode, text); + if ("error" in result) { + setError(result.error); + return; + } + setError(null); + setSaving(true); + onSave( + result.value, + () => onOpenChange(false), + () => { + setSaving(false); + setError("The server refused the rows; your text is kept to fix and save again."); + }, + ); + }; + return ( + + + + Edit allowed models + + A JSON list, as in the settings file. Each row names a driver (such as claudeAgent or + codex) and a model; efforts limits its efforts (a row without it checks only the model), + defaultEffort is one of them, and useFor is a note shown to agents. + + + +