Commit Graph
63 Commits
Author SHA1 Message Date
yetone ead0bf0059 agents, sessions: open in a terminal on Windows and Linux too, and copy any CLI agent's launch line
lileo0668 on Discord: clicking an agent should start it in a terminal,
and a history session should resume there. Opening a terminal was the
Mac app's only (Open in terminal on an Agents row, and Sessions' Open in
the selected terminal and Continue with another agent), and Copy launch
command was only for agy, Cursor (local) and Claude Science.

- terminal_open.go: openTerminal off a Mac.
  - Windows: Windows PowerShell (the system default), PowerShell 7 and
    Windows Terminal. The line, PowerShell's as Sessions already copies
    it, goes as -EncodedCommand: no script file, so no execution policy,
    no file encoding and no quoting in between. A shell gets its own
    console through cmd's start (magpie's children are CREATE_NO_WINDOW);
    wt is started directly, on pwsh or else powershell.
  - Linux: $TERMINAL, then xdg-terminal-exec, then x-terminal-emulator,
    then the first of GNOME Terminal, Konsole, Xfce Terminal, kitty,
    Alacritty, Ghostty, foot, WezTerm, Terminator and XTerm, each with its
    own words before the command. The line runs from a script of its own
    in sh, then the user's shell, as the Mac's .command file does.
  - A terminal that quits failing within a second says so, with what it
    printed ("cannot open display").
- Settings' Session terminal row lists the terminals found on Windows and
  Linux too; no row when none is found.
- Every agent row with a program now carries `command`, the line the
  server builds (Launch, or the program quoted for this system's shell;
  an agent in a WSL distro is started through wsl.exe on Windows). The
  row menu (right-click or the grip) has Copy launch command after Open in
  terminal, on the web build and in the panel too.

Run:
- mote (macOS 27, go1.26.8): go vet of internal/gui and internal/settings
  for darwin, for linux with -tags nogui, and for windows; GOOS=windows
  and GOOS=linux (nogui) builds of the binary; go test ./internal/gui
  ./internal/settings ./internal/agent. Everything passes except
  TestMainWindowCorners/macOS_26_SDK, which is #3949.
- Windows (win-run, xiaomi-gpu): go test ./internal/gui ./internal/settings.
  The new tests pass, among them TestAgentLineWindows, where real
  PowerShell runs the encoded line on a claude.cmd in a folder named
  `it's a $(New-Item made1) & New-Item made2 #` and runs nothing else.
  The six reds are filed: TestLodyImportHandoff,
  TestImportStatusUnreadableIsUnknown and TestAionUiImportRow (#4115),
  TestUpdateThatWontStart (#1827), and TestPluginAgentMissingSaysSo and
  TestGatewayHeldByAContainer (#5324).
- Linux (wsl-run, magpie-desktop): go test -tags nogui -timeout 45m
  ./internal/gui ./internal/settings: both ok (internal/gui 630s; at
  the default 10m it timed out with nothing hung)
- Real use. A throwaway test called openTerminal, not committed.
  - On xiaomi-gpu's console desktop (schtasks /IT): system default and
    wt each opened a window and ran a line with ' and 中文. pwsh isn't
    installed there and was refused by name.
  - On magpie-desktop under Xvfb: the system default
    (x-terminal-emulator, the xfce4-terminal wrapper) and xfce4-terminal
    each ran it (TERM=xterm-256color, set by the terminal). xterm isn't
    installed there and was refused. Without a display, xfce4-terminal's
    "cannot open display" came back as the error.
- GUI (mote, Playwright Chromium and WebKit): agent-open-terminal (five
  languages, 980px and 420px; Copy sends the server's line to /api/copy
  unchanged), session-terminal (Win32 and Linux platforms at 420px, and
  no row when nothing is found), settings-general, and the agent-*,
  sessions-*, session-*, gui-de, gui-ja and gui-zh-tw files with
  fold-show-grip, grip-inset, tap-click, menu-input-scroll and
  click-scroll (102 files): 1689 pass, 5 fail. The fails:
  menu-input-scroll, 4 of 4 red alone on origin/main 152c3852f too
  (#3402), and i18n-keys' "a plugin's words are its own" is
  red on origin/main too (#5332, #5327, #5426, #5482).
- gofmt -l is clean. TestCoreScriptBudget passes; no budget was raised.

Broken by hand:
- PowerShell quoting turned into POSIX quoting: TestAgentLineWindows red.
- cmd's start dropped: TestWinTerminalArgv red.
- A terminal's failure ignored: TestOpenLinuxTerminalRuns red.
- app.js and settings.js put back as they were: 32 GUI tests red
  (agent-open-terminal, session-terminal).

Not tried:
- A real GNOME, KDE, kitty, Alacritty, Ghostty, foot or WezTerm. Their
  words come from their docs.
- Omarchy's xdg-terminal-exec.
- PowerShell 7 on a real desktop (not installed on the box).
- The packaged GUI app on Windows or Linux; the real runs called
  openTerminal from a test binary.

Refs #4474.

Reported-by: lileo0668 (Discord)
2026-11-06 16:02:04 +08:00
yetone c28220a5e7 sessions: a Codex thread saved on another provider resumes from Sessions
mrten_95615 on Discord: opening a Codex session from Sessions ran
`codex resume <id>` and Codex 0.166 stopped at "This chat uses custom,
but your current provider is magpie. Switch to custom to continue."
(modelProviderMismatch). Codex 0.166's app-server resumes a thread only
on the provider it was saved with (its state-database row, else its
session_meta), checked against the one config.toml (with -c) selects
(codex-rs app-server config_manager.rs load_for_resume); no flag lets a
resume go on another provider, and a provider config.toml no longer has
fails as modelProviderNotConfigured. Codex 0.165 resumed it on its own
provider without asking.

sessions.ResumeNow is the line that runs when the user opens a session
(GUI Terminal, TUI enter); the listed line is unchanged and nothing more
is read on a listing. For a Codex thread saved on a provider other than
the one Codex is on:
- config.toml still has that provider's table, or it is a Codex
  built-in (openai, amazon-bedrock(-runtime), gcp, ollama, lmstudio):
  `codex resume -c model_provider=<it> <id>`. Codex runs that embedded
  (no shared daemon) on the thread's own provider.
- the provider is gone: MoveCodexProvider moves the thread to the
  provider Codex is on (files copied to magpie's trash first, the state
  row too) and it resumes there, the only way Codex resumes it at all. A
  thread written to in the last minute or open in a Codex is left
  (ErrActive) and the plain line runs.
A WSL distro's Codex session and every other agent are as listed.

Run at this head (mote):
- go test -count=1 -run 'TestCodexResume|TestMoveCodexProvider|TestCodexProviderIn' ./internal/sessions: ok
- go vet ./internal/{sessions,gui,tui}, GOOS=linux -tags nogui and GOOS=windows vet of them: ok; gofmt -l: clean
- At this head (rebased on origin/main bf05291e2): go test -count=1
  ./internal/sessions ./internal/tui: ok; ./internal/gui: ok but
  TestMainWindowCorners/macOS_26_SDK (#3949, mote is macOS 27; this
  change touches only gui/sessions.go's terminal route); go vet darwin,
  GOOS=linux -tags nogui, GOOS=windows of the three: ok; gofmt -l clean.
- Full suite before the rebase (go test -tags nogui -timeout 45m ./...
  on mote, at eb779ce92 + this change): 86 packages ok; internal/gateway
  red on TestCodexPoolSaysTheClientsVersion alone (#4807, open, a full
  package run's known red). Not re-run after the rebase.
Broken by hand: ResumeNow returning the listed line, TestCodexResumeOnItsProvider
fails "resume ... && codex resume 01a0bdc9-..., want ... codex resume -c
model_provider=custom 01a0bdc9-..."; with the move dropped it fails
"the thread's rollout wasn't moved to magpie".
Real Codex: codex-cli 0.166.0 (npm darwin-arm64) in a sandbox
CODEX_HOME with two fake Responses servers: a thread made on "custom",
config.toml switched to magpie. Plain `codex exec resume` failed with
the reporter's modelProviderMismatch; ResumeNow's line resumed it and the
turn reached custom's server. With custom's table removed, plain resume
failed with modelProviderNotConfigured; ResumeNow moved it and the turn
reached magpie's server. The TUI `codex resume -c model_provider=custom`
was also driven in tmux (resumed, turn on custom, "Running without the
shared background server" warning). Codex 0.165.0 resumes it plainly.
Not tried: a Codex profile that names its own model_provider (a -c
override may lose to it); the Codex desktop app's resume; Windows'
PowerShell line (same flag, not run there).
2026-11-03 10:50:30 +08:00
yetone 1829cd52ff sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.

- usage.EachGatewaySession walks the projection without copying it.
  gui's listedExternal stops at the list's limit and skips hidden
  sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
  reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
  folder lists the same names. One file new or gone is stepped over.
  This holds ~32 B per file (~480 KB at 15k files), and the strings are
  shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
  gateway-sessions.md describes the lazy rows.

Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
  15k sessions x 10 turns, 400k ledger rows
    after a session file grows  150.6 MB, 201 ms -> 109.9 MB, 170 ms
    unchanged (warm)             17.2 MB         ->  12.0 MB
  3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
    after a session file grows   31.3 MB         ->  29.6 MB
    unchanged (warm)              4.5 MB         ->   3.4 MB
  /api/usage is unchanged at 0.4 MB.

Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
  6000 gateway sessions in tied pairs, one hidden and one carrying a
  native's id. At limits 5, 40 and 6010, and with no limit, the rows
  equal the old pipeline's (listedGateway + gatewayListed +
  MergeExternal) after the JSON round trip. A grown native comes first
  with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
  and 20 rows give MergeExternal's first 20, with allocation under a
  tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
  is equal to the first, in at most 3n mallocs. A file added, files
  removed, and a folder gone with another new each list as a fresh
  listing does. Another agent's keys keep their own prefix.

Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
  the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.

Run on mote (mote-run) at 73a1b8769, rebased on origin/main 07f4d46c5:
gofmt -l internal (empty), go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./... all clean. go test -count=1 -timeout
45m ./internal/sessions ./internal/usage ./internal/gui: sessions ok,
usage ok. gui is ok except TestMainWindowCorners/macOS_26_SDK, which is
#3949 (red on mote's macOS 27, an AppKit title bar test this change
doesn't reach). It was red the same way in the run before the rebase.

Not tried:
- A real app window with RSS measured over time. The numbers are
  allocation per poll from a probe.
- The rest of a changed poll: statsKept re-sums every session (~26 MB at
  15k), listing (~24 MB) and byKey (~9 MB). None was a cheap, safe
  change.
- Windows and Linux test runs (vet only).
- A gateway title store in the fixture. GatewayTitler's ReadDirs now run
  only for the rows shown.
2026-11-02 17:19:23 +08:00
yetone 344a59f9db gui: an unchanged Sessions poll answers Same without making the rows
The Sessions tab asks for every session each 15 s. When nothing had
changed, the handler still copied the kept listing, made a row of each
session, merged the gateway's sessions, read Codex's effort and the
vias, encoded every row and hashed them, only to answer X-Magpie-Same.
Over ~17k real sessions (69 GB of Claude Code and Codex history) that
was ~140 ms of CPU and ~24 MB of garbage per poll.

Now the handler keeps, per ?limit, what the last list it sent was made
from: the sessions listing (sessions.ListUnless's number, which changes
whenever the listing is made again, and at least once a minute), the
usage log's version (usage.LogVersion), the user's usage aliases, and
the agents' names and icons with the folders. An ask whose
X-Magpie-Had is that list's tag, while all of these stand, gets
X-Magpie-Same before any row is made or the listing copied. Anything
else a row shows (a Codex thread's effort, a gateway title) follows
within the minute the kept listing stands. writeJSONRows returns the
tag it sent.

Measured on the real history (a sandbox HOME with APFS clones of
~/.claude/projects and ~/.codex/sessions, 17,140 files), 30 polls of
/api/sessions + stats + overview, the same script for both builds:
  before (d614f2172): 4.19 s CPU, /api/sessions median 64 ms, 711 MB
    allocated
  after:              2.67 s CPU, median 47 ms, 298 MB allocated
What is left is the listing's own look at every file (getattrlistbulk,
~43% of the samples) and its GC.

Tests: TestSessionsSameWithoutRows: an unchanged poll is Same without
rows, and a gateway call, an alias and a new session file each make the
rows again. Broken by hand on mote: never taking the shortcut fails it
("rows made 1 times"), and leaving the log version out of the key fails
it ("after a gateway call: same true"). go vet and go test of
internal/gui, internal/sessions and internal/usage on mote (macOS):
sessions and usage ok; gui's reds were TestMainWindowCorners (red on
origin/main b646a9127 too, #3949) and the BusyLoad guard (#4739, fixed
by b646a9127; passes after the rebase onto 403323af7). GOOS=linux go
vet of sessions and usage, GOOS=windows of all three.

Not run: the full ./... suite, a Linux vet of internal/gui (cgo), the GUI suite (the page's api() and its
X-Magpie-Had handling are unchanged), Windows and Linux.
2026-11-01 15:27:49 +08:00
yetone f506638690 sessions: the Sessions poll makes its rows as the gateway's sessions merge
/api/sessions copied every one of ~17k sessions into MergeExternal's
merged list, and MergeExternal made a set of every native session's
keys again to leave natives out of the gateway's, though
GatewaySessions had already left them out by the same keys. The rows
were then copied from that list.

EachMerged hands each session to the caller in MergeExternal's order
(newest first, a native before an external of the same moment) from
the list as List gives it and the gateway's sessions sorted alone, so
the handler copies each session once, into its row. MergeExternal
keeps its own copy and dedupe for its other callers; both share
externalSessions.

TestEachMergedListsWhatMergeExternalDid: same rows, field for field, as
MergeExternal for a sorted list, an unsorted one (sorted in a copy, the
caller's left as it was) and none; with and without externals; ties;
stops at false. TestEachMergedCopiesNoList: 5000 natives merge in under
a twentieth of the list's bytes. Broken by hand, each red:
  EachMerged over MergeExternal's list: 5,437,624 bytes for a
    2,480,000-byte list
  EachMerged making the native key set again: 394,352 bytes

Measured on mote's build against the real ~17k sessions (sandbox HOME,
APFS clones), 30 polls, against v0.1.2554's build:
  heap diff alloc_space   726 MB -> 701 MB (MergeExternal's 107 MB
                          gone; externalSessions 51 MB left, the
                          gateway's own sessions)
  CPU over 30 polls       4.44s -> 4.24s
  /api/sessions median    73ms -> 71ms

Run on mote: go vet ./internal/sessions ./internal/gui ok;
go test ./internal/sessions ok; ./internal/gui red only in
TestSettingsSaveKeepsWhatItDoesNotSend (#4739) and
TestMainWindowCorners (#3949), both red on origin/main 788057340.
Not run: the full suite, the GUI suite (the answer's rows are the same).
Then rebased onto 1e6a27d4f (gui: an icon's image URL; none of the four commits touch sessions or the Sessions handler); not rerun.
Then rebased onto 994cd4fb6 (gui: Rex switches to the tab magpie opens, through the app's); not rerun.
2026-11-01 14:39:38 +08:00
yetone c76bcaea7a gui: between reads the heap grows by half of what it holds, not all of it
The window and the app's page, resting on ~60 MB live, poll /api/state,
/api/drift and /api/providers and throw ~10 MB away a round. At Go's
default GOGC of 100 the heap grew to twice what it kept before each
collection, so the footprint stood at 121-135 MB and peaked at 136-138
MB for a ~60 MB heap.

steadyGCStart, run once with the warm-up, sets GOGC to half, or to what
lets the heap grow by 32 MB when that is more (never above 100), and
sets it again for the live heap after each collection, through the
retightenGC hook the tight reads already use. The usage and sessions
reads under a tight GC still set their tenth while they run, and the
steady value comes back after them. A GOGC the user set in the
environment is kept, and nothing is retuned. No memory limit (#2278).

Run (mote, at this tree):
- go test -count=1 ./internal/gui: ok except TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514) and TestMainWindowCorners (#3949), the known reds.
- -run 'GC|Steady|Tight' 3 times and once under -race: ok.
- Broken by hand: ignoring GOGC in the environment, TestSteadyGCKeepsTheUsersGOGC
  is red ("GOGC=200 set by the user, magpie runs under 50"); with no
  retune after a collection, TestSteadyGCRetunesAfterACollection is red
  ("GOGC after collections = 50, want 100").
- gofmt -l, go vet, GOOS=windows go vet -tags nogui ./internal/gui: clean.
- Real accounts, magpie web in a sandbox HOME, 40 rounds of the three
  polls, twice each, alternating, v0.1.2507 against this change:
    phys_footprint_peak  136 / 137 MB  ->  115 / 116 MB
    phys_footprint end   135 / 121 MB  ->   96 /  94 MB
    CPU of the polls     3.84 / 3.98s  ->  4.05 / 4.24s
  /api/state and /api/drift byte-identical.
  GOGC=50 in the environment gave 107-108 MB at +9% CPU; the 32 MB room
  keeps a small heap from collecting that often.

Not run: the desktop window (Wails) and Windows/Linux machines; the
tray app takes the same Handler path. A large usage history between
reads (~280 MB live) now grows by ~140 MB, not ~280, before a
collection; not measured here.

Picked onto 4179cf2d8 (pii: pf-serve-base for CPUs without AVX2; no file in common); not run again there.
2026-11-01 08:49:18 +08:00
yetone d9845432f7 gui: a same-tagged answer is written twice, never held whole (#2278)
writeSame wrote each answer into a buffer to hash and send it, and kept
two such buffers between polls (answerLinger). The Sessions tab's stats
answers are ~6 MB each over a full history, so 12.5 MB of a warm start's
169 MB live heap was those buffers (heap profile, bytes.growSlice under
statsAnswer). Now write is given an io.Writer and called twice: once into
the hash for the tag, and once straight to rw (32 KB bufio) when the page
hasn't got that answer. statsAnswer encodes a part at a time into a small
buffer. The stats route still answers "same" from its kept tag without
encoding at all when nothing changed, so the second encode costs only on
a changed answer. answerBuffers, answerBuffer, keepAnswer go.

Run on mote (M5 Pro), from this tree:
- go vet ./internal/gui ok; gofmt -l clean.
- go test -count=1 ./internal/gui: FAIL only TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514) and TestMainWindowCorners/macOS_26_SDK (#3949), both filed, both
  untouched by this change. TestStatsAnswerWritesWhatEncodeDid (bytes are
  the whole Encoder's) and the new TestSameAnswerNotHeldWhole pass.
- Broken by hand: writeSame's bufio sized 64 MB, TestSameAnswerNotHeldWhole
  red ("allocated 67117776 bytes for a 4194304-byte answer").
- Warm start on a copy of the owner's real history (11,925 Codex .zst,
  4,696 Claude .jsonl, 5,000 listed sessions), the page's 10 reads every
  5s, interleaved, load ~25-34:
    before (bb5eb83c3): footprint peak 267, 269, 274 MB; cpu 9.6-10.1s
    after:              footprint peak 255, 257, 258 MB; cpu 9.9-10.2s

Not tried: a cold start A/B (the buffers matter once polls begin).
2026-10-31 20:31:26 +08:00
yetone b9e5bc6cb3 gui: Rex is a session terminal, opened through its rex CLI (#4565)
Rex (com.superlogical.rex) claims no .command file, so Launch Services
never listed it and `open -a` can't hand it a script (StringKe).
Sessions' terminal list now offers Rex when its CLI is found: a native
`rex` on PATH, or one inside a Rex*.app in /Applications or
~/Applications (Rex puts rex on PATH only in its own terminals). Perl's
Rex installs a script named rex too, so only a Mach-O or ELF program
counts. Resume, carry and an agent's Open then run
`rex run --label <title> -- /bin/sh -c '<command>; exec login shell'`:
no shell parses the label or the command on the way. With no session
to add a tab to (exit 3) it runs `rex new`; with Rex's server not
running (exit 4) the error says to open Rex. Rex is then brought
forward with `open -b`. The GUI already lists s.terminalApps, so no
JS changed. reference.md's Session terminal says it.

Parts 2 to 4 of #4565 (accounts run per account, OSC 7501 status,
folder mapping) build on #992, which isn't merged; not done here.

Ran, at this tree on origin/main e90a635a9, through mote-run:
- go test ./internal/gui -run 'TestFindRex|TestOpenInRex|
  TestDiscoverTerminals|TestTerminalOpenArgs|TestAgentOpen': ok.
  TestOpenInRex runs the real sh script with SHELL=/usr/bin/true and
  checks the command ran in its folder, and a label holding $(...) and
  quotes stays one argument.
- go vet ./...; GOOS=linux (-tags nogui) and GOOS=windows go vet and
  go build: ok (at the pre-rebase head; go vet ./... again rebased).
- Full suite, go test -tags nogui -timeout 45m ./..., at the
  pre-rebase head: every package ok but internal/gui, red on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red the same on
  origin/main e90a635a9) and TestColdTurnsTaken (#4510). Rebased,
  internal/gui and internal/provider whole again: red on #4514 only.

Broke by hand, each red, then restored: withRex taken out of
discovery (TestDiscoverTerminalsOffersRex); the exit-3 fallback to
rex new turned off (TestOpenInRex: "rex: Error: no session"); the
native-program check dropped for PATH (TestFindRex took the Perl
script).

Not tried: the real Rex app or rex binary. Its installer needs a
Discord sign-in, so the CLI was driven from Rex's docs only; whether
`rex run` with no -s from outside Rex targets the shown session or
exits 3 is not confirmed. Not run on Linux or Windows (Rex's Linux
build, and the tests skip on Windows). No GUI Playwright run, as no
JS changed.
2026-10-31 19:35:16 +08:00
yetone ca7eb9aff7 gui: underTightGC's comment names the room a tight GC leaves a small heap
The comment still said a tight GC lets the heap grow by a tenth. Since
v0.1.2331 it grows by tightGCRoom (32 MB) when that is more
(tightPercent). Comment only. gofmt clean; nothing else to run.
2026-10-31 15:11:58 +08:00
yetone 0bf5adb118 gui: a tight GC lets a small heap grow by 32 MB, not a tenth (#2278)
The usage and sessions reads run under GOGC=10. On a first start they
begin on a ~50 MB live heap and allocate ~400 MB a second, so a tenth
was a collection every few MB: 2,102 to 2,239 collections in the first
75 s, about 70 s of the start's CPU, and each one emptied the zstd and
bufio pools, which were then allocated again.

While a read is under a tight GC, each collection now sets GOGC for
the heap it left: tightPercent gives a tenth, or enough for 32 MB of
growth, never above what was set before (a lower or off GOGC is kept).
A heap over 320 MB is held to a tenth as before. The hook is a
finalizer re-armed after each collection while a read is under it.

Cold start on mote's copy of the real history (75 s, two runs each,
v0.1.2330's lastIndex build vs this):
- CPU 3:46.66 / 4:00.50 -> 3:08.69 / 3:10.04 (user 3:18.97 / 3:28.67 ->
  2:44.23 / 2:45.85)
- collections 2,239 / 2,102 -> 706 / 705
- phys_footprint_peak 318 / 312 -> 330 / 335 MB
- heat, requests, overview 0/7/30 and stats 0/30 answers byte-identical
A 16 MB room: 3:46.86 / 3:38.78 CPU, 1,554 / 1,390 collections, peak
331 / 323 MB, so it buys little.

Tests (mote): go vet ./internal/gui; go test ./internal/gui -run
'TightGC|WarmUp|UnderTight|TightPercent|WarmCodex' ok.
TestTightPercentLeavesRoom pins the bound; TestTightGCRetunesAfterACollection
checks a collection retunes GOGC and the read's end restores it.
Broken by hand: retightenGC not setting GOGC turns
TestTightGCRetunesAfterACollection red.
Not tried: the full gui package (TestCoveredWindowStaysUp is killed on
mote, #4125); Windows and Linux runs.
2026-10-31 13:03:34 +08:00
yetone 86e19b9b74 gui: a cold start's turn lets the matcher's scratch go when it ends (#2278)
Each turn of the warm-up and of a page's first ask (coldTurns) now ends
with usage.ReleaseMatchScratch: the request matcher's kept maps, picks
and row buffers, which sat for scratchLinger (30 s) under the next
turn's read of the history. The priced blocks stay, so the next turn's
queries don't price the history again.

On mote, a sandbox HOME with the real history (13k sessions, ~720k
gateway calls), 75 s with ten answers asked every 5 s, phys_footprint
peak:
- start with its caches: 260 and 263 MB, against 274 and 285 MB at
  v0.1.2284.
- first start, run alternately with v0.1.2284: 359, 359 and 361 MB
  against 360, 360 and 364. CPU 3:41-3:47 against 3:35-3:41. The
  slowest first answer was 31.5-32.4 s against 30.9-31.8 s.
- the heatmap and the requests answers are byte for byte the same.
Dropped: releasing the priced blocks too (ReleaseScratch). That gave
253-255 MB with caches, but 362-369 MB on a first start, which priced
the history again in each turn.

Run on mote at 03d21ab8e + this:
- go vet ./...: ok.
- go test ./internal/usage: ok.
- go test ./internal/gui: red only in ten real-window AppKit tests,
  killed at their deadlines under load. They are the same ten that fail
  on a clean a6951cc63 (#4125, #2645).
- TestMatchScratchGoesPricedBlocksStay goes red with
  ReleaseMatchScratch made a no-op, and red when it releases the priced
  blocks too.
- gofmt -l: clean.
Not run: Linux vet of internal/gui (no gtk4 on wsl-run). After this was
run, the rebase onto origin/main brought in 11fc687c0 (a GUI test's
wait), 06c2c35d1 (Claude's interactive start) and 6ba593de0 (the main
window's passing note). They touch none of these files.
2026-10-31 08:31:15 +08:00
yetone 03d21ab8e1 gui: a page's read and the warm-up collect at GOGC 10, not 25 (#2278)
tightGCPercent goes from 25 to 10. This is the GOGC that underTightGC (the
warm-up's reads) and every /api/sessions* and /api/usage* answer
(held) run under; it is put back once the last read ends.

Profiled on mote (heap dumps at each 8 MB of live heap, plus a goroutine
dump). After v0.1.2280 the first start's reads already take turns, so the
peak is one build at a time over what the indexes keep. The live peak is
~280 MB, and at GOGC 25 Go let the heap grow ~70 MB past that before a
collection.

Bench: the mote sandbox HOME with the real history (13k sessions, ~720k
gateway calls), MAGPIE_NO_STATS=1, a poll of ten answers every 5 s,
75 s per run, footprint peak (phys_footprint_peak):
- cold start (no caches), 3 runs each:
  - v0.1.2280: 397/390/392 MB, 162–168 s user CPU, slowest first answer
    29.8–30.6 s
  - this change: 352/350/352 MB, 197–200 s user CPU, slowest first answer
    31.9–32.4 s
- start with caches, 2 runs each:
  - v0.1.2280: 321/304 MB, 7.6 s user CPU
  - this change: 271/275 MB, 10.3 s user CPU, mean answer 0.12 → 0.13 s

Tried and dropped:
- 10 only until the warm-up ends: cold 372–374 MB, warm 301–306 MB.
- 10 only inside usage's big builds (a holdBigBuild hook): cold
  373–395 MB, warm 304–312 MB. The peaks are not all big builds.
- Warming the heatmap as a fifth warm-up step: cold 395–401 MB, the same.
  The goroutine dump shows the page asks already take their turns.

Run on mote, first at 7f2acb9ff + this, then again after the rebase onto
a6951cc63 (which brought a GLM card fix, the WorkBuddy min and the main
window's footer):
- go vet ./...: ok, at both heads.
- go test -timeout 45m ./internal/gui/ at 7f2acb9ff + this: every test
  passed except TestCoveredWindowStaysUp (#4125).
- The same run at the rebased head: ten real-window AppKit tests were
  killed at their deadlines (dock, panel, tray, titlebar, plugin page,
  covered window). Five of them, run alone on a clean a6951cc63 checkout
  without this change, were killed the same way while another session's
  GUI suite loaded mote. They are filed: #4125, #2645, #1936 and #3178.
- gofmt -l: clean.
Not run: the Linux vet of internal/gui (Wails needs cgo to cross-compile,
and the WSL distro has no gtk4). The change is a constant and comments.
2026-10-31 07:42:25 +08:00
yetone 7f2acb9ffa gui: a first start's page asks and warm-up reads take turns (#2278)
On a first start with no sums on disk, the window asks the Sessions
page's stats and overview and the Usage page's requests and heatmap
while the warm-up reads the same history. A heap profile at a live
294 MB, 30.6 s in, had ~147 MB in those asks' handlers (QueryPage 102
MB, session stats 51 MB) beside ~42 MB in the warm-up's session scan.
Each was a first read of the history held beside the others.

Until the warm-up ends, each warm-up step and each ask of /api/sessions,
/api/sessions/stats, /api/sessions/overview, /api/usage,
/api/usage/requests and /api/usage/heatmap take one turn at a time
(coldTurns). Each read comes after the one before it has kept what it
read, so most find it kept. held's sessions.Ask still makes the
warm-up read at full speed while a page waits. No page waits more than
2 minutes for its turn, so a stuck warm-up can't hold the pages. Once
the warm-up is over, nothing waits. Tests don't take turns
(coldTurnsTaken).

Bench on mote (M5 Pro), a real 390k-call history, cold (no caches),
poll.sh asking what an open window asks every 5 s, the poll loop killed
between runs (advgcp2.sh); phys_footprint peak:
  before (bca0d6d69): 456 494 500 469 424 424 416 410 MB
  after:              392 396 394 404 389 393 392 MB
  live heap max: ~293-338 before, ~276-288 after
  slowest requests/heatmap answer: 31-46 s before, 30-39 s after;
  every poll answered 200 in the last three runs (100 of 100)

Also tried and not shipped: reading the warm-up's 0 and 30 day session
stats in one pass, with asks for a range being read waiting for it. Its
peaks were 408 480 463 405 MB against 424 424 416 410 MB.

Run at bca0d6d69, rebased onto c59c547c5, whose two commits touch no
file here (claudetui, gateway, provider, and app.js/i18n.js strings):
- go vet ./internal/gui (darwin) and GOOS=windows: clean.
- go test -count=1 ./internal/gui on mote: ok except
  TestCoveredWindowStaysUp, a real AppKit window killed at its 30 s
  deadline. That is #4125: mote's AppKit tests hang.
- go test -race -count=3 of TestColdTurnsTaken, TestWarmUp*, TestStats*,
  SessionStats, Overview, Heatmap: ok.
- Broken by hand: with coldTurn's turn skipped, TestColdTurnsTaken fails
  with "the page was answered while the warm-up's step read".
Not run: Linux go vet. Cross-compiling needs cgo for Wails, and the WSL
distro has no gtk4 or webkitgtk-6.0 dev packages. The change has no
OS-specific code.
2026-10-31 06:22:53 +08:00
yetone f03ed8c26e agents: Open in terminal on a Mac's Agents row (coolmantou)
coolmantou on Discord asked to start an agent from magpie's Agents list.
In the Mac app's window, an agent row's menu (openRowMenu, the one the
grip and a right-click open) now has "Open in terminal". This includes a
row under Not set up. Clicking it posts POST /api/agents/open with only
{agent: id}. The server finds that exact id in agent.Detected() (not
agent.Find's prefix match) and builds the line itself: the agent's
Launch() where it has one (agy, Claude Science, Cursor local), otherwise
its program's path, single-quoted (BinPath, new in internal/agent).
openTerminal then opens that line with the user's Session terminal
choice. The command never comes from the page. Other systems, the web
build, WSL agents and desktop apps with no program are refused, and
their rows have no item (agentJSON.terminal). The tray panel's rows don't
have the item either. The label is "Open in terminal", not "Terminal",
because the user's terminal can be iTerm or Ghostty. The string is in
en, zh, zh-TW, ja and de. Windows and Linux are #4474.

The core budget had 39 bytes left on main, so no budget was raised.
Instead:
- the item says nothing on success; the terminal opening is the answer,
  and a failure goes to statusErr;
- the omp roles' comment above OMP_UNSET was cut to what OMP_UNSET's
  values don't already say.
app.js is now 22 bytes under main's size.

Run:
- go test ./internal/gui ./internal/agent on mote (macOS) and in
  magpie-desktop (Linux, -tags nogui), both ok.
  - TestAgentOpenRunsOnlyTheAgent puts claude in a folder named
    "it's a' $(touch made1) `touch made2`; touch made3 #". It posts the
    ids "claude; touch made4", "claude'$(touch made5)'" and "cl"; none
    of them opens anything. It then runs the line made for claude
    through /bin/sh and checks that only the program ran.
  - After the rebase onto origin/main 2604d68db, the core budget
    first went red (1,536,904 > 1,536,586). It passed again after the
    trims above, along with TestAgentOpen* and TestAgentCommand*.
- gofmt -l clean. go vet on darwin, GOOS=linux -tags nogui and
  GOOS=windows for internal/gui and internal/agent: ok.
- GUI, both engines (wsl-run): agent-open-terminal.test.cjs is new,
  14/14 at the pushed tree. It covers every language, a row under Not set up, no item for
  the desktop app, the web build or the tray panel, and checks that the
  post body is the id only. Its goto has 30s, since a goto while
  another suite ran on the box took 5s once. i18n-keys and agent-disconnect pass.
- Real run on mote in a sandbox HOME: the endpoint was called through
  the real openTerminal with an `open` on PATH that records instead of
  opening. It returned 204, and the open args were -a
  /System/Applications/Utilities/Terminal.app <file>. The file was
  -rwx------ and read: #!/bin/sh / '<sandbox>/.local/bin/claude' /
  exec "${SHELL:-/bin/zsh}" -l.

Broken by hand:
- agentCommand returning the path unquoted: the Go test went red with
  "ran more than the agent: [made1 made2 made3]".
- The term item dropped from openRowMenu: the 10 row tests went red.
- The panel and web gates dropped: the 4 gate tests went red.

Not tried:
- No terminal app actually opened. The scratch run recorded what
  `open` would get instead.
- iTerm, Ghostty and the other Session terminal choices were not tried.
- Launch() agents (agy, Claude Science, Cursor local) were not opened
  for real; their lines were already quoted and used by
  "Copy launch command".
- The full Go suite and the whole GUI suite were started before the
  rebase and not waited on (ship at once).
2026-10-31 01:22:28 +08:00
yetone 1334934881 sessions: a listing's gateway titles ask once whether anything was recorded, not once a session (#2278)
Each poll of the Sessions list and of every stats range titled each of
~5000 gateway sessions with GatewayTitle, which made the recordings
folder's name and Stat-ed it each time. With nothing recorded, as for
most users, that was the whole cost: os.Stat 62 MB and gatewayDir 18 MB
of 90 s of polls while an agent worked.

GatewayTitler makes the folder's name and asks once, and gives "" with
no work when nothing is recorded; gatewayListed takes it. GatewayTitle
is GatewayTitler()(agent, id), for one session.

Bench (mote, ~/r2278/full, hmw.sh second runs), e14 = bed604efb, e15 =
this: GatewayTitle 81 MB -> gone, gatewayListed 100 -> 19 MB, polls 170
x 200 in both; total 2308 -> 2350 MB is the run-to-run band.

TestGatewayTitlerAsksOnce: with nothing recorded a title makes 0
allocations; after a turn is recorded a titler made then finds what
GatewayTitle finds. Broken by hand (Stat and the folder's name again per
session): red.

At 825db07aa on bed604efb (mote): gofmt clean; go vet -tags nogui
./internal/gui/ ./internal/sessions/ for linux, windows, darwin ok;
go test ./internal/sessions/ ok; go test ./internal/gui/ -run
'Gateway|Sessions|Stats' ok.
2026-10-30 19:12:35 +08:00
yetone bed604efb3 gui: the Sessions list and stats answers are written into buffers kept between polls, the stats a day at a time (#2278)
With the Sessions tab open, every poll grew each long answer's buffer
from nothing: writeJSONRows' `whole` (~8 MB of rows) and writeJSONSame's
buffer plus encoding/json's own encodeState for the stats (~6 MB of
days), which the Encoder grows to the whole value after each
collection. In 90 s of polls while an agent worked, writeJSONRows was
245 MB and the stats' writeJSONSame 209 MB of 2702 MB allocated.

- answerBuffer/keepAnswer keep two buffers, dropped 30 s after the last
  answer (as the usage scratch lingers). A ResponseWriter copies what
  it is written, and only the rows' sums outlive the call, so nothing
  reads a buffer once it is put back.
- writeSame is writeJSONSame over a write func; writeJSONRows and the
  stats handler use the kept buffers.
- statsAnswer encodes the stats a Day at a time, byte for byte the
  Encoder of struct{ sessions.Stats; Agents } (the page's tag rests on
  those bytes).

Bench (mote, ~/r2278/full, hmw.sh: a gateway call every 3 s, 10
endpoints polled every 5 s with X-Magpie-Had; second runs compared),
e13 = 3bce283df, e14 = this:
  total alloc 2702 -> 2308 MB, writeJSONRows 245 -> 110 MB,
  stats encoding 209 -> 46 MB, /api/sessions/stats handler 306 -> 128 MB,
  GCs in 90 s 85 -> 71, fp_peak 347 -> 360 MB (noise band 345-370).
  Polls 170 x 200 in both. One e14 run (y14) had 60 answers of "400 Bad
  Request" (15 bytes, <6 ms): Go's net/http refusing a malformed request
  header from the bench's tag file; y12 at the old code had the same 60,
  and a rerun had none. That run is not compared.

Tests: TestStatsAnswerWritesWhatEncodeDid (nil/empty/HTML/U+2028 days,
keys, agents, a hidden Sessions), TestAnswerBufferKeptForTheNext
(writeSame and writeJSONRows put a buffer back that the next answer
takes). Broken by hand, each red: writeSame without keepAnswer (red),
writeJSONRows without keepAnswer (red), statsAnswer keeping Encode's
newline (red).

At 9d6461416 rebased on 9e73f69af (mote): gofmt clean; go vet -tags nogui
./internal/gui/ ./internal/sessions/ for linux, windows, darwin ok;
go test ./internal/gui/ -run 'TestStatsAnswer|TestAnswerBuffer|
TestWriteJSONRows|Sessions|Stats|Same' ok; go test ./internal/sessions/ ok.

Full internal/gui on mote at the pre-rebase tree: every test ok but ten
real-window AppKit tests killed at their 20-40 s deadline (dock order,
panel close/space, plugin page, dock reopen, titlebar corners/RTL, tray
shown, released panel, window up), mote's #4125 / #2645, which this
change doesn't reach.
2026-10-30 19:05:17 +08:00
yetone bcf0cfa232 sessions: usage counts a session Claude Desktop's Code tab ran under Desktop
CyberCaius on Discord: Usage's Claude Code filter listed Claude Desktop's
sessions. Desktop's Code tab runs Claude Code, which keeps the session in
~/.claude/projects like a terminal one; only each line's `entrypoint`
(claude-desktop, claude-desktop-3p) tells them apart. The calls were
counted under Desktop already (desktopEntrypoint), but the session, its
stats rows and its summary were Claude Code's, and the gateway's own
record of the session ("claude-desktop|<id>") wasn't matched with it, so
it could be listed twice.

The parse now keeps the entrypoint (state.Entry, on both the ccWhere fast
path and the full parse; cacheVersion 29) and a Code tab session gets
Session.App "claude-desktop". Its Agent, key claude:<id>, resume and
transcript stay Claude Code's. Stats rows and the summary use the app,
GatewayKeys and MergeExternal know the claude-desktop|<id> pair, the GUI
names it Claude Desktop, and Usage › Sessions filters by app || agent.

Run at the pushed tip (the AnySearch commit after this one, on
e8d42c02d): go test ./internal/sessions ./internal/library ok (mote);
go vet darwin, linux -tags nogui, windows over ./internal/... VET-OK;
i18n-keys ok; usage-sessions-desktop-app.test.cjs (new) 4/4 chromium +
webkit, en + zh, on the Linux box (on mote its webkit.launch timed out at
load ~40, before any page code).
This commit alone, before the last rebase (8bd8f50d5 on 1534474c8):
go test ./internal/sessions ok and the new GUI test 4/4 (mote).
Run at 7ec95b5dd (both commits on 1534474c8):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  (mote): VET-OK.
- Full go test -tags nogui ./... -timeout 45m on the Linux box (wsl-run).
  Red only where origin/main eadeb89c4 is red on the same box, each filed:
  internal/agent install detection (#4033, #3548), internal/gateway
  Antigravity turned-away and TestCodexSpentGrokFailingIsTold (#4362);
  internal/cli TestAgentFieldNameShowsIt and
  TestEveryAgentFieldNameWritesNothing red in the full run, ok alone at
  this tip (#4247).
- GUI: i18n-keys and gui-de/ja/zh-tw ok on mote; the other sessions-*
  and usage-* files hadn't finished on mote when pushed.
- The whole GUI suite has not finished: a WSL run at the tip was about
  half way (2226 ok) when this was pushed, with reds only in files these
  changes don't reach (routing key models, panel name width, LAN
  addresses, Codex composer, Copilot GHE, gateway key limits, ...);
  they'll be checked against origin/main and filed on their own.
Earlier, before the rebase (da5f1e5bd on ffa07395e): full go test
-tags nogui ./... on mote, 80 packages ok.

Broken by hand, each red: stats not using appsOf (usage agent stays
claude); the Entry in claudeFull; the Entry in ccWhere (the test's first
line is an attachment so the fast path is taken); MergeExternal without
the App pair (3 sessions become 4); page.js's byAgent on agent only (GUI
test times out).

Not tried: a real Code tab transcript (none on this machine; fixtures are
written from the field names only). A Code tab that sends the plain
magpie key through settings.json env would be recorded by the gateway as
claude, not looked at. NativeIDs for claude-desktop doesn't read Claude
Code's files yet: #4333.
2026-10-30 14:38:22 +08:00
yetone 37527c7ad3 sessions: omp's subagents and advisor are their session's to the gateway, not counted again (Jumy on Discord)
omp's task subagent (Kid.jsonl) and advisor (__advisor.jsonl) each have
a header id of their own, and omp sends that id, not the main
session's, in x-session-affinity (seen in a real omp 18.9.1 run through
a fake upstream: the main session's requests carried 01a18ae4-555c-…,
the subagent's 01a18ae4-5671-…). magpie counts those files in the main
session, but the gateway's native keys held only omp|<main id>, so the
gateway's records of the subagent's and advisor's calls were added
again as sessions of their own: in Usage › Sessions' totals
(MergeExternalStats), in the Sessions list (MergeExternal) and in
NativeIDs.

Session.Subs (subIDs) now holds those ids, and GatewayKeys,
MergeExternal and nativeIDsWith take them as the session's own.
GatewayKeys takes Claude Code's Copies too, which the GUI list added
by hand beside it; the stats' native map already had each copy's own
group, so nothing counts differently there.

This is at most a second count of the subagent's and advisor's share,
not a ~1000x: it may not explain the whole ~900M Jumy saw. Not found
in the reader: omp's usage is per call (assistant messages only;
toolResult and compaction carry none), re-reads continue from the
offset only when the head and sampled prefix hashes match.

Tests: TestOmpSubagentsAreTheSessionsToTheGateway (sessions, the
existing omp fixture, whose sub headers match omp 18.9.1's) and
TestOmpSubagentCountedOnceWithTheGateway (gui, /api/sessions/overview
and /api/sessions, from omp 18.9.1's own lines). Broken by hand
(subIDs returning nil): both red, the overview showing the Kid id as a
second gateway session with 5000 input beside the native one.

Run on mote: go test ./internal/sessions -run 'TestOmp|TestRaft',
./internal/gui -run 'TestOmpSubagent|TestTopSessions'; gofmt -l;
go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet on the two
packages; go build for darwin, linux (nogui), windows.
go test -timeout 45m ./internal/sessions ./internal/gui ./internal/usage:
sessions and usage ok; gui red only in TestMainWindowCorners/macOS_26_SDK,
#3949 (mote's macOS 27, titlebar code this change doesn't reach). The
full ./... was not run before the push: mote had other sessions' full
suites running at load ~180.

Not tried: Jumy's own session files or ledger (not available), so the
rest of the 900M is unexplained; Kimi Code's subagents (it sends no
session header magpie knows, so its gateway rows aren't sessions);
the GUI Playwright suite (no asset changed).
2026-10-30 11:54:46 +08:00
yetone 7db0810b03 sessions: stats asked again unchanged are not encoded again; lists made at their size (#2278)
The Sessions page asks for /api/sessions/stats (7, 30 and every day) and
the list every poll. On a full history (52G Codex + 13G Claude) the
stats for every day are ~6 MB of JSON, encoded and hashed again on each
ask even when the page already had them, because the read behind every
10s replaced the kept stats with an equal copy.

- statsKept has a gen, kept when the read behind finds the same stats
  (sameStats: From, To, Keys, Days, what is sent). The handler keeps the
  tag last sent per ?days with its gen and agent names, and an ask with
  that tag is answered X-Magpie-Same without encoding. Only the 32-char
  tag is kept, no body.
- MergeExternalStats grows Sessions once for every external session; a
  Clip and then an append a session copied the whole list over and over.
- listSessions makes its page and its latest map at their size.

Run on mote at this head (rebased on 484bdca7c, run again after):
- go test ./internal/gui/ ./internal/sessions/: sessions ok; gui ok but
  TestMainWindowCorners/macOS_26_SDK, red on mote's macOS 27 the same
  without this change (#3949).
- GOOS=linux/windows/darwin go vet -tags nogui on both packages, gofmt.
- Broken by hand: the read behind always taking a new gen makes
  TestStatsTagKeptWhileTheSame red ("gen 2, want 1 kept").
- Real full history on mote, magpie web polled with the page's
  X-Magpie-Had, 10 endpoints every 5s, cur = cdf8151a2:
  alloc in 60s 1755 MB -> 1342 MB; bytes.growSlice 393 -> 105 MB;
  CPU in 60s 4.25s -> 3.60s, GC mark 1.28s -> 0.88s.
Not tried: the Windows and Linux apps; the encoding is the same code.
2026-10-30 08:32:57 +08:00
yetone c7ae24f0a6 gui: the warm-up's usage read sets no memory limit, a cold start stops collecting nonstop (#2278)
The warm-up's QueryPage(All) and Codex effort ran under tightenGC(true):
GOGC 25 and a soft memory limit at what Go held when the read began. On
a cold start the heap reached that limit all live, and gctrace showed a
collection every ~160 ms from ~11 s to ~24 s, heap = live = limit, about
one core the whole time.

Now the read takes GOGC 25 only, as a page's request already did, and
tightenGC lost its limit parameter and heldMemory.

Measured on mote (M5 Pro), cold start with no caches, 390k calls in
usage.jsonl plus a growing Codex rollout, 10 endpoints polled every 5 s,
60 s each (coldx.sh: footprint each second, gctrace, ps cpu time):
- before (v0.1.2111 head): CPU 3:39.33, 1166 GCs, phys_footprint_peak 855 MB
- after: CPU 2:05.86 / 2:04.60 / 2:02.78, 618 GCs, peak 860 / 835 / 863 MB
The cold start reads no request index, so it builds one from every
session, the case the limit was added for; its peak is unchanged.

Tests at this head, through mote-run:
- go vet -tags nogui ./... for GOOS linux, windows and darwin: ok
- go test -timeout 45m ./internal/gui/ ./internal/usage/ ./internal/sessions/:
  usage, sessions ok; gui only TestMainWindowCorners/macOS_26_SDK, #3949.
TestUnderTightGCLimitsMemory became TestUnderTightGCSetsNoMemoryLimit;
the old code set a limit below MaxInt64, so it would be red there (not
run on the old code: tightenGC's signature changed).
2026-10-30 06:34:53 +08:00
yetone 45fce0495d sessions: a poll's session list is sorted and gathered in slices made for it (#2278)
listSessions kept each group's latest time in a map and sorted a key
slice that looked it up; the /api/sessions handler grew its native-key
map and its output slice by appending. Under 80s of polls while a
session was written (ab17, v0.1.1978 with stats kept) those were 72 MB
(latest map), 129 MB (listSessions out) and 139 MB (gui out.Sessions)
of 5.4 GB allocated. The groups are now one slice of key and latest,
sorted once, and every output is made at its size.

Run at this head (mote, Go 1.26.8):
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
  ./internal/gui/ ./internal/usage/: clean.
- go test -timeout 45m ./internal/sessions/ ./internal/gui/: sessions
  ok; gui red only on TestCoreScriptBudget (#4133, red on main since
  a4e929212) and TestMainWindowCorners/macOS_26_SDK (#3949, red on
  macOS 27), neither touched here.

Rebased onto origin/main f982e46f2 after the run above; the three #2278
commits were run again together there (see the last commit's body).
2026-10-30 05:57:11 +08:00
yetone af8f3a9399 sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.

- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
  from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
  the aggregators (allFiles, callFilesWith, callSourcesWith,
  traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
  readers of an already-listed session (TranscriptOf, ContentOf,
  SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
  ErrNotRead, so a cache from before a switch was turned off goes no
  further. The Sessions list, stats, /api/sessions/overview, the call and
  trace indexes, Usage's agent-file calls and the Codex/Pi title readers
  all pass it.
- SettleReads decides once and saves: an install with sessions.json or
  a calls-v* cache read sessions before and keeps all on; a fresh one
  reads none, not asked. A saved value is never replaced; save, sync and
  restore keep it (KeepOwn); only SetSessionReads writes it. An
  unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
  shows a consent card: each agent found (by a stat of its folder only)
  with a switch, Allow selected and Allow all. Settings > Privacy >
  Agents' session history has "Agents found later" and a row per agent.
  Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
  says on stderr when nothing is allowed yet; the TUI's empty Sessions
  page says how.

Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).

Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).

Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
  GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
  change on 8c63c5b78: 79 packages ok; internal/gui red on
  TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
  by SetSessionReads only, the test now sets it so; green after) and
  TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
  8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
  (comments named "Allow all"/"Allow selected"; lowercased) and
  account-discovery (read the last Privacy heading; now the one above
  its list); both green after. The 44 files again on origin/main
  c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
  #4120, #4125). stays-strict green alone; gateway-key-models webkit red
  1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
  internal/sessions, settings, cli, tui ok; internal/gui
  TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
  account-discovery, sessions-reads: 62 pass, 0 fail.

Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
  gates hold); both off: TestFreshInstall red on List, Agents, Calls,
  CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
  all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.

Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.

Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
2026-10-29 23:56:05 +08:00
yetone 9474eaf9cb sessions: Raft's Pi agents' sessions are listed as Raft's, with their prompts, calls and delete
Raft (slock's raft-computer) runs its agents on Pi and keeps each one's
Pi SDK session files in that agent's folder: <slock>/agents/<id>/
.pi-sessions/<ts>_<id>.jsonl, or .builtin-sessions/ for its built-in
runtime. <slock> is $SLOCK_HOME or ~/.slock (%USERPROFILE%\.slock on
Windows, the distro's ~/.slock under WSL). Read from raft-computer
1.0.14's PiDriver (buildPiSessionDir), BuiltInDriver and
resolveSlockHome, and a read-only listing of ~/.slock here.
runtime-sessions/ holds handoff notes, no sessions, and is not read.

- The Sessions page lists them as Raft's (agent "raft", in agent.Clients'
  others), titled and opened with their prompts as Pi's are.
- Their calls count on the Usage page as Raft's; calls through magpie
  stay the gateway's, as Pi's do.
- Raft's Pi uses the user's own ~/.pi/agent, so a request it sends
  through magpie reaches the gateway as Pi's under the same session id.
  sessions.GatewayKeys gives a Raft session both "raft|ID" and "pi|ID",
  so the gateway's copy is not listed twice nor counted twice (Merge,
  stats, NativeIDs, the GUI's Via).
- Delete and restore work as Pi's: the one file goes to the trash, and a
  folder beside it is left (the agent's workspace is not the session's).
  A session written in the last minutes is refused as active.
- No resume command, no carry and no trace export: Raft starts its own
  agents, and nothing outside it can resume one.
- SLOCK_HOME is passed through agentenv like the other agents' homes.

Run (at 958ad9f10 on e61e10535):
- mote (macOS): -run 'Raft|TestPi|TestDirs|TestVars|TestFolderVars' in
  sessions and agentenv: ok, and red for each break below. A full
  go test ./... was started there; at load ~300 from other sessions'
  suites it printed only magpie and internal/access (ok) before mote
  stopped answering (host down), so no full macOS record exists.
- mote (macOS), rebased on 5d24bc6cc: go test -count=1 ./internal/sessions/
  ./internal/agentenv/: ok (sessions 495s, agentenv 1.1s). agent and gui
  were not run in full on macOS.
- mote: GOOS=windows go vet of sessions, agent, agentenv, gui; GOOS=linux
  go vet of sessions, agent, agentenv: ok.
- Windows (win-run): agentenv ok; -run 'Raft|TestPi|TestDirs' in
  sessions ok. The full sessions package hit its 30m timeout after
  TestOneListing's red (#4114) and the Agy reds (#4115, #4177). agent
  and gui reds (Hermes, WorkBuddy, Lody, Qoder/Copilot plugin folders,
  Codex keychain, ClaudeDesktop language, Aside, InstallWithoutNode,
  DesktopExec, AionUi, ImportStatus, UpdateThatWontStart,
  GatewayHeldByAContainer, GatewaySessionHistoryAndCalendar): each run
  again at origin/main c1660481c on Windows and red there too, except
  TestHermesProfilesFollowMagpieModel which passed there alone; it is
  #1388's Hermes model rewrite, which this change does not reach.
- Linux (wsl-run): sessions ok, agentenv ok. agent's TestInstalledVersion,
  TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI and
  TestOmpDetectedWithPiDir are red at origin/main c1660481c too (#4033,
  #3548). gui does not build there (no gtk4/webkitgtk-6.0 in the distro).

Broken by hand, each red, then restored: Raft's listing removed; the
"pi|ID" key dropped from GatewayKeys; the folder-beside check reverted to
Pi's absence; $SLOCK_HOME ignored; Raft's calls left out of piCallFiles;
NativeIDs without Raft; stats' native keys without "pi|ID".

Not tried: with real Raft. No agent on this machine has run on Pi, so
the fixtures are Pi 1.1.0's own files (testdata/pi-calls, testdata/pi)
placed in Raft's folders. The GUI was not run in a browser: no JS
changed, Raft's name and icon come from agent.Clients. Raft's icon is the
generic one.
2026-10-29 15:29:30 +08:00
yetone fa2dfc1458 sessions: the page's 7, 30 and all-time stats are read again in one pass (#2278)
statsFor keeps each ?days range the Usage page asks for and reads it
again behind the page once it is 10s old. Each of the three ranges
(7, 30, 0) was its own combinedSessionStats: a listing of every Claude
Code and Codex file, a refresh, the Codex identities and task titles,
every session assembled for the native keys, and the ccCopies, all
identical whatever the range. With 25k Codex rollouts that was ~4.2s of
CPU a minute on a polled page.

Now a stale range takes every other stale range with it, and
statsReadAll does the shared part once and sums each range from it
(statsOfRange). The sessions assembled for the native keys are reused
for each range's list instead of assembling them again.

Rebased onto b4267de59; the tests and vets below ran again on mote at
the rebased head, same results. The A/B ran before the rebase:
- TestStatsAllRangesOnePass (new): ranges 0, 1, 7, 30 from one pass
  are each DeepEqual to statsRead of that range alone, and the files
  are listed once.
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions
  ./internal/gui: clean.
- go test ./internal/sessions ./internal/usage: ok. ./internal/gui: ok
  but for TestMainWindowCorners/macOS_26_SDK, the macOS 27 red in #3949
  (titlebar, untouched here).
- A/B on mote, sandbox HOME with a copy of the real 115MB usage.jsonl
  (240k rows) and 25k Codex rollouts, the page's 10 reads every 5s and
  4 appends a second, 240s each, v0.1.1959 (d7e9c3745) then this:
    stats refresh (statsFor.func1) CPU  4.17s -> 2.22s a minute
    process CPU in the 60s profile      33.8s -> 30.7s
    stats?days=0/30/7 mean              0.76/0.77/0.78s -> 0.39/0.36/0.39s
    /api/sessions/overview mean         1.29s -> 0.72s
    /api/sessions mean                  2.01s -> 1.37s
    every read's mean                   0.99s -> 0.62s
    peak RSS                            985 -> 1033 MiB (mote at load
                                        ~35 from other sessions; peak is
                                        next)
2026-10-29 05:29:36 +08:00
yetone fcbbb8e479 gui: the start's warm-up and read-ahead look at each file once a second (#1665)
The warm-up after a start (sessions, usage, Codex effort) and the usage
read-ahead asked for settings.json, logins.json and the rest for each
session and row they read: a Windows sandbox's second start stat'ed
settings.json 677 times in 25s, 286 of them settings.load and
AccountDiscoveryOff under the warm-up. Both now hold what was read
(filememo.Hold), as the GUI's requests and a catalog sync's round do. A
write still reads the disk (edit.Read, settings' writes, logins.json
under loginsMu), so nothing is written from a held read; a file another
app changes is seen up to a second late while they run.

Measured on xiaomi-gpu (Windows 11), an empty sandbox HOME, magpie web
--gateway, second start, 27s, with a build counting each look at the
disk (instrumentation not committed):
  before   1113 looks, settings.json 677
  after     483 looks, settings.json 114
The catalog sync's round stays at ~100ms.

Run:
- TestWarmUpHoldsWhatItReads: red with the warm-up's Hold taken out by
  hand (the second read saw the other app's change), green with it.
- mote: gofmt -l internal/gui clean; GOOS=windows and darwin go vet
  ./internal/gui and GOOS=linux go vet -tags nogui ./internal/gui clean;
  go test -count=1 ./internal/gui ./internal/usage: usage ok, gui red
  only on TestMainWindowCorners (#3949, mote's macOS 27, red on main
  before this).
2026-10-28 13:51:37 +08:00
yetone f4762e9217 sessions: a Claude conversation Claude Code copied into another file is one row
Neo (Discord #feedback): one Claude conversation was listed as ~11 rows
with the same title, message count and size, each under its own id.

Claude Code 2.1.312 copies a conversation into a new <id>.jsonl when it
forks one (--resume --fork-session, /branch) or moves it to a background
session: every message again, under the same uuids, with the new
sessionId. magpie keyed each file as a session, so each copy was a row,
and the copies' tokens were counted again in usage.

Each main Claude-format file (Claude Code, Qoder, Qoder CN) now records
the uuids of its first and last message (state Root/Leaf, cacheVersion
23, so every file is read once more and old copies fold in too). Of the
files of one agent that start with the same message, one whose last
message another holds is a copy (cc_copies.go). Only a random (v4) uuid counts, as Claude Code
writes them: files whose writer reuses ids like "u" stay apart. A copy
is not listed
(List, ListAgent, Agents), not counted in stats, and Delete trashes it
with the session that holds it (Restore brings it back). A fork that
went on with a turn of its own has a last message no other file holds
and stays its own row, as Claude Code's /resume shows it. The gateway's
session rows and the GUI's native keys know the copies' ids, so a
gateway-only row doesn't stand in for one.

Fixtures: testdata/claude-forks is Claude Code 2.1.312's own files from
a sandbox HOME with a fake API (a session, a --fork-session of it with a
third prompt, another fork with a different one), trimmed of request
records and attachment text. Pure copies are that session with its
sessionId rewritten, as /branch leaves one.

Run (mote) at 2b7ce2967 on d8c70504d: go test -tags nogui -timeout 45m
./... all 76 packages ok; gofmt -l
clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions
./internal/gui ok; go build ./... ok.
Broken by hand, each red: ccCopies returning nil (all four row tests),
stats counting copies (110 in / 55 out, want 30 / 15), Delete not taking
copies (a copy came back as the row), MergeExternal ignoring Copies (a
gateway row came back). Without the v4 check, five tests whose
fixtures share "uuid":"u" went red (cli, gui x2, sessions, tui).
GUI: no file reaches it; the GUI tests fake the API and the JSON a page
gets is unchanged (Copies is json:"-").
Not tried: Neo's own files, and the opened view showing only "session
start" and one line in the second screenshot; that was not reproduced.
The calls ledger (FindCall) still holds a copy's calls.
2026-10-28 10:40:28 +08:00
yetone e056779a67 gui: the app serves its page to a browser, behind its key (Settings › Browser access)
jiakun_zhao on X ran `magpie web` in a terminal beside the desktop app,
to manage it through a Cloudflare tunnel. Settings › Network and sharing ›
Browser access now has the app serve the same page itself: Off, This
computer (127.0.0.1, for a tunnel or SSH forward) or Local network.

Access is magpie web's, unchanged: the key in the link is traded for the
cookie (webGuard), the allow list holds, and the gateway's client routes
on the page's port need a gateway key (onePort). A rebound Host and
Origin: null get no cookie. There is no way to serve it without the key.
The key and choice live in web-page.json (0600) beside settings.json, so
a sync never carries them. GET/POST /api/web-page are the app windows'
alone: a browser on the page can't read the key or turn the page off. A
busy port (magpie web, the magpie before an update) is tried every 4s;
`magpie web` on the same port opens the app's link instead.

Run at d43b7c40d (this change on ef155a5ca), then rebased onto the four
newer main commits, which touch gateway, usage, proc and library only:
- gofmt -l internal/gui internal/cli: nothing. go vet, GOOS=linux go vet
  -tags nogui and GOOS=windows go vet of internal/gui and internal/cli:
  clean. go build: ok.
- go test -timeout 45m ./internal/gui/ ./internal/cli/: ok (180s, 70s).
- GUI, alone: browser-access.test.cjs and model-test-one.test.cjs pass in
  both engines; i18n-keys 23 of 24, its red is #3897 ("Runs as" from
  7f827b3b0), not this change. agent-stale-copies.test.cjs 80 of 80 at
  8d343a811 (this change before the rebase).
- Full GUI suite at 8d343a811: cut short. The disk filled (708MB free):
  browsers failed to launch with ENOSPC in agent-stale-copies, which then
  passed 80 of 80 alone, and node ended with exit 7 before the rest of
  the files ran. There is no full GUI record for this change.

Not tried: a real Cloudflare tunnel to the page, and Local network from
another machine.
2026-10-27 18:58:16 +08:00
yetone 353519f557 gui: a Sessions or Usage poll's reads are collected under GOGC 25, and two reads under it at once put back what was set before
An open Sessions or Usage window polls every 15 s, and a poll's reads
allocate ~330 MB to keep ~105 MB. At GOGC 100 the heap grew to twice
what it kept before a collection, so Activity Monitor showed ~280-360 MB
during each poll. Each /api/sessions* and /api/usage* GET now runs under
GOGC 25, the warm-up's usage read's setting, without the memory limit
that read also takes: held at heldMemory, every poll collected over and
over and the window spent 5x the CPU.

underTightGC put back what it found, so two reads at once ended with the
second's 25 for good when the first ended first. A count now holds it:
the first read sets GOGC (and the limit, for the warm-up), the last puts
back what was there before the first.

Measured in a sandbox HOME over the real session and usage data (6 GUI
polls 15 s apart after a warm start, footprint right after each poll /
10 s later; CPU over the 6 polls):
- origin/main: 326 326 326 290 364 281 MB / 188-217 MB; 5.2 s
- GOGC 25 + memory limit: 190 176 172 161 216 186 / 149-172; 20.7 s
- this (GOGC 25 only): 278 217 220 197 248 214 / 186-209; 5.6 s
/api/sessions 495 ms vs 653 ms on main, the other routes the same.

TestTightGCOverlappingReads ends two overlapping reads in either order;
with the count taken out (each read putting back what it found) it is red,
"one read still in flight under GOGC=100, want 25".

Run at this head (ea7c0067e + this): gofmt -l clean; GOOS=linux, windows,
darwin go vet -tags nogui ./internal/gui/ clean; go test -timeout 45m
./internal/gui/ ok (203.3s; a run before it had three
reds that were all "no space left on device", the disk filled by
another build of mine). Then rebased onto 6eb510f78, whose only
internal/gui change is web.go's home-screen manifest: gofmt and the
three vets clean again, and -run 'TightGC|Warm|Held|PageRead|Sessions'
./internal/gui/ ok.
Not tried: the Linux and Windows apps' own footprint.
2026-10-27 14:31:17 +08:00
yetone d5f86d9919 sessions: a Sessions poll's three reads share one listing of the files
The Sessions tab asks /api/sessions, /api/sessions/stats and
/api/sessions/overview at once, and statsFor refreshes its memo in a
goroutine beside them. Each listed every session file again. The stats
and overview routes and the refresh now take sessions.ShareListing: a
hold that, unlike OneListing, doesn't start a new "since" when one is
already held, so a listing a read in flight is making is waited for
and shared (heldFiles keeps a ready channel per listing) instead of
made again. The refresh is also counted as a page read (readingPage),
so its memory goes back once it rests.

Run at this head: go test ./internal/sessions ./internal/gui ok,
TestShareListing -race -count=5 ok. TestShareListing was red with the
wait taken out of heldFiles by hand (the second read listed again).
A/B on real session files, 8 polls of the parallel trio then
/api/state, v0.1.1661 vs this: total allocated 1.96 -> 1.82 GB, trio
mean 572 -> 438 ms, first trio 2071 -> 1456 ms, allFiles 353 -> 322 MB.
Footprint between polls stayed ~160 MB; statsRead (~520 MB) and
listSessions (~345 MB) are the rest and are not changed here.
Rebased on 65ee8c65c and run again: dirent and sessions ok; gui had
one red, TestRestartHandsTheGatewayOver, with an A/B run of magpie
beside it; it is #3451 (EOF during the handover under load). It passed
3 of 3 alone and the whole gui package passed on a rerun.
Rebased again on cc9d68ffd (agent and update only) and run at the
pushed head: dirent, sessions and gui ok.
2026-10-27 09:28:34 +08:00
yetone 51a2068b52 sessions: a Sessions poll lists the session folders once, not twice
Each /api/sessions read listed every Claude Code and Codex session file
for its list (allFiles), then again for the Codex threads' effort
(usage.CodexModelEffort -> readRequestState -> CallSourcesAndCodexIdentities):
~21k files on this machine, twice every 15 s poll.

sessions.OneListing holds the folders' listings (ccFiles per folder,
codexFiles) while a request is answered; GET /api/sessions and
/api/sessions/manage take one. A listing is shared only if it was taken
after the latest hold began, so no request reads files from before it
came, and the listings go when no hold is left. Folders are listed
outside the lock. The warm-up's own memo (warmListing) is unchanged.

Measured on the real history (rss-home, symlinked ~/.claude/projects;
prof.sh, 20 s CPU profile, /api/sessions back to back), against
fe903798f:
- poll 170 ms -> 118 ms
- readRequestState 3.89 s -> 1.58 s of samples; listedRollouts 4.95 s ->
  3.50 s, now only under List

TestOneListing: one listing under a hold; a hold begun after a listing
lists again; every read lists once no hold is left. Red with the
"taken since the latest hold" check removed by hand.

Run at df1ba9586 (on fe903798f):
- gofmt clean; GOOS=linux and GOOS=windows go vet -tags nogui ok for
  sessions and gui
- go test -tags nogui -count=1 -timeout 45m: sessions 12.6s, usage 15.0s,
  gui 52.3s, dirent 4.7s, all ok
- not run here: the GUI suite (no page script changed) and the importer
  packages (run at fe903798f, all ok)
2026-10-27 06:40:30 +08:00
yetone 8bc72bf10a gui: the Sessions tab's 15 s reads send only what changed, not the ~8 MB list
Every 15 s the Sessions tab read /api/sessions (7.9 MB over a long
history, 5000 rows) and /api/sessions/stats (0.7 to 5.7 MB), parsed both
and ran JSON.stringify over the old and new answers to find them the
same. While an agent works one row changes, so it was all of it, every
poll, in the WebView.

- writeJSONSame (api.go) tags an answer with a hash of its bytes. An ask
  whose X-Magpie-Had is that tag gets X-Magpie-Same and no body, and the
  page keeps the object it has. Used for the stats.
- writeJSONRows does the same for the list, and keeps each row's hash
  for the last 4 lists it sent. Asked with the tag of one of those, it
  sends X-Magpie-Delta: sessions and a list of only the new rows, each
  run of old rows written [from, count].
- api() in app.js sends the tag it has, rebuilds a delta on the rows it
  holds (the same objects), and remembers each answer's tag. The tab
  compares answers by tag, so it no longer stringifies 8 MB twice.
- Not an ETag and a 304: on Windows Wails strips If-None-Match from
  WebView2's requests and turns a 304 into a 505.

Run at this head (macOS, go1.27, parent eee571999 = origin/main):
- TestSessionsSentOnceWhileTheSame: an unchanged answer is sent with no
  body, another tag gets it whole, and after a new session the list is
  the new row plus [0,1], which rebuilt on the old list equals the whole
  answer. Red with the Had check or the delta turned off by hand.
- tests/sessions-same.test.cjs (chromium and webkit, en and zh): no body
  sent again while unchanged, and the very objects kept. One new session
  sends a delta, and the old row is the object the tab had. The new
  title is drawn. Red in chromium with the client's rebuild removed.
- go test -tags nogui -timeout 45m ./internal/gui/ ./internal/sessions/
  ./internal/usage/: ok. gofmt -l clean; GOOS=linux and GOOS=windows
  go vet -tags nogui ./internal/gui/ ./internal/sessions/: ok.
- GUI: the 72 files that read /api/sessions or its stats, and
  i18n-keys, both engines: 1081 tests, 1053 pass, 28 fail. The fails are
  usage-agents-hide (#3414) and usage-ledger's "newest live route needs
  no return-to-live button" (#3104). Each file fails the same alone
  with eee571999's app.js and page.js (5/11 and 14/3 in chromium).
- A built binary on the real history (~15.9k sessions, a Claude Code
  session being written), six reads 15 s apart sending the last tag:
  20,753 B once (only this session's row), then 0 B with Same five
  times; the list was 7,928,438 B whole. Each rebuilt list equalled a
  whole read taken just after it. Stats asked again: 0 B, against
  5,688,332 B whole.

Not run: the whole GUI suite (~12.5k tests, ~5 h at this load). It was
stopped at 1,218 tests with only account-discovery red, which is #3497
and is red the same with this change's app.js and page.js put back.
Not tried: the Windows app (WebView2) and the Linux app.
2026-10-27 06:18:24 +08:00
yetone 99de8e1ad1 gui: the warm-up's whole-history reads hold Go to the memory it held when they began (#3493)
A cold build of the request index (after any update that changes
internal/usage) reads every session again and allocates ~1.2 GB to keep
~40 MB more. Even under GOGC 25 the heap overshot its goal into pages it
kept, so a cold start peaked ~70 MB over a warm one. underTightGC now also
sets a soft memory limit at what Go holds of the system's memory when its
read begins (total mapped less released), and puts the old limit back
after. A lower limit the user set is kept, and GOGC off gets none.

Real data, 15.7k sessions (sbpairs: copies of the real cache/config, the
real Claude Code and Codex session folders linked read-only), harness
TestZZWarm running warmSteps under sessions.Warm, phys_footprint_peak,
old = 9dc7d6eb8, alternated:
  cold (requests-v1.bin removed): old 313/308/320/323 MB, new 251/241/247/249
  warm: old 247/255/250, new 211/225/228
  at rest after: unchanged (old 186-200, new 174-190)
  user CPU, cold run: old 4.8-5.9 s, new 6.0-12.8 s (load 120-200 on the
  box, wall time the same: 2.8-4.9 s vs 3.0-5.9 s)
Fixed 220/200 MB limits were tried first: 200 doubled CPU; a limit relative
to what is held scales to other histories.

Run: go test -count=1 ./internal/gui ok (132s); the first full run had one
red, TestRestartHandsTheGatewayOver (handover, #3451, commented), green 3 of
3 alone. GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gui ok,
gofmt clean.
Broken by hand, TestUnderTightGCLimitsMemory red each time: no limit set;
a limit under GOGC off; the user's lower limit replaced.
Not tried: Windows with real sessions (the box has none); a history much
larger than 15.7k sessions.
2026-10-25 17:14:38 +08:00
yetone 15f0d4cdeb sessions: a Claude Code session goes on in Codex, and a Codex one in Claude Code
0xPlato on X asked for conversations to carry across agents, at least on
one machine. A session row's Continue in (换 Agent 继续) now offers Codex
for a Claude Code session and Claude Code for a Codex one, when the other
is installed. Picking it converts the session then: a new session in the
target's own store, which its own resume opens. Listing converts nothing.

- Claude Code to Codex: a rollout in CODEX_HOME/sessions/YYYY/MM/DD with
  session_meta (model_provider from config.toml now, no
  base_instructions, so Codex uses its own), response_items and the
  event_msg user/agent messages the TUI shows. Codex indexes it on
  resume itself.
- Codex to Claude Code: CLAUDE_CONFIG_DIR/projects/<cwd>/<uuid>.jsonl,
  lines chained by parentUuid, assistant model "<synthetic>" so usage
  counts no call for them.
- Carried: user and agent text, pasted images, shell calls natively
  (Bash and exec_command) with their output, other tools as the agent's
  text (name, input, result in fences, cut at 64 KiB). Dropped: thinking,
  reasoning, signatures, encrypted content, Claude Code's own and Codex's
  context messages. After a compaction only what replaced the history.
- The source is only read. The new file goes through temp, sync, rename
  and never over an existing path. Asking again for an unchanged file
  gives the same session (memo by path, target, size, mtime).
- POST /api/sessions/carry {agent, id, to, open}: copies the resume line,
  or with open (Mac app) opens it in the session terminal. The details
  pane's Continue in line converts from its copy button too.
- Read-only and WSL sessions get no offer. Pi, omp, OpenCode, Kimi,
  Cursor and the rest are not converted.

Run (worktree at 42976f9a0, rebased onto origin/main before push):
- Real use in a sandbox HOME (HOME, CLAUDE_CONFIG_DIR, CODEX_HOME under
  magpie-wt/carry-sb), real binaries Claude Code 2.1.310 and Codex
  0.162.1, through magpie's gateway:
  - Claude to Codex: a Claude session that ran Bash, Write, Read and Edit
    was converted. `codex exec resume <id>` answered what the dog was
    called, which command ran and what was added. `codex resume` showed
    the whole history in the TUI.
  - Codex to Claude: a Codex session with exec_command and apply_patch was
    converted. `claude -p --resume <id>` answered the colour, the commands
    and the function added. `claude --resume` showed the history in the
    TUI.
- Fixtures in internal/sessions/testdata/carry are those real sandbox
  files. Claude's attachment text (system prompt, instruction files) and
  api-request lines were taken out; the line chain is kept.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
  sessions ok (15.7s), gui ok (119s), size budgets among them.
- Broken by hand, each red: Codex context kept (environment_context
  carried), no convert offer (all four TestCarry* red), images dropped
  (TestCarryImagesAndCompaction red). sessions-convert.test.cjs is red
  in chromium on the old client.js.
- GUI (playwright 1.62.0, chromium and webkit): sessions-convert in en,
  zh, zh-TW, ja and de, every sessions-*.test.cjs, i18n-keys,
  click-scroll, gateway-conversations: 424 of 424 pass.
- gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build.

Not tried: Windows and WSL with real binaries (WSL sessions get no
offer), images through the real binaries (round trip in tests only),
Open in session terminal on a real Terminal (the POST is tested, the
terminal path is the existing openTerminal), a Codex session compacted
by OpenAI (encrypted, not carried), and the full ./... suite.
2026-10-25 12:25:06 +08:00
yetone b1a2eec2c1 gui: the warm-up reads Codex's effort under the tight GC too
The warm-up's last step reads Codex's per-thread effort from the whole
ledger right after the usage page's read, while that page still holds
every row (~300 MB live on the owner's history). It ran at GOGC 100, so
the heap was let grow to about twice that: a heap profile every 2 s of a
cold start showed heapSys going 342 -> 622 MB while live stayed ~300,
in the seconds after QueryPage returned. It now runs under underTightGC
like the usage read.

Footprint (phys_footprint, what Activity Monitor shows), cold start on a
clone of the real history (15,176 files), alternating, two runs each:
  4042aa4d1  peak 611 / 575 MB  end RSS 659 / 651 MB  CPU 4:20.6 / 3:54.9
  this       peak 521 / 498 MB  end RSS 595 / 568 MB  CPU 4:11.7 / 4:00.7

Tests: TestWarmUpReadsCodexEffort now also checks the read runs at
GOGC 25; with the step put back to warmCodexEffort() by hand it is red.
go test ./... -timeout 45m on 083b1c8e7: 68 packages ok; rebased onto
b3f595349 (routing CSS/JS only), go test ./internal/gui ok again.
GOOS=linux and GOOS=windows go vet -tags nogui ./... clean; gofmt clean.
2026-10-22 00:04:28 +08:00
yetone 1414705159 gui: the warm-up's read of the whole usage history runs under GOGC 25, so a cold start peaks ~130 MB lower
The warm-up's last big read, the Usage page's QueryPage over all time,
holds every row of the history unpacked at once (129 MB of rows, 271 MB
live at that moment for this history), and at Go's default GOGC the heap
grows to twice what is live before collecting: Activity Monitor's
footprint peaked at 555-587 MB there, on a magpie that rests at ~200 MB
once it is done. underTightGC lets the heap grow by a quarter during that
read and puts back what was set; a GOGC the user set lower, or off, is
kept. Holding fewer rows at once needs the page built in passes over
packed chunks (rowRef points into unpacked ones), which is the next step.

The whole warm-up under GOGC 25 gave the same peak for ~11 s more CPU, so
only that read is.

Measured with startheap-runs/fp.sh: cold start (calls and sessions caches
deleted) of a 6,437-file history, phys_footprint sampled every 2 s and
footprint's own phys_footprint_peak at the end, run until the caches stop
growing for 30 s; every run wrote the same 6,437 files / 70,069,451 bytes.
Machine at load ~85-140 from other sessions.

  before (e68a0b1db)        peak 555, 587 MB   cpu 2:01 (one run)
  whole warm-up at 25       peak 438, 410 MB   cpu 2:12, 2:14
  this commit               peak 421, 456 MB   cpu 2:05, 2:01
  at rest after, all        183-215 MB

(ps RSS reads 500-720 MB at rest in every build: macOS counts the pages Go
already gave back with MADV_FREE until it takes them; heapReleased was
438-678 MB of that.)

Run:
- TestUnderTightGC (new): the read runs under 25 from GOGC 100 and 200,
  under 10 from 10, and with GC off from off; each is put back after.
  TestWarmUpTightensOnlyTheUsageRead: other warm-up steps run at 100.
- go test -run 'TestWarmUp|TestUnderTightGC' ./internal/gui ok.
- gofmt -l clean.
- go test -tags nogui -count=1 ./internal/gui (the whole package) ok
  77.2s; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gui
  ok. No other test sets or reads GOGC (grep SetGCPercent/FreeOSMemory
  in *_test.go). The full suite's last run (e58108c3b, the commit before)
  had every package ok but internal/agent at the 45m deadline under load
  ~120; alone it passed in 2213s (noted on #2544).
2026-10-21 19:12:19 +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 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 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 81029fc63c sessions: the overview's stats and their native sessions come of one pass over the files (#2776)
combinedSessionStats, behind /api/sessions/stats and /overview (each
range read again in the background when its memo is over 10 s old, so
on every 15 s poll of the Sessions page), took sessions.StatsFor and then
sessions.List(All) only for the agent|id set that keeps a gateway session
the agent keeps too from counting twice: two passes over every agent's
files, each refreshing them all. sessions.StatsAndNative gives both from
StatsFor's one pass: the same set, a session List would list (one
nothing was said in still left out, as before), but with no 5000 limit,
so a gateway session whose native one is among the oldest of a long
history is no longer counted again.

Test: TestStatsAndNativeOnePass: one pass over the files (filesHook, new),
and the same keys as List(All) on the fixtures. Red with StatsAndNative
written as the old pair of calls: "2 passes over the files".

Measured on the synthetic sandbox HOME (3000 Claude Code, 1500 Codex,
2000 Hermes sessions), combinedSessionStats warm after a restart, CPU
time (load average ~250, wall times noisy), parent 8e2b1dce6 against
this change, 4 rounds each:
  days=30  94-99 ms -> 57-62 ms CPU
  days=0  107-130 ms -> 68-74 ms CPU
  first after a restart (days=30)  558 -> 510 ms CPU

Run at this commit (the series' last; it covers 0179cef63, bbee24810
and 8e2b1dce6 too), on a machine at load average ~250-500:
- go test ./... -timeout 45m: 60 packages ok, sessions (869.8s), usage
  ok. Red only under that load, all green when run again:
  - internal/agent and internal/gateway timed out at 45m in tests that
    don't touch sessions (TestPiOffersItsOwnOpenAICodexModels,
    TestVisionSettingPicksTheDescriber). Run again with -timeout 90m:
    agent ok (1394.2s), gateway ok (1546.9s).
  - internal/gui TestSetAnswersWhileDevinAndProvidersHang: set took
    44.6s under load; it is #1375. Alone: ok.
  - internal/plugin TestGatewayHookMixedPiPackage: "starting plugins:
    context deadline exceeded" after 718s (bun's install cache was slow).
    Alone: ok (163.6s). No issue found for it.
- gofmt -l: clean.
- GOOS=windows go vet ./...: ok.
- GOOS=linux go vet -tags nogui ./...: ok. Without the tag, vet stops in
  wails v3's own linux files (undefined: pointer, cgo off when vetting
  across OSes from macOS); go.mod is untouched here.
- No GUI assets changed, so the GUI suite was not run.
2026-10-19 03:57:52 +08:00
yetone 486ea82378 agents: cursor-agent's row is Cursor CLI (@G_Z_Y on X)
@G_Z_Y looked for Cursor CLI on the Agents page and took the "Cursor" row
for the editor. The row is cursor-agent, so it is named Cursor CLI. What
it keeps in ~/.cursor is the Cursor editor's too (MCP servers, skills,
chats), so the Library and Sessions name it Cursor there (SharedName).

Run at this head before the rebase onto 0f391a7a7: go test -tags nogui -count=1 -timeout 45m ./... under a sandbox HOME, every package ok; gofmt -l clean; go vet clean for darwin, linux (nogui) and windows; GUI files agent*, i18n*, gui-*, getting-started, library*, sess* and import-row in both engines: 1638/1638.
2026-10-16 05:10:43 +08:00
yetone c516841e46 sessions: a Claude Code, Qoder, OpenCode or Kimi Code session lists its subagents, and the transcript route reads one by sub= (#2261, infinitr0us)
What changes:

- A session's subagents are now on the session, as Session.Subagents (subagentsOf in the new internal/sessions/subagents.go). Each one has its id, title, kind, parent subagent, start and last.
  - Claude Code and Qoder: subagents/agent-<id>.jsonl. The type, description and parentAgentId come from agent-<id>.meta.json, through ccMeta, which SubagentParent also uses now. With no meta file, the title is the first user line. A compaction's own run (agent-acompact-*) is left out.
  - OpenCode: child sessions found through ocRoots, which now records each file's parent. The title is split from "<description> (@<agent> subagent)"; "Child session - <time>" counts as no title.
  - Kimi Code: agents/agent-<n>/wire.jsonl. The title is the first turn.prompt. Kimi 1.5's subagent.spawned record adds the description, type and parent agent.
- GET /api/sessions/transcript takes sub=. It is resolved only among the subagents the session lists (SubagentTranscript; ErrNoSubagent otherwise), never as a path. A subagent's file path is not sent (Path is json:"-").
- Codex is unchanged: its subagents are sessions of their own, with parent_session.

Fixtures:

- Claude Code: the meta and line shapes are copied from real files under ~/.claude/projects, with their words and ids replaced.
- OpenCode: titles of both the 1.x and 2.x forms.
- Kimi 1.4: the existing redacted reporter fixture.
- Kimi 1.5: the record is built from Kimi Code's schema (agent-core-v2 SubagentSpawned), not from a real file.

What was run:

- go test ./internal/sessions ./internal/gui. TestClaudeSubagents, TestQoderSubagents, TestOpenCodeSubagents (JSON and db), TestKimiSubagents and TestSessionSubagentTranscript are new.
- Broken by hand: with the subagentsOf call removed from assemble, 4 sessions tests and the gui test fail. Restored afterwards.
- gofmt -l is clean. go vet passes for darwin, linux (-tags nogui) and windows.
- The full suite (go test -p 4 ./...) under a temp HOME, at 5618ade1e with both commits: green (exit 0).
- Real use: a sandbox magpie (temp HOME, ports 3486/3487) against read-only copies of real Claude Code sessions, including a real nested pair (a subagent that started a subagent). The listing showed 5 subagents, and the nested subagent's transcript opened with 256 parts through sub=.

Not tried:

- No real OpenCode child sessions: this Mac's opencode.db has none.
- No real Kimi Code sessions.
- Qoder only with the fixture.
2026-10-15 08:23:54 +08:00
Hogee 644f4316f9 sessions, usage, gui: separate Codex thread relationships and consumption (#1591)
Preserve native Codex thread IDs and explicit parent chains. Associate gateway
calls with their actual thread by unique response ID before legacy matching;
fold identical native history copies and keep ambiguous actors unknown.

Existing Sessions APIs expose optional Codex roles, parent/root relationships
and per-thread model/effort consumption. The overview uses its existing calendar
range. Usage request APIs expose query-time actor classification and reuse
session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing,
UI assets, raw Usage logs and model-only aggregation retain their semantics.

Verified after rebasing onto main 331c27703a,
at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree
78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward.
Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches.

Passed (each exit 0):
- git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output)
- go vet ./...
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./...
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./...
- go build -o /tmp/magpie-codex-session-identity-p4-darwin
- GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux
- GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe
- go test -tags nogui ./...
- go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1
- git diff --check

Behavior-break proof: removing identity/thread-ID promotion fails native identity,
upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses
a neighboring main call. Removing API enrichment yields missing consumption;
using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed
its targeted tests and the final checks above.

Native checks had Clang enum/linker deployment-target warnings.
Linux/Windows runtime, real accounts/vendors and manual UI were not exercised.
No frontend suite was run because the change does not touch GUI assets.

Refs #1591 (Codex portion only).

Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e).
The one conflict was call_cache.go's version: main had taken calls-v13 for
compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up
commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/main e5cd125f0 (Go 1.26.8
darwin/arm64, sandbox HOME, private GOCACHE):
- gofmt -l on the changed files: none
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- the darwin, linux (nogui) and windows builds
- go test -tags nogui -timeout 40m ./...: all ok
- go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage'
  ./internal/sessions ./internal/usage ./internal/gui: ok
Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage
tests), setting it for a main thread too (2), Session kept raw instead of
the root (7), thread_spawn's parent_thread_id not read (3 sessions tests),
response pairs not reserved before the old matching (6).
Not tried: a real Codex subagent rollout (none on this machine; every
recent rollout is a vscode main thread whose session_id equals its id),
and the GUI by hand. Claude Code's fields are unchanged.
2026-10-14 22:45:40 +08:00
yetone 9dd5917a41 gui: the session-stats memo lets go of the range asked least recently, counted by asks rather than the clock (review of CaramelizedCUDA's cap, #1827)
9f0c9593 caps the memo at 8 ranges and stamps each with time.Now() when
asked. Its test only checked the count and that the newest range stays,
which passes with the eviction reversed (k.used.After) or with a hit that
doesn't restamp. TestStatsMemoKeepsTheRangeAskedAgain fills the memo, asks
range 1 again, adds one more and checks 1 is kept and 2 let go.

The stamp is now the memo's ask count: Windows' clock can read the same
for two asks in a row, so with time stamps the range asked again could
tie with one asked once and either could go.

Run (macOS, go1.26.8, sandbox HOME, private caches):
- reversed comparison (> for <): the new test fails, "the range asked
  again was let go before one asked once"; a hit that doesn't restamp:
  the same failure. Both pass with the change.
- go test -tags nogui -count=1 ./internal/gui ./internal/plugin: ok.
- gofmt -l clean; go vet on both packages for darwin, linux (nogui) and
  windows/amd64; go build for darwin, linux nogui and windows.
Not run: the whole suite (machine loaded), the new test on Windows.
2026-10-12 23:33:56 +08:00
CaramelizedCUDAandClaude Code bbe8825c04 gui: the Usage page's session-stats memo keeps the 8 most recently asked ?days ranges, not one per number a request sends
statsFor keeps a whole sessions.Stats per distinct ?days= value, and
only forgetStats ever emptied the map. Each new number a caller sent
added a snapshot that stayed until a session was deleted, restored or
purged. Now the memo keeps the 8 most recently used ranges.

Run before this commit (Linux, WSL2 Ubuntu 24.04, official go1.26.8):
the new test fails with the fix reverted and passes with it;
go test -tags nogui ./internal/gui ./internal/plugin is ok. Both
builds were compared with magpie web on a sandbox copy of a real
~/.codex/sessions: all 10 stats/overview answers byte-identical, and
300 distinct ?days values left HEAD's memory up 21-25 MB against 6 MB
for this change.

macOS was not run here; CI's macOS job runs the new test.

Reviewed for magpie (CaramelizedCUDA/magpie pr/stats-memo-cap at 05f0afa4, cherry-picked onto f340aecab, then rebased onto 6ccf23efa and run again there): on macOS, go1.26.8, sandbox HOME, TestStatsMemoKeepsAFewDays fails with the cap turned off ("the memo holds 64, want at most 8") and passes with it. The next commits add a test for which range goes and stamp by ask count.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-12 23:33:56 +08:00
yetone 260ded9af4 sessions: the Sessions page's search finds a session by what was said in it, and a gateway session is titled by what it was first asked (YOU on Discord)
Why: the filter matched only titles, folders, ids and models, and a
session the gateway recorded was listed under its bare ses_… id, so one
couldn't be found by anything a person remembers about it.

What changed:
- sessions.GatewayTitle: the first user text of a recorded session (not
  a <…> context tag, # AGENTS.md or an image), made one line. It reads at
  most 8 complete turns of the oldest file of it, caches a finished
  file's answer by path, and costs one stat when nothing is recorded.
  gatewayListed applies it in every list (/api/sessions, /manage, /one,
  the stats summaries); ExternalSession gained Title.
- GET /api/sessions/search?agent=&q= (searchSessions): an agent's
  sessions, newest first, read by up to 4 workers, each only to its
  first match. Native files go through a byte prefilter (mayHold: the
  query's longest word, ASCII case folded without a copy, 1 MiB chunks,
  skipped for zstd and for queries JSON may escape), and of a Claude or
  Codex file only the lines holding every word are decoded
  (readTranscriptOf; claudeContentOf/codexContentOf take an optional
  line test, nil for every other caller); gateway sessions, and an
  unreadable agent's sessions (unread: true), through their recorded
  transcript. System prompts, tool definitions and images never match.
  It stops at 200 hits or 8s (cut, searched of total) and when the
  request's context ends. Each hit carries the match with 36 runes
  before and 120 after.
- sessions.js: the field says "Search sessions"; title/folder/id/model
  matches show at once, the server is asked 300ms after the last
  keystroke, a new query aborts the request in flight and its answer is
  dropped, under 2 letters asks nothing. A session found shows a line of
  the words round its match with the match in <mark> (text nodes, no
  innerHTML). A note says when it is searching, cut short, failed, or
  limited to recorded text. New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-sessions.md describes both.

Run:
- Go: TestSearchSession* (snippet, case and line breaks, said text
  preferred over a tool call, cut ends, cancelled context, a Codex file,
  only matching lines decoded: 1 part of 3), TestContainsFold,
  TestMayHoldSkipsAFileWithoutTheWords (incl. a match across chunks),
  TestGatewayTitleAndSearch (context tag and system prompt skipped),
  TestSessionsSearchFindsGatewaySessionsByWhatWasSaid (endpoint + manage
  titles), TestSessionsSearchStopsWhenItsRequestEnds. Without the
  endpoint/title they fail (404, id as title).
- GUI: new sessions-search.test.cjs in chromium and webkit, en/zh at
  1100, zh-TW/ja at 560, de at 420: title shown, one letter no request,
  one debounced request, snippet mark, cancelled earlier request never
  shown, cut note, empty state, Escape, every language's strings, no
  overflow; 12/12, and 0/12 with the old sessions.js. The sessions-*,
  sess-*, session-* and i18n-keys tests pass in both engines
  (sessions-manage's placeholder updated to "Search sessions").
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., the builds: clean. go test -tags nogui
  ./... at load ~25-60 (other sessions' runs): every package passed but
  internal/agent and internal/gateway, which hit the 30m timeout; run
  again alone, agent passed and gateway's only red was
  TestOTelWaterfallIncludesUnbilledFallback, filed as #1794 (passes
  alone, -count=3).
- Real data, read-only (a temporary probe, not committed, pointed at
  the owner's ~/.claude and ~/.codex; one worker, 8s, load ~50):
  Claude, 58 sessions / 3 GB: before the line filter one 1.3 GB session
  took the whole 8s ("redis": 1 of 58); after, all 58 in 4.7s ("redis",
  13 hits), 7.4s ("gateway session"), 2.8s (no match). Codex, 11534
  sessions / 65 GB: 245-656 sessions in 8s either way, which is what
  the cut note ("latest n of total") is for.

Not verified: the endpoint and page against a real recorded gateway
store (only fixtures and temp homes); the timings above were taken on
a machine at load ~50 and vary run to run.
2026-10-12 22:29:46 +08:00
yetone e044ea862f sessions: the warm-up at start reads with a quarter of the cores unless a page waits, and a long first read keeps what it read (#1665, laowangba233)
#1665: magpie pegs the CPU on every start (Windows Task Manager showed
95.8%). Three seconds after start, warmSessions indexes every Claude/Codex
session file and reads every file's calls for usage. refresh() ran
min(max(8, 2*NumCPU), 32) parsers at once and usage's prefetch 8 more, so the
background warm-up took every core while nobody was looking at the result.

Two goals, in one commit because they touch the same loop in refresh():

1. Quiet warm-up (quiet.go). gui's warmSessions runs inside
   sessions.Warm. While a warm-up runs and no request waits, every parse in
   refresh() and every readCalls takes one of max(1, NumCPU/4) slots. A
   request to /api/sessions* or /api/usage* (gui's held middleware) calls
   sessions.Ask(), which lifts the limit for as long as it runs, so a page
   the user opened isn't slowed down. A waiting reader re-checks every 50ms,
   so Ask takes effect mid-read.

2. Checkpoints. refresh() saved sessions.json only once all files were
   parsed. Quitting magpie before that (a slow machine, or the user closing
   it because the CPU is pegged) kept nothing, and the next start parsed
   every file again. Now every 5s (checkpointEvery) the files done so far
   are published and saved, if the cache generation still matches.

Measured on a Mac (14 cores) with a sandbox HOME holding 8.9 GB of real
sessions (copied read-only), sessions.json and calls-v11 removed, sampling
ps every 2s:
- cold start before: 41.2 CPU-s, peak 580-600%, done ~14s
- cold start after:  34.7 CPU-s, peak ~300-360%, done ~16s
- quit mid-index, before: quit at 6s (13.5 CPU-s spent) left no
  sessions.json and no calls files; the next start spent 41 CPU-s again.
- quit mid-index, after: quit at 12s left a 1.3 MB sessions.json (of
  3.0 MB); the next start spent 26.6 CPU-s instead of 34.7.

Tests (each red with its part undone, script-checked: refresh's slot
replaced by a no-op, readCalls' slot removed, the checkpoint block removed):
- TestWarmReadsOnlyInItsSlots: with every slot held, neither the index nor
  the calls read anything for 300ms; Ask() lets both finish.
- TestReadSlotOnlyWhileWarming: outside Warm, or while asked, reads don't
  wait.
- TestLongReadKeepsWhatItRead: a read held after its 3rd file has saved
  sessions.json with fewer files than it has to do.

Run: go test -tags nogui ./internal/sessions ./internal/gui
./internal/library ./internal/usage; gofmt -l; GOOS=linux and
GOOS=windows go vet of sessions, gui, library; full go test ./... before
push.
Not tried: the reporter's machine or data volume; a Windows re-measure.
2026-10-12 02:56:01 +08:00
yetone f0834b6f0d gui, sessions: a session magpie's gateway recorded downloads as Markdown instead of a 400 (akic404 on Discord)
akic404's public magpie serves other magpies as a remote magpie and records
their agents' conversations. The Sessions page showed them, but Download as
Markdown in magpie web answered 400 {"error":"no such session"}: the export
(GET /api/sessions/markdown, and the app's POST /api/sessions/export) only
looked for the agent's own session file, and an agent that ran on another
machine has none here. The transcript endpoint already fell back to the
gateway's record; the export didn't.

sessionMarkdown now takes the same fallback: no native session, but a known
gateway session for that agent and id, is written from GatewayTranscript by
the new sessions.WriteGatewayMarkdown. It shares WriteMarkdown's layout
(writeMarkdown), says "Recorded by: magpie's gateway" in place of the file,
and notes when older turns or the end of a long part weren't kept. It is not
the Host check or CSRF: the GET with the web cookie reached the handler.

Run:
- Sandbox upstream (magpie web --gateway, MAGPIE_WEB_KEY) with recorded pi
  and omp sessions reached through a downstream remote magpie: the old
  binary's /api/sessions/markdown gave 400 "no such session"; the new one
  gives 200 with the text, Content-Disposition
  magpie-session-pi-01a126b7-2a4.md; without the cookie still 401.
- TestGatewaySessionExportsMarkdown fails on the old sessionMarkdown with
  that 400 and passes now; TestSessionExportMarkdown, TestGatewayConversationAPI.
- go test ./internal/gui ./internal/sessions, gofmt -l, go vet for darwin,
  GOOS=linux and GOOS=windows on internal/gui and internal/sessions.
2026-10-11 01:13:52 +08:00
yetone eb035e29e1 sessions: a session seen only through the gateway can be deleted: its row and recorded conversation go to magpie's trash, and Restore brings them back (lc on Discord)
lc ("只可列出?不可删除?agent claude code") saw Claude Code sessions named by
uuid under "No folder" at "0 B", with "These Claude Code sessions are read
only; magpie can list them, but cannot resume or delete them." Those rows are
gateway projections from the usage ledger: Claude Code ran with its own files
somewhere magpie can't see (another computer, a container, another config
folder), so nothing native won on the same agent+id. An agent with only such
rows was sent as not deletable, and every row was read_only, so the page had
no Delete at all.

What changed:
- sessions.DeleteGateway moves the session's recorded text folders
  (gateway-conversations/<date>/<identity hash>) into
  trash/sessions/gateway/<ts>-<hash>/files/<date> with a note marked gateway,
  and records {agent, id, last} in gateway-sessions-hidden.json.
  /api/sessions and /api/sessions/manage leave it out up to that last
  request; a newer request lists it again. The usage ledger is untouched, so
  Usage, /api/sessions/one and stats keep what it spent. A session with a
  request in the last minute is refused as active.
- Restore moves the text back (skipping what expired or was cleared, refusing
  rather than overwriting a same-day re-recording), checks each item is this
  session's identity folder inside the store, and unhides it. Delete forever
  keeps it hidden.
- The recording's promises hold in the trash: the hourly prune erases
  trashed gateway text past 7 days, "Delete saved conversations…" erases it
  too, and HasGatewayConversations counts it.
- The manage route marks an agent with gateway rows deletable and sends
  those rows deletable, with gateway: true and the size of their recorded
  text; the delete route sends gateway ids to DeleteGateway and native ones
  to Delete as before.
- Sessions page: gateway rows group under "Seen through the gateway"
  instead of "No folder", show "{size} recorded" only when something was
  recorded (no "0 B"), and the note says why they can't be resumed and what
  Delete takes and keeps. The delete dialog says the same for gateway rows
  instead of "Their files are moved…"; the Trash marks them and notes the
  7-day expiry. New strings in zh, zh-TW, ja and de.
- docs/subsystems/gateway-sessions.md describes the delete, hidden list,
  restore, expiry and clear.

Verified:
- go test -tags nogui ./... (sandbox HOME) green; gofmt -l clean; go vet
  ./...; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/sessions
  ./internal/gui; go build, GOOS=linux -tags nogui and GOOS=windows builds.
- TestSessionsDeleteGatewaySession fails on the old code with "Claude Code
  with only gateway sessions isn't deletable: [{Agent:claude
  Deletable:false}]"; sessions-gateway-delete.test.cjs fails there too.
  TestGatewayDeleteTrashExpires, TestGatewayPurgeKeepsItHidden,
  TestGatewayDeleteNothingRecorded and TestGatewayRestoreRefusesForeignItems
  cover expiry, purge, an unrecorded session and a forged note.
- GUI: sessions-gateway-delete.test.cjs in Chromium and WebKit, en, zh,
  zh-TW, ja, de, at 1000 and 390px (in-app dialog, Cancel sends nothing,
  click doesn't scroll, no left-border accents, no page overflow); all
  sessions-*, gateway-conversations, checkbox-look, old-webkit,
  sess-agent-strip, i18n-keys, gui-ja, gui-de and gui-zh-tw tests pass.
- Real try: magpie web from this tree on a sandbox HOME seeded with three
  gateway-only Claude Code sessions (two recorded): deleted a recorded and an
  unrecorded one, checked the store, trash and hidden list on disk, restored
  the recorded one (its transcript reads again), purged the other (stays
  hidden). That try found the Trash page breaking on an unrecorded session's
  null items; DeleteGateway now writes [] (TestGatewayDeleteNothingRecorded
  fails without it) and the page reads a missing list as empty.
2026-10-10 09:53:38 +08:00
木子不是木子狸 c9b8263378 sessions, gateway: Sessions lists gateway sessions, and can keep their text on this computer when turned on (#1355, mu-zi-lee)
What changed: the Sessions page lists sessions seen only through the
gateway (from the usage ledger, read-only, a native session of the same id
wins), and shows in gateway mode. A Sessions switch, off by default and
confirmed before it turns on, records each gateway exchange's text under
the config dir (scrubbed, at most 7 days and 256 MiB, cleaned hourly).
Settings sync and restore can't turn it on; POST /api/sessions/recording
turns it on or off and can clear what was kept.

Why: users of magpie as a gateway (gateway mode, LAN clients) had no way
to see their conversations; the owner chose this design on the PR.

Squashed from PR head 6a343ba1 onto origin/main. Conflicts: gui-shell.md
(kept main's placeMenu text, took the PR's Sessions in gateway mode) and
settings_keep_test.go (main's fields plus GatewayConversations).

Run: go build ./..., go vet on gateway, gui, sessions, settings, usage;
go test -race -timeout 900s on those five packages: all ok.
2026-10-10 04:24:18 +08:00
yetone ddb6f806ac gui: the sessions warm-up hands its garbage back to the system when it ends, so a magpie just started doesn't read ~470 MB at rest for its first two minutes (H20 on Discord)
The warm-up reads every session file for the Sessions page and Usage › Requests. On a 13.5k-session history it allocates ~830 MB (QueryPage ~570, StatsFor ~260) to keep ~80 MB of indexes, and Go's scavenger returns the freed pages only over the next minutes. warmUp now calls debug.FreeOSMemory once its reads are done: one forced GC and scavenge, once, at start.

RSS of a linux nogui `magpie web` in Docker on a copy of a real config with those sessions mounted read-only, sampled every 15 s from start (with the dsh round change before it): 15 s 472 -> 197 MB, 30 s 475 -> 285, 60 s 417 -> 281, 2 min 337 -> 281, 3.5 min 266 -> 218, 12 min ~250 -> ~204. TestWarmUpReturnsItsGarbage fails without the FreeOSMemory call (10 of 10: 46-334 MB of freed heap still held, or the heap not yet collected) and passes 10 of 10 with it. go test -tags nogui ./internal/gui ./internal/sessions (Docker golang:1.26.8, temp HOME), go vet -tags nogui ./internal/gui for linux, windows and darwin, and gofmt -l pass. Not measured on macOS: a fresh build there hangs at exec behind syspolicyd today.
2026-10-08 21:21:01 +08:00