Commit Graph
13 Commits
Author SHA1 Message Date
yetoneandKoohoko 067f39f406 sessions: Desktop titles read once per second, from every handle Desktop keeps, and reach stats and Context (#1675)
Follow-up to Koohoko's 3d6f8b8e, after review.

- Cost: assemble asks DesktopTitles once per native Claude Desktop
  session, and each call globbed and stat'ed every local_*.json, so a
  list of N Cowork sessions looked at the metadata N times. The names
  are now one index, rebuilt at most once a second (desktopTitlesHeld);
  a rename in Desktop shows within that second. Files are read through
  filememo, the shared reader the usage resolver already uses for these
  same files, which also catches a same-size rewrite inside one mtime
  tick (the patch's own size+mtime cache didn't).
- A record that is there but doesn't parse (Desktop midway through a
  write) keeps its last parse instead of dropping to the bare id; a
  record gone still takes its names with it.
- Handles: Claude.app 2.7032's LocalSessionManager (app.asar, read-only)
  counts unarchivedCliSessionId as a live handle beside cliSessionId and
  preClearCliSessionId as lineage beside priorCliSessionIds, and runs a
  record with no cliSessionId under its sessionId without "local_".
  All are named now; the raw "local_..." id no longer is (no usage
  record carries it).
- Siblings: MergeExternalStats (the Sessions page's stats summaries)
  and the Context page named gateway-only Desktop sessions by the
  recorded prompt or nothing; both use the Desktop name now.
- docs/subsystems/gateway-sessions.md says all of the above.

Real layout: no Desktop session records exist on this Mac or the
Windows box (only claude_desktop_config.json), so field names and types
were checked against Claude.app 2.7032's own reader/writer code: a
string title, string cliSessionId/unarchivedCliSessionId/
preClearCliSessionId, an array priorCliSessionIds, files
<account>/<org>/local_*.json under claude-code-sessions and
local-agent-mode-sessions. Dirs come from desktopdir.Everywhere, the
resolver the other Desktop session readers use (Windows %APPDATA% and
MSIX LocalCache, Linux ~/.config); Windows/Linux not run.

Run: new tests TestDesktopSessionTitleHandles, TestDesktopSessionTitleInStats,
TestDesktopTitlesReadOncePerList, and context checks in
TestDesktopSessionTitlesOnPages. Each broken by hand went red:
rescan per call -> "metadata looked at 12 times, want once"; no
last-good -> "a half-written file lost its names"; no unarchived/stem ->
missing ids; stats without the name -> "stats titles map[cli-s:Recorded
prompt ...]"; Context without it -> "context titles map[...: ...]".
go test -race -count=20 -run TestDesktop ./internal/sessions;
go test -tags nogui ./... (sandbox HOME, pinned caches): all ok but
internal/plugin's TestPiPackage (pi-codemode export missing; passes
alone, doesn't import sessions or gui), filed as #1879; gofmt -l;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./...; go build, GOOS=linux go build -tags nogui, GOOS=windows go build.
GUI: routing-sessions, session-identity, sessions-overview,
sessions-bar-names, sessions-gateway-delete, sessions-manage,
context-window in Chromium and WebKit (84/84 each).
Real binary: magpie web under a sandbox HOME with Claude-3p Code and
Claude Cowork fixture records and five claude-desktop usage records;
the Sessions page (Chromium, WebKit) showed both titles on current,
prior and unarchived ids and the bare id on the unmatched one;
/api/gateway/session-titles named them; a rename showed after 1.3s;
a half-written file kept the name; deleting the record went back to
the id.

Co-authored-by: Koohoko <koohoko@gmail.com>
2026-10-13 07:14:22 +08:00
Haogao Gu d46a5635c0 sessions: Claude Desktop uses its saved conversation titles (#1675)
Read Code and Cowork metadata when native CLI transcripts are absent,
including current/prior CLI IDs and renames. Keep gateway identity,
accounting and capabilities. Desktop titles take precedence over the
recorded first-prompt fallback added upstream; unknown names keep it.

Rebased onto 751e05d8. All three new regressions fail on that unmodified
base and pass with the patch. Full Go suite, targeted race checks repeated
20 times, and macOS/Linux/Windows vet/builds pass. Baseline and patched
binaries reproduce UUID/title display in Chromium and WebKit with the
same synthetic Code/Cowork metadata and recording off. The patch applies
cleanly to newer origin/main 84cd8153. Linux/Windows runtime UI was not
executed. No live gateway or agent files were modified.
2026-10-13 07:14:22 +08:00
yetone d3d1605c2c sessions: Kimi Code's own calls reach Usage, read from its wire files (#1607, infinitr0us)
Usage counts the gateway's calls and the calls the agents' own session
files record (sessions.Calls). Kimi Code had no reader, so its calls
straight to api.kimi.com on Kimi's own sign-in never showed (the
reporter's 47 k3 calls of one session on 2026-10-11).

The reader (calls_kimi.go) is built from the redacted real wire files
infinitr0us shared from two machines (protocols 1.0, 1.4, 1.5; text
replaced, every id, model and number kept) and their notes from Kimi
Code's source. It reads every agents/*/wire.jsonl under
$KIMI_CODE_HOME/sessions, else ~/.kimi-code/sessions (as agent.KimiDir
finds the new Kimi Code), main and subagents, ses_* folders included.
One call per usage.record: inputOther, inputCacheRead and
inputCacheCreation go to Input, CacheRead and CacheWrite, output as is,
the record's own model and time. Nothing is paired with step.end, since
1.4 and 1.5 write them in opposite orders and the June 1.4 build has no
messageId or llm.request. A model beginning "magpie/" (magpie's own
entry in Kimi's config) is skipped: the gateway counted it. kimi fork
copies the parent's records unchanged, so a call is keyed by agent
(agentId, else its agents/<id> folder), time, model and usage, and Calls
counts a key once. It is a whole-file call source (callSources,
wholeCallReaders) and the folder is watched (Dirs). The subsystem page
gets the list of call readers.

Fixtures (testdata/kimi-code) are the reporter's files cut to the lines
a call is read from, each line verbatim (50 KB; one of the July
session's eight agents kept).

Run: the reader over the reporter's whole, untrimmed files gives exactly
their README's totals (32/2,841,972/12,283; 151/7,025,587/122,782;
6/147,822/2,009; 10/338,328/2,176; 0 for the four others).
TestKimiCodeCalls (both homes), TestKimiCodeSkipsCallsThroughMagpie,
TestKimiCodeForkCountsOnce, TestKimiCodeBrokenFiles (cut mid-record,
empty, junk, null/negative/timeless usage) pass. Broken by hand, each
goes red: no magpie skip, no key, key without agent, no negative or
time guard, main only, KIMI_CODE_HOME ignored, cache read dropped.
go test -tags nogui ./internal/sessions ./internal/usage ./internal/cli
./internal/gui under a sandbox HOME, gofmt -l, go vet (darwin),
GOOS=linux go vet -tags nogui, GOOS=windows go vet.

Not tried: a live Kimi Code run (fixtures are the reporter's real
files, not a sandbox capture), a successful call through magpie (the
magpie-routed record in the test is the reporter's quoted 1.5 line with
a magpie/ model), a compaction record (usageScope "session", none in
the files), Kimi Code in WSL (not read), Windows paths at runtime. A
subagent's calls carry the session but no Subagent field.

Thanks to infinitr0us for the write-up from Kimi's source and the
redacted wire files.

Reported-by: infinitr0us
2026-10-13 06:59:17 +08:00
yetoneandliubing 9935119f1d sessions: search finds Cursor and OpenCode sessions read from their stores, and a Cursor chat's system prompt isn't shown as said (#1743)
Follow-up to liubing's #1743 patch, which put cursor and opencode in
HasTranscript. That moved their search from magpie's recorded
transcript to SearchSession, whose byte prefilter (mayHold) reads
s.Path. For these agents s.Path isn't the conversation:
- OpenCode's JSON storage: the session info file, without messages,
  so every word missed;
- OpenCode's and Cursor's SQLite stores: the newest pages are in the
  -wal, so a live chat's latest turns missed.
linesFile now skips the prefilter for them (a Cursor .jsonl still
gets it).

cursorTranscript also handed the CLI store's system message ("You
are a coding agent.") to the transcript as a said part; system
messages are skipped, as the listing already does.

The patch's tests commit left TestSearchSessionWithoutATranscript
red (it used cursor as the agent without a transcript; now gemini).
sessions-empty-range.test.cjs runs in every language, de at 420px.

Run: go test -tags nogui -count=1 ./internal/sessions/ ok, and -race
ok; sessions-empty-range 10/10 (Chromium+WebKit, en zh zh-TW ja de);
sessions-today/overview/toolbar/search/manage/calendar-fill/paging
GUI tests pass.
Broken by hand: prefilter always on -> TestSearchOpenCodeFiles and
TestSearchCursorLiveChat red; system skip removed ->
TestSearchCursorLiveChat red. Also broke the patch itself: editor
files not appended, readOnly Delete guard, stats message dates, CLI
dedupe, HasTranscript entries, parseCursor readOnly dispatch, and
the "All sessions" button (via MAGPIE_TEST_APP_JS); each went red.

Co-authored-by: liubing <lb0806@foxmail.com>
2026-10-13 06:43:50 +08:00
yetone d4c2512d2d usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
  one record or an array, in usage.jsonl's shape:
  - the post may carry up to 5000 records and 32 MiB;
  - t, agent, provider, model and rid are required.
  Each field is checked: unknown fields, quoted numbers, negative or absurd
  counts, a status outside 100-599, a cost over 10000 USD, and a t more
  than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
  whole post with a 400 that names error.index and error.param, and nothing
  is written. A past t is otherwise taken as given, so history can be
  backfilled. The reply gives accepted and skipped counts and each
  record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
  shared, behind the Host check). A browser page also needs a key, since
  corsGuard lets localhost pages and Origin null through. A held key is
  refused.
- usage.IngestReported writes under usage.mu to the same file as
  usage.Append. Rows carry source "reported" and no caller key. A rid
  already reported is skipped, as is one repeated in the post. The set of
  reported rids is read back from the log: one scan after a restart (lines
  without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
  flag; packed flags widened to uint16). Otherwise it is priced at
  magpie's prices.
- Display:
  - SourceReported is a source of its own: RequestPage.Reported,
    ?via=reported, and Ledger now honours via.
  - The Requests tab gains a fourth cell "reported by apps", shown once
    there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
  - a key's budget/spend limit (budget.counts);
  - window holds, and the log start that decides whether a window can be
    reckoned (logSnapshot.firstOwn);
  - gateway sessions and Vias;
  - Codex's sealed answers and remembered model.
  There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
  site integrate.html (en, zh).

Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.

Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
  - usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
    languages, 1180 and 420 wide, light and dark);
  - usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
    usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
  - 40 posts of 5000 took 0.40 s (worst batch 18 ms);
  - the first post after a restart took 0.45 s (rid rescan), a later one
    1.6 ms;
  - the cold index build took 2.1 s (as for gateway rows);
  - page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
  - summary all took 215 ms, 30d 20 ms.

Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
  cost; the block pricer overwriting own cost; the Reported split;
  fromBrowser's key rule; skipping bad records instead of refusing; the
  max-records and body limits; the ingest lock (race); both locks;
  firstOwn -> first; the IsReported guards in windowHolds,
  buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.

Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
2026-10-13 06:32:03 +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 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 7a5536793e agent: Pi's and omp's turns are recorded by "Record gateway conversations", as OpenCode's are (akic404 on Discord)
akic404 runs a public magpie as the upstream and a local magpie that reaches
it as a remote magpie; with recording on, only OpenCode's conversations were
kept, on either side. The gateway records a turn only under the session the
client names (it never makes one up), and the configs magpie wrote for Pi and
omp didn't have them name one:

- Pi (1.1.0) sends x-session-affinity on Chat and Anthropic Messages only when
  the provider's compat says sendSessionAffinityHeaders (Responses sends
  session_id anyway). magpie's Pi provider block now sets it. A value the
  user set in that block is kept through a sync and a pick (piBlockKept, for
  pi, OmO and the aside's native Pi path).
- omp (18.6.1) sends its session header on Chat/Responses only to OpenAI
  itself, unless the provider's compat.promptCacheSessionHeader names one
  (pi-catalog 16.0.6+). magpie's omp provider entry now names
  x-session-affinity for omp 16.0.6 and later; an older or unknown version
  is left as it was.

withCaller already passes the session on to a remote magpie, so naming it
once is enough for both sides to record.

Run:
- Header dump (fake upstream LLM): real pi and omp with these provider
  blocks send x-session-affinity / session_id on every API; without them,
  nothing on Chat/Messages.
- End to end in sandbox HOMEs: an upstream (magpie web --gateway) and a
  downstream (serve, remote magpie to the upstream), both recording; the new
  binary wrote ~/.pi/agent/models.json and ~/.omp/agent/models.yml through
  `magpie pi …` / `magpie omp …`; real pi (Chat and Messages models) and real
  omp turns were recorded under gateway-conversations on both sides.
- TestPiNamesItsSessionToTheGateway and TestOmpNamesItsSessionToTheGateway
  fail on the old code (no compat; Compat field missing) and pass now.
- go test ./internal/agent (-timeout 40m), gofmt -l, go vet for darwin,
  GOOS=linux and GOOS=windows on internal/agent.
2026-10-11 01:13:52 +08:00
yetone b6a263b9fd gateway, usage: the Usage page's numbers are read over the gateway, and a Claude Code subagent's call says which subagent and which started it (HoGee_xxl on X)
HoGee_xxl wants their own usage app to read magpie over the gateway,
which had no /api/usage counterpart, and asked for subagents' parent ids.

- GET /v1/magpie/usage (the /api/usage summary, ?period=) and
  GET /v1/magpie/usage/requests (the /api/usage/requests ledger page, same
  filters, offset/limit) on the gateway. The builders moved out of gui into
  internal/usageapi so both serve the same JSON; gui keeps aliases and sets
  usageapi.Clients for agent names (gateway can't import agent). Guard as
  /v1/magpie/quotas: this machine, or another with an enabled gateway key,
  behind the same Host check. A key held to a budget, models or accounts is
  refused the summary (403) and gets the ledger filtered to its own
  CallerKey, with callerKeys/agents/providers/accounts cut to its own rows
  (usageapi.OwnPage): those facets are drawn from every call in the period.
  `path` is left out for another machine.
- usage.Record gains subagent and parent_agent; session stays the parent
  conversation. Gateway rows take them from x-claude-code-agent-id and
  x-claude-code-parent-agent-id; session-file rows from the file name
  (<session>/subagents[/workflows/<run>]/agent-<id>.jsonl, no cache version
  bump) and the parentAgentId of the agent-<id>.meta.json beside it. Both
  packed into the request page's text columns (now 29, msg at 29).
  Codex sub-threads: only kind, as before; no spawned thread on disk to
  take a parent shape from.

Run: real Claude Code 2.1.296 under a sandbox CLAUDE_CONFIG_DIR against a
local fake Anthropic endpoint that made it spawn a subagent from a
subagent: the nested request carried X-Claude-Code-Agent-Id=a143287ac46b82a96
and X-Claude-Code-Parent-Agent-Id=a99ca20c03d1813d8, the first-level one
the agent id only, Session-Id the parent's throughout; the nested meta.json
had parentAgentId. Tests use those bytes. TestUsageOverGateway goes red
with OwnPage, the CallerKey pin, or the header read removed (each tried).
gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
GOOS=windows go vet ./...; set -o pipefail; go test ./... green.
2026-10-10 20:47:00 +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
yetone 62d7cd7be3 sessions: recording gateway conversations is a setting card over the list, with what it keeps and where, and a labelled delete that shows only when text is kept (lee on Discord)
What changed: c9b82633 (#1355) put a bare "Record gateway conversations"
checkbox and an unlabelled trash icon on lines of their own under the agent
tabs, on every agent. They are now one card in the list's column, as wide
as the list: a switch (the app's lib-switch), its title, and a line that
says what is kept and where ("on this computer only, for up to 7 days
(256 MiB)", worded for on and off). "Delete saved conversations…" sits in
the card, says what it deletes, and asks in magpie's own dialog as before.
The card shows only where it applies: on an agent whose list has gateway
sessions, in gateway mode, or while recording is on or text is kept; not on
an agent without gateway sessions, nor in the Trash. The delete shows only
while some text is kept.

To know that, /api/sessions/manage marks gateway-only rows `gateway` and
says `recorded` (sessions.HasGatewayConversations: any file under
gateway-conversations; a folder that can't be read counts as holding some,
so it can still be cleared). New strings in zh, zh-TW, ja and de.
docs/subsystems/gateway-sessions.md says where the switch is and when it
shows.

Why: lee (Discord feedback, 1558248607751344220) said the controls' look
and place need a redesign: they read as stray, unaligned controls, and the
icon didn't say what it deletes.

Run: gofmt -l (nothing); go vet, GOOS=linux go vet -tags nogui,
GOOS=windows go vet (with and without -tags nogui) on ./internal/gui/...
./internal/sessions/...; go test ./internal/gui/... and go test -tags nogui
./internal/gui/... ./internal/sessions/... under a sandbox HOME: ok.
GUI: gateway-conversations (both tests, en/zh/zh-TW/ja/de, 1000/1400 and
390px) plus checkbox-look, click-scroll, gateway-mode, i18n-keys,
old-webkit, sess-agent-strip, every sessions-* test and
usage-sessions-agents-fit: 221/221 (default run) and 114/114 with
BROWSER=webkit. Not run: the whole GUI suite.
Fails without the change: with origin/main's sessions_manage.go,
TestGatewayConversationAPI fails "listing: …" (no gateway/recorded); with
origin/main's sessions.js/.css, every gateway-conversations case fails
(no .sm-record switch; "no bare checkbox bar under the tabs 2 !== 0").
2026-10-10 07:40:03 +08:00
yetone 3e5bc3d8fe gateway, usage: conversation text is kept only under a session the client named, and a client's "request-…" session counts like any other (#1355)
What changed: with recording on, a request that names no session used to
get a made-up "request-…" id and its text saved under it. Nothing listed
that id and GatewaySessionByID turned it away, so the text could never be
opened. magpie now makes up no id: such a request isn't recorded, and the
X-Magpie-Session reply header only echoes the client's own session.

With no made-up ids left, the "request-" prefix checks in appendUsage,
OTel, Usage's sessions, Routing's vias and the gateway Sessions projection
only dropped sessions clients named themselves (appendUsage wiped them from
the ledger). They are gone. The tests that held the old rule now say the
new one, and gateway-sessions.md says it.

Run: TestGatewayConversationNeedsTheClientsSession and
TestGatewayConversationClientRequestPrefixedSession fail on the PR's code
(a made-up id is returned; the ledger keeps 0 of 2 calls) and pass here;
putting appendUsage's prefix check back turns the second red again.
gofmt -l clean; go vet; GOOS=linux and GOOS=windows go vet -tags nogui on
gateway, gui, sessions, settings, usage; go test -race -timeout 900s on
those five: ok (gateway's TestCORSKeyThroughTheServer rerun after its fix).
GUI: gateway-conversations, gateway-mode and all sessions-* tests, 216
cases in Chromium and WebKit: pass.
2026-10-10 04:24:18 +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