diff --git a/docs/reference.md b/docs/reference.md index 3586e0290..eb64e29f0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3024,8 +3024,10 @@ protocol-specific base URLs. Keep `3425` behind a firewall or VPN and do not expose it publicly without gateway-key authentication. Such a page is in **gateway mode**: it shows Providers, Gateway, Routing, -Usage, Plugins and Settings, with no Agents, Sessions or Library tab, and -Settings leaves out what is written into this machine's agents (provider in +Usage, Sessions, Plugins and Settings, with no Agents or Library tab. +Sessions lists only the sessions of other computers' agents that came +through this gateway, never this machine's agents' session files +([gateway sessions](subsystems/gateway-sessions.md)). Settings leaves out what is written into this machine's agents (provider in model names) and the desktop's alerts and tray. Codex's and Claude Code's own settings (Codex subagents, long conversations, Codex thread titles and the rest) are on the Agents page, in the agent's opened row, so a gateway has diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 771a98a10..1b2b2f579 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -335,6 +335,34 @@ choice from the CLI (`sessionReadsTo`); while it is not asked, says how (`sessNothing`). Tests: `TestSessionsRead`, `TestSessionsNotAskedSaysHow`. +In gateway mode (`magpie web`'s page, [`gatewaymode.go`](../../internal/gui/gatewaymode.go)) +no agent's own session files are read, whatever `SessionReads` says +(paultian on Discord: a server put in gateway mode with agents installed +listed its own sessions beside those other computers sent). The gui sets +`sessions.OwnOff` to `ownSessionsOff`, and `currentReads` answers "none" +while it holds, so `Reads`, `allowed` and every route above (the list, +`one`, `transcript`, `markdown`, `export`, stats, the overview, search, +`manage`, delete, carry, the Codex provider move, and Usage's agent-file +calls) see no local session; `Found` and `Dirs` are empty, the +trash lists and restores only what the gateway kept, and moving Claude +Code's project folder is refused (`ErrNotRead`). Gateway-recorded +sessions (the ledger's projection and the recorded conversations) are not +behind this gate and still show, a local agent's that went through this +gateway among them. `ownSessionsOff` asks `settings.Shared()` and an +agents look kept for 30 s, as it is asked on every read, and when its +answer turns it resets the sessions' caches and the stats +(`forgetOwnSessions`), as `POST /api/settings/gateway-mode` does at once. +`/api/sessions/reads` says `gateway: true` then: the Sessions page asks +nothing, its empty state says the sessions shown are those of other +computers' agents that use this gateway, and Settings › Privacy leaves +*Agents' session history* out. A session is listed only when its +requests name one in a header (`sessionOf`: `X-Magpie-Session`, or the +agent's own, `sessionHeaders`), under the agent its User-Agent names +(`usage.AgentOf`, magpie's agents and plugins' agents; another client by +its product name). +The app's windows are never in gateway mode. Tests: +`TestGatewayModeListsNoOwnSessions`, `gateway-mode-sessions.test.cjs`. + 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 diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index c768c7343..71f1efb37 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -19969,7 +19969,7 @@ function renderGatewayMode(s) { flag: t("Now on: magpie web was started with --gateway"), "no-agents": t("Now on: no agents on this computer"), }[s.gatewayWhy] || t("Now off: agents found on this computer"); - $("#gatewayModeSub").textContent = [t("Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings"), now].filter(Boolean).join(" · "); + $("#gatewayModeSub").textContent = [t("Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions"), now].filter(Boolean).join(" · "); } // renderLangPick: Settings' language, one menu button showing the language diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index de87b3e1b..0052fc5a2 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -995,7 +995,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} 没有声明读取 {what}", "No such call: {what}": "没有这个调用:{what}", "The page hit an error": "页面出错了", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只显示给其他电脑当网关所需的内容:不显示 Agent 和资源库,也不显示本机 Agent 的设置", + "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "只显示给其他电脑当网关所需的内容:不显示 Agent 和资源库,也不显示本机 Agent 的设置和会话", "Now on: magpie web was started with --gateway": "当前开启:magpie web 以 --gateway 启动", "Now on: no agents on this computer": "当前开启:本机没有 Agent", "Now off: agents found on this computer": "当前关闭:本机找到了 Agent", @@ -5587,7 +5587,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} 沒有宣告讀取 {what}", "No such call: {what}": "沒有這個呼叫:{what}", "The page hit an error": "頁面出錯了", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 和資源庫,也不顯示本機 Agent 的設定", + "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "只顯示給其他電腦當閘道所需的內容:不顯示 Agent 和資源庫,也不顯示本機 Agent 的設定和會話", "Now on: magpie web was started with --gateway": "目前開啟:magpie web 以 --gateway 啟動", "Now on: no agents on this computer": "目前開啟:本機沒有 Agent", "Now off: agents found on this computer": "目前關閉:本機找到了 Agent", @@ -10150,7 +10150,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} は {what} の読み取りを宣言していません", "No such call: {what}": "そのような呼び出しはありません:{what}", "The page hit an error": "ページでエラーが起きました", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "他のコンピューターのゲートウェイに必要なものだけ:エージェント、ライブラリ、このコンピューターのエージェントの設定は表示しません", + "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "他のコンピューターのゲートウェイに必要なものだけ:エージェント、ライブラリ、このコンピューターのエージェントの設定とセッションは表示しません", "Now on: magpie web was started with --gateway": "現在オン:magpie web が --gateway で起動されています", "Now on: no agents on this computer": "現在オン:このコンピューターにエージェントがありません", "Now off: agents found on this computer": "現在オフ:このコンピューターにエージェントがあります", @@ -14728,7 +14728,7 @@ const I18N = { "{name} doesn't ask to read {what}": "{name} fragt nicht danach, {what} zu lesen", "No such call: {what}": "Kein solcher Aufruf: {what}", "The page hit an error": "Die Seite hat einen Fehler", - "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings": "Nur, was ein Gateway für andere Computer braucht: keine Agenten oder Bibliothek, keine Einstellungen der Agenten auf diesem Computer", + "Only what a gateway for other computers needs: no Agents or Library, nor this computer's agents' settings or sessions": "Nur, was ein Gateway für andere Computer braucht: keine Agenten oder Bibliothek, keine Einstellungen oder Sitzungen der Agenten auf diesem Computer", "Now on: magpie web was started with --gateway": "Jetzt an: magpie web wurde mit --gateway gestartet", "Now on: no agents on this computer": "Jetzt an: keine Agenten auf diesem Computer", "Now off: agents found on this computer": "Jetzt aus: Agenten auf diesem Computer gefunden", diff --git a/internal/gui/assets/plugins/sessions/client.js b/internal/gui/assets/plugins/sessions/client.js index 276b7425f..093f1059e 100644 --- a/internal/gui/assets/plugins/sessions/client.js +++ b/internal/gui/assets/plugins/sessions/client.js @@ -365,7 +365,9 @@ magpie.plugin("sessions", (ctx) => { // 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; + // In gateway mode no agent's files here are read (reads.gateway), so + // there is nothing to ask. + const consentApplies = () => data?.reads && data.reads.asked === false && !data.reads.gateway; function consentCard() { const found = data.reads.found || []; @@ -514,7 +516,10 @@ magpie.plugin("sessions", (ctx) => { 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."))); + e.append(el("b", "", t("No sessions yet")), el("span", "", data.reads?.gateway + // gateway mode lists no session of this computer's agents + ? t("The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.") + : 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); return box; } diff --git a/internal/gui/assets/plugins/sessions/i18n.js b/internal/gui/assets/plugins/sessions/i18n.js index 03be94909..3ebdc5cf9 100644 --- a/internal/gui/assets/plugins/sessions/i18n.js +++ b/internal/gui/assets/plugins/sessions/i18n.js @@ -37,6 +37,7 @@ magpie.strings({ "Made a new {agent} session from this one, and copied the command that opens it": "已从此会话新建 {agent} 会话,并复制了打开它的命令", "Opening in session terminal": "正在所选终端中打开", "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.": "本机 Claude Code、Codex、Hermes、OpenCode 和 Pi 的会话按运行目录列在这里。", + "The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.": "其他电脑上通过此网关的智能体会话按运行目录列在这里。", "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.": "可列出并继续 {agent} 的会话,但无法删除:它们没有独立文件。", "magpie can list {agent}'s sessions, but cannot resume or delete them.": "可列出 {agent} 的会话,但无法继续或删除。", "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.": "这些 {agent} 会话只读:可列出,但无法继续或删除。", @@ -123,6 +124,7 @@ magpie.strings({ "Made a new {agent} session from this one, and copied the command that opens it": "已從此會話新建 {agent} 會話,並複製了開啟它的命令", "Opening in session terminal": "正在所選終端機中開啟", "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.": "本機 Claude Code、Codex、Hermes、OpenCode 和 Pi 的會話按執行目錄列在這裡。", + "The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.": "其他電腦上透過此閘道的智慧體會話按執行目錄列在這裡。", "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.": "可列出並繼續 {agent} 的會話,但無法刪除:它們沒有獨立檔案。", "magpie can list {agent}'s sessions, but cannot resume or delete them.": "可列出 {agent} 的會話,但無法繼續或刪除。", "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.": "這些 {agent} 會話只讀:可列出,但無法繼續或刪除。", @@ -209,6 +211,7 @@ magpie.strings({ "Made a new {agent} session from this one, and copied the command that opens it": "このセッションから新しい {agent} セッションを作り、開くコマンドをコピーしました", "Opening in session terminal": "セッション用ターミナルで開いています", "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.": "このコンピュータ上の Claude Code、Codex、Hermes、OpenCode、Pi のセッションが、実行されたフォルダごとにここに表示されます。", + "The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.": "このゲートウェイを使う他のコンピュータのエージェントのセッションが、実行されたフォルダごとにここに表示されます。", "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.": "magpie は {agent} のセッションを一覧表示・再開できますが、削除はできません。セッションごとのファイルとして保存されていないためです。", "magpie can list {agent}'s sessions, but cannot resume or delete them.": "magpie は {agent} のセッションを一覧表示できますが、再開や削除はできません。", "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.": "これらの {agent} セッションは読み取り専用です。magpie は一覧表示できますが、再開や削除はできません。", @@ -295,6 +298,7 @@ magpie.strings({ "Made a new {agent} session from this one, and copied the command that opens it": "Neue {agent}-Sitzung aus dieser erstellt und den Befehl zum Öffnen kopiert", "Opening in session terminal": "Wird im Sitzungsterminal geöffnet", "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.": "Sitzungen von Claude Code, Codex, Hermes, OpenCode und Pi auf diesem Computer erscheinen hier, gruppiert nach dem Ordner, in dem sie liefen.", + "The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.": "Sitzungen der Agenten auf anderen Computern, die diesen Zugangspunkt nutzen, erscheinen hier, gruppiert nach dem Ordner, in dem sie liefen.", "magpie can list {agent}'s sessions and resume them, but not delete them: they aren't kept as files of their own.": "magpie kann die Sitzungen von {agent} auflisten und fortsetzen, aber nicht löschen, da sie nicht als eigene Dateien vorliegen.", "magpie can list {agent}'s sessions, but cannot resume or delete them.": "magpie kann die Sitzungen von {agent} auflisten, aber weder fortsetzen noch löschen.", "These {agent} sessions are read only; magpie can list them, but cannot resume or delete them.": "Diese Sitzungen von {agent} sind schreibgeschützt; magpie kann sie auflisten, aber weder fortsetzen noch löschen.", diff --git a/internal/gui/assets/plugins/sessions/settings.js b/internal/gui/assets/plugins/sessions/settings.js index d72899566..a39e96e51 100644 --- a/internal/gui/assets/plugins/sessions/settings.js +++ b/internal/gui/assets/plugins/sessions/settings.js @@ -50,6 +50,12 @@ let sessionReadsSeq = 0; function renderSessionReads(s) { const box = $("#sessionReadsList"); const r = sessionReads || { asked: !!s?.sessionReads?.asked, all: !!s?.sessionReads?.all, found: [] }; + // gateway mode reads no agent's session history here, whatever these + // say (ownSessionsOff), so they are left out + const gw = !!(s?.gatewayOn || r.gateway); + box.hidden = gw; + box.previousElementSibling.hidden = gw; + if (gw) return; const save = (body) => { const n = ++sessionReadsSeq; writingPrefs(api("sessions/reads", body)) diff --git a/internal/gui/assets_revalidate_test.go b/internal/gui/assets_revalidate_test.go index 53e48bf03..61425dfb1 100644 --- a/internal/gui/assets_revalidate_test.go +++ b/internal/gui/assets_revalidate_test.go @@ -22,7 +22,7 @@ func TestPageFilesRevalidate(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{}, nil) + srv := webPageHandler(t, webHost{}, nil) get := func(path, etag string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", path, nil) if etag != "" { @@ -80,7 +80,7 @@ func TestPageNamesItsFilesByContent(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{}, nil) + srv := webPageHandler(t, webHost{}, nil) get := func(path, etag string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", path, nil) if etag != "" { diff --git a/internal/gui/fonts_test.go b/internal/gui/fonts_test.go index 9b07734e3..80bd3e4a9 100644 --- a/internal/gui/fonts_test.go +++ b/internal/gui/fonts_test.go @@ -161,7 +161,7 @@ func TestFontSettingsAPIAndBoot(t *testing.T) { if err := json.Unmarshal(boot(h)["uiFont"], &first); err != nil || !reflect.DeepEqual(&first, face) { t.Fatalf("first paint font = %#v: %v", first, err) } - web := Handler(webHost{}, nil) + web := webPageHandler(t, webHost{}, nil) post(web, map[string]any{"uiFont": nil, "codeFont": nil}, 200) if !reflect.DeepEqual(settings.Load().UIFont, face) { t.Fatal("browser save replaced a desktop font") diff --git a/internal/gui/gatewaymode.go b/internal/gui/gatewaymode.go index e1c30d038..77c34fae6 100644 --- a/internal/gui/gatewaymode.go +++ b/internal/gui/gatewaymode.go @@ -4,9 +4,13 @@ import ( "encoding/json" "fmt" "net/http" + "os" + "sync" "sync/atomic" + "time" "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/sessions" "github.com/yetone/magpie/internal/settings" ) @@ -74,6 +78,79 @@ func gatewayModeRoutes(mux *http.ServeMux) { fail(rw, err) return } + // the Sessions page lists this computer's agents' sessions, or + // stops, at once (ownSessionsOff) + ownSessionsOff() + forgetOwnSessions() writeJSON(rw, settingsState()) }) } + +// ownSessionsOff is gatewayMode as the sessions' gate asks it +// (sessions.OwnOff; paultian on Discord): in gateway mode the Sessions page +// and Usage › Sessions list what came through this gateway, never this +// computer's own agents' session files, which a machine put in gateway +// mode with agents installed still listed. It is asked on every read of a +// session, so it reads the shared settings and an agents look kept a while +// (agentsHereKept) rather than gatewayMode's own. When its answer turns, +// what was read under the other answer is dropped (ownTurned). +func ownSessionsOff() bool { + on := false + if webPage.Load() { + switch settings.Shared().GatewayMode { + case "on": + on = true + case "off": + default: + on = WebGateway.Load() || !agentsHereKept() + } + } + ownTurned(on) + return on +} + +// ownWas is ownSessionsOff's last answer: 0 none yet, 1 off, 2 on. +var ownWas atomic.Int32 + +// ownTurned drops the sessions read, and the stats made, under the other +// answer, off the caller's goroutine: the gate is asked under the +// sessions' own lock, which Reset takes. +func ownTurned(on bool) { + v := int32(1) + if on { + v = 2 + } + if was := ownWas.Swap(v); was != 0 && was != v { + go forgetOwnSessions() + } +} + +func forgetOwnSessions() { + sessions.Reset() + forgetStats() +} + +// agentsHereKept is agentsHere looked at most every half minute: it looks +// for every agent's files and commands. Another HOME or PATH (a test's +// sandbox) is looked at afresh. +var agentsSeen struct { + sync.Mutex + at time.Time + on string // the HOME and PATH it was looked for in + here bool +} + +func agentsHereKept() bool { + agentsSeen.Lock() + defer agentsSeen.Unlock() + on := os.Getenv("HOME") + "\x00" + os.Getenv("PATH") + if agentsSeen.at.IsZero() || agentsSeen.on != on || time.Since(agentsSeen.at) > 30*time.Second { + agentsSeen.here, agentsSeen.at, agentsSeen.on = agentsHere(), time.Now(), on + } + return agentsSeen.here +} + +func init() { + f := ownSessionsOff + sessions.OwnOff.Store(&f) +} diff --git a/internal/gui/gatewaymode_test.go b/internal/gui/gatewaymode_test.go index 4d9852b30..537670f86 100644 --- a/internal/gui/gatewaymode_test.go +++ b/internal/gui/gatewaymode_test.go @@ -27,7 +27,7 @@ func TestGatewayMode(t *testing.T) { agentsHere = func() bool { return here } t.Cleanup(func() { agentsHere = was; WebGateway.Store(false); webPage.Store(false) }) - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) do := func(method, path, body string) *httptest.ResponseRecorder { rec := httptest.NewRecorder() srv.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) diff --git a/internal/gui/masking_test.go b/internal/gui/masking_test.go index cadc852fa..fc019bbf9 100644 --- a/internal/gui/masking_test.go +++ b/internal/gui/masking_test.go @@ -42,7 +42,7 @@ func TestMaskingRecordsAPI(t *testing.T) { Snips: map[string]string{p: sent}}) other := maskrec.Add(maskrec.Record{What: "search", N: 1, Values: []maskrec.Value{{Placeholder: "{{EMAIL_00000000}}", Kind: "EMAIL", By: redact.ByRule}}}) - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) get := func(path string, into any) int { rw := httptest.NewRecorder() srv.ServeHTTP(rw, httptest.NewRequest("GET", path, nil)) @@ -159,7 +159,7 @@ func TestMaskingPreviewKeepsKeyForm(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) preview := func() string { rw := httptest.NewRecorder() srv.ServeHTTP(rw, httptest.NewRequest("POST", "/api/masking/preview", strings.NewReader(`{"text":"用密钥 `+key+` 部署可以吗,或用密钥 OPENAI_API_KEY=`+key+`"}`))) diff --git a/internal/gui/novideo_test.go b/internal/gui/novideo_test.go index d5aced56f..7fe94ba04 100644 --- a/internal/gui/novideo_test.go +++ b/internal/gui/novideo_test.go @@ -26,7 +26,7 @@ func TestBootSaysNoVideo(t *testing.T) { if b := boot(Handler(nil, nil)); !strings.Contains(b, `"noVideo":true`) { t.Fatalf("the app, with no video: %s", b) } - if b := boot(Handler(webHost{}, nil)); strings.Contains(b, "noVideo") { + if b := boot(webPageHandler(t, webHost{}, nil)); strings.Contains(b, "noVideo") { t.Fatalf("a browser tab plays its own video: %s", b) } webkitPlaysVideo = func() bool { return true } diff --git a/internal/gui/privacymodel_test.go b/internal/gui/privacymodel_test.go index 937cbe025..cf4b7f38a 100644 --- a/internal/gui/privacymodel_test.go +++ b/internal/gui/privacymodel_test.go @@ -23,7 +23,7 @@ func TestPrivacyModelOnlyOnOnceDownloaded(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) do := func(method, path, body string) *httptest.ResponseRecorder { rec := httptest.NewRecorder() srv.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) @@ -79,7 +79,7 @@ func TestPrivacyModelCancelledDefaultIsOff(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) rec := httptest.NewRecorder() srv.ServeHTTP(rec, httptest.NewRequest("POST", "/api/privacy-model", strings.NewReader(`{"do":"cancel"}`))) var st privacyModelJSON @@ -143,7 +143,7 @@ func TestPrivacyModelPick(t *testing.T) { t.Cleanup(func() { modelOf, models = wasOf, wasModels }) modelOf = func(id string) pii.Model { return fakes[id] } models = func() []pii.Model { return []pii.Model{fakes[pii.PrivacyFilter], fakes[pii.AstrLinkGuard]} } - srv := Handler(webHost{func() {}}, nil) + srv := webPageHandler(t, webHost{func() {}}, nil) do := func(body string) privacyModelJSON { t.Helper() rec := httptest.NewRecorder() diff --git a/internal/gui/quitask_test.go b/internal/gui/quitask_test.go index b65090a0f..2eaab54b3 100644 --- a/internal/gui/quitask_test.go +++ b/internal/gui/quitask_test.go @@ -18,7 +18,7 @@ import ( func TestWindowQuitAsksFirst(t *testing.T) { quits := 0 asked := make(chan struct{}, 4) - h := Handler(askingHost{webHost{quit: func() { quits++ }}, asked}, nil) + h := webPageHandler(t, askingHost{webHost{quit: func() { quits++ }}, asked}, nil) post := func(url string) { t.Helper() r := httptest.NewRecorder() @@ -48,7 +48,7 @@ func TestWindowQuitAsksFirst(t *testing.T) { default: } - web := Handler(webHost{quit: func() { quits++ }}, nil) + web := webPageHandler(t, webHost{quit: func() { quits++ }}, nil) r := httptest.NewRecorder() web.ServeHTTP(r, httptest.NewRequest("POST", "/api/window/quit", nil)) if quits != 2 { @@ -88,7 +88,7 @@ func TestQuitAPIListsAgents(t *testing.T) { t.Cleanup(func() { quitAgents = old }) quitAgents = func() []quitAgentJSON { return []quitAgentJSON{{ID: "codex", Name: "Codex", Icon: "openai"}} } r := httptest.NewRecorder() - Handler(webHost{}, nil).ServeHTTP(r, httptest.NewRequest("GET", "/api/quit", nil)) + webPageHandler(t, webHost{}, nil).ServeHTTP(r, httptest.NewRequest("GET", "/api/quit", nil)) var got struct{ Agents []quitAgentJSON } if err := json.Unmarshal(r.Body.Bytes(), &got); err != nil || len(got.Agents) != 1 || got.Agents[0].ID != "codex" { t.Fatalf("GET /api/quit = %d %s (%v)", r.Code, r.Body, err) @@ -145,7 +145,7 @@ func TestQuitDontAskAgain(t *testing.T) { } quits := 0 - h := Handler(askingHost{webHost{quit: func() { quits++ }}, make(chan struct{}, 1)}, nil) + h := webPageHandler(t, askingHost{webHost{quit: func() { quits++ }}, make(chan struct{}, 1)}, nil) r := httptest.NewRecorder() h.ServeHTTP(r, httptest.NewRequest("POST", "/api/window/quit?now=1&noAsk=1", nil)) if r.Code != 204 || quits != 1 { diff --git a/internal/gui/sessions_gateway_mode_test.go b/internal/gui/sessions_gateway_mode_test.go new file mode 100644 index 000000000..91c02d414 --- /dev/null +++ b/internal/gui/sessions_gateway_mode_test.go @@ -0,0 +1,233 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/usage" +) + +// paultian on Discord: in gateway mode the Sessions page and Usage › +// Sessions list what came through this gateway from other computers, +// never this computer's own agents' session files, which a machine put in +// gateway mode with Claude Code and Codex installed still listed. Every +// route that reaches a session is asked: the list, one, the transcript, +// Markdown and its export, the stats and the overview, search, manage +// and its trash, delete, restore, purge, carry and moving Claude Code's folder. +// The gateway's session shows on each. Gateway mode off, as before. +func TestGatewayModeListsNoOwnSessions(t *testing.T) { + h := sandboxHome(t) + claude := filepath.Join(h, ".claude") + codex := filepath.Join(h, ".codex") + t.Setenv("CLAUDE_CONFIG_DIR", claude) + t.Setenv("CODEX_HOME", codex) + if err := os.MkdirAll(filepath.Join(h, "Downloads"), 0o755); err != nil { + t.Fatal(err) + } + proj := filepath.Join(claude, "projects", "-work") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + at := time.Now().Add(-time.Hour).Truncate(time.Second) + claudeSession := func(id, text string) string { + ts := at.UTC().Format("2006-01-02T15:04:05.000Z") + p := filepath.Join(proj, id+".jsonl") + b := `{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"` + text + `"},"uuid":"u` + id + `","timestamp":"` + ts + `","cwd":"/work","sessionId":"` + id + `"}` + "\n" + + `{"parentUuid":"u` + id + `","isSidechain":false,"message":{"model":"claude-sonnet-5","id":"msg_` + id + `","type":"message","role":"assistant","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":10,"output_tokens":2}},"requestId":"req_` + id + `","type":"assistant","uuid":"a` + id + `","timestamp":"` + ts + `","cwd":"/work","sessionId":"` + id + `"}` + "\n" + if err := os.WriteFile(p, []byte(b), 0o644); err != nil { + t.Fatal(err) + } + os.Chtimes(p, at, at) + return p + } + const local, trashed, codexID = "11111111-1111-2222-3333-444444444444", "22222222-1111-2222-3333-444444444444", "019a0000-0000-7000-8000-00000000c0de" + localFile := claudeSession(local, "my local secret plan") + claudeSession(trashed, "an old local plan") + writeCodexAPITestThread(t, codex, codexID, codexID, "", []codexTestCall{{response: "resp_1", model: "gpt-5.5", effort: "high", at: at, input: 100, output: 10}}) + sessions.Reset() + t.Cleanup(sessions.Reset) + + mux := http.NewServeMux() + sessionRoutes(mux, folderOnly{}) + sessionManageRoutes(mux, folderOnly{}) + gatewayModeRoutes(mux) + call := func(method, path, body string) (int, string) { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) + return w.Code, w.Body.String() + } + ok := func(method, path, body string) string { + t.Helper() + code, b := call(method, path, body) + if code != 200 { + t.Fatalf("%s %s: %d %s", method, path, code, b) + } + return b + } + + // a session another computer's Pi sent through this gateway, its + // conversation recorded + ok("POST", "/api/sessions/recording", `{"on":true}`) + const remote = "ses_remote_pi_1" + usage.Append(usage.Record{Time: at, Agent: "pi", Session: remote, Provider: "fake", Model: "m", Input: 50, Output: 5, Status: 200}) + if err := sessions.SaveGatewayTurn(sessions.GatewayTurn{Agent: "pi", Session: remote, Time: at, + Input: []sessions.Part{{Role: "user", Kind: "text", Text: "rename foo to bar remotely"}}, + Output: []sessions.Part{{Role: "assistant", Kind: "text", Text: "Renamed it."}}}); err != nil { + t.Fatal(err) + } + + listed := func() map[string]bool { + t.Helper() + var out struct{ Sessions []sessions.Session } + if err := json.Unmarshal([]byte(ok("GET", "/api/sessions", "")), &out); err != nil { + t.Fatal(err) + } + m := map[string]bool{} + for _, s := range out.Sessions { + m[s.Agent+":"+s.ID] = true + } + return m + } + + // gateway mode off (the app's windows, or Settings' Off): every one + if _, err := sessions.Delete("claude", trashed); err != nil { + t.Fatal(err) + } + if l := listed(); !l["claude:"+local] || !l["codex:"+codexID] || !l["pi:"+remote] { + t.Fatalf("gateway mode off: listed %v", l) + } + for _, key := range []string{"claude:" + local, "codex:" + codexID} { + ok("GET", "/api/sessions/one?key="+key, "") + } + if b := ok("GET", "/api/sessions/transcript?agent=claude&id="+local, ""); !strings.Contains(b, "secret plan") { + t.Fatalf("gateway mode off: the local transcript: %s", b) + } + if b := ok("GET", "/api/sessions/stats?days=0", ""); !strings.Contains(b, `"claude"`) { + t.Fatalf("gateway mode off: stats leave out Claude Code: %s", b) + } + var trash struct { + Trash []struct{ Key, ID string } + } + json.Unmarshal([]byte(ok("GET", "/api/sessions/manage?agent=claude", "")), &trash) + trashKey := "" + for _, tr := range trash.Trash { + if tr.ID == trashed { + trashKey = tr.Key + } + } + if trashKey == "" { + t.Fatalf("gateway mode off: the trash has no %s: %+v", trashed, trash) + } + + // magpie web's page, put in gateway mode by Settings + webPage.Store(true) + t.Cleanup(func() { + webPage.Store(false) + ownWas.Store(0) + sessions.Reset() + forgetStats() + }) + ok("POST", "/api/settings/gateway-mode", `{"mode":"on"}`) + if settings.Load().GatewayMode != "on" { + t.Fatal("gateway mode wasn't saved") + } + ownLeft := func(what, body string) { + t.Helper() + for _, s := range []string{local, trashed, codexID, "secret plan", "old local plan", `"claude"`, `"codex"`, "/work"} { + if strings.Contains(body, s) { + t.Fatalf("gateway mode: %s says %q:\n%s", what, s, body) + } + } + } + if l := listed(); len(l) != 1 || !l["pi:"+remote] { + t.Fatalf("gateway mode: listed %v, want the gateway's session alone", l) + } + b := ok("GET", "/api/sessions", "") + ownLeft("the list", b) + if strings.Contains(b, filepath.ToSlash(claude)) || strings.Contains(b, ".claude") || strings.Contains(b, ".codex") { + t.Fatalf("gateway mode: the list names this computer's folders: %s", b) + } + for _, days := range []string{"0", "7"} { + ownLeft("stats", ok("GET", "/api/sessions/stats?days="+days, "")) + b = ok("GET", "/api/sessions/overview?days="+days, "") + ownLeft("the overview", b) + if !strings.Contains(b, remote) { + t.Fatalf("gateway mode: the overview leaves out the gateway's session: %s", b) + } + } + for _, key := range []string{"claude:" + local, "codex:" + codexID} { + if code, b := call("GET", "/api/sessions/one?key="+key, ""); code == 200 { + t.Fatalf("gateway mode: one %s: %d %s", key, code, b) + } + } + ok("GET", "/api/sessions/one?key=pi:"+remote, "") + for _, q := range []string{"agent=claude&id=" + local, "agent=codex&id=" + codexID} { + for _, p := range []string{"GET /api/sessions/transcript", "GET /api/sessions/markdown", "POST /api/sessions/export"} { + method, path, _ := strings.Cut(p, " ") + if code, b := call(method, path+"?"+q, "{}"); code == 200 || strings.Contains(b, "secret") { + t.Fatalf("gateway mode: %s?%s: %d %s", p, q, code, b) + } + } + } + if b := ok("GET", "/api/sessions/transcript?agent=pi&id="+remote, ""); !strings.Contains(b, "rename foo") { + t.Fatalf("gateway mode: the gateway's transcript: %s", b) + } + if b := ok("GET", "/api/sessions/markdown?agent=pi&id="+remote, ""); !strings.Contains(b, "rename foo") { + t.Fatalf("gateway mode: the gateway's Markdown: %s", b) + } + ownLeft("search", ok("GET", "/api/sessions/search?agent=claude&q=secret", "")) + if b := ok("GET", "/api/sessions/search?agent=pi&q=remotely", ""); !strings.Contains(b, remote) { + t.Fatalf("gateway mode: search leaves out the gateway's session: %s", b) + } + for _, agent := range []string{"", "claude", "codex"} { + b = ok("GET", "/api/sessions/manage?agent="+agent, "") + ownLeft("manage", b) + var m struct { + Agents []struct{ Agent string } + Reads readsJSON + } + json.Unmarshal([]byte(b), &m) + if len(m.Agents) != 1 || m.Agents[0].Agent != "pi" || !m.Reads.Gateway || len(m.Reads.Found) != 0 { + t.Fatalf("gateway mode: manage = %s", b) + } + } + if b := ok("GET", "/api/sessions/reads", ""); !strings.Contains(b, `"gateway":true`) || strings.Contains(b, `"claude"`) { + t.Fatalf("gateway mode: reads = %s", b) + } + b = ok("POST", "/api/sessions/delete", `{"agent":"claude","ids":["`+local+`"]}`) + if _, err := os.Stat(localFile); err != nil || !strings.Contains(b, `"refused":[{`) { + t.Fatalf("gateway mode: delete of a local session: %s (%v)", b, err) + } + if code, b := call("POST", "/api/sessions/carry", `{"agent":"claude","id":"`+local+`","to":"codex"}`); code == 200 { + t.Fatalf("gateway mode: carry: %s", b) + } + if code, b := call("POST", "/api/sessions/restore", `{"key":"`+trashKey+`"}`); code == 200 { + t.Fatalf("gateway mode: restore of a local session: %s", b) + } + for _, body := range []string{`{"keys":["` + trashKey + `"]}`, `{"all":true}`} { + if b := ok("POST", "/api/sessions/purge", body); !strings.Contains(b, `"purged":[]`) { + t.Fatalf("gateway mode: purge of a local session: %s", b) + } + } + if code, b := call("POST", "/api/sessions/relocate-claude", `{"from":"/work","to":"/elsewhere"}`); code == 200 { + t.Fatalf("gateway mode: relocating Claude Code's folder: %s", b) + } + + // Off again: this computer's sessions are back at once + ok("POST", "/api/settings/gateway-mode", `{"mode":"off"}`) + if l := listed(); !l["claude:"+local] || !l["codex:"+codexID] || !l["pi:"+remote] { + t.Fatalf("gateway mode turned off: listed %v", l) + } + if b := ok("GET", "/api/sessions/manage?agent=claude", ""); !strings.Contains(b, trashed) { + t.Fatalf("gateway mode turned off: the trash lost the local session: %s", b) + } +} diff --git a/internal/gui/sessions_reads.go b/internal/gui/sessions_reads.go index abb9eb5ce..04f514822 100644 --- a/internal/gui/sessions_reads.go +++ b/internal/gui/sessions_reads.go @@ -30,6 +30,9 @@ type readsJSON struct { // Found: the agents with session history on this computer, and those // the user named Found []readAgentJSON `json:"found"` + // Gateway: gateway mode, which reads no agent's files here whatever + // the choice (ownSessionsOff), so nothing is asked and none is found + Gateway bool `json:"gateway,omitempty"` } func readsNow() readsJSON { @@ -37,7 +40,7 @@ func readsNow() readsJSON { if s := settings.Shared().SessionReads; s != nil { r = s } - out := readsJSON{Found: []readAgentJSON{}} + out := readsJSON{Found: []readAgentJSON{}, Gateway: ownSessionsOff()} if r != nil { out.Asked, out.All = r.Asked, r.All } diff --git a/internal/gui/signin_open_2043_test.go b/internal/gui/signin_open_2043_test.go index 0aed5d6d1..9a52de811 100644 --- a/internal/gui/signin_open_2043_test.go +++ b/internal/gui/signin_open_2043_test.go @@ -66,7 +66,7 @@ func TestOpenSaysTheBrowserDidntOpen(t *testing.T) { t.Fatalf("open: %d %s", rec.Code, rec.Body) } rec = httptest.NewRecorder() - Handler(webHost{}, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/open", strings.NewReader(`{"url":"https://example.invalid/authorize"}`))) + webPageHandler(t, webHost{}, nil).ServeHTTP(rec, httptest.NewRequest("POST", "/api/open", strings.NewReader(`{"url":"https://example.invalid/authorize"}`))) if rec.Code != http.StatusNoContent { t.Fatalf("an open that worked: %d %s", rec.Code, rec.Body) } diff --git a/internal/gui/tests/gateway-mode-sessions.test.cjs b/internal/gui/tests/gateway-mode-sessions.test.cjs new file mode 100644 index 000000000..909760bf2 --- /dev/null +++ b/internal/gui/tests/gateway-mode-sessions.test.cjs @@ -0,0 +1,126 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Gateway mode's Sessions (paultian on Discord): magpie web as the gateway +// for other computers lists only the sessions that came through it, never +// this computer's agents' files (ownSessionsOff). The server says so with +// reads.gateway, so the page never asks which agents' history to read +// (there is none to read), its empty state speaks of the gateway's +// sessions, and Settings › Privacy leaves out the rows for agents' session +// history. 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(); + +function serve(lang, { sessions }) { + const settings = { lang, theme: "light", web: true, gatewayMode: "on", gatewayOn: true, gatewayWhy: "on", sessionReads: { asked: false, all: false } }; + 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,gateway: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 }); + if (url.pathname === "/api/settings") return json(settings); + 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 } }); + // what the server answers in gateway mode: nothing of this computer's + // agents, asked still false as the settings have it + const reads = { asked: false, all: false, found: [], gateway: true }; + if (url.pathname === "/api/sessions/reads") return json(reads); + if (url.pathname === "/api/sessions/manage") { + const rows = sessions ? [{ agent: "pi", id: "ses_remote_1", gateway: true, cwd: "/srv/app", title: "rename foo to bar", start: at(10), last: at(5), models: [], resume: "", size: 10, messages: 2, files: 0, deletable: true }] : []; + const agents = rows.length ? [{ agent: "pi", count: 1, deletable: true, name: "Pi", icon: "pi" }] : []; + return json({ agents, agent: agents[0]?.agent || "", sessions: rows, terminal: false, trash: [], trashDir: "", recording: true, reads }); + } + 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: { empty: "The sessions of agents on other computers that use this gateway show up here, by the folder they ran in.", head: "Agents' session history", share: "Sharing" }, + zh: { empty: "其他电脑上通过此网关的智能体会话按运行目录列在这里。", head: "智能体的会话历史" }, + "zh-TW": { empty: "其他電腦上透過此閘道的智慧體會話按執行目錄列在這裡。", head: "智慧體的會話歷史" }, + ja: { empty: "このゲートウェイを使う他のコンピュータのエージェントのセッションが、実行されたフォルダごとにここに表示されます。", head: "エージェントのセッション履歴" }, + de: { empty: "Sitzungen der Agenten auf anderen Computern, die diesen Zugangspunkt nutzen, erscheinen hier, gruppiert nach dem Ordner, in dem sie liefen.", head: "Sitzungsverlauf der Agenten" }, +}; + +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); + page.setDefaultNavigationTimeout(60000); + return { page, errors }; +} + +// nothing in sel is cut off or wider than the window +async function fits(page, sel) { + const over = await page.$eval(sel, (box) => { + const vw = document.documentElement.clientWidth; + const bad = [...box.querySelectorAll("*")].filter((e) => { const b = e.getBoundingClientRect(); return b.width && (b.right > vw + 0.5 || b.left < -0.5); }).map((e) => e.className); + return { vw, bad, scroll: document.documentElement.scrollWidth > vw }; + }); + assert.ok(!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: gateway mode lists the gateway's sessions and never asks to read this computer's`, async (t) => { + const { page, errors } = await open(engine, width, t); + await page.route("**/*", serve(lang, { sessions: true })); + await page.goto("http://magpie.test/?view=sessions"); + await page.locator('#view-sessions .row.sm-sess[data-id="ses_remote_1"]').waitFor(); + assert.equal(await page.locator("#view-sessions .sm-consent").count(), 0, "the consent card in gateway mode"); + await fits(page, "#view-sessions"); + assert.deepEqual(errors, []); + }); + test(`${engine} ${lang} ${width}px: gateway mode with no session yet says where they come from`, async (t) => { + const { page, errors } = await open(engine, width, t); + await page.route("**/*", serve(lang, { sessions: false })); + await page.goto("http://magpie.test/?view=sessions"); + const empty = page.locator("#view-sessions .empty-state"); + await empty.waitFor(); + assert.equal(await empty.locator("span").textContent(), w.empty); + assert.equal(await page.locator("#view-sessions .sm-consent").count(), 0, "the consent card in gateway mode"); + await fits(page, "#view-sessions"); + assert.deepEqual(errors, []); + }); + test(`${engine} ${lang} ${width}px: Settings › Privacy has no rows for this computer's session history in gateway mode`, async (t) => { + const { page, errors } = await open(engine, width, t); + const asked = []; + page.on("request", (r) => { if (new URL(r.url()).pathname === "/api/sessions/reads") asked.push(r.method()); }); + await page.route("**/*", serve(lang, { sessions: true })); + await page.goto("http://magpie.test/?view=settings&tab=privacy"); + await page.locator("#setPage-privacy").waitFor(); + await page.locator("#setPage-privacy .row-head .label", { hasText: "Sharing" }).or(page.locator("#shareList")).first().waitFor({ state: "attached" }); + // a reads answer the page asked for is drawn from before the check + if (asked.length) await page.waitForResponse((r) => new URL(r.url()).pathname === "/api/sessions/reads").catch(() => {}); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => setTimeout(r)))); + assert.ok(await page.locator("#sessionReadsList").isHidden(), "the agents' rows"); + assert.ok(await page.locator("#setPage-privacy .row-head .label", { hasText: w.head }).isHidden(), "their heading"); + assert.equal(await page.locator("#sessionReadsList .row").count(), 0); + if (w.share) assert.ok(await page.locator("#setPage-privacy .row-head .label", { hasText: w.share }).isVisible(), "the rest of Privacy stays"); + await fits(page, "#setPage-privacy"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/web_app_test.go b/internal/gui/web_app_test.go index 8cf78f0c3..86ba21124 100644 --- a/internal/gui/web_app_test.go +++ b/internal/gui/web_app_test.go @@ -27,7 +27,7 @@ func TestWebAppAddsToHomeScreen(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) const key = "0123456789abcdef-key" - srv := webHandler("3430", key, 0, Handler(webHost{}, nil)) + srv := webHandler("3430", key, 0, webPageHandler(t, webHost{}, nil)) do := func(method, path string, signedIn bool) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, nil) if signedIn { diff --git a/internal/gui/web_compress_test.go b/internal/gui/web_compress_test.go index e539f3584..df066b3d8 100644 --- a/internal/gui/web_compress_test.go +++ b/internal/gui/web_compress_test.go @@ -26,7 +26,7 @@ func TestWebCompresses(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := webHandler("3430", "0123456789abcdef-key", 0, Handler(webHost{}, nil)) + srv := webHandler("3430", "0123456789abcdef-key", 0, webPageHandler(t, webHost{}, nil)) cookie := &http.Cookie{Name: "magpie_web_3430", Value: "0123456789abcdef-key"} get := func(path, enc, etag string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", path, nil) @@ -112,7 +112,7 @@ func TestVersionedFilesKept(t *testing.T) { t.Setenv("USERPROFILE", h) t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) - srv := Handler(webHost{}, nil) + srv := webPageHandler(t, webHost{}, nil) get := func(path string) *httptest.ResponseRecorder { rec := httptest.NewRecorder() srv.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) diff --git a/internal/gui/webpage_handler_test.go b/internal/gui/webpage_handler_test.go new file mode 100644 index 000000000..f4a5e782c --- /dev/null +++ b/internal/gui/webpage_handler_test.go @@ -0,0 +1,49 @@ +package gui + +import ( + "net/http" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/yetone/magpie/internal/gateway" +) + +// webPageHandler is Handler for a test that serves magpie web's own page. +// Handler marks the process as magpie web (webPage) for good, which is +// right for the one page a real process serves but would carry into every +// later test of the package: one with a sandbox HOME and no agents would +// then be in gateway mode by itself, and read none of its own sessions +// (TestUsageRequestContent went red so). The mark ends with the test. +func webPageHandler(t *testing.T, w Windows, gw *gateway.Server) http.Handler { + t.Helper() + was := webPage.Load() + t.Cleanup(func() { + webPage.Store(was) + ownWas.Store(0) + }) + return Handler(w, gw) +} + +// Every test that serves magpie web's page goes through webPageHandler, so +// none leaves the package in magpie web's gateway mode. +func TestWebPageHandlerEveryWhere(t *testing.T) { + files, err := filepath.Glob("*_test.go") + if err != nil { + t.Fatal(err) + } + direct := regexp.MustCompile(`\bHandler\((askingHost\{)?webHost\{`) + for _, f := range files { + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + for i, line := range strings.Split(string(b), "\n") { + if direct.MatchString(line) && !strings.Contains(line, "webPageHandler(") { + t.Errorf("%s:%d serves magpie web's page without webPageHandler: %s", f, i+1, strings.TrimSpace(line)) + } + } + } +} diff --git a/internal/sessions/access.go b/internal/sessions/access.go index fbcaa46b2..878744944 100644 --- a/internal/sessions/access.go +++ b/internal/sessions/access.go @@ -6,6 +6,7 @@ import ( "path/filepath" "slices" "sync" + "sync/atomic" "testing" "github.com/yetone/magpie/internal/settings" @@ -42,7 +43,28 @@ func Reads(agent string) bool { return currentReads().Reads(agent) } +// readsNone is the answer while OwnOff holds: no agent's files are read. +var readsNone = &settings.SessionReads{Asked: true} + +// OwnOff, when set and true, is gateway mode on magpie web's page +// (gui.gatewayMode; paultian on Discord): the page lists what came +// through this gateway from other computers, never this computer's own +// agents' session files, so no agent's files are read, whatever +// SessionReads says. Gateway-recorded sessions (the usage ledger and the +// gateway's own store) are not behind this gate and still show. It is +// asked on every Reads, so it must be cheap. +var OwnOff atomic.Pointer[func() bool] + +// ownOff is whether OwnOff is set and says so. +func ownOff() bool { + f := OwnOff.Load() + return f != nil && (*f)() +} + func currentReads() *settings.SessionReads { + if ownOff() { + return readsNone + } if r := settings.Shared().SessionReads; r != nil { return r } @@ -169,6 +191,10 @@ func allowed(fs []file) []file { // 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 { + // gateway mode reads none of them, so it asks about none (OwnOff) + if ownOff() { + return nil + } exists := func(p string) bool { if p == "" { return false diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index 677c09531..daaa2f337 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -698,6 +698,11 @@ func Trash() []Trashed { if err != nil || json.Unmarshal(b, &t) != nil { continue } + // gateway mode lists what the gateway kept, not this computer's + // agents' sessions (OwnOff) + if !t.Gateway && ownOff() { + continue + } dir := filepath.Dir(p) t.Key = filepath.Base(filepath.Dir(dir)) + "/" + filepath.Base(dir) if t.Gateway { @@ -728,6 +733,9 @@ func Purge(key string) error { if dir == "" { return errors.New("no such deleted session") } + if !isGatewayKey(key) && ownOff() { + return ErrNotRead + } mu.Lock() defer mu.Unlock() for _, p := range []string{filepath.Dir(dir), dir} { @@ -754,6 +762,9 @@ func Restore(key string) (Trashed, error) { return Trashed{}, errors.New("no such deleted session") } t.Key = key + if !isGatewayKey(key) && ownOff() { + return Trashed{}, ErrNotRead + } mu.Lock() defer mu.Unlock() if isGatewayKey(key) { diff --git a/internal/sessions/relocate_claude.go b/internal/sessions/relocate_claude.go index 3d4b682e4..97e2eb082 100644 --- a/internal/sessions/relocate_claude.go +++ b/internal/sessions/relocate_claude.go @@ -39,6 +39,10 @@ type ClaudeRelocationResult struct { // session-ID-keyed files (file-history, todos and session-env). IDs stay intact. // Clients must be closed: the in-process lock cannot exclude Claude itself. func RelocateClaudeProject(in ClaudeRelocation) (ClaudeRelocationResult, error) { + // gateway mode touches no agent's files here (OwnOff) + if ownOff() { + return ClaudeRelocationResult{}, ErrNotRead + } storeMu.Lock() defer storeMu.Unlock() mu.Lock() diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 3458ba6ec..6eb0b253c 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -772,6 +772,10 @@ func distinctPaths(fs []file) []file { // Dirs are the folders the sessions are read from: Claude Code's and // Codex's, and the other agents' where they keep sessions on this computer. func Dirs() []string { + // gateway mode reads no folder here (OwnOff) + if ownOff() { + return nil + } out := []string{ClaudeDir()} out = append(out, CodexDirs()...) var named []os.FileInfo diff --git a/site/public/docs/docker.html b/site/public/docs/docker.html index 9a287abec..4f417c0b4 100644 --- a/site/public/docs/docker.html +++ b/site/public/docs/docker.html @@ -128,7 +128,7 @@ docker logs magpie
Open the link from the log. The key in it is traded for a cookie and taken out of the address; a page opened without it is turned away (401). With MAGPIE_WEB_KEY set (16 or more letters, digits or - . _ ~; openssl rand -hex 16 makes one) the key stays the same across restarts and the browser stays signed in for 400 days. Without it, every start makes a new key and the cookie lasts the browser session.
The page is in gateway mode: Providers, Gateway, Routing, Usage, Plugins and Settings, with no Agents, Sessions or Library, since there are no agents in the container. Settings → General → Gateway mode turns it off.
+The page is in gateway mode: Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings, with no Agents or Library, since there are no agents in the container. Sessions lists only the sessions of agents on other computers that came through this gateway, never this machine’s agents’ files. Settings → General → Gateway mode turns it off.
On a NAS or a server you reach over SSH, open the page through a tunnel rather than publishing 3430: ssh -L 3430:127.0.0.1:3430 you@nas, then the log’s link on your own computer.
MAGPIE_TLS_CERT and MAGPIE_TLS_KEY, or put it behind a reverse proxy with TLS, such as Caddy.ログのリンクを開きます。リンクのキーは cookie に置き換わり、アドレスから消えます。キーなしで開いたページは拒否されます(401)。MAGPIE_WEB_KEY(英数字か - . _ ~ で 16 文字以上。openssl rand -hex 16 で作れます)を設定すると、再起動してもキーは変わらず、ブラウザは 400 日サインインしたままです。設定しなければ起動のたびに新しいキーができ、cookie はそのブラウザセッションの間だけ有効です。
ページはゲートウェイモードで開きます:プロバイダ、ゲートウェイ、ルーティング、使用量、プラグイン、設定だけで、コンテナにはエージェントがないのでエージェント、セッション、ライブラリはありません。設定 → 一般 → ゲートウェイモードでオフにできます。
+ページはゲートウェイモードで開きます:プロバイダ、ゲートウェイ、ルーティング、使用量、セッション、プラグイン、設定だけで、コンテナにはエージェントがないのでエージェントとライブラリはありません。セッションには、このゲートウェイを通った他のコンピュータのエージェントのセッションだけが並び、このマシンのエージェントのセッションファイルは読みません。設定 → 一般 → ゲートウェイモードでオフにできます。
NAS や SSH で入るサーバーでは、3430 を公開せずにトンネル経由でページを開きます:ssh -L 3430:127.0.0.1:3430 you@nas を実行してから、自分のコンピューターでログのリンクを開きます。
MAGPIE_TLS_CERT と MAGPIE_TLS_KEY で magpie に証明書を渡すか、Caddy のような TLS 付きのリバースプロキシの後ろに置きます。打开日志里的链接。链接里的 key 会换成一个 cookie,并从地址栏里去掉;不带 key 打开会被拒绝(401)。设置了 MAGPIE_WEB_KEY(16 个以上的字母、数字或 - . _ ~;openssl rand -hex 16 可以生成一个)时,重启后 key 不变,浏览器保持登录 400 天。不设置时每次启动都会生成新 key,cookie 只在本次浏览器会话里有效。
这个页面处于网关模式:只有 供应商、网关、路由、用量、插件和 设置,没有 Agent、会话和资源库,因为容器里没有 Agent。设置 → 常规 → 网关模式 可以关掉它。
+这个页面处于网关模式:只有 供应商、网关、路由、用量、会话、插件和 设置,没有 Agent 和资源库,因为容器里没有 Agent。会话只列出其他电脑上通过这个网关的 Agent 会话,从不读这台机器上 Agent 的会话文件。设置 → 常规 → 网关模式 可以关掉它。
NAS 或通过 SSH 访问的服务器上,用隧道打开页面,不要发布 3430:ssh -L 3430:127.0.0.1:3430 you@nas,然后在自己电脑上打开日志里的链接。
MAGPIE_TLS_CERT 和 MAGPIE_TLS_KEY 给 magpie 一张证书,或者放在带 TLS 的反向代理(如 Caddy)后面。