Commit Graph
7089 Commits
Author SHA1 Message Date
yetone b641868eb3 gateway: TestHeldClock passes each zone in instead of writing time.Local (#2949)
CI run 39242954115 (b749cffbb, ubuntu Race) went red on a data race:
TestHeldClock assigned time.Local per zone while a goroutine left by an
earlier gateway test (restAfterMarked -> narrowWhenRead) called time.Now,
which reads time.Local. heldClock now delegates to heldClockIn(t, now,
loc), and the test calls heldClockIn with the zone, so nothing writes
time.Local. Callers are unchanged.

Run: go test -race -run 'TestHeldClock|TestZhipu' -count=3
./internal/gateway/ ok; GOOS=linux go vet -tags nogui and GOOS=windows
go vet of internal/gateway ok; gofmt -l clean. The race itself was not
reproduced locally (it needs the stray goroutine's timing); the test no
longer writes the global the race trace names.
2026-10-19 19:55:11 +08:00
yetone b749cffbb1 gateway: a reply asked past what the window leaves is asked again for what it leaves, not failed as too long (molvqingtai, da34, Jeremy.Zhou on Discord)
DeepSeek counts the reply asked for (max_tokens) in its 1M window with
the prompt: "maximum context length is 1000000 tokens. However, you
requested N tokens (P in the messages, C in the completion)". Since
62020b9c2 (#2355) a client's max_completion_tokens reaches DeepSeek as
max_tokens, so a turn asking the model's whole 384K on a ~620K+
conversation was refused there and read as "too long for its model"
(molvqingtai: auto-deepseek-v4.1-flash, round robin, the official
member failing where WorkBuddy and OpenCode Go answered). Codex turns
are asked the model's own 393216 on Anthropic's API (#1792), and since
1a3b92688 (v0.1.1290) Claude Code beside a [1m] DeepSeek is told 1M
and compacts only near it, so both met the same refusal before they
compacted (da34: Codex "ran out of room"; Jeremy.Zhou: Claude Code).

replyLeft (maxoutput.go) reads the window and the prompt from that
refusal, in DeepSeek's/vLLM's words or Anthropic's ("input length and
`max_tokens` exceed context limit: P + C > W"), and the same account and
model are asked once more for W-P (withReplyCap: the request's own field
lowered, or max_tokens / max_output_tokens set where it named none).
Room under 8192 is left alone: the agent is told it overflowed, to
compact. The try is "room" in the Routing page ("reply asked past the
window left", zh/zh-TW/ja/de). DeepSeek's documented window stays 1M
(api-docs pricing: deepseek-flash 1M, max output 384K), as models.dev
and the catalog say, so no number changes.

Run:
- TestDeepSeekReplyFitsTheWindowLeft: deepseek preset on a fake chat
  API that refuses in DeepSeek's words when prompt+max_tokens > 1M;
  max_completion_tokens 393216, max_tokens 393216 and a Responses
  client each arrive as 393216 then 293216 and answer 200; 32000 is
  asked once; room under 8192 reaches the agent as the 400, asked once.
- TestAnthropicReplyFitsTheWindowLeft: Anthropic's wording; Claude
  Code's max_tokens 64000 -> 30000, Codex naming none -> 393216 -> 30000.
- TestReplyLeft: both wordings, vLLM's newer one, and errors with no
  room or no parts give 0.
- Broken by hand: the retry's condition off -> both tests FAIL with the
  vendor's 400; the cap not applied on the retry -> FAIL the same.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... clean.
- go test -timeout 45m ./... at 33dbdcc52 + this change: 64 packages ok,
  0 FAIL (load average 130-160). An earlier run before the Anthropic
  wording was added timed out in internal/agent (TestPortMovesEveryAgent
  at the 45m mark, load ~110), which this change doesn't touch; the
  second run passed it.
- GUI: i18n-keys, routing-*, panel-routing* in both engines and every
  language. Red here and on origin/main ab7ec8c65 alike: routing-bodies
  (#2559), routing-model-rest (#2115), routing-request-metrics WebKit
  (#2571), routing-keys-fold WebKit ja/de once (#2658).
- Not tried against the real DeepSeek API: the refusal's wording is
  DeepSeek's documented OpenAI-compatible one, not captured from the
  reporters.
2026-10-19 19:05:30 +08:00
yetone c3b2e6109b provider: signing in to a plugin again takes the lapsed mark off when the providers' list is empty too (#2748)
clearPluginLapse cleared an account's "sign in again" mark only through
plugin.Cached(): it looked for the plugin's provider in the list and
cleared nothing when it wasn't there. The list is empty while
checkList reads another magpie's change to plugins.json again
(provCache = nil, before the providers file is written), so a sign-in
finished then left the account lapsed until a request or usage read
went through. TestPluginLoginTakesTheLapseOff (internal/cli) went red
that way on ubuntu CI twice (runs 39216129687 and 39234604936: "signed
in again, but still lapsed").

The mark now goes by the account's agent and key alone
(notePluginLapseOf), with the same sign-in count ordering as before;
only the stale usage reading still needs the provider, and is still
dropped when it is listed.

TestPluginSignInClearsLapseWithoutTheList saves two lapsed plugin
accounts with no plugin listed, signs one in again, and checks its mark
went and the other's stayed. On the old plugin_accounts.go it fails:
  plugin_fetch_lapse_test.go:83: signed in again, but still lapsed:
  "gone@fake's FakeCo sign-in has expired — sign in again"
and passes with the change.

Whether CI's two reds were this empty list and not another path is
inferred from the code, not captured; #2748 stays open until CI has
gone a while without it.

Run on origin/main 9fd80b212 + this change, macOS, load ~170-230:
- gofmt -l internal/provider: clean; go vet ./internal/provider/;
  GOOS=linux and GOOS=windows go vet -tags nogui on internal/provider and
  internal/cli: ok
- go test -timeout 45m -count=1 ./internal/provider/ ./internal/cli/:
  ok provider 552.7s, ok cli 324.7s
- -run 'TestPluginLogin|TestPluginSignIn|Lapse' on both packages, 5
  times: ok every time
- not the full ./... suite: the change is internal/provider's lapse
  clearing, and the two packages that sign plugins in were run whole.
2026-10-19 18:58:42 +08:00
yetone 5b267fbd8e provider: moved Command Code accounts take plugin 0.1.14, which can ask for Zero Data Retention (plugins #246)
Raises the commandcode-plan mover's min from 0.1.13 to 0.1.14 so
keepMovedCurrent updates every moved user. 0.1.14 (plugins 5f101a5)
adds a "Zero Data Retention" switch (auth.options), off by default, and
honours CMD_ZDR=1. While it is on, the Provider API and Go's
/alpha/generate requests carry x-cmd-zdr: 1, as the CLI sends it. A
model with no ZDR upstream reaches the agent as Command Code refused it:
a 422 cmd_zdr_no_providers on the Provider API, a 400 typed
cmd_zdr_no_providers on /alpha/generate.

0.1.14 is on npm: npm view --prefer-online
@magpie-community/opencode-commandcode-auth version says 0.1.14. The
publish run 39237235562 published it. That run is red only for
middleware-think-tags's trusted publisher (plugins #180).

Run: gofmt -l internal/provider (clean); go vet ./internal/provider/ on
darwin, GOOS=linux and GOOS=windows (ok); go test -timeout 45m
./internal/provider/ (ok, 431s). The full suite was not run: only the
mover's min string changed. Not tried: the switch in a running magpie's
editor.
2026-10-19 18:39:35 +08:00
yetone 9fd80b2128 library: skills install from any git repository, GitLab and a company's own among them (sunset on Discord)
ProbeSkills took only a GitHub source or a folder. It now also takes any
git repository's address: https/http on gitlab.com or a self-hosted
server (any depth of groups), a GitLab or Gitea page of a folder
(/-/tree/<ref>/<path>, /-/blob/..., /src/branch/...), ssh://,
git@host:group/repo.git, a bare host.name/group/repo, and file://.
Such a source is kind "git" (gitSource, skillgit.go).

It is fetched with the user's own git (proc.FindTool), so their
credential helpers and SSH keys reach an intranet host: git init, then
fetch --depth 1 --no-tags -- <url> <ref|HEAD>, checkout FETCH_HEAD into
a magpie-skill-* folder, .git removed; the same keepProbe/maxFetch path
GitHub's tarball takes.

What the user typed is data: an address starting with - and any
transport:: address (ext::, fd::, file::) are refused before git runs;
the address follows --; git runs with protocol.ext.allow=never and
core.symlinks=false, no shell, GIT_TERMINAL_PROMPT=0, and ssh -o
BatchMode=yes unless the user set their own SSH command (GIT_SSH,
GIT_SSH_COMMAND, core.sshCommand), so a sign-in it can't make fails
instead of waiting. An address with a password or token in it is
refused: library.json is shown and backed up. Git missing, a sign-in
refused, an unknown host key, a missing branch and an unreachable host
each say so plainly (gitError).

Updates: Commit keeps the repository head the skill was fetched at. A
check runs git ls-remote; another head is fetched (once per repository
and ref) and the skill's folder hashed, so a commit elsewhere in the
repository leaves it current and moves Commit on. UpdateSkill and the
edited-skill refusal work as for GitHub; EditedError and the page's
Changed here / Update / replace question name the repository instead of
GitHub. findNew, Group again, icons and the market stay GitHub's only
(documented).

Page, TUI and docs: the add box's placeholder in en/zh/zh-TW/ja/de
(zh: owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹),
a git skill's source shown as a link (https) or text (SSH), its own
Update and Check for updates; the TUI's prompt; library.md's Skills and
Skill updates rows. GIT_SSH/GIT_SSH_COMMAND are listed in agentenv's
notAnAgent (TestFolderVarsAreListed).

Tests (fail on the old code: gitSource/gitPath don't exist there, and
skill-git-source.test.cjs fails on the old assets' placeholder, checked
by stashing client.js/i18n.js): TestGitSourceReads,
TestInstallFromGitRepo (a local bare repo over file://: probe, install,
check finds an update, update, a commit elsewhere stays current, an
edit here is refused naming the repo), TestGitTreeURLInstallsFolder,
TestGitMissingSaysSo, TestGitSignInRefusedSaysSo (a local httptest 401,
GIT_CONFIG_NOSYSTEM so no Keychain), TestGitRefusesOptionsAndTransports,
TestGitErrorsSaid. No test reaches the network.

Run (worktree at origin/main 224ea7d5b, machine load average ~120-145
from other sessions):
- gofmt -l: clean. go vet darwin, GOOS=linux -tags nogui, GOOS=windows:
  clean.
- set -o pipefail; go test -timeout 45m ./...: 63 packages ok; one red,
  internal/agent TestFolderVarsAreListed (GIT_SSH vars), fixed above
  and rerun alone: ok.
- After later edits, rerun ./internal/library ./internal/cli
  ./internal/tui ok; internal/gui TestMainWindowCorners red once at
  load 144 (76.5s, AppKit window test this change doesn't touch),
  passed alone (28.6s); internal/agent timed out at 45m in that
  combined rerun at load ~140 (it ran 962s in the full run) and passed
  alone (1808s, load ~100).
- GUI: the 88 test files that load the library page, chromium and
  webkit: 1420/1420 pass; skill-git-source + skill-update-edited rerun
  after the last client.js edit: 20/20.
- Real use in a sandbox HOME (GIT_CONFIG_NOSYSTEM=1): a local bare repo
  over file:// probed, installed, checked current, a new commit found as
  update, updated to v2; ext:: and --upload-pack refused with nothing
  run; https://gitlab.com/gitlab-org/ai/skills probed (52 skills), its
  /-/tree/main/skills/glab installed and checked current; a private
  gitlab.com address said "git couldn't sign in to gitlab.com ...".
- Not tried: a real self-hosted GitLab with credentials, ssh:// against
  a real host, Windows.
2026-10-19 18:16:57 +08:00
yetone eb3f174289 agent: Claude Code's auto mode classifier model is set on its Agents row (Linka on Discord)
Claude Code 2.1.302 reads CLAUDE_CODE_AUTO_MODE_MODEL for the model its
client-side auto mode classifier checks each action with. It doesn't
change server-side auto mode, and a classifier model Anthropic sets for
the account comes first. The installed 2.1.303 binary has the variable:
unset, Claude Code picks the sonnet tier's model, else Sonnet. It refuses
claude-sonnet-5-5, claude-opus-5-5 and claude-opus-5 with a warning and
uses its own pick instead.

- Claude Code gets an "auto mode" field (key auto_mode, Quiet, follows
  nothing). It can be set only while Claude Code is routed through
  magpie, only to one of magpie's models, and is written dashed like the
  other model keys. Its options leave out the three models Claude Code
  refuses, and Set refuses them too.
- A value the user had before magpie routed Claude Code is stashed with
  their tiers (claudeOwnEnv). It is taken out while wired in and comes
  back on Disconnect or Claude Code's own model, unless they have set one
  again since. The restore loop now skips any claudeOwnEnv key the user
  wrote again.
- magpie's own value goes when magpie steps out. A value the user sets
  while wired in is never touched.
- GUI: an "Auto mode" line in the opened row's Tiers, after Subagents,
  using the app's model picker. Default is noted as Claude Code's own
  pick. Strings are translated for zh, zh-TW, ja and de.
- Docs: agent-wiring.md and reference.md.

Run, in a worktree at origin/main 33dbdcc52, sandbox HOME, load ~110-135:
- gofmt -l: clean.
- go vet ./... (darwin), GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- set -o pipefail; go test -timeout 45m ./...: every package ok.
- Breaking by hand turned the new tests red: dropping the stash-time
  removal, the "set again since" check, the no-classifier refusal and the
  removal on step-out made TestClaudeAutoModeModel, TestClaudeAutoModeUserValue
  and TestClaudeDisconnect fail.
- GUI, playwright 1.62.0, Chromium and WebKit: 84 files the change reaches
  (agent*, claude*, tier/subagent effort, codex subagent/memories,
  gui-de, gui-ja, gui-zh-tw, i18n-keys, header-relang, and every file
  with a Claude row or the model picker), concurrency 4: 1305 of 1306
  pass.
  - The one red is agent-expand-steady "webkit 980px ... slides" ("slid
    open: 208"). Its fixture has no auto mode field. Alone it passed 3
    of 3. Filed as #2935.
- claude-auto-mode.test.cjs (new; en and zh, 1100px and 560px, both
  engines): 8 of 8 pass, and 4 of 4 fail in Chromium on the old app.js.
- Not tried against a real Claude Code session.
- After rebasing on origin/main ab7ec8c65 (three commits, none touching
  these files):
  - go vet ./internal/agent and TestClaudeAutoMode*/TestClaudeDisconnect:
    ok.
  - claude-auto-mode, tier-effort, i18n-keys and agent-layout, both
    engines: 23 of 23 pass serially, and 19 of 19 in parallel.
  - A first parallel try at load ~127 had 16 reds in claude-auto-mode
    and tier-effort, and its output wasn't kept. It didn't come back in
    the next three runs.
2026-10-19 18:12:45 +08:00
yetone 9b72add51d provider: Codex's zstd encoder keeps two coders, not one per core, and holds ~9 MB instead of ~80
A live gateway (v0.1.1290, 48 minutes up, ~50 Claude Code and Codex
sessions on a 14-core Mac) had a 288 MB heap, and 74 MB of it was the
shared zstd encoder that compresses ChatGPT turns: klauspost's EncodeAll
keeps a coder per GOMAXPROCS, and each keeps its 4 MiB history (2 MiB
window) and tables for the life of the process (pprof inuse_space:
fastBase.ensureHist 56 MB, encoderOptions.encoder 17.8 MB).

The encoder now keeps two coders (WithEncoderConcurrency(2)) in
low-memory mode (WithLowerEncoderMem). A 1 MiB turn encodes in about
half a millisecond, so two keep up. Neither option changes the frame:
measured on 28 concurrent 1 MiB turns on this Mac:

  default         retained 84.1 MB  13.2ms  28054 bytes  round-trips
  conc2+lowmem    retained  8.9 MB  13.8ms  28054 bytes  round-trips

TestCodexZstdHoldsLittle sets GOMAXPROCS 16, encodes 28 turns at once
and fails above 24 MB. With the two options removed by hand it fails
("the encoder holds 88 MB after 28 turns at once"); with them it passes
(-count=5).

Run on 129d8b08a + this change, macOS, load ~100-115:
- go test -run 'TestCodexZstd|TestCodexCompressed|TestCodexWarmGoesZstd'
  -count=3 ./internal/provider/: ok
- go vet ./internal/provider/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet -tags nogui on the package: ok; gofmt -l: clean
- go test -timeout 45m ./...: every package ok except internal/agent,
  which ran out at 2709.7s (#2544, the same timeout at load). That package
  alone on the same tree: ok in 1363.1s. TestOwnProviderNamedAsMagpies,
  at the deadline, passes alone in 17.9s.

The frames are byte for byte the old ones: the default and the new
encoder compressed 303 bodies from this Mac's own ~/.codex/sessions
rollouts (whole, cut at 1 MiB and at 3 MiB, read locally, sent nowhere)
to identical bytes. So what reaches the backend is unchanged; a live
Codex turn through the new build was not run.
2026-10-19 18:02:56 +08:00
yetone ab7ec8c657 gui: Manage agents' names sit beside their icons, not at the row's far end
The owner's screenshot (zh, a wide window): each row's name was pushed
to the right edge, next to 未隐藏, far from its icon. A row is a <label>,
so .editor label, a form field's label rule (text-align: right, 12px,
padding-top 5px), reached it and outranked .ag-manage-row; under 560px
another rule set labels left, which is why the narrow tests never saw it.
The row's rule is now .modal .editor label.ag-manage-row, left-aligned,
13px in the text colour, with its own padding back.

Run:
- agent-bulk-visibility.test.cjs, which now measures each name's text
  against its icon at 1240 and 560 wide in every language: 10/10
  (Chromium, WebKit; en, zh, zh-TW, ja, de). With the old app.css
  0/10, "name beside its icon at 1240: 424,410,435,427". zh screenshots
  at both widths looked at.
- agent-visibility-saving 12/12, panel-fold 6/6 (the other files that
  open this sheet). The selector matches only .ag-manage-row, which
  app.js makes only in this sheet, so no other page can reach it.
Not tried: the real app window.
2026-10-19 16:45:35 +08:00
yetone 65f5f0153d gui: a sign-in's field and its button are one height, 8px apart
The key field in a sign-in (a plugin's key, Copilot GHE's address, a
pasted callback, the proxy ask) was 30px tall with its button at the
button's own ~24px and 4px beside it: a short button jammed against a tall
field (the owner, on OpenCode 2 Free's key). The field is now 28px with no
vertical padding, its button 28px with the same 7px corners, 8px apart.

Measured (plugin key form, Chromium and WebKit): zh 1100 and en 900: field
28, button 28, gap 8, one row, button's right edge at the form's; de 420:
both 44 (the narrow-width touch height), gap 8.

Run:
- Full GUI suite (2156 tests at ~load 100): red only in
  codex-predictions (10, the same 10 on origin/main 224ea7d5b, #2624) and
  agent-expand-steady webkit 560px (1, passes alone on 224ea7d5b and
  here; under-load flake, #1583).
- plugin-signin-scrolls, signin-*.test.cjs within the full run: green.
CSS only.
2026-10-19 16:43:21 +08:00
yetone 129d8b08a5 gateway: a schema a tool's $ref reaches goes to Kimi with a type
chaosy on Discord: Codex on Kimi Code k3 failed every request, 400 "not
a valid moonshot flavored json schema … $defs.__schema20 … must be
defined". Moonshot's validator expands each $ref and refuses a target
with no type ("At path 'properties.b': detected infinite recursion
without termination condition"), though the same schema written inline
passes. Codex sends its MCP and Codex App tools as zod's $defs and types
a def with properties or an enum, but leaves a oneOf or allOf def as it
was, so the whole request fails.

kimiToolRefTypes, scoped by isKimi and run in forwardOnce after
kimiToolEnumTypes (chat, Anthropic and Codex's Responses routes all pass
there), writes a type after the brace of each untyped $ref target: the
one its keywords or branches say, a type array when they differ, every
type when nothing does. {} targets, anyOf targets (Kimi refuses a type
beside an anyOf) and pure $ref chains are left alone. kimiToolEnumTypes
now also types an enum of one type plus null as [T,"null"], the one type
array Kimi takes beside an enum. Kimi doesn't count as a moved
subscription, so no plugin path reaches it.

Measured against the real Kimi Code chat endpoint
(api.kimi.com/coding/v1/chat/completions, a key without a plan, so a
schema that passes validation gets 403 access_terminated_error and a
refused one gets 400 first):
- Codex 0.162.1's processed shapes: 400 at properties.b before, 403
  after.
- Raw shapes (properties-only, minLength-only, const, [1,null] enum,
  description-only and oneOf-of-refs defs): 400 before, 403 after.
- The zod-built Codex App automation_update forms: 403 before and after.
- [T,"null"] plus enum, a type array beside oneOf, and every type beside
  a description: 403.
The Anthropic endpoint answers 403 before it validates, so it couldn't
be probed; the same rewrite reaches it.

Tests: TestKimiToolRefTypes posts on /v1/chat/completions, /v1/messages
and /v1/responses to Kimi and to another provider, which gets the tools
unchanged. With the forwardOnce line removed it fails on all three
Kimi routes. TestKimiToolEnumTypes now expects [T,"null"] for
["a",null], and fails with that branch removed.

Run at this head: gofmt -l (clean); go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... (clean);
set -o pipefail; HOME=<sandbox> go test -timeout 45m ./... at
33dbdcc52 plus this change: exit 0, all 64 packages ok (internal/gateway
1203.9s).
2026-10-19 16:38:24 +08:00
yetone 33dbdcc529 plugins: Sign in on Installed takes the reader down to the plugin's sign-in
Sign in on Plugins › Installed (or a plugin card) opens the Providers add
sheet with the plugin's sign-in drawn at the sheet's foot, under every
tile. With many plugins the sheet is taller than the window and the reader
was left at its top, the sign-in out of sight: the click seemed to do
nothing (the owner, on magpie-intelligence-check).

The click now passes its event, so pluginSignIn scrolls the sign-in into
the middle of the view on purpose. In WebKit that alone didn't hold: the
list show() loads redraws the sheet after the scroll, WebKit pulls the view
to 0 while it is drawn, and inside the purpose window that 0 was taken as
the reader's, then backToReader returned there. arrived(v) ends the
purpose window once the scroll is done and keeps where it left the view as
where the reader is, so the redraw is put back to the sign-in.

Run:
- plugin-signin-scrolls.test.cjs (new; 24 signed-in plugins and one
  signed out, 900x560, Chromium and WebKit, en and zh): 6/6 pass. On
  origin/main 0/6 ("the page went down to the sign-in"); with the scroll
  but without arrived(), Chromium passes and WebKit fails 2/2.
- GUI: plugin*, *scroll*, *signin*, builtins: 1033 pass, 0 fail.
- go test -tags nogui ./internal/gui: ok (script budget, guard tests).
No Go changes.
2026-10-19 16:05:09 +08:00
yetone 224ea7d5be catalog: a reset drops what a request built of the old catalog
5351343e7 keeps what a request built of the catalog for the next
request within heldFor, dropped by every write magpie makes. A reset
of models.dev's catalog (catalog.Reset) wasn't one of them: Sync tells
Touched after it, but a Reset alone left the providers' entries with
the old windows and output limits for up to a second, and Pi's and
Crush's model lists written in that second carried them
(TestPiModelsCarryMaxTokens, TestCrushModelsCarryMaxTokens red in the
full run: "unknown output sent: ...maxTokens:131072"). Reset now tells
Forget (provider.Changed) after it lets go of its lock.

Test: TestHoldKeptUntilAWrite gains "the catalog reset". Broken by
hand (Reset not telling Forget): red, "the catalog reset: built 0
times, want 1", and both agent tests red again; fixed, the agent tests
pass 3 of 3.

Run: go test ./internal/catalog -count 1: ok (3.4s); go test
./internal/provider -run TestHoldKeptUntilAWrite: ok; go test
./internal/agent -run 'TestPiModelsCarryMaxTokens|TestCrushModelsCarryMaxTokens'
-count 3: ok; go vet ./internal/catalog ./internal/provider.
2026-10-19 15:19:31 +08:00
yetone 627e8e7d95 provider: a request's groups are built once under its Hold, not again by each look-up
groupsIn read providers.json's groups, matched each pattern against
every model and found the automatic groups over the whole catalog, and
every caller did it again: a request to a group asks FindGroup for its
route, members and window, and the group list, several times each.
Under a Hold the built groups are now kept (heldFrom, keyed on the
catalog's entries, dropped by a write as the other held values are),
and each caller gets a deep copy (cloneGroups) so a change of its own,
such as the TUI's edit before a failed save, never reaches the next.

Tests:
- TestGroupsBuiltOnceWhileHeld: 40 look-ups under one Hold build the
  groups 0 more times; a change to a returned group's members isn't
  the next caller's; a SaveGroup under the Hold is seen. Broken by
  hand (groupsIn built every time): red, "the groups were built 40
  times more in 40 looks under one Hold, want 0". Without the copy:
  red, "a change to a held group's members reached the next caller"
  (and TestHeldGroupsAreTheCallers red too).
- TestCloneGroupsSharesNothing fills every field of a Group and its
  Rules by reflection and fails on any slice, map or pointer the copy
  shares, so a field added later is caught. Broken by hand (Weights
  not cloned): red, "Group.Weights is shared with the held group".

BenchmarkGroupLooksHeld (30 providers x 60 models, 4 FindGroup and 1
Groups under one Hold; -benchtime 200x, two rounds; load average ~450):
  before  13.8 / 23.9 ms/op  26.2MB/op  41080 allocs/op
  after   0.18 / 0.14 ms/op   310KB/op    413 allocs/op
User+sys CPU of the binary, 300 iterations minus 3: before 4.5/4.2 s
(~15 ms per request's look-ups), after 0.08/0.06 s (~0.2 ms).
BenchmarkGroupOverhead (200KB, not streamed, 30x): allocs of a group
request fell (30x60 g4 72.9K/75.0K -> 60.5K/75.8K, g1 70.9K/73.1K ->
62.4K/68.4K; 12x20 g4 46.1K/45.8K -> 43.7K/44.7K); cpu-ms/op moved
within the noise of a machine at load ~450, where a request's wall
time passes heldFor and the held values are built again.

Run: go vet ./internal/provider; go test ./internal/provider -run
'Group|Hold|Held|Rule|Clone' -count 1: ok (17.0s); go test
./internal/gateway -run Group -count 1: ok (53.1s).
2026-10-19 15:19:31 +08:00
yetone ec6fba4720 gateway: a long body's top level is split at its members once, not by each decode of it
decodeJSON remembered that a body of 32KB or more was valid (validMemo),
but each decode of it still walked every byte of the conversation to
find its members: a request's readers (the model and stream flag, the
metadata, max tokens, the messages, the tools...) decode the same body a
dozen times, each into a few members. Where the top level's members are
is now remembered with the body's validity (longBody), and fillJSON
fills a struct or map at the top from those spans; a member the type
doesn't want is passed over without a walk. A body under 32KB, or one
not an object, is decoded as before.

Test: TestDecodeJSONSplitsALongBodyOnce: 20 decodes of one long body
into five types (a struct, a slice inside one, a pointer, a map of
RawMessage, a nested struct) split it once, and each gets what
encoding/json gives. Broken by hand (members never remembered): red,
"split 21 times over 20 decodes, want 1".

BenchmarkDecodeReaders (one 200KB body decoded into three small
structs, as a request's readers do; -test.cpu 1, user+sys CPU of the
whole binary, 3000 iterations minus a 30-iteration run, two rounds;
load average ~450, so CPU time, not wall ns/op):
  before  1.26 / 1.25 s (0.09-0.11 s at 30)  ~383 us per request's three decodes
  after   0.26 / 0.26 s (0.07-0.11 s at 30)  ~57 us
Allocations are unchanged (25 allocs, ~358B per iteration).
BenchmarkGroupOverhead's 200KB request moved within its noise
(12x20 p0/m1 22.16 -> 19.30/21.45 cpu-ms/op; 30x60 g4 43.22/48.49 ->
43.86/45.24).

Run: go test ./internal/gateway -run 'JSON|Json|Decode|Fill|Memo'
-count 1: ok (23.5s).
2026-10-19 15:19:31 +08:00
yetone 2a27fb8da8 gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself
attempt() asked searchAsked first, on every relayed request, and only
then whether the provider searches by itself. searchAsked looked for
three words with strings.Contains(string(body), …), each conversion a
copy of the whole body (a 211KB body: ~640KB and ms a request), and a
body offering web_search was then parsed whole: Codex offers it on
every turn, so each relayed Codex turn was parsed only to be told
"Codex searches by itself". searchedForIt now asks what is known of the
provider and model first, and searchAsked looks with bytes.Contains.
The same copy in the siblings that look at an error body
(fallback.passing, patience.busy, routing.failure's insufficient_quota)
goes too. lan.go's and the lower-cased look-ups in gateway.go need the
string they make and are left as they are.

Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the
old order put back): red, "a 211KB body with no search in it: 3
allocations, want 0" and "a provider that searches by itself: 29
allocations, the body parsed".

BenchmarkSearchedForIt (211KB Responses body; load average ~450):
  codex-asks   old 2.55-5.02 ms/op  665KB/op  29-30 allocs/op
               new 0.1-1.9 us/op    0B/op     0 allocs/op
  other-plain  old 1.6-4.8 ms/op    663KB/op  3 allocs/op
               new 0.26-1.15 ms/op  0B/op     0 allocs/op

Run: go test ./internal/gateway -run
'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy|
Passing|Failure|Credit|Quota' -count 1: ok (140s).
2026-10-19 15:19:31 +08:00
yetone a1118187b5 gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer
answered() (and unanswered()) called saveSticks on every request
answered: up to 512 conversations sorted, marshalled, written to a temp
file and renamed, one answer after another under sticksSaving. Now the
stick is in memory at once (stickOf reads the map first) and the file
follows within sticksFlushAfter (2s): what is answered meanwhile goes in
one write. The gateway's drain (ListenAndServe) and magpie ending on a
signal (cli/signals.go, beside FlushServed) write what is waiting, so a
restart or the magpie handed over to reads every answer. A crash loses
the last 2s, as served.json does since 4f9e8331a. In a test binary the
wait is 0 and the file is written at once, as it was (no timer outlives
a test; 8215e8275 did the same for served.json). A write waiting for
another HOME's file (a test's) is dropped, not written into this one.

Test: TestSticksWrittenBehind (2s set by the test): 200 answers write
no file, the last is known in memory, flushSticks writes all 200, and a
short wait writes by itself. Broken by hand (noteSticks calling
saveSticks always): red, "affinity.json written on a request answered".

BenchmarkAnswered (512 sticks kept, 200x, 2 runs; load average ~450):
  old (saveSticks inline)  21.3 / 25.0 ms/op  506KB/op  2140 allocs/op
  new                      2.5 / 5.6 us/op    392-434B/op  8 allocs/op

Run: go test ./internal/gateway -run '^TestSticksWrittenBehind$' -count 1:
ok. go test ./internal/gateway -run 'TestSticksWrittenBehind|Affinity|
Sealed|Stick|Strict' -count 1: ok (57.8s).
2026-10-19 15:19:31 +08:00
yetone ed3a46d02b provider: what a request built of the catalog stays for the next request within a second, not built again for each
Hold dropped everything held when the last request let go, so one
request after another built the catalog again from every provider's
files and accounts (All, entries, the groups' entries, the settings):
a fifth to a third of a request's CPU with 30 providers. What is built
now stays until heldFor (1s) is past, as it already did for requests
that overlapped. It is built again at once when anything it was built
from may have moved:
- Changed() and a plugin change (dropHeld), as before;
- a write that only tells filememo (settings.Save, writePrivate, an
  agent's account file): held values carry filememo.Gen(), new here, and
  are dropped when it moved;
- providers.json or settings.json written by another process (the CLI's
  "magpie group add"): the first Hold of a request stats both and drops
  what is held when either changed, so the next request sees it, not a
  second later;
- the groups served or gated (GateGroups, ServeGroups): holdGate drops
  what is held on both changes (TestGroupsOnAndOff was red without it);
- another environment (a test's HOME), by a hash of os.Environ().
Other files another process writes (an agent's own sign-in file) are
seen within heldFor, as filememo already takes a file found unchanged.

Tests:
- TestHoldKeptForTheNextRequest: five requests one after another build
  once. Broken by hand (held.built = nil on the last release put back):
  red, "five requests one after another: built 5 times, want 1".
- TestHoldKeptUntilAWrite: each of filememo.Forget, providers.json and
  settings.json written behind magpie's back, and GateGroups, builds
  again once. Broken by hand, one at a time: the Gen check off, red
  "filememo told: built 0 times, want 1"; the stat off, red
  "providers.json written by another process: built 0 times, want 1";
  holdGate's dropHeld off, red "the groups gated: built 0 times, want 1".
- TestRequestBuildsProvidersOnce now wants 1, 0, then 1 after
  Changed() (a request later than 0.9s after the first may rightly
  build again on a loaded machine; the test allows it).

BenchmarkGroupOverhead (internal/gateway, 200KB Anthropic body,
stream=false, 100x, two rounds alternating; load average ~450, so the
cpu-ms/op it reports is the measure, not wall ns/op). base is 8215e8275:

  12x20 p0/m1  base  25.66 / 24.36 cpu-ms/op  16.8MB  41723-41827 allocs
               this  22.13 / 20.67 cpu-ms/op  13.4MB  33771-33969 allocs
  12x20 g4     base  30.59 / 30.68 cpu-ms/op  22.5MB  53213-53409 allocs
               this  25.91 / 25.60 cpu-ms/op  19.0MB  45213-45613 allocs
  30x60 p0/m1  base  54.95 / 53.26 cpu-ms/op  42.5MB  89466-90023 allocs
               this  30.80 / 29.27 cpu-ms/op  23.0MB  45853-46928 allocs
  30x60 g4     base  66.67 / 73.07 cpu-ms/op  68-70MB  112283-116845 allocs
               this  45.59 / 48.38 cpu-ms/op  49-52MB  68540-74905 allocs

Run: go test ./internal/provider -run 'Hold|Group|Changed|Served'
-count 1: ok (91s). go test ./internal/gateway -run
'^(TestGroupsOnAndOff|TestRequestBuildsProvidersOnce)$' -count 1: ok.
The full suite at the head of this series is in its last commit.
2026-10-19 15:19:31 +08:00
yetone ae019defed provider: in a test binary served.json is written as an answer is noted, so no write outlives its test
4f9e8331a wrote served.json 2s behind the answer. In a test binary that
timer outlived the test that answered, and wrote into its temp HOME as
testing removed it: BenchmarkGroupOverhead's first case failed 1 run in
6 with "TempDir RemoveAll cleanup: unlinkat …: directory not empty", and
TestOTelSessionDedupOnlyUnkeyedLoopback failed the same way in a package
run. servedFlushAfter is now 0 in a test binary (testing.Testing(), as
partners.go already does), and NoteServed writes at once, after it lets
go of servedAt, as it did before 4f9e8331a. TestNoteServedWritesBehind
sets the 2s itself.

Test: TestNoteServedInATestWritesAtOnce. Broken by hand (writeBehind
returning d in a test binary too): red, "not written as the answer was
noted: … served.json: no such file or directory".

Run: go test ./internal/provider -run 'TestNoteServed|LastServed'
-count 1: ok. BenchmarkGroupOverhead's 12x20 p0/m1 case, 6 runs of 100
requests before: 1 failed on the cleanup; see the next commits' records
for the runs after.
2026-10-19 15:19:31 +08:00
yetone 8fd74d15bf provider: retired.json is looked at on disk once a second, not on every request answered
Every answered request asks Unretire (the gateway's servedCandidate), and
each catalog built asks retiredNow; each was an os.Stat of retired.json
under retired's lock. Only retired.go writes the file (writeRetired, for
Retire and Unretire), and it keeps retired.at and the file's time current
itself, so this process's own retirements are told at once. The file is
now looked at again only after retiredLook (1s): another magpie's write
is seen within it. A config path of its own (another HOME) is read at
once, as before.

Numbers (Apple M4 Pro, loaded by other sessions):
  BenchmarkUnretire  before 98.8 us/op  640 B/op  5 allocs/op
                     after  0.46 us/op  320 B/op  3 allocs/op

Test: TestRetiredLooksOnceInAWhile: 200 Unretire+Retired calls look at
the disk at most twice; Retire and Unretire are told at once; a write
another magpie makes is seen once retiredLook passes; a new config path
is read at once. Broken by hand (the throttle disabled): red, "400 looks
at retired.json for 200 requests".

Run: go test ./internal/provider -run TestRetiredLooksOnceInAWhile;
./internal/gateway -run 'Retired|Zen': ok. The full suite run is in the
last commit of this series.
2026-10-19 15:19:31 +08:00
yetone e1ebd173e8 filememo: a file not there is, while a request holds what was read, not looked for again
A provider with no live model list fetched has no live-models file, and
each request asked after it for each of its models (Provider.Exposed ->
ListedAPIs -> catalog.LiveByID -> readLive), each time an os.Stat that
failed: in a CPU profile of a 30-provider, 60-model catalog, os.Stat was
32% of a request, nearly all of it this. A file found unchanged was
already taken as unchanged for heldFor (1s) within a hold; a file found
missing now is too, in the same generation of Forget. Forget (a write
magpie makes), Look(path) (another's write), the hold's end, a second
gone by, or a stat finding the file there drops it. Unheld, every read
still looks.

Numbers, BenchmarkGroupOverhead, 200KB body, stream=false, 100x each,
binaries alternated twice (Apple M4 Pro, loaded by other sessions):
                       before (cpu-ms/op, allocs)  after
  30x60  p0/m1         34.69 / 35.14   95126        32.87 / 31.84  89266
  30x60  group/g4      44.33 / 43.88  115303        40.77 / 40.77 109071
  12x20  p0/m1         15.75 / 16.30   42535        16.22 / 15.09  41645
  12x20  group/g4      18.15 / 18.50   54138        18.16 / 17.76  53118
(about 7-8% of a request's CPU on the larger catalog; within noise on
the small one, which has fewer missing files.)

Test: TestHoldMissing: 100 held reads of a missing file make one stat; a
file written meanwhile isn't seen until Forget, and is seen after Forget,
after Look and after the release; unheld, 3 reads make 3 stats. Broken by
hand (the missing check disabled): red, "100 looks at a file not there,
held".

Run: go test ./internal/filememo ./internal/catalog: ok. The full suite
run is in the last commit of this series.
2026-10-19 15:19:31 +08:00
yetone a20d86900d provider: what answered a request is written to served.json behind it, once in a while, not on every answer
NoteServed ran on every answered request (servedCandidate): it read
served.json, merged, and wrote it through steady.WriteFile (a synced temp
file renamed over it), all under servedAt's lock, so concurrent answers
queued behind each other's fsync.

Now NoteServed only notes in memory and arms one write for
servedFlushAfter (2s) later; everything noted meanwhile goes in that one
write, merged with what the file holds (another gateway's) and pruned past
servedKeep as before. The file's format is unchanged. This process's
LastServed has a note at once (it merges memory over the file, as it
did); the CLI, a process of its own, sees it within 2s. FlushServed writes
what is pending: the gateway calls it as Serve ends, and the CLI's signal
handler before it dies of the signal. A crash loses at most the last 2s
of notes. A note made under one config path (a test's HOME) is never
written into another's: a path change drops the pending write.

Numbers (Apple M4 Pro, machine loaded by other sessions):
  BenchmarkNoteServed  before 5.10-5.33 ms/op  7.8 KB/op  82 allocs/op
                       after  0.64 us/op       352 B/op    5 allocs/op

Test: TestNoteServedWritesBehind notes 200 answers and checks the file is
untouched, LastServed has the latest at once, FlushServed writes it once
(a second flush writes nothing), merged with another gateway's entry, and
that the timer writes it by itself. Broken by hand (origin/main's
served.go with stubs for the new names): red, "written on a request
answered", and the 200 notes took 1.04s.

Run: go test ./internal/provider -run 'TestNoteServedWritesBehind|TestQuotasLastServed|TestCardsLastServed';
./internal/gateway -run TestQuotasLastServedAt; ./internal/cli -run
'TestQuotaJSONLastServedAt|Signal'; ./internal/gui -run
TestServedMovedWakesTheMenuBar: ok. The full suite run is in the last
commit of this series.
2026-10-19 15:19:31 +08:00
yetone 865b618086 gui: a gateway session is listed without its days, which only the stats read (#2776)
gatewayExternal copied every gateway session's days into the
ExternalSession it hands the Sessions list, each agent's manage page
and a session's detail. MergeExternal, which all three go through,
never reads them; only MergeExternalStats does. The Sessions list asks
for every session, so each poll of an open page copied every gateway
session's days. After the Vias fix (the commit before this one), that copy was the
largest allocation an idle open page makes: 5.11 GB of 9.14 GB in 6
minutes on the 720k-call sandbox.

gatewayExternal now leaves the days out, and the stats add them
through gatewayDays. Each model list is made at its size.

TestGatewayListCopiesNoDays lists a session with 365 days: no days in
the listed copy, and gatewayDays has all of them. With the days copy
put back in gatewayExternal by hand: red, "a listed session copied 365
days". TestGatewaySessionHistoryAndCalendar still sees each day's
output in the stats.

720k-call sandbox, idle with an open page's polls every 15 s, this and
the build before it side by side for 10 minutes, load ~190-210, 12
poll rounds each. Allocated from minute 2 to minute 8: gatewayListed
5,440 MB before and 1,000 MB after, the Sessions list handler 5,820 MB
and 2,970 MB, the manage page 2,220 MB and 1,850 MB. The live heap at
the snapshots ran 393-857 MB before and 389-889 MB after, and RSS
406-1176 MB and 357-934 MB, with no trend in either over the 10
minutes.

Run: go test -p 4 -count=1 ./internal/gui/ ./internal/sessions/: ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 2fcd4b33c4 usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.

The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.

TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.

720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.

Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:19 +08:00
yetone 34b1757843 usage: the kept gateway projection's days and models are lists of their own size (#2776)
buildGatewaySessions grew each session's Daily and Models an item at a
time from empty. The projection is kept for as long as the log is
unchanged, and so was the spare room append had left each list (five
days took eight). slices.Clip in gatewayProjection hides that room from
callers but doesn't free it. On the 720k-call sandbox, that append was
the largest single allocation of the build (319 MB of 1.14 GB), and the
lists are most of what the start keeps for the Sessions page.

Each list is now made at the size its map already counts.

TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days
with one to five models each, and measures the heap the projection
keeps. The bound is its days and models x1.3, plus the sessions' list
and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With
the two makes taken out by hand: red, 12,754,488 bytes.

720k-call sandbox, cold start, the four first asks together, the live
heap 20 s after them, back to back: 541 MB before, 479 MB after. The
machine's load was ~250-290 and the answers took ~140 s in both runs,
so their peak RSS (1395 and 1891 MB) measured the load, not this.

Run: go test -p 4 -count=1 ./internal/usage/: ok.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 43bd998b15 usage: GatewaySessions hands out the kept projection's lists instead of cloning every session's days for each ask (#2776)
GatewaySessions cloned every session's Models and Daily for each ask,
from the projection kept for exactly these asks. The start's first
asks (the Sessions list, each agent's manage page, the stats) each
cloned them all. In a heap snapshot at the 720k-call sandbox's peak,
cloneGatewaySession held ~447 MB live of the 1362 MB. Every caller
(gatewayExternal, listedGateway) only reads the lists, and copies them
again into its own ExternalSession anyway.

The lists are now the kept projection's, shared and read only, which
GatewaySessions' doc now says. This changes the old contract that a
caller owned its copy. The kept lists are clipped, so an append by a
caller makes a slice of its own and can't write into another's.
gatewaySessionFrom shares the days in a window the same way.
GatewaySessionByID still hands out a clone.

TestGatewaySessionsHandOutTheKeptProjection writes 2000 sessions x 10
days and asks 10 times: 435,215 bytes an ask, against the 368,000-byte
list itself. With the clone put back by hand: red, 3,669,150 bytes an
ask. TestGatewaySessionsCacheRefreshAndOwnership now checks that two
asks share the days, that two callers' appends don't alias each other
or the kept list, and that the kept data is unchanged after them. With
the clone put back it is red too ("each ask has a copy of the days of
its own").

Run: go test -p 4 -count=1 ./internal/usage/ ./internal/gui/: ok (load
~157).

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 6359b2c27c usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.

Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.

TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone 227b864a45 usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776)
CodexModelEffort built the whole ledger of the period and kept the rows
that carry a Codex thread. Every gateway call became a Record (in
gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and
a priced Row (ledgerMatched), all held at once, though only a gateway
call paired with a Codex session file's call by its response id can
carry a thread. On the 720k-call sandbox this build was 7.6 GB of the
start's 18 GB allocated and most of its peak.

codexEffortRows visits the log once and keeps only the gateway calls
with a response id, request id or session (native, else magpie's) that
one of the session files' calls has, or an agy call when one is agy's.
No other gateway call can change gatewayMatchesDetails' answer: the
request-id match looks up only the locals' ids, the fallback groups are
looked up only by the locals' sessions, and a response id's uniqueness
is counted over every call that has it, all of which are kept. Only the
paired calls are priced into rows, and the rows are the whole ledger's
thread rows in the same order, so the sums (floats included) are the
same.

TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole
ledger's for All, Today and 7d, with Codex's reader and every agent's:
a pair by response id, an ambiguous response id, a session-and-tokens
match, a call two days old, and unrelated calls around them. With the
session test dropped from matchingRecords by hand it is red (all,
every agent: the session-matched call shows as a row of its own).

TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated
gateway calls and allows a visit of the log and a half. With the old
build put back (LedgerOf): red, 18,347,128 bytes against a visit's
1,198,680. With the fix: 1,321,824 against 1,321,744.

720k-call sandbox, cold start, the four first asks together, back to
back (load 48.7 then 14.7, so the times are not comparable; the memory
is what this measures):
  before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB
  after:              peak RSS 2427 MB, heapSys 2413 MB, live 542 MB
  manage?agent=codex answered in 41.5 s before, 23.1 s after.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone baef679f29 sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776)
d7e02ae08 sized scanAt's buffer by the rest of the file. The other line
readers of a session file still took 1 MiB per file read:
- readMiniMaxCalls, readAgyCalls and readWorkBuddyCalls (WorkBuddy and
  CodeBuddy Code), which read a changed file whole;
- scanFrames, dsh's packed (.zstd) sessions, read on from a frame;
- mayHold, a search's first look at each file.
(calls_pi, calls_kimi, calls_dsh and dsh.go no longer hold one since
the incremental readers before a77f6ae16.) Each now takes
scanBuffer(f, off): the rest of a plain file plus one byte, 16 KiB to
1 MiB. ReadBytes and readFrame read a line or frame longer than the
buffer whole, as before; a packed WorkBuddy file (a zstd stream, not
an *os.File) keeps 1 MiB.

TestReadersOfASmallFileTakeASmallBuffer reads a two-line file 50 times
through each of the five and allows 256 KiB per read. With the five
readers put back (the test kept): red in all five, 1,049,161 (minimax),
1,049,271 (agy), 1,049,256 (workbuddy), 1,068,296 (frames) and
1,056,984 (search) bytes per read.

Not measured on the 600k sandbox: it holds no MiniMax, agy, WorkBuddy or
dsh sessions, so the saving there is the test's: ~1 MiB per file each
time one of these is read again.

Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main f76201a84: go test -p 4 ./... -timeout
45m, exit 0, 64 packages ok and none failed (gateway 1783 s, gui 361 s),
41 minutes at load ~190-200. gofmt -l: no files. go vet: darwin, linux
(-tags nogui) and windows exit 0. The GUI suite wasn't run: no file
under internal/gui/assets changed.
2026-10-19 14:34:18 +08:00
yetone c483feadfd usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X)
ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示".

Cause, two parts:
- An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source,
  so KeyBalances skipped it without a word and the Usage page drew no card.
  OpenCode has no balance a key can read. In sst/opencode,
  packages/console/app/src/lib/inference-proxy.ts serves only the model
  routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and
  /zen/v1/billing all 404, and billing.mdx shows the credits only in the
  console (Overview -> Credits, to owners and admins). No endpoint was
  invented.
- planQuotaSourceOf matched only /zen/go. models.dev now gives Go as
  opencode.ai/inference/go/openai/v1, so a Go provider saved there got no
  plan card at all. openCodeGateway() now tells go/zen/other (custom is
  the user's own) for both URL shapes, and Go at either one reads
  https://opencode.ai/zen/go/v1/usage.

What changed:
- A Zen key's card now carries errOpenCodeNoBalance and seeAt
  (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key
  its balance — see Zen's credits in the OpenCode console, Overview →
  Credits", with an "Open the console ↗" button. That is one button with
  the needsAccessKey "Open settings" one (#1821), so the bytes stay small.
- A provider with its own BalanceURL is still asked that URL.
- Strings are in zh, zh-TW, ja and de.
- coreScriptBudget: rebased onto f76201a84, whose 1,469,000 already
  holds the card (~390 bytes; the tray panel draws it too); unchanged.
  TestCoreScriptBudget re-run after the rebase: ok.
- Plugins: there is no OpenCode built-in mover, and this is a
  key provider, so the change is all in magpie.

Run, all on this tree (HEAD 94919109c):
- Old code: TestOpenCodeZenSaysItTellsNoBalance (adapted), TestPlanQuotaSource,
  TestPlanQuotas and opencode-zen-balance.test.cjs all fail on a detached
  HEAD checkout; they pass here.
- Real use, in a sandbox (go build -tags dev, sandbox HOME, ports
  3486/3487, never the live config), with the owner's OpenCode key copied
  read-only:
  - /api/usage/quotas gives the Zen variant the new error and seeAt.
  - Both Go providers (/zen/go and /inference/go) request the usage URL and
    show the vendor's real 401 "This API key has expired". The owner's key
    is expired, so no live Go reading was seen. There's no Zen account with
    credit either, so the console page itself wasn't checked against a
    balance.
  - A Playwright screenshot shows the card. Clicking the button posted
    /api/open with the console URL.
- go test -p 4 ./... -timeout 45m: every package ok except these.
  - internal/agent timed out at 45m under load; alone it is ok in 1184s
    (#2723, #2544).
  - gateway TestClaudeAccountsSpentFallBackToCodex and
    TestMaxRPMWaitsForRoomInTheMinute pass alone -count=3 (#2858/#2859,
    #1791).
  - gui TestCoreScriptBudget was mine; fixed above.
- gofmt -l clean. go vet: darwin all; GOOS=windows provider and gui;
  GOOS=linux provider (gui needs cgo/wails for linux).
- GUI, chromium + webkit, en/zh/zh-TW/ja/de at 900 and 420px, 2 workers.
  The full suite was stopped at ~416 tests (load 160-500). Its reds were
  in agent-*/account-* files, which this doesn't touch (#1544, #1949).
  - The targeted set passed: quota-*, balance-*, key-balance-card,
    opencode-*, usage-access-key-card, gui-de/ja/zh-tw, i18n-keys,
    panel-usage, panel-balance-order, panel-quota-refresh, tray-usages,
    usage-quota-head, glm/plugin-quota-error, gateway-key-quotas,
    usage-remote-cards, usage-card-refresh and deprecated-subscriptions.
  - Exceptions: gateway-key-quotas (ja launch timeout) and panel-usage
    (zh) were red under load and pass alone.
  - quota-name-translated and quota-count-wrap (webkit) are red alone
    here and on origin/main f76201a84, with the same asserts. That is
    #2228, commented.
2026-10-19 13:42:21 +08:00
yetone f76201a84a plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里".
Grok's plugin signs in through `grok login --device-auth`, and Grok Build
(1.0.50, the webbrowser crate) opens the device page itself, through
NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER;
the macOS binary has no "BROWSER" string. magpie then opened the same URL
from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a
browser tab) or `magpie plugin login`. Reproduced in a sandbox
HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not
involved, with and without SSH_CONNECTION. Built-in grok is retired
(2927a161e), so the plugin's path is the only one.

- The plugin's authorize result can say `opened: true` (not OpenCode's).
  host.js passes it on as Authorization.Opened, then SignInState.Opened,
  and the desktop handler, the CLI and app.js (both open points) open
  nothing then; the link is still shown.
- opencode-grok-auth 0.1.17 (magpie-community/plugins 47fbf63, on npm per
  `npm view --prefer-online`) says opened on darwin/win32, and elsewhere
  gives grok BROWSER=true, a no-op, so magpie stays the one opener there.
  The grok mover min is raised to 0.1.17.
- No other plugin's CLI opens a page: devin, cursor, kiro and qoder run
  status/refresh commands only.
- docs/subsystems/provider-plugins.md says so.

Tests:
- TestPluginSignInPageOpensOnce: the fake plugin signs in through
  /api/plugin-signin. "cli-opened" opens 0 pages; otherwise 1. Red with
  the old gui/plugins.go ("opened 1 more times").
- plugin-signin-opened.test.cjs: in a browser tab, right away and after
  an install, 5 languages, Chromium and WebKit. Every "opened" case is
  red on HEAD's app.js (23 fail); 42/42 with the change.

Run at the change (base origin/main 2ceff7370):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean.
- go test -p 4 -count=1 ./... -timeout 45m (load 150-380): every package
  ok except two.
  - gateway: TestVisionWaitIsntTheDescribersTime. It passes alone; filed
    as #2901.
  - gui: TestDockReopenKeepsTheWindowsSpace, TestMainWindowCorners,
    TestMainWindowRightToLeft, TestTrayCellClickReleasedPanel and
    TestCoveredWindowStaysUp, killed at their deadlines. All pass alone
    with TestPluginSignInPageOpensOnce; filed as #2645/#1936.
- GUI, both engines, at most 2 workers: plugin-signin-opened,
  plugin-signin, plugin-signin-no-url, plugin-moved-signin,
  signin-paste-plugin, signin-browser-down, signin-link,
  plugin-password-prompt and plugin-replaced. The run went 126 pass,
  10 fail, all launch or 5s timeouts at load ~380. Alone,
  plugin-signin-opened passes in both engines and password-prompt
  passes. signin-browser-down was red in one case per run, a different
  one each time. plugin-moved-signin (Chromium) is red alone at HEAD's
  app.js too. Both are filed as #2900.
- plugins: bun test packages/grok 49 pass; scripts/check.mjs ok. Its
  publish run is red only for middleware-think-tags's npm trust
  (plugins#180); grok 0.1.17 was published.
2026-10-19 12:42:48 +08:00
yetone e7114d3882 usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
The gateway's sessions were projected and kept once per `since`, up to
four at once (all time, and each Sessions stats range: today, 7, 30
days...). With 600k calls the all-time projection alone is ~160 MB in
use (pprof inuse_space of buildGatewaySessions on the sandbox below),
and #2776 counted 148 MB for its copies.

Now only the all-time projection is kept. A range that starts at a
local midnight (every stats range does: combinedSessionStats parses
st.From in time.Local) is derived from it: each session's days from that
date on, with its tokens, models, cost and start/last summed from those
days. Each kept day now carries the first and last time of its requests
(unexported, two time.Time) so the derived start and last are exact.
Any other start is built from the log and not kept. The cache is keyed
on the zone too, since the days are local dates.

TestGatewayWindowsShareOneProjection: six days of calls over three
sessions, priced and unpriced models; the all-time read and five ranges
(0, 1, 2, 3 and 7 days back) build one projection between them, and each
range equals a direct build from its midnight (sessions, start, last,
tokens, models, cost within 1e-9, unpriced, days). Broken by hand:
- the midnight path turned off (a build per range, as before): red,
  "built 6 projections for one log and 5 ranges, want 1".
- the derived start taken from the whole session: red, codex|even's
  Start 2026-10-15 where the build says 2026-10-19.

Cost: the two times per kept day add ~13 MB to the one projection on the
sandbox below (158 -> 171 MB in use), against a whole second projection
(~160 MB) for each range a page asks for.

Measured: the sandbox runs (see the commits before) ask only the 30-day
range, so their heap shows one kept projection on both sides; the
saving is per extra range asked and is shown by the test's build count,
not by those runs.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +08:00
yetone cfbd321fc4 gui: the start's warm-up reads Codex's per-thread effort when there are Codex sessions (#2776)
The first Sessions page after a start that showed Codex rows read
usage.CodexModelEffort cold, from the whole ledger, while the page
waited. The warm-up now reads it as its last step, after the stats it
already warmed, and only when those stats hold a Codex session; every
later ask is answered from what CodexModelEffort keeps per period.

The steps move into warmSteps() so a test can run them.
TestWarmUpReadsCodexEffort: with Codex keys in the stats the step reads
the effort once, with none it reads nothing. With the step removed: red,
"read 0 times, want 1".

Measured on the same sandbox as the commit before (600k gateway calls,
~4,600 sessions), base 1a3b92688 against this branch, back to back, at a
load average of 350-480 (nine agents running suites):

  manage?agent=codex, asked 3.5s after the routes:
    base 226s / 190s / 232s (cold)   new 247s / 222s / 246s (cold)

It is not faster here: asked at 3.5s, the page arrives before the
warm-up reaches its last step, and both read the ledger at once; the
load makes every one of these numbers mostly CPU wait. The step helps a
first Codex page opened after the warm-up is done, which is the case in
#2776 (a page opened some time after a restart). Not measured at that
point under this load.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:33:00 +08:00
yetone d7e02ae088 sessions: a scan's read buffer is the size of what is left of the file, 1 MiB at most (#2776)
scanAt gave every scan a 1 MiB bufio buffer. A start reads ~4,600
mostly small session files (and reads each again from where it was
left), so those buffers were the largest single allocation of a start:
9.4 GB of the 22.4 GB a warm start allocated on the sandbox below. The
buffer is now the rest of a plain file plus one byte, at least 16 KiB
and at most 1 MiB; a packed (zstd) file keeps 1 MiB. A line longer than
the buffer (a file grown since its size was read) is still read whole
through scanAt's long-line path.

Tests (internal/sessions/scan_buffer_test.go):
- TestScanOfASmallFileTakesASmallBuffer: 200 scans of a two-line file
  allocate under 64 KiB each. With the 1 MiB buffer back: red, "a scan
  of a two-line file allocated 1048871 bytes".
- TestScanReadsALineLongerThanItsBuffer: a line three buffers long, then
  a short one, are both handed over whole.

Measured on a sandbox instance (600k gateway calls, ~4,600 sessions),
base 1a3b92688 against this branch with every #2776 commit, back to back
at a load average of 340-450 (nine agents running suites), heap profile
after the four first API calls and 60s idle:

                       allocated   of it scan buffers   live heap
  warm  base            22.40 GB         9.40 GB          483 MB
  warm  new             15.86 GB         1.98 GB          498 MB
  cold  base            22.48 GB         9.31 GB          450 MB
  cold  new             15.76 GB         1.98 GB          498 MB

What is left in bufio.NewReaderSize is the other call readers' own
1 MiB buffers (calls_pi, calls_kimi, ...). Peak RSS did not drop at this
load (base 4.38/4.41 GB, new 4.59/4.54 GB): the peak comes from the four
first calls each materialising the 600k-call ledger at once
(gatewayRecords appends every Record, 2.56 GB allocated; ledgerOfAt
6.2 GB for CodexModelEffort), which this commit does not change.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
2026-10-19 11:32:59 +08:00
yetone c381e4cd1e sessions: a read is never held by another read's refresh, only by a change to the files (#2776)
A read of the sessions (List, Stats, Manage, the agents' lists, Codex's
threads) took dbReadMu, a plain mutex, for the whole call, parse
included. The start's warm-up reads every session file with a quarter of
the cores, so the first pages and API calls after a start waited for its
whole read before they could even look at the cache.

- dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only
  the changes to the files (Delete, a Codex provider move, a Claude
  project relocation) take it alone.
- A file another refresh is reading now is in `parsing`, with a channel
  closed when its parse is in the cache. A second read serves the parse
  it already has of such a file, and waits only for one it has never
  read; it never reads the same file twice at once.
- Each parse is published as it finishes, not in checkpoint batches, so
  a waiting reader gets it at once.
- The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the
  end of every read; with reads overlapping, one could close a handle
  another still used. They now live as long as their last user
  (useDBs). get() and the titles path closed them without the lock at
  all before.

Tests (internal/sessions/refresh_shared_test.go), each broken by hand:
- TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is
  held; List and Manage answer within 10s from the kept parses, each file
  is parsed once in all, and a later List parses none. With storeMu.Lock
  in List: red, "List waited for another read of the same files to end".
- TestReadWaitsForAFirstReadUnderWay: a file never read is waited for,
  not served empty, and read once. Without the waits: red, "List answered
  without the files being read". Without the skip of a file being read:
  panic, close of nil channel.
- TestStoresLiveAsLongAsTheirLastUser: with the release always closing:
  red, "closed while a read still used it".
All three pass with -race.

Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code
and Codex sessions, 300 grown since the last start; 4 API calls asked
3.5s after the routes, when the warm-up starts), base 1a3b92688 against
this branch, back to back. The machine's load average was 350-480
(nine agents running suites), so these timings are mostly CPU wait and
vary by tens of seconds run to run:

  first answer (stats?days=30)  base 91s / 81s    new 50s / 79s
  manage?agent=claude           base 112s / 95s   new 83s / 96s

The pages no longer queue behind the warm-up's lock, but at this load the
answer is bound by the CPU its own parse gets, so no gain shows above the
noise in the second pair. On an idle machine the held reads are what
#2776 reports; the tests above show they are no longer held.

Run on origin/main 2ceff7370 with all four #2776 commits' changes
(this one and the three beside it), load average 291-568 (nine agents
running suites), macOS:
- go test -p 4 ./... -timeout 45m, 09:35-10:49: 62 packages ok,
  among them agent (2310s), gateway (1707s), provider (764s), usage
  (83s). Red:
  - internal/sessions: TestWSLOmpProfiles, TestWSLStoppedDistroKept,
    TestWSLStoppedSinceNotOpened, TestWSLNoneWithoutHomes, each
    "TempDir: mkdir ...: no space left on device" (the disk filled
    mid-run). After space was freed, ./internal/sessions alone: ok
    (139s).
  - internal/gui: TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt,
    TestPanelJoinsFullScreenSpaces, TestPluginPageLoadsItsFilesInTheWindow,
    TestDockReopenKeepsTheWindowsSpace (each killed at 30s) and
    TestMainWindowCorners (86s): the real-window AppKit tests under
    load, already filed as #2645 and #1936. Rerun alone at load ~335:
    all pass, with TestSetAnswersWhileDevinAndProvidersHang (17s).
- gofmt -l: none. go vet: darwin, GOOS=linux -tags nogui and
  GOOS=windows all exit 0.
- No internal/gui/assets file changed, so the GUI Playwright suite was
  not run.
- At this commit alone (2ceff7370 + this change): ./internal/sessions
  ok (82s), and its three new tests with -race ok.
2026-10-19 11:32:59 +08:00
yetone a77f6ae168 sessions: a WorkBuddy reply whose first line spent nothing is one call
Found in the reader audit, not a speed fix. readWorkBuddyCalls replaced
the call before a line whenever the line's messageId was the one the
line before it carried. A zero-token line makes no call but still set
that id. So a reply opening with a zero line:
  - as a session's first reply, panicked: index out of range [-1] at
    st.Calls[len(st.Calls)-1], which took down the Usage ledger's read;
  - after another reply, overwrote that reply's call. m8 50/5, then m9
    0/0, then m9 300/20 gave one call (m9) where the Sessions summary
    (workbuddyLine: unuse m9's zero, keep m8) counts both.
The call before is replaced now only when it carries the same id.
CodeBuddy and the other WorkBuddy builds read through the same reader.

Test: TestWorkBuddyCallsReplyStartingAtZero writes both cases.
  - On the old code: panic, index out of range [-1].
  - Broken by hand, with only a len(st.Calls) > 0 check: red, "calls
    [m9 300/20], want m8's and m9's".

Run: go test ./internal/sessions -run 'WorkBuddy|CodeBuddy|Buddy'
-count=1 ok. The full-suite record is in the report for this series.
2026-10-19 11:30:48 +08:00
yetone ec396be60c sessions: a dsh session read for calls is read on, not whole
dsh's calls were read by a whole-file reader: each reply appended to a
session made Usage's ledger read the whole file again and, packed,
decompress every frame of it. parseDsh already reads on from the frame
it left off in (frames.go, 827c304d9); the call reader now does too.

readDshCalls is handed what the last read came to and reads on from its
tail (scanFrames for a packed file, scanAt for a plain one), carrying
dsh's header in dshCarry. It says how many of the calls it gives were
kept from before, so only the new ones are appended to the disk shard
(resumeCallReaders in call_cache.go). The carry is kept in the shard's
state as JSON (callDiskState.Dsh), since the in-memory read is let go
after packing. A fork's inherited end-seed met in a later read drops
what was counted before it and rewrites the shard whole, as the whole
read did by cutting at the last one. A file cut short or replaced
(tail.holds) is read whole. One change from before, as for parseDsh: a
last line not ended by a newline waits for it.

Measured (CPU, getrusage; 50 MB of events, ~3600 calls, a reply
appended between reads; packed: frames of 200 lines; the old reader
measured from a worktree at 432a2ba5e with the same harness; machine at
load ~500):
  plain  before: 91-109 ms CPU, 0.5-1.3 s wall per read after an append
  plain  after:  0.6-7.7 ms CPU, 2-129 ms wall
  packed before: 214-230 ms CPU, 3.5-4.8 s wall per read after an append
  packed after:  1.2-1.5 ms CPU, 13-46 ms wall
  first read unchanged (plain ~60-105 ms, packed ~195-215 ms CPU)

Tests: TestDshCallsReadOnlyWhatWasAppended (packed dsh-a) checks where
each read starts (scanHook) and its calls: a frame appended is read
alone; half a frame waits; a frame ending inside a line is read on from
that frame; after resetCalls() the read goes on from the disk shard;
cut short reads from 0. TestDshCallsEndSeedAcrossReads: dsh-c's
end-seed arriving in a later read drops the seeded call, its own is
read on, and the shard holds only that after resetCalls().
Broken by hand: no resume -> both red ("read from 0, want 654"); the
carry not written to the shard -> both red (same); the end-seed not
rewriting the shard -> red ("the fork's own ...: [50 100]").

Run: go test ./internal/sessions -run 'Dsh|Call|Usage|Pi' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
2026-10-19 11:30:48 +08:00
yetone da9fc17eb6 sessions: a Pi or omp session file read for calls is read on, not whole
Pi's and omp's calls (#1951) were read by a whole-file reader: every
time a session file grew by one line, Usage's ledger decoded the whole
file again, its header and every message, and rewrote its disk shard.
Pi and omp only append to a session file, a line an entry, as Kimi
Code's wire file is.

Pi and omp are now line readers (lineCallReaders): a file that only grew
is read on from the last whole line, and only the calls it adds are
appended to the shard. What a later line's call is read with is carried
in piCarry on the callFile: the header's cwd, a fork's start (what came
before it is its parent's), and the provider and model in use for a
compaction's or tool result's usage. That carry is kept in the shard's
state too, flat (callDiskState.Pi*), as the in-memory read is let go
after packing: a carry that lived only in memory made every append read
from 0 again. A shard written before has no carry (piCallsKept false)
and its file is read whole once more. Cut shorter, written over, or
grown at a changed head: read whole again (prepareCalls' head and
prefix hashes, as for Kimi).

Measured (CPU, getrusage; one 50 MB Pi session, ~3500 calls, a call
appended between reads; the old reader measured from a worktree at
432a2ba5e with the same harness; machine at load ~500):
  before: 112-153 ms CPU, 1.0-2.5 s wall per read after an append
  after:  1.1-3.1 ms CPU, 5-57 ms wall per read after an append;
          first read ~95 ms CPU, as before

Test: TestPiCallsReadOnlyWhatWasAppended (a fork, its model set once at
the top, compaction usage) checks where each read starts (scanHook) and
the calls it gives: an append with a half line after reads from the old
end and leaves the half line; finished, it is read; a line older than
the fork's start is left out after a resume as on a whole read; the
model, provider and cwd stay right on calls read on; after resetCalls()
the read resumes from the disk shard; cut shorter and written over read
from 0.
Broken by hand: piCallsKept always false -> red ("read from 0, want
686"); the carry not written to the shard -> red (same); begin run on
every read, the carry lost -> red ("calls [1 2], want [1 2 3]").

Run: go test ./internal/sessions -run 'Pi|Omp|OMP|Call|Usage' -count=1
ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record
is in the last commit of this series.
2026-10-19 11:30:47 +08:00
yetone 1f411802b8 sessions: Droid's and Grok's listings open only the files that changed
Droid's listing opened every transcript to read its first line, for
whether it is a subagent's (callingSessionId), and Grok Build's read and
decoded every session's summary.json for its session_kind and parent.
The listing runs on every 15s poll of Sessions and Usage, so with
thousands of sessions each poll opened thousands of files that had not
changed.

listMemo (listmemo.go) keeps what a listing read from each file by that
file's own size and mtime, not the folded size the listing gives the
session. A listing is a round: a file not seen in it (a session deleted)
is dropped when it ends, so the memo never outgrows the sessions there
are. A read that failed, such as a transcript whose first line is still
being written, is not kept, and the next listing reads it again: a
failed read means unknown, not "nobody's". Reset clears both memos.

Measured (3000 sessions each, one listing after another, CPU by
getrusage, the machine at load ~500):
  Droid before: 1103 ms CPU / 8.3 s wall per listing
  Droid after:  27-47 ms CPU / 0.05-1.0 s wall (first listing 1166 ms)
  Grok before:  649 ms CPU / 4.2 s wall per listing
  Grok after:   252-295 ms CPU / 1.8-2.2 s wall (first listing 707 ms)
What Grok's listing still spends is its globs and two stats a session
(updates.jsonl, summary.json), not reads.

Tests: TestDroidListingReadsOnlyChangedTranscripts counts transcript
opens (scanHook): a second listing opens only the half-written one,
appending reopens only that file, a finished first line is then kept,
and a transcript written over without a caller is its own session.
TestGrokListingReadsOnlyChangedSummaries counts summary reads
(grokSummaryHook): none when nothing changed or only the updates grew,
one when the summary is written over, and the key follows it.
Broken by hand: the memo never hit -> both red ("nothing changed: read
map[...all...]"); failed reads kept -> Droid red ("nothing changed: read
map[], want only the half-written one again").

Run: go test ./internal/sessions -run 'Listing|Droid|Grok' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
2026-10-19 11:30:47 +08:00
yetone 11b42c0e2e sessions: a Kimi Code wire file read for calls is read on, not whole
Kimi Code's calls (#1607) were read by a whole-file reader: every poll of
Usage after a session's wire.jsonl grew decoded the whole file again for
the one or two records added. Kimi only appends to that file, a record a
line, so its calls now go through the line path Claude Code's and Codex's
take: lineCallReaders gives readCalls a begin (the session id) and a line
reader, and prepareCalls reads a grown file on from where the last read
left off, writing only the added calls to the disk shard. A half-written
last line waits for the rest; a file cut shorter, or written over, fails
the head and prefix checks and is read whole again.

That alone did not resume for any main session: Kimi's listing folds
state.json's size into the main wire file's, so the prefix hash, taken
over the listed size, ran past the end of the file and came back empty,
and an empty hash never matches. The hash is now taken over the bytes the
reader consumed (Off) rather than the listed size; for a Claude or Codex
file with no partial tail the two are the same, so their shards keep
their hashes. A title change in state.json still re-lists the file, and
now costs a resume, not a whole read.

TestKimiCodeForkCountsOnce wrote its subagent files without a final
newline, which a line reader keeps as an unfinished line; real wire files
end in one (all nine of the reporter's do), so the fixture now does too.

Measured (CPU, getrusage; one 50 MB wire.jsonl with a state.json beside
it, one record appended between reads, readCalls alone; machine loaded):
  before: 40-90 ms CPU, 240-980 ms wall per read after an append
  after:  0.9-1.1 ms CPU, 10-21 ms wall per read after an append;
          first read ~40-55 ms

Test: TestKimiCodeCallsReadOnlyWhatWasAppended (state.json present)
checks where each scan starts and what calls come back: appended with a
half line after, the half line finished, cut shorter, written over.
Broken by hand: no resume for kimi -> red ("read from 0, want 567");
resume without the size/prefix checks -> red ("cut shorter: read from
945, want 0"); the hash over the listed size again -> red ("read from 0,
want 567").

Run: go test ./internal/sessions -run 'Kimi|Call|Codex|Claude|Long|Grow|
Append|Resume|Prefix|Hash' -count=1 ok (359s); gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
yetone 6d3caf6fa4 sessions: a Cline session whose manifest alone changed is not read again
Cline keeps a session's messages in one JSON document, rewritten whole,
and its title, start and fork in a manifest beside it, whose size and
mtime are folded into the session file's. Cline rewrites that manifest
on its own (a title given, the session's status touched), and every such
rewrite made the Sessions and Usage pages decode the whole messages file
again, though nothing in it had changed.

parseCline now keeps what its messages were counted from: the messages
file's own size and mtime, and the start and fork time the manifest gave
then, with the first prompt that names the session. When the messages
file is as it was and the manifest still gives the same start and fork,
the counts stand and only the manifest is read again for the id, cwd,
name and title. Messages rewritten (any size or mtime change), or a
start or fork that moved, read them whole again as before. A messages
document can't be read on from where it was: it is rewritten, not
appended to.

Measured (CPU, getrusage; 50 MB messages file, the manifest rewritten
between reads; machine loaded):
  before: ~205-290 ms per read after a manifest change
  after:  0.1 ms per read after a manifest change; first read ~290 ms

Test: TestClineReadsMessagesOnlyWhenTheyChange counts reads of the
messages file (clineHook) and checks each read against a whole one: a
manifest touched or titled reads none of it, and the title from the
first prompt stays; a message changed, the same size at a later time, a
fork added and the start moved each read it again.
Broken by hand: no resume -> red ("manifest touched: messages read
again"); the start and fork not compared -> red (read on differs from
whole, after the fork); the carried prompt dropped -> red (read on
differs from whole).

Run: go test ./internal/sessions -run Cline -count=1 ok, and the whole
package green at the previous commit; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
yetone b3642e7277 sessions: a dsh session read before is read on from where it was left, not whole
dsh only appends to a session file, a line at a time or, packed
(.zstd), a frame of lines at a time. Every reply still made the
Sessions and Usage pages read, and for a packed file decompress, the
whole file again: a packed file "can't be read on from the middle of a
frame".

It can be read on from the start of one. frames.go walks a file of zstd
frames without decoding them (RFC 8878: the frame header, then blocks
that each give their length, then the checksum), decodes one frame at a
time, and says where to go on from: the frame the first line not yet
whole starts in, and how far into what it holds. A frame not yet
written whole waits for the next read, and so does a line a frame ends
inside of.

parseDsh keeps a tail (tail.go) and the header it read, and counts each
event as it comes (dshCount) instead of collecting them all first. A
fork's inherited end-seed met in a later read starts the counts over
from the session's start, keeping its title and name, as the whole read
did by cutting at the last one. A file that shrank or was replaced is
read whole again. One change from before: a last line not ended by a
newline now waits for it, like every other appended file's.

Measured (CPU, getrusage; 50 MB of events, a reply appended between
reads; packed: 17 MB of frames; machine loaded):
  plain   before: ~110-120 ms per read after an append
          after:  0.4-2.6 ms per read after an append; first read ~120 ms
  packed  before: ~190-250 ms per read after an append
          after:  0.4-0.5 ms per read after an append; first read ~260 ms

Tests: TestDshReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases.
TestDshPackedReadsOnlyWhatWasAppended appends a frame (read alone), half a frame (waits), a
frame ending inside a line and the frame that ends it (read on from the
first of the two, the line counted once), then cuts the file short and
replaces it with a longer one (read whole). TestDshEndSeedAcrossReads
writes a fork's seeded lines, its end-seed and its own, a read apart
each. Every read on is checked equal to a whole read.
Broken by hand: resume off -> red in both ReadsOnly tests ("after a
line appended to 1308 bytes, read from 0", "after a frame appended to
654 bytes, read from 0"); a line split over two frames resumed at the
second frame -> red (read on differs from whole); the end-seed reset
removed -> red in TestDshEndSeedAcrossReads and TestDsh.

Run: go test ./internal/sessions -count=1 -timeout 45m ok; gofmt -l
and go vet ./internal/sessions clean. The full-suite record is in the
last commit of this series.
2026-10-19 11:30:47 +08:00
yetone e03d495f83 sessions: a Kimi Code session read before is read on from where it was left, not whole
Kimi Code only appends to a session's wire.jsonl, but every message (and
every rewrite of its state.json, whose size and mtime are folded into
the wire's) made the Sessions and Usage pages read the whole wire again,
a fork's twice: once for its last marker, once to count.

parseKimi is now one pass that keeps a tail (tail.go) and what the read
carries on with: the session's start, whether it is a fork, and the
fork's marker time. A forked marker met in a later read starts the
counts over from it, as a whole read does. Title, cwd and name still
come from state.json on every read, so a state.json-only change reads
none of the wire. A forkedFrom set or cleared reads whole again, and so
does a wire that shrank or was replaced; a half line waits.

Measured (CPU, getrusage; 50 MB wire, a message appended between reads;
machine loaded):
  before: ~256-278 ms per read after an append (same as the first read)
  after:  0.3-0.6 ms per read after an append

Tests: TestKimiReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases on a real wire's events,
then a state.json title change (nothing of the wire read) and a
forkedFrom set (read whole). Every read on is checked equal to a whole
read. TestKimiForkMarkerAcrossReads writes a fork's copied lines, then
its marker, then its own usage, a read apart each: only the fork's own
usage counts.
Broken by hand: resume off -> red ("after a line appended to 29089
bytes, read from 0"); the marker's reset removed -> red in
TestKimiForkMarkerAcrossReads and TestKimiCodeSessionFork.

Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
yetone b9b4c21c5b sessions: a Droid transcript read before is read on from where it was left, not whole
Droid only appends to a session's transcript, but every message (and
every rewrite of its settings.json, whose size and mtime are folded into
the transcript's) made the Sessions and Usage pages parse the whole
transcript again.

parseDroid now keeps a tail (tail.go) and what the read carries on with:
whether the session_start line and a fork's copied lines are behind it,
and what the settings' running total was counted as (date, model,
tokens). The next read takes that total back (dropUse, which leaves no
empty model or day behind, so the summary is the one a whole read makes),
reads on from the tail, and counts the total again on the day of the last
message. A transcript that shrank or was replaced is read whole again; a
half line waits for the next read.

Measured (CPU, getrusage; 50 MB transcript, a message appended between
reads; machine loaded):
  before: ~490 ms per read after an append (same as the first read)
  after:  0.2-1.8 ms per read after an append; first read ~470 ms

Tests: TestDroidReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases, then a message a day later
with a grown total (counted once, moved to the new day), then a
settings-only change (nothing of the transcript read). Every read on is
checked equal to a whole read. TestDroidForkAcrossReads appends a fork's
copied lines one read at a time.
Broken by hand: resume off -> red ("after a line appended to 825 bytes,
read from 0"); the old total not taken back -> red (read on differs from
whole).

Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
yetone d9f6b42cbc sessions: a Grok Build session read before is read on from where it was left, not whole
Grok Build only appends to a session's updates.jsonl, but every change
to it (and every rewrite of its summary.json, whose size and mtime are
folded into the file's) made the Sessions and Usage pages parse the
whole file again.

parseGrok now keeps a tail (tail.go) with its summary: the offset after
the last whole line, the file's head and a sampled prefix hash. The next
read goes on from that offset when the file has only grown and the
summary still names the same model, created time and parent; the first
prompt still coming in chunks carries over too. A file that shrank, or
whose head or sampled prefix changed, is read whole again, and a half
line at the end waits for the next read.

Measured (CPU, getrusage; 50 MB updates.jsonl, a turn appended between
reads; the machine was loaded, so CPU time, not wall):
  before: 46 ms per read after an append (same as the first read)
  after:  0.2 ms per read after an append; first read 44 ms

Tests: TestGrokReadsOnlyWhatWasAppended checks where each read starts
(through scanHook) and that every read on from a tail equals a whole
read: a line appended is read alone; half a line waits and is counted
once; the file cut back to its old bytes, or one byte changed in place
in a line it had, is read whole; a summary-only change reads nothing of
the updates; a changed model reads whole. TestGrokPromptAcrossReads
carries a chunked first prompt across reads.
Broken by hand: resume turned off -> red ("after a line appended to
2684 bytes, read from 0"); tail.holds made to trust any grown file ->
red ("rewritten in place, read from 3055").

Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:46 +08:00
yetone 5774c790bd plugin: a reply's chunk frame is read by its fixed shape, not through encoding/json
Each chunk of a plugin's streamed reply (up to 64 KB of base64 a frame)
went through json.Unmarshal into message. encoding/json scanned every
byte twice (validating, then decoding the string) and cost far more than
decoding the base64 itself. chunkFrame reads the one shape host.js's
chunkLine writes, {"id":N,"event":"chunk","data":"..."}. Any other line,
or one whose data holds a quote or a backslash, still goes through
json.Unmarshal. push checks the data is base64 of a frame's size either
way, as before.

Measured (64 KB frame, json vs chunkFrame, each followed by the base64
decode push does; -cpu 1, 6 runs, load average ~480, so absolute times
are inflated):
- json.Unmarshal + DecodeString: 7.3-14.0 ms/op, median ~8.7 ms
- chunkFrame + DecodeString: 0.11-2.3 ms/op, median ~0.33 ms

Test: TestChunkFrameReadsWithoutJSON. Frames json.Marshal'd with a \n,
\r\n or no line end must parse and equal what json.Unmarshal makes. It
also refuses 11 other shapes, among them:
- an escape in the data;
- a negative id, or 1e3;
- extra fields or trailing bytes;
- a 20-digit id;
- reordered keys.
Broken by hand (chunkFrame always false), it went red: "a chunk frame as
host.js writes it ... went through encoding/json".

Run (load ~420): go test ./internal/plugin -count=1 -run on the chunk
frame, host, flow, stream, chunk, credit and fetch tests: ok (54.0 s).
The whole package runs with the final checks.
2026-10-19 09:40:46 +08:00
yetone ef75a9a2b5 plugin: a streamed reply's chunk frame is joined, not stringified, and its bytes viewed, not copied
Every chunk of a plugin's streamed reply went out as
JSON.stringify({id, event: "chunk", data}), and stringify scanned every
byte of the base64 for something to escape. Base64 has nothing JSON
escapes, so chunkLine joins the line from strings instead. The line is
byte-for-byte the one stringify made. A Uint8Array chunk that isn't a
Buffer (what a Response body hands over) was also copied whole by
Buffer.from before it was encoded. It is now viewed: the bytes are
encoded before the next read, so nothing else touches them.

Measured in bun, old and new interleaved in one process, medians (load
average 363-413, so absolute times are inflated). The bench asserts the
lines are equal.
- 2032 B frame: 152.8 us -> 12.8 us (78.9 -> 6.6 ms per MB)
- 16 KB frame: 675.8 us -> 69.4 us (43.3 -> 4.4 ms per MB)
- 64 KB frame (MAX_FRAME): 2135 us -> 292.6 us (34.2 -> 4.7 ms per MB)

Test: TestHostFramesChunksCheaply streams Uint8Array parts (one of 70 KB,
so it splits at MAX_FRAME) through host.js's fetch loop in a vm. It
checks:
- 4 chunk frames;
- the bytes come back equal;
- JSON.stringify never sees a chunk;
- Buffer.from never copies a chunk.
Broken by hand twice, red both times:
- the frame built as an object again: "chunk frames are joined, not
  stringified";
- Buffer.from(chunk) again: "chunks are viewed, not copied".

Run (load ~420): go test ./internal/plugin -count=1 -run on the host,
flow, stream, chunk, credit, fetch and auth tests: ok (51.2 s). The whole package runs with the final checks.
2026-10-19 09:40:45 +08:00
yetone 8f37ed57d2 plugin: plugin-auth.json is parsed once per version of the file, not on every request
Every request read and parsed plugin-auth.json in the host two or three
times: accountKey (when no account is named), fresh (is a renewal due),
and the plugin's getAuth from its loader's fetch. Reading and parsing a
20 KB file (12 sign-ins) cost ~0.65-0.97 ms each on this loaded machine.

readAuth now keeps what it parsed while the file has the same mtime,
size and inode, as Go's filememo does. While the file's time is within
2 s of now it also keeps the bytes and compares them, so two same-size
writes inside one tick of a coarse clock (Linux) still read as two. A
file that doesn't parse is never kept, so the .bak recovery path is
unchanged. changeAuth still reads afresh under the lock. The kept
object is shared, so what a plugin is handed (getAuth for loader, usage
and check-in, the models hook's auth, pi.js's readAuth) is a copy of its
own (authCopy).

Measured (load average 360-460, so absolute times are inflated):
- readAuth on a settled 20 KB file, old and new interleaved in one bun
  process, 6 rounds of 5000: old median 970 us (min 841) and 1 file read
  per call. New median 23 us (min 2.3), a stat, and 0 file reads.
- whole fetch (TestPerfScratch, not committed, {} body, 400 fetches):
  host CPU 750-825 us -> 750-775 us per fetch, inside this load's noise.
  A control run without the big file read 875 us at the same load. Host
  RSS 53 MB -> 42 MB.

Test: TestAuthReadOncePerVersion runs host.js's own auth section in node
with readFileSync counted. It checks:
- 100 reads of a settled file read it once;
- a rewrite is read;
- a same-size rewrite with the same mtime is read;
- authCopy's copies are the caller's own.
Broken by hand twice, red both times:
- readAuth made the old uncached read: "a settled file is read once for
  100 reads, read 100 times".
- bytes of a just-written file not kept: "a same-size rewrite in one
  tick is read".

Run (-p 4, load ~470): go test ./internal/plugin -count=1 ok with
TestGatewayHookMixedPiPackage skipped. That test passed alone at 545.6 s
(pinned pi install under load); in a full package run it hit its 4-minute
start deadline ("starting plugins: context deadline exceeded").
2026-10-19 09:40:45 +08:00
yetone e3c09f4f36 plugin: a request is told the provider info built once per account, not built again per fetch
host.js ran info(provider, key) on every fetch, to hand chat.headers
hooks the provider. Each build rebuilt the model list from models.dev and
config, read and parsed plugin-auth.json twice, JSON-cloned the list and
asked the plugin's provider.models hook, which real plugins (cursor, zed
and others) answer by asking the vendor once their own TTL runs out. It ran
even when no plugin had a chat.headers hook.

infoOf(id, key) now keeps the info per account. Any change to the
account's sign-in (setAuth, removeAuth, settle, client.auth.set, renew,
take, reload, all through forgetAccount), new provider options, or a new
models.dev file builds it again, once. providers() seeds the cache with
what it built. The loader, usage and check-in read it too; check's strict
build stays direct. chat.headers gets the shared object, as OpenCode hands
plugins the provider it keeps, and the request asks for it only when a
plugin has a chat.headers hook.

Measured (TestPerfScratch harness, not committed; fake plugin, sandbox
HOME, loaded machine, two runs each):
- {} body, 1-event reply, 400 fetches: models hook asked 400 -> 0 times.
- same, a plugin with 300 config models: 0.995-1.17 ms -> 0.27-0.29 ms
  wall per fetch, host CPU 1.23-1.33 ms -> 0.30 ms per fetch, host RSS
  87-89 MB -> ~54 MB.
- 246 KB body, 2 MB SSE reply, 40 fetches: host CPU 10.25 -> 8.25 ms per
  fetch, models hook asked 40 -> 0 times.
- idle host CPU ~10-20 ms per 10 s before and after.

Tests: TestFetchBuildsInfoOnce counts the fake's models hook (new
FAKE_MODELS_LOG): 20 fetches ask it 0 more times, a new sign-in and new
options each ask it exactly once, and chat.headers and the loader still
see fake-1 and every model. Broken by hand twice, red both times:
returning no cached info ("20 requests asked the models hook 20 more
times, want 0"), and not forgetting it on sign-in ("after a new sign-in
... 0 times, want 1"). host_flow_test's mid-setup case now stubs infoOf
and registers a chat.headers hook for its "info" stage, which red on
this change without it (the stage was never entered).

Run: go test ./internal/plugin -count=1 ok (159.5s);
TestFlowAbortDuringSetup|TestFetchBuildsInfoOnce -count=2 ok.
2026-10-19 09:40:45 +08:00
yetone 2ceff7370f gui: the window back reads the state once, not once for visibility and again for focus
A window shown again hears visibilitychange and focus together, and each
called load(true): two reads of /api/state (every agent's config), with
loadCLIs, loadInstalls, the providers and the Usage refresh after each.
Under focus-follows-mouse every pointer crossing into the window was one
more. loadBack now joins a return to the read asked under a second ago;
a return while an older read is still out gets one read after it, however
many came meanwhile.

Numbers (sandbox HOME, 16 agents, 1230 catalog models, dev build):
  /api/state is 2.28 MB and ~55 ms of CPU per read (20 reads: 1.11 s).
  Reads per window return: before 2, after 1.

The core's scripts were 1,446,845 bytes, 155 under their budget; loadBack
adds 523. Every page needs it, so it is the core's own: coreScriptBudget
goes to the new total, 1,447,368, plus 1.5% (1,469,000), as the budget's
own rule says.

Test: internal/gui/tests/window-back-once.test.cjs counts /api/state
reads for a return, a later return, and returns during a held read.
On the old app.js: 8 of 8 red, "shown again ... actual 2, expected 1".

Run at this head (load average ~500, nine sessions' suites at once):
  node --test window-back-once.test.cjs, Chromium and WebKit, en and zh,
  window and panel: 8 of 8 ok. TestCoreScriptBudget ok.
  GUI files that fire focus or visibility (15 files, both engines): 194 of
  196 ok. claude-usage-asked webkit en passes 9 of 9 alone.
  tray-cell-click webkit zh is red alone 3 of 3, on 1a3b92688's own app.js
  too: #2686, output added there.
  go test -p 4 ./... -timeout 45m (HOME a sandbox): 59 packages ok, and:
  - internal/gui: TestCoreScriptBudget red, fixed here (budget above);
    TestSetAnswersWhileDevinAndProvidersHang red (13.8s sets), ok alone
    (12.6s) and the whole package ok alone (391s): #1375, output added.
  - internal/plugin: TestGatewayHookMixedPiPackage red ("starting plugins:
    context deadline exceeded"), ok alone (110.8s): #2865, output added.
  - internal/agent, internal/library, internal/gateway: timed out at 45m.
    agent timed out alone too (2701.5s): #2544, output added. library is
    #2853 and gateway #2870. Neither was rerun alone, to keep load off
    the machine.
  go vet on darwin, linux (nogui) and windows: clean. gofmt -l: clean.
2026-10-19 09:29:28 +08:00
yetone 94919109cb gateway: a silent HTTP/2 connection to a vendor is pinged and dropped (#2843)
pinewhite (#2843, v0.1.1279, Linux): for ~30 minutes every request to
group/auto-deepseek-v4-1-flash hung with no first byte. The WorkBuddy
member was resting on a 429, so they all went to ClinePass, and usage
shows only 499s with in=0. A restart answered the same request in 1.6s.

Cause: the gateway's transport (upstreamTransport) speaks HTTP/2 to
any vendor that offers it, so every request to api.cline.bot shares one
connection. It had no HTTP/2 health check. A connection that goes silent
without closing (a local proxy whose own way out died, or a NAT that
forgot the flow) stays in the pool. Every new request is multiplexed
onto it and waits for the 10-minute ResponseHeaderTimeout while the
kernel takes the writes. The agent gives up first, so nothing fails over
and nothing rests the member. Restarting dropped the connection.

Fix: netproxy.HTTP2Health() (SendPingTimeout 20s, PingTimeout 10s) on
upstreamTransport. Go now pings a connection that has had no frame for
20s and closes it when no answer comes within 10s. The requests on it
fail as a 502 ("http2: client connection lost"), so a group moves on,
and the next request dials a new connection. A live vendor answers a
ping whatever its streams are doing, so a long wait for a first byte is
not cut. The same setting goes on http.DefaultTransport in
netproxy.Install, the sibling pool that usage cards, catalogs and
sign-ins use. Not covered: requests a plugin sends from Bun.

Tests (new):
- TestSilentHTTP2ConnectionIsDropped: an HTTP/2 TLS httptest vendor
  behind a TCP relay that can go silent on its open connections (it
  takes writes, passes nothing). After the relay goes silent, a request
  must end well inside 10s, and the next one must succeed on a second
  connection.
- TestGroupMovesOnFromSilentHTTP2Connection: the same through the real
  Handler, with an ordered group a/m then b/m. Once a's connection is
  silent, the request must get b's reply.
- TestInstallChecksHTTP2Connections (netproxy).

What was run (worktree on origin/main 1a3b92688, sandbox HOME, pinned
GOCACHE/GOMODCACHE, go1.26.8 darwin/arm64):
- Red without the fix (HTTP2 lines removed, tests kept):
  TestSilentHTTP2ConnectionIsDropped FAIL "hung 10.003s, until the
  client gave up: context deadline exceeded";
  TestGroupMovesOnFromSilentHTTP2Connection FAIL "200 <empty> after
  10.005s; want b's reply"; TestInstallChecksHTTP2Connections FAIL
  "HTTP/2 after Install: <nil>".
- Green with it: those, TestCodexBackendOverHTTP1 and the Stale tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok. go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build: ok.
- go test -timeout 45m ./...: 59 packages ok. The machine's load average
  was 400-460 (other sessions' GUI suites and builds).
  internal/agent, internal/gateway and internal/library hit the 45m
  alarm while a test that had just started was running (0-40s in), not
  stuck in one test. Four tests failed on a time bound:
  TestIntentClassifierGroup, TestClaudeAccountsSpentFallBackToCodex
  (gateway), TestSetAnswersWhileDevinAndProvidersHang (gui; a set took
  18s against its bar) and TestGatewayHookWaitsForStartingHost (plugin).
  None of them uses HTTP/2. Rerun alone on this change: gateway,
  gui and plugin ok. internal/library alone: ok
  (2220s). internal/agent alone hit 45m again at load ~400, as filed
  in #2723/#2544 (it doesn't call netproxy.Install or upstreamTransport
  in a test this touches). The reds are filed: #1813, #2858/#2859,
  #1375, #2723/#2544, #2853, #2870, and #2871 (new, the plugin one).

Not verified: no real ClinePass account behind a proxy that goes silent,
so the reporter's path is reproduced with an injected silent relay, not
seen live. Not tried on Linux or Windows beyond vet and build. The GUI
is not touched, so the GUI suite was not run.
2026-10-19 08:00:04 +08:00