Commit Graph
5 Commits
Author SHA1 Message Date
yetone b8270850df sessions: a kept parse's rarely set fields live in a StateMore made only when one is set (#2278)
Each of the ~18k files the Sessions cache keeps had a 760-byte state, and
~330 bytes of it were fields almost no file sets: the Codex spawn and agent
maps, Named/Custom/First, the dsh and Claude conversation lists, Root/Leaf,
Compacts, and the six per-agent tails (Grok, Droid, Kimi, Agy, Dsh, Cline).
On the owner's real cache (18,331 files) Root and Leaf are set in 150,
Named in 117, Compacts in 78, First in 35. They move to an embedded
*StateMore, nil unless something is in it: reads go through more() (a
shared empty one when nil), writes through own(). The JSON is the same
(embedded fields are inlined), so the cache version stays.

- parseWith drops an extra that only had empty values written to it, and
  share() drops one the decode made empty.
- clone() deep-copies the extra, so growing a clone leaves the kept state
  alone. Copies that never write (withoutRevisions, the Agent rename)
  share it, as they shared the maps before.

Run on mote at this tree:
- gofmt -l internal/sessions: clean. go vet ./internal/sessions/ on
  darwin, GOOS=linux and GOOS=windows: ok.
- go test -count=1 ./internal/sessions/: ok (26s).
- Every selector was checked by renaming the embedding to a named field
  and compiling with -gcflags=-e until only the struct literals were left,
  so no field is reached through a nil *StateMore.
- New tests in state_more_test.go: zero() knows every field (reflect), a
  read makes no extra and a write never reaches the shared empty one, a
  clone owns its extra, and a cache round trip keeps no empty extra.
  Broken by hand: dropping Cline from zero() and sharing the extra in
  clone() each turn their test red; restored.
- Real-account idle heap (copy of the owner's config and 24.6MB sessions
  cache, gateway idle 180s, heap after GC): decodeCache's retained heap
  35.0MB -> 22.5MB, reflect.unsafe_New 20.0MB -> 10.5MB. The total
  (128.7MB -> 133.6MB) moves by more than that between runs of one binary
  (118-140MB), from late passes that happened to be live.

Not tried: the full ./... suite (state is unexported; only internal/sessions
uses it, and the whole binary builds).
2026-11-09 18:08:28 +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 e03d495f83 sessions: a Kimi Code session read before is read on from where it was left, not whole
Kimi Code only appends to a session's wire.jsonl, but every message (and
every rewrite of its state.json, whose size and mtime are folded into
the wire's) made the Sessions and Usage pages read the whole wire again,
a fork's twice: once for its last marker, once to count.

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

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

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

Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
2026-10-19 11:30:47 +08:00
yetone 407595b2ab sessions: a Kimi Code session whose state.json names no folder takes it from session_index.jsonl (#2103, infinitr0us)
Early protocol 1.4 sessions and those migrated from the Python kimi-cli
(ses_* folders) have neither cwd nor workDir in state.json, so they were
listed under "No folder" and resumed with a bare `kimi --session <id>`.
Kimi Code's session_index.jsonl, at the root of its home beside sessions/,
has {sessionId, sessionDir, workDir} for every session (Kimi's
docs/en/configuration/data-locations.md). parseKimi now falls back to the
workDir of the index line whose sessionId is the session folder's name;
a folder state.json names still wins. The index is read again only when
its size or mtime changes. parseKimi is the only place a Kimi session's
folder is derived (the resume command is built from it).

Run:
- TestKimiCodeSessionFolderFromIndex (new): the reporter's 1.4 and
  migrated sessions get the index's folder and a `cd '<folder>' &&`
  resume; state.json's cwd beats a different index line; a session with
  no folder anywhere stays without one. With kimi.go put back it fails:
  `june folder ""`.
- go test -tags nogui ./internal/sessions/... under a sandbox HOME with
  pinned caches: ok.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.

Not tried: a real Kimi Code home with an index (this machine's
~/.kimi-code has no sessions); the format is from Kimi's docs, the
reporter's line on the issue and Coffee-CLI's reader of the same file.
Not run: the full go test ./... suite.
2026-10-14 14:19:23 +08:00
yetoneandggbdpq 4921e5e2a6 sessions: Kimi Code's sessions are listed on the Sessions page and the Usage page's Sessions tab (#1913, infinitr0us)
Kimi Code's calls reached the usage ledger in #1607, but no session reader
was ever written for it: allFiles had no Kimi entry, so its sessions were
missing from Sessions and from Usage > Sessions (both read sessions.List).

kimi.go reads a session folder, sessions/<workdir slug>/<id>/, as Kimi Code
itself does (packages/agent-core-v2, checked at MoonshotAI/kimi-code afd95f6):
- state.json: the title, custom or Kimi's own (isCustomTitle, titleKind,
  an old customTitle, as normalizeSessionTitle decides), cwd or 1.4's
  workDir, createdAt as epoch ms or an RFC 3339 string. Its size and mtime
  join the main file's, so a rename reads the session again.
- each agent's wire.jsonl: usage.record tokens (a magpie/ model counted
  under its own name: here it is the session's spend), turn.prompt typed by
  the user (a subagent's system_trigger and a skill_activation aren't),
  step.end end_turn as replies, tool.call names.
- a fork counts only what follows its last {"type":"forked"} marker
  (copyAgentWire + appendForkedMarker); one without a marker is cut at its
  createdAt.
- resume: kimi --session <id>.
The same files feed the calls reader (kimiCallFiles now shares
kimiFilesIn). Siblings: Kimi's ~/.kimi-code in a WSL distro is listed
(wslAgents) and its calls are counted (callSources); the Usage page's
Sessions tab reads the same List.

ggbdpq described a reader on the issue; the patch they mentioned didn't
come through as an attachment, so this is written from their notes and
Kimi's source. Co-authored for the design.

Tests (testdata/kimi-code-sessions: the #1607 reporter's whole real files,
6 sessions, totals equal to their README's): TestKimiCodeSessions,
TestKimiCodeSessionCounts, TestKimiCodeSessionFork, TestWSLKimiCode. Broken
by hand, each goes red: no kimiFiles in allFiles, no marker cut (the
clock-set-back fork), no createdAt cut, no WSL entry, any origin as a
prompt, no workDir, no resume case.

Run: go test -tags nogui ./internal/sessions/ ./internal/gui/ in a sandbox
HOME, gofmt -l, GOOS=linux and windows go vet. Not tried with a live Kimi
Code install (the fixtures are real files from one).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-13 15:46:21 +08:00