sessions: a new install reads no agent's session history until the user allows it (RustCats on X)
RustCats on X: a fresh magpie showed every agent's session history on
the Sessions page before anyone agreed to it, and asked for a per-agent
choice instead.
- sessions.Reads(agent) (internal/sessions/access.go) is the one gate,
from settings.SessionReads {Asked, All, Agents}. Every lister asks it,
the aggregators (allFiles, callFilesWith, callSourcesWith,
traceLineFiles, wslFiles, DesktopDataDirs) filter by it again, and
readers of an already-listed session (TranscriptOf, ContentOf,
SearchSession, SubagentTranscript, CarryOver, ReadCallSource) return
ErrNotRead, so a cache from before a switch was turned off goes no
further. The Sessions list, stats, /api/sessions/overview, the call and
trace indexes, Usage's agent-file calls and the Codex/Pi title readers
all pass it.
- SettleReads decides once and saves: an install with sessions.json or
a calls-v* cache read sessions before and keeps all on; a fresh one
reads none, not asked. A saved value is never replaced; save, sync and
restore keep it (KeepOwn); only SetSessionReads writes it. An
unwritable settings.json reads nothing this run.
- GUI: GET/POST /api/sessions/reads. While not asked, the Sessions page
shows a consent card: each agent found (by a stat of its folder only)
with a switch, Allow selected and Allow all. Settings > Privacy >
Agents' session history has "Agents found later" and a row per agent.
Strings in en, zh, zh-TW, ja, de.
- CLI: magpie sessions read [on|off all|<agent>...]; magpie sessions
says on stderr when nothing is allowed yet; the TUI's empty Sessions
page says how.
Read either way, because none of it lists or shows a session: the
gateway's own usage ledger, its projections and the conversations it
recorded (magpie's own records, so usage and cost keep working); the
agents' config and sign-in files; Claude Code's and Codex's
history.jsonl last-used time and a session file's mtime for a quota's
first use; Codex's newest rollout's last line before magpie restarts
Codex (codexTurnOpen).
Tests: TestFreshInstallReadsNoAgentUntilAllowed,
TestSettleReadsKeepsWhatWasThere, TestSessionReadsRoutes,
TestSessionsRead, TestSessionsNotAskedSaysHow, sessions-reads.test.cjs
(26 cases: consent and Settings in 5 languages, Chromium and WebKit,
390 to 900 wide).
Run on mote:
- full Go suite (gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui,
GOOS=windows go vet, go build, go test -timeout 45m ./...) at this
change on 8c63c5b78: 79 packages ok; internal/gui red on
TestSettingsSaveKeepsWhatItDoesNotSend (mine: SessionReads is written
by SetSessionReads only, the test now sets it so; green after) and
TestMainWindowCorners (the same on origin/main c1da9ccda, #3949).
- whole GUI suite (make test-ui, concurrency 2) at this change on
8c63c5b78: 14985 tests, 276 failed in 44 files. Mine: i18n-keys
(comments named "Allow all"/"Allow selected"; lowercased) and
account-discovery (read the last Privacy heading; now the one above
its list); both green after. The 44 files again on origin/main
c1da9ccda: 36 red there too (#4304, with #3218, #3412, #3414, #3795,
#4120, #4125). stays-strict green alone; gateway-key-models webkit red
1 of 3 alone on main too; plugin-github de 440 red on main (#3218).
- at the pushed head (rebased on cd10dfbe6): go build ./...; go test
internal/sessions, settings, cli, tui ok; internal/gui
TestSettingsSave*, TestSessionReads*, TestSessions* ok; i18n-keys,
account-discovery, sessions-reads: 62 pass, 0 fail.
Broken by hand:
- the aggregator filter off with the leaf gates on: green (the leaf
gates hold); both off: TestFreshInstall red on List, Agents, Calls,
CallSources, traces, stats, TranscriptOf and Search.
- consentApplies=false and Settings' old save({all}) without the rows:
all 13 Chromium cases of sessions-reads red.
- sessNothing's hint removed: TestSessionsNotAskedSaysHow red.
Real binary in a sandbox HOME on mote (removed after): a fresh
`magpie sessions` is empty with the hint on stderr; `sessions read`
says not asked, claude off; `read --help` prints usage and saves
nothing; `read on claude` lists the one session; `read off all`
empties it again.
Not tried: the GUI and real app on Windows and Linux; WSL agents in the
consent list (WSL distros are not looked into; Allow all covers them);
a fresh install of a signed release build.
This commit is contained in:
@@ -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 Recording
|
||||
|
||||
The Sessions page offers an explicit, default-off recording switch. Confirmation
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -133,6 +133,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie sessions [--model <m>] [--folder <f>] [--json] the latest Claude Code, Codex, OpenCode and Pi sessions, with what each cost
|
||||
magpie 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 balance
|
||||
magpie quota wait <provider|account> [--timeout <d>] [--quiet]
|
||||
block until that subscription (any of its accounts) or account has allowance again
|
||||
|
||||
@@ -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.ClaudeRelocation
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 yet
|
||||
async function discoveryOffWarning() {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -60,6 +60,10 @@ magpie.plugin("sessions", (ctx) => {
|
||||
let fitObserver = null;
|
||||
let focus = null; // { agent, id, until }: a session to bring into sight once drawn
|
||||
let 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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -580,6 +580,9 @@ var warmOnce sync.Once
|
||||
|
||||
func 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)
|
||||
|
||||
@@ -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.ClaudeRelocation
|
||||
if 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 delete
|
||||
Recorded 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()
|
||||
|
||||
@@ -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())
|
||||
})
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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"}`)))
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 nil
|
||||
|
||||
@@ -147,7 +147,17 @@ type cxCallUsage = cxUsage
|
||||
var 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 session
|
||||
homes, _ := 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 read
|
||||
n := 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. The
|
||||
|
||||
@@ -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 []file
|
||||
walkLinked(minimaxSessions(), func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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 nil
|
||||
|
||||
@@ -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 := false
|
||||
for _, c := range carries(s) {
|
||||
if c.Agent == to && c.Convert {
|
||||
|
||||
@@ -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 []file
|
||||
for _, p := range paths {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 file
|
||||
return out, errNoPlace
|
||||
|
||||
@@ -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 []file
|
||||
for _, p := range paths {
|
||||
|
||||
@@ -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:")] = true
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -69,6 +69,9 @@ var (
|
||||
)
|
||||
|
||||
func dshFiles() []file {
|
||||
if !Reads("dsh") {
|
||||
return nil
|
||||
}
|
||||
dirs, _ := filepath.Glob(filepath.Join(DshDir(), "sessions", "*", "*"))
|
||||
var out []file
|
||||
parent := map[string]string{}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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 []file
|
||||
for _, dir := range HermesDirs() {
|
||||
path := filepath.Join(dir, "state.db")
|
||||
|
||||
@@ -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 []file
|
||||
for _, p := range paths {
|
||||
|
||||
@@ -47,6 +47,9 @@ func ompRootsIn(dir string) []string {
|
||||
}
|
||||
|
||||
func ompFiles() []file {
|
||||
if !Reads("omp") {
|
||||
return nil
|
||||
}
|
||||
var out []file
|
||||
seen := 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 []file
|
||||
seen := map[string]bool{}
|
||||
for _, root := range ompRootsIn(dir) {
|
||||
|
||||
@@ -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 []file
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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 out
|
||||
|
||||
@@ -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 []string
|
||||
for _, sub := range []string{".pi-sessions", ".builtin-sessions"} {
|
||||
more, _ := filepath.Glob(filepath.Join(dir, "agents", "*", sub, "*.jsonl"))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 []file
|
||||
for _, folder := range []string{"sessions", "archived_sessions"} {
|
||||
root := filepath.Join(dir, folder)
|
||||
|
||||
@@ -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 {
|
||||
continue
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 []file
|
||||
for _, 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 string
|
||||
Timestamp time.Time
|
||||
|
||||
@@ -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, ErrNoTranscript
|
||||
|
||||
@@ -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 []file
|
||||
walkLinked(filepath.Join(dir, "projects"), func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() || !strings.HasSuffix(d.Name(), ".jsonl") {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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.SessionReads
|
||||
s.UIFont, s.CodeFont = cur.UIFont, cur.CodeFont
|
||||
s.Window, s.Proxy, s.Port, s.Dock, s.DockWindow, s.Lightweight = cur.Window, cur.Proxy, cur.Port, cur.Dock, cur.DockWindow, cur.Lightweight
|
||||
s.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 *SessionReads
|
||||
if 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 read
|
||||
if err := lastgood.Keep(Path(), validSettings, 0o600); err != nil {
|
||||
|
||||
@@ -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.Time
|
||||
if days > 0 {
|
||||
@@ -230,7 +239,7 @@ func sessListLines(list []sessions.Session, agents []*agent.Agent, rng int, mode
|
||||
if 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, wi
|
||||
if 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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user