Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
yetoneaf8f3a939979
diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.mdindex 9603e53d8..542897479 100644--- a/docs/subsystems/gateway-sessions.md+++ b/docs/subsystems/gateway-sessions.md@@ -193,6 +193,63 @@ Implementation: [`internal/usage/gateway_sessions.go`](../../internal/usage/gate[`internal/sessions/external.go`](../../internal/sessions/external.go), and[`internal/gui/sessions.go`](../../internal/gui/sessions.go).+## Which agents' sessions magpie reads++An agent's own session files are read only when the user allows that+agent (RustCats on X: a new install showed every agent's history before+anyone agreed). `sessions.Reads(agent)` in+[`access.go`](../../internal/sessions/access.go) is the one gate, from+`settings.SessionReads` (`Asked`, `All`, `Agents`; an agent named in+`Agents` wins, the others follow `All`). Every lister asks it at its+entry (`ccFiles`, `codexFiles`, `openCodeFiles`, `piFilesIn`, ... down to+`geminiTraceFiles`), the aggregators filter by it again (`allFiles`,+`callFilesWith`, `callSourcesWith`, `traceLineFiles`, `wslFiles`, and+`DesktopDataDirs`, which Usage's Desktop readers take), and the readers+that take a session already listed (`TranscriptOf`, `ContentOf`,+`SearchSession`, `SubagentTranscript`, `CarryOver`, `ReadCallSource`)+return `ErrNotRead`, so a cache from before a switch was turned off is+read no further. So the Sessions page and list, stats, the overview, the+call and trace indexes, Usage's agent-file calls and the Codex and Pi+title readers all go through it.++`SettleReads` decides once, for an install with no `SessionReads`: one+that kept a sessions cache (`sessions.json`) or a call cache+(`calls-v*`) read sessions before, and keeps reading every agent+(`Asked`, `All`); a fresh one reads none, not asked. The decision is+saved, so a cache written later never turns it into "all", and a value+already saved is never replaced. `settings.save` keeps the stored value+and sync and restore keep it (`KeepOwn`); only `SetSessionReads` writes+it. A settings.json that can't be written leaves this run reading+nothing. In a test binary nothing settled reads everything and nothing+is written (`readsAllInTests`).++`/api/sessions/reads` (GET; POST `{all, agents}`) in+[`sessions_reads.go`](../../internal/gui/sessions_reads.go) gives the+choice and the agents found (`sessions.Found`, by a stat of each agent's+folder, nothing in it read; WSL distros are not looked into, Allow all+covers them), and `sessions/manage` carries the same as `reads`. While+`asked` is false the Sessions page shows the consent (`consentCard` in+the sessions plugin): each agent found with a switch, off; Allow selected+saves `all: false` with each agent picked or not, Allow all `all: true`.+Settings › Privacy, *Agents' session history* (`renderSessionReads` in+app.js), has *Agents found later* (`all`, sent with each listed agent+at the value its row shows) and a row per agent.+`magpie sessions read [on|off all|<agent>…]` shows and changes the same+choice from the CLI (`sessionReadsTo`); while it is not asked,+`magpie sessions` says so on stderr and the TUI's empty Sessions page+says how (`sessNothing`). Tests: `TestSessionsRead`,+`TestSessionsNotAskedSaysHow`.++What is read either way: the gateway's own usage ledger, its+projections and the conversations it recorded (they are magpie's own),+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, and+Codex's newest rollout's last line before magpie restarts Codex+(`codexTurnOpen`), none of which lists or shows a session. Tests:+`TestFreshInstallReadsNoAgentUntilAllowed`,+`TestSettleReadsKeepsWhatWasThere`, `TestSessionReadsRoutes`,+`sessions-reads.test.cjs`.+## Local Gateway Conversation RecordingThe Sessions page offers an explicit, default-off recording switch. Confirmationdiff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.mdindex 8ac7c4c62..54d66cd93 100644--- a/docs/subsystems/gui-shell.md+++ b/docs/subsystems/gui-shell.md@@ -18,7 +18,7 @@ three.| The app's page in a browser | Settings › Network and sharing › Browser access (`renderWebPage` in `plugins/gateway/settings.js`, drawn with the Web pages rows) has the app serve its own page to a browser while it runs, so a tunnel (Cloudflare Tunnel, SSH) or a computer on the network can reach it without `magpie web` kept running in a terminal (jiakun_zhao on X). Off, This computer (`127.0.0.1`, which a tunnel's service points at) or Local network (every address; a "Not encrypted" row without `--tls-cert`). It is `magpie web`'s page and guard, not a second kind: `startAppPage` (from `Run`, after `startBackend`) serves `webServed` over a `Handler` of its own, whose `Windows` is `appWebHost` (a browser tab for `isWeb`, but not `ownWeb`, so the app's windows aren't taken for `magpie web`'s: `webPage` and gateway mode stay the app's; quitting quits the app, and a restart to update from it brings back the windows the app has up, `restartFrom`). The key is always asked for: no mode serves without it. It lives with the mode and port in `web-page.json` beside settings.json (0600, never in settings.json, so sync and backup don't carry it), is made the first time the page is turned on, kept across restarts (a browser's cookie stays good), and replaced by New key, which turns away every browser signed in with the old one (the guard is swapped atomically, `appPage.cur`). A file that can't be read, or names no known mode, is off and says why; Settings rewrites it only given a whole choice. A port another program holds (`magpie web`; the magpie before a restart to update) is said and tried again every 4 s (`appPageRetry`); the port must be 1024 up and not the gateway's. `GET/POST /api/web-page` are on the app's own windows' API only, never a browser's, so a browser on the page can neither read the key it came in without nor turn the page off under itself. `magpie web` on the port the app serves prints the app's link and opens it rather than starting a second (`gui.AppPage`, `samePort`). Sessions are warmed once a process however many `Handler`s there are (`warmOnce`). See `TestAppPageServesOnlyWithItsKey`, `TestAppPageWaitsForABusyPort`, `TestAppPageUnreadFileServesNothing`, `TestAppPageTurnsDownBadChoices`, `TestAppPageBrowserIsATab` and `browser-access.test.cjs`. | [`apppage.go`](../../internal/gui/apppage.go), [`web_cli.go`](../../internal/cli/web_cli.go) || The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `plugins.js` and `context.js`, and those a plugin adds under `assets/plugins/<id>/` (the Gateway, Sessions, Library, Routing and Usage pages, see [plugin runtime](plugin-runtime.md)) (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js`, and a plugin's own in its `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) || Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar, or drawn at once from boot.js's `sideGateway`; on a page other machines open, `magpie web`, it is `MAGPIE_PUBLIC_URL` while they are let in, as the Gateway page's address and About's Gateway URL are, noahhrreion on Discord; a port applied in Settings redraws it), and the header a breadcrumb (`renderCrumb`). A page whose head holds only its tools (Library, Plugins, Settings) has them in the title bar after the breadcrumb, `tools` setting the room between it and the window's own buttons. When they don't fit there the tools show their icons alone (`tools-tight`; each keeps its name as `aria-label` and in its tooltip), then the breadcrumb drops its leading parts, and last the page's name is cut at its end, so no tool lies over the title (#2625, `title-bar-tools.test.cjs`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. A page's tabs share its one scroll, so a row that picks another tab opens it at its top (`scrollOnPurpose` with the row's click); the tab already open, picked again, leaves the page where it is (`sidebar-tab-top.test.cjs`). The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. The open page's own row is marked the same way, by one shape (`.nav-top-hl`, the rows' own ground given up to it, hovered or pressed too) that `navTopGo` moves to the row picked on a damped spring, as iOS moves a selection (`NAV_SPRING`, SwiftUI's response 0.42s and damping 0.84; `navTopStep` steps it each frame): it sets off as the row is pressed and comes back if the press leaves the row or the page isn't left, turns with the speed it has when the press changes its mind, and follows its row while the list above it folds, landing where the row ends up. It is put in place, not sent, when the window opens on a page or the rows move under it at rest (a `ResizeObserver`), is away while Settings is open (it has its own selection at the foot), comes back fading in on its row, jumps under reduced motion, and isn't drawn in the header's tabs, which have their `.thumb`. `#nav` is `position: relative` in the sidebar for it, so `.seg`'s centring `left` and `top` are reset. See `sidebar-glide.test.cjs`. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. The reader's own place is kept instead for a second while the page is laid out again (`relaid`, a `ResizeObserver` on the open page's parts calling `backToReader`): crossing `SIDE_AT` the browser clamps the scroll to each layout it passes through, and the page ended short of its foot (#1672, `text-size.test.cjs`). See `sidebar.test.cjs`. A sidebar longer than a short window keeps no scroll bar beside its pages: the native bars of `.side-scroll` and `.side-foot` are hidden, and `sideBars` lays a thin bar over each box's edge that shows while it scrolls, fades about a second after it stops (kept while hovered or dragged), can be dragged or clicked to page, and is gone when the box fits, the same in WebKit, WebView2 and WebKitGTK. See `sidebar-overlay-scrollbar.test.cjs`. The window opens on the page the reader last left, as a Mac app comes back as it was (molvqingtai and lc on Discord): `show` keeps the page in localStorage `magpie.lastView` (which the app's webview keeps across restarts, as it keeps `magpie.navLayout`), and `keptView` opens it at start. A page asked for in the address (`?view=`, the tray's links, a reload) wins, Agents too; a kept name that is no page opens the first page, and one gateway mode leaves out opens Providers (`show`). Opening on it scrolls nothing. See `last-page.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |-| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) |+| Settings › Privacy | The page opens on what masking kept from vendors (`drawMaskObs` in app.js, fed by `/api/masking/summary`): the values masked over 7 or 30 days with a chart of the days, the kinds, what only the local model found, agents to providers, and the values masked most, each shown only while pointed at (`maskTip`, `/api/masking/value`, which says it is gone after a restart). Its records (`drawMaskRecs`, `/api/masking/records` and `/api/masking/record`) take the page's place, filtered by kind, finder, agent or provider, a day at a time, each opening on the text the vendor saw with its placeholders marked. `maskedBadge`, on the Gateway page's recent calls and the Routing page's log, opens a request's own record (`openMaskRecord`), in amber with the count sent as written when every value found was on Warn. Below the card, *What to mask*, *How it's found* (the rules, always on while anything is masked, and the local model on top of them), *When a value is found* (Mask, Warn or Block per kind, the secret kinds first and the personal ones behind *Show all kinds*, and the *Never mask* list; `renderMaskActions`), *Try it* (`renderMaskTry`, the text as the vendor would get it from `/api/masking/preview`, kept in no storage) and *Sharing*. *Agents' session history* (`renderSessionReads`, read from `/api/sessions/reads` only while the Privacy part is shown) has *Agents found later* and a row per agent found, the choice the Sessions page asks first on a fresh install; see [gateway sessions](gateway-sessions.md#which-agents-sessions-magpie-reads). See [gateway routing](gateway-routing.md) for what is recorded. | [`assets/app.js`](../../internal/gui/assets/app.js), [`masking.go`](../../internal/gui/masking.go) || Built-in plugins | Plugins › Built-in, the page's first tab (`drawBuiltin` in `plugins.js`, rows by `renderBuiltins` in `app.js`), lists magpie's built-in plugins, each with a name, a line on what it is and a switch: Routing groups, Library, Observability, Sessions, Warm-up and check-in, and the Gateway and Routing pages (Essential). A plugin on with settings has their rows under its row, drawn from its schema by the kernel's `ui.form`, and a change posts `{id, config}`. The Gateway page is drawn by its plugin's own scripts through the window's kernel (`kernel.js`, `assets/plugins/gateway/`); see the [plugin runtime](plugin-runtime.md), "The window's kernel". They are `plugins/*` registered with the [plugin runtime](plugin-runtime.md); `GET /api/plugins/builtin` says each one (`builtinJSON`: on is active, the user's own choice, what of it is in use) and `POST {id, on}` (or `{id, config}`) writes plugins.yml. A page marks what goes with a plugin `data-feature="<id>"`. Off, `featureStyle` hides everything so marked (rows drawn later too), `navHides` leaves its page's tab out of the sidebar and the header, `show` opens Agents for an address kept for it, and `setSetTab`, `partShows` and `findSettings` leave its Settings tab and rows out, of the search too. One in use stays on: its switch is disabled and the row says what uses it, and the POST refuses it off. A plugins.yml that doesn't parse is said above the list and no switch moves. `boot.js` says which are off (`featuresOff`) and their settings (`pluginConfig`) before the first paint, and `settings.builtins` carries the list on every state read. The TUI doesn't follow them. See `builtins.test.cjs`, `builtins_test.go`. | [`builtins.go`](../../internal/gui/builtins.go), [`assets/plugins.js`](../../internal/gui/assets/plugins.js), [`assets/app.js`](../../internal/gui/assets/app.js) || No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) || The terminal quitting | `magpie tui` that served the gateway with an agent connected hands the gateway on as it quits, on Linux where nothing opens magpie at login (a WSL distro, a server over SSH; zaidu259434 on X): `keepGateway` starts magpie's service when it is installed, installs it (`daemon.Install`) when the user never removed it (`daemon.Removed`, a mark `magpie daemon uninstall` leaves), and otherwise starts `magpie serve` in its own session (`serveInBackground`, log in magpie's cache). Elsewhere, with nothing connected, or where magpie opens at login, it only says the gateway stopped. | [`keep.go`](../../internal/tui/keep.go) |diff --git a/internal/cli/main.go b/internal/cli/main.goindex d1a3408e3..0445745bc 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -133,6 +133,7 @@ const usage = `magpie — one place to pick every agent's modelmagpie sessions [--model <m>] [--folder <f>] [--json] the latest Claude Code, Codex, OpenCode and Pi sessions, with what each costmagpie sessions --days N|today|all [--model <m>] [--folder <f>] [--json]what every session spent, day by day, with the top models and folders (7 days)+ magpie sessions read [on|off all|<agent>…] which agents' session history magpie may read (none until allowed)magpie quota [<provider>] [--json] what is left of every subscription, plan and key balancemagpie quota wait <provider|account> [--timeout <d>] [--quiet]block until that subscription (any of its accounts) or account has allowance againdiff --git a/internal/cli/sessions_cli.go b/internal/cli/sessions_cli.goindex f3d4bf609..a43e9f281 100644--- a/internal/cli/sessions_cli.go+++ b/internal/cli/sessions_cli.go@@ -6,6 +6,7 @@ import ("io""os""path/filepath"+ "slices""strconv""strings""time"@@ -24,9 +25,87 @@ func sessionsCmd(args []string) error {if len(args) > 1 && args[1] == "relocate-claude" {return relocateClaudeTo(os.Stdout, args[2:])}+ if len(args) > 1 && args[1] == "read" {+ return sessionReadsTo(os.Stdout, args[2:])+ }+ if r := sessions.SettleReads(); !r.Asked {+ fmt.Fprintln(os.Stderr, notAskedLine)+ }return sessionsTo(os.Stdout, args[1:], time.Now())}+const sessionReadsUsage = "usage: magpie sessions read [on|off all|<agent>...]"++// notAskedLine: a fresh install reads no agent's sessions until the user+// allows it (RustCats on X), so an empty list says why.+const notAskedLine = "magpie reads no agent's session history until you allow it: magpie sessions read on all (or on <agent>…), or the Sessions page"++// sessionReadsTo: `magpie sessions read` — which agents' session history+// magpie may read, as the Sessions page's consent and Settings › Privacy+// set it; `read on|off all|<agent>…` changes it. "all" is every agent,+// those found later too.+func sessionReadsTo(w io.Writer, args []string) error {+ if len(args) == 0 {+ r := sessions.SettleReads()+ switch {+ case !r.Asked:+ fmt.Fprintln(w, "Not asked yet: no agent's sessions are read.")+ case r.All:+ fmt.Fprintln(w, "Agents found later: read")+ default:+ fmt.Fprintln(w, "Agents found later: not read")+ }+ names := agentNames()+ found := sessions.Found()+ for a := range r.Agents {+ if !slices.Contains(found, a) {+ found = append(found, a)+ }+ }+ slices.Sort(found)+ for _, a := range found {+ name := names[a]+ if name == "" {+ name = a+ }+ on := "off"+ if r.Reads(a) {+ on = "on"+ }+ fmt.Fprintf(w, " %-3s %s (%s)\n", on, name, a)+ }+ return nil+ }+ if len(args) < 2 || (args[0] != "on" && args[0] != "off") {+ return fmt.Errorf("%s", sessionReadsUsage)+ }+ on := args[0] == "on"+ var all *bool+ agents := map[string]bool{}+ known := agentNames()+ for _, a := range args[1:] {+ if a == "all" {+ all = &on+ // "off all" turns off the agents named before too+ for _, f := range sessions.Found() {+ agents[f] = on+ }+ continue+ }+ if strings.HasPrefix(a, "-") {+ return fmt.Errorf("%s", sessionReadsUsage)+ }+ if _, ok := known[a]; !ok && !slices.Contains(sessions.Found(), a) {+ return fmt.Errorf("unknown agent %q (magpie sessions read lists them)\n%s", a, sessionReadsUsage)+ }+ agents[a] = on+ }+ if err := sessions.SetReads(all, agents); err != nil {+ return err+ }+ return sessionReadsTo(w, nil)+}+func relocateClaudeTo(w io.Writer, args []string) error {const usage = "usage: magpie sessions relocate-claude --from <absolute-path> --to <absolute-path> [--confirm <preview-token>]"var in sessions.ClaudeRelocationdiff --git a/internal/cli/sessions_read_cli_test.go b/internal/cli/sessions_read_cli_test.gonew file mode 100644index 000000000..bcaee5071--- /dev/null+++ b/internal/cli/sessions_read_cli_test.go@@ -0,0 +1,63 @@+package cli++import (+ "bytes"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/settings"+)++// magpie sessions read (RustCats on X): a fresh install reads no agent's+// sessions, so the list is empty and the agents found are off until+// `read on` allows them; `read off all` turns every one off again. A flag+// or an unknown agent is refused, never saved.+func TestSessionsRead(t *testing.T) {+ now := sessionsHome(t)+ // a fresh install as SettleReads leaves it: decided, not asked+ if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {+ return &settings.SessionReads{}+ }); err != nil {+ t.Fatal(err)+ }+ read := func(args ...string) (string, error) {+ var b bytes.Buffer+ err := sessionReadsTo(&b, args)+ return b.String(), err+ }+ out, err := read()+ if err != nil {+ t.Fatal(err)+ }+ wantAll(t, out, "Not asked yet", "off Claude Code (claude)", "off Codex (codex)")+ if l := runSessions(t, now); strings.Contains(l, "Fix login bug") || strings.Contains(l, "Add a README") {+ t.Fatalf("not asked, the list read sessions:\n%s", l)+ }++ out, err = read("on", "claude")+ if err != nil {+ t.Fatal(err)+ }+ wantAll(t, out, "Agents found later: not read", "on Claude Code (claude)", "off Codex (codex)")+ l := runSessions(t, now)+ if !strings.Contains(l, "Fix login bug") || strings.Contains(l, "Add a README") {+ t.Fatalf("claude allowed, the list:\n%s", l)+ }++ if _, err := read("off", "all"); err != nil {+ t.Fatal(err)+ }+ if l := runSessions(t, now); strings.Contains(l, "Fix login bug") {+ t.Fatalf("off all, the list still read claude:\n%s", l)+ }++ before := settings.Load().SessionReads+ for _, bad := range [][]string{{"--help"}, {"on"}, {"on", "--help"}, {"on", "no-such-agent"}, {"maybe", "claude"}} {+ if _, err := read(bad...); err == nil || !strings.Contains(err.Error(), "usage: magpie sessions read") {+ t.Errorf("read %v: %v, want the usage", bad, err)+ }+ }+ if after := settings.Load().SessionReads; after.All != before.All || len(after.Agents) != len(before.Agents) {+ t.Errorf("a refused command changed the choice: %+v to %+v", before, after)+ }+}diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex c6579daff..62584d578 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -19470,6 +19470,8 @@ function setSetTab(tab, remember) {$("#setPage-" + id).hidden = !on;}setShown = tab;+ // each agent's row is read only where it is shown+ if (view === "settings" && tab === "privacy" && !setQuery) loadSessionReads();$("#setTabs").setAttribute("aria-label", t("Settings"));$("#setQ").setAttribute("aria-label", t("Find a setting"));if (view === "settings") syncURL();@@ -19812,6 +19814,7 @@ function renderSettings() {renderDisabledModels(s);renderRedact(s, keep);renderDiscovery(s);+ renderSessionReads(s);renderOTel(s, keep);renderPort(s);renderBareIds(s);@@ -21775,6 +21778,59 @@ function renderDiscovery(s) {r.append(who, val);box.replaceChildren(r);}+// renderSessionReads: which agents' own session history magpie reads+// (RustCats on X: a new install showed every agent's sessions before+// anyone agreed). The Sessions page asks once; here it changes later.+// "Agents found later" is whether an agent with no row of its own is+// read, and drawn from the settings at once; each agent found on this+// computer has a row of its own, read from /api/sessions/reads when the+// Privacy part is shown (loadSessionReads).+let sessionReads = null; // /api/sessions/reads, as last read+let sessionReadsSeq = 0;+function renderSessionReads(s) {+ const box = $("#sessionReadsList");+ const r = sessionReads || { asked: !!s?.sessionReads?.asked, all: !!s?.sessionReads?.all, found: [] };+ const save = (body) => {+ const n = ++sessionReadsSeq;+ writingPrefs(api("sessions/reads", body))+ .then((got) => { if (n === sessionReadsSeq) { sessionReads = got; renderSessionReads(prefs); } })+ .catch((e) => { status(t(e.message), "err"); renderSessionReads(prefs); });+ };+ const row = (name, sub, on, fn) => {+ const rw = el("div", "row pref");+ const who = el("div", "who");+ who.append(el("div", "name", name));+ if (sub) who.append(el("div", "sub", sub));+ const val = el("div", "val");+ val.append(segs([["off", t("Off")], ["on", t("On")]], on ? "on" : "off", (v) => {+ if ((v === "on") !== on) fn(v === "on");+ }));+ rw.append(who, val);+ return rw;+ };+ const rows = [row(t("Agents found later"), t("Read the session history of an agent with no row here, one installed later too. Off, magpie reads only the agents turned on below; what its gateway served is counted either way"),+ r.asked && r.all, (on) => {+ // the agents with a row keep what their rows show+ const agents = {};+ for (const a of r.found || []) agents[a.agent] = !!a.on;+ save(Object.keys(agents).length ? { all: on, agents } : { all: on });+ })];+ for (const a of r.found || []) {+ const rw = row(a.name, "", a.on, (on) => save({ agents: { [a.agent]: on } }));+ rw.dataset.agent = a.agent;+ rows.push(rw);+ }+ box.replaceChildren(...rows);+}+function loadSessionReads() {+ const n = ++sessionReadsSeq;+ api("sessions/reads").then((got) => {+ if (n !== sessionReadsSeq) return;+ sessionReads = got;+ renderSessionReads(prefs);+ }).catch(() => {}); // the row drawn from the settings stays+}+// what turning discovery off stops: the subscriptions signed in now, by// name, the Providers list read for it when no page has yetasync function discoveryOffWarning() {diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 29134d441..b6689b5c3 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1031,6 +1031,9 @@ const I18N = {"Allowance display": "额度显示","Allowance reads": "额度刷新","Agents' sign-ins": "智能体登录",+ "Agents' session history": "智能体的会话历史",+ "Agents found later": "之后发现的智能体",+ "Read the session history of an agent with no row here, one installed later too. Off, magpie reads only the agents turned on below; what its gateway served is counted either way": "读取这里没有单独一行的智能体的会话历史,包括之后安装的。关闭时,magpie 只读取下面开启的智能体;网关处理过的请求照常计入","Subscription accounts": "订阅账号","Turn off subscription accounts?": "关闭订阅账号?","Turn them off": "关闭",@@ -5151,6 +5154,9 @@ const I18N = {"Allowance display": "額度顯示","Allowance reads": "額度重新整理","Agents' sign-ins": "智慧體登入",+ "Agents' session history": "智慧體的會話歷史",+ "Agents found later": "之後發現的智慧體",+ "Read the session history of an agent with no row here, one installed later too. Off, magpie reads only the agents turned on below; what its gateway served is counted either way": "讀取這裡沒有單獨一行的智慧體的會話歷史,包括之後安裝的。關閉時,magpie 只讀取下面開啟的智慧體;閘道處理過的請求照常計入","Subscription accounts": "訂閱帳號","Turn off subscription accounts?": "關閉訂閱帳號?","Turn them off": "關閉",@@ -9233,6 +9239,9 @@ const I18N = {"Allowance display": "利用枠の表示","Allowance reads": "利用枠の読み込み","Agents' sign-ins": "エージェントのサインイン",+ "Agents' session history": "エージェントのセッション履歴",+ "Agents found later": "あとで見つかったエージェント",+ "Read the session history of an agent with no row here, one installed later too. Off, magpie reads only the agents turned on below; what its gateway served is counted either way": "ここに行のないエージェント(あとでインストールしたものも含む)のセッション履歴を読みます。オフでは、magpie は下でオンにしたエージェントだけを読みます。ゲートウェイが処理したリクエストはどちらでも集計されます","Subscription accounts": "サブスクリプションアカウント","Turn off subscription accounts?": "サブスクリプションアカウントをオフにしますか?","Turn them off": "オフにする",@@ -13349,6 +13358,9 @@ const I18N = {"Allowance display": "Kontingentanzeige","Allowance reads": "Kontingente abrufen","Agents' sign-ins": "Anmeldungen der Agenten",+ "Agents' session history": "Sitzungsverlauf der Agenten",+ "Agents found later": "Später gefundene Agenten",+ "Read the session history of an agent with no row here, one installed later too. Off, magpie reads only the agents turned on below; what its gateway served is counted either way": "Liest den Sitzungsverlauf eines Agenten ohne eigene Zeile hier, auch eines später installierten. Aus liest magpie nur die unten eingeschalteten Agenten; was das Gateway bedient hat, wird so oder so gezählt","Subscription accounts": "Abo-Konten","Turn off subscription accounts?": "Abo-Konten ausschalten?","Turn them off": "Ausschalten",diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.htmlindex 60557730d..13d7049bd 100644--- a/internal/gui/assets/index.html+++ b/internal/gui/assets/index.html@@ -427,6 +427,8 @@<div class="list prefs" id="shareList"></div><div class="row-head"><span class="label" data-t>Agents' sign-ins</span></div><div class="list prefs" id="discoveryList"></div>+ <div class="row-head"><span class="label" data-t>Agents' session history</span></div>+ <div class="list prefs" id="sessionReadsList"></div></section><section class="set-page" id="setPage-otel" role="tabpanel" aria-labelledby="setTab-otel" data-feature="otel"><div id="otelList"></div>diff --git a/internal/gui/assets/plugins/sessions/client.js b/internal/gui/assets/plugins/sessions/client.jsindex 491a6fb03..b1723a33c 100644--- a/internal/gui/assets/plugins/sessions/client.js+++ b/internal/gui/assets/plugins/sessions/client.js@@ -60,6 +60,10 @@ magpie.plugin("sessions", (ctx) => {let fitObserver = null;let focus = null; // { agent, id, until }: a session to bring into sight once drawnlet recordingBusy = false;+ // the agents picked in the consent (RustCats on X), by id, and whether+ // the choice is being saved+ const consentPicked = new Set();+ let consentBusy = false;// An open folder draws its latest SM_PAGE sessions and a "Show N more"// that adds the next page where it is (ChildhoodAndy on X: with thousands// of sessions, switching to the page or to another agent, a keystroke in@@ -355,6 +359,82 @@ magpie.plugin("sessions", (ctx) => {return card;}+ // The consent (RustCats on X: a new install showed every agent's history+ // before anyone agreed to it). Until the reader says which agents'+ // sessions magpie may read (data.reads.asked), it reads none of them and+ // this card comes first: the agents found here, each with its own+ // switch, off; Allow selected reads those picked, and Allow all every+ // agent, those found later too. Settings › Privacy changes it later.+ const consentApplies = () => data?.reads && data.reads.asked === false;++ function consentCard() {+ const found = data.reads.found || [];+ const card = el("div", "sm-consent");+ const title = el("b", "sm-consent-title", t("Show your agents' sessions?"));+ title.id = "smConsentTitle";+ card.setAttribute("role", "group");+ card.setAttribute("aria-labelledby", title.id);+ card.append(title, el("p", "sm-consent-sub", t("magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.")));+ if (found.length) {+ const list = el("div", "list sm-consent-list");+ for (const x of found) {+ const on = consentPicked.has(x.agent);+ const row = el("div", "row sm-consent-row");+ const name = el("span", "sm-consent-name", x.name);+ name.id = "smConsent-" + x.agent;+ const sw = el("button", "lib-switch" + (on ? " on" : ""));+ sw.type = "button";+ sw.setAttribute("role", "switch");+ sw.setAttribute("aria-checked", String(on));+ sw.setAttribute("aria-labelledby", name.id);+ sw.disabled = consentBusy;+ sw.append(el("i"));+ sw.onclick = (e) => {+ e.stopPropagation();+ if (consentPicked.has(x.agent)) consentPicked.delete(x.agent); else consentPicked.add(x.agent);+ const now = consentPicked.has(x.agent);+ sw.classList.toggle("on", now);+ sw.setAttribute("aria-checked", String(now));+ const some = card.querySelector(".sm-consent-some");+ if (some) some.disabled = consentBusy || !consentPicked.size;+ };+ row.onclick = () => sw.click();+ row.append(icon(x.icon), name, sw);+ list.append(row);+ }+ card.append(list);+ } else {+ card.append(el("p", "sm-consent-none", t("No agent's sessions were found on this computer yet.")));+ }+ const acts = el("div", "sm-consent-acts");+ const save = async (all) => {+ consentBusy = true;+ draw();+ const agents = {};+ for (const x of found) agents[x.agent] = all || consentPicked.has(x.agent);+ try {+ await api("sessions/reads", { all, agents });+ consentPicked.clear();+ await load();+ } catch (err) { status(err.message, "err"); }+ finally { consentBusy = false; draw(); }+ };+ if (found.length) {+ const some = el("button", "text sm-consent-some", t("Allow selected"));+ some.type = "button";+ some.disabled = consentBusy || !consentPicked.size;+ some.onclick = () => save(false);+ acts.append(some);+ }+ const all = el("button", "text primary sm-consent-all", t("Allow all"));+ all.type = "button";+ all.disabled = consentBusy;+ all.onclick = () => save(true);+ acts.append(all);+ card.append(acts);+ return card;+ }+function head() {const h = el("div", "usage-head sm-head");const wrap = el("div", "sm-switch");@@ -429,8 +509,10 @@ magpie.plugin("sessions", (ctx) => {return box;}if (trashOn) { box.append(...trash()); return box; }+ if (consentApplies()) box.append(consentCard());if (recordingApplies()) box.append(recordingCard());if (!data.agents.length) {+ if (consentApplies()) return box;const e = el("div", "empty-state");e.append(el("b", "", t("No sessions yet")), el("span", "", t("Claude Code's, Codex's, Hermes's, OpenCode's and Pi's sessions on this computer show up here, by the folder they ran in.")));box.append(e);diff --git a/internal/gui/assets/plugins/sessions/i18n.js b/internal/gui/assets/plugins/sessions/i18n.jsindex 6f29e932a..b38435683 100644--- a/internal/gui/assets/plugins/sessions/i18n.js+++ b/internal/gui/assets/plugins/sessions/i18n.js@@ -2,6 +2,11 @@// kernel adds them to i18n.js's (magpie.strings).magpie.strings({zh: {+ "Show your agents' sessions?": "显示智能体的会话吗?",+ "magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "在你允许之前,magpie 不读取任何智能体的会话历史。选择本页可以显示哪些智能体的会话;magpie 网关处理过的请求照常计入。之后可在 设置 › 隐私 中更改。",+ "No agent's sessions were found on this computer yet.": "这台电脑上还没有找到任何智能体的会话。",+ "Allow selected": "允许所选",+ "Allow all": "全部允许","Other folders": "其他文件夹","Temporary folders, the disk's root and apps' hidden folders": "临时文件夹、磁盘根目录和应用的隐藏文件夹","Delete all sessions": "删除全部会话",@@ -81,6 +86,11 @@ magpie.strings({"Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。",},"zh-TW": {+ "Show your agents' sessions?": "顯示智慧體的會話嗎?",+ "magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "在你允許之前,magpie 不讀取任何智慧體的會話歷史。選擇本頁可以顯示哪些智慧體的會話;magpie 閘道處理過的請求照常計入。之後可在 設定 › 隱私 中變更。",+ "No agent's sessions were found on this computer yet.": "這台電腦上還沒有找到任何智慧體的會話。",+ "Allow selected": "允許所選",+ "Allow all": "全部允許","Other folders": "其他資料夾","Temporary folders, the disk's root and apps' hidden folders": "暫存資料夾、磁碟根目錄和應用程式的隱藏資料夾","Delete all sessions": "刪除全部會話",@@ -160,6 +170,11 @@ magpie.strings({"Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。",},ja: {+ "Show your agents' sessions?": "エージェントのセッションを表示しますか?",+ "magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "許可するまで、magpie はどのエージェントのセッション履歴も読みません。このページに表示してよいエージェントを選んでください。magpie のゲートウェイが処理したリクエストはどちらでも集計されます。あとから 設定 › プライバシー で変更できます。",+ "No agent's sessions were found on this computer yet.": "このコンピュータにはまだエージェントのセッションが見つかりません。",+ "Allow selected": "選択したものを許可",+ "Allow all": "すべて許可","Other folders": "その他のフォルダ","Temporary folders, the disk's root and apps' hidden folders": "一時フォルダ、ディスクのルート、アプリの隠しフォルダ","Delete all sessions": "すべてのセッションを削除",@@ -239,6 +254,11 @@ magpie.strings({"Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。",},de: {+ "Show your agents' sessions?": "Sitzungen deiner Agenten anzeigen?",+ "magpie reads no agent's session history until you allow it. Pick the agents whose sessions this page may show; what magpie's gateway served is counted either way. You can change this in Settings › Privacy.": "magpie liest den Sitzungsverlauf keines Agenten, bis du es erlaubst. Wähle die Agenten, deren Sitzungen diese Seite zeigen darf; was das Gateway von magpie bedient hat, wird so oder so gezählt. Ändern kannst du das unter Einstellungen › Datenschutz.",+ "No agent's sessions were found on this computer yet.": "Auf diesem Computer wurden noch keine Sitzungen von Agenten gefunden.",+ "Allow selected": "Ausgewählte erlauben",+ "Allow all": "Alle erlauben","Other folders": "Weitere Ordner","Temporary folders, the disk's root and apps' hidden folders": "Temporäre Ordner, das Stammverzeichnis und versteckte Ordner von Apps","Delete all sessions": "Alle Sitzungen löschen",diff --git a/internal/gui/assets/plugins/sessions/sessions.css b/internal/gui/assets/plugins/sessions/sessions.cssindex dc6e902c5..8bbab369a 100644--- a/internal/gui/assets/plugins/sessions/sessions.css+++ b/internal/gui/assets/plugins/sessions/sessions.css@@ -151,3 +151,16 @@ body.window .row.sm-sub-row { min-height: 42px; padding-left: calc(14px + var(--@media (max-width: 560px) {.sm-subs { --sub-step: 10px; padding-left: calc(12px + var(--sub-depth, 0) * var(--sub-step)); padding-right: 8px; }}++/* the consent (RustCats on X): which agents' sessions may be read, asked+ before any is; a plain grouped list of switches, as System Settings */+.sm-consent { display: flex; flex-direction: column; gap: 10px; max-width: 560px; margin: 8px auto 16px; padding: 18px 18px 16px; border-radius: 12px; background: var(--card, var(--bg)); box-shadow: 0 0 0 0.5px var(--line); }+.sm-consent-title { font-size: 14px; font-weight: 600; color: var(--fg); }+.sm-consent-sub, .sm-consent-none { margin: 0; font-size: 12px; line-height: 1.5; color: var(--muted); }+.sm-consent-list { margin: 2px 0 0; }+.sm-consent-row { display: flex; align-items: center; gap: 10px; min-height: 36px; padding: 6px 12px; cursor: pointer; }+.sm-consent-row > svg, .sm-consent-row > img { flex: none; width: 16px; height: 16px; }+.sm-consent-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12.5px; color: var(--fg); }+.sm-consent-row .lib-switch { flex: none; cursor: pointer; padding: 0; border: 0; }+.sm-consent-row .lib-switch:disabled { opacity: .5; cursor: default; }+.sm-consent-acts { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; margin-top: 4px; }diff --git a/internal/gui/sessions.go b/internal/gui/sessions.goindex 0d4476462..b95363ebd 100644--- a/internal/gui/sessions.go+++ b/internal/gui/sessions.go@@ -580,6 +580,9 @@ var warmOnce sync.Oncefunc warmStart() {go func() {+ // a fresh install reads no agent's sessions until asked; one+ // that read them before keeps reading them (decided once)+ sessions.SettleReads()time.Sleep(3 * time.Second)// with few readers, as nobody waits on it yet: after an update// that reads every file again, it held every core (#1665)diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.goindex a27bd9ae6..be2f70e05 100644--- a/internal/gui/sessions_manage.go+++ b/internal/gui/sessions_manage.go@@ -82,6 +82,7 @@ func trashJSON(looks map[string]*agent.Agent) []trashedJSON {}func sessionManageRoutes(mux *http.ServeMux, w Windows) {+ sessionReadsRoutes(mux)mux.HandleFunc("POST /api/sessions/relocate-claude", func(rw http.ResponseWriter, r *http.Request) {var in sessions.ClaudeRelocationif err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 16384)).Decode(&in); err != nil {@@ -133,7 +134,10 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {Recording bool `json:"recording"`// Recorded: some gateway conversation text is kept, to deleteRecorded bool `json:"recorded"`- }{Agents: []manageAgentJSON{}, Sessions: []managedJSON{}, Terminal: runtime.GOOS == "darwin" && !isWeb(w),+ // Reads: which agents' own sessions magpie may read; the page+ // asks first when nothing is decided (asked false)+ Reads readsJSON `json:"reads"`+ }{Reads: readsNow(), Agents: []manageAgentJSON{}, Sessions: []managedJSON{}, Terminal: runtime.GOOS == "darwin" && !isWeb(w),Trash: trashJSON(looks), TrashDir: tilde(sessions.TrashDir()), Recording: settings.Load().GatewayConversations,Recorded: sessions.HasGatewayConversations()}out.Home, _ = os.UserHomeDir()diff --git a/internal/gui/sessions_reads.go b/internal/gui/sessions_reads.gonew file mode 100644index 000000000..abb9eb5ce--- /dev/null+++ b/internal/gui/sessions_reads.go@@ -0,0 +1,87 @@+package gui++import (+ "encoding/json"+ "net/http"+ "slices"+ "sort"++ "github.com/yetone/magpie/internal/sessions"+ "github.com/yetone/magpie/internal/settings"+)++// Which agents' session history magpie may read (RustCats on X): the+// Sessions page asks once on a fresh install, and Settings changes it per+// agent later. sessions.Reads is the gate every reader asks.++type readAgentJSON struct {+ Agent string `json:"agent"`+ Name string `json:"name"`+ Icon string `json:"icon"`+ On bool `json:"on"`+}++type readsJSON struct {+ // Asked: the user said which agents may be read (or the install read+ // them all before there was a choice)+ Asked bool `json:"asked"`+ // All: every agent, those found later too, unless one is turned off+ All bool `json:"all"`+ // Found: the agents with session history on this computer, and those+ // the user named+ Found []readAgentJSON `json:"found"`+}++func readsNow() readsJSON {+ r := sessions.SettleReads()+ if s := settings.Shared().SessionReads; s != nil {+ r = s+ }+ out := readsJSON{Found: []readAgentJSON{}}+ if r != nil {+ out.Asked, out.All = r.Asked, r.All+ }+ agents := sessions.Found()+ if r != nil {+ for a := range r.Agents {+ if !slices.Contains(agents, a) {+ agents = append(agents, a)+ }+ }+ }+ looks := agentLooks()+ for _, a := range agents {+ j := readAgentJSON{Agent: a, Name: a, Icon: "generic", On: r.Reads(a)}+ if l := looks[a]; l != nil {+ j.Name, j.Icon = l.SharedName(), l.Icon+ }+ out.Found = append(out.Found, j)+ }+ sort.SliceStable(out.Found, func(i, j int) bool { return out.Found[i].Name < out.Found[j].Name })+ return out+}++func sessionReadsRoutes(mux *http.ServeMux) {+ mux.HandleFunc("GET /api/sessions/reads", func(rw http.ResponseWriter, r *http.Request) {+ writeJSON(rw, readsNow())+ })+ // {all, agents: {id: on}}: all, when sent, is whether an agent not+ // named is read (allow all sends true, allow selected false), and each+ // agent named is read or not; either way the choice is made (asked).+ mux.HandleFunc("POST /api/sessions/reads", func(rw http.ResponseWriter, r *http.Request) {+ var in struct {+ All *bool `json:"all"`+ Agents map[string]bool `json:"agents"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(rw, r.Body, 16384)).Decode(&in); err != nil {+ fail(rw, err)+ return+ }+ if err := sessions.SetReads(in.All, in.Agents); err != nil {+ fail(rw, err)+ return+ }+ forgetStats()+ writeJSON(rw, readsNow())+ })+}diff --git a/internal/gui/sessions_reads_test.go b/internal/gui/sessions_reads_test.gonew file mode 100644index 000000000..4188a3c2e--- /dev/null+++ b/internal/gui/sessions_reads_test.go@@ -0,0 +1,96 @@+package gui++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/sessions"+ "github.com/yetone/magpie/internal/settings"+)++// The Sessions page's consent and Settings' rows (RustCats on X): a fresh+// install's /api/sessions/reads lists the agents found, none on, and+// sessions/manage lists no session until one is allowed; allow selected+// reads that agent only, and Settings turns it off again.+func TestSessionReadsRoutes(t *testing.T) {+ h := sandboxHome(t)+ claude := filepath.Join(h, ".claude")+ t.Setenv("CLAUDE_CONFIG_DIR", claude)+ f := filepath.Join(claude, "projects", "-work-app", "sess1.jsonl")+ if err := os.MkdirAll(filepath.Dir(f), 0o755); err != nil {+ t.Fatal(err)+ }+ line := `{"type":"user","timestamp":"2026-09-20T10:00:00Z","message":{"role":"user","content":"my secret plan"},"cwd":"/work/app","sessionId":"sess1"}`+ if err := os.WriteFile(f, []byte(line+"\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ // a fresh install as SettleReads leaves it: decided, not asked+ if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {+ return &settings.SessionReads{}+ }); err != nil {+ t.Fatal(err)+ }+ sessions.Reset()+ t.Cleanup(sessions.Reset)++ mux := http.NewServeMux()+ sessionManageRoutes(mux, folderOnly{})+ call := func(method, path, body string) []byte {+ t.Helper()+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))+ if w.Code != 200 {+ t.Fatalf("%s %s: %d %s", method, path, w.Code, w.Body)+ }+ return w.Body.Bytes()+ }+ var r readsJSON+ json.Unmarshal(call("GET", "/api/sessions/reads", ""), &r)+ if r.Asked || r.All || len(r.Found) != 1 || r.Found[0].Agent != "claude" || r.Found[0].On {+ t.Fatalf("fresh reads = %+v, want claude found and off", r)+ }+ type manage struct {+ Sessions []struct {+ ID string `json:"id"`+ } `json:"sessions"`+ Reads readsJSON `json:"reads"`+ }+ var m manage+ json.Unmarshal(call("GET", "/api/sessions/manage", ""), &m)+ if len(m.Sessions) != 0 || m.Reads.Asked || len(m.Reads.Found) != 1 {+ t.Fatalf("not asked: manage = %+v", m)+ }+ if strings.Contains(string(call("GET", "/api/sessions/manage", "")), "secret") {+ t.Fatal("manage carries the session's text before it was allowed")+ }++ // allow selected, Claude Code on+ json.Unmarshal(call("POST", "/api/sessions/reads", `{"all":false,"agents":{"claude":true}}`), &r)+ if !r.Asked || r.All || !r.Found[0].On {+ t.Fatalf("after allow selected: %+v", r)+ }+ m = manage{}+ json.Unmarshal(call("GET", "/api/sessions/manage", ""), &m)+ if len(m.Sessions) != 1 || m.Sessions[0].ID != "sess1" {+ t.Fatalf("claude allowed: manage = %+v", m)+ }++ // Settings turns it off+ json.Unmarshal(call("POST", "/api/sessions/reads", `{"agents":{"claude":false}}`), &r)+ m = manage{}+ json.Unmarshal(call("GET", "/api/sessions/manage", ""), &m)+ if len(m.Sessions) != 0 || !m.Reads.Asked || m.Reads.Found[0].On {+ t.Fatalf("claude turned off: manage = %+v", m)+ }++ w := httptest.NewRecorder()+ mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/sessions/reads", strings.NewReader("{")))+ if w.Code == 200 {+ t.Fatal("a body that isn't JSON was taken")+ }+}diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.goindex d284771f8..2caae0fd1 100644--- a/internal/gui/settings_keep_test.go+++ b/internal/gui/settings_keep_test.go@@ -198,6 +198,12 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {if err := settings.SetGatewayConversations(true); err != nil {t.Fatal(err)}+ // only SetSessionReads writes the agents whose sessions are read+ if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {+ return &settings.SessionReads{Asked: true, Agents: map[string]bool{"claude": true, "codex": false}}+ }); err != nil {+ t.Fatal(err)+ }was = settings.Load()rec := httptest.NewRecorder()Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(`{"theme":"dark"}`)))diff --git a/internal/gui/tests/account-discovery.test.cjs b/internal/gui/tests/account-discovery.test.cjsindex dfea58396..133f464b6 100644--- a/internal/gui/tests/account-discovery.test.cjs+++ b/internal/gui/tests/account-discovery.test.cjs@@ -103,7 +103,8 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",const { context, page, errors } = await open(browser, lang, width, posts);const box = page.locator("#discoveryList");const opts = box.locator(".opt");- assert.equal((await page.locator("#setPage-privacy .row-head .label").last().textContent()).trim(), head);+ // the heading right above the list (Agents' session history follows it)+ assert.equal((await box.evaluate((b) => b.previousElementSibling.querySelector(".label").textContent)).trim(), head);assert.equal((await box.locator(".name").textContent()).trim(), name);const sub = (await box.locator(".sub").textContent()).trim();assert(sub.includes("Claude Code") && sub.includes("Codex"), "the sub names what is read: " + sub);diff --git a/internal/gui/tests/sessions-reads.test.cjs b/internal/gui/tests/sessions-reads.test.cjsnew file mode 100644index 000000000..7604255fa--- /dev/null+++ b/internal/gui/tests/sessions-reads.test.cjs@@ -0,0 +1,190 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// Which agents' session history magpie reads (RustCats on X: a new+// install showed every agent's history before anyone agreed). Until the+// user says (sessions/manage's reads.asked false), the Sessions page shows+// the consent first: the agents found, each with a switch of its own, off;+// Allow selected stays off until one is picked and saves those picked,+// Allow all saves every agent and those found later. Settings › Privacy+// has a row for agents found later and one per agent, each saved alone.+// Every language, Chromium and WebKit, a narrow window; the API is faked.+const assert = require("node:assert/strict");+const fs = require("node:fs/promises");+const path = require("node:path");+const { test } = require("node:test");+const { chromium, webkit } = require("playwright");++const assets = path.resolve(__dirname, "../assets");+const at = (min) => new Date(Date.now() - min * 60e3).toISOString();+const found = () => [+ { agent: "claude", name: "Claude Code", icon: "claudecode-color", on: false },+ { agent: "codex", name: "Codex", icon: "codex", on: false },+];++function serve(lang, store, posts) {+ return async (route) => {+ const req = route.request(), url = new URL(req.url());+ const json = (data) => route.fulfill({ json: data });+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light", sessionReads: { asked: store.asked, all: store.all } } });+ if (url.pathname === "/api/settings") return json({ lang, theme: "light" });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });+ if (url.pathname === "/api/sessions/reads") {+ if (req.method() === "POST") {+ const b = req.postDataJSON();+ posts.push(b);+ store.asked = true;+ if (typeof b.all === "boolean") store.all = b.all;+ for (const f of store.found) if (b.agents && f.agent in b.agents) f.on = b.agents[f.agent];+ }+ for (const p of posts) for (const a in p.agents || {}) store.named[a] = true;+ for (const f of store.found) if (!(f.agent in store.named)) f.on = store.asked && store.all;+ return json({ asked: store.asked, all: store.all, found: store.found });+ }+ if (url.pathname === "/api/sessions/manage") {+ const on = store.found.filter((f) => store.asked && f.on);+ const agents = on.map((f) => ({ agent: f.agent, count: 1, deletable: true, name: f.name, icon: f.icon }));+ const agent = agents[0]?.agent || "";+ const sessions = agent ? [{ agent, id: agent + "-1", cwd: "/work/app", title: "a " + agent + " chat", start: at(10), last: at(5), models: [], resume: "", path: "/x/" + agent, size: 10, messages: 2, files: 1, deletable: true }] : [];+ return json({ agents, agent, sessions, terminal: false, trash: [], trashDir: "", reads: { asked: store.asked, all: store.all, found: store.found } });+ }+ if (url.pathname.startsWith("/api/")) return json({});+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];+ try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }+ };+}++const words = {+ en: { nav: "Sessions", title: "Show your agents' sessions?", some: "Allow selected", all: "Allow all", head: "Agents' session history", later: "Agents found later", on: "On", off: "Off" },+ zh: { nav: "会话", title: "显示智能体的会话吗?", some: "允许所选", all: "全部允许", head: "智能体的会话历史", later: "之后发现的智能体", on: "开启", off: "关闭" },+ "zh-TW": { nav: "會話", title: "顯示智慧體的會話嗎?", some: "允許所選", all: "全部允許", head: "智慧體的會話歷史", later: "之後發現的智慧體", on: "開啟", off: "關閉" },+ ja: { nav: "セッション", title: "エージェントのセッションを表示しますか?", some: "選択したものを許可", all: "すべて許可", head: "エージェントのセッション履歴", later: "あとで見つかったエージェント", on: "オン", off: "オフ" },+ de: { nav: "Sitzungen", title: "Sitzungen deiner Agenten anzeigen?", some: "Ausgewählte erlauben", all: "Alle erlauben", head: "Sitzungsverlauf der Agenten", later: "Später gefundene Agenten", on: "An", off: "Aus" },+};++async function open(engine, width, t) {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));+ const context = await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" });+ const page = await context.newPage();+ const errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); });+ t.after(async () => {+ if (process.env.ARTIFACT_DIR) {+ await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });+ await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${t.name.replace(/[^\w-]+/g, "-")}.png`) }).catch(() => {});+ }+ await browser.close();+ });+ page.setDefaultTimeout(6000);+ return { page, errors };+}++// nothing in the card is cut off or wider than the window+async function fits(page, sel) {+ const over = await page.$eval(sel, (card) => {+ const vw = document.documentElement.clientWidth;+ const r = card.getBoundingClientRect();+ const bad = [...card.querySelectorAll("*")].filter((e) => { const b = e.getBoundingClientRect(); return b.width && (b.right > vw + 0.5 || b.left < -0.5); }).map((e) => e.className);+ return { right: r.right, vw, bad, scroll: document.documentElement.scrollWidth > vw };+ });+ assert.ok(over.right <= over.vw + 0.5 && !over.bad.length && !over.scroll, JSON.stringify(over));+}++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ for (const [lang, width] of [["en", 900], ["en", 390], ["zh", 420], ["zh-TW", 420], ["ja", 420], ["de", 390]]) {+ const w = words[lang];+ test(`${engine} ${lang} ${width}px: the Sessions page asks before reading any agent's sessions`, async (t) => {+ const { page, errors } = await open(engine, width, t);+ const store = { asked: false, all: false, found: found(), named: {} }, posts = [];+ await page.route("**/*", serve(lang, store, posts));+ await page.goto("http://magpie.test/?view=sessions");+ const card = page.locator("#view-sessions .sm-consent");+ await card.waitFor();+ assert.equal(await card.locator(".sm-consent-title").textContent(), w.title);+ assert.equal(await card.getAttribute("role"), "group");+ // no session is listed, and no empty state talks over the card+ assert.equal(await page.locator("#view-sessions .row.sm-sess").count(), 0);+ assert.equal(await page.locator("#view-sessions .empty-state").count(), 0);+ const sw = (name) => card.getByRole("switch", { name, exact: true });+ assert.equal(await sw("Claude Code").getAttribute("aria-checked"), "false");+ assert.equal(await sw("Codex").getAttribute("aria-checked"), "false");+ const some = card.getByRole("button", { name: w.some, exact: true });+ assert.ok(await some.isDisabled(), "Allow selected with nothing picked");+ await fits(page, "#view-sessions .sm-consent");+ // a click on the row's name flips its switch too+ await card.locator(".sm-consent-row", { hasText: "Claude Code" }).locator(".sm-consent-name").click();+ assert.equal(await sw("Claude Code").getAttribute("aria-checked"), "true");+ assert.ok(await some.isEnabled());+ await sw("Codex").click();+ await sw("Codex").click();+ assert.equal(await sw("Codex").getAttribute("aria-checked"), "false");+ assert.equal(posts.length, 0, "nothing is saved before a button is pressed");+ await some.click();+ await card.waitFor({ state: "detached" });+ assert.deepEqual(posts, [{ all: false, agents: { claude: true, codex: false } }]);+ await page.locator('#view-sessions .row.sm-sess[data-id="claude-1"]').waitFor();+ assert.deepEqual(errors, []);+ });+ }+ test(`${engine} en 390px: Allow all reads every agent, those found later too`, async (t) => {+ const { page, errors } = await open(engine, 390, t);+ const store = { asked: false, all: false, found: found(), named: {} }, posts = [];+ await page.route("**/*", serve("en", store, posts));+ await page.goto("http://magpie.test/?view=sessions");+ const card = page.locator("#view-sessions .sm-consent");+ await card.getByRole("button", { name: "Allow all", exact: true }).click();+ await card.waitFor({ state: "detached" });+ assert.deepEqual(posts, [{ all: true, agents: { claude: true, codex: true } }]);+ await page.locator("#view-sessions .row.sm-sess").first().waitFor();+ assert.deepEqual(errors, []);+ });+ test(`${engine} en: no agent found, the consent says so and still offers Allow all`, async (t) => {+ const { page, errors } = await open(engine, 900, t);+ const store = { asked: false, all: false, found: [], named: {} }, posts = [];+ await page.route("**/*", serve("en", store, posts));+ await page.goto("http://magpie.test/?view=sessions");+ const card = page.locator("#view-sessions .sm-consent");+ await card.locator(".sm-consent-none").waitFor();+ assert.equal(await card.getByRole("button", { name: "Allow selected" }).count(), 0);+ assert.equal(await card.getByRole("button", { name: "Allow all", exact: true }).count(), 1);+ assert.deepEqual(errors, []);+ });+ for (const [lang, width] of [["en", 900], ["zh", 420], ["zh-TW", 420], ["ja", 420], ["de", 390]]) {+ const w = words[lang];+ test(`${engine} ${lang} ${width}px: Settings › Privacy changes each agent's reading later`, async (t) => {+ const { page, errors } = await open(engine, width, t);+ const store = { asked: true, all: true, found: found().map((f) => ({ ...f, on: true })), named: {} }, posts = [];+ await page.route("**/*", serve(lang, store, posts));+ await page.goto("http://magpie.test/?view=settings&tab=privacy");+ const list = page.locator("#sessionReadsList");+ await page.locator("#setPage-privacy .row-head .label", { hasText: w.head }).waitFor();+ const row = (sel) => list.locator(sel);+ await row('.row[data-agent="codex"]').waitFor();+ const later = list.locator(".row", { has: page.locator(".name", { hasText: w.later }) });+ const val = (r) => r.locator(".opt.on").textContent();+ assert.equal(await val(later), w.on);+ assert.equal(await val(row('.row[data-agent="claude"]')), w.on);+ assert.equal(await val(row('.row[data-agent="codex"]')), w.on);+ await fits(page, "#sessionReadsList");+ // a click scrolls the row into view itself, and finds it again when a+ // save has drawn the list anew+ const click = (r, name) => r.getByRole("button", { name, exact: true }).click();+ await click(row('.row[data-agent="codex"]'), w.off);+ for (let i = 0; i < 100 && !posts.length; i++) await page.waitForTimeout(50);+ assert.deepEqual(posts[0], { agents: { codex: false } });+ await page.waitForFunction((off) => document.querySelector('#sessionReadsList .row[data-agent="codex"] .opt.on')?.textContent === off, w.off);+ assert.equal(await val(row('.row[data-agent="claude"]')), w.on, "only the agent switched changed");+ await click(later, w.off);+ for (let i = 0; i < 100 && posts.length < 2; i++) await page.waitForTimeout(50);+ // the agents listed keep what their rows show+ assert.deepEqual(posts[1], { all: false, agents: { claude: true, codex: false } });+ await page.waitForFunction(([later, off]) => [...document.querySelectorAll("#sessionReadsList .row")].some((r) => r.querySelector(".name")?.textContent === later && r.querySelector(".opt.on")?.textContent === off), [w.later, w.off]);+ assert.equal(await val(row('.row[data-agent="claude"]')), w.on, "a listed agent keeps its row's value");+ assert.deepEqual(errors, []);+ });+ }+}diff --git a/internal/sessions/access.go b/internal/sessions/access.gonew file mode 100644index 000000000..317e5bbcd--- /dev/null+++ b/internal/sessions/access.go@@ -0,0 +1,213 @@+package sessions++import (+ "errors"+ "os"+ "path/filepath"+ "sync"+ "testing"++ "github.com/yetone/magpie/internal/settings"+)++// Which agents' session files magpie may read (RustCats on X: a new+// install showed every agent's history before anyone agreed to it). Reads+// is the one gate: every lister asks it before it lists an agent's+// folder, the listings are filtered by it again, and so are the readers+// that take a session or a call already listed (a cache made before a+// switch was turned off). A fresh install reads nothing until the+// Sessions page's consent, or Settings, allows an agent; an install that+// already read sessions keeps reading them all.++// ErrNotRead: the session's agent is one magpie may not read.+var ErrNotRead = errors.New("magpie is not allowed to read this agent's sessions (Settings, Sessions)")++// settled is the decision SettleReads made this run, so a fresh install+// that couldn't save it (settings.json unreadable) still reads nothing,+// and the listings don't write settings.json again and again.+var settled struct {+ sync.Mutex+ r *settings.SessionReads+ done bool+}++// readsAllInTests: in a test binary an install nothing settled reads every+// agent, as before, and SettleReads writes nothing to settings.json; the+// tests of the gate turn it off.+var readsAllInTests = testing.Testing()++// Reads is whether magpie may read agent's own session files.+func Reads(agent string) bool {+ return currentReads().Reads(agent)+}++func currentReads() *settings.SessionReads {+ if r := settings.Shared().SessionReads; r != nil {+ return r+ }+ if readsAllInTests {+ return &settings.SessionReads{Asked: true, All: true}+ }+ return SettleReads()+}++// SettleReads decides, once, what an install with no SessionReads reads:+// one that already read sessions (its sessions cache or call cache is+// there) keeps reading every agent; a fresh one reads none until asked.+// The decision is saved, so a cache written later can't turn a fresh+// install into one that reads everything. A value already saved is kept.+func SettleReads() *settings.SessionReads {+ if r := settings.Shared().SessionReads; r != nil {+ return r+ }+ if readsAllInTests {+ return &settings.SessionReads{Asked: true, All: true}+ }+ settled.Lock()+ defer settled.Unlock()+ if settled.done {+ return settled.r+ }+ r := &settings.SessionReads{}+ if readBefore() {+ r = &settings.SessionReads{Asked: true, All: true}+ }+ var saved *settings.SessionReads+ err := settings.SetSessionReads(func(cur *settings.SessionReads) *settings.SessionReads {+ if cur != nil {+ saved = cur+ return cur+ }+ return r+ })+ if saved != nil {+ r = saved+ }+ if err != nil {+ // not saved: decided for this run only; an unreadable+ // settings.json is not a reason to read more+ r = &settings.SessionReads{}+ }+ settled.r, settled.done = r, true+ return r+}++// forgetSettled is for tests that settle again in a new HOME.+func forgetSettled() {+ settled.Lock()+ settled.r, settled.done = nil, false+ settled.Unlock()+}++// readBefore is whether this install read sessions before SessionReads+// existed: it kept a sessions cache, or a call cache of any version.+func readBefore() bool {+ if _, err := os.Stat(CachePath()); err == nil {+ return true+ }+ m, _ := filepath.Glob(filepath.Join(filepath.Dir(CachePath()), "calls-v*"))+ return len(m) > 0+}++// SetReads records the user's choice: all, when given, is whether an+// agent nobody named is read (allow all, Settings' "agents found later");+// each agent in agents is read or not as given; the others stay as they+// were. The lists are read again.+func SetReads(all *bool, agents map[string]bool) error {+ err := settings.SetSessionReads(func(cur *settings.SessionReads) *settings.SessionReads {+ r := &settings.SessionReads{Asked: true}+ if cur != nil {+ r.All = cur.All+ for a, on := range cur.Agents {+ if r.Agents == nil {+ r.Agents = map[string]bool{}+ }+ r.Agents[a] = on+ }+ }+ if all != nil {+ r.All = *all+ }+ for a, on := range agents {+ if r.Agents == nil {+ r.Agents = map[string]bool{}+ }+ r.Agents[a] = on+ }+ return r+ })+ if err != nil {+ return err+ }+ settled.Lock()+ settled.r, settled.done = nil, false+ settled.Unlock()+ Reset()+ return nil+}++// allowed is fs without the files of agents magpie may not read.+func allowed(fs []file) []file {+ r := currentReads()+ out := fs[:0:0]+ for _, f := range fs {+ if r.Reads(f.agent) {+ out = append(out, f)+ }+ }+ return out+}++// Found is the agents with a session store on this computer, by a look at+// their folders only (nothing in them is read): those the consent lists.+// WSL distros are not looked into; allow all covers them.+func Found() []string {+ exists := func(p string) bool {+ if p == "" {+ return false+ }+ _, err := os.Stat(p)+ return err == nil+ }+ var out []string+ add := func(agent string, paths ...string) {+ for _, p := range paths {+ if exists(p) {+ out = append(out, agent)+ return+ }+ }+ }+ add("claude", filepath.Join(ClaudeDir(), "projects"))+ var desktop []string+ for _, d := range callDesktopDirs() {+ desktop = append(desktop, filepath.Join(d, "local-agent-mode-sessions"), filepath.Join(d, "claude-code-sessions"))+ }+ add("claude-desktop", desktop...)+ var codex []string+ for _, h := range CodexDirs() {+ codex = append(codex, filepath.Join(h, "sessions"), filepath.Join(h, "archived_sessions"))+ }+ add("codex", codex...)+ add("opencode", OpenCodeDir())+ add("pi", PiDir())+ add("raft", filepath.Join(SlockDir(), "agents"))+ add("zcode", zcodeDB())+ add("dsh", filepath.Join(DshDir(), "sessions"))+ add("cline", ClineSessionDir())+ add("qoder", filepath.Join(QoderDir("qoder"), "projects"))+ add("qoder-cn", filepath.Join(QoderDir("qoder-cn"), "projects"))+ add("grok", filepath.Join(GrokDir(), "sessions"))+ add("workbuddy", filepath.Join(WorkBuddyDir(), "projects"))+ add("codebuddy", filepath.Join(CodeBuddyDir(), "projects"))+ add("omp", filepath.Join(OmpDir(), "sessions"))+ add("droid", filepath.Join(FactoryDir(), "sessions"))+ add("cursor", filepath.Join(CursorDir(), "chats"), filepath.Join(cursorDataDir(), "projects"), cursorEditorDB())+ add("hermes", HermesDirs()...)+ add("alma", almaDB())+ add("minimax-code", minimaxSessions())+ add("kimi", kimiSessions())+ add("agy", filepath.Join(AgyDir(), "brain"))+ add("gemini", geminiTmpDir())+ return out+}diff --git a/internal/sessions/access_test.go b/internal/sessions/access_test.gonew file mode 100644index 000000000..d84f854b3--- /dev/null+++ b/internal/sessions/access_test.go@@ -0,0 +1,203 @@+package sessions++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/settings"+)++// consentHome is setupCalls with settings of its own, and the gate as a+// user's magpie has it: nothing settled reads as unsettled, not all-on.+func consentHome(t *testing.T) callDirs {+ t.Helper()+ d := setupCalls(t)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(filepath.Dir(d.claude), "config"))+ readsAllInTests = false+ forgetSettled()+ t.Cleanup(func() { readsAllInTests = true; forgetSettled(); Reset() })+ return d+}++// writeTwoAgents gives the home a Claude Code session and a Codex one,+// each with a call, and returns the Claude session's file.+func writeTwoAgents(t *testing.T, d callDirs) string {+ t.Helper()+ claude := filepath.Join(d.claude, "projects", "-work-app", "sess1.jsonl")+ writeLines(t, claude,+ `{"type":"user","timestamp":"`+stamp(0)+`","message":{"role":"user","content":"my secret plan"},"cwd":"/work/app","sessionId":"sess1"}`,+ claudeMsg("m1", "claude-opus-5-5", 100, 1, 0, 0, 1))+ name := "rollout-2026-09-20T10-00-00-0190aaaa-1111-7222-8333-444455556666.jsonl"+ lines := []string{`{"timestamp":"` + stamp(0) + `","type":"session_meta","payload":{"id":"thread-id","session_id":"sess-x","cwd":"/work/start"}}`}+ lines = append(lines, cxTurnLines(1, "t1", "gpt-6-astra", "high")...)+ lines = append(lines, tokenCountLine(2, cxUse(1000, 600, 0, 50, 20), cxUse(1000, 600, 0, 50, 20)), cxDoneLine(5, "t1", 5000, 700))+ writeLines(t, filepath.Join(d.codex, "sessions", "2026", "09", "20", name), lines...)+ return claude+}++func agentsOf[T any](xs []T, agent func(T) string) map[string]int {+ out := map[string]int{}+ for _, x := range xs {+ out[agent(x)]+++ }+ return out+}++// RustCats on X: a fresh install read every agent's history before anyone+// agreed. Until the user allows an agent, no route reads its files: the+// Sessions list, the per-agent lists, calls, stats, traces, transcripts+// and search. Allowed one by one, only that agent is read.+func TestFreshInstallReadsNoAgentUntilAllowed(t *testing.T) {+ d := consentHome(t)+ claudeFile := writeTwoAgents(t, d)++ r := SettleReads()+ if r.Asked || r.All || len(r.Agents) > 0 {+ t.Fatalf("a fresh install settled to %+v, want nothing allowed", r)+ }+ if got := settings.Load().SessionReads; got == nil || got.Asked {+ t.Fatalf("the decision was not saved as not asked: %+v", got)+ }+ found := strings.Join(Found(), ",")+ if !strings.Contains(found, "claude") || !strings.Contains(found, "codex") {+ t.Errorf("Found() = %q, want claude and codex (found by their folders alone)", found)+ }++ none := func(when string) {+ t.Helper()+ if l := List(0); len(l) != 0 {+ t.Errorf("%s: List read %d sessions: %+v", when, len(l), l)+ }+ if a := Agents(); len(a) != 0 {+ t.Errorf("%s: Agents() = %+v", when, a)+ }+ if l := ListAgent("claude"); len(l) != 0 {+ t.Errorf("%s: ListAgent(claude) = %d", when, len(l))+ }+ if c := Calls(time.Time{}); len(c) != 0 {+ t.Errorf("%s: Calls read %d calls", when, len(c))+ }+ if c := AgentCalls(time.Time{}, "codex"); len(c) != 0 {+ t.Errorf("%s: AgentCalls(codex) read %d calls", when, len(c))+ }+ if s := CallSources(); len(s) != 0 {+ t.Errorf("%s: CallSources = %+v", when, s)+ }+ if f := traceLineFiles(); len(f) != 0 {+ t.Errorf("%s: the trace reader lists %d files", when, len(f))+ }+ if st := StatsAt(0, callT0.Add(time.Hour)); len(st.Keys) != 0 {+ t.Errorf("%s: stats count %v", when, st.Keys)+ }+ if _, err := TranscriptOf(Session{Agent: "claude", ID: "sess1", Path: claudeFile}); !errors.Is(err, ErrNotRead) {+ t.Errorf("%s: TranscriptOf a session listed before read it: %v", when, err)+ }+ if _, _, err := SearchSession(t.Context(), Session{Agent: "claude", ID: "sess1", Path: claudeFile}, "secret"); !errors.Is(err, ErrNotRead) {+ t.Errorf("%s: SearchSession read it: %v", when, err)+ }+ }+ none("not asked")++ // allow selected: Claude Code only+ if err := SetReads(new(bool), map[string]bool{"claude": true, "codex": false}); err != nil {+ t.Fatal(err)+ }+ if got := agentsOf(List(0), func(s Session) string { return s.Agent }); got["claude"] != 1 || got["codex"] != 0 {+ t.Errorf("claude allowed: List agents = %v", got)+ }+ if got := agentsOf(Calls(time.Time{}), func(c Call) string { return c.Agent }); got["claude"] == 0 || got["codex"] != 0 {+ t.Errorf("claude allowed: Calls agents = %v", got)+ }+ if _, err := TranscriptOf(Session{Agent: "claude", ID: "sess1", Path: claudeFile}); errors.Is(err, ErrNotRead) {+ t.Errorf("claude allowed: TranscriptOf still refused")+ }++ // turned off again in Settings: gone at once, though it was read+ if err := SetReads(nil, map[string]bool{"claude": false}); err != nil {+ t.Fatal(err)+ }+ none("claude turned off")++ // allow all+ on := true+ if err := SetReads(&on, map[string]bool{"claude": true, "codex": true}); err != nil {+ t.Fatal(err)+ }+ if got := agentsOf(List(0), func(s Session) string { return s.Agent }); got["claude"] != 1 || got["codex"] != 1 {+ t.Errorf("all allowed: List agents = %v", got)+ }+ if !Reads("gemini") {+ t.Error("allow all leaves out an agent not named (one found later)")+ }+}++// An install that read sessions before the choice existed keeps reading+// them all; a fresh one stays unasked once decided, whatever is cached+// after; and the user's own choice is never replaced.+func TestSettleReadsKeepsWhatWasThere(t *testing.T) {+ t.Run("existing", func(t *testing.T) {+ consentHome(t)+ if err := os.MkdirAll(filepath.Dir(CachePath()), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(CachePath(), []byte("{}"), 0o644); err != nil {+ t.Fatal(err)+ }+ if r := SettleReads(); !r.Asked || !r.All {+ t.Errorf("an install with a sessions cache settled to %+v, want all read", r)+ }+ })+ t.Run("existing call cache", func(t *testing.T) {+ consentHome(t)+ if err := os.MkdirAll(filepath.Join(filepath.Dir(CachePath()), "calls-v14"), 0o755); err != nil {+ t.Fatal(err)+ }+ if r := SettleReads(); !r.Asked || !r.All {+ t.Errorf("an install with a call cache settled to %+v, want all read", r)+ }+ })+ t.Run("fresh, then a cache", func(t *testing.T) {+ consentHome(t)+ if r := SettleReads(); r.Asked {+ t.Fatalf("fresh settled to %+v", r)+ }+ if err := os.MkdirAll(filepath.Dir(CachePath()), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(CachePath(), []byte("{}"), 0o644); err != nil {+ t.Fatal(err)+ }+ forgetSettled() // a new run+ if r := SettleReads(); r.Asked || Reads("claude") {+ t.Errorf("a fresh install became %+v once a cache was written", r)+ }+ })+ t.Run("user's choice", func(t *testing.T) {+ consentHome(t)+ if err := os.MkdirAll(filepath.Dir(CachePath()), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(CachePath(), []byte("{}"), 0o644); err != nil {+ t.Fatal(err)+ }+ old := settings.Load() // a snapshot from before the choice+ if err := SetReads(nil, map[string]bool{"codex": true}); err != nil {+ t.Fatal(err)+ }+ forgetSettled()+ if r := SettleReads(); r.All || !r.Reads("codex") || r.Reads("claude") {+ t.Errorf("the user's choice became %+v", r)+ }+ // a save from the old snapshot (another page, sync) keeps it+ if err := settings.Save(old); err != nil {+ t.Fatal(err)+ }+ if r := settings.Load().SessionReads; r == nil || !r.Reads("codex") || r.Reads("claude") {+ t.Errorf("a save from an older snapshot changed the choice to %+v", r)+ }+ })+}diff --git a/internal/sessions/agy.go b/internal/sessions/agy.goindex 4fa395cc9..4bb2a934f 100644--- a/internal/sessions/agy.go+++ b/internal/sessions/agy.go@@ -176,6 +176,9 @@ func agyFolder(uri, goos string) string {// agyTranscripts are each conversation's transcript_full.jsonl in an agy// data folder, keyed agy:<conversation id>.func agyTranscripts(dir string) []file {+ if !Reads("agy") {+ return nil+ }brain := filepath.Join(dir, "brain")dirs, _ := os.ReadDir(brain)var out []file@@ -202,6 +205,9 @@ func agyFiles() []file { return agyFilesIn(AgyDir()) }// steps in conversations/<id>.db too, protobuf this doesn't read) is// listed from its row alone: its title, folder and time, and no tokens.func agyFilesIn(dir string) []file {+ if !Reads("agy") {+ return nil+ }out := agyTranscripts(dir)rows := agySummariesOf(dir)if len(out) == 0 && len(rows) == 0 {diff --git a/internal/sessions/alma.go b/internal/sessions/alma.goindex f38375a7c..6dd35b290 100644--- a/internal/sessions/alma.go+++ b/internal/sessions/alma.go@@ -80,6 +80,9 @@ const almaCronTitle = "⏰ Cron:"// files change with every write to any chat, so a chat is read again only// when its own rows did.func almaFiles() []file {+ if !Reads("alma") {+ return nil+ }path := almaDB()if path == "" || !fileExists(path) {return nildiff --git a/internal/sessions/calls.go b/internal/sessions/calls.goindex e4d962902..a4fcb111c 100644--- a/internal/sessions/calls.go+++ b/internal/sessions/calls.go@@ -147,7 +147,17 @@ type cxCallUsage = cxUsagevar callDesktopDirs = desktopDataDirs// DesktopDataDirs are the folders whose session metadata belongs to this index.-func DesktopDataDirs() []string { return callDesktopDirs() }+func DesktopDataDirs() []string { return desktopReadDirs() }++// desktopReadDirs are callDesktopDirs, or none when Claude Desktop's+// sessions are not to be read (Reads): its local_*.json and Cowork's+// folders are its session history.+func desktopReadDirs() []string {+ if !Reads("claude-desktop") {+ return nil+ }+ return callDesktopDirs()+}// Calls reads per-file request shards, separately from the session summaries.// Only changed files are scanned, and only a bounded number of parses stay in@@ -293,14 +303,14 @@ func callFiles() []file { return callFilesWith(codexFiles()) }// callFilesWith is callFiles with codex the rollouts codexFiles found.func callFilesWith(codex []file) []file {lists := [][]file{ccFiles("claude", ClaudeDir())}- for _, d := range callDesktopDirs() {+ for _, d := range desktopReadDirs() {// Cowork keeps a Claude Code folder of its own for each sessionhomes, _ := SessionGlob(filepath.Join(d, "local-agent-mode-sessions", "*", "*", "local_*", ".claude"))for _, h := range homes {lists = append(lists, ccFiles("claude-desktop", h))}}- lists = append(lists, codex, wslFiles("claude", "codex"))+ lists = append(lists, allowed(codex), wslFiles("claude", "codex"))// sized once: a file is ~200 bytes, and growing a list of ~20k of them// on every 15 s poll was ~36 MB a readn := 0@@ -344,7 +354,7 @@ func callSourcesWith(codex []file) []file {out = append(out, piCallFiles()...)out = append(out, codebuddyCallFiles()...)out = append(out, agyCallFiles()...) // #2097- return distinctPaths(append(out, workbuddyCallFiles()...))+ return allowed(distinctPaths(append(out, workbuddyCallFiles()...)))}// desktopDataDirs are Claude Desktop's folders on this computer that@@ -1202,6 +1212,9 @@ func callSourcesOf(fs []file) []CallSource {// ReadCallSource returns immutable calls for one source. Independent files can// be read concurrently; disk IO never holds callsMu.func ReadCallSource(s CallSource) []Call {+ if !Reads(s.Agent) {+ return nil+ }st := readCalls(file{path: s.Path, key: s.Key, agent: s.Agent, size: s.Size, mod: s.Modified})// Requests retains its own compact snapshot. Keeping the expanded parser's// calls as well doubles residency, especially for long active sessions. Thediff --git a/internal/sessions/calls_minimax.go b/internal/sessions/calls_minimax.goindex b48383518..08ac6c63c 100644--- a/internal/sessions/calls_minimax.go+++ b/internal/sessions/calls_minimax.go@@ -51,6 +51,9 @@ const mcodeGateway = "custom_provider:magpie"// beside it (messages*.jsonl). A reply copied into another generation keeps// its message_id, and Calls counts an id once.func minimaxCallFiles() []file {+ if !Reads("minimax-code") {+ return nil+ }var out []filewalkLinked(minimaxSessions(), func(p string, d os.DirEntry, err error) error {if err != nil || d.IsDir() {diff --git a/internal/sessions/calls_opencode.go b/internal/sessions/calls_opencode.goindex 3d80c4385..4489095dd 100644--- a/internal/sessions/calls_opencode.go+++ b/internal/sessions/calls_opencode.go@@ -39,6 +39,9 @@ var ocCallList struct {// openCodeCallFiles are OpenCode's sessions as call sources.func openCodeCallFiles() []file {+ if !Reads("opencode") {+ return nil+ }path := openCodeDB()if !fileExists(path) {return openCodeJSONFiles(filepath.Join(OpenCodeDir(), "storage"))diff --git a/internal/sessions/calls_zcode.go b/internal/sessions/calls_zcode.goindex 550d16bf7..f116b496e 100644--- a/internal/sessions/calls_zcode.go+++ b/internal/sessions/calls_zcode.go@@ -37,6 +37,9 @@ var zcCallList struct {// zcodeCallFiles are ZCode's sessions as call sources.func zcodeCallFiles() []file {+ if !Reads("zcode") {+ return nil+ }path := zcodeDB()if !fileExists(path) {return nildiff --git a/internal/sessions/carry_convert.go b/internal/sessions/carry_convert.goindex a14199d18..1361286f9 100644--- a/internal/sessions/carry_convert.go+++ b/internal/sessions/carry_convert.go@@ -126,6 +126,9 @@ type carryKey struct {// CarryOver converts a session for the agent to (one carries offers it// with Convert), and says how to open the new one.func CarryOver(s Session, to string) (CarryResult, error) {+ if !Reads(s.Agent) {+ return CarryResult{}, ErrNotRead+ }ok := falsefor _, c := range carries(s) {if c.Agent == to && c.Convert {diff --git a/internal/sessions/cline.go b/internal/sessions/cline.goindex 6d6189a7f..5ec882faf 100644--- a/internal/sessions/cline.go+++ b/internal/sessions/cline.go@@ -43,6 +43,9 @@ func ClineSessionDir() string {}func clineFiles() []file {+ if !Reads("cline") {+ return nil+ }paths, _ := filepath.Glob(filepath.Join(ClineSessionDir(), "*", "*.messages.json"))var out []filefor _, p := range paths {diff --git a/internal/sessions/codex_catalog.go b/internal/sessions/codex_catalog.goindex 14daa2494..0ad13d9e3 100644--- a/internal/sessions/codex_catalog.go+++ b/internal/sessions/codex_catalog.go@@ -411,6 +411,9 @@ var tidyOnce sync.Once// rollout is gone out of it, once a run of magpie: those magpie deleted// before it did so itself.func TidyCodexCatalog() {+ if !Reads("codex") {+ return+ }tidyOnce.Do(func() {mu.Lock()defer mu.Unlock()diff --git a/internal/sessions/codex_titles.go b/internal/sessions/codex_titles.goindex 35a30a9c0..8164bb97f 100644--- a/internal/sessions/codex_titles.go+++ b/internal/sessions/codex_titles.go@@ -70,7 +70,12 @@ func codexTitleOf() func(id string) string {// CodexTitles reads only the append-only name index. It caches unchanged// files and reads newly appended complete lines from the previous offset.-func CodexTitles(ids []string) map[string]string { return codexTitlesAt(codexTitleIndexPath(), ids) }+func CodexTitles(ids []string) map[string]string {+ if !Reads("codex") {+ return map[string]string{}+ }+ return codexTitlesAt(codexTitleIndexPath(), ids)+}func codexTitlesAt(path string, ids []string) map[string]string {out := make(map[string]string)if len(ids) == 0 {@@ -93,7 +98,7 @@ func codexTitlesAt(path string, ids []string) map[string]string {// They still count as conflicting recipients of a generated title.func CodexTitleRecipients(digests []string) map[string][]TitleApplication {out := map[string][]TitleApplication{}- if len(digests) == 0 {+ if len(digests) == 0 || !Reads("codex") {return out}codexTitles.Lock()diff --git a/internal/sessions/content.go b/internal/sessions/content.goindex 9b60b3170..c5f7621de 100644--- a/internal/sessions/content.go+++ b/internal/sessions/content.go@@ -83,6 +83,9 @@ func keep(p Part) (Part, bool) {// ContentOf reads what was said in a call from its file.func ContentOf(c Call) (Content, error) {+ if !Reads(c.Agent) {+ return Content{Input: []Part{}, Output: []Part{}}, ErrNotRead+ }out := Content{Input: []Part{}, Output: []Part{}}if c.File == "" || c.Agent == "opencode" { // OpenCode's are rows, not lines of a filereturn out, errNoPlacediff --git a/internal/sessions/cursor.go b/internal/sessions/cursor.goindex 08524425d..b8e977cad 100644--- a/internal/sessions/cursor.go+++ b/internal/sessions/cursor.go@@ -245,6 +245,9 @@ func copyFile(from, to string) error {}func cursorFiles() []file {+ if !Reads("cursor") {+ return nil+ }paths, _ := filepath.Glob(filepath.Join(CursorDir(), "chats", "*", "*", "store.db"))var out []filefor _, p := range paths {diff --git a/internal/sessions/cursor_editor.go b/internal/sessions/cursor_editor.goindex 83555acae..aff0b3d39 100644--- a/internal/sessions/cursor_editor.go+++ b/internal/sessions/cursor_editor.go@@ -87,6 +87,9 @@ func cursorEditorDB() string {}func cursorEditorFiles(cli []file) []file {+ if !Reads("cursor") {+ return nil+ }seen := map[string]bool{}for _, f := range cli {seen[strings.TrimPrefix(f.key, "cursor:")] = truediff --git a/internal/sessions/droid.go b/internal/sessions/droid.goindex 30597d78d..2f8c53ac5 100644--- a/internal/sessions/droid.go+++ b/internal/sessions/droid.go@@ -71,6 +71,9 @@ func readDroidStart(path string) (droidStart, bool) {var droidCallers listMemo[string]func droidFiles() []file {+ if !Reads("droid") {+ return nil+ }root := filepath.Join(FactoryDir(), "sessions")a, _ := filepath.Glob(filepath.Join(root, "*.jsonl"))b, _ := filepath.Glob(filepath.Join(root, "*", "*.jsonl"))diff --git a/internal/sessions/dsh.go b/internal/sessions/dsh.goindex d55501de0..f68f36203 100644--- a/internal/sessions/dsh.go+++ b/internal/sessions/dsh.go@@ -69,6 +69,9 @@ var ()func dshFiles() []file {+ if !Reads("dsh") {+ return nil+ }dirs, _ := filepath.Glob(filepath.Join(DshDir(), "sessions", "*", "*"))var out []fileparent := map[string]string{}diff --git a/internal/sessions/grok.go b/internal/sessions/grok.goindex e3ae5161a..e0480e8b3 100644--- a/internal/sessions/grok.go+++ b/internal/sessions/grok.go@@ -89,6 +89,9 @@ type grokKind struct{ Kind, Parent string }var grokKinds listMemo[grokKind]func grokFiles() []file {+ if !Reads("grok") {+ return nil+ }kinds := grokKinds.round()defer kinds.done()root := filepath.Join(GrokDir(), "sessions")diff --git a/internal/sessions/hermes.go b/internal/sessions/hermes.goindex 2725fa75b..a5d8b2577 100644--- a/internal/sessions/hermes.go+++ b/internal/sessions/hermes.go@@ -289,6 +289,9 @@ func hermesSelect(cols map[string]bool, names []string, fallback string) string}func hermesFiles() []file {+ if !Reads("hermes") {+ return nil+ }var out []filefor _, dir := range HermesDirs() {path := filepath.Join(dir, "state.db")diff --git a/internal/sessions/kimi.go b/internal/sessions/kimi.goindex 42b76fdd6..6aafbe0fd 100644--- a/internal/sessions/kimi.go+++ b/internal/sessions/kimi.go@@ -59,6 +59,9 @@ import (// state.json is part of the main file, so a title changed there reads the// session again.func kimiFilesIn(sessions string) []file {+ if !Reads("kimi") {+ return nil+ }paths, _ := SessionGlob(filepath.Join(sessions, "*", "*", "agents", "*", "wire.jsonl"))var out []filefor _, p := range paths {diff --git a/internal/sessions/omp.go b/internal/sessions/omp.goindex 270d83ea8..8fe7ebd22 100644--- a/internal/sessions/omp.go+++ b/internal/sessions/omp.go@@ -47,6 +47,9 @@ func ompRootsIn(dir string) []string {}func ompFiles() []file {+ if !Reads("omp") {+ return nil+ }var out []fileseen := map[string]bool{}for _, root := range ompSessionRoots() {@@ -59,6 +62,9 @@ func ompFiles() []file {// its profiles': the variables that move them (PI_CODING_AGENT_DIR,// $XDG_DATA_HOME) are the distro's and aren't read from Windows.func ompFilesIn(dir string) []file {+ if !Reads("omp") {+ return nil+ }var out []fileseen := map[string]bool{}for _, root := range ompRootsIn(dir) {diff --git a/internal/sessions/opencode.go b/internal/sessions/opencode.goindex 7d437d3de..d003ca9bc 100644--- a/internal/sessions/opencode.go+++ b/internal/sessions/opencode.go@@ -142,6 +142,9 @@ func ms(n int64) time.Time {// messages and its time that of the latest change to one; from the files// its own file's path, the sum of its messages' sizes and the latest time.func openCodeFiles() []file {+ if !Reads("opencode") {+ return nil+ }if db := openCodeDB(); fileExists(db) {return openCodeDBFiles("opencode", db)}@@ -222,6 +225,9 @@ type ocDB struct{ db *sql.DB }// openCodeDBFiles are the sessions in OpenCode's database, or ZCode's.func openCodeDBFiles(agent, path string) []file {+ if !Reads(agent) {+ return nil+ }db := openDB(path)if db == nil {return nil@@ -403,6 +409,9 @@ func (s ocV2DB) parts(mid string) [][]byte {type ocFiles struct{ root string } // storage/func openCodeJSONFiles(root string) []file {+ if !Reads("opencode") {+ return nil+ }infos, _ := filepath.Glob(filepath.Join(root, "session", "*", "*.json"))store := ocFiles{root}var out []filediff --git a/internal/sessions/pi.go b/internal/sessions/pi.goindex b708ac316..fcb98d1af 100644--- a/internal/sessions/pi.go+++ b/internal/sessions/pi.go@@ -72,6 +72,9 @@ func piFiles() []file { return piFilesIn(PiDir(), piSessionDir()) }// piFilesIn are the sessions in a Pi folder, and in the folder it was told// to keep them in ("" for none).func piFilesIn(dir, sessionDir string) []file {+ if !Reads("pi") {+ return nil+ }paths, _ := filepath.Glob(filepath.Join(dir, "sessions", "*", "*.jsonl"))if d := sessionDir; d != "" {more, _ := filepath.Glob(filepath.Join(d, "*.jsonl"))diff --git a/internal/sessions/pidesktop_titles.go b/internal/sessions/pidesktop_titles.goindex 85cf9ad80..014a99810 100644--- a/internal/sessions/pidesktop_titles.go+++ b/internal/sessions/pidesktop_titles.go@@ -44,6 +44,9 @@ var piDesktopTitlesHeld = time.Second// store.db is (openCursorStore). A database that can't be read leaves the// names last read standing: unknown, not untitled.func PIDesktopTitles(ids []string) map[string]string {+ if !Reads("pi") {+ return map[string]string{}+ }out := map[string]string{}if len(ids) == 0 {return outdiff --git a/internal/sessions/raft.go b/internal/sessions/raft.goindex 504c5bfd7..59b191cf2 100644--- a/internal/sessions/raft.go+++ b/internal/sessions/raft.go@@ -35,6 +35,9 @@ func raftFiles() []file { return raftFilesIn(SlockDir()) }// raftFilesIn are the Pi sessions of the agents in a Raft folder.func raftFilesIn(dir string) []file {+ if !Reads("raft") {+ return nil+ }var paths []stringfor _, sub := range []string{".pi-sessions", ".builtin-sessions"} {more, _ := filepath.Glob(filepath.Join(dir, "agents", "*", sub, "*.jsonl"))diff --git a/internal/sessions/search.go b/internal/sessions/search.goindex 00f8d4250..38d94801e 100644--- a/internal/sessions/search.go+++ b/internal/sessions/search.go@@ -223,6 +223,9 @@ func equalFoldASCII(a, lower []byte) bool {// from its agent's own file; ErrNoTranscript for an agent whose// conversations aren't read.func SearchSession(ctx context.Context, s Session, needle string) (Hit, bool, error) {+ if !Reads(s.Agent) {+ return Hit{}, false, ErrNotRead+ }if !HasTranscript(s.Agent) || s.Path == "" {return Hit{}, false, ErrNoTranscript}diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.goindex d9f4ae8da..70d6e4a19 100644--- a/internal/sessions/sessions.go+++ b/internal/sessions/sessions.go@@ -571,6 +571,9 @@ func parallel(n, per int, one func(i int)) {// its workflows (ultracode) in <id>/subagents/workflows/<run>/agent-*.jsonl// — beside each run's journal.jsonl, which isn't a transcript.func ccFiles(agent, dir string) []file {+ if !Reads(agent) {+ return nil+ }return heldFiles("cc\x00"+agent+"\x00"+dir, func() []file { return listCCFiles(agent, dir) })}@@ -630,7 +633,9 @@ func allFiles() []file {grokFiles(), workbuddyFiles(), codebuddyFiles(), droidFiles(), ompFiles(), cursorFiles(), hermesFiles(), almaFiles(), kimiFiles(), agyFiles()} {out = append(out, fs...)}- return distinctPaths(out)+ // each lister asked Reads already; a file listed under another+ // agent's name is held to that agent too+ return allowed(distinctPaths(out))}// distinctPaths is fs with each path kept once, the first time it is@@ -708,6 +713,9 @@ const zstSuffix = ".zst"// reading CodexDir alone left out every other account's sessions and// calls (phantom3792 on X).func codexFiles() []file {+ if !Reads("codex") {+ return nil+ }if !quiet() {return heldFiles("codex", listCodexFiles)}@@ -788,6 +796,9 @@ func walkLinked(root string, fn fs.WalkDirFunc) error {// codexFilesIn are the rollouts in a Codex folder.func codexFilesIn(dir string) []file {+ if !Reads("codex") {+ return nil+ }var out []filefor _, folder := range []string{"sessions", "archived_sessions"} {root := filepath.Join(dir, folder)diff --git a/internal/sessions/subagents.go b/internal/sessions/subagents.goindex 73cec8928..d9581ab32 100644--- a/internal/sessions/subagents.go+++ b/internal/sessions/subagents.go@@ -303,6 +303,9 @@ var ErrNoSubagent = errors.New("no such subagent in this session")// SubagentTranscript is the conversation of the session's subagent sub.func SubagentTranscript(s Session, sub string) (Transcript, error) {+ if !Reads(s.Agent) {+ return Transcript{Parts: []Part{}}, ErrNotRead+ }for _, sa := range s.Subagents {if sa.ID != sub {continuediff --git a/internal/sessions/traces.go b/internal/sessions/traces.goindex 7b3a599ef..15ecea47b 100644--- a/internal/sessions/traces.go+++ b/internal/sessions/traces.go@@ -90,14 +90,18 @@ func traceLineFiles() []file {files := append(codexFiles(), piFiles()...)claude := func(agent, dir string) { files = append(files, ccFiles(agent, dir)...) }claude("claude", ClaudeDir())- for _, dir := range callDesktopDirs() {+ for _, dir := range desktopReadDirs() {homes, _ := SessionGlob(filepath.Join(dir, "local-agent-mode-sessions", "*", "*", "local_*", ".claude"))for _, home := range homes {claude("claude-desktop", home)}}seen := map[string]bool{}- for _, root := range ompSessionRoots() {+ var ompRoots []string+ if Reads("omp") {+ ompRoots = ompSessionRoots()+ }+ for _, root := range ompRoots {paths, _ := SessionGlob(filepath.Join(root, "*", "*.jsonl"))for _, path := range paths {if seen[path] {@@ -110,7 +114,7 @@ func traceLineFiles() []file {}}}- return append(files, geminiTraceFiles()...)+ return allowed(append(files, geminiTraceFiles()...))}func TraceID(parts ...string) string {diff --git a/internal/sessions/traces_gemini.go b/internal/sessions/traces_gemini.goindex 9661d4654..ed1f2616f 100644--- a/internal/sessions/traces_gemini.go+++ b/internal/sessions/traces_gemini.go@@ -15,11 +15,10 @@ import (// messages, $set/$patch and $rewindTo records. Both stores use the same message// schema. Message/tool timestamps are event boundaries, not measured latency.func geminiTraceFiles() []file {- home, _ := os.UserHomeDir()- if custom := appdir.Getenv("GEMINI_CLI_HOME"); custom != "" {- home = custom+ if !Reads("gemini") {+ return nil}- root := filepath.Join(home, ".gemini", "tmp")+ root := geminiTmpDir()var out []filefor _, pattern := range []string{"*/chats/session-*.json", "*/chats/session-*.jsonl"} {paths, _ := SessionGlob(filepath.Join(root, pattern))@@ -33,6 +32,15 @@ func geminiTraceFiles() []file {return out}+// geminiTmpDir is where Gemini CLI keeps its chats.+func geminiTmpDir() string {+ home, _ := os.UserHomeDir()+ if custom := appdir.Getenv("GEMINI_CLI_HOME"); custom != "" {+ home = custom+ }+ return filepath.Join(home, ".gemini", "tmp")+}+type geminiTraceTool struct {ID, Name, Status stringTimestamp time.Timediff --git a/internal/sessions/transcript.go b/internal/sessions/transcript.goindex 9b228f463..fe8e3fca6 100644--- a/internal/sessions/transcript.go+++ b/internal/sessions/transcript.go@@ -62,6 +62,9 @@ func (t *Transcript) add(_ bool, p Part) bool {// TranscriptOf reads a session's conversation from its (main) file.func TranscriptOf(s Session) (Transcript, error) {+ if !Reads(s.Agent) {+ return Transcript{Parts: []Part{}}, ErrNotRead+ }out := Transcript{Parts: []Part{}}if !HasTranscript(s.Agent) || s.Path == "" {return out, ErrNoTranscriptdiff --git a/internal/sessions/workbuddy.go b/internal/sessions/workbuddy.goindex 2cf6a4523..9cb3d49da 100644--- a/internal/sessions/workbuddy.go+++ b/internal/sessions/workbuddy.go@@ -75,6 +75,9 @@ func isBuddy(agent string) bool { return agent == "workbuddy" || agent == "codeb// buddyFiles are the sessions under projects/ in dir, as agent's: WorkBuddy's,// or CodeBuddy Code's, which keeps them the same way.func buddyFiles(agent, dir string) []file {+ if !Reads(agent) {+ return nil+ }var out []filewalkLinked(filepath.Join(dir, "projects"), func(p string, d os.DirEntry, err error) error {if err != nil || d.IsDir() || !strings.HasSuffix(d.Name(), ".jsonl") {diff --git a/internal/sessions/wsl.go b/internal/sessions/wsl.goindex b40f24d48..8d587763e 100644--- a/internal/sessions/wsl.go+++ b/internal/sessions/wsl.go@@ -6,6 +6,7 @@ import ("log""os""path/filepath"+ "slices""sort""strings""sync"@@ -136,7 +137,8 @@ func wslListPath() string { return filepath.Join(filepath.Dir(CachePath()), "ses// as last listed; a listing is started behind when the last is older than// wslRelist.func wslFiles(agents ...string) []file {- if !wslLooking() {+ agents = slices.DeleteFunc(slices.Clone(agents), func(a string) bool { return !Reads(a) })+ if len(agents) == 0 || !wslLooking() {return nil}wslSess.Lock()diff --git a/internal/sessions/zcode.go b/internal/sessions/zcode.goindex dc254a4b3..314fa60f9 100644--- a/internal/sessions/zcode.go+++ b/internal/sessions/zcode.go@@ -28,6 +28,9 @@ func ZCodeDir() string {func zcodeDB() string { return filepath.Join(ZCodeDir(), "cli", "db", "db.sqlite") }func zcodeFiles() []file {+ if !Reads("zcode") {+ return nil+ }if db := zcodeDB(); fileExists(db) {return openCodeDBFiles("zcode", db)}diff --git a/internal/settings/settings.go b/internal/settings/settings.goindex e9ca2f684..61c603cb4 100644--- a/internal/settings/settings.go+++ b/internal/settings/settings.go@@ -221,6 +221,13 @@ type Settings struct {// GatewayConversations is local, opt-in recording of session traffic.// Only SetGatewayConversations changes it; other saves keep local consent.GatewayConversations bool `json:"gatewayConversations,omitempty"`+ // SessionReads is which agents' own session files magpie may read+ // (RustCats on X: a first open listed every agent's history unasked).+ // Nil is not settled yet (sessions.SettleReads decides it once). Only+ // SetSessionReads changes it; other saves keep what the file holds,+ // and it is this computer's own (KeepOwn): its agents and their files+ // are this computer's.+ SessionReads *SessionReads `json:"sessionReads,omitempty"`// CodexWarmup starts a ChatGPT account's next window as soon as the// last one resets, with one tiny request, so it counts from then (a// Codex window starts at its first use): "" off, "week" the weekly@@ -1164,6 +1171,7 @@ func (s Settings) Compact() int {// shows it; Lullaby: sharing turned on at home came on at work).func (s *Settings) KeepOwn(cur Settings) {s.GatewayConversations = cur.GatewayConversations+ s.SessionReads = cur.SessionReadss.UIFont, s.CodeFont = cur.UIFont, cur.CodeFonts.Window, s.Proxy, s.Port, s.Dock, s.DockWindow, s.Lightweight = cur.Window, cur.Proxy, cur.Port, cur.Dock, cur.DockWindow, cur.Lightweights.DockNever, s.DockSettled = cur.DockNever, cur.DockSettled@@ -1469,12 +1477,55 @@ func SavedAddr() string {return fmt.Sprintf("127.0.0.1:%d", p)}-// Save validates and writes the settings, preserving current recording consent.+// Save validates and writes the settings, preserving current recording+// consent and which agents' sessions may be read.func Save(s Settings) error {defer lockFile()()return save(s, false)}+// SessionReads is the user's answer to which agents' session files magpie+// reads. Before it is asked (Asked false) no agent's are read. Then an+// agent named in Agents is read as it says, and any other as All says:+// "allow all" is All with no Agents, so an agent installed later is read+// too, and "allow selected" names each agent found then.+type SessionReads struct {+ Asked bool `json:"asked"`+ All bool `json:"all,omitempty"`+ Agents map[string]bool `json:"agents,omitempty"`+}++// Reads says whether agent's session files may be read.+func (r *SessionReads) Reads(agent string) bool {+ if r == nil || !r.Asked {+ return false+ }+ if on, ok := r.Agents[agent]; ok {+ return on+ }+ return r.All+}++// SetSessionReads changes which agents' sessions may be read, as edit+// returns it from what the file holds now (nil when not settled), so a+// save elsewhere from an older snapshot neither undoes nor brings it+// back. A settings file that can't be read is left as it is, with the+// error.+func SetSessionReads(edit func(*SessionReads) *SessionReads) error {+ defer lockFile()()+ s, err := loadChecked()+ if err != nil {+ return err+ }+ var cur *SessionReads+ if s.SessionReads != nil {+ c := s.clone().SessionReads+ cur = c+ }+ s.SessionReads = edit(cur)+ return saveOwn(s, false, true)+}+// SetGatewayConversations changes local recording consent without overwriting// other settings from an earlier snapshot.func SetGatewayConversations(on bool) error {@@ -1586,7 +1637,11 @@ func UseRedactModel(name string) error {}// save is called under fileMu. Only the consent setter may replace recording.-func save(s Settings, recording bool) error {+func save(s Settings, recording bool) error { return saveOwn(s, recording, false) }++// saveOwn is save; reads says s's SessionReads is the one to write, where+// any other save keeps the file's.+func saveOwn(s Settings, recording, reads bool) error {defer filememo.Forget() // read again, where a request holds it// what is written is settled: a Settings read from an older file was// settled as it was read, and one made without reading has its Dock@@ -1772,6 +1827,7 @@ func save(s Settings, recording bool) error {// Load may have returned defaults or only part of an unreadable file.// Do not replace it, including its permissions, with those values.consent := false+ var storedReads *SessionReadsif b, err := steady.ReadFile(Path()); err == nil {b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))if len(bytes.TrimSpace(b)) != 0 {@@ -1787,6 +1843,7 @@ func save(s Settings, recording bool) error {_ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &stored)}consent = stored.GatewayConversations+ storedReads = stored.SessionReads}} else if !os.IsNotExist(err) {return fmt.Errorf("could not read settings at %s: %w", Path(), err)@@ -1794,6 +1851,9 @@ func save(s Settings, recording bool) error {if !recording {s.GatewayConversations = consent}+ if !reads {+ s.SessionReads = storedReads+ }// the file there now is kept first, before anything below can make// one: as the last good generation, or aside when it doesn't readif err := lastgood.Keep(Path(), validSettings, 0o600); err != nil {diff --git a/internal/tui/sessions.go b/internal/tui/sessions.goindex 650e24c8c..7f1981744 100644--- a/internal/tui/sessions.go+++ b/internal/tui/sessions.go@@ -57,6 +57,15 @@ func (m model) sessShown() []sessions.Session {return sessFilter(m.slist, sessRanges[m.srange].days, m.smodel, m.sfolder, time.Now())}+// sessNothing is what an empty range says: until the user allows an+// agent (RustCats on X), magpie reads no agent's sessions, and says how.+func sessNothing() string {+ if !sessions.SettleReads().Asked {+ return "magpie reads no agent's session history until you allow it · magpie sessions read on all (or on <agent>), or the app's Sessions page"+ }+ return "nothing in this range · Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here"+}+func sessFilter(all []sessions.Session, days int, model, folder string, now time.Time) []sessions.Session {var since time.Timeif days > 0 {@@ -230,7 +239,7 @@ func sessListLines(list []sessions.Session, agents []*agent.Agent, rng int, modeif model != "" || folder != "" {add(sMuted.Render("no session matches · x clears the filters"))} else {- add(sMuted.Render("nothing in this range · Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here"))+ add(sMuted.Render(sessNothing()))}return out}@@ -319,7 +328,7 @@ func sessLines(st sessions.Stats, rng int, model, folder string, byCost bool, wiif model != "" || folder != "" {add(sMuted.Render("no session matches · x clears the filters"))} else {- add(sMuted.Render("nothing in this range · Claude Code's, Codex's, OpenCode's and Pi's sessions on this computer show up here"))+ add(sMuted.Render(sessNothing()))}return out}diff --git a/internal/tui/sessions_test.go b/internal/tui/sessions_test.goindex 3761bcafe..c8fb3317e 100644--- a/internal/tui/sessions_test.go+++ b/internal/tui/sessions_test.go@@ -273,3 +273,21 @@ func TestSessionsListIsNotCutAtTheLimit(t *testing.T) {t.Fatalf("the page shows %d sessions, want at least %d", got, n)}}++// Not asked yet (RustCats on X), the page lists nothing and says how to+// allow an agent, where it would say none ran in the range.+func TestSessionsNotAskedSaysHow(t *testing.T) {+ sessionsHome(t)+ if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {+ return &settings.SessionReads{}+ }); err != nil {+ t.Fatal(err)+ }+ m := press(t, model{w: 220, h: 40, srange: 1}, "5", "A")+ if n := len(m.sessShown()); n != 0 {+ t.Fatalf("not asked, %d sessions read", n)+ }+ if v := m.View(); !strings.Contains(v, "magpie sessions read on all") {+ t.Errorf("the empty page doesn't say how to allow an agent:\n%s", v)+ }+}