sessions: gateway mode lists only the gateway's sessions, never this computer's agents' files

paultian on Discord: magpie web in gateway mode, on a machine with Claude
Code and Codex installed, listed that machine's own sessions beside the
ones other computers sent through it. Owner's call (via the lead): keep
Sessions in gateway mode, scope it.

- sessions.OwnOff (set by the gui to ownSessionsOff): while it holds,
  currentReads answers "none", Found and Dirs are empty, the trash lists
  and restores/purges only what the gateway kept, and moving Claude
  Code's folder is refused. Every route built on Reads follows: the list,
  one, transcript, markdown, export, stats, overview, search, manage,
  delete, carry, Usage's agent-file calls. Gateway-recorded sessions
  (ledger projection, recorded conversations) are not behind the gate.
- ownSessionsOff: magpie web's page, and Settings' gateway mode On, or
  Automatic with --gateway or no agents found (looked at once per 30s,
  and again on another HOME/PATH). A turn of the answer resets the
  sessions' caches and stats; the gateway-mode route does it at once.
- /api/sessions/reads says gateway:true: the page asks nothing, its empty
  state names the gateway's sessions (en/zh/zh-TW/ja/de), and Settings ›
  Privacy leaves out Agents' session history.
- The gateway-mode subtitle (5 languages), docs/reference.md and
  site docs/docker.html (en/zh/ja) say Sessions stays and what it lists
  (they said there was no Sessions tab, which was already wrong);
  docs/subsystems/gateway-sessions.md has the design.
- Tests: Handler marks the process as magpie web for good, and 13 tests
  served magpie web's page, so a later test's sandbox could be in gateway
  mode by itself. webPageHandler ends the mark with the test, and
  TestWebPageHandlerEveryWhere fails on a direct Handler(webHost{...}).

Ran (mote, at this tree rebased on origin/main):
- TestGatewayModeListsNoOwnSessions: red on the old code, green now.
- gateway-mode-sessions.test.cjs: chromium + webkit, en 900/390, zh,
  zh-TW, ja 420, de 390: 36/36; red on the old client.js (every case).
- GUI files the change reaches (gateway-mode*, sessions-*, session-*,
  privacy-*, usage-sessions-*, i18n-keys), both engines: 657/657.
- TestCoreScriptBudget ok.
- go test -shuffle=on ./internal/gui ./internal/sessions: sessions ok;
  gui ok but TestMainWindowCorners/macOS_26_SDK, red the same on
  origin/main 2f726b1f9 on mote (#3949).
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of both
  packages; gofmt -l clean.

Broken by hand: OwnOff answering false (the Go test goes red on the list,
stats, manage, one, transcript); the Purge guard and the Restore guard
each (red on purge / restore); the old client.js and settings.js (the GUI
test red). An injected stale agents memo and leaked webPage did not
reproduce the one TestUsageRequestContent red seen in the first package
run; it did not come back in two more runs, one shuffled.

Not tried: a real magpie web on a server with real agents on other
computers; the Go test on Windows and Linux boxes; the 30s memo under
real use.
This commit is contained in:
yetone
2026-11-04 20:20:41 +08:00
parent 2f726b1f95
commit f44fa2ef6a
29 changed files with 609 additions and 31 deletions
+4 -2
View File
@@ -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
+28
View File
@@ -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
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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",
@@ -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;
}
@@ -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.",
@@ -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))
+2 -2
View File
@@ -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 != "" {
+1 -1
View File
@@ -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")
+77
View File
@@ -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)
}
+1 -1
View File
@@ -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)))
+2 -2
View File
@@ -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+`"}`)))
+1 -1
View File
@@ -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 }
+3 -3
View File
@@ -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()
+4 -4
View File
@@ -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 {
+233
View File
@@ -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)
}
}
+4 -1
View File
@@ -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
}
+1 -1
View File
@@ -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)
}
@@ -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, []);
});
}
}
+1 -1
View File
@@ -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 {
+2 -2
View File
@@ -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))
+49
View File
@@ -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))
}
}
}
}
+26
View File
@@ -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
+11
View File
@@ -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) {
+4
View File
@@ -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()
+4
View File
@@ -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
+1 -1
View File
@@ -128,7 +128,7 @@ docker logs magpie</pre>
<h2 id="web"><a class="anchor" href="#web">The browser UI</a></h2>
<p>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 <code>MAGPIE_WEB_KEY</code> set (16 or more letters, digits or <code>- . _ ~</code>; <code>openssl rand -hex 16</code> 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.</p>
<p>The page is in <b>gateway mode</b>: <span class="ui">Providers</span>, <span class="ui">Gateway</span>, <span class="ui">Routing</span>, <span class="ui">Usage</span>, <span class="ui">Plugins</span> and <span class="ui">Settings</span>, with no Agents, Sessions or Library, since there are no agents in the container. <span class="ui">Settings</span> → <span class="ui">General</span> → <span class="ui">Gateway mode</span> turns it off.</p>
<p>The page is in <b>gateway mode</b>: <span class="ui">Providers</span>, <span class="ui">Gateway</span>, <span class="ui">Routing</span>, <span class="ui">Usage</span>, <span class="ui">Sessions</span>, <span class="ui">Plugins</span> and <span class="ui">Settings</span>, with no Agents or Library, since there are no agents in the container. <span class="ui">Sessions</span> lists only the sessions of agents on other computers that came through this gateway, never this machine’s agents’ files. <span class="ui">Settings</span> → <span class="ui">General</span> → <span class="ui">Gateway mode</span> turns it off.</p>
<p>On a NAS or a server you reach over SSH, open the page through a tunnel rather than publishing 3430: <code>ssh -L 3430:127.0.0.1:3430 you@nas</code>, then the log’s link on your own computer.</p>
<div class="callout"><b>Anyone with the link can change magpie and see its keys.</b> Keep 3430 on loopback or a VPN. Across the network, serve it over HTTPS: give magpie a certificate with <code>MAGPIE_TLS_CERT</code> and <code>MAGPIE_TLS_KEY</code>, or put it behind a reverse proxy with TLS, such as Caddy.</div>
+1 -1
View File
@@ -128,7 +128,7 @@ docker logs magpie</pre>
<h2 id="web"><a class="anchor" href="#web">ブラウザ UI</a></h2>
<p>ログのリンクを開きます。リンクのキーは cookie に置き換わり、アドレスから消えます。キーなしで開いたページは拒否されます(401)。<code>MAGPIE_WEB_KEY</code>(英数字か <code>- . _ ~</code> で 16 文字以上。<code>openssl rand -hex 16</code> で作れます)を設定すると、再起動してもキーは変わらず、ブラウザは 400 日サインインしたままです。設定しなければ起動のたびに新しいキーができ、cookie はそのブラウザセッションの間だけ有効です。</p>
<p>ページは<b>ゲートウェイモード</b>で開きます:<span class="ui">プロバイダ</span>、<span class="ui">ゲートウェイ</span>、<span class="ui">ルーティング</span>、<span class="ui">使用量</span>、<span class="ui">プラグイン</span>、<span class="ui">設定</span>だけで、コンテナにはエージェントがないのでエージェント、セッション、ライブラリはありません。<span class="ui">設定</span> → <span class="ui">一般</span> → <span class="ui">ゲートウェイモード</span>でオフにできます。</p>
<p>ページは<b>ゲートウェイモード</b>で開きます:<span class="ui">プロバイダ</span>、<span class="ui">ゲートウェイ</span>、<span class="ui">ルーティング</span>、<span class="ui">使用量</span>、<span class="ui">セッション</span>、<span class="ui">プラグイン</span>、<span class="ui">設定</span>だけで、コンテナにはエージェントがないのでエージェントとライブラリはありません。<span class="ui">セッション</span>には、このゲートウェイを通った他のコンピュータのエージェントのセッションだけが並び、このマシンのエージェントのセッションファイルは読みません。<span class="ui">設定</span> → <span class="ui">一般</span> → <span class="ui">ゲートウェイモード</span>でオフにできます。</p>
<p>NAS や SSH で入るサーバーでは、3430 を公開せずにトンネル経由でページを開きます:<code>ssh -L 3430:127.0.0.1:3430 you@nas</code> を実行してから、自分のコンピューターでログのリンクを開きます。</p>
<div class="callout"><b>リンクを持つ人は誰でも magpie を変更し、そのキーを見られます。</b>3430 はループバックか VPN 上に置いてください。ネットワーク越しなら HTTPS で:<code>MAGPIE_TLS_CERT</code> と <code>MAGPIE_TLS_KEY</code> で magpie に証明書を渡すか、Caddy のような TLS 付きのリバースプロキシの後ろに置きます。</div>
+1 -1
View File
@@ -128,7 +128,7 @@ docker logs magpie</pre>
<h2 id="web"><a class="anchor" href="#web">Web 界面</a></h2>
<p>打开日志里的链接。链接里的 key 会换成一个 cookie,并从地址栏里去掉;不带 key 打开会被拒绝(401)。设置了 <code>MAGPIE_WEB_KEY</code>(16 个以上的字母、数字或 <code>- . _ ~</code>;<code>openssl rand -hex 16</code> 可以生成一个)时,重启后 key 不变,浏览器保持登录 400 天。不设置时每次启动都会生成新 key,cookie 只在本次浏览器会话里有效。</p>
<p>这个页面处于<b>网关模式</b>:只有 <span class="ui">供应商</span>、<span class="ui">网关</span>、<span class="ui">路由</span>、<span class="ui">用量</span>、<span class="ui">插件</span>和 <span class="ui">设置</span>,没有 Agent、会话和资源库,因为容器里没有 Agent。<span class="ui">设置</span> → <span class="ui">常规</span> → <span class="ui">网关模式</span> 可以关掉它。</p>
<p>这个页面处于<b>网关模式</b>:只有 <span class="ui">供应商</span>、<span class="ui">网关</span>、<span class="ui">路由</span>、<span class="ui">用量</span>、<span class="ui">会话</span>、<span class="ui">插件</span>和 <span class="ui">设置</span>,没有 Agent 和资源库,因为容器里没有 Agent。<span class="ui">会话</span>只列出其他电脑上通过这个网关的 Agent 会话,从不读这台机器上 Agent 的会话文件。<span class="ui">设置</span> → <span class="ui">常规</span> → <span class="ui">网关模式</span> 可以关掉它。</p>
<p>NAS 或通过 SSH 访问的服务器上,用隧道打开页面,不要发布 3430:<code>ssh -L 3430:127.0.0.1:3430 you@nas</code>,然后在自己电脑上打开日志里的链接。</p>
<div class="callout"><b>拿到链接的人都能修改 magpie、看到它的密钥。</b>让 3430 只在回环地址或 VPN 上。要跨网络访问,就用 HTTPS:用 <code>MAGPIE_TLS_CERT</code> 和 <code>MAGPIE_TLS_KEY</code> 给 magpie 一张证书,或者放在带 TLS 的反向代理(如 Caddy)后面。</div>