diff --git a/AGENTS.md b/AGENTS.md index d8210a7..f0a7929 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,8 @@ Host bundle (`lib/index.mjs`), a thin `apply` barrel over small modules: - `scripts/report-host-drift.ts` — the nightly harness-drift report (CI's `host-drift` job, schedule and dispatch only): reads the registry the way the records are defined (`dsh` as the newest build any dist-tag carries on the record's line, or a newer stable release under the tag the record names for its line graduating, `graduatesUnder`; pi's range, floor and newest, and every cordis-family member at the floor of the range the tagged cluster declares) and prints one `::warning::` per compared field that moved, exiting 0 whatever it finds, because a channel moving is the harness's release, not a regression. Its rules are `scripts/host-drift.ts` (`readChannel`, the one reading, and `hostDrift`, both pure), held by `test/host-drift.test.ts` with known answers and the job's evaluated condition, and its CLI by `test/mock/host-drift-cli.mock.ts` against a loopback registry (it binds a socket, so it is the mock suite's). The packument reads are `scripts/registry-view.ts`, shared with the proposal below. - `scripts/propose-host-bump.ts` · `scripts/host-bump.ts` — the nightly bump proposal (the same job, schedule only): plans each channel from the report's own reading (`bumpPlan`: `current`; `blocked` on any unread answer; `waiting` while the new `dsh` or pi is inside pnpm's one-day release-age window, which it never lifts; `range` for a cut that opens a prerelease tuple the peer ranges do not admit, moves the bridge's pi range or sits under a dist-tag the record type does not admit; else `data`; a dist-tag moves only with `dsh`, so a plan is `current` exactly when the report has no line for it) and, with `--write`, moves CONTRIBUTING's release-step-3 data and nothing else — the record (`withRecord`), alpha's pins (`channelManifest`), the README pair's "today" sentences (`withReadmePolicy`, a value both channels share left for review unless both records move it to the same value), the root lockfile and the rc relock — for CI to push as `chore/host-bump`, dispatching the floor cells (with the keyed e2e tier off) when `piFloor` or a family field moved. Both lockfiles hold one pi, so a proposed pi move carries every record (`coupleSharedPi`: a channel waiting only on its own young cut takes a pi-only move when its recorded pi range admits it; one that cannot, a dsh-only proposal included, holds the pi move as `blocked`). It never edits a measured table, and runs no test: the proposed pull request's CI is the run. CI writes the plan in a step with no token in its environment (which holds because nothing approves a dependency build script, so the install runs none of the cut's code; `test/host-drift.test.ts` names an approval in every source the pinned pnpm reads, which are `pnpm-workspace.yaml`, a `PNPM_CONFIG_*` variable and a CLI flag in the step, the proposer or the rc relock, and a pnpmfile at the root or named by any of them, and in the older spellings pnpm 12 ignores), and a second step pushes it; **an open proposal is the reviewer's**: one with the same target (the marker line its body ends with, `bumpTarget`: every proposed record in full, never the title) is left alone, and a newer target rebuilds the branch only while every commit on it is the nightly's own, as author and as committer (only this repository's own branch is the proposal). `host-bump.ts` is pure (`test/host-bump.test.ts`), the text half of `--write` included (`applyBumpTexts`: every edit, each README plan checked against the other channel's record now and as proposed; the CLI only writes what it returns and runs the installs); the CLI runs against a loopback registry in `test/mock/host-drift-cli.mock.ts` (its `--out` files, the pi coupling, and on a scratch copy through `--root` a successful `--write`'s `files` list and a failed one's put-back); the two CI steps are executed with stub tools in `test/host-drift.test.ts`. - `scripts/use-channel.ts` — switches the dev install: `rc` or `alpha` installs that channel's committed lockfile (unpatched pi at the newest version the bridge's range admits, what an npm user runs), and `--floor` the same cluster with pi at the range's floor, never committed. It restores every tracked file it touched, so a switch leaves no diff. Its pure half is `scripts/channel-manifest.ts` (`channelManifest`, `pinFor`, `workspaceWithPi`, and `withoutHostPackages`, the lockfile `rc --relock` starts from), held by `test/use-channel.test.ts`. A relock keeps the cordis family at the record's floors because `package.json` pins every member the install resolves (include, group and cosmokit too, which arrive transitively and would otherwise resolve to the newest patch inside their `~` ranges) and `pinFor` moves each with the channel. `rc --relock` belongs in the same commit as ANY change to `package.json`'s dependencies or `pnpm-workspace.yaml`'s catalog or overrides, not only a channel bump: the rc lockfile carries every specifier the root one does and CI installs it frozen, and `test/harness-channel.test.ts` fails, naming the command, when they disagree. Dependabot ignores the cluster and pi, which move only as a channel bump. **This repository carries no pi patch** (D14''): an npm install runs pi unpatched, the harness's patch reaches users only through the desktop app and touches nothing the plugin reads, and a version-keyed patch would break every pi bump. `test/architecture.test.ts` keeps it that way by failing if `src` ever reads a streamed tool-call delta, partial arguments or a thought signature. -- `src/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema and its defaults; dependency-free readers and type guards. The client bundle may import these, and it does — along with the contract and presentation modules (`usage-contract.ts`, `settings-copy.ts`, `settings-fields.ts`, `usage-ui.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`, `opencode-store-contract.ts`). The rule is not a list of names: **the client may import a module that reaches nothing host-only** — no cordis context, no credential seam, no node built-in — and `test/architecture.test.ts`'s client-bundle block ("the client bundle reaches nothing host-only") is what enforces it: it walks the entry's import graph, and the unit suite fails the build rather than anyone having to remember. An earlier version of this line named two files as the only ones allowed, which the tree had already outgrown. +- `src/settings-table.ts` — the one field table: a row per setting (its kind, default, choice values, volatile flag and card group), from which `config.ts` derives the schema, the resolver, the config types, the defaults and the config-only list (`CONFIG_ONLY_FIELDS`), `settings-fields.ts` derives the card's field specs, `settings-copy.ts` checks the copy keys a card row implies, and `test/manifest.test.ts` holds `cordis.patch.yml`'s header to it (order, type labels, defaults, choice values). **Adding a setting is one row there plus its copy when the card shows it**, and a card row without its label, hint, option or group copy fails to compile. The schema descriptions and the config-only reasons are a second export, `SETTING_PROSE`, which only the host-side `config.ts` imports, so the bundler drops it from the page (`test/client-bundle.test.ts` pins that). +- `src/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema, the resolver and their defaults, read off the table; dependency-free readers and type guards. `config.ts` is host-side: it imports schemastery, so the client imports the table and never the schema (`test/architecture.test.ts` checks the client graph never reaches it). The client bundle may import the other two, and it does — along with the contract and presentation modules (`usage-contract.ts`, `settings-copy.ts`, `settings-fields.ts`, `settings-table.ts`, `usage-ui.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`, `opencode-store-contract.ts`). The rule is not a list of names: **the client may import a module that reaches nothing host-only** — no cordis context, no credential seam, no node built-in — and `test/architecture.test.ts`'s client-bundle block ("the client bundle reaches nothing host-only") is what enforces it: it walks the entry's import graph, and the unit suite fails the build rather than anyone having to remember. An earlier version of this line named two files as the only ones allowed, which the tree had already outgrown. ## `src/utils/` — pure by construction, enforced by test @@ -131,7 +132,7 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `src/opencode-store.ts` — reading the credentials an OpenCode installation already holds, through `node:sqlite`. Two rules shape it: nothing throws (a missing file, a foreign schema and `:memory:` all answer `undefined`), and a value never leaves the return value — no log line, no error message, no client bundle. `node:sqlite` is host-only, which is what keeps the module on the host side of the bundle rule. It is reached only through `resolveOpencodeStoreKey`, which is the last step of every key-source policy and is off unless `readOpencodeStore` is on. Its second reader, `inspectOpencodeStore`, answers the _other_ question — "is there a credential here, and whose is it?" — with a sanitized summary (email, org, kind, expiry) and never the token, which is what lets the settings card show the evidence beside the permission. - **What the plugin page shows is `docs/detail.md`, not the README.** The page renders one document: the Markdown `meta.detail` in `locale/.json` names, else the whole `README.md`. This package declared nothing for years, so its page carried 461 lines of engineering notes above the settings card. It now declares a page per language that is **one image and nothing else** — a UI preview of the card and the meter (`docs/media/preview.svg`, `.zh.svg`) — which is the shape the upstream plugins use, because the header above the card already carries the title and the one-sentence description. The image is served from the package, so `files` has to ship it (the detail-image route reads package-relative paths). `test/plugin-detail.test.ts` holds the contract: a declared detail in every locale, a path that exists AND is shipped, an image that does the same, and a page that is the picture and nothing else. - `src/opencode-store-contract.ts` · `src/opencode-store-service.ts` — the inspection seam: the sanitized summary type both sides share, and the host service that produces it. The contract is pure data (no `node:`, no context), so the client bundle may import it; the service is the half that touches `node:sqlite` and the filesystem, and it rewrites the store path to `~`-relative before answering — a home directory is a fact about the machine, not about the plugin. `inspect` is declared through the `Object.defineProperty` marker rather than `@Remote`, for the reason `usage.ts` documents. -- **The login stack is not in this tree.** It lives on the `v2` bookmark, and the map used to describe it here for years after it left — nine modules a reader could not find. What this tree carries is the API-key path only; a login grant is the other half, and reviving it is a days-scale port rather than a rebase (`v2` is 163 commits behind, and its `src/index.ts` exports a module the tree no longer has). The settings copy still holds its strings, and `credentialOrg` is the one remnant with behaviour: a configured org is sent as `x-opencode-org-id`. +- **The login stack is not in this tree.** It lives on the `v2` bookmark, and the map used to describe it here for years after it left — nine modules a reader could not find. What this tree carries is the API-key path only; a login grant is the other half, and reviving it is a days-scale port rather than a rebase (`v2` is 163 commits behind, and its `src/index.ts` exports a module the tree no longer has). `credentialOrg` is the one remnant with behaviour: a configured org is sent as `x-opencode-org-id`. - A timing dependency every remote shares, worth knowing before debugging a row that will not appear: the mount is an async `$mount` started in an effect, and the card reads `ctx.remote.` SYNCHRONOUSLY when its injector builds the props. If the injector runs before the mount resolves, the service is not there yet and the surface renders nothing. More often the cause is a namespace with no client descriptor at all — the purge row and the store-inspection row each shipped that way — which `test/remote-contract.test.ts` now catches per method. Each caller reports an empty lookup (`no opencodeStore service on the remote`, `no opencodeGoUsage service on the remote`, with the keys the remote does expose), so the symptom is a console line rather than a blank. And since P5 the host services go with the plugin's last activation: a reload unloads before it applies again, which leaves a short window in which a call finds no active Remote method (the meter's poll retries; a purge click there reports the host's refusal), and disabling the plugin withdraws all three, including the `opencodeGoUsage` instance the sibling `dsh-opencode-go` account page reads. diff --git a/README.md b/README.md index bd6c1fb..9c64467 100644 --- a/README.md +++ b/README.md @@ -223,7 +223,7 @@ Hovering the trigger explains its own number; clicking it opens the panel. The s ### Settings card — _Settings → Plugins → OpenCode Patch_ -Nine controls in four sections — the decisions a user actually makes. Everything renders from the platform's own primitives (`Switch`, `Tag`, `Button`, host tokens), and every knob carries a hint plus a reset-to-default affordance. +Nine controls in four sections — the decisions a user actually makes. Everything renders from the platform's own primitives (`Switch`, `Tag`, `Button`, host tokens), and every knob carries a hint plus a reset-to-default affordance. A change takes effect the next time the plugin is applied (disable and re-enable it, or restart `dsh`), as the card says above its controls. | Section | Control | Default | What it does | | :-- | :-- | :-: | :-- | diff --git a/README.zh-CN.md b/README.zh-CN.md index ac3d36b..7243fbc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -109,7 +109,7 @@ npm install dsh-opencode-patch **4. 重启 `dsh web`。** 宿主 bundle 只在启动时导入(`hmr root: []`),因此要重启才会加载 `lib/index.mjs`;客户端 UI 变更(`lib/client.js`)只需刷新浏览器。 -完成——**OpenCode 补丁设置**卡片会出现在 _Settings → Plugins_ 下,一旦有 OpenCode 模型激活,计量表就会挂载到输入框停靠栏。 +完成——**OpenCode 补丁**卡片会出现在 _Settings → Plugins_ 下,一旦有 OpenCode 模型激活,计量表就会挂载到输入框停靠栏。 --- @@ -215,13 +215,13 @@ Zen 的 provider 级 SDK 是 `@ai-sdk/openai-compatible`。models.dev **只在 | :-- | :-- | :-- | | **计量表触发按钮** | 输入框停靠栏,模型选择器旁 | Go:圆环 + 该窗口的百分比。Zen:本会话消费额,**不画圆环** | | **计量表面板** | 点击触发按钮 | 三个窗口、月度额度、本会话消耗、Zen 余额、操作链接 | -| **设置卡片** | _Settings → Plugins → OpenCode 补丁设置_ | 九个控件,上方另有一份实时 Go 用量摘要 | +| **设置卡片** | _Settings → Plugins → OpenCode 补丁_ | 九个控件,上方另有一份实时 Go 用量摘要 | 悬停触发按钮解释它自己的数字;点击打开面板。下面逐节展示每个界面,逐状态的行为见 [docs/quota-meter.zh-CN.md](./docs/quota-meter.zh-CN.md)。 -### 设置卡片 — _Settings → Plugins → OpenCode 补丁设置_ +### 设置卡片 — _Settings → Plugins → OpenCode 补丁_ -四个分区共九个控件——都是用户真正会做出的决定。所有控件都基于平台自身的原语渲染(`Switch`、`Tag`、`Button`、宿主 token),每个配置项都带提示以及恢复默认的操作。 +四个分区共九个控件——都是用户真正会做出的决定。所有控件都基于平台自身的原语渲染(`Switch`、`Tag`、`Button`、宿主 token),每个配置项都带提示以及恢复默认的操作。更改在插件下次应用时生效(停用后重新启用插件,或重启 `dsh`),卡片在控件上方也这样说明。 | 分区 | 控件 | 默认 | 作用 | | :-- | :-- | :-: | :-- | diff --git a/cordis.patch.yml b/cordis.patch.yml index edec176..d3ba804 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -12,7 +12,14 @@ # # Shown in the settings card (Settings -> Plugins -> OpenCode Patch). These are # the decisions a user actually makes: behaviour toggles, plus the credential -# policy. See src/settings-fields.ts CARD_FIELDS. +# policy. In the card's order; the source is src/settings-table.ts, read as +# src/settings-fields.ts CARD_FIELDS. +# endpoint: string endpoint family: auto | modern | legacy (default 'auto', an alias of +# modern). modern = the per-protocol inference family; legacy = one base +# per plane. +# keySource: string which credential source wins: auto | request | configured (default 'auto'). +# readOpencodeStore: boolean read the credential an OpenCode installation already holds, as the LAST +# resort after every declared one (default false). # injectUserAgent: boolean restore OpenCode CLI User-Agent stripped by DSH adapter (default true). # injectOriginHeaders: bool inject x-opencode-client (default true). # injectProject: boolean attach active workspace project in x-opencode-project (default true). @@ -20,32 +27,28 @@ # model discovery; off leaves both raw (default true). # injectCoreTools: boolean auto-inject read & bash tool schemas on free models (default true). # usageEnabled: boolean enable host-side OpenCode Go usage querying (default true). -# keySource: string which credential source wins: auto | request | configured (default 'auto'). -# readOpencodeStore: boolean read the credential an OpenCode installation already holds, as the LAST -# resort after every declared one (default false). -# endpoint: string endpoint family: auto | modern | legacy (default 'auto', an alias of -# modern). modern = the per-protocol inference family; legacy = one base -# per plane. # # Config-only overrides — the card deliberately hides these, because each is a # literal, a marker, or a reference whose default fits every documented setup. -# See src/settings-fields.ts CONFIG_ONLY_FIELDS. -# providers: [string] route ids whose turns this plugin decorates (default: opencode, -# opencode-go; both planes are always included, so only a relay route -# needs adding). +# In the table's order; the source is src/settings-table.ts, read as +# src/config.ts CONFIG_ONLY_FIELDS. +# credentialOrg: string org id (wrk_...) sent with an account credential that came from elsewhere. +# debug: true|false log every streamed call that receives the header to the console +# (default false). +# debugFile: path optional JSONL file for the request and stream debug entries; naming +# it writes the file whether or not debug is on. # userAgent: string optional custom User-Agent override (default empty = use OpenCode CLI UA). # originClient: string x-opencode-client value (default 'cli'). # sessionIdEnv: string env var carrying a caller-supplied session id (default 'OPENCODE_SESSION_ID'). # freeModelMarker: string model-id substring getting the core-tool fallback ('*' = all; a blank # value inherits the default 'free'; models the catalog marks free always # qualify). +# providers: [string] route ids whose turns this plugin decorates (default: opencode, +# opencode-go; both planes are always included, so only a relay route +# needs adding). # gatewayUrls: [string] URL substrings marking OpenCode gateway traffic (default both # families: ['opencode.ai/zen', 'opencode.ai/inference']). # usageBaseURL: string OpenCode Go gateway base URL (default 'https://opencode.ai/zen/go/v1'). -# credentialOrg: string org id (wrk_...) sent with an account credential that came from elsewhere. -# debug: true|false log every streamed call that receives the header to the console. -# debugFile: path optional JSONL file for the request and stream debug entries; naming -# it writes the file whether or not debug is on. - insert: - id: dsh-opencode-patch name: "dsh-opencode-patch" diff --git a/docs/improvement-plan.md b/docs/improvement-plan.md index 276accf..1b028a1 100644 --- a/docs/improvement-plan.md +++ b/docs/improvement-plan.md @@ -37,7 +37,7 @@ Phases land as **stacked pull requests**. The open ones are rebased, each onto i | P5 | | `fix:` the remote services follow the plugin's latest activation and go with its last | in review | **on P-R3**; `installRemoteService` (`src/host/remote.ts`) mounts the three services (usage, purge, store inspection), one per root while a live activation holds it, reading the latest live activation's options and disposed with the last activation, so the usage settings apply the next time the plugin is applied (a disable and re-enable, or a restart) and a disable withdraws all three; each mount is reported through the activation's logger once it has settled (no false "did not register" on a healthy boot, a refused mount said by name); the provide arm is dropped (`KNOWN_DEFECT P5` flipped); L1's warn-once, which treats any live patch of the plugin's as in place. Retitled from `refactor:`, because the README announces it and the changelog must carry it (P-H's precedent; a `refactor` is hidden from it); the owner may override at landing, and keeping `refactor:` drops the README pair with it | | P6 | | `fix:` the fetch patch's credential fill | in review | **on P5**; one resolver for an empty or placeholder wire key (`src/credentials.ts` over the pure `src/utils/credential-policy.ts`), a capture store per root that keeps a key only from a decorated turn (OC3) and drops it after a second well-formed 401 in a row (L8), the global fetch install in `src/host/global-fetch.ts` (any disposal order ends at the fetch that was there; both `KNOWN_DEFECT P6` assertions flipped), the plane headers set per call through pi-ai's `prepareHeaders` with the host's `llm-pi-ai/request-headers` waterfall run on the planes (OC4, OC5), the seam's floor stated in the README pair with the typert peer kept as it was (OC11), and a parity pin over the four deciders landed first. Retitled from `refactor:` (P-H's and P5's precedent): the pull request's title is the release signal under squash, a `refactor` is hidden from the changelog, and the phase carries behaviour changes the README pair announces (OC3, L8, the placeholder filter at every exit, the disposal order, the per-call headers). No `!` and no BREAKING CHANGE footer (1.x minors only). The peer narrowing was decided at landing: it landed as its own commit and was reverted at landing, keeping the old range, a decision taken for the owner and recorded as such (design item 14) | | P7 | | `refactor:` one source per table | in review | **on P6**; one route-to-plane table (`src/utils/planes.ts`: `PLANE_OF_ROUTE`, the exact `planeOfPlaneRoute` and the relay-inclusive `planeForRoute`) with `planeForUrl` beside `isGoPlaneUrl`, one `formatUsd` with two named styles (`src/utils/usd.ts`), one spec lookup (`specOn`/`specFor` in `src/models-catalog.ts`) and `liveCatalogOn`, the last capitalised level name read from `effortName`; L6's client-generation table (`src/utils/client-generation.ts`, 1.x emulated, 2.x recorded and unread) and L11's measured-window table (`src/utils/context-windows.ts`, shipped empty); the Mistral rationale reworded to the plugin's own rule. No behaviour change: the caller pins (`test/plane-table.test.ts`, `test/usd-callers.test.tsx`, the level-name and User-Agent cases, a per-plane purge case, the credential variable's exact-route edges and the meter's no-key refusal per route) were green on the base and land unchanged | -| P8 | | `refactor:` settings table | planned | | +| P8 | | `fix:` the card says when its settings apply, over one settings table | in review | **on P7**; one field table (`src/settings-table.ts`: `SETTINGS`, a row per key, and `SETTING_PROSE`, its host-only prose) from which `config.ts` derives the schema, resolver, types, defaults and config-only list, `settings-fields.ts` the card specs, and `settings-copy.ts` checks the copy keys; `cordis.patch.yml`'s header held to it by order, type label, stated default and choice values; fifteen dead copy keys and the meter's `modelMarkers` prop deleted, the zh README's stale name for the card replaced by the package's `meta.title`, and the card says its settings apply on re-apply (performed on the real host in both channels: a volatile edit of the plugin's row commits in place and the plugin follows it only once re-applied). No setting changed: the schema, resolver and card pins (`test/settings-snapshot.test.ts`) were green on the base and land unchanged but for the named edits (the copy keys, `CONFIG_DEFAULTS`' `credentialOrg: undefined`, the resolved type's modifiers). Retitled from `refactor:` (P-H's, P5's and P6's precedent): under squash the pull request's title is the release signal and a `refactor` is hidden from the changelog, while the phase ships a visible card line and the README pair's re-apply sentence. No `!` and no BREAKING CHANGE footer (1.x minors only); the owner may keep `refactor:` at landing, and the card line then ships without a changelog entry | | P9 | | `refactor:` remote seam | planned | | | P10a | | `refactor:` pure module moves | planned | | | P10b | | `fix:` catalog state | planned | | @@ -486,7 +486,10 @@ What stays private is pinned by contract tests against the real host packages: - **The per-call mark is per turn, on one activation's state (open).** `callHeadersFor` sets `perCall` on the turn state of the activation whose route claim built the adapter, for the rest of the turn. (a) A later request of that turn carrying a well-formed `x-opencode-session` is left unshaped by the fetch patch, whoever wrote the header. (b) With two live activations on one root (two entries of the plugin; cordis disposes before it re-applies), the other activation's stream hook has its own turn store with no mark, so its nested patch rewrites every plane header, a request-headers contributor's change and the minted `x-opencode-request` included; before P6 both patches rewrote them anyway, so nothing regressed. The tighter mechanism, when one is wanted, marks the request rather than the turn: the patch stands down only when the session on the wire equals the value the per-call seam wrote (`state.value`), or the mark is kept per root so every activation's patch sees it. - **L4, not decided.** P-R2's rows measured nothing about `x-opencode-request`; it is sent as before, now from the shared header table, so the decision is one line when a variants run answers. The tier-A case that asserts it on every protocol is labelled a characterization, and the decision is carried to P10a's row with the next variants run. 15. **P7 `refactor:` one source per table.** One `planeForRoute` (four copies today), `formatUsd` and `specFor`; delete the duplicate `ALL_THINKING_LEVELS` and the capitalisation copies. **As landed:** the route-to-plane rule had eleven copies in nine files (`catalogPlaneForRoute`, `isZenProvider`'s inline rule, `tierForRequest`, `resolveDiscoveryProvider` and `servedPlane`, the route claim's two catalog and family picks, the plane adapter's auth, the purge action's table, the credential variable a plane asks for, the meter's Zen-overflow check), now `PLANE_OF_ROUTE` read through `planeOfPlaneRoute` (exact) or `planeForRoute` (relays included, case-sensitive; `isZenProvider` keeps its own case-insensitive, name-gated reading on top of it); the URL half had four copies, now `planeForUrl`; the plane-to-catalog pick had four, now `liveCatalogOn`; the spec lookup had three, now `specOn` (the meter's prospective price keeps the plane-only `findModelSpecOn`, so a Zen route never shows a Go price). `formatUsd` is one function with two named styles, `allowance` and `metered`, and every caller names its style. `ALL_THINKING_LEVELS` had already left with P-R1; the one capitalisation copy left (`"Off"` in `reasoningFor`) reads `effortName`. A source scan keeps one copy of the route rule in the spellings it names (`test/planes.test.ts`: the exact comparisons, the relay half `startsWith("opencode-go…")`, a `case` label, and a quoted route paired with a plane's name in either order and under any key name, the purge table's form and the key order its replacement builds; counted per file and exactly, so a copy inside an allowed file is seen and a removed one forces its allowance down; `go-discovery.ts`'s provider-row reads stay until P10a moves it). The scan is a tripwire for the spellings it names, not a proof: what passes it includes, for example, an unquoted key, another key between the route and the plane, and a route built from parts, each planted as a non-offender. The level names' scans likewise see any capitalised level literal (`"High"` as well as `"Off"`), not only the copy that was removed. `PLANE_OF_ROUTE` is read through `planeOfPlaneRoute` or `planeForRoute`, or indexed directly where the route is already a typed `PlaneRoute` (the route claim, the purge action, the plane model, discovery's `servedPlane`). Left in place: the relay predicate `!provider.startsWith("opencode")` (is this route a relay at all, which picks the client-generation row's relay headers) is still inline in `lifecycle.ts` and `fetch-patch.ts`; it asks a different question from route-to-plane, and is folded when a later phase touches `planeHeadersFor`'s callers. The measured window (L11) is read by the plane model and, in the catalog's place in each field order, by the discovery rows, both through a table parameter defaulting to the shipped one. -16. **P8 `refactor:` settings table.** It starts with a snapshot test of the derived `Config`. Then one field table drives the schema, resolver, types, card, copy and manifest. +16. **P8 `fix:` the card says when its settings apply, over one settings table.** It starts with a snapshot test of the derived `Config`. Then one field table drives the schema, resolver, types, card, copy and manifest. Retitled from `refactor:`, because the changelog must carry the card's new line. + - **As landed.** `src/settings-table.ts` holds `SETTINGS`, nineteen rows in the card's render order and then the config-only order, each with its kind (`boolean`, `string`, `choice`, `list`, `routes`), default, choice values, volatile flag and card group. `config.ts` builds the schema with one loop (a node per kind, `.default()` when the row has one, `.volatile()` when the row says so, the description from `SETTING_PROSE`), resolves with one reader per kind, and derives `CONFIG_DEFAULTS`, `PluginConfig` and `ResolvedPluginConfig` as mapped types over the table. `settings-fields.ts` reads `CARD_FIELDS` off it and `config.ts` reads `CONFIG_ONLY_FIELDS`, and `en` is checked against `SettingsCopyKey`, the copy keys a card row implies (label, hint, each choice, each group), so a card row without its copy fails to compile (a choice value or group spells its copy key through a typed lookup, not a capitaliser: P7's scans keep the one capitalisation in `src` inside `effortName`). `config.ts` is host-side; the client imports the table, never the schema. The prose (each key's description and each config-only reason) is a second export no client module imports: its one reader is `config.ts`, which builds `CONFIG_ONLY_FIELDS` beside the schema, so the bundler drops it from the page with no annotation to rely on (`lib/client.js` 143,074 bytes against the 143,360 tripwire, from 141,010 on the base: the table ships its rows and their one-line docs, and the deleted keys and the old literal registry no longer do; the next phase that adds client code meets the tripwire). `Config.dict`'s key order is now the table's; nothing reads it as an order. + - **The dead copy keys were fifteen**, counted by scanning the code of every `src` file, comment lines blanked, for each of `en`'s 119 keys (the scan is now a case of `settings-copy`, which reports each of the fifteen as unread): `storeInspectFound`, the eleven `login*` keys the removed sign-in used (`loginAction`, `loginAgain`, `loginExpired`, `loginFailed`, `loginSignedIn`, `loginSignedOut`, `loginPlane`, `loginPlaneGo`, `loginPlaneZen`, `loginTitle`, `loginWaiting`), `zenFallbackNotice`, `zenOverflowActive` and `title`. The first count, fourteen, read comments as code and missed `title`, which only a comment in `src/usage-ui.ts` quoted: nothing has read it since the card moved to `plugins.bundle.config`, whose heading the host takes from the package's `meta.title`. Also gone: the meter's `modelMarkers` prop (read by nothing; the meter's gate is the provider list) and a stale `usageModelMarkers` fixture key. The zh dictionary's `title` said "OpenCode 补丁设置" while `meta.title` says "OpenCode 补丁", so the card on screen already said "OpenCode 补丁"; `README.zh-CN.md`, which named it the old way, now names it as `meta.title` does. + - **The choice fields stay `z.string()`.** `z.union([z.const(…)]).default("auto").loose().volatile()` composes, measured on both channels' schemastery (3.18.6-alpha.2 on alpha, 3.19.0 on rc), in either call order: a valid value is kept, and a typo, a number, `null` and an absent value all answer the default. It is not adopted here, because it would change the snapshot this phase holds (the node's `type`, a `loose` flag in its `meta`, the schema JSON `settings.describe` serves) and turn a non-string value from a load failure into the default. The table carries the values, so the switch is one line in the schema's builder when it is wanted. 17. **P9 `refactor:` remote seam.** `defineRemote`, `markRemote` and `callRemote`, with the parity test reading the contracts. 18. **P10a `refactor:` pure module moves.** - `models-discovery` → `host/*`; @@ -534,10 +537,10 @@ How each phase changes now that it sits on `main` 1.8.0 and on both harness chan | P5 | Unchanged, plus L1's warn-once when `globalThis.fetch` is no longer the patched function. **As landed:** `installRemoteService` (`src/host/remote.ts`) for the three services, with the latest live activation's options, disposal with the last activation, reports through the activation's logger after the mount settles, and no provide arm; L1's warn-once is the stream hook's, on the first decorated turn that finds `globalThis.fetch` outside the plugin's live patches (`installFetchPatch` returns the predicate, so two live activations' nested patches raise no warning). | | P6 | L8: verify before evicting a key; L4's outcome (drop `x-opencode-request`, or send it only where it is accepted). From the console study: OC3 (capture a key only from a request the plugin decorated, and close the fill path that could reuse a captured token; the marker guard, never capturing from a request carrying `x-opencode-plugin`, landed with D27), OC4 (`prepareHeaders` on the plane adapter, so the host's `llm-pi-ai/request-headers` waterfall runs on the planes), OC5 (the plane's headers set per call through that option, not the global fetch patch), OC11 (the peer range says what the header seam needs), OC2's remainder (the marker pass-through, which landed with D27 and reads the header's presence today, moves into `src/utils/request-shape.ts`; its second rule is not adopted) and OC10's last sentence (the README's coexistence section gains that the meter and headers stay off Console traffic, once OC3's discriminator lands). **As landed:** L8 adopted as its second arm (a second well-formed 401 in a row, no verification probe); L4 not decided (P-R2 measured nothing); OC3 met (capture only from a decorated turn, L8's strikes and drop lifts counted only on decorated turns too, the fill on neither plane closed to a plane's key, the meter reading the same per-root store); OC4 and OC5 met through `prepareHeaders` on `PlaneAdapter`; OC11 met by stating the seam's floor in the README pair, not by the peer (a narrowing landed and was reverted; see design item 14); OC2's remainder met (`pluginMarkerOn` in `src/utils/request-shape.ts`, still triggering on presence); OC10's last sentence met in the README pair. | | P7 | L6's client-generation table and L11's context-window overrides table; the `planeForRoute` copies now include `main`'s `isGoPlaneUrl` and `catalogPlaneForRoute` pair; the places that justify `@ai-sdk/mistral` → completions by "the plugin follows pi" (`docs/redirect-planes.md` §2, `docs/protocol-routing-and-merge.md`'s Mistral paragraph and its SDK table row, this plan's protocol row in the P-R1 design, the SDK table row in `README.md` and `README.zh-CN.md`, `test/protocols.test.ts`'s SDK-table case title and its `piKnows` assertion, which at most stays an informational pi characterization, and `test/catalog.test.ts`'s note that pi's data files the SDK as completions) are reworded to the plugin's own routing rule, since pi's catalog no longer decides a protocol (D26). **As landed:** all of them, with the `piKnows` assertion dropped: no other row uses that pi premise, and a hard assertion on pi's data would gate every channel's run on a fact the plugin no longer reads, while `PROTOCOL_FOR_SDK` in `test/protocols.test.ts` pins the plugin's own rule; L6 and L11 as their rows below say. | -| P8 | The health snapshot shows the catalog's `lastError` on the card. From P5's review: every field of the row is `.volatile()`, and a Settings edit takes the loader's volatile-only path (`entry.update` → `_commitVolatile`, no remount), while `resolveConfig` unwraps each node once at apply; so no part of the plugin (the usage options, the fetch patch, the stream hook) follows a Settings edit until the plugin is applied again. P8 decides whether the settings table reads those values per call or says in the card that they apply on re-apply. | +| P8 | The health snapshot shows the catalog's `lastError` on the card. From P5's review: every field of the row is `.volatile()`, and a Settings edit takes the loader's volatile-only path (`entry.update` → `_commitVolatile`, no remount), while `resolveConfig` unwraps each node once at apply; so no part of the plugin (the usage options, the fetch patch, the stream hook) follows a Settings edit until the plugin is applied again. P8 decides whether the settings table reads those values per call or says in the card that they apply on re-apply. **As landed:** they apply on re-apply, and the card says so once above its controls (`appliesOnReapply`), as both READMEs do; `host-planes` performs it on the real host in both channels (a volatile edit of the plugin's own row, then a re-apply). Reading per call is not a refactor: `lifecycle.ts` mounts the usage service at apply only when `usageEnabled` is on, copies `keySource` and `readOpencodeStore` into the services it builds, and the route claim reads `endpoint` once. The catalog's `lastError` on the card is carried to P10b: no health snapshot exists, `refreshCatalog` swallows its error, and the carrier would be a remote contract that P9 reshapes over catalog state that P10b rewrites. | | P9 | A loopback triple guard, only if a `webServer` route appears. | | P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/`. L4, carried from P6 (P-R2 measured nothing): with the next keyed variants run, drop `x-opencode-request` or send it only where it is accepted, which is one line in `planeHeadersFor` and one expectation in `test/host-planes-headers.test.ts`. | -| P10b | L12's test; optionally emit `llm/models-updated` on refresh, a new host event. | +| P10b | L12's test; optionally emit `llm/models-updated` on refresh, a new host event. The catalog's `lastError` on the card (L14), carried from P8: the refresh keeps its last error with the state it rewrites, and the card shows it beside the purge row. | | P11, P12 | Unchanged. | ## Lessons from opencode2dsh @@ -559,7 +562,7 @@ Two community plugins solve the same problem on the same host: [`FishBottle7/ope | L11 | **Context-window overrides with dated evidence.** FB keeps measured windows for two free models that differ from the catalog's; an understated window is the overflow trap. | FB `packages/plugin/src/adapter/catalog.ts`. | P7 | Adopted in P7 as the pattern only: `MEASURED_CONTEXT_WINDOWS` (`src/utils/context-windows.ts`), each row a window, an ISO date and its evidence, read ahead of the catalog's window by the plane model and the discovery rows; it ships with no rows, since this repository has measured none (FB's two are FB's) | | L12 | **A failed or partial refresh must not replace the maps.** | SF `lib/catalog.js`; FB `packages/plugin/src/adapter/catalog.ts`. | P10b | Adopt | | L13 | **Test against the host's newer pi**, not only the pin: unit and tier A on the newest pi the host's range resolves, not just the binary e2e; the `/zen/v1/systemone` family belongs in P-R2's families. | FB's hoisted-pi test and loader hook. | P-T1a (unit and mock on each channel's newest pi), P-T1b (tiers A and B), P-R2 (the family) | Adopt | -| L14 | Smaller: a triple loopback guard if a `webServer` route is ever added (the remotes seam remains the better one); the host's `volatileForm()` as an alternative to hand-written card fields; the catalog's `lastError` on the card rather than in a file. | FB `packages/plugin/src/ip-pool-settings/bridge.ts`, `packages/plugin/src/config.ts`. | P9, P8 or P11, P8 | Adopt where the phase reaches it | +| L14 | Smaller: a triple loopback guard if a `webServer` route is ever added (the remotes seam remains the better one); the host's `volatileForm()` as an alternative to hand-written card fields; the catalog's `lastError` on the card rather than in a file. | FB `packages/plugin/src/ip-pool-settings/bridge.ts`, `packages/plugin/src/config.ts`. | P9, P11, P10b | Adopt where the phase reaches it | **Do not adopt:** SF's Bun transport and its `` prompt injection (which also leaks the host server's working directory); FB's IP pool, sibling-host replay and credential-custody delegation; automatic retry with thinking turned off; FB's own stream watchdogs (the host has one). These circumvent the vendor's stated gate ("Free models work in OpenCode"); the vendor answers with IP blocks, and these features would expose our users' keys. Classify the refusals honestly instead (L2, L3). Also avoid their session-id scheme, which is derived from the first user message and re-minted per process: ours is stable per DSH session (`src/utils/session-id.ts`). From the console study (OC13): writing the user's patch file (D8: the plugin never writes the user's profile on its own), providing a `credentials` service (a second one in the default realm throws, and the plugin needs none), and reading the Console's sign-in (credential custody that would bypass the workspace's own policy gate). @@ -778,6 +781,14 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ - **New with the change:** `planes` (the table, its readers, and two source scans, each counted per file and exactly, with a planted addition and a planted removal: the comparisons (the exact comparison, the relay half and a `case` label; allowances `utils/planes.ts` 2, `utils/protocols.ts` 2, `go-discovery.ts` 2), and a quoted route paired with a plane's name in a table row, in either order and under any key name (allowances `utils/planes.ts` 1, `go-discovery.ts` 1 until P10a), with the spellings it does not name planted as non-offenders), `usd`, `client-generation` (the emulated row's names rebuild `planeHeadersFor`'s output; the rest are record checks), `context-windows`, `plane-model`'s L11 case (a seeded window beats the catalog and pi, loses to the user's row and the override, and the other plane's row is ignored) and `models-discovery`'s (catalog-first, measured beats the catalog and pi; pi-first, pi still wins and measured beats the catalog; the other plane's row is ignored). - **Test edits that are not pins:** `go-limits` and `session-cost` lose their `formatUsd` cases to `usd`; `protocols`' SDK-table title and its `piKnows` assertion, which is dropped (the plugin's rule is `PROTOCOL_FOR_SDK`'s), and `catalog`'s Mistral note, both reworded to the plugin's own rule. +**P8** + +- **Pin first, green on the base (`ac8f34f`):** `settings-snapshot` (every `Config.dict` key's type, inner type, default, volatile flag, description and `meta` flag list; `Config` run on an empty row, a typo and a wrong type; `resolveConfig({})`'s nineteen keys and each kind's degradation for every key of that kind; `CONFIG_DEFAULTS`'s sixteen defaults; `CARD_FIELDS`, `CONFIG_ONLY_FIELDS` and `SPECS` with their draft conversions; the copy keys in both languages; the raw and resolved config types, compile-time). Controls, each reverted: one description, one default and one card option changed in the expectation each failed the case, and a widened `endpoint` type failed `tsc`. Also green on the base: `manifest`'s type labels and choice values, and its shipped row sets only defaults; `architecture`'s client graph does not reach `config.ts`; `client-bundle` ships no schema description and no config-only reason. +- **The pin-file edits, each named:** the snapshot's copy-key list loses the fifteen deleted keys (each now asserted absent from both dictionaries) and gains `appliesOnReapply`; `CONFIG_DEFAULTS` is pinned with `toStrictEqual`, and loses the hand-written object's `credentialOrg: undefined` (the derived object holds only the rows with a default; nothing read the key); the compile-time case pins the modifiers its `Defined` normalises away, and the derived `ResolvedPluginConfig` makes its three keys without a default (`credentialOrg`, `debugFile`, `userAgent`) optional and none readonly, where the hand-written type had `credentialOrg` required as `string | undefined`, and it and `readOpencodeStore` readonly. Both loosen the public type (a reader sees the same value types; no writer exists), so they ship under a 1.x minor. The resolver's volatile-node cases hold each kind's non-default value (`{ get: () => !fallback }` for a boolean, one node per string, choice, list and routes key), so an unread node cannot pass. +- **Red on the base, landing with the change:** `settings-copy` (each README names the card by the package's `meta.title` per language; the zh README said "OpenCode 补丁设置"), `deleted-settings` (`modelMarkers` and `usageModelMarkers` named in `src/usage-pill.tsx`), `manifest` (the header lists the card and config-only keys in the table's order; it states every default the schema has, a scalar as the phrase right after "default" so a block that names every choice or a type label containing the value cannot pass, with planted controls for a wrong choice, boolean and string default, a quoted scalar that a longer stated value extends (the closing quote decides it) and an unquoted one (only the end-of-value check decides it), a list stating fewer items than the default, a list item matched only as a substring with the count agreeing (only whole-item equality decides it), and a stated list the default has shrunk from; a list is stated whole, as the same set of items; red for `debug` alone), `settings-page-card` (the page view says once, outside every control, that the settings apply on re-apply; the summary view does not). +- **New with the change:** `settings-table` (one row per schema key in the schema's order, a choice's default among its values, card rows first with each group adjacent, a reason exactly on the rows the card does not show, a card control only on a boolean or a choice, a `routes` row's default equal to `PLANE_ROUTES`, the floor its reader builds on); `architecture`'s client graph reaches `settings-table.ts`; `settings-copy`'s READMEs name the card by `meta.title` and no zh page keeps the old name, and every `en` key has a reader in `src` (a quoted literal in code, with comment lines, JSX `{/* … */}` spans and `//` tails after code blanked, or a key the card derives from the table; the fifteen deleted keys, a planted orphan, and planted keys only a comment line, a JSX comment or a `//` tail quotes are reported); `host-planes`' re-apply case, tier B on both channels (a volatile edit of the plugin's own row, made through Settings' `mutate` as the card's save makes it, commits one `loader/volatile-update` naming the key on the same fiber, a turn still carries `x-opencode-project`, and after `fiber.restart()` it does not, while every turn carries `x-opencode-client`, so the absence is the row read and not an undecorated turn), which performs the behaviour the card line states; a 100% coverage floor on `src/settings-table.ts`. +- **Test edits that are not pins:** `usage-pill`'s two gate cases drop the deleted `modelMarkers` prop and are retitled to the provider list; `settings-page` drops the stale `usageModelMarkers` fixture key; the door re-exports `SETTINGS` and `SETTING_PROSE`, and `CONFIG_ONLY_FIELDS` from `config.ts`. + ## End-to-end infrastructure ### The `e2e-host` job (`ci.yml`) diff --git a/src/config-values.ts b/src/config-values.ts index 1e47e78..de332ae 100644 --- a/src/config-values.ts +++ b/src/config-values.ts @@ -48,11 +48,6 @@ export type KeySourcePolicy = (typeof KEY_SOURCE_POLICIES)[number]; /** Policy applied when a row does not name one. */ export const DEFAULT_KEY_SOURCE: KeySourcePolicy = "auto"; -/** Whether `value` is one of the accepted policies. */ -export const isKeySourcePolicy = (value: unknown): value is KeySourcePolicy => - typeof value === "string" && - (KEY_SOURCE_POLICIES as readonly string[]).includes(value); - /** * Which endpoint family the gateway's requests go to. * @@ -75,11 +70,6 @@ export type EndpointFamily = (typeof ENDPOINT_FAMILIES)[number]; /** Family applied when a row does not name one. */ export const DEFAULT_ENDPOINT_FAMILY: EndpointFamily = "auto"; -/** Whether `value` is one of the accepted families. */ -export const isEndpointFamily = (value: unknown): value is EndpointFamily => - typeof value === "string" && - (ENDPOINT_FAMILIES as readonly string[]).includes(value); - /** * Unwrap a schemastery volatile `.get()` node to its current value. * diff --git a/src/config.ts b/src/config.ts index 2e1f996..64a28f3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2,11 +2,14 @@ * Host-side plugin configuration: defaults, raw/resolved types, the row * schema, and the resolver that folds either into one resolved shape. * - * Every default lives exactly once — in {@link CONFIG_DEFAULTS} — and both - * `resolveConfig` and the `Config` schema read from it, so the schema and the - * resolver cannot drift apart (the "defaults mirror resolveConfig" contract - * is structural rather than a comment asking future editors to keep two - * literal lists in sync). + * Every one of them is read from the settings table (`settings-table.ts`): + * a row's kind picks its schema node and its reader, and its default is the + * schema's `.default()` and the resolver's fallback both, so the schema, the + * resolver and the types cannot drift apart. The one exception is `routes`, + * whose resolved floor is the planes themselves (`PLANE_ROUTES`, D19), not the + * row's default; `test/settings-table.test.ts` holds the two equal. This + * module is the host half: it imports schemastery and carries the prose, so + * the client reads the table and never this file. * * @module dsh-opencode-patch/config */ @@ -18,8 +21,6 @@ import { DEFAULT_KEY_SOURCE, DEFAULT_PROVIDERS, ENDPOINT_FAMILIES, - isEndpointFamily, - isKeySourcePolicy, KEY_SOURCE_POLICIES, type EndpointFamily, type KeySourcePolicy, @@ -27,6 +28,15 @@ import { readString, readStringList, } from "./config-values.ts"; +import { + isConfigOnlySetting, + SETTING_KEYS, + SETTING_PROSE, + SETTINGS, + type SettingKey, + type SettingRow, + type SettingRows, +} from "./settings-table.ts"; import { PLANE_ROUTES } from "./utils/protocols.ts"; export { @@ -39,11 +49,6 @@ export { type KeySourcePolicy, }; -/** - * URL substrings that mark a request as OpenCode gateway traffic even when no - * turn is active. Configurable so mirrors, proxies, and self-hosted gateways - * can be targeted without a code change. - */ /** * URL substrings marking gateway traffic. * @@ -52,222 +57,153 @@ export { * credential's format decides which of the two it is actually sent to - see * `endpoint-pairing.ts`. */ -export const DEFAULT_GATEWAY_URLS = [ - "opencode.ai/zen", - "opencode.ai/inference", -]; +export const DEFAULT_GATEWAY_URLS: readonly string[] = + SETTINGS.gatewayUrls.default; /** Value restored into `x-opencode-client` by default. */ -export const DEFAULT_ORIGIN_CLIENT = "cli"; - -/** Whether to attach the workspace project identifier (x-opencode-project) by default. */ -export const DEFAULT_INJECT_PROJECT = true; +export const DEFAULT_ORIGIN_CLIENT: string = SETTINGS.originClient.default; /** * Model-id substring that marks a request as free-tier (and therefore in need * of the core-tool schema fallback). */ -export const DEFAULT_FREE_MODEL_MARKER = "free"; - -/** Environment variable consulted for the fallback session id. */ -export const DEFAULT_SESSION_ID_ENV = "OPENCODE_SESSION_ID"; +export const DEFAULT_FREE_MODEL_MARKER: string = + SETTINGS.freeModelMarker.default; /** Default OpenCode Go quota endpoint. */ -export const DEFAULT_USAGE_BASE_URL = "https://opencode.ai/zen/go/v1"; +export const DEFAULT_USAGE_BASE_URL: string = SETTINGS.usageBaseURL.default; /** Default environment variable / credential ref holding the Go key. */ export const DEFAULT_USAGE_KEY_ENV = "OPENCODE_GO_API_KEY"; -/** - * The single source of truth for every documented default. Blank / absent - * user values fall back to these; the `Config` schema `.default()`s to the - * same values. - */ -export const CONFIG_DEFAULTS = { - credentialOrg: undefined as string | undefined, - debug: false, - enrichModels: true, - endpoint: DEFAULT_ENDPOINT_FAMILY, - freeModelMarker: DEFAULT_FREE_MODEL_MARKER, - gatewayUrls: DEFAULT_GATEWAY_URLS, - injectCoreTools: true, - injectOriginHeaders: true, - injectProject: DEFAULT_INJECT_PROJECT, - injectUserAgent: true, - keySource: DEFAULT_KEY_SOURCE, - originClient: DEFAULT_ORIGIN_CLIENT, - providers: DEFAULT_PROVIDERS, - readOpencodeStore: false, - sessionIdEnv: DEFAULT_SESSION_ID_ENV, - usageBaseURL: DEFAULT_USAGE_BASE_URL, - usageEnabled: true, -} as const; +/** The value a row of this shape holds, before resolution. */ +type RawOf = R extends { kind: "boolean" } + ? boolean + : R extends { kind: "choice"; values: readonly (infer V)[] } + ? V + : R extends { kind: "list" | "routes" } + ? string[] + : string; + +/** The value a row of this shape resolves to. */ +type ResolvedOf = R extends { kind: "routes" } ? Set : RawOf; + +/** The keys whose row has a default, so they always resolve to a value. */ +type DefaultedKey = { + [K in SettingKey]: SettingRows[K] extends { default: unknown } ? K : never; +}[SettingKey]; /** The raw shape a cordis row's `config` may carry (all optional). */ -export interface PluginConfig { - credentialOrg?: string; - debug?: boolean; - debugFile?: string; - enrichModels?: boolean; - endpoint?: EndpointFamily; - freeModelMarker?: string; - gatewayUrls?: string[]; - injectCoreTools?: boolean; - injectOriginHeaders?: boolean; - injectProject?: boolean; - injectUserAgent?: boolean; - keySource?: KeySourcePolicy; - originClient?: string; - providers?: string[]; - readOpencodeStore?: boolean; - sessionIdEnv?: string; - userAgent?: string; - usageBaseURL?: string; - usageEnabled?: boolean; -} +export type PluginConfig = { + -readonly [K in keyof SettingRows]?: RawOf; +}; -/** The fully-defaulted shape the plugin's runtime branches read. */ -export interface ResolvedPluginConfig { - /** - * The org to send with an account credential, when the credential does not - * carry one itself. - * - * A session token needs the org it belongs to: measured on a paid model, - * `200` with the org and `403` without. It never unlocked the free tier — - * nothing sent from a request does. A login performed by this plugin stores - * the org beside the token, so a deployment that logged in needs nothing - * here — this is for one whose token came from somewhere else. - */ - readonly credentialOrg: string | undefined; - debug: boolean; - debugFile?: string; - enrichModels: boolean; - /** - * Which endpoint family the gateway's requests go to. - * - * The two families are independently entitled and both are still served, so - * the choice is the user's: `auto` is an alias of `modern` (the default), and - * `legacy` pins the older single base per plane. See {@link ENDPOINT_FAMILIES}. - */ - endpoint: EndpointFamily; - /** `*` when the core-tool fallback should run for every model. */ - freeModelMarker: string; - /** URL substrings marking gateway traffic; never empty after resolution. */ - gatewayUrls: string[]; - injectCoreTools: boolean; - injectOriginHeaders: boolean; - injectProject: boolean; - injectUserAgent: boolean; - /** Which credential source wins when more than one resolves. */ - keySource: KeySourcePolicy; - originClient: string; - /** - * The route ids whose turns this plugin decorates: the two planes, always, - * and any relay route the row names beside them. - */ - providers: Set; - /** - * Whether the OpenCode installation's own credential store may be read. - * - * Off by default, and LAST in the resolution order when on: reading another - * program's private store is something a user turns on, and a credential they - * declared in DSH always outranks one inferred from the installation. - */ - readonly readOpencodeStore: boolean; - sessionIdEnv: string; - userAgent?: string; - usageBaseURL: string; - usageEnabled: boolean; -} +/** + * The fully-defaulted shape the plugin's runtime branches read: a key whose + * row has a default always holds a value, and the three without one + * (`credentialOrg`, `debugFile`, `userAgent`) hold `undefined` until a row + * sets them. + */ +export type ResolvedPluginConfig = { + -readonly [ + K in keyof SettingRows as K extends DefaultedKey ? K : never + ]: ResolvedOf; +} & { + -readonly [ + K in keyof SettingRows as K extends DefaultedKey ? never : K + ]?: ResolvedOf; +}; /** - * Fold a raw row config (or schema-validated output) into the resolved shape. - * - * Blank strings and empty lists inherit the defaults, so a row that mentions a - * key without a usable value behaves exactly like a row that omits it. - * - * @param rawInput - raw or validated row config. + * Every default, by key: the table's, read back. Blank or absent user values + * fall back to these, and the `Config` schema `.default()`s to the same ones. */ +export const CONFIG_DEFAULTS = + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `Object.fromEntries` forgets the keys; the filter keeps exactly the rows with a default. + Object.fromEntries( + SETTING_KEYS.flatMap((key) => { + const row: SettingRow = SETTINGS[key]; + return row.default === undefined ? [] : [[key, row.default]]; + }) + ) as { readonly [K in DefaultedKey]: SettingRows[K]["default"] }; + /** - * A row's key-source policy, or the default when it names something else. + * Knobs that exist in the schema but deliberately render no control: the + * table's rows without a `card` group, each with the reason it gives + * (`SETTING_PROSE`, which says why a key stays off the card in general). * - * Deliberately lenient: a typo in a hand-edited row degrades to `auto` rather - * than failing the plugin load. + * A test pins that this list and the card's `CARD_FIELDS` partition the schema + * exactly: no knob may be in both, and none may be in neither. It lives here, + * on the host side, so no client module imports the prose it carries. */ -const resolvedKeySource = (raw: unknown): KeySourcePolicy => { - const value = readString(raw); - return isKeySourcePolicy(value) ? value : CONFIG_DEFAULTS.keySource; -}; +export const CONFIG_ONLY_FIELDS: readonly { + field: string; + /** Why this knob stays out of the card. */ + reason: string; +}[] = SETTING_KEYS.filter(isConfigOnlySetting).map((field) => ({ + field, + reason: SETTING_PROSE[field].reason, +})); /** - * A row's endpoint family, or the default when it names something else. - * - * Lenient for the same reason {@link resolvedKeySource} is: a typo in a - * hand-edited row degrades to `auto`, the default, so a typo cannot select a - * family the user never named. + * One row's value, read by its kind. Lenient throughout: a typo or a wrong type + * in a hand-edited row degrades to the default rather than failing the plugin + * load, and a choice outside its values cannot select one the user never named. */ -const resolvedEndpoint = (raw: unknown): EndpointFamily => { - const value = readString(raw); - return isEndpointFamily(value) ? value : CONFIG_DEFAULTS.endpoint; +const readSetting = (row: SettingRow, raw: unknown): unknown => { + if (row.kind === "boolean") { + return readBoolean(raw, row.default); + } + if (row.kind === "choice") { + const value = readString(raw); + return value !== undefined && row.values.includes(value) + ? value + : row.default; + } + if (row.kind === "list") { + const list = readStringList(raw); + return list.length > 0 ? list : [...row.default]; + } + if (row.kind === "routes") { + // The planes are the plugin's own routes (D19), so a row's list adds + // relay routes to them and can never take one away. + return new Set([...PLANE_ROUTES, ...readStringList(raw)]); + } + return readString(raw) ?? row.default; }; +/** + * Fold a raw row config (or schema-validated output) into the resolved shape. + * + * Blank strings and empty lists inherit the defaults, so a row that mentions a + * key without a usable value behaves exactly like a row that omits it. Every + * key is present on the result, holding `undefined` when it has no default. + * + * @param rawInput - raw or validated row config. + */ export const resolveConfig = ( rawInput: PluginConfig = {} ): ResolvedPluginConfig => { - const config = rawInput ?? {}; - - const providers = readStringList(config.providers); - const gatewayUrls = readStringList(config.gatewayUrls); + const config: Record = rawInput ?? {}; + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one entry per table row, each read by its own row's kind. + return Object.fromEntries( + SETTING_KEYS.map((key) => [key, readSetting(SETTINGS[key], config[key])]) + ) as ResolvedPluginConfig; +}; - return { - credentialOrg: readString(config.credentialOrg), - debug: readBoolean(config.debug, CONFIG_DEFAULTS.debug), - debugFile: readString(config.debugFile), - enrichModels: readBoolean( - config.enrichModels, - CONFIG_DEFAULTS.enrichModels - ), - endpoint: resolvedEndpoint(config.endpoint), - freeModelMarker: - readString(config.freeModelMarker) ?? CONFIG_DEFAULTS.freeModelMarker, - gatewayUrls: - gatewayUrls.length > 0 ? gatewayUrls : [...CONFIG_DEFAULTS.gatewayUrls], - injectCoreTools: readBoolean( - config.injectCoreTools, - CONFIG_DEFAULTS.injectCoreTools - ), - injectOriginHeaders: readBoolean( - config.injectOriginHeaders, - CONFIG_DEFAULTS.injectOriginHeaders - ), - injectProject: readBoolean( - config.injectProject, - CONFIG_DEFAULTS.injectProject - ), - injectUserAgent: readBoolean( - config.injectUserAgent, - CONFIG_DEFAULTS.injectUserAgent - ), - keySource: resolvedKeySource(config.keySource), - originClient: - readString(config.originClient) ?? CONFIG_DEFAULTS.originClient, - // The planes are the plugin's own routes (D19), so a row's list adds - // relay routes to them and can never take one away. - providers: new Set([...PLANE_ROUTES, ...providers]), - readOpencodeStore: readBoolean( - config.readOpencodeStore, - CONFIG_DEFAULTS.readOpencodeStore - ), - sessionIdEnv: - readString(config.sessionIdEnv) ?? CONFIG_DEFAULTS.sessionIdEnv, - userAgent: readString(config.userAgent), - usageBaseURL: - readString(config.usageBaseURL) ?? CONFIG_DEFAULTS.usageBaseURL, - usageEnabled: readBoolean( - config.usageEnabled, - CONFIG_DEFAULTS.usageEnabled - ), - }; +/** One row's schema node, before its flag and description. */ +const nodeFor = (row: SettingRow): z => { + if (row.kind === "boolean") { + return z.boolean().default(row.default); + } + if (row.kind === "list" || row.kind === "routes") { + return z.array(z.string()).default([...row.default]); + } + // A choice is a string here: the schema does not hold the option set, so a + // typo passes the load and the resolver degrades it (see `readSetting`). + return row.default === undefined + ? z.string() + : z.string().default(row.default); }; /** @@ -282,134 +218,17 @@ export const resolveConfig = ( * the namespace is omitted from `describe()`, `configForms.whileServed` never * fires, and the Plugins page shows the bundle with no card. */ -export const Config = z.object({ - providers: z - .array(z.string()) - .default([...CONFIG_DEFAULTS.providers]) - .volatile() - .description( - "Route ids whose turns this plugin decorates; opencode and opencode-go are always included." - ), - gatewayUrls: z - .array(z.string()) - .default([...CONFIG_DEFAULTS.gatewayUrls]) - .volatile() - .description( - "URL substrings marking OpenCode gateway traffic (matched before providers)." - ), - injectUserAgent: z - .boolean() - .default(CONFIG_DEFAULTS.injectUserAgent) - .volatile() - .description( - "Restore the opencode CLI User-Agent stripped by the DSH LLM adapter." - ), - userAgent: z - .string() - .volatile() - .description( - "Custom User-Agent string. Leave blank to use the canonical OpenCode CLI one." - ), - keySource: z - .string() - .default(CONFIG_DEFAULTS.keySource) - .volatile() - .description( - "Which credential source wins when several resolve. auto: a literal key declared in another entry, then a key captured from a live request, then the declared reference, then a captured key for the other plane. request: a captured key first, then a literal one, then the declared reference. configured: a literal key, then the declared reference, then captured ones. An unrecognised value falls back to auto." - ), - readOpencodeStore: z - .boolean() - .default(CONFIG_DEFAULTS.readOpencodeStore) - .volatile() - .description( - "Read the credential the OpenCode installation already holds, from its " + - "own database, as the LAST resort: after every credential this " + - "deployment declares. Off by default — reading another tool's store is " + - "something a user turns on, not something that happens to them." - ), - injectOriginHeaders: z - .boolean() - .default(CONFIG_DEFAULTS.injectOriginHeaders) - .volatile() - .description("Inject x-opencode-client header."), - originClient: z - .string() - .default(CONFIG_DEFAULTS.originClient) - .volatile() - .description("Value restored into the x-opencode-client header."), - injectProject: z - .boolean() - .default(CONFIG_DEFAULTS.injectProject) - .volatile() - .description( - "Attach the active workspace folder name (or 'global' if outside a project) in x-opencode-project." - ), - injectCoreTools: z - .boolean() - .default(CONFIG_DEFAULTS.injectCoreTools) - .volatile() - .description( - "Auto-inject read and bash tool schemas on free-tier requests." - ), - freeModelMarker: z - .string() - .default(CONFIG_DEFAULTS.freeModelMarker) - .volatile() - .description( - "Model-id marker triggering the core-tool fallback; * applies to every model." - ), - sessionIdEnv: z - .string() - .default(CONFIG_DEFAULTS.sessionIdEnv) - .volatile() - .description( - "Environment variable consulted for the fallback session id outside a turn." - ), - usageEnabled: z - .boolean() - .default(CONFIG_DEFAULTS.usageEnabled) - .volatile() - .description("Enable host-side OpenCode Go usage querying."), - enrichModels: z - .boolean() - .default(CONFIG_DEFAULTS.enrichModels) - .volatile() - .description( - "Enrich the gateway /models listing and Settings model discovery from the OpenCode catalog; a plane's model info follows the user's row and the catalog either way." - ), - endpoint: z - .string() - .default(CONFIG_DEFAULTS.endpoint) - .description( - "Which endpoint family the gateway's requests go to. modern: the " + - "per-protocol inference family, " + - "https://opencode.ai/inference/{openai,anthropic,google}/... on Zen " + - "and https://opencode.ai/inference/go/{openai,anthropic,google}/... " + - "on Go. auto: an alias of modern, and the default. legacy: the older " + - "single base per plane, https://opencode.ai/zen/v1 and " + - "https://opencode.ai/zen/go/v1. The two families are separately " + - "entitled and both still answer, so this is a choice rather than a " + - "migration; an unrecognised value falls back to auto." - ) - .volatile(), - usageBaseURL: z - .string() - .default(CONFIG_DEFAULTS.usageBaseURL) - .volatile() - .description("OpenCode Go gateway base URL."), - credentialOrg: z - .string() - .volatile() - .description( - "The org id (wrk_...) to send with an account credential. A login through " + - "this plugin stores the org with the token, so this is only for a token " + - "that came from elsewhere." - ), - debug: z - .boolean() - .default(CONFIG_DEFAULTS.debug) - .description("Log injected streamed calls."), - debugFile: z - .string() - .description("Server-side path for JSONL stream-debug entries."), -}); +export const Config = z.object( + Object.fromEntries( + SETTING_KEYS.map((key) => { + const row: SettingRow = SETTINGS[key]; + const node = nodeFor(row); + return [ + key, + (row.volatile ? node.volatile() : node).description( + SETTING_PROSE[key].description + ), + ]; + }) + ) +); diff --git a/src/settings-boolean-field.tsx b/src/settings-boolean-field.tsx index 705c20d..e207473 100644 --- a/src/settings-boolean-field.tsx +++ b/src/settings-boolean-field.tsx @@ -1,7 +1,7 @@ /** * Boolean settings field: the injected `Switch` inside the shared - * {@link SettingsFieldShell}. See `AGENTS.md` → "Why the card owns its - * boolean/list fields". + * {@link SettingsFieldShell}. Ours because the host ships no boolean field + * spec. * * @module dsh-opencode-patch/settings-boolean-field */ diff --git a/src/settings-card.tsx b/src/settings-card.tsx index 07d5a24..25928a3 100644 --- a/src/settings-card.tsx +++ b/src/settings-card.tsx @@ -19,7 +19,7 @@ import React from "react"; import { SettingsBooleanField } from "./settings-boolean-field.tsx"; import { SettingsChoiceField } from "./settings-choice-field.tsx"; import { withBundleCopy, type Translate } from "./settings-copy.ts"; -import { CARD_FIELDS, FIELD, type CardFieldSpec } from "./settings-fields.ts"; +import { CARD_FIELDS, type CardFieldSpec } from "./settings-fields.ts"; import type { PurgeOutcome } from "./settings-purge.ts"; import { StoreInspectRow } from "./settings-store-inspect.tsx"; import type { StoreInspectOutcome } from "./settings-store.ts"; @@ -187,12 +187,6 @@ export interface CardProps { * that cannot act invites a click that explains nothing. */ inspectStore?: () => Promise; - /** - * The Host's sign-in remote. Never absent: the page always hands over the three - * calls, and each resolves the service when it is invoked, so a remote that mounts - * late is still reached and a host that mounts none shows a row that says so. - */ - edit: (field: string, text: string) => void; resetField: (field: string) => void; save: () => void; @@ -327,6 +321,20 @@ export const OpencodeCard: React.FC = (props: CardProps) => { {props.purgeDeprecated !== undefined && ( )} + {/* + A Settings write takes the loader's volatile-only path and the plugin + reads its row once, at apply: said once, above the form, rather than in + every control's hint. + */} +
+ {t("appliesOnReapply")} +
= (props: CardProps) => { // says what MAY be read, the row says what IS there. Splitting them // across the card is what left "turn this on" as a blind choice. const beside = - entry.field === FIELD.readOpencodeStore && + entry.field === "readOpencodeStore" && props.inspectStore !== undefined ? [ & Record; /** `zh` mirrors `en` key-for-key; the type makes a missing key a compile error. */ export const zh: Record = { + appliesOnReapply: + "更改在插件下次应用时生效:停用后重新启用插件,或重启 DSH。", description: "OpenCode Zen 网关来源头恢复、会话保持、免费模型兼容与 Go 实时额度显示。", enrichModels: "用 OpenCode 官方目录补全列表(默认开启)", @@ -221,7 +214,6 @@ export const zh: Record = { storeInspectTitle: "本机 OpenCode 安装", storeInspectHint: "读取本机 OpenCode CLI 已保存的凭据库,并报告它属于哪个账号。密钥本身既不会显示,也不会外传。", - storeInspectFound: "已找到", storeInspectMissing: "本机没有找到 OpenCode 的凭据库。", storeInspectNoAccount: "凭据库存在,但其中没有 OpenCode 账号凭据。", storeInspectUnavailable: "当前宿主未挂载检测服务。", @@ -244,7 +236,6 @@ export const zh: Record = { save: "保存", saveFailed: "保存失败,请检查填写内容。", saving: "保存中…", - title: "OpenCode 补丁设置", unavailable: "插件未加载,暂无法配置。", usageConsole: "控制台", usageTopUp: "充值", @@ -278,17 +269,6 @@ export const zh: Record = { usageSummaryTitle: "Go 用量", usageSummaryStatusOk: "状态正常", usageSummaryStatusLimited: "已达限额", - loginAction: "登录 OpenCode", - loginAgain: "重新登录", - loginExpired: "验证码已过期", - loginFailed: "登录失败", - loginSignedIn: "已登录", - loginSignedOut: "未登录", - loginPlane: "登录到", - loginPlaneGo: "Go(订阅)", - loginPlaneZen: "Zen(按量付费)", - loginTitle: "OpenCode 账户", - loginWaiting: "等待批准…", usageSummaryUnavailable: "读不到配额", usageSummaryUsed: "已用", usageSummaryRemaining: "剩余", @@ -303,8 +283,6 @@ export const zh: Record = { usage_rolling: "5 小时", usage_weekly: "每周", zenCredit: "可用 Zen 余额", - zenFallbackNotice: "请求将自动从 Zen 余额中扣除", - zenOverflowActive: "Zen 余额已就绪,将在额度用尽时自动承接", zenPaygBadge: "按量计费", goPlanTitle: "OpenCode Go", goPlusTier: "Plus", diff --git a/src/settings-fields.ts b/src/settings-fields.ts index 05e5514..587d0cb 100644 --- a/src/settings-fields.ts +++ b/src/settings-fields.ts @@ -1,10 +1,13 @@ /** - * Field registry for the OpenCode Patch card — the single source of truth for - * which knobs the card edits: knob, section, control kind and copy keys. + * The card's view of the settings table: which keys the card edits, under + * which heading, with which control and copy. * - * {@link SPECS} and the card's JSX are both derived from it, so a field can no - * longer be bound but never rendered. See `AGENTS.md` → "Why the card owns its - * boolean/list fields" for why the helpers below are ours. + * Nothing here is a second list: {@link CARD_FIELDS} is read off + * `settings-table.ts`, and {@link SPECS} and the card's JSX are derived from + * it, so a field can no longer be bound but never rendered. The keys the card + * leaves to the row are `CONFIG_ONLY_FIELDS`, in `config.ts`, beside the prose + * that says why. The draft conversions below are ours because the host ships + * no boolean or enum field spec. * * @module dsh-opencode-patch/settings-fields */ @@ -12,110 +15,21 @@ import type { SettingsFieldSpec } from "@deepseek-ai/dsh-client-ui-primitives"; import type { CopyKey } from "./settings-copy.ts"; - -/** Schema knob names the card edits; keys double as label ids. */ -export const FIELD = { - endpoint: "endpoint", - enrichModels: "enrichModels", - injectCoreTools: "injectCoreTools", - injectOriginHeaders: "injectOriginHeaders", - injectProject: "injectProject", - injectUserAgent: "injectUserAgent", - keySource: "keySource", - readOpencodeStore: "readOpencodeStore", - usageEnabled: "usageEnabled", -} as const; - -/** - * Knobs that exist in the schema but deliberately render no control. - * - * The card shows the decisions a user actually makes — behaviour toggles and the - * credential policy. Everything here is an *override*: a literal (a UA string, a - * header value, an endpoint), a marker (a model-id or URL substring), or a - * reference (an env-var name, a credential ref, a route list). Their defaults are - * correct for every documented setup, so exposing them only invites someone to - * break their own routing — and they are all still editable in the row's - * `config` (`cordis.patch.yml` carries the reference). - * - * A test pins that this list and {@link CARD_FIELDS} partition the schema - * exactly: no knob may be in both, and none may be in neither. - */ -export const CONFIG_ONLY_FIELDS: readonly { - field: string; - /** Why this knob stays out of the card. */ - reason: string; -}[] = [ - { - field: "credentialOrg", - reason: - "the org an account credential belongs to; a login through this plugin " + - "stores it with the token, so the row is for a token that came from " + - "elsewhere and has no UI to belong to", - }, - { - field: "debug", - reason: - "diagnostic console logging of streamed calls, not a behaviour a user " + - "tunes in the UI", - }, - { - field: "debugFile", - reason: - "the JSONL file both debug halves append to; naming it writes the file " + - "whether or not debug is on, and a server-side path is a deployment fact " + - "rather than a card control", - }, - { - field: "userAgent", - reason: - "literal User-Agent override; the default is the canonical CLI string", - }, - { - field: "originClient", - reason: - "literal x-opencode-client value; the default ('cli') is what the gateway expects", - }, - { - field: "sessionIdEnv", - reason: "names an env var only a caller-supplied session id would use", - }, - { - field: "freeModelMarker", - reason: - "model-id substring; 'free' tracks the vendor's ids, '*' forces the fallback", - }, - { - field: "providers", - reason: - "route ids whose turns are decorated; both planes are always included, so only a relay route needs adding", - }, - { - field: "gatewayUrls", - reason: "URL substrings; only a mirror or relay needs to change them", - }, - { - field: "usageBaseURL", - reason: "endpoint override; auto-discovered from the composition", - }, -]; +import { + type CardSettingKey, + groupKeyOf, + hintKeyOf, + isCardSetting, + isChoiceSetting, + labelKeyOf, + optionKeyOf, + SETTING_KEYS, + SETTINGS, +} from "./settings-table.ts"; /** Which control renders a field, and which draft conversion backs it. */ export type FieldKind = "boolean" | "select"; -/** - * Section headings, in the order they appear. - * - * A field names its group and the card inserts a heading wherever it changes, so - * the display order comes from {@link CARD_FIELDS} rather than a second list. - * Keeping each group's entries adjacent is what makes the heading appear once. - */ -export const GROUP = { - access: "groupAccess", - models: "groupModels", - quota: "groupQuota", - requests: "groupRequests", -} as const; - /** One choice a `select` field offers: the label is copy, the value is stored. */ export interface CardFieldOption { labelKey: CopyKey; @@ -124,7 +38,7 @@ export interface CardFieldOption { /** One rendered field: the knob, its control kind, and its copy. */ export interface CardFieldSpec { - field: string; + field: CardSettingKey; /** Section heading this field renders under. */ group: CopyKey; hintKey: CopyKey; @@ -197,94 +111,34 @@ const toSettingsFieldSpec = (entry: CardFieldSpec): SettingsFieldSpec => FIELD_SPEC_BUILDERS[entry.kind](entry); /** - * Every field the card renders, in render order, grouped into sections. + * Every field the card renders, in render order, grouped into sections: the + * table's rows that name a `card` group, in table order. * - * Entries are ordered so each {@link GROUP} stays contiguous: the card inserts a + * The table keeps each group's rows adjacent, because the card inserts a * heading where the group changes. Only decisions a user makes live here — the - * override knobs are in {@link CONFIG_ONLY_FIELDS}. - * - * The endpoint family and the credential choice both live under - * {@link GROUP.access}: together they are "which account, on which endpoint", - * and filing the credential knob under the quota meter instead is what made it - * hard to find. + * override knobs are `CONFIG_ONLY_FIELDS`, in `config.ts`. */ -export const CARD_FIELDS: readonly CardFieldSpec[] = [ - { - field: FIELD.endpoint, - group: GROUP.access, - hintKey: "endpointHint", - kind: "select", - labelKey: "endpoint", - // Values must stay in step with `ENDPOINT_FAMILIES`; a test pins that. - options: [ - { labelKey: "endpointAuto", value: "auto" }, - { labelKey: "endpointLegacy", value: "legacy" }, - { labelKey: "endpointModern", value: "modern" }, - ], - }, - { - field: FIELD.keySource, - group: GROUP.access, - hintKey: "keySourceHint", - kind: "select", - labelKey: "keySource", - // Values must stay in step with `KEY_SOURCE_POLICIES`; a test pins that. - options: [ - { labelKey: "keySourceAuto", value: "auto" }, - { labelKey: "keySourceRequest", value: "request" }, - { labelKey: "keySourceConfigured", value: "configured" }, - ], - }, - { - field: FIELD.readOpencodeStore, - group: GROUP.access, - hintKey: "readOpencodeStoreHint", - kind: "boolean", - labelKey: "readOpencodeStore", - }, - { - field: FIELD.injectUserAgent, - group: GROUP.requests, - hintKey: "injectUserAgentHint", - kind: "boolean", - labelKey: "injectUserAgent", - }, - { - field: FIELD.injectOriginHeaders, - group: GROUP.requests, - hintKey: "injectOriginHeadersHint", - kind: "boolean", - labelKey: "injectOriginHeaders", - }, - { - field: FIELD.injectProject, - group: GROUP.requests, - hintKey: "injectProjectHint", - kind: "boolean", - labelKey: "injectProject", - }, - { - field: FIELD.enrichModels, - group: GROUP.models, - hintKey: "enrichModelsHint", - kind: "boolean", - labelKey: "enrichModels", - }, - { - field: FIELD.injectCoreTools, - group: GROUP.models, - hintKey: "injectCoreToolsHint", - kind: "boolean", - labelKey: "injectCoreTools", - }, - { - field: FIELD.usageEnabled, - group: GROUP.quota, - hintKey: "usageEnabledHint", - kind: "boolean", - labelKey: "usageEnabled", - }, -]; +export const CARD_FIELDS: readonly CardFieldSpec[] = SETTING_KEYS.filter( + isCardSetting +).map((field): CardFieldSpec => { + const entry = { + field, + group: groupKeyOf(SETTINGS[field].card), + hintKey: hintKeyOf(field), + labelKey: labelKeyOf(field), + }; + // A boolean entry has no `options` key at all, not an undefined one. + return isChoiceSetting(field) + ? { + ...entry, + kind: "select", + options: SETTINGS[field].values.map((value) => ({ + labelKey: optionKeyOf(field, value), + value, + })), + } + : { ...entry, kind: "boolean" }; +}); /** The draft conversions the form model binds, derived from {@link CARD_FIELDS}. */ export const SPECS: SettingsFieldSpec[] = CARD_FIELDS.map(toSettingsFieldSpec); diff --git a/src/settings-page.tsx b/src/settings-page.tsx index 7ded198..49ada41 100644 --- a/src/settings-page.tsx +++ b/src/settings-page.tsx @@ -58,7 +58,8 @@ export const PKG = "dsh-opencode-patch"; * `opencodeLogin` namespace are v2 work. */ export const patchRemote = { - // ONE contribution, TWO namespaces. Typert enforces a unique package name per + // ONE contribution, THREE namespaces (usage, purge, store inspection). + // Typert enforces a unique package name per // contribution, so mounting them separately with the same package throws // "already registered" and drops the remote entirely. descriptors: [ @@ -362,13 +363,14 @@ export const apply = (ctx: ClientContext): void => { return noopDisposer; }, "dsh-opencode-patch: dictionaries"); - // Both remotes mount as ONE contribution under the plugin's package name. - // Typert enforces unique package names per contribution (`dsh-typert-registry`: + // The three remotes (usage, purge, store inspection) mount as ONE + // contribution under the plugin's package name. Typert enforces unique + // package names per contribution (`dsh-typert-registry`: // `if (this.packages.has(contribution.package)) throw new Error(...)`). - // Mounting `usageRemote` and `loginRemote` separately with the same package - // name ("dsh-opencode-patch") causes the second `$mount` call to throw - // `Remote package "dsh-opencode-patch" is already registered` — dropping the - // remote completely. + // Mounting `usageRemote`, `purgeRemote` and `storeRemote` separately with the + // same package name ("dsh-opencode-patch") causes the second `$mount` call to + // throw `Remote package "dsh-opencode-patch" is already registered` — + // dropping that remote completely. // // One contribution registers the package ONCE, which is what lets `api-gateway` // install the meter's namespace. @@ -376,7 +378,7 @@ export const apply = (ctx: ClientContext): void => { const remotes = mountRemote( ctx, patchRemote, - "remotes; the meter and sign-in row will render nothing" + "remotes; the meter, purge and store rows will render nothing" ); // The meter is registered when the mount is DONE, which is the fact the ten // -second timeout used to stand in for. `registerMeter` is idempotent, so @@ -665,8 +667,7 @@ export const apply = (ctx: ClientContext): void => { // host inspects its own OpenCode store and answers a sanitized // summary, so the card can show the account without the secret. inspectStore: () => inspectStore(ctx), - // The sign-in remote, when the host mounted one. Same shape as - // the meter's: the card calls, the host holds the credential. + // The form model's edit, reset, save and discard. ...model.actions(), }), key: alias.key, diff --git a/src/settings-table.ts b/src/settings-table.ts new file mode 100644 index 0000000..50a1cfa --- /dev/null +++ b/src/settings-table.ts @@ -0,0 +1,368 @@ +/** + * The plugin's settings, one row per key: the table the schema, resolver, + * types, defaults and config-only list (`config.ts`), the card's fields + * (`settings-fields.ts`), its copy keys and the manifest test all read. Client-safe: no schemastery. + * + * @module dsh-opencode-patch/settings-table + */ + +import { + DEFAULT_ENDPOINT_FAMILY, + DEFAULT_KEY_SOURCE, + DEFAULT_PROVIDERS, + ENDPOINT_FAMILIES, + KEY_SOURCE_POLICIES, +} from "./config-values.ts"; + +/** The card's sections, in the order they render. */ +export type GroupId = "access" | "requests" | "models" | "quota"; + +/** + * One setting. `kind` decides the schema node, the resolver's reader and the + * card's control; `volatile` is the schema's flag (without it the settings + * page omits the namespace); `card` is the section a card field renders under, + * and a row without it is config-only. + */ +export type SettingRow = + | { card?: GroupId; default: boolean; kind: "boolean"; volatile: boolean } + | { default?: string; kind: "string"; volatile: boolean } + | { + card?: GroupId; + default: string; + kind: "choice"; + values: readonly string[]; + volatile: boolean; + } + /** A list the row may replace; empty means the default. */ + | { default: readonly string[]; kind: "list"; volatile: boolean } + /** A list the row adds to: the default is always included. */ + | { default: readonly string[]; kind: "routes"; volatile: boolean }; + +// Adding a setting is one row here, plus its copy when the card shows it. +// The card imports this module and never `config.ts`, so schemastery stays on +// the host; the prose (`SETTING_PROSE`) is a separate export no client module +// imports (`config.ts` is its one reader), so the bundler drops it from the +// page. JSDoc ships with the client bundle, which is why the row docs below +// stay to a line. + +/** + * Every setting: the card's rows in render order, each group adjacent (a + * heading goes where the group changes), then the config-only rows. + */ +export const SETTINGS = { + // The endpoint family and the credential choice both live under `access`: + // together they are "which account, on which endpoint", and filing the + // credential knob under the quota meter instead is what made it hard to find. + /** Endpoint family: `auto` (= `modern`), `modern` or `legacy`. */ + endpoint: { + card: "access", + default: DEFAULT_ENDPOINT_FAMILY, + kind: "choice", + values: ENDPOINT_FAMILIES, + volatile: true, + }, + /** Which credential source wins when several resolve. */ + keySource: { + card: "access", + default: DEFAULT_KEY_SOURCE, + kind: "choice", + values: KEY_SOURCE_POLICIES, + volatile: true, + }, + /** May the OpenCode installation's own store be read (LAST). */ + readOpencodeStore: { + card: "access", + default: false, + kind: "boolean", + volatile: true, + }, + injectUserAgent: { + card: "requests", + default: true, + kind: "boolean", + volatile: true, + }, + injectOriginHeaders: { + card: "requests", + default: true, + kind: "boolean", + volatile: true, + }, + injectProject: { + card: "requests", + default: true, + kind: "boolean", + volatile: true, + }, + enrichModels: { + card: "models", + default: true, + kind: "boolean", + volatile: true, + }, + injectCoreTools: { + card: "models", + default: true, + kind: "boolean", + volatile: true, + }, + usageEnabled: { + card: "quota", + default: true, + kind: "boolean", + volatile: true, + }, + /** Org sent with an account credential that carries none. */ + credentialOrg: { kind: "string", volatile: true }, + debug: { default: false, kind: "boolean", volatile: false }, + debugFile: { kind: "string", volatile: false }, + userAgent: { kind: "string", volatile: true }, + /** Value restored into `x-opencode-client`. */ + originClient: { default: "cli", kind: "string", volatile: true }, + /** Env var holding a fallback session id. */ + sessionIdEnv: { + default: "OPENCODE_SESSION_ID", + kind: "string", + volatile: true, + }, + /** Model-id substring marking free-tier; `*` is every model. */ + freeModelMarker: { default: "free", kind: "string", volatile: true }, + /** Routes whose turns this plugin decorates: the planes, always. */ + providers: { default: DEFAULT_PROVIDERS, kind: "routes", volatile: true }, + /** URL substrings marking gateway traffic. */ + gatewayUrls: { + default: ["opencode.ai/zen", "opencode.ai/inference"], + kind: "list", + volatile: true, + }, + /** OpenCode Go quota endpoint. */ + usageBaseURL: { + default: "https://opencode.ai/zen/go/v1", + kind: "string", + volatile: true, + }, +} as const satisfies Record; + +/** The table's rows, by key. */ +export type SettingRows = typeof SETTINGS; + +/** Every setting's key. */ +export type SettingKey = keyof SettingRows; + +/** The keys the card renders a control for. */ +export type CardSettingKey = { + [K in SettingKey]: SettingRows[K] extends { card: GroupId } ? K : never; +}[SettingKey]; + +/** The keys whose value is one of a fixed set. */ +export type ChoiceSettingKey = { + [K in SettingKey]: SettingRows[K] extends { kind: "choice" } ? K : never; +}[SettingKey]; + +/** The copy key naming one value of a choice field: `endpoint` + `Auto`. */ +export type OptionCopyKey = { + [ + K in ChoiceSettingKey + ]: `${K}${Capitalize}`; +}[ChoiceSettingKey]; + +/** + * Every copy key the table implies: a card field's label (its own key) and + * hint, each choice's label, and each group's heading. `settings-copy.ts` + * checks its dictionary against this, so a card row without its copy fails to + * compile. + */ +export type SettingsCopyKey = + | CardSettingKey + | `${CardSettingKey}Hint` + | OptionCopyKey + | `group${Capitalize}`; + +/** Every setting's key, in the table's order. */ +export const SETTING_KEYS: readonly SettingKey[] = Object.keys(SETTINGS).filter( + (key): key is SettingKey => key in SETTINGS +); + +/** Whether the card renders `key`. */ +export const isCardSetting = (key: SettingKey): key is CardSettingKey => + "card" in SETTINGS[key]; + +/** Whether the card leaves `key` to the row. */ +export const isConfigOnlySetting = ( + key: SettingKey +): key is Exclude => !isCardSetting(key); + +/** Whether `key` holds one of a fixed set of values. */ +export const isChoiceSetting = (key: SettingKey): key is ChoiceSettingKey => + SETTINGS[key].kind === "choice"; + +/** Every value a choice field offers. */ +type ChoiceValue = SettingRows[ChoiceSettingKey]["values"][number]; + +// Each choice value and group id as a copy key spells it. A lookup rather than +// a capitaliser: the type makes every entry exact, so a new value or group +// without its spelling fails to compile, and the level names keep the one +// capitalisation in `src` (`effortName`). +const CAPITALIZED: { readonly [W in ChoiceValue | GroupId]: Capitalize } = { + access: "Access", + auto: "Auto", + configured: "Configured", + legacy: "Legacy", + models: "Models", + modern: "Modern", + quota: "Quota", + request: "Request", + requests: "Requests", +}; + +/** A card field's label key: the field's own name. */ +export const labelKeyOf = (field: K): K => field; + +/** A card field's hint key. */ +export const hintKeyOf = (field: K): `${K}Hint` => + `${field}Hint`; + +/** + * The label key of one choice of a choice field: `endpoint` and `auto` give + * `endpointAuto`. Typed as the table's option keys: with a union of fields the + * compiler cannot pair each field with its own values, and the caller reads + * both off the same row. + */ +export const optionKeyOf = ( + field: K, + value: SettingRows[K]["values"][number] +): OptionCopyKey => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the caller reads the field and the value off the same row. + `${field}${CAPITALIZED[value]}` as OptionCopyKey; + +/** A card group's heading key. */ +export const groupKeyOf = ( + group: G +): `group${Capitalize}` => `group${CAPITALIZED[group]}`; + +/** + * What the row's reader is told about each key: the schema's description, and + * for a key the card does not show, why (the type requires it there, and only + * there). Host-side reading only, kept apart + * from {@link SETTINGS} so the client bundle, which imports the table, drops + * it. + * + * Why a key stays off the card, in general: the card shows the decisions a + * user makes, behaviour toggles and the credential policy. A config-only key is + * an override: a literal (a UA string, a header value, an endpoint), a marker + * (a model-id or URL substring), or a reference (an env-var name, a credential + * ref, a route list). Its default is right for every documented setup, so a + * control would only invite someone to break their own routing; it stays + * editable in the row's `config`, and `cordis.patch.yml` documents it. + */ +export const SETTING_PROSE: { + readonly [K in SettingKey]: K extends CardSettingKey + ? { description: string } + : { description: string; reason: string }; +} = { + credentialOrg: { + description: + "The org id (wrk_...) to send with an account credential. A login through " + + "this plugin stores the org with the token, so this is only for a token " + + "that came from elsewhere.", + reason: + "the org an account credential belongs to; a login through this plugin " + + "stores it with the token, so the row is for a token that came from " + + "elsewhere and has no UI to belong to", + }, + debug: { + description: "Log injected streamed calls.", + reason: + "diagnostic console logging of streamed calls, not a behaviour a user " + + "tunes in the UI", + }, + debugFile: { + description: "Server-side path for JSONL stream-debug entries.", + reason: + "the JSONL file both debug halves append to; naming it writes the file " + + "whether or not debug is on, and a server-side path is a deployment fact " + + "rather than a card control", + }, + endpoint: { + description: + "Which endpoint family the gateway's requests go to. modern: the " + + "per-protocol inference family, " + + "https://opencode.ai/inference/{openai,anthropic,google}/... on Zen " + + "and https://opencode.ai/inference/go/{openai,anthropic,google}/... " + + "on Go. auto: an alias of modern, and the default. legacy: the older " + + "single base per plane, https://opencode.ai/zen/v1 and " + + "https://opencode.ai/zen/go/v1. The two families are separately " + + "entitled and both still answer, so this is a choice rather than a " + + "migration; an unrecognised value falls back to auto.", + }, + enrichModels: { + description: + "Enrich the gateway /models listing and Settings model discovery from the OpenCode catalog; a plane's model info follows the user's row and the catalog either way.", + }, + freeModelMarker: { + description: + "Model-id marker triggering the core-tool fallback; * applies to every model.", + reason: + "model-id substring; 'free' tracks the vendor's ids, '*' forces the fallback", + }, + gatewayUrls: { + description: + "URL substrings marking OpenCode gateway traffic (matched before providers).", + reason: "URL substrings; only a mirror or relay needs to change them", + }, + injectCoreTools: { + description: + "Auto-inject read and bash tool schemas on free-tier requests.", + }, + injectOriginHeaders: { + description: "Inject x-opencode-client header.", + }, + injectProject: { + description: + "Attach the active workspace folder name (or 'global' if outside a project) in x-opencode-project.", + }, + injectUserAgent: { + description: + "Restore the opencode CLI User-Agent stripped by the DSH LLM adapter.", + }, + keySource: { + description: + "Which credential source wins when several resolve. auto: a literal key declared in another entry, then a key captured from a live request, then the declared reference, then a captured key for the other plane. request: a captured key first, then a literal one, then the declared reference. configured: a literal key, then the declared reference, then captured ones. An unrecognised value falls back to auto.", + }, + originClient: { + description: "Value restored into the x-opencode-client header.", + reason: + "literal x-opencode-client value; the default ('cli') is what the gateway expects", + }, + providers: { + description: + "Route ids whose turns this plugin decorates; opencode and opencode-go are always included.", + reason: + "route ids whose turns are decorated; both planes are always included, so only a relay route needs adding", + }, + readOpencodeStore: { + description: + "Read the credential the OpenCode installation already holds, from its " + + "own database, as the LAST resort: after every credential this " + + "deployment declares. Off by default — reading another tool's store is " + + "something a user turns on, not something that happens to them.", + }, + sessionIdEnv: { + description: + "Environment variable consulted for the fallback session id outside a turn.", + reason: "names an env var only a caller-supplied session id would use", + }, + usageBaseURL: { + description: "OpenCode Go gateway base URL.", + reason: "endpoint override; auto-discovered from the composition", + }, + usageEnabled: { + description: "Enable host-side OpenCode Go usage querying.", + }, + userAgent: { + description: + "Custom User-Agent string. Leave blank to use the canonical OpenCode CLI one.", + reason: + "literal User-Agent override; the default is the canonical CLI string", + }, +}; diff --git a/src/usage-pill.tsx b/src/usage-pill.tsx index c578965..267bbfc 100644 --- a/src/usage-pill.tsx +++ b/src/usage-pill.tsx @@ -79,10 +79,6 @@ export interface UsagePillProps { */ directory?: SnapshotStore; getLocale?: () => string; - /** - * Deprecated: model markers are no longer used for gating. Kept optional for backward compatibility. - */ - modelMarkers?: readonly string[]; /** Why the meter has no directory; set only on the diagnostic path. */ reason?: string; /** @@ -437,7 +433,6 @@ const reportAbsence = (reason: string): void => { export const UsagePill = ({ directory, meterProviders, - modelMarkers: _modelMarkers, reason, ...props }: UsagePillProps): React.ReactElement | null => { diff --git a/test/architecture.test.ts b/test/architecture.test.ts index 7d6d08d..7ec9313 100644 --- a/test/architecture.test.ts +++ b/test/architecture.test.ts @@ -527,6 +527,10 @@ describe("architecture · the client bundle reaches nothing host-only", () => { expect(graph.has("config-values.ts")).toBe(true); // And it must not wander into the host half through a type-only import. expect(graph.has("lifecycle.ts")).toBe(false); + // The settings table does, and the schema module, and schemastery with + // it, never reaches the browser. + expect(graph.has("settings-table.ts")).toBe(true); + expect(graph.has("config.ts")).toBe(false); }); it("imports no node built-in, no cordis runtime and no pi", () => { diff --git a/test/client-bundle.test.ts b/test/client-bundle.test.ts index cd3164f..900e82e 100644 --- a/test/client-bundle.test.ts +++ b/test/client-bundle.test.ts @@ -309,4 +309,16 @@ describe("client-bundle: artifact & VM loader boundary", () => { registeredSlots.filter((slot) => slot === "conversation.input.right") ).toHaveLength(1); }); + + it("ships no schema description and no config-only reason", () => { + // The settings table's prose (each key's schema description and the reason + // a key stays off the card) is host-side reading: the card renders neither. + // It is one export no client module imports (`config.ts`, host-side, is + // its one reader, `CONFIG_ONLY_FIELDS` included), so the bundler drops it, + // and a client module that started reading it would ship it all. + // Known answer: the card's own copy is in the bundle. + expect(SOURCE).toContain("Credential Source"); + expect(SOURCE).not.toContain("Route ids whose turns this plugin decorates"); + expect(SOURCE).not.toContain("literal User-Agent override"); + }); }); diff --git a/test/deleted-settings.test.ts b/test/deleted-settings.test.ts index 5409320..c85698a 100644 --- a/test/deleted-settings.test.ts +++ b/test/deleted-settings.test.ts @@ -17,6 +17,8 @@ * The hidden routes the plugin used to mount (`INTERNAL_ROUTES`, * `opencode-responses`, `opencode-anthropic`, `opencode-google` and their Go * twins) went with them (D13): the planes are the only routes it claims. + * The meter's `modelMarkers` prop (and the `usageModelMarkers` key that fed + * it) went in P8: the meter's gate is the provider list, and nothing read it. * * @module test/deleted-settings.test */ @@ -32,7 +34,7 @@ const ROOT = join(import.meta.dirname, ".."); /** A deleted name, as a whole word. */ const DELETED = - /\b(?:internalRoutes|resolveRoutedKey|RoutedKeyDetails|modelOverrides|maxContextWindow|modelRoutes|hiddenModels|INTERNAL_ROUTES)\b|\bopencode-(?:go-)?(?:responses|anthropic|google)\b/u; + /\b(?:internalRoutes|resolveRoutedKey|RoutedKeyDetails|modelOverrides|maxContextWindow|modelRoutes|hiddenModels|INTERNAL_ROUTES|modelMarkers|usageModelMarkers)\b|\bopencode-(?:go-)?(?:responses|anthropic|google)\b/u; /** The deleted settings, one by one, for the places that list settings. */ const DELETED_SETTINGS: readonly string[] = [ @@ -54,7 +56,7 @@ const PI_AI_KEY_READERS: ReadonlyMap = new Map([ /** What a README may not name outside its "Changed in 1.x" section. */ const DELETED_IN_README = - /\b(?:internalRoutes|modelOverrides|maxContextWindow|modelRoutes|hiddenModels|INTERNAL_ROUTES)\b|\bopencode-(?:go-)?(?:responses|anthropic|google)\b/u; + /\b(?:internalRoutes|modelOverrides|maxContextWindow|modelRoutes|hiddenModels|INTERNAL_ROUTES|modelMarkers|usageModelMarkers)\b|\bopencode-(?:go-)?(?:responses|anthropic|google)\b/u; /** Every `.ts`/`.tsx` under `dir`, at any depth, relative to `ROOT`. */ const sourcesUnder = (dir: string): string[] => diff --git a/test/host-planes.test.ts b/test/host-planes.test.ts index 84da9a8..2f1fd1f 100644 --- a/test/host-planes.test.ts +++ b/test/host-planes.test.ts @@ -32,11 +32,13 @@ import { routeIds, settle, stateOf, + turn, wire, } from "./support/host-planes.ts"; import { type ApplyOrder, bootTierB, + CHARACTERIZED_MODELS, characterizedProviders, drainStream, fakeCredentials, @@ -332,6 +334,66 @@ describe("host planes · lifecycle", { timeout: 30_000 }, () => { expect(restarts() - before).toBe(0); }); + it("a volatile edit of the plugin's own row commits in place, and the plugin follows it only once re-applied (tier B; the card's re-apply line)", async () => { + const { tier } = await bootPlanes(); + await waitForPlaneOwner(tier.llm); + const { pluginEntry } = tier; + if (pluginEntry === undefined) { + throw new Error("no plugin row"); + } + const volatile: unknown[] = []; + tier.ctx.on( + "loader/volatile-update", + (paths: unknown) => { + volatile.push(paths); + }, + { global: true } + ); + const model = CHARACTERIZED_MODELS.opencode[0] ?? ""; + // The plane headers of one turn's first request. `x-opencode-client` + // (`injectOriginHeaders`, on by default) is the positive control: it goes + // out on every turn the plugin decorates, so a missing project header + // means the plugin read its row, not that it stopped decorating. + const planeHeaders = async (): Promise<{ + client: unknown; + project: unknown; + }> => { + const { requests } = await turn(tier.llm, "opencode", model); + expect(requests.length, "the turn reached the wire").toBeGreaterThan(0); + const headers = requests[0]?.headers ?? {}; + return { + client: headers["x-opencode-client"], + project: headers["x-opencode-project"], + }; + }; + // A known answer first: the default sends the header. + expect(await planeHeaders()).toEqual({ client: "cli", project: "global" }); + + const { fiber } = pluginEntry; + // The write the card's save performs: Settings' `mutate` on the row's + // namespace, which checks the path is volatile before the config editor + // commits it. + await tier.ctx.settings.mutate(pluginEntry.options.id, [ + { op: "set", path: ["injectProject"], value: false }, + ]); + // The loader committed it as a volatile edit: one update naming the key, + // and the same fiber, so nothing re-ran the plugin's apply. + expect(volatile).toEqual([[["injectProject"]]]); + expect(pluginEntry.fiber).toBe(fiber); + expect(stateOf(fiber)).toBe(FIBER_STATE.ACTIVE); + // The plugin read its row once, at apply: the header still goes out. + expect(await planeHeaders()).toEqual({ client: "cli", project: "global" }); + + // Re-applied, it follows the row. + await fiber?.restart(); + await until( + () => stateOf(pluginEntry.fiber) === FIBER_STATE.ACTIVE, + "the plugin row applies again" + ); + await waitForPlaneOwner(tier.llm); + expect(await planeHeaders()).toEqual({ client: "cli", project: undefined }); + }); + it("an llm restart registers every route again, the planes the plugin's (tier B)", async () => { const { tier } = await bootPlanes(); await waitForPlaneOwner(tier.llm); diff --git a/test/manifest.test.ts b/test/manifest.test.ts index 6786d5d..6bd057e 100644 --- a/test/manifest.test.ts +++ b/test/manifest.test.ts @@ -16,7 +16,9 @@ import { Config, CONFIG_ONLY_FIELDS, DEFAULT_PROVIDERS, + ENDPOINT_FAMILIES, isRecord, + KEY_SOURCE_POLICIES, name as PLUGIN_NAME, NS, } from "./support/src.ts"; @@ -108,6 +110,13 @@ describe("bundle manifest consistency", () => { }); }); +/** One documented key: the type label after `key:`, and its whole entry. */ +interface DocumentedKey { + /** The key's line and its deeper-indented continuation lines, joined. */ + block: string; + label: string; +} + /** * The keys `cordis.patch.yml` documents in its header and sets in its row. * @@ -120,7 +129,13 @@ describe("bundle manifest consistency", () => { */ const manifestKeys = ( text: string -): { card: string[]; configOnly: string[]; set: string[] } => { +): { + card: string[]; + configOnly: string[]; + documented: Map; + row: Map; + set: string[]; +} => { const lines = text.split("\n"); const insert = lines.findIndex((line) => line.startsWith("- insert:")); const cardStart = lines.findIndex((line) => line.includes("CARD_FIELDS")); @@ -144,13 +159,100 @@ const manifestKeys = ( .map((line) => pattern.exec(line)?.[1]) .filter((key): key is string => key !== undefined); const documented = /^# {3}([A-Za-z]\w*):/u; + const entries = new Map(); + for (const [index, line] of lines.slice(0, insert).entries()) { + const head = /^# {3}([A-Za-z]\w*):\s+(\S+)/u.exec(line); + if (head?.[1] === undefined || head[2] === undefined) { + continue; + } + const continuation = lines + .slice(index + 1) + .findIndex((next) => !/^# {4,}\S/u.test(next)); + const end = continuation === -1 ? insert : index + 1 + continuation; + entries.set(head[1], { + block: lines.slice(index, end).join("\n"), + label: head[2], + }); + } + const row = new Map( + lines + .slice(configStart + 1) + .map((line) => /^ {8}([A-Za-z]\w*):\s*(.*)$/u.exec(line)) + .filter((match) => match?.[1] !== undefined) + .map((match) => [match?.[1] ?? "", match?.[2] ?? ""]) + ); return { card: keysOf(lines.slice(cardStart, configOnlyStart), documented), configOnly: keysOf(lines.slice(configOnlyStart, insert), documented), + documented: entries, + row, set: keysOf(lines.slice(configStart + 1), /^ {8}([A-Za-z]\w*):/u), }; }; +/** How the header and the row spell a default: a string bare, else as JSON. */ +const literalOf = (value: unknown): string => + typeof value === "string" ? value : JSON.stringify(value); + +/** + * The list a header block states after "default": the quoted items when the + * phrase quotes them (`default both families: ['a', 'b']`), else its + * comma-separated words (`default: a, b`), up to the first `;` or `)`. + * Continuation lines are joined first, so a list may wrap. + */ +const statedList = (block: string): string[] | undefined => { + const joined = block.replaceAll(/\n#\s+/gu, " "); + const phrase = /default:?\s+([^;)]*)/u.exec(joined)?.[1]; + if (phrase === undefined) { + return undefined; + } + const quoted = [...phrase.matchAll(/'([^']*)'|"([^"]*)"/gu)].map( + (match) => match[1] ?? match[2] ?? "" + ); + if (quoted.length > 0) { + return quoted; + } + return phrase + .split(",") + .map((word) => word.trim()) + .filter((word) => word !== ""); +}; + +/** + * Whether a header block states `fallback` as its default. A scalar must be + * the phrase right after "default" (`(default 'auto'`, `(default false)`, + * `inherits the default 'free'`), because a block may name every choice or + * spell a type label that contains the value; an opening quote must close, and + * the value must end there, so a longer value is not read as a shorter one. A + * list must be stated whole, as the same set of whole items. + */ +const statesDefault = (block: string, fallback: unknown): boolean => { + if (Array.isArray(fallback)) { + const stated = statedList(block); + const expected = fallback.map(literalOf); + return ( + stated !== undefined && + stated.length === new Set(stated).size && + stated.toSorted().join("\n") === expected.toSorted().join("\n") + ); + } + const literal = literalOf(fallback).replaceAll( + /[.*+?^${}()|[\]\\]/gu, + "\\$&" + ); + return new RegExp( + String.raw`default:?\s+(['"]?)${literal}\1(?![\w./:-])`, + "u" + ).test(block); +}; + +/** The type labels the header may give a key, by the schema node's `type`. */ +const LABELS_BY_TYPE: Record = { + array: ["[string]"], + boolean: ["boolean", "bool", "true|false"], + string: ["string", "path"], +}; + describe("cordis.patch.yml agrees with the schema and the field registry", () => { const root = path.dirname(import.meta.dirname); const read = async () => @@ -197,4 +299,179 @@ describe("cordis.patch.yml agrees with the schema and the field registry", () => expect(set).toContain("providers"); expect(new Set(set).size).toBe(set.length); }); + + it("labels each key with its schema type and names every choice value", async () => { + const { documented } = await read(); + // Known answers: the reader found both kinds of label. + expect(documented.get("providers")?.label).toBe("[string]"); + expect(documented.get("debugFile")?.label).toBe("path"); + expect([...documented.keys()].toSorted()).toEqual(schemaKeys.toSorted()); + + const mislabelled = [...documented].flatMap(([key, entry]) => { + const type = Config.dict?.[key]?.type ?? "missing"; + return (LABELS_BY_TYPE[type] ?? []).includes(entry.label) + ? [] + : [`${key}: ${entry.label} (schema ${type})`]; + }); + expect(mislabelled).toEqual([]); + + for (const value of KEY_SOURCE_POLICIES) { + expect(documented.get("keySource")?.block).toContain(value); + } + for (const value of ENDPOINT_FAMILIES) { + expect(documented.get("endpoint")?.block).toContain(value); + } + }); + + it("sets only defaults in the shipped row", async () => { + const { row } = await read(); + // Known answers, so an empty read cannot pass. + expect(row.get("debug")).toBe("false"); + expect(row.get("userAgent")).toBe('""'); + + const drifted = [...row].flatMap(([key, text]) => { + const fallback: unknown = Config.dict?.[key]?.meta.default; + if (text === "") { + // A list follows on the next lines; the providers case reads it. + return Array.isArray(fallback) ? [] : [`${key}: no value`]; + } + if (text === '""') { + // A blank string is unset: only a key without a default may carry it. + return fallback === undefined ? [] : [`${key}: blank over a default`]; + } + return text === literalOf(fallback) ? [] : [`${key}: ${text}`]; + }); + expect(drifted).toEqual([]); + }); + + it("documents the card fields and the config-only fields in the table's order", async () => { + const { card, configOnly } = await read(); + expect(card).toStrictEqual(CARD_FIELDS.map((entry) => entry.field)); + expect(configOnly).toStrictEqual( + CONFIG_ONLY_FIELDS.map((entry) => entry.field) + ); + }); + + it("states every default the schema has", async () => { + const { documented } = await read(); + const unstated = [...documented].flatMap(([key, entry]) => { + const fallback: unknown = Config.dict?.[key]?.meta.default; + if (fallback === undefined) { + return []; + } + return statesDefault(entry.block, fallback) ? [] : [key]; + }); + // Known answer: the reader saw a block with a default in it. + expect(documented.get("usageBaseURL")?.block).toContain( + "https://opencode.ai/zen/go/v1" + ); + expect(unstated).toEqual([]); + }); + + it("reads the stated default, not any mention of its value (planted controls)", () => { + // Each block names the drifted value elsewhere, the way the real header + // lists every choice or spells a type label; only the phrase after + // "default" counts. + const cases: [string, unknown, boolean][] = [ + [ + "# endpoint: string auto | modern | legacy (default 'auto', an alias)", + "auto", + true, + ], + [ + "# endpoint: string auto | modern | legacy (default 'legacy')", + "auto", + false, + ], + [ + "# debug: true|false log calls\n# (default false).", + false, + true, + ], + [ + "# debug: true|false log calls\n# (default false).", + true, + false, + ], + [ + "# originClient: string x-opencode-client value (default 'x').", + "cli", + false, + ], + [ + "# originClient: string x-opencode-client value (default 'cli').", + "cli", + true, + ], + [ + "# freeModelMarker: string ('*' = all; inherits the default 'free')", + "*", + false, + ], + [ + "# freeModelMarker: string ('*' = all; inherits the default 'free')", + "free", + true, + ], + [ + "# providers: [string] ids (default: opencode,\n# opencode-go)", + ["opencode", "opencode-go"], + true, + ], + [ + "# providers: [string] ids (default: opencode)", + ["opencode", "opencode-go"], + false, + ], + // A list states as many items as the default holds: one stated item + // against two expected fails on the count. + [ + "# providers: [string] ids (default: opencode-go)", + ["opencode", "opencode-go"], + false, + ], + // A list item is a whole item, not a substring of a longer one: the + // count agrees here, so only whole-item equality decides it. + [ + "# providers: [string] ids (default: opencode-zen, opencode-go)", + ["opencode", "opencode-go"], + false, + ], + // A list states the default whole: an item the default dropped fails. + [ + "# gatewayUrls: [string] substrings (default both\n# families: ['opencode.ai/zen', 'opencode.ai/inference']).", + ["opencode.ai/zen"], + false, + ], + [ + "# gatewayUrls: [string] substrings (default both\n# families: ['opencode.ai/zen', 'opencode.ai/inference']).", + ["opencode.ai/zen", "opencode.ai/inference"], + true, + ], + // A quoted scalar must close on the value: a quoted URL that extends it + // fails at the closing quote. + [ + "# usageBaseURL: string base (default 'https://opencode.ai/zen/go/v1').", + "https://opencode.ai/zen/go", + false, + ], + // An unquoted scalar is the whole value: no closing quote to miss, so + // only the end-of-value check decides that a longer URL fails. + [ + "# usageBaseURL: string base (default https://opencode.ai/zen/go/v1).", + "https://opencode.ai/zen/go", + false, + ], + [ + "# usageBaseURL: string base (default 'https://opencode.ai/zen/go/v1').", + "https://opencode.ai/zen/go/v1", + true, + ], + // An opening quote must close on the value. + ["# originClient: string value (default 'cli-x').", "cli", false], + ]; + for (const [block, fallback, expected] of cases) { + expect(statesDefault(block, fallback), block).toBe(expected); + } + }); }); diff --git a/test/package-checks.test.ts b/test/package-checks.test.ts index a9c51a4..871715e 100644 --- a/test/package-checks.test.ts +++ b/test/package-checks.test.ts @@ -41,7 +41,6 @@ import { } from "../scripts/package-checks.ts"; import * as packageChecks from "../scripts/package-checks.ts"; import { SCOPED_TARGETS } from "../scripts/scoped-targets.ts"; -import { en as cardCopy } from "./support/src.ts"; const ROOT = join(import.meta.dirname, ".."); @@ -374,7 +373,7 @@ describe("package checks · the manifest (moved from check.ts)", () => { expect(dts).toMatch(/interface TypertRemoteContribution\b/u); }); - it("the locales hold the same keys, and the bundle shows one display name", () => { + it("the locales hold the same keys", () => { const [en, zh] = ["en", "zh"].map( (lang) => JSON.parse( @@ -388,6 +387,9 @@ describe("package checks · the manifest (moved from check.ts)", () => { const enKeys = localeKeyPaths(en).toSorted(); expect(enKeys.length).toBeGreaterThan(0); expect(localeKeyPaths(zh).toSorted()).toStrictEqual(enKeys); - expect(en?.meta?.title).toBe(cardCopy.title); + // A known answer that the read reached `meta.title`, the card's one + // display name; that the card's dictionary has no `title` of its own is + // pinned by test/settings-snapshot.test.ts. + expect(en?.meta?.title).toBe("OpenCode Patch"); }); }); diff --git a/test/settings-copy.test.ts b/test/settings-copy.test.ts index 892a360..f74dfee 100644 --- a/test/settings-copy.test.ts +++ b/test/settings-copy.test.ts @@ -16,10 +16,19 @@ */ import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { en, withBundleCopy, zh } from "./support/src.ts"; +import { + CARD_FIELDS, + en, + isRecord, + withBundleCopy, + zh, +} from "./support/src.ts"; +import { blankCommentLines } from "./support/strip-comments.ts"; /** A seat whose dictionary predates every key: it answers with the key itself. */ const staleSeat = (key: string): string => key; @@ -109,3 +118,165 @@ describe("the dictionaries", () => { } }); }); + +describe("the card's name", () => { + const ROOT = join(import.meta.dirname, ".."); + const read = (file: string): string => readFileSync(join(ROOT, file), "utf8"); + /** + * The package's own title in one language. The host heads the card with it + * (the plugin manager reads `meta.title`), so it is the card's name; the + * dictionary has no title of its own. + */ + const metaTitle = (locale: "en" | "zh"): string => { + const parsed: unknown = JSON.parse(read(`locale/${locale}.json`)); + const title = + isRecord(parsed) && isRecord(parsed.meta) ? parsed.meta.title : undefined; + if (typeof title !== "string") { + throw new TypeError(`locale/${locale}.json has no meta.title`); + } + return title; + }; + + it("is the name each README gives the card", () => { + // Known answers: the reads reached the files. + expect(metaTitle("en")).toBe("OpenCode Patch"); + expect(metaTitle("zh")).toBe("OpenCode 补丁"); + expect(read("README.md")).toContain( + `_Settings → Plugins → ${metaTitle("en")}_` + ); + expect(read("README.zh-CN.md")).toContain( + `_Settings → Plugins → ${metaTitle("zh")}_` + ); + // The stale zh name P8 replaced is gone from every zh page, not only from + // the italic path: one sentence also named the card in bold. + for (const page of [ + "README.zh-CN.md", + "docs/detail.zh-CN.md", + "docs/quota-meter.zh-CN.md", + ]) { + const text = read(page); + expect(text.length, page).toBeGreaterThan(0); + expect(text, page).not.toContain("OpenCode 补丁设置"); + } + }); +}); + +describe("every copy key has a reader", () => { + const SRC = join(import.meta.dirname, "..", "src"); + + /** + * The keys of `keys` nothing in `sources` names: a quoted literal (`"x"`, + * `'x'` or `` `x` ``) in code, or one of `derived`, the keys the card builds + * from the settings table rather than spells. Comments are blanked first, + * so a word a comment quotes is not a reader: comment lines through + * {@link blankCommentLines}, then a JSX `{/* … *\/}` span and a `// …` tail + * after code (with a space before the `//`, so a `"https://…"` string is + * not cut short). Blanking too much is the loud direction for this scan, + * since a key it hides is reported as unread. + */ + const unread = ( + keys: readonly string[], + sources: readonly string[], + derived: ReadonlySet + ): string[] => { + const named = new Set(derived); + for (const text of sources) { + const code = blankCommentLines(text) + .replaceAll(/\{\/\*[\s\S]*?\*\/\}/gu, "") + .replaceAll(/(?<=\s)\/\/.*$/gmu, ""); + for (const match of code.matchAll(/["'`](\w+)["'`]/gu)) { + named.add(match[1] ?? ""); + } + } + return keys.filter((key) => !named.has(key)); + }; + + // Every source file but the dictionary itself, which names every key. + const sources = readdirSync(SRC, { recursive: true, withFileTypes: true }) + .filter( + (entry) => + entry.isFile() && + /\.tsx?$/u.test(entry.name) && + entry.name !== "settings-copy.ts" + ) + .map((entry) => readFileSync(join(entry.parentPath, entry.name), "utf8")); + const derived = new Set( + CARD_FIELDS.flatMap((entry) => [ + entry.labelKey, + entry.hintKey, + entry.group, + ...(entry.options ?? []).map((option) => option.labelKey), + ]) + ); + + it("names every key in src, spelled or derived from the table", () => { + // Known answers: the read reached the tree, a group heading is only + // derived, and a purge key is only spelled. + expect(sources.length).toBeGreaterThan(20); + expect(sources.some((text) => text.includes('"groupAccess"'))).toBe(false); + expect(derived).toContain("groupAccess"); + expect(unread(["purgeAction"], sources, new Set())).toEqual([]); + expect(unread(Object.keys(en), sources, derived)).toEqual([]); + }); + + it("reports a key nothing reads (planted)", () => { + expect( + unread([...Object.keys(en), "plantedOrphanKey"], sources, derived) + ).toEqual(["plantedOrphanKey"]); + // A key only a comment quotes has no reader: the comment is blanked. + const commented = [ + "/**", + " * The panel header (which is `plantedCommentKey`).", + " */", + "// and `plantedCommentKey` again", + 'export const read = t("purgeAction");', + ].join("\n"); + expect( + unread(["plantedCommentKey", "purgeAction"], [commented], new Set()) + ).toEqual(["plantedCommentKey"]); + // Nor does one only a JSX comment or a `//` tail after code quotes, + // though neither opens its line. + const jsxAndTail = [ + " return (", + "
", + " {/* the top-up link,", + ' labelled "plantedJsxKey" */}', + ' {t("purgeAction")} // was "plantedTailKey"', + ' {/* "plantedJsxKey" */}', + "
", + " );", + ].join("\n"); + expect( + unread( + ["plantedJsxKey", "plantedTailKey", "purgeAction"], + [jsxAndTail], + new Set() + ) + ).toEqual(["plantedJsxKey", "plantedTailKey"]); + // The fifteen keys P8 deleted, found by this same scan: had they stayed, + // each would be reported. `title` among them was quoted only by a comment + // in `src/usage-ui.ts`, about the meter's own panel header. + const deleted = [ + "storeInspectFound", + "loginAction", + "loginAgain", + "loginExpired", + "loginFailed", + "loginSignedIn", + "loginSignedOut", + "loginPlane", + "loginPlaneGo", + "loginPlaneZen", + "loginTitle", + "loginWaiting", + "zenFallbackNotice", + "zenOverflowActive", + "title", + ]; + expect(unread(deleted, sources, derived)).toEqual(deleted); + // A derived key is read only through the table. + expect(unread(["groupAccess"], sources, new Set())).toEqual([ + "groupAccess", + ]); + }); +}); diff --git a/test/settings-page-card.test.tsx b/test/settings-page-card.test.tsx index ee53711..b2c0081 100644 --- a/test/settings-page-card.test.tsx +++ b/test/settings-page-card.test.tsx @@ -17,7 +17,7 @@ import { KEY_SOURCE_POLICIES, PKG, } from "./support/src.ts"; -import { elementName, findAll, firstOf } from "./test-helpers.ts"; +import { collectText, elementName, findAll, firstOf } from "./test-helpers.ts"; describe("settings-page: OpencodeCard rendering", () => { const mountCard = () => { @@ -258,6 +258,49 @@ describe("settings-page: OpencodeCard rendering", () => { }); }; + it("says once, on the page view, that the settings apply when the plugin is applied again", () => { + // A Settings write takes the loader's volatile-only path and the plugin + // reads its row once, at apply, so an edit lands on the next apply. The + // card says so once, above the form, rather than in every control's hint. + const Card = mountCard(); + const seat = (k: string): string => `seat:${k}`; + const state = { + fields: {}, + shell: { + available: true, + dirty: false, + failed: false, + invalid: false, + saving: false, + writable: true, + }, + }; + const tree = Card({ + discard: () => {}, + edit: () => {}, + resetField: () => {}, + save: () => {}, + t: seat, + useOpencodeCard: (selector: (s: typeof state) => unknown) => + selector(state), + view: "page", + }); + const line = seat("appliesOnReapply"); + expect(collectText(tree).filter((text) => text === line)).toHaveLength(1); + // Not inside a control: no control carries it as a label or a hint. + const controls = controlsInOrder(tree); + expect(controls).toHaveLength(CARD_FIELDS.length); + for (const control of controls) { + expect(Object.values(control.props)).not.toContain(line); + expect(collectText(control)).not.toContain(line); + } + + const summary = Card({ t: seat, view: "summary" }) as { + props: { children: unknown }; + }; + expect(summary.props.children).toBe(seat("description")); + }); + it("renders one control per register entry, in register order", () => { const tree = renderPage(mountCard()); const controls = controlsInOrder(tree); diff --git a/test/settings-page.test.tsx b/test/settings-page.test.tsx index a778bd9..d170ed9 100644 --- a/test/settings-page.test.tsx +++ b/test/settings-page.test.tsx @@ -720,7 +720,6 @@ describe("settings-page: apply & slots", () => { status: "ready", user: {}, value: { - usageModelMarkers: ["custom-go-model"], providers: ["custom-go-route"], }, writable: true, diff --git a/test/settings-snapshot.test.ts b/test/settings-snapshot.test.ts new file mode 100644 index 0000000..ac01378 --- /dev/null +++ b/test/settings-snapshot.test.ts @@ -0,0 +1,851 @@ +/** + * The settings, pinned as the plugin derives them: the schema the loader + * validates the row with, the resolver's every key, the card's field specs and + * the copy keys. + * + * Written before P8 moved all of it onto one table (`src/settings-table.ts`) + * and run green on the hand-written tree, so the refactor is held to the same + * literals. The expectations are copied from that tree, not computed from the + * table, because a pin that reads its subject cannot see it change. The edits + * the refactor made to this file are named: in the copy keys, P8 deleted + * fifteen keys nothing rendered and added the card's re-apply line; + * `CONFIG_DEFAULTS` no longer carries `credentialOrg: undefined`; and the + * resolved type's three keys without a default are optional and none is + * readonly. + * + * @module test/settings-snapshot.test + */ + +import { describe, expect, it } from "vitest"; + +import { + CARD_FIELDS, + Config, + CONFIG_DEFAULTS, + CONFIG_ONLY_FIELDS, + en, + ENDPOINT_FAMILIES, + KEY_SOURCE_POLICIES, + type PluginConfig, + resolveConfig, + type ResolvedPluginConfig, + SPECS, + zh, +} from "./support/src.ts"; + +/** One schema node, read the way `settings.describe` and the loader read it. */ +interface SchemaPin { + default: unknown; + description: unknown; + inner: string | undefined; + meta: string[]; + type: string; + volatile: boolean; +} + +const MARKS = ["default", "description", "volatile"]; + +/** Every key of `Config`, as the hand-written schema declared it. */ +const SCHEMA: Record = { + endpoint: { + default: "auto", + description: + "Which endpoint family the gateway's requests go to. modern: the per-protocol inference family, https://opencode.ai/inference/{openai,anthropic,google}/... on Zen and https://opencode.ai/inference/go/{openai,anthropic,google}/... on Go. auto: an alias of modern, and the default. legacy: the older single base per plane, https://opencode.ai/zen/v1 and https://opencode.ai/zen/go/v1. The two families are separately entitled and both still answer, so this is a choice rather than a migration; an unrecognised value falls back to auto.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, + keySource: { + default: "auto", + description: + "Which credential source wins when several resolve. auto: a literal key declared in another entry, then a key captured from a live request, then the declared reference, then a captured key for the other plane. request: a captured key first, then a literal one, then the declared reference. configured: a literal key, then the declared reference, then captured ones. An unrecognised value falls back to auto.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, + readOpencodeStore: { + default: false, + description: + "Read the credential the OpenCode installation already holds, from its own database, as the LAST resort: after every credential this deployment declares. Off by default — reading another tool's store is something a user turns on, not something that happens to them.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + injectUserAgent: { + default: true, + description: + "Restore the opencode CLI User-Agent stripped by the DSH LLM adapter.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + injectOriginHeaders: { + default: true, + description: "Inject x-opencode-client header.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + injectProject: { + default: true, + description: + "Attach the active workspace folder name (or 'global' if outside a project) in x-opencode-project.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + enrichModels: { + default: true, + description: + "Enrich the gateway /models listing and Settings model discovery from the OpenCode catalog; a plane's model info follows the user's row and the catalog either way.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + injectCoreTools: { + default: true, + description: + "Auto-inject read and bash tool schemas on free-tier requests.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + usageEnabled: { + default: true, + description: "Enable host-side OpenCode Go usage querying.", + inner: undefined, + meta: MARKS, + type: "boolean", + volatile: true, + }, + credentialOrg: { + default: undefined, + description: + "The org id (wrk_...) to send with an account credential. A login through this plugin stores the org with the token, so this is only for a token that came from elsewhere.", + inner: undefined, + meta: ["description", "volatile"], + type: "string", + volatile: true, + }, + debug: { + default: false, + description: "Log injected streamed calls.", + inner: undefined, + meta: ["default", "description"], + type: "boolean", + volatile: false, + }, + debugFile: { + default: undefined, + description: "Server-side path for JSONL stream-debug entries.", + inner: undefined, + meta: ["description"], + type: "string", + volatile: false, + }, + userAgent: { + default: undefined, + description: + "Custom User-Agent string. Leave blank to use the canonical OpenCode CLI one.", + inner: undefined, + meta: ["description", "volatile"], + type: "string", + volatile: true, + }, + originClient: { + default: "cli", + description: "Value restored into the x-opencode-client header.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, + sessionIdEnv: { + default: "OPENCODE_SESSION_ID", + description: + "Environment variable consulted for the fallback session id outside a turn.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, + freeModelMarker: { + default: "free", + description: + "Model-id marker triggering the core-tool fallback; * applies to every model.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, + providers: { + default: ["opencode", "opencode-go"], + description: + "Route ids whose turns this plugin decorates; opencode and opencode-go are always included.", + inner: "string", + meta: MARKS, + type: "array", + volatile: true, + }, + gatewayUrls: { + default: ["opencode.ai/zen", "opencode.ai/inference"], + description: + "URL substrings marking OpenCode gateway traffic (matched before providers).", + inner: "string", + meta: MARKS, + type: "array", + volatile: true, + }, + usageBaseURL: { + default: "https://opencode.ai/zen/go/v1", + description: "OpenCode Go gateway base URL.", + inner: undefined, + meta: MARKS, + type: "string", + volatile: true, + }, +}; + +/** What an empty row resolves to, every key present. */ +const RESOLVED_EMPTY: ResolvedPluginConfig = { + credentialOrg: undefined, + debug: false, + debugFile: undefined, + endpoint: "auto", + enrichModels: true, + freeModelMarker: "free", + gatewayUrls: ["opencode.ai/zen", "opencode.ai/inference"], + injectCoreTools: true, + injectOriginHeaders: true, + injectProject: true, + injectUserAgent: true, + keySource: "auto", + originClient: "cli", + providers: new Set(["opencode", "opencode-go"]), + readOpencodeStore: false, + sessionIdEnv: "OPENCODE_SESSION_ID", + usageBaseURL: "https://opencode.ai/zen/go/v1", + usageEnabled: true, + userAgent: undefined, +}; + +/** The keys of each kind, so every key's degradation is run, not a sample. */ +const BOOLEAN_KEYS = [ + "readOpencodeStore", + "injectUserAgent", + "injectOriginHeaders", + "injectProject", + "enrichModels", + "injectCoreTools", + "usageEnabled", + "debug", +] as const; +const STRING_KEYS = [ + "credentialOrg", + "debugFile", + "userAgent", + "originClient", + "sessionIdEnv", + "freeModelMarker", + "usageBaseURL", +] as const; +const CHOICE_KEYS = { + endpoint: ENDPOINT_FAMILIES, + keySource: KEY_SOURCE_POLICIES, +} as const; + +/** Every copy key that stays, in both languages. */ +const LIVE_KEYS = [ + "description", + "endpoint", + "endpointAuto", + "endpointHint", + "endpointLegacy", + "endpointModern", + "enrichModels", + "enrichModelsHint", + "freeModel", + "goPlanTitle", + "goPlusTier", + "goTier", + "groupAccess", + "groupModels", + "groupQuota", + "groupRequests", + "injectCoreTools", + "injectCoreToolsHint", + "injectOriginHeaders", + "injectOriginHeadersHint", + "injectProject", + "injectProjectHint", + "injectUserAgent", + "injectUserAgentHint", + "invalidText", + "keySource", + "keySourceAuto", + "keySourceConfigured", + "keySourceHint", + "keySourceRequest", + "monthlyAllowance", + "overridden", + "purgeAction", + "purgeBusy", + "purgeCatalogUnread", + "purgeFailed", + "purgeHint", + "purgeNothing", + "purgeRemoved", + "purgeTitle", + "purgeUnavailable", + "readOnly", + "readOpencodeStore", + "readOpencodeStoreHint", + "reset", + "save", + "saveFailed", + "saving", + "sessionSpend", + "sessionSpendEmpty", + "storeInspect", + "storeInspectAccount", + "storeInspectBusy", + "storeInspectExpired", + "storeInspectExpires", + "storeInspectFailed", + "storeInspectHint", + "storeInspectKind", + "storeInspectKindKey", + "storeInspectKindOauth", + "storeInspectKindUnknown", + "storeInspectMissing", + "storeInspectNoAccount", + "storeInspectOrg", + "storeInspectRefreshable", + "storeInspectTitle", + "storeInspectUnavailable", + "storeInspectValid", + "unavailable", + "usageAuthRejected", + "usageConsole", + "usageEnabled", + "usageEnabledHint", + "usageLastUpdated", + "usageLimited", + "usageOverflowBilling", + "usageRefreshFailed", + "usageRefreshing", + "usageResetPassed", + "usageResetUnderMinute", + "usageResetsAtPrefix", + "usageResetsAtSuffix", + "usageResetsIn", + "usageRetry", + "usageSummaryAllowance", + "usageSummaryNote", + "usageSummaryRemaining", + "usageSummaryStatusLimited", + "usageSummaryStatusOk", + "usageSummaryTitle", + "usageSummaryUnavailable", + "usageSummaryUsed", + "usageTitle", + "usageTopUp", + "usageUnavailable", + "usageUpgradePlan", + "usageZenFallbackNotice", + "usage_monthly", + "usage_rolling", + "usage_weekly", + "zenCredit", + "zenPaygBadge", + "zenPaygTitle", + "zenPaygTooltip", +]; + +/** The keys P8 deleted: nothing in `src` rendered any of them. */ +const DELETED_IN_P8 = [ + "storeInspectFound", + "loginAction", + "loginAgain", + "loginExpired", + "loginFailed", + "loginSignedIn", + "loginSignedOut", + "loginPlane", + "loginPlaneGo", + "loginPlaneZen", + "loginTitle", + "loginWaiting", + "zenFallbackNotice", + "zenOverflowActive", + "title", +]; + +/** A volatile node's value, or the value itself. */ +const unwrap = (value: unknown): unknown => + value !== null && + typeof value === "object" && + "get" in value && + typeof value.get === "function" + ? Reflect.apply(value.get, value, []) + : value; + +const hasGet = (value: unknown): boolean => unwrap(value) !== value; + +describe("the settings, as the plugin derives them", () => { + it("the schema: every key's type, default, volatile flag and description", () => { + expect(Config.type).toBe("object"); + const dict = Config.dict ?? {}; + const actual = Object.fromEntries( + Object.entries(dict).map(([key, schema]) => [ + key, + { + default: schema.meta.default, + description: schema.meta.description, + inner: schema.inner?.type, + // The flag list itself, so a new one (loose, required, hidden) + // fails here rather than changing the schema quietly. + meta: Object.keys(schema.meta).toSorted(), + type: schema.type, + volatile: schema.meta.volatile === true, + }, + ]) + ); + expect(Object.keys(actual)).toHaveLength(19); + expect(actual).toStrictEqual(SCHEMA); + }); + + it("the schema, run: an empty row, a typo and a wrong type", () => { + /** A hand-edited row: the schema's input type would refuse the cases. */ + const load = (input: Record): Record => + Config(input as never); + const row = load({}); + // debugFile has neither a default nor `.volatile()`, so it is absent. + expect(Object.hasOwn(row, "debugFile")).toBe(false); + expect( + Object.fromEntries( + Object.entries(row).map(([key, value]) => [key, unwrap(value)]) + ) + ).toStrictEqual({ + credentialOrg: undefined, + debug: false, + endpoint: "auto", + enrichModels: true, + freeModelMarker: "free", + gatewayUrls: ["opencode.ai/zen", "opencode.ai/inference"], + injectCoreTools: true, + injectOriginHeaders: true, + injectProject: true, + injectUserAgent: true, + keySource: "auto", + originClient: "cli", + providers: ["opencode", "opencode-go"], + readOpencodeStore: false, + sessionIdEnv: "OPENCODE_SESSION_ID", + usageBaseURL: "https://opencode.ai/zen/go/v1", + usageEnabled: true, + userAgent: undefined, + }); + // Every volatile key answers a node; debug is a plain value. + expect( + Object.entries(row) + .filter(([, value]) => hasGet(value)) + .map(([key]) => key) + .toSorted() + ).toStrictEqual( + Object.entries(SCHEMA) + .filter(([key, pin]) => pin.volatile && key !== "debugFile") + .map(([key]) => key) + .toSorted() + ); + expect(hasGet(row.debug)).toBe(false); + + // The schema does not know the option sets: a typo passes it, and the + // resolver is what degrades it. + expect(unwrap(load({ endpoint: "typo" }).endpoint)).toBe("typo"); + expect(() => load({ keySource: "live" })).not.toThrow(); + // A wrong type fails the load. + expect(() => load({ keySource: 42 })).toThrow(); + expect(() => load({ debug: "x" })).toThrow(); + expect(() => load({ providers: "a" })).toThrow(); + // An unknown key does not. + expect(() => load({ noSuchSetting: 1 })).not.toThrow(); + }); + + it("the resolver: every key of an empty row, and each kind's degradation", () => { + const empty = resolveConfig({}); + expect(Object.keys(empty)).toHaveLength(19); + expect(empty).toStrictEqual(RESOLVED_EMPTY); + + const resolved = (key: string, value: unknown): unknown => + Reflect.get(resolveConfig({ [key]: value } as PluginConfig), key); + + for (const key of BOOLEAN_KEYS) { + const fallback = RESOLVED_EMPTY[key]; + for (const junk of ["yes", 1, null]) { + expect(resolved(key, junk), `${key} = ${String(junk)}`).toBe(fallback); + } + // A volatile node, holding the value the default is not: an unread + // node would resolve to the fallback. + expect(resolved(key, { get: () => !fallback }), key).toBe(!fallback); + expect(resolved(key, !fallback), key).toBe(!fallback); + } + + for (const key of STRING_KEYS) { + const fallback = RESOLVED_EMPTY[key]; + for (const junk of ["", " ", 42, null]) { + expect(resolved(key, junk), `${key} = ${String(junk)}`).toBe(fallback); + } + expect(resolved(key, " set "), key).toBe("set"); + expect(resolved(key, { get: () => " node " }), key).toBe("node"); + } + + for (const [key, values] of Object.entries(CHOICE_KEYS)) { + for (const value of values) { + expect(resolved(key, value), key).toBe(value); + } + for (const junk of ["typo", "", 42]) { + expect(resolved(key, junk), `${key} = ${String(junk)}`).toBe("auto"); + } + expect(resolved(key, { get: () => values.at(-1) }), key).toBe( + values.at(-1) + ); + } + + expect(resolved("gatewayUrls", [])).toStrictEqual( + RESOLVED_EMPTY.gatewayUrls + ); + expect(resolved("gatewayUrls", [" "])).toStrictEqual( + RESOLVED_EMPTY.gatewayUrls + ); + expect(resolved("gatewayUrls", [" a "])).toStrictEqual(["a"]); + expect(resolved("gatewayUrls", { get: () => [" a "] })).toStrictEqual([ + "a", + ]); + expect(resolved("providers", { get: () => ["r"] })).toStrictEqual( + new Set(["opencode", "opencode-go", "r"]) + ); + expect(resolved("providers", ["x"])).toStrictEqual( + new Set(["opencode", "opencode-go", "x"]) + ); + expect(resolved("providers", [])).toStrictEqual( + new Set(["opencode", "opencode-go"]) + ); + + // Strict: the hand-written object also carried `credentialOrg: + // undefined`, which the derived one, holding only the rows with a + // default, does not (a named edit; see the plan's P8 block). + expect(CONFIG_DEFAULTS).toStrictEqual({ + debug: false, + endpoint: "auto", + enrichModels: true, + freeModelMarker: "free", + gatewayUrls: ["opencode.ai/zen", "opencode.ai/inference"], + injectCoreTools: true, + injectOriginHeaders: true, + injectProject: true, + injectUserAgent: true, + keySource: "auto", + originClient: "cli", + providers: ["opencode", "opencode-go"], + readOpencodeStore: false, + sessionIdEnv: "OPENCODE_SESSION_ID", + usageBaseURL: "https://opencode.ai/zen/go/v1", + usageEnabled: true, + }); + }); + + it("the card: field specs, config-only knobs and draft conversions", () => { + expect(CARD_FIELDS).toStrictEqual([ + { + field: "endpoint", + group: "groupAccess", + hintKey: "endpointHint", + kind: "select", + labelKey: "endpoint", + options: [ + { labelKey: "endpointAuto", value: "auto" }, + { labelKey: "endpointLegacy", value: "legacy" }, + { labelKey: "endpointModern", value: "modern" }, + ], + }, + { + field: "keySource", + group: "groupAccess", + hintKey: "keySourceHint", + kind: "select", + labelKey: "keySource", + options: [ + { labelKey: "keySourceAuto", value: "auto" }, + { labelKey: "keySourceRequest", value: "request" }, + { labelKey: "keySourceConfigured", value: "configured" }, + ], + }, + { + field: "readOpencodeStore", + group: "groupAccess", + hintKey: "readOpencodeStoreHint", + kind: "boolean", + labelKey: "readOpencodeStore", + }, + { + field: "injectUserAgent", + group: "groupRequests", + hintKey: "injectUserAgentHint", + kind: "boolean", + labelKey: "injectUserAgent", + }, + { + field: "injectOriginHeaders", + group: "groupRequests", + hintKey: "injectOriginHeadersHint", + kind: "boolean", + labelKey: "injectOriginHeaders", + }, + { + field: "injectProject", + group: "groupRequests", + hintKey: "injectProjectHint", + kind: "boolean", + labelKey: "injectProject", + }, + { + field: "enrichModels", + group: "groupModels", + hintKey: "enrichModelsHint", + kind: "boolean", + labelKey: "enrichModels", + }, + { + field: "injectCoreTools", + group: "groupModels", + hintKey: "injectCoreToolsHint", + kind: "boolean", + labelKey: "injectCoreTools", + }, + { + field: "usageEnabled", + group: "groupQuota", + hintKey: "usageEnabledHint", + kind: "boolean", + labelKey: "usageEnabled", + }, + ]); + + expect(CONFIG_ONLY_FIELDS).toStrictEqual([ + { + field: "credentialOrg", + reason: + "the org an account credential belongs to; a login through this plugin stores it with the token, so the row is for a token that came from elsewhere and has no UI to belong to", + }, + { + field: "debug", + reason: + "diagnostic console logging of streamed calls, not a behaviour a user tunes in the UI", + }, + { + field: "debugFile", + reason: + "the JSONL file both debug halves append to; naming it writes the file whether or not debug is on, and a server-side path is a deployment fact rather than a card control", + }, + { + field: "userAgent", + reason: + "literal User-Agent override; the default is the canonical CLI string", + }, + { + field: "originClient", + reason: + "literal x-opencode-client value; the default ('cli') is what the gateway expects", + }, + { + field: "sessionIdEnv", + reason: "names an env var only a caller-supplied session id would use", + }, + { + field: "freeModelMarker", + reason: + "model-id substring; 'free' tracks the vendor's ids, '*' forces the fallback", + }, + { + field: "providers", + reason: + "route ids whose turns are decorated; both planes are always included, so only a relay route needs adding", + }, + { + field: "gatewayUrls", + reason: "URL substrings; only a mirror or relay needs to change them", + }, + { + field: "usageBaseURL", + reason: "endpoint override; auto-discovered from the composition", + }, + ]); + + expect(SPECS.map((spec) => spec.field)).toStrictEqual([ + "endpoint", + "keySource", + "readOpencodeStore", + "injectUserAgent", + "injectOriginHeaders", + "injectProject", + "enrichModels", + "injectCoreTools", + "usageEnabled", + ]); + for (const [index, spec] of SPECS.entries()) { + const entry = CARD_FIELDS[index]; + if (entry?.kind === "boolean") { + expect(spec.format(true), spec.field).toBe("true"); + expect(spec.format(false), spec.field).toBe("false"); + expect(spec.format("x"), spec.field).toBe(""); + expect(spec.parse(" TRUE "), spec.field).toStrictEqual({ + kind: "set", + value: true, + }); + expect(spec.parse("false"), spec.field).toStrictEqual({ + kind: "set", + value: false, + }); + expect(spec.parse(""), spec.field).toStrictEqual({ kind: "clear" }); + expect(spec.parse("maybe"), spec.field).toBeUndefined(); + } else { + expect(entry?.kind, spec.field).toBe("select"); + for (const option of entry?.options ?? []) { + expect(spec.parse(option.value), spec.field).toStrictEqual({ + kind: "set", + value: option.value, + }); + } + expect(spec.parse(""), spec.field).toStrictEqual({ kind: "clear" }); + expect(spec.parse("hand-edited"), spec.field).toBeUndefined(); + expect(spec.format(42), spec.field).toBe(""); + } + } + }); + + it("the copy keys: the full list, in both languages", () => { + expect(LIVE_KEYS).toHaveLength(104); + const expected = [...LIVE_KEYS, "appliesOnReapply"].toSorted(); + expect(Object.keys(en).toSorted()).toStrictEqual(expected); + expect(Object.keys(zh).toSorted()).toStrictEqual(expected); + for (const key of DELETED_IN_P8) { + expect(Object.keys(en)).not.toContain(key); + expect(Object.keys(zh)).not.toContain(key); + } + for (const entry of CARD_FIELDS) { + const keys = [ + entry.labelKey, + entry.hintKey, + entry.group, + ...(entry.options ?? []).map((option) => option.labelKey), + ]; + for (const key of keys) { + expect(LIVE_KEYS, entry.field).toContain(key); + } + } + }); + + it("the config types keep their keys and value types (compile-time)", () => { + // Optionality is normalised away here, so this says what each key holds; + // the modifiers are pinned below. + type Defined = { [K in keyof T]-?: Exclude }; + type Exact = [A] extends [B] + ? [B] extends [A] + ? true + : false + : false; + interface ExpectedRaw { + credentialOrg: string; + debug: boolean; + debugFile: string; + endpoint: "auto" | "legacy" | "modern"; + enrichModels: boolean; + freeModelMarker: string; + gatewayUrls: string[]; + injectCoreTools: boolean; + injectOriginHeaders: boolean; + injectProject: boolean; + injectUserAgent: boolean; + keySource: "auto" | "request" | "configured"; + originClient: string; + providers: string[]; + readOpencodeStore: boolean; + sessionIdEnv: string; + usageBaseURL: string; + usageEnabled: boolean; + userAgent: string; + } + interface ExpectedResolved extends Omit< + ExpectedRaw, + "gatewayUrls" | "providers" + > { + gatewayUrls: string[]; + providers: Set; + } + const raw: Exact, ExpectedRaw> = true; + const resolved: Exact< + Defined, + ExpectedResolved + > = true; + // The modifiers `Defined` normalises away, pinned on their own. The + // derived resolved type makes the three keys without a default optional + // and every key mutable; the hand-written one had `credentialOrg` required + // (as `string | undefined`) and it and `readOpencodeStore` readonly. Both + // loosen the type, so no reader or writer breaks (a named edit; see the + // plan's P8 block). + type OptionalKeys = { + [K in keyof T]-?: Pick extends Required> ? never : K; + }[keyof T]; + type Mutable = { -readonly [P in keyof O]: O[P] }; + // The one check TypeScript has that tells `readonly` apart: two generic + // signatures are identical only when the types they test are. + type Same = + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- the identity check's generic is never read, by design. + (() => V extends X ? 1 : 2) extends () => V extends Y ? 1 : 2 + ? true + : false; + type ReadonlyKeys = { + [K in keyof T]-?: Same, Mutable>> extends true + ? never + : K; + }[keyof T]; + const rawOptional: Exact< + OptionalKeys, + keyof ExpectedRaw + > = true; + const resolvedOptional: Exact< + OptionalKeys, + "credentialOrg" | "debugFile" | "userAgent" + > = true; + const rawMutable: Exact, never> = true; + const resolvedMutable: Exact< + ReadonlyKeys, + never + > = true; + // Known answers, so the two helpers cannot pass vacuously. + const optionalRead: Exact, "a"> = true; + const readonlyRead: Exact< + ReadonlyKeys<{ readonly c: 3; d: 4 }>, + "c" + > = true; + expect([ + raw, + resolved, + rawOptional, + resolvedOptional, + rawMutable, + resolvedMutable, + optionalRead, + readonlyRead, + ]).toStrictEqual([true, true, true, true, true, true, true, true]); + }); +}); diff --git a/test/settings-table.test.ts b/test/settings-table.test.ts new file mode 100644 index 0000000..527fe74 --- /dev/null +++ b/test/settings-table.test.ts @@ -0,0 +1,101 @@ +/** + * The settings table's own rules: the ones its type cannot state. + * + * The derived schema, resolver and card are pinned literally in + * `settings-snapshot.test.ts`; this file holds the table to the invariants a + * new row has to keep for those derivations to stay right. + * + * @module test/settings-table.test + */ + +import { describe, expect, it } from "vitest"; + +import { + Config, + PLANE_ROUTES, + resolveConfig, + SETTING_PROSE, + SETTINGS, +} from "./support/src.ts"; + +const rows = Object.entries(SETTINGS); + +describe("the settings table", () => { + it("has one row per schema key, in the schema's order", () => { + expect(rows).toHaveLength(19); + expect(Object.keys(Config.dict ?? {})).toStrictEqual(Object.keys(SETTINGS)); + }); + + it("gives a choice a default among its values", () => { + const choices = rows.flatMap(([key, row]) => + row.kind === "choice" ? [[key, row] as const] : [] + ); + // Known answer: both choice fields are read. + expect(choices.map(([key]) => key)).toStrictEqual([ + "endpoint", + "keySource", + ]); + for (const [key, row] of choices) { + expect(row.values, key).toContain(row.default); + } + }); + + it("keeps each card group's rows adjacent, and every card row first", () => { + const groups = rows.map(([, row]) => + "card" in row ? row.card : undefined + ); + const firstConfigOnly = groups.indexOf(undefined); + expect(firstConfigOnly).toBe(9); + expect( + groups.slice(firstConfigOnly).every((group) => group === undefined) + ).toBe(true); + const runs = groups + .slice(0, firstConfigOnly) + .filter((group, index, all) => index === 0 || all[index - 1] !== group); + expect(runs).toStrictEqual(["access", "requests", "models", "quota"]); + }); + + it("gives a reason exactly to the rows the card does not show", () => { + for (const [key, row] of rows) { + // Read as the general shape: the type already says which rows carry a + // reason, and this checks the object agrees. + const prose: { description: string; reason?: string } = + SETTING_PROSE[key as keyof typeof SETTINGS]; + expect(prose.description.trim(), key).not.toBe(""); + if ("card" in row) { + expect(prose.reason, key).toBeUndefined(); + } else { + expect(prose.reason?.trim(), key).toBeTruthy(); + } + } + expect(Object.keys(SETTING_PROSE).toSorted()).toStrictEqual( + Object.keys(SETTINGS).toSorted() + ); + }); + + it("gives a `routes` row the planes as its default, the floor its reader adds to", () => { + // The reader of a `routes` row builds on `PLANE_ROUTES` (D19), not on the + // row's default, so the schema's `.default()` and the resolved set agree + // only while the two lists do. + const routes = rows.flatMap(([key, row]) => + row.kind === "routes" ? [[key, row] as const] : [] + ); + // Known answer: the one routes row is read. + expect(routes.map(([key]) => key)).toStrictEqual(["providers"]); + for (const [key, row] of routes) { + expect([...row.default].toSorted(), key).toStrictEqual( + [...PLANE_ROUTES].toSorted() + ); + expect(Reflect.get(resolveConfig({}), key), key).toStrictEqual( + new Set(row.default) + ); + } + }); + + it("keeps a card control only on a boolean or a choice", () => { + const cardKinds = new Set( + rows.flatMap(([, row]) => ("card" in row ? [row.kind] : [])) + ); + expect([...cardKinds].toSorted()).toStrictEqual(["boolean", "choice"]); + }); +}); diff --git a/test/support/src.ts b/test/support/src.ts index b0e383f..44d3a79 100644 --- a/test/support/src.ts +++ b/test/support/src.ts @@ -66,6 +66,7 @@ export type { KeySourcePolicy } from "../../src/config-values.ts"; export { Config, CONFIG_DEFAULTS, + CONFIG_ONLY_FIELDS, DEFAULT_FREE_MODEL_MARKER, DEFAULT_ORIGIN_CLIENT, DEFAULT_USAGE_BASE_URL, @@ -319,11 +320,7 @@ export { SettingsFieldShell } from "../../src/settings-field-shell.tsx"; export type { FieldShellProps } from "../../src/settings-field-shell.tsx"; // settings-fields.ts -export { - CARD_FIELDS, - CONFIG_ONLY_FIELDS, - SPECS, -} from "../../src/settings-fields.ts"; +export { CARD_FIELDS, SPECS } from "../../src/settings-fields.ts"; // settings-page.tsx export { @@ -355,6 +352,9 @@ export { export { inspectStore } from "../../src/settings-store.ts"; export type { StoreInspectOutcome } from "../../src/settings-store.ts"; +// settings-table.ts +export { SETTING_PROSE, SETTINGS } from "../../src/settings-table.ts"; + // settings-usage.tsx export { readGoUsage, diff --git a/test/usage-pill.test.tsx b/test/usage-pill.test.tsx index fb9c20f..0db31ee 100644 --- a/test/usage-pill.test.tsx +++ b/test/usage-pill.test.tsx @@ -432,7 +432,7 @@ describe("usage-pill: UsagePill component gating", () => { expect(element.type).toBeDefined(); }); - it("replaces the default gate when custom markers exclude the stock route", () => { + it("replaces the default gate when the configured routes exclude the stock route", () => { const store = createStore({ current: { model: "deepseek-v4.1-flash", @@ -442,7 +442,6 @@ describe("usage-pill: UsagePill component gating", () => { const element = UsagePill({ directory: store, - modelMarkers: ["only-this-model"], meterProviders: ["only-this-route"], readUsage: async () => createMockUsage(), t: (k: string) => k, @@ -451,7 +450,7 @@ describe("usage-pill: UsagePill component gating", () => { expect(element).toBeNull(); }); - it("falls back to the default markers when the configured lists are empty", () => { + it("falls back to the default routes when the configured list is empty", () => { const store = createStore({ current: { model: "some-model", @@ -461,7 +460,6 @@ describe("usage-pill: UsagePill component gating", () => { const element = UsagePill({ directory: store, - modelMarkers: [], meterProviders: [], readUsage: async () => createMockUsage(), t: (k: string) => k, diff --git a/vite.config.ts b/vite.config.ts index 4a57c89..d4d6dd6 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -342,6 +342,13 @@ export default defineConfig({ functions: 100, lines: 100, }, + // The one settings table (P8): data and four one-line key helpers. + "src/settings-table.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, // The plane routes' host half, measured rather than aspirational: what // is left uncovered are guards for host shapes no composition offers. "src/host/route-claim.ts": {