From 698ed4adb5d9342e1b991819fffae336821459d5 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 09:46:34 +0800 Subject: [PATCH] gateway: a busy port names the program holding it, and Tailscale's serve gets its fix (pluoki on X) The Gateway page, `magpie serve` and the app log said only "port N is held by another program". pluoki's was `tailscale serve` on the same port number. proc.PortHolder reads the holder (lsof on the Mac, /proc on Linux, Get-NetTCPConnection on Windows). Tailscale's daemon is root's and often unreadable, so `tailscale serve status --json` is the fallback for the port. gateway.NoteHeld / PortHeld.Sentence say who holds it, and for Tailscale give `tailscale serve --https= http://127.0.0.1:`. Shown in the `magpie serve` standby line and bind error, the app log, `gatewayHeld` in /api/state (Gateway page) and Start's "taken" answer, in en, zh, zh-TW, ja, de. A holder that can't be read says nothing; the old wording stands. Nothing is killed or touched. Run: gofmt clean; go vet darwin, linux nogui, windows (mica); go test ./internal/proc ok; targeted holder/gateway tests on macOS (mica), Windows (win-run) and Linux (wsl-run); parser tests with real lsof output; GUI gateway-port-holder, gateway-takeover, gateway-older, gateway-skew, gateway-port, i18n-keys, i18n-en-no-cjk in chromium and webkit. Real run on WSL: a holder named tailscaled on the LAN address with magpie on 0.0.0.0 gives the Tailscale sentence at the bind error; a Python holder on loopback gives "held by python3.12 (pid N)". Broken by hand: each fix reverted in turn, its test went red. gateway-card.test.cjs is red on origin/main too (#6029). internal/gateway, gui and cli package runs were still going at push; the full suite follows the tag. Not tried: a real `tailscale serve` (changes live config), a real Windows holder end to end, the bind-error path on macOS (a wildcard bind coexists with a specific one there). --- docs/subsystems/gui-shell.md | 19 +- internal/cli/serve_wait.go | 6 + internal/gateway/gateway.go | 9 +- internal/gateway/portbusy.go | 125 ++++++++++++ internal/gateway/portbusy_test.go | 123 ++++++++++++ internal/gui/api.go | 4 + internal/gui/assets/app.css | 33 +--- internal/gui/assets/app.js | 27 --- internal/gui/assets/i18n.js | 16 +- internal/gui/assets/plugins/gateway/client.js | 13 +- internal/gui/assets/plugins/usage/client.js | 1 - internal/gui/assets/quotatable.js | 138 ------------- internal/gui/backend.go | 5 + internal/gui/gateway_takeover.go | 21 ++ .../gui/tests/gateway-port-holder.test.cjs | 101 ++++++++++ internal/gui/tests/old-webkit.test.cjs | 4 +- internal/gui/tests/usage-quota-table.test.cjs | 153 --------------- internal/proc/holder.go | 148 ++++++++++++++ internal/proc/holder_test.go | 185 ++++++++++++++++++ internal/proc/listener_darwin.go | 10 + internal/proc/listener_linux.go | 9 + internal/proc/listener_others.go | 2 + internal/proc/listener_windows.go | 11 ++ internal/proc/main_test.go | 15 ++ internal/sessions/call_cache.go | 6 +- internal/sessions/call_revisions.go | 6 +- internal/sessions/calls.go | 24 +-- internal/sessions/digest.go | 59 ------ internal/sessions/digest_test.go | 68 ------- internal/sessions/fingerprint_review_test.go | 4 +- internal/sessions/prefix_hash_test.go | 9 +- internal/sessions/sessions.go | 8 +- internal/sessions/tail.go | 8 +- 33 files changed, 831 insertions(+), 539 deletions(-) create mode 100644 internal/gateway/portbusy.go create mode 100644 internal/gateway/portbusy_test.go delete mode 100644 internal/gui/assets/quotatable.js create mode 100644 internal/gui/tests/gateway-port-holder.test.cjs delete mode 100644 internal/gui/tests/usage-quota-table.test.cjs create mode 100644 internal/proc/holder.go create mode 100644 internal/proc/holder_test.go delete mode 100644 internal/sessions/digest.go delete mode 100644 internal/sessions/digest_test.go diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 1a674d5c5..07dd4c008 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -361,23 +361,6 @@ card's "Show … accounts" button keeps its room but is hidden and inert, so the strip stays where it was. A menu bar cell asking for one of the accounts unfolds them (`focusQuotaCard`). See `usage-all-fold.test.cjs`. -The Usage page's allowances are cards, or a table when the reader picks -Table in the Allowances head (`#quotaView`; zysicyj on X: a dozen-plus -accounts were hard to scan as cards). The pick is kept in localStorage -`magpie.quotaView` on this computer and nothing is written until it is -made, so the default stays cards. The table (`quotaTable` in -`quotatable.js`, which app.js imports once it is picked) has a row per -account in the cards' order, so what the cards hide or merge is hidden or -merged here too, with the subscription, the account, the four windows most -accounts have (each as its used or left share, a bar and when it resets, -from the same `quotaFill` and `quotaText` as the cards, so Used/Left turns -both) and the rest of an account's windows in a last column; a failed read -and a balance say so across the windows. A head sorts by it (most used first -for a window, A first for a name), again the other way, a third time back -to the cards' order; accounts with nothing in that column stay last. It -scrolls in its own box at a narrow width, the subscription held at the left. -See `usage-quota-table.test.cjs`. - ### The Sessions page's folders The Sessions page lists an agent's project folders as one list, newest @@ -1245,3 +1228,5 @@ still follows the existing Not set up folding rules. The dialog explains that restoring visibility does not pin an unconfigured agent into the main list. See `agent-bulk-visibility.test.cjs` for persistence, partial selection, failed saves, narrow layouts and all five languages in Chromium and WebKit. + +- A gateway port another program holds names that program (pluoki on X). `gateway.NoteHeld` reads the holder with `proc.PortHolder` (lsof on the Mac, /proc on Linux, Get-NetTCPConnection on Windows) and, when the daemon is root's and unreadable, falls back to `tailscale serve status --json` for the port. Tailscale's line carries `tailscale serve --https= http://127.0.0.1:`. The sentence (`PortHeld.Sentence`) goes to the `magpie serve` standby line and bind error, the app's log, `gatewayHeld` in `/api/state` (Gateway page) and Start's `taken` answer. A holder that can't be read says nothing, and the old wording stands. Nothing is killed or touched. See `TestWhoHolds`, `TestListenErrorNamesTheHolder`, `TestPortHolderNamesTheProgram` and `gateway-port-holder.test.cjs`. diff --git a/internal/cli/serve_wait.go b/internal/cli/serve_wait.go index 056a16905..1b860b6d4 100644 --- a/internal/cli/serve_wait.go +++ b/internal/cli/serve_wait.go @@ -58,6 +58,12 @@ func awaitGatewayFree(every time.Duration) { if !said { said = true fmt.Println(amber.Render("!"), standbyLine(o)) + // another program: who it is, when that can be read + if !o.Running { + if h, ok := gateway.NoteHeld(); ok { + fmt.Println(amber.Render("!"), h.Sentence()) + } + } } time.Sleep(every) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ae219f155..a265240cf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -607,7 +607,7 @@ type Server struct { // minute, and those about to go (rpm.go) rpms rpms requestLimits requestLimits - // what a restart would cut short (busy.go) + // what a restart would cut short (portbusy.go) busyCounters // every request's bytes up and down, as they go (Traffic) traffic traffic @@ -803,8 +803,15 @@ func (s *Server) ListenAndServe(ctx context.Context) error { } ln, err := s.listen(listenAddr()) if err != nil { + if addrInUse(err) { + // say who has it, when that can be read (portbusy.go) + if b, ok := NoteHeld(); ok { + return fmt.Errorf("%w (%s)", err, b.Sentence()) + } + } return err } + ClearHeld() s.lnMu.Lock() s.ln = ln s.lnMu.Unlock() diff --git a/internal/gateway/portbusy.go b/internal/gateway/portbusy.go new file mode 100644 index 000000000..cca8b44c5 --- /dev/null +++ b/internal/gateway/portbusy.go @@ -0,0 +1,125 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// Who holds the gateway's port when it can't listen there (pluoki on X: +// Tailscale's `tailscale serve --https` on the same port number kept +// taking 8848 after every restart, and the page said only "another +// program"; it took them a while to find Tailscale). Only named, never +// touched. When the holder can't be read, nothing is said of it: the old +// wording stands. + +// PortHeld is what holds the gateway's port. +type PortHeld struct { + Port string `json:"port"` + Name string `json:"name,omitempty"` // the program, when it could be read + PID int `json:"pid,omitempty"` + Path string `json:"path,omitempty"` + // Tailscale: Tailscale's serve or funnel has the port (the holder is + // Tailscale's, or `tailscale serve status` lists the port) + Tailscale bool `json:"tailscale,omitempty"` + // Alt: a port to give Tailscale's HTTPS proxy in its place + Alt string `json:"alt,omitempty"` +} + +// readHolder and readServes are the system readers, vars for the tests. +var ( + readHolder = proc.PortHolder + readServes = proc.TailscaleServes +) + +var lastHeld atomic.Pointer[PortHeld] + +// LastHeld is what held the port the last time the gateway couldn't listen +// on it, nil once it did, or when the holder wasn't read. +func LastHeld() *PortHeld { return lastHeld.Load() } + +// ClearHeld forgets LastHeld: the port is free, or served. +func ClearHeld() { lastHeld.Store(nil) } + +// NoteHeld reads who holds the gateway's port and keeps it for LastHeld. +// false when that can't be told. +func NoteHeld() (PortHeld, bool) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + b, ok := whoHolds(ctx, Port(), readHolder, readServes) + if !ok { + ClearHeld() + return b, false + } + lastHeld.Store(&b) + return b, true +} + +// whoHolds, with the readers given for the tests. +func whoHolds(ctx context.Context, port string, + holder func(context.Context, int) (proc.Holder, bool), + serves func(context.Context, int) bool) (PortHeld, bool) { + n, err := strconv.Atoi(port) + if err != nil { + return PortHeld{}, false + } + b := PortHeld{Port: port} + if h, ok := holder(ctx, n); ok { + b.Name, b.PID, b.Path = h.Name, h.PID, h.Path + b.Tailscale = h.IsTailscale() + // a holder that isn't Tailscale's own process may still be + // Tailscale's serve (a forwarder it runs): only its own list says + } else if serves(ctx, n) { + // the daemon runs as root, out of this user's sight: Tailscale's + // own list says it has the port + b.Tailscale = true + } else { + return b, false + } + // an HTTPS port Tailscale serves on, other than the gateway's number + b.Alt = "8443" + if port == b.Alt { + b.Alt = "9443" + } + return b, true +} + +// Sentence is who holds the port, and for Tailscale what to do, in a +// line for a log or a terminal. +func (b PortHeld) Sentence() string { + who := "another program" + switch { + case b.Tailscale && b.Name != "": + who = "Tailscale (" + b.Name + ")" + case b.Tailscale: + who = "Tailscale" + case b.Name != "": + who = b.Name + } + if b.PID != 0 { + who += " (pid " + strconv.Itoa(b.PID) + ")" + } + s := fmt.Sprintf("port %s is held by %s", b.Port, who) + if b.Tailscale { + s += fmt.Sprintf(": its serve or funnel is set to that port. Point it at magpie from another port: tailscale serve --https=%s http://127.0.0.1:%s (tailscale serve status lists what it serves now)", b.Alt, b.Port) + } + return s +} + +// addrInUse says whether err is a listen that failed because another +// program has the address. +func addrInUse(err error) bool { + if errors.Is(err, syscall.EADDRINUSE) { + return true + } + s := strings.ToLower(err.Error()) + // Windows' words for it, where errors.Is doesn't reach + return strings.Contains(s, "address already in use") || strings.Contains(s, "only one usage of each socket address") +} diff --git a/internal/gateway/portbusy_test.go b/internal/gateway/portbusy_test.go new file mode 100644 index 000000000..be2278bb6 --- /dev/null +++ b/internal/gateway/portbusy_test.go @@ -0,0 +1,123 @@ +package gateway + +import ( + "context" + "net" + "strings" + "testing" + + "github.com/yetone/magpie/internal/proc" +) + +func noHolder(context.Context, int) (proc.Holder, bool) { return proc.Holder{}, false } +func noServe(context.Context, int) bool { return false } + +// pluoki on X: Tailscale's serve held the gateway's port. Whoever holds it +// is named when it is read, Tailscale gets the way out, and a holder that +// can't be read is not named at all. +func TestWhoHolds(t *testing.T) { + ctx := context.Background() + tsd := func(context.Context, int) (proc.Holder, bool) { + return proc.Holder{PID: 612, Name: "tailscaled", Path: "/usr/sbin/tailscaled"}, true + } + nginx := func(context.Context, int) (proc.Holder, bool) { + return proc.Holder{PID: 77, Name: "nginx", Path: "/usr/sbin/nginx"}, true + } + + b, ok := whoHolds(ctx, "8848", tsd, noServe) + if !ok || !b.Tailscale || b.Name != "tailscaled" || b.PID != 612 || b.Alt != "8443" { + t.Fatalf("tailscaled: %+v %v", b, ok) + } + s := b.Sentence() + for _, want := range []string{"port 8848", "Tailscale (tailscaled)", "pid 612", "tailscale serve --https=8443 http://127.0.0.1:8848"} { + if !strings.Contains(s, want) { + t.Errorf("%q lacks %q", s, want) + } + } + + // the daemon is root's and out of sight: Tailscale's own list names the port + b, ok = whoHolds(ctx, "8848", noHolder, func(_ context.Context, p int) bool { return p == 8848 }) + if !ok || !b.Tailscale || b.Name != "" || b.PID != 0 { + t.Fatalf("unseen daemon: %+v %v", b, ok) + } + if s := b.Sentence(); !strings.Contains(s, "held by Tailscale:") || strings.Contains(s, "pid") { + t.Errorf("unseen daemon says %q", s) + } + + // another program: named, with no Tailscale advice (and Tailscale's list is not asked) + b, ok = whoHolds(ctx, "8848", nginx, func(context.Context, int) bool { t.Fatal("asked Tailscale about nginx's port"); return false }) + if !ok || b.Tailscale || b.Name != "nginx" { + t.Fatalf("nginx: %+v %v", b, ok) + } + if s := b.Sentence(); !strings.Contains(s, "nginx (pid 77)") || strings.Contains(s, "Tailscale") || strings.Contains(s, "tailscale") { + t.Errorf("nginx says %q", s) + } + + // nothing read: unknown, so nothing is said + if b, ok := whoHolds(ctx, "8848", noHolder, noServe); ok { + t.Fatalf("an unread holder was named: %+v", b) + } + if _, ok := whoHolds(ctx, "x", tsd, noServe); ok { + t.Fatal("a port that isn't a number was named") + } + + // the other port isn't the gateway's own + if b, _ := whoHolds(ctx, "8443", tsd, noServe); b.Alt != "9443" { + t.Errorf("alt for 8443: %q", b.Alt) + } +} + +// A bind that fails because the port is taken says who has it in the error +// that the log and `magpie serve` print, and an unread holder leaves the +// error as the system worded it. +func TestListenErrorNamesTheHolder(t *testing.T) { + taken, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer taken.Close() + t.Setenv("MAGPIE_ADDR", taken.Addr().String()) + _, port, _ := net.SplitHostPort(taken.Addr().String()) + + wasHolder, wasServes := readHolder, readServes + defer func() { + readHolder, readServes = wasHolder, wasServes + ClearHeld() + }() + readHolder = func(context.Context, int) (proc.Holder, bool) { + return proc.Holder{PID: 612, Name: "tailscaled", Path: "/usr/sbin/tailscaled"}, true + } + readServes = noServe + + err = New().ListenAndServe(t.Context()) + if err == nil { + t.Fatal("listened on a taken port") + } + if !addrInUse(err) { + t.Fatalf("not taken as an address in use: %v", err) + } + if !strings.Contains(err.Error(), "port "+port+" is held by Tailscale (tailscaled) (pid 612)") { + t.Fatalf("the holder isn't named: %v", err) + } + if h := LastHeld(); h == nil || !h.Tailscale || h.Port != port { + t.Fatalf("LastHeld %+v", h) + } + + // nobody read: the system's words alone, and nothing kept + readHolder = noHolder + err = New().ListenAndServe(t.Context()) + if err == nil || !addrInUse(err) || strings.Contains(err.Error(), "held by") { + t.Fatalf("an unread holder changed the error: %v", err) + } + if h := LastHeld(); h != nil { + t.Fatalf("LastHeld kept %+v", h) + } +} + +// A listen that fails for another reason isn't taken for a busy port. +func TestAddrInUseIsOnlyThat(t *testing.T) { + _, err := net.Listen("tcp", "256.256.256.256:1") + if err == nil || addrInUse(err) { + t.Fatalf("a bad address: %v", err) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 06da67b7a..d2c7be369 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -333,6 +333,9 @@ type stateJSON struct { // GatewayOther is a magpie of another version serving the gateway in // this one's place, which the Agents page says (gateway_older.go) GatewayOther *gatewaySkew `json:"gatewayOther,omitempty"` + // GatewayHeld: the program that has the gateway's port when this magpie + // couldn't listen on it, as far as it could be read (gateway.PortHeld) + GatewayHeld *gateway.PortHeld `json:"gatewayHeld,omitempty"` } // unlistedJSON is a model of a provider kept for routing groups, and the @@ -3111,6 +3114,7 @@ func state() stateJSON { s.ConfigBlocked = configBlocked() if served.Load() == nil { s.GatewayOther = gatewayOther.Load() + s.GatewayHeld = gateway.LastHeld() } for _, e := range provider.Served() { if e.Group == "" { diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 766d94e16..a6e4ccb18 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -998,41 +998,14 @@ body.panel .row.pref.flash { border-radius: 10px; } /* packed into columns (packUsage): each card as tall as itself, placed on rows a pixel high, the gap between cards in its place on them (#860) */ .subscription-usage.packed { grid-auto-rows: 1px; row-gap: 0; } -/* the allowances as a table: a row an account (quotatable.js); wider than the - page, it scrolls in its own box with the subscription held at the left */ -.subscription-usage.tabled { display: block; } -.qt-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: 10px; background: var(--card); } -.qt { width: 100%; min-width: 560px; border-collapse: separate; border-spacing: 0; font-size: 12px; } -.qt th, .qt td { padding: 8px 10px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); } -.qt tbody tr:last-child td { border-bottom: 0; } -.qt th { padding-block: 4px; font-size: 10.5px; font-weight: 500; color: var(--muted); white-space: nowrap; } -.qt .qt-sub { position: sticky; left: 0; z-index: 1; min-width: 118px; background: var(--card); } -.qt .qt-w { min-width: 84px; width: 15%; } -.qt-sort { display: inline-flex; align-items: center; gap: 3px; padding: 2px 0; font: inherit; color: inherit; background: none; border: 0; cursor: pointer; } -.qt-sort.on { color: var(--fg); } -.qt-arrow { display: inline-block; min-width: 1ch; } -@media (hover: hover) and (pointer: fine) { .qt-sort:hover { color: var(--fg); } } -.qt-id { display: flex; align-items: center; gap: 6px; } -.qt-id .ic { width: 15px; height: 15px; flex: none; } -.qt-id b { font-weight: 600; white-space: nowrap; } -.qt .plan { display: block; margin: 2px 0 0 21px; font-size: 10.5px; color: var(--muted); text-transform: capitalize; white-space: nowrap; } -.qt .qt-acct { min-width: 120px; max-width: 220px; color: var(--fg-2); } -.qt .subscription-account { margin: 0; font-size: 12px; } -.qt .qt-acct .quota-of, .qt .qt-acct .quota-seat { color: var(--muted); } -.qt-win { display: grid; gap: 4px; } -.qt-win + .qt-win { margin-top: 8px; } -.qt-fig { font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; } -.qt-name { font-weight: 400; color: var(--muted); } -.qt-reset { font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } -.qt .qt-msg { color: var(--muted); } .subscription-card { padding: 10px 12px 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); min-width: 0; } /* a card's captions (resets, the period, a curve's dates) read at 4.5:1 or better on the card, below its figures (Jiabubu on Discord): light's --muted is 3.7:1 on white, so a card takes the controls' quiet text; dark's --muted is 4.6:1 already */ -.subscription-card, .pq-card, .quota-all, .qt-wrap { --muted: var(--ctl-fg); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; } } -:root[data-theme="dark"] :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; } +.subscription-card, .pq-card, .quota-all { --muted: var(--ctl-fg); } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card) { --muted: inherit; } } +:root[data-theme="dark"] :is(.subscription-card, .pq-card) { --muted: inherit; } .subscription-head { display: flex; align-items: center; gap: 7px; margin-bottom: 9px; } .subscription-head:last-child { margin-bottom: 0; } .subscription-head .ic { width: 17px; height: 17px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 454652099..433177595 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14604,10 +14604,6 @@ function quotaAllJS() { return (quotaAllJS.p ||= import("./quotaall.js").then(() => renderQuotas(), () => {})); } const quotaAllOf = (...a) => window.quotaAll ? quotaAll(...a) : void quotaAllJS(); -// quotatable.js: the allowances as a table, loaded once chosen. Cards or -// table is the reader's own pick on this computer, cards until then. -let quotaView = kept("quotaView", "cards"); -const quotaTableJS = () => (quotaTableJS.p ||= import("./quotatable.js").then(() => renderQuotas(), () => {})); // tiersText: a family's windows, one a line, for its tooltip. function tiersText(w) { return (w.tiers || []).map((x) => t(x.name) + " " + quotaText(x) @@ -15987,16 +15983,6 @@ function renderQuotas(lazy) { } slide(pick, "quotaMode"); } - const views = $("#quotaView"); - views.hidden = !quotas?.length; - if (!views.hidden) { - views.replaceChildren(...[["cards", "Cards"], ["table", "Table"]].map(([v, name]) => { - const b = el("button", "opt" + (v === quotaView ? " on" : ""), t(name)); - b.onclick = () => { if (v !== quotaView) { quotaView = v; keep("quotaView", v); renderQuotas(); } }; - return b; - })); - slide(views, "quotaView"); - } renderQuotaTrend(); renderQuotaHid(); if (!quotas) { @@ -16014,19 +16000,6 @@ function renderQuotas(lazy) { // less the ones hidden from it (overviewCards, the Usage page's) const shown = overviewCards(quotas); subscriptions.hidden = !shown.length; - // the table: a row an account, in the cards' order - const rows = quotaView === "table" && shown.length && (window.quotaTable ? quotaTable(byUsageOrder(keyCards(shown))) : void quotaTableJS()); - subscriptions.classList.toggle("tabled", !!rows); - if (rows) { - usagePack.disconnect(); - usagePacked = null; - subscriptions.classList.remove("packed"); - subscriptions.style.gridTemplateColumns = ""; - subscriptions.append(rows); - restoreFlash(); - restoreRefresh(); - return; - } // an agent with several accounts is one card, a section per account const groups = []; keepIcons(...was); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 795d5cbf3..128e5ad3c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,8 +4,6 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { - "Cards": "卡片", - "Table": "表格", "Quick check": "快速检测", "Test all": "全部测试", "One real call each, at the provider's price": "每项真实调用一次,按服务商的价格计费", @@ -3130,6 +3128,8 @@ const I18N = { "magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).": "magpie {v}(pid {pid})没有退出。请在系统的进程列表(活动监视器、任务管理器)里结束它。", "Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.": "端口 {port} 上的 magpie 被立即重新启动了({path},pid {pid}):有登录项或系统服务让它一直运行(LaunchAgent、systemd 单元、计划任务)。请先移除它,再重试。", "Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.": "端口 {port} 被 {path}(pid {pid})占用:请退出它,或在设置里把网关换到其他端口。", + "Port {port} is in use by {name} (pid {pid}): quit it, or move the gateway to another port in Settings.": "端口 {port} 被 {name}(pid {pid})占用:请退出它,或在设置里把网关换到其他端口。", + "Tailscale's serve or funnel has port {port}. Point it at magpie from another port: tailscale serve --https={alt} http://127.0.0.1:{port} (or move the gateway to another port in Settings).": "Tailscale 的 serve 或 funnel 占用了端口 {port}。请让它从另一个端口转发给 magpie:tailscale serve --https={alt} http://127.0.0.1:{port}(或在设置里把网关换到其他端口)。", "Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.": "端口 {port} 被其他程序占用:请退出它,或在设置里把网关换到其他端口。", "magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.": "网关由 magpie {v} 提供,它不比当前版本旧:请在那边退出它,再由这里提供网关。", "The gateway couldn't be served here: {error}": "无法在这里提供网关:{error}", @@ -5124,8 +5124,6 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { - "Cards": "卡片", - "Table": "表格", "Quick check": "快速檢測", "Test all": "全部測試", "One real call each, at the provider's price": "每項真實呼叫一次,按服務商的價格計費", @@ -8214,6 +8212,8 @@ const I18N = { "magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).": "magpie {v}(pid {pid})沒有退出。請在系統的程序列表(活動監視器、工作管理員)裡結束它。", "Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.": "連接埠 {port} 上的 magpie 被立即重新啟動了({path},pid {pid}):有登入項或系統服務讓它一直執行(LaunchAgent、systemd 單元、計劃任務)。請先移除它,再重試。", "Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.": "連接埠 {port} 被 {path}(pid {pid})佔用:請退出它,或在設定裡把閘道換到其他連接埠。", + "Port {port} is in use by {name} (pid {pid}): quit it, or move the gateway to another port in Settings.": "連接埠 {port} 被 {name}(pid {pid})佔用:請退出它,或在設定裡把閘道換到其他連接埠。", + "Tailscale's serve or funnel has port {port}. Point it at magpie from another port: tailscale serve --https={alt} http://127.0.0.1:{port} (or move the gateway to another port in Settings).": "Tailscale 的 serve 或 funnel 佔用了連接埠 {port}。請讓它從另一個連接埠轉發給 magpie:tailscale serve --https={alt} http://127.0.0.1:{port}(或在設定裡把閘道換到其他連接埠)。", "Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.": "連接埠 {port} 被其他程式佔用:請退出它,或在設定裡把閘道換到其他連接埠。", "magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.": "閘道由 magpie {v} 提供,它不比目前版本舊:請在那邊退出它,再由這裡提供閘道。", "The gateway couldn't be served here: {error}": "無法在這裡提供閘道:{error}", @@ -10229,8 +10229,6 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { - "Cards": "カード", - "Table": "表", "Quick check": "クイックチェック", "Test all": "すべてテスト", "One real call each, at the provider's price": "それぞれ実際に 1 回呼び出し、プロバイダの料金がかかります", @@ -13322,6 +13320,8 @@ const I18N = { "magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).": "magpie {v}(pid {pid})が終了しませんでした。システムのプロセス一覧(アクティビティモニタ、タスクマネージャー)で終了してください。", "Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.": "ポート {port} の magpie がすぐに再起動されました({path}、pid {pid})。ログイン項目やサービス(LaunchAgent、systemd ユニット、タスクスケジューラ)が動かし続けています。それを削除してからもう一度お試しください。", "Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.": "ポート {port} は {path}(pid {pid})が使用中です。終了するか、設定でゲートウェイを別のポートに移してください。", + "Port {port} is in use by {name} (pid {pid}): quit it, or move the gateway to another port in Settings.": "ポート {port} は {name}(pid {pid})が使用中です。終了するか、設定でゲートウェイを別のポートに移してください。", + "Tailscale's serve or funnel has port {port}. Point it at magpie from another port: tailscale serve --https={alt} http://127.0.0.1:{port} (or move the gateway to another port in Settings).": "Tailscale の serve または funnel がポート {port} を使っています。別のポートから magpie に転送してください: tailscale serve --https={alt} http://127.0.0.1:{port}(または設定でゲートウェイを別のポートに移してください)。", "Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.": "ポート {port} は他のプログラムが使用中です。終了するか、設定でゲートウェイを別のポートに移してください。", "magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.": "ゲートウェイは magpie {v} が提供しており、これより古くありません。ここで提供するには、そちらで終了してください。", "The gateway couldn't be served here: {error}": "ここでゲートウェイを提供できませんでした: {error}", @@ -15336,8 +15336,6 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { - "Cards": "Karten", - "Table": "Tabelle", "Quick check": "Schnelltest", "Test all": "Alle testen", "One real call each, at the provider's price": "Je ein echter Aufruf, zum Preis des Anbieters", @@ -18439,6 +18437,8 @@ const I18N = { "magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).": "magpie {v} (PID {pid}) wurde nicht beendet. Beenden Sie es in der Prozessliste Ihres Systems (Aktivitätsanzeige, Task-Manager).", "Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.": "magpie auf Port {port} wurde sofort wieder gestartet ({path}, PID {pid}): Ein Anmeldeobjekt oder ein Dienst hält es am Laufen (ein LaunchAgent, eine systemd-Unit, eine geplante Aufgabe). Entfernen Sie diesen und versuchen Sie es erneut.", "Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.": "Port {port} wird von {path} (PID {pid}) verwendet: Beenden Sie es oder legen Sie den Zugangspunkt in den Einstellungen auf einen anderen Port.", + "Port {port} is in use by {name} (pid {pid}): quit it, or move the gateway to another port in Settings.": "Port {port} wird von {name} (PID {pid}) verwendet: Beenden Sie es oder legen Sie den Zugangspunkt in den Einstellungen auf einen anderen Port.", + "Tailscale's serve or funnel has port {port}. Point it at magpie from another port: tailscale serve --https={alt} http://127.0.0.1:{port} (or move the gateway to another port in Settings).": "Tailscales serve oder funnel belegt Port {port}. Leiten Sie es von einem anderen Port an magpie weiter: tailscale serve --https={alt} http://127.0.0.1:{port} (oder legen Sie den Zugangspunkt in den Einstellungen auf einen anderen Port).", "Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.": "Port {port} wird von einem anderen Programm verwendet: Beenden Sie es oder legen Sie den Zugangspunkt in den Einstellungen auf einen anderen Port.", "magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.": "magpie {v} stellt den Zugangspunkt bereit und ist nicht älter als diese Version: Beenden Sie es dort, um den Zugangspunkt hier bereitzustellen.", "The gateway couldn't be served here: {error}": "Der Zugangspunkt konnte hier nicht bereitgestellt werden: {error}", diff --git a/internal/gui/assets/plugins/gateway/client.js b/internal/gui/assets/plugins/gateway/client.js index 2d8501d1f..47862ee47 100644 --- a/internal/gui/assets/plugins/gateway/client.js +++ b/internal/gui/assets/plugins/gateway/client.js @@ -172,7 +172,7 @@ function gatewayFixButton(g, older) { // gatewayFixSays is why a take-over or a restart didn't go, in the page's // language, naming the process it was function gatewayFixSays(o) { - const p = { port: o.port || "", pid: o.pid || "", path: o.path || "", v: o.version || "", error: o.error || "" }; + const p = { port: o.port || "", pid: o.pid || "", path: o.path || "", v: o.version || "", error: o.error || "", name: o.name || "", alt: o.alt || "8443" }; switch (o.reason) { case "not-magpie": return t("Port {port} is held by {path} (pid {pid}), which isn't magpie, so magpie leaves it alone. Quit it yourself, or move the gateway to another port in Settings.", p); // leslie_luo on Discord: an old magpie in OrbStack, its helper named @@ -182,7 +182,13 @@ function gatewayFixSays(o) { case "denied": return t("magpie {v} (pid {pid}, {path}) runs as another user or as administrator, so this magpie can't quit it. Quit it there.", p); case "stuck": return t("magpie {v} (pid {pid}) didn't quit. End it in your system's process list (Activity Monitor, Task Manager).", p); case "respawned": return t("Something started magpie on port {port} again at once ({path}, pid {pid}): a login item or a service keeps it running (a LaunchAgent, a systemd unit, a scheduled task). Remove that, then try again.", p); - case "taken": return p.pid + // pluoki on X: Tailscale's serve on the gateway's port number, found + // only by trial and error; the program is named when it can be read + case "taken": return o.tailscale + ? t("Tailscale's serve or funnel has port {port}. Point it at magpie from another port: tailscale serve --https={alt} http://127.0.0.1:{port} (or move the gateway to another port in Settings).", p) + : p.name && !p.path + ? t("Port {port} is in use by {name} (pid {pid}): quit it, or move the gateway to another port in Settings.", p) + : p.pid ? t("Port {port} is in use by {path} (pid {pid}): quit it, or move the gateway to another port in Settings.", p) : t("Port {port} is in use by another program: quit it, or move the gateway to another port in Settings.", p); case "other": return t("magpie {v} serves the gateway, and it isn't older than this one: quit it there to serve the gateway here.", p); @@ -285,6 +291,9 @@ function renderGateway() { who.append(name, el("div", "sub old", t("Agents' requests go through magpie {v} and are sent as it sends them, without this version's fixes. Quit it here and this one serves the gateway at once.", { v: g.version }))); } else if (g.paused) { who.append(name, el("div", "sub", t("Paused, agents are disconnected and use their own settings"))); + } else if (!g.running && state.gatewayHeld) { + // the gateway couldn't listen: what has the port, as far as it is read + who.append(name, el("div", "sub old err", gatewayFixSays({ reason: "taken", ...state.gatewayHeld }))); } else who.append(name, el("div", "sub", g.running ? [t(g.models === 1 ? "{n} model" : "{n} models", { n: g.models }), n ? t(n === 1 ? "{n} agent routed through it" : "{n} agents routed through it", { n }) : t("no agent routed through it yet"), t("five APIs, one URL")].join(" · ") : t("start it with magpie serve, or open magpie at login"))); diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index cf77af6a6..410aba4ad 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -36,7 +36,6 @@ magpie.plugin("usage", (ctx) => { -
diff --git a/internal/gui/assets/quotatable.js b/internal/gui/assets/quotatable.js deleted file mode 100644 index d0e207e80..000000000 --- a/internal/gui/assets/quotatable.js +++ /dev/null @@ -1,138 +0,0 @@ -// The Usage page's allowances as a table (zysicyj on X: a dozen-plus -// accounts are hard to scan as cards): a row an account, the subscription -// and the account first, then its windows' used (or left) share with the -// time they start again, the same readings the cards draw. app.js imports -// this once the table is chosen (quotaTableJS), so it weighs nothing on the -// core. -// -// The columns are the windows most accounts have ("5 hours", "7 days"); -// the rest of an account's go in the last column. A click on a head sorts -// by it, again the other way, a third time back to the cards' order. -const TABLE_WINDOWS = 4; -let sorted = null; // { key, down } - -// the figure a window sorts and bars by: the share as the page shows it -// (used, or left), -1 when it has none -const share = (w) => (!w || w.unlimited || quotaNoShare(w) ? -1 : quotaFill(w)); -const spanOf = (name) => { - const m = /^(\d+)\s*(hour|day|week)s?$/i.exec(name || ""); - return m ? m[1] * { hour: 1, day: 24, week: 168 }[m[2].toLowerCase()] : Infinity; -}; - -// a window's cell: its share and bar, and when it starts again -function windowCell(w, long) { - const box = el("div", "qt-win"); - if (!w) return box; - const top = el("div", "qt-fig"); - const text = quotaText(w); - const bar = share(w) >= 0; - top.append(el("span", "qt-n", bar ? quotaFill(w) + "%" : text)); - if (long) top.prepend(el("span", "qt-name", t(w.name)), " "); - box.append(top); - if (bar) { - const track = el("div", "quota-track"), fill = el("i"); - fill.style.width = quotaFill(w) + "%"; - track.append(fill); - box.append(track); - } - const at = w.resetsAt ? new Date(w.resetsAt) : null; - if (at) box.append(el("div", "qt-reset", at > Date.now() ? resetClock(at) : t("Reset time passed"))); - box.title = tipLines(t(w.name) + " · " + text, at && resetText(at, at.toLocaleString(intlLang())), w.tiers && tiersText(w)); - return box; -} - -function quotaTable(subs) { - const rows = subs.map((sub, order) => ({ sub, order, ws: sub.error ? [] : familyWindows(sub.windows) || [] })); - // the windows most rows have, by their span - const count = new Map(); - for (const r of rows) for (const w of new Set(r.ws.filter((x) => !x.members).map((x) => x.name))) count.set(w, (count.get(w) || 0) + 1); - const names = [...count.keys()].map((n, i) => [n, i]).sort(([a, i], [b, j]) => count.get(b) - count.get(a) || i - j).slice(0, TABLE_WINDOWS) - .sort(([a, i], [b, j]) => spanOf(a) - spanOf(b) || i - j).map(([n]) => n); - const extra = (r) => r.ws.filter((w) => !names.includes(w.name)); - const bare = (r) => r.sub.balance && !r.ws.length && !r.sub.error; // a balance and no window - const more = rows.some((r) => extra(r).length || (r.sub.balance && r.ws.length)) || (!names.length && rows.some(bare)); - const value = (r, key) => key === "sub" ? quotaName(r.sub).toLowerCase() - : key === "acct" ? (r.sub.alias || r.sub.user || "").toLowerCase() || null - : Math.max(-1, ...r.ws.filter((w) => w.name === key).map(share)); - if (sorted && sorted.key !== "sub" && sorted.key !== "acct" && !names.includes(sorted.key)) sorted = null; - const list = sorted ? [...rows].sort((a, b) => { - const x = value(a, sorted.key), y = value(b, sorted.key); - // a row with nothing here stays below the rest either way - const none = (v) => v === null || v < 0; - if (none(x) !== none(y)) return none(x) ? 1 : -1; - return (x < y ? -1 : x > y ? 1 : 0) * (sorted.down ? -1 : 1) || a.order - b.order; - }) : rows; - - const wrap = el("div", "qt-wrap"); - const table = el("table", "qt"); - const head = el("tr"); - const th = (key, label, cls = "") => { - const c = el("th", cls); - const on = sorted?.key === key; - c.scope = "col"; - c.setAttribute("aria-sort", on ? (sorted.down ? "descending" : "ascending") : "none"); - const b = el("button", "qt-sort" + (on ? " on" : ""), label); - b.type = "button"; - const arrow = el("span", "qt-arrow", on ? (sorted.down ? "↓" : "↑") : ""); - arrow.setAttribute("aria-hidden", "true"); - b.append(arrow); - b.onclick = () => { - // windows start at the most used, names at A - const first = key !== "sub" && key !== "acct"; - sorted = !on ? { key, down: first } : sorted.down === first ? { key, down: !first } : null; - renderQuotas(); - }; - c.append(b); - return c; - }; - head.append(th("sub", t("Subscription"), "qt-sub"), th("acct", t("Account"), "qt-acct")); - for (const n of names) head.append(th(n, t(n), "qt-w")); - if (more) head.append(el("th", "qt-w", t("Other"))); - table.append(el("thead", "", head)); - - const body = el("tbody"); - for (const { sub, ws } of list) { - const tr = el("tr"); - tr.dataset.card = trayCardID(sub); - tr.dataset.provider = sub.provider; - const s = el("td", "qt-sub"); - const who = el("div", "qt-id"); - who.append(icon(sub.icon), el("b", "", quotaName(sub))); - s.append(who); - if (sub.plan || sub.until) s.append(planSpan(sub)); - const a = el("td", "qt-acct"); - const name = el("div", "subscription-account"); - name.append(...quotaWho(sub)); - a.append(name); - tr.append(s, a); - const cols = names.length + (more ? 1 : 0); - if (sub.error) { - const e = el("td", "qt-msg", quotaError(sub.error, sub)); - e.colSpan = cols; - e.title = sub.error; - tr.append(e); - } else { - if (bare({ sub, ws })) { - const b = el("td", "qt-msg", t("{n} left", { n: sub.balance })); - b.colSpan = cols; - tr.append(b); - } else for (const n of names) { - const w = ws.find((x) => x.name === n); - const c = el("td", "qt-w"); - if (w) c.append(windowCell(w)); - tr.append(c); - } - if (more && !bare({ sub, ws })) { - const o = el("td", "qt-w qt-other"); - for (const w of extra({ ws })) o.append(windowCell(w, true)); - if (sub.balance) o.append(el("div", "qt-fig", t("{n} left", { n: sub.balance }))); - tr.append(o); - } - } - body.append(tr); - } - table.append(body); - wrap.append(table); - return wrap; -} -window.quotaTable = quotaTable; diff --git a/internal/gui/backend.go b/internal/gui/backend.go index 852b3fd3a..1c9c5c23a 100644 --- a/internal/gui/backend.go +++ b/internal/gui/backend.go @@ -165,12 +165,17 @@ func serveGatewayLocked() *gateway.Server { if gateway.Taken() { if !takenSaid.Swap(true) { log.Printf("gateway: %s is taken but doesn't answer as magpie yet; this magpie serves the gateway once it is free", gateway.URL()) + // who has it, when that can be read: the page says it too + if h, ok := gateway.NoteHeld(); ok { + log.Printf("gateway: %s", h.Sentence()) + } } return nil } } takenSaid.Store(false) gatewayOther.Store(nil) + gateway.ClearHeld() gw := gateway.New() served.Store(gw) serving.Add(1) diff --git a/internal/gui/gateway_takeover.go b/internal/gui/gateway_takeover.go index 1f38d589e..da0b6a884 100644 --- a/internal/gui/gateway_takeover.go +++ b/internal/gui/gateway_takeover.go @@ -40,6 +40,12 @@ type gatewayFixJSON struct { Port string `json:"port,omitempty"` Version string `json:"version,omitempty"` Error string `json:"error,omitempty"` // the system's own words + // Name, Tailscale and Alt: for "taken", the program that has the port + // and whether it is Tailscale's serve or funnel, with another port to + // give that (gateway.PortHeld); left out when the holder isn't read + Name string `json:"name,omitempty"` + Tailscale bool `json:"tailscale,omitempty"` + Alt string `json:"alt,omitempty"` } func gatewayFixRoutes(mux *http.ServeMux) { @@ -141,6 +147,21 @@ func startHere() gatewayFixJSON { break } } + if out.Reason == "taken" { + if h := gateway.LastHeld(); h != nil || out.PID == 0 { + if h == nil { + if n, ok := gateway.NoteHeld(); ok { + h = &n + } + } + if h != nil { + out.Name, out.Tailscale, out.Alt = h.Name, h.Tailscale, h.Alt + if out.PID == 0 { + out.PID, out.Path = h.PID, h.Path + } + } + } + } return out } diff --git a/internal/gui/tests/gateway-port-holder.test.cjs b/internal/gui/tests/gateway-port-holder.test.cjs new file mode 100644 index 000000000..d5961a6e1 --- /dev/null +++ b/internal/gui/tests/gateway-port-holder.test.cjs @@ -0,0 +1,101 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// pluoki on X: Tailscale's serve held the gateway's port and the page said +// only "another program". With the gateway not running and the backend +// naming what holds the port (state.gatewayHeld), the Gateway card says so: +// Tailscale gets the way out (serve it from another port that forwards to +// magpie), another program is named, and with nothing read the card keeps +// its old line. The Start button's answer says the same. In every language. +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"); + +function fixture(lang, world) { + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (route.request().method() === "POST" && url.pathname.startsWith("/api/gateway/")) return json(world.answer); + if (route.request().method() !== "GET" && url.pathname.startsWith("/api/")) return json({}); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, gatewayHeld: world.held }); + if (url.pathname === "/api/providers") { + return json({ providers: [], gateway: { running: false, mine: false, window: true, url: "http://127.0.0.1:8848", calls: [], groups: [], models: 0 } }); + } + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: false, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const ts = { port: "8848", tailscale: true, alt: "8443" }; +const words = { + en: { tail: /Tailscale's serve or funnel has port 8848\. .*tailscale serve --https=8443 http:\/\/127\.0\.0\.1:8848.*another port in Settings/, named: /Port 8848 is in use by nginx \(pid 77\): quit it/, old: /start it with magpie serve/ }, + zh: { tail: /Tailscale 的 serve 或 funnel 占用了端口 8848。.*tailscale serve --https=8443 http:\/\/127\.0\.0\.1:8848.*其他端口/, named: /端口 8848 被 nginx(pid 77)占用:请退出它/, old: /magpie serve/ }, + "zh-TW": { tail: /Tailscale 的 serve 或 funnel 佔用了連接埠 8848。.*tailscale serve --https=8443 http:\/\/127\.0\.0\.1:8848.*其他連接埠/, named: /連接埠 8848 被 nginx(pid 77)佔用:請退出它/, old: /magpie serve/ }, + ja: { tail: /Tailscale の serve または funnel がポート 8848 を使っています。.*tailscale serve --https=8443 http:\/\/127\.0\.0\.1:8848.*別のポート/, named: /ポート 8848 は nginx(pid 77)が使用中です/, old: /magpie serve/ }, + de: { tail: /Tailscales serve oder funnel belegt Port 8848\. .*tailscale serve --https=8443 http:\/\/127\.0\.0\.1:8848.*anderen Port/, named: /Port 8848 wird von nginx \(PID 77\) verwendet/, old: /magpie serve/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: the gateway card names what holds its port`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch()); + t.after(() => browser.close()); + const errors = []; + const open = async (world) => { + const context = await browser.newContext({ viewport: { width: 420, height: 520 }, reducedMotion: "reduce" }); + const page = await context.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, world)); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gateway .state").waitFor(); + return { context, page }; + }; + const sub = (page) => page.locator("#gateway .sub"); + + // Tailscale's serve, the daemon out of sight + { + const { context, page } = await open({ held: ts, answer: {} }); + assert.match(await sub(page).textContent(), w.tail); + assert(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), "the page scrolls sideways"); + await context.close(); + } + // another program, named + { + const { context, page } = await open({ held: { port: "8848", name: "nginx", pid: 77 }, answer: {} }); + assert.match(await sub(page).textContent(), w.named); + await context.close(); + } + // the holder not read: the card's old line, nothing made up + { + const { context, page } = await open({ held: undefined, answer: {} }); + assert.match(await sub(page).textContent(), w.old); + assert.equal(await page.locator("#gateway .sub.err").count(), 0); + await context.close(); + } + // Start's own answer, when the page had not been told + { + const world = { held: undefined, answer: { ok: false, reason: "taken", port: "8848", pid: 612, name: "tailscaled", tailscale: true, alt: "8443" } }; + const { context, page } = await open(world); + await page.locator("#gateway .gw-fix").click(); + await page.locator("#gateway .sub.err").waitFor(); + assert.match(await page.locator("#gateway .sub.err").textContent(), w.tail); + await context.close(); + } + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 99b4e26d1..e2ecbeb9b 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -150,7 +150,7 @@ test("compat.js is the first of the page's own scripts", async () => { // the pointer comes over the sidebar, whatsnew.js when release notes // open, claudemode.js when a Claude provider's editor opens, ctxtext.js // when a context window part is opened, resetask.js when a Codex reset's - // Use is pressed, quotaall.js when a provider has two accounts, quotatable.js when the Usage page's table is picked, + // Use is pressed, quotaall.js when a provider has two accounts, // quitask.js when a Quit asks first, proxies.js when Settings draws its saved proxies, checkinnow.js when Settings' Check // in now for one account is pressed, autobackup.js when Settings draws // Sync, scrollends.js on the window's first scroll, profilerename.js @@ -178,7 +178,7 @@ test("compat.js is the first of the page's own scripts", async () => { // pipecheck.js when Settings draws Models; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/usage-quota-table.test.cjs b/internal/gui/tests/usage-quota-table.test.cjs deleted file mode 100644 index 1c19dde72..000000000 --- a/internal/gui/tests/usage-quota-table.test.cjs +++ /dev/null @@ -1,153 +0,0 @@ -// Run with Node's test runner and Playwright on the module path; see README.md. -// The Usage page's allowances as a table beside the cards (zysicyj on X: "a -// dozen-plus accounts, the waterfall is hard to scan, could it be a -// table"). Cards stay the default and the table is the reader's own pick, -// remembered on this computer: a row an account, its subscription and -// account first, then its windows' share and when they start again; a click -// on a head sorts by it, again the other way, a third time back to the -// cards' order. A narrow window scrolls the table in its own box, never the -// page. Both engines, every language, wide and narrow; no backend, the API -// is faked here. -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 H = 3600e3; -const at = (h) => new Date(Date.now() + h * H).toISOString(); -const w = (name, used, h) => ({ name, used, resetsAt: at(h) }); -// as a user with a dozen-plus accounts has them: several of one agent, -// plans with other windows, a balance, a failed read -const quotas = [ - ...[["a", 20, 40], ["b", 90, 10], ["c", 55, 75], ["d", 5, 99]].map(([u, five, week]) => ( - { provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Plus", user: u + "@example.com", windows: [w("5 hours", five, 2), w("7 days", week, 90)] })), - ...[["e", 33, 12], ["f", 71, 61], ["g", 9, 3]].map(([u, five, week]) => ( - { provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Max 5x", user: u + "@example.com", windows: [w("5 hours", five, 3), w("7 days", week, 80), w("7 days Opus", 14, 80)] })), - { provider: "antigravity", name: "Antigravity", icon: "antigravity-color", plan: "Google AI Pro", user: "h@example.com", windows: [ - { name: "Gemini 3 Flash", family: "Gemini", used: 100, resetsAt: at(13) }, { name: "Claude Sonnet 4.6", family: "Claude", used: 0, resetsAt: at(5) }] }, - { provider: "kimi", name: "Kimi", icon: "kimi", user: "i@example.com", windows: [w("Weekly", 42, 70)] }, - { provider: "zai", name: "Z.ai", icon: "zai", user: "j@example.com", windows: [w("5 hours", 64, 1), w("Weekly", 12, 70)] }, - { provider: "deepseek", name: "DeepSeek", icon: "deepseek", windows: [], balance: "¥17.41" }, - { provider: "minimax", name: "MiniMax", icon: "minimax", user: "k@example.com", windows: [], error: "unauthorized" }, - { provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Pro", user: "l@example.com", windows: [w("5 hours", 0, 5), w("7 days", 0, 160)] }, - { provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Pro", user: "m@example.com", windows: [w("5 hours", 12, 4), w("7 days", 25, 100)] }, - { provider: "kimi", name: "Kimi", icon: "kimi", user: "n@example.com", windows: [w("Weekly", 77, 70)] }, -]; - -function serve(lang, left) { - const settings = { theme: "light", lang, tray: "panel", quotaLeft: left, currency: "usd" }; - return async (route) => { - const url = new URL(route.request().url()); - const json = (data) => route.fulfill({ json: data }); - if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); - if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); - if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings }); - if (url.pathname === "/api/settings") return json(settings); - if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); - if (url.pathname === "/api/usage/quotas") return json(quotas); - if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); - if (url.pathname === "/api/plugins") return json({ plugins: [] }); - 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 CARDS = { en: "Cards", zh: "卡片", "zh-TW": "卡片", ja: "カード", de: "Karten" }; -const TABLE = { en: "Table", zh: "表格", "zh-TW": "表格", ja: "表", de: "Tabelle" }; - -for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { - for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { - for (const width of [1100, 420]) { - test(`${engine} ${lang} ${width}px: the allowances as cards or a table`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); - page.setDefaultTimeout(5000); - page.setDefaultNavigationTimeout(60000); - const errors = []; - page.on("pageerror", (e) => errors.push(e.message)); - await page.route("**/*", serve(lang, false)); - await page.goto("http://magpie.test/?view=usage"); - await page.waitForSelector("#subscriptionUsage .subscription-card"); - - // cards until the reader picks the table - assert.equal(await page.locator(".qt").count(), 0); - assert.equal(await page.locator("#quotaView .opt.on").innerText(), CARDS[lang]); - assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), null, "nothing is saved until the reader picks"); - - await page.locator("#quotaView .opt", { hasText: TABLE[lang] }).click(); - await page.waitForSelector("#subscriptionUsage .qt tbody tr"); - assert.equal(await page.locator("#subscriptionUsage .subscription-card").count(), 0); - // a row an account (a card's several accounts are rows too) - const accounts = quotas.length; - assert.equal(await page.locator(".qt tbody tr").count(), accounts); - const heads = await page.$$eval(".qt thead th", (ths) => ths.map((x) => x.textContent.trim())); - assert.equal(heads.length, 2 + 4 + 1, `${heads}`); - // the cards' figures, the same readings - const row = await page.$eval('.qt tbody tr:nth-child(1)', (tr) => tr.innerText.replace(/\s+/g, " ")); - assert.match(row, /Codex/); - assert.match(row, /a@example\.com/); - assert.match(row, /20%/); - assert.match(row, /40%/); - // when each starts again - assert.ok((await page.$$eval(".qt .qt-reset", (x) => x.length)) >= accounts, "resets are shown"); - // a failed read and a balance say so across the windows - assert.equal(await page.locator('.qt tbody tr:has-text("¥17.41")').count(), 1); - assert.equal(await page.locator(".qt tbody tr .qt-msg").count(), 2); - - // the pick is remembered - assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), '"table"'); - await page.reload(); - await page.waitForSelector("#subscriptionUsage .qt tbody tr"); - assert.equal(await page.locator("#quotaView .opt.on").innerText(), TABLE[lang]); - - // sorted by a window: the most used first, again the least, then the cards' order - const first = () => page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " ")); - const fiveHours = page.locator(".qt thead th.qt-w .qt-sort").first(); - await fiveHours.click(); - assert.match(await first(), /b@example\.com/); - assert.equal(await page.locator('.qt thead th[aria-sort="descending"]').count(), 1); - await page.locator(".qt thead th.qt-w .qt-sort").first().click(); - assert.match(await first(), /l@example\.com/, "ascending: unused first"); - assert.equal(await page.locator('.qt thead th[aria-sort="ascending"]').count(), 1); - await page.locator(".qt thead th.qt-w .qt-sort").first().click(); - assert.match(await first(), /a@example\.com/, "back to the cards' order"); - assert.equal(await page.locator('.qt thead th[aria-sort]:not([aria-sort="none"])').count(), 0); - // by account, A first - await page.locator(".qt thead th.qt-acct .qt-sort").click(); - assert.match(await first(), /a@example\.com/); - - // the page itself never scrolls sideways; the table scrolls in its box - const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); - assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); - const box = await page.$eval(".qt-wrap", (b) => ({ w: b.clientWidth, s: b.scrollWidth, page: document.documentElement.clientWidth, right: b.getBoundingClientRect().right })); - assert.ok(box.right <= box.page + 1, "the table's box stays inside the page"); - if (width === 420) assert.ok(box.s > box.w, "a narrow table scrolls in its box"); - - // back to the cards - await page.locator("#quotaView .opt", { hasText: CARDS[lang] }).click(); - await page.waitForSelector("#subscriptionUsage .subscription-card"); - assert.equal(await page.locator(".qt").count(), 0); - assert.equal(await page.evaluate(() => document.querySelector("#subscriptionUsage").classList.contains("tabled")), false); - assert.deepEqual(errors, []); - }); - } - } - test(`${engine}: Left reads in the table too`, async (t) => { - const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); - t.after(() => browser.close()); - const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); - page.setDefaultTimeout(5000); - await page.addInitScript(() => localStorage.setItem("magpie.quotaView", '"table"')); - await page.route("**/*", serve("en", true)); - await page.goto("http://magpie.test/?view=usage"); - await page.waitForSelector("#subscriptionUsage .qt tbody tr"); - const row = await page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " ")); - assert.match(row, /80%/); - assert.match(row, /60%/); - }); -} diff --git a/internal/proc/holder.go b/internal/proc/holder.go new file mode 100644 index 000000000..7ffa433c7 --- /dev/null +++ b/internal/proc/holder.go @@ -0,0 +1,148 @@ +package proc + +import ( + "context" + "encoding/json" + "net" + "os" + "path/filepath" + "runtime" + "slices" + "strconv" + "strings" +) + +// Who holds a port, for a message that names it (pluoki on X: Tailscale's +// `tailscale serve` kept magpie's gateway port, and the page said only +// "another program"). Only read, never ended: Terminate and Kill are the +// take-over's, and only for a magpie. + +// Holder is a process listening on a port. +type Holder struct { + PID int + Name string // the program's name, without a folder or .exe + Path string // where it runs from, "" when the system won't say +} + +// PortHolder is the first process other than this one that this user can +// see listening on TCP port. false when none is seen, or the read failed: +// an unreadable holder is unknown, never "none". +func PortHolder(ctx context.Context, port int) (Holder, bool) { + pids, err := ListeningOn(ctx, port) + if err != nil { + return Holder{}, false + } + for _, pid := range pids { + if pid == os.Getpid() { + continue + } + h := Holder{PID: pid} + h.Path, _ = Executable(pid) + if h.Path != "" { + h.Name = programName(h.Path) + } else { + h.Name = programName(processName(pid)) + } + return h, true + } + return Holder{}, false +} + +// programName is the file name of a program's path, without .exe. +func programName(p string) string { + if p == "" { + return "" + } + n := filepath.Base(filepath.Clean(strings.ReplaceAll(p, `\`, "/"))) + n = strings.TrimSuffix(n, ".exe") + if n == "." || n == "/" { + return "" + } + return n +} + +// IsTailscale says whether the holder is Tailscale's: tailscaled, the +// tailscale CLI, the Mac app (Tailscale.app, whose network extension is +// io.tailscale.ipn.macsys.network-extension) or the Windows service. +func (h Holder) IsTailscale() bool { + s := strings.ToLower(strings.ReplaceAll(h.Path+"/"+h.Name, `\`, "/")) + return strings.Contains(s, "tailscale") +} + +// TailscaleServes says whether Tailscale's serve or funnel is set to answer +// on port, as `tailscale serve status --json` says it. The daemon runs as +// root, so its sockets are often out of this user's sight and PortHolder +// finds nobody; Tailscale itself still tells. Read only, within ctx: false +// for no Tailscale, no answer or output that doesn't parse. +func TailscaleServes(ctx context.Context, port int) bool { + bin := tailscaleCLI() + if bin == "" { + return false + } + out, err := CommandContext(ctx, bin, "serve", "status", "--json").Output() + if err != nil { + return false + } + return slices.Contains(servePorts(out), port) +} + +// tailscaleCLI is the tailscale command: on PATH, or where the Mac app and +// the Windows installer put it. +func tailscaleCLI() string { + if p, err := Look("tailscale"); err == nil { + return p + } + var cand []string + switch runtime.GOOS { + case "darwin": + cand = []string{"/Applications/Tailscale.app/Contents/MacOS/Tailscale"} + case "windows": + for _, k := range []string{"ProgramFiles", "ProgramFiles(x86)"} { + if d := os.Getenv(k); d != "" { + cand = append(cand, filepath.Join(d, "Tailscale", "tailscale.exe")) + } + } + } + for _, c := range cand { + if _, err := os.Stat(c); err == nil { + return c + } + } + return "" +} + +// servePorts is the ports `tailscale serve status --json` has: Tailscale's +// ipn.ServeConfig, whose TCP map is keyed by port ("443") and whose Web +// and AllowFunnel maps are keyed by host:port ("host.tailnet.ts.net:8848"). +// A warning line before the JSON (a client older than its daemon prints +// one) is skipped. +func servePorts(out []byte) []int { + if i := strings.IndexByte(string(out), '{'); i > 0 { + out = out[i:] + } + var cfg struct { + TCP map[string]json.RawMessage `json:"TCP"` + Web map[string]json.RawMessage `json:"Web"` + AllowFunnel map[string]json.RawMessage `json:"AllowFunnel"` + } + if json.Unmarshal(out, &cfg) != nil { + return nil + } + var ps []int + add := func(s string) { + if n, err := strconv.Atoi(s); err == nil && !slices.Contains(ps, n) { + ps = append(ps, n) + } + } + for k := range cfg.TCP { + add(k) + } + for _, m := range []map[string]json.RawMessage{cfg.Web, cfg.AllowFunnel} { + for k := range m { + if _, p, err := net.SplitHostPort(k); err == nil { + add(p) + } + } + } + return ps +} diff --git a/internal/proc/holder_test.go b/internal/proc/holder_test.go new file mode 100644 index 000000000..3b4836988 --- /dev/null +++ b/internal/proc/holder_test.go @@ -0,0 +1,185 @@ +package proc + +import ( + "bufio" + "context" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strconv" + "testing" + "time" +) + +// PortHolder names the program another process keeps a port with: a child +// of the test, started under a name of its own, listening on a port of its +// own; and this process, which has the port too, is not the answer. +func TestPortHolderNamesTheProgram(t *testing.T) { + probe, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := probe.Addr().(*net.TCPAddr).Port + probe.Close() + + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(self) + if err != nil { + t.Fatal(err) + } + name := "tailscaled-fake" + bin := filepath.Join(t.TempDir(), name) + if runtime.GOOS == "windows" { + bin += ".exe" + } + if err := os.WriteFile(bin, b, 0o755); err != nil { + t.Fatal(err) + } + cmd := exec.Command(bin, "-test.run=^$") + cmd.Env = append(os.Environ(), "MAGPIE_PROC_LISTEN=127.0.0.1:"+strconv.Itoa(port)) + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { stdin.Close(); cmd.Process.Kill(); cmd.Wait() }) + line, _ := bufio.NewReader(out).ReadString('\n') + if line != "listening\n" { + t.Fatalf("the child said %q", line) + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + h, ok := PortHolder(ctx, port) + if !ok { + t.Fatalf("port %d is held by pid %d, and nobody was read", port, cmd.Process.Pid) + } + if h.PID != cmd.Process.Pid || h.Name != name { + t.Fatalf("holder %+v, want pid %d named %q", h, cmd.Process.Pid, name) + } + if !h.IsTailscale() { + t.Fatalf("%+v is not taken for Tailscale's", h) + } + + // a port this process holds itself has no other holder + mine, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer mine.Close() + if h, ok := PortHolder(ctx, mine.Addr().(*net.TCPAddr).Port); ok { + t.Fatalf("this process was named as another's: %+v", h) + } +} + +// Nothing listening is no holder, and a failed read is no holder either: +// unknown, never a made-up name. +func TestPortHolderUnknownIsNotNamed(t *testing.T) { + probe, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := probe.Addr().(*net.TCPAddr).Port + probe.Close() + if h, ok := PortHolder(context.Background(), port); ok { + t.Fatalf("a free port has a holder: %+v", h) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if h, ok := PortHolder(ctx, port); ok { + t.Fatalf("a cancelled read named %+v", h) + } +} + +func TestIsTailscale(t *testing.T) { + for h, want := range map[Holder]bool{ + {Name: "tailscaled", Path: "/usr/sbin/tailscaled"}: true, + {Name: "Tailscale", Path: "/Applications/Tailscale.app/Contents/MacOS/Tailscale"}: true, + {Name: "tailscaled", Path: `C:\Program Files\Tailscale\tailscaled.exe`}: true, + {Name: "io.tailscale.ipn.macsys.network-extension"}: true, + {Name: "nginx", Path: "/usr/sbin/nginx"}: false, + {Name: "magpie", Path: "/Applications/Magpie.app/Contents/MacOS/magpie"}: false, + {Name: "node", Path: "/Users/u/tools/node"}: false, + {}: false, + } { + if got := h.IsTailscale(); got != want { + t.Errorf("%+v: %v, want %v", h, got, want) + } + } +} + +func TestProgramName(t *testing.T) { + for in, want := range map[string]string{ + "/usr/sbin/tailscaled": "tailscaled", + `C:\Program Files\Tailscale\tailscaled.exe`: "tailscaled", + "/Applications/Tailscale.app/Contents/MacOS/Tailscale": "Tailscale", + "tailscaled": "tailscaled", + "": "", + } { + if got := programName(in); got != want { + t.Errorf("programName(%q) = %q, want %q", in, got, want) + } + } +} + +// `tailscale serve status --json` as Tailscale writes it (ipn.ServeConfig): +// the TCP map by port, Web and AllowFunnel by host:port. The first is a +// serve of port 8848 over HTTPS to magpie, the second a funnel. +func TestServePorts(t *testing.T) { + serve := `{ + "TCP": { + "8848": { + "HTTPS": true + } + }, + "Web": { + "mini.tail1234.ts.net:8848": { + "Handlers": { + "/": { + "Proxy": "http://127.0.0.1:3425" + } + } + } + } +}` + funnel := `{ + "TCP": {"443": {"HTTPS": true}, "8443": {"HTTPS": true}}, + "Web": { + "mini.tail1234.ts.net:443": {"Handlers": {"/": {"Proxy": "http://127.0.0.1:3000"}}}, + "mini.tail1234.ts.net:8443": {"Handlers": {"/": {"Proxy": "http://127.0.0.1:3425"}}} + }, + "AllowFunnel": {"mini.tail1234.ts.net:8443": true} +}` + // a client older than its daemon prints this before the JSON + warned := "Warning: client version \"1.94.1-td885b3477\" != tailscaled server version \"1.102.3-t9329c3677-ga522f65e9\"\n" + serve + for name, c := range map[string]struct { + in string + want []int + }{ + "serve": {serve, []int{8848}}, + "funnel": {funnel, []int{443, 8443}}, + "warning": {warned, []int{8848}}, + "none": {"{}\n", nil}, + "garbage": {"not json", nil}, + "empty": {"", nil}, + "truncated": {serve[:40], nil}, + } { + got := servePorts([]byte(c.in)) + slices.Sort(got) + if !slices.Equal(got, c.want) { + t.Errorf("%s: %v, want %v", name, got, c.want) + } + } +} diff --git a/internal/proc/listener_darwin.go b/internal/proc/listener_darwin.go index 113906722..359d135a6 100644 --- a/internal/proc/listener_darwin.go +++ b/internal/proc/listener_darwin.go @@ -56,3 +56,13 @@ func executable(pid int) (string, error) { } return "", errors.New("no program path") } + +// processName is the program's name by ps, which names any user's process +// where the path (kern.procargs2) is denied. +func processName(pid int) string { + out, err := CommandContext(context.Background(), "ps", "-o", "comm=", "-p", strconv.Itoa(pid)).Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} diff --git a/internal/proc/listener_linux.go b/internal/proc/listener_linux.go index f7520410a..330c1fc05 100644 --- a/internal/proc/listener_linux.go +++ b/internal/proc/listener_linux.go @@ -79,3 +79,12 @@ func listenInodes(table string, port int) map[string]bool { func executable(pid int) (string, error) { return os.Readlink(filepath.Join("/proc", strconv.Itoa(pid), "exe")) } + +// processName is /proc//comm, which any user may read. +func processName(pid int) string { + b, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "comm")) + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} diff --git a/internal/proc/listener_others.go b/internal/proc/listener_others.go index a54071d6b..54826238b 100644 --- a/internal/proc/listener_others.go +++ b/internal/proc/listener_others.go @@ -12,3 +12,5 @@ var errUnsupported = errors.New("not supported on this system") func listeningOn(context.Context, int) ([]int, error) { return nil, errUnsupported } func executable(int) (string, error) { return "", errUnsupported } + +func processName(int) string { return "" } diff --git a/internal/proc/listener_windows.go b/internal/proc/listener_windows.go index 64e423266..bcbb9fcc5 100644 --- a/internal/proc/listener_windows.go +++ b/internal/proc/listener_windows.go @@ -78,3 +78,14 @@ func exitWith(pid int, code uint32) error { } return nil } + +// processName is Get-Process' name, which names a service's process where +// opening it for its path is denied. +func processName(pid int) string { + out, err := CommandContext(context.Background(), "powershell", "-NoProfile", "-NonInteractive", "-Command", + `(Get-Process -Id `+strconv.Itoa(pid)+` -ErrorAction SilentlyContinue).ProcessName`).Output() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} diff --git a/internal/proc/main_test.go b/internal/proc/main_test.go index f5573ac77..74f75e0a0 100644 --- a/internal/proc/main_test.go +++ b/internal/proc/main_test.go @@ -3,6 +3,7 @@ package proc import ( "fmt" "io" + "net" "os" "testing" @@ -16,7 +17,21 @@ import ( // // With MAGPIE_PROC_SLEEP set, it runs until its stdin closes // (listener_test.go). +// +// With MAGPIE_PROC_LISTEN set to an address, it listens there first, says +// "listening" and then runs the same way (holder_test.go). func TestMain(m *testing.M) { + if addr := os.Getenv("MAGPIE_PROC_LISTEN"); addr != "" { + ln, err := net.Listen("tcp", addr) + if err != nil { + fmt.Println("error", err) + os.Exit(1) + } + defer ln.Close() + fmt.Println("listening") + io.Copy(io.Discard, os.Stdin) + os.Exit(0) + } if os.Getenv("MAGPIE_PROC_SLEEP") != "" { io.Copy(io.Discard, os.Stdin) os.Exit(0) diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 48b937860..0cde82d6a 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -596,7 +596,7 @@ type callDiskState struct { } func diskCallState(s *callFile) callDiskState { - d := callDiskState{ContentHash: s.ContentHash.String(), Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head.String(), HeadSize: s.HeadSize, + d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, Parser: callParseVersions[s.Agent], At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} if s.Dsh != nil { @@ -611,8 +611,8 @@ func diskCallState(s *callFile) callDiskState { return d } func (s callDiskState) restore() *callFile { - st := &callFile{ContentHash: parseDigest(s.ContentHash), Size: s.Size, Mod: s.Mod, Off: s.Off, - Head: parseDigest(s.Head), HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, + st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, + Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst} if len(s.Dsh) > 0 { var c dshCarry diff --git a/internal/sessions/call_revisions.go b/internal/sessions/call_revisions.go index 69789168e..b0291d550 100644 --- a/internal/sessions/call_revisions.go +++ b/internal/sessions/call_revisions.go @@ -35,7 +35,7 @@ func writeCallRevisions(st *callFile) { _ = os.Remove(path) return } - r := callRevisions{Off: st.Off, ContentHash: st.ContentHash.String(), CompactMs: st.CompactMs, Window: st.Claude.window()} + r := callRevisions{Off: st.Off, ContentHash: st.ContentHash, CompactMs: st.CompactMs, Window: st.Claude.window()} var data bytes.Buffer if gob.NewEncoder(&data).Encode(r) != nil { return @@ -57,7 +57,7 @@ func writeCallRevisions(st *callFile) { // withCallRevisions is old with the window kept for it, when old is a // Claude file's read without one and the window kept is of that same read. func withCallRevisions(old *callFile) *callFile { - if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == (digest{}) { + if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == "" { return old } data, err := os.ReadFile(callRevisionsPath(old.Path)) @@ -65,7 +65,7 @@ func withCallRevisions(old *callFile) *callFile { return old } var r callRevisions - if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || parseDigest(r.ContentHash) != old.ContentHash { + if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || r.ContentHash != old.ContentHash { return old } c := *old diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index 400abc81d..e91182df4 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -70,7 +70,7 @@ type Call struct { // what it takes to read on from off. type callFile struct { Claude *claudeUsageState - ContentHash digest + ContentHash string dirty map[int]bool // readSize is the size of the file being read (prepareCalls), for // growCalls @@ -80,7 +80,7 @@ type callFile struct { Size int64 Mod int64 // unix nanoseconds Off int64 // after the last whole line read - Head digest // of the prefix, to tell one replaced from one grown + Head string // hash of the prefix, to tell one replaced from one grown HeadSize int Path string Calls []Call @@ -392,7 +392,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile { head := headOf(f.path) var st *callFile - if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Off) == old.ContentHash { + if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Off) == old.ContentHash { if owned { st = old.cloneState() } else { @@ -411,7 +411,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile { } } st.dirty = map[int]bool{} - st.Head, st.HeadSize, st.Path = headDigest(head), len(head), f.path + st.Head, st.HeadSize, st.Path = hashHead(head), len(head), f.path st.readSize = f.size return st } @@ -1292,18 +1292,18 @@ func (st *callFile) codexCompact(i int) { } func hashHead(head string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(head))) } -func sameHead(head string, hash digest, size int) bool { - return size >= 0 && len(head) >= size && headDigest(head[:size]) == hash +func sameHead(head, hash string, size int) bool { + return size >= 0 && len(head) >= size && hashHead(head[:size]) == hash } // prefixHash checks distributed windows of the indexed prefix. Small files -// are checked in full. +// are checked in full. The version tag invalidates earlier full-file hashes. // Rewrites outside the sampled windows can go undetected; appends cost at most // 64 KiB of reads per fingerprint regardless of the session's length. -func prefixHash(path string, n int64) digest { +func prefixHash(path string, n int64) string { f, err := os.Open(path) if err != nil { - return digest{} + return "" } defer f.Close() h := sha256.New() @@ -1314,7 +1314,7 @@ func prefixHash(path string, n int64) digest { defer hashBufs.Put(buf) if n <= window*samples { if _, err = io.ReadFull(f, buf[:n]); err != nil { - return digest{} + return "" } h.Write(buf[:n]) } else { @@ -1322,12 +1322,12 @@ func prefixHash(path string, n int64) digest { off := (n - window) * i / (samples - 1) // A full window may come back with io.EOF at the file's end. if k, _ := f.ReadAt(buf[:window], off); int64(k) < window { - return digest{} + return "" } h.Write(buf[:window]) } } - return digest(h.Sum(nil)[:16]) + return fmt.Sprintf("sample-v1:%x", h.Sum(nil)) } var hashBufs = sync.Pool{New: func() any { return new([64 << 10]byte) }} diff --git a/internal/sessions/digest.go b/internal/sessions/digest.go deleted file mode 100644 index 081cbdf5d..000000000 --- a/internal/sessions/digest.go +++ /dev/null @@ -1,59 +0,0 @@ -package sessions - -import ( - "crypto/sha256" - "encoding/hex" - "strings" -) - -// digest is a file's head or sampled prefix as kept to know it again -// (headDigest, prefixHash): the first 16 bytes of its SHA-256, in the -// state itself. As hex strings, 64 and 74 bytes of their own, they were -// 144 bytes a file beside its state; 18k files' states held 2.6 MB of -// them (#2278). The zero digest is none: the file couldn't be read. -type digest [16]byte - -// MarshalText is d in hex, "" for none. -func (d digest) MarshalText() ([]byte, error) { - if d == (digest{}) { - return nil, nil - } - return []byte(hex.EncodeToString(d[:])), nil -} - -// UnmarshalText reads a digest as written, or as a magpie before it wrote -// the whole hash: the 64 hex of hashHead's, or prefixHash's "sample-v1:" -// before them, whose first 32 are this digest. A cache from before reads -// as the same files, so nothing is read again for it. Anything else is -// none, which matches no file. -func (d *digest) UnmarshalText(b []byte) error { - *d = parseDigest(string(b)) - return nil -} - -// parseDigest is the digest s spells (UnmarshalText), none when it spells -// none. -func parseDigest(s string) digest { - var d digest - s = strings.TrimPrefix(s, "sample-v1:") - if (len(s) != 32 && len(s) != 64) || s == "" { - return d - } - if _, err := hex.Decode(d[:], []byte(s[:32])); err != nil { - return digest{} - } - return d -} - -// String is d as MarshalText writes it, for the shards' gob, whose -// field stays a string so a shard written before reads the same. -func (d digest) String() string { - b, _ := d.MarshalText() - return string(b) -} - -// headDigest is the digest of a file's first bytes, head. -func headDigest(head string) digest { - sum := sha256.Sum256([]byte(head)) - return digest(sum[:16]) -} diff --git a/internal/sessions/digest_test.go b/internal/sessions/digest_test.go deleted file mode 100644 index 6785609d4..000000000 --- a/internal/sessions/digest_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package sessions - -import ( - "crypto/sha256" - "encoding/json" - "fmt" - "os" - "path/filepath" - "strings" - "testing" -) - -// A cache a magpie before digest wrote holds the whole hashes in hex. Read -// now, its files must be the same files, or every one is read again on the -// first start after the update. -func TestDigestReadsTheHashesWrittenBefore(t *testing.T) { - path := filepath.Join(t.TempDir(), "rollout.jsonl") - head := strings.Repeat(`{"type":"session_meta"}`+"\n", 3) - if err := os.WriteFile(path, []byte(head+strings.Repeat("x", 200<<10)), 0o600); err != nil { - t.Fatal(err) - } - size := int64(len(head) + 200<<10) - oldHead := fmt.Sprintf("%x", sha256.Sum256([]byte(head))) - oldHash := oldPrefixHash(path, size) - if !strings.HasPrefix(oldHash, "sample-v1:") || len(oldHead) != 64 { - t.Fatalf("old forms %q %q", oldHead, oldHash) - } - - var st state - old := fmt.Sprintf(`{"head":%q,"head_size":%d,"content_hash":%q,"size":%d}`, oldHead, len(head), oldHash, size) - if err := json.Unmarshal([]byte(old), &st); err != nil { - t.Fatal(err) - } - if !sameHead(head, st.Head, int(st.HeadSize)) || st.ContentHash != prefixHash(path, size) || st.ContentHash == (digest{}) { - t.Fatalf("an old state reads as another file: %x %x", st.Head, st.ContentHash) - } - // A shard keeps its hashes as strings: one written before restores the same. - c := callDiskState{Head: oldHead, ContentHash: oldHash}.restore() - if c.Head != st.Head || c.ContentHash != st.ContentHash { - t.Fatalf("an old shard reads as another file: %x %x", c.Head, c.ContentHash) - } - if back := diskCallState(c).restore(); back.Head != c.Head || back.ContentHash != c.ContentHash { - t.Fatal("a shard written now reads back as another file") - } - - b, err := json.Marshal(&st) - if err != nil { - t.Fatal(err) - } - var again state - if err := json.Unmarshal(b, &again); err != nil || again.Head != st.Head || again.ContentHash != st.ContentHash { - t.Fatalf("written now, read again: %s", b) - } - if strings.Contains(string(b), oldHead) || !strings.Contains(string(b), oldHead[:32]) { - t.Fatalf("not written as the digest: %s", b) - } - - // None stays none, and isn't written. - b, _ = json.Marshal(&state{}) - if strings.Contains(string(b), "head") || strings.Contains(string(b), "content_hash") { - t.Fatalf("no hash written as one: %s", b) - } - for _, s := range []string{"", "sample-v1:", "zz" + oldHead[2:], oldHead[:40]} { - if parseDigest(s) != (digest{}) { - t.Fatalf("%q read as a digest", s) - } - } -} diff --git a/internal/sessions/fingerprint_review_test.go b/internal/sessions/fingerprint_review_test.go index 8a46fbe05..2439b6435 100644 --- a/internal/sessions/fingerprint_review_test.go +++ b/internal/sessions/fingerprint_review_test.go @@ -51,7 +51,7 @@ func TestSampledPrefixFingerprint(t *testing.T) { } os.WriteFile(path, data, 0600) } - if prefixHash(path, n+1) != (digest{}) { + if prefixHash(path, n+1) != "" { t.Fatal("short read accepted") } } @@ -64,7 +64,7 @@ func BenchmarkPrefixFingerprint(b *testing.B) { for _, impl := range []struct { name string f func(string, int64) string - }{{"sampled", func(p string, n int64) string { return prefixHash(p, n).String() }}, {"without_sampling", fullPrefixHash}} { + }{{"sampled", prefixHash}, {"without_sampling", fullPrefixHash}} { b.Run(impl.name, func(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { diff --git a/internal/sessions/prefix_hash_test.go b/internal/sessions/prefix_hash_test.go index 3e979b1de..0e868d330 100644 --- a/internal/sessions/prefix_hash_test.go +++ b/internal/sessions/prefix_hash_test.go @@ -10,9 +10,8 @@ import ( "testing" ) -// oldPrefixHash is prefixHash as it was, through io.CopyN and written in -// full: a stored hash must still match after the change, or every cache -// is read again. +// oldPrefixHash is prefixHash as it was, through io.CopyN: a stored hash +// must still match after the change, or every cache is read again. func oldPrefixHash(path string, n int64) string { f, err := os.Open(path) if err != nil { @@ -46,13 +45,13 @@ func TestPrefixHashUnchangedAndUnbuffered(t *testing.T) { t.Fatal(err) } for _, n := range []int64{0, 1, 4095, 4096, 65535, 65536, 65537, 1 << 20, 3 << 20} { - if got, want := prefixHash(path, n), parseDigest(oldPrefixHash(path, n)); got != want || got == (digest{}) { + if got, want := prefixHash(path, n), oldPrefixHash(path, n); got != want || got == "" { t.Fatalf("n=%d: %q, was %q", n, got, want) } } // Past the file's end is unknown, as it was. for _, n := range []int64{3<<20 + 1, 4 << 20} { - if got := prefixHash(path, n); got != (digest{}) { + if got := prefixHash(path, n); got != "" { t.Fatalf("n=%d past the end: %q", n, got) } if old := oldPrefixHash(path, n); old != "" { diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index 1ea727bc8..08862cc4a 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -218,14 +218,14 @@ type state struct { Codex *codexUsageState `json:"-"` codexPath string // the rollout read, for its fork's parent Claude *claudeUsageState `json:"claude,omitempty"` - Head digest `json:"head,omitzero"` + Head string `json:"head,omitempty"` // int32 beside CdRead: the head is headLen bytes at most, and the 8 bytes // it saves take a state from the 448-byte size class to 416 (#2278) HeadSize int32 `json:"head_size,omitempty"` // Claude Code: parsed by a magpie that reads /cd's relocated lines // (ccRelocated), so Cwd is the folder the session was last moved to CdRead bool `json:"cd_read,omitempty"` - ContentHash digest `json:"content_hash,omitzero"` + ContentHash string `json:"content_hash,omitempty"` Size int64 `json:"size"` Mod int64 `json:"mod"` // unix nanoseconds Off int64 `json:"off"` // after the last whole line read @@ -2346,13 +2346,13 @@ func parseRead(f file, old *state, calls *callsRide) *state { headBytes := headOf(f.path) var s *state - if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Size) == old.ContentHash { + if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != "" && prefixHash(f.path, old.Size) == old.ContentHash { s = old.clone() } else { s = &state{} } s.Size, s.Mod = f.size, f.mod.UnixNano() - s.Head, s.HeadSize = headDigest(headBytes), int32(len(headBytes)) + s.Head, s.HeadSize = hashHead(headBytes), int32(len(headBytes)) s.CdRead = parser.claude s.ContentHash = prefixHash(f.path, f.size) var head func([]byte) bool diff --git a/internal/sessions/tail.go b/internal/sessions/tail.go index 55185dd98..e8c9735dc 100644 --- a/internal/sessions/tail.go +++ b/internal/sessions/tail.go @@ -17,9 +17,9 @@ type tail struct { Off int64 `json:"off"` Skip int64 `json:"skip,omitempty"` Size int64 `json:"size"` - Head digest `json:"head"` + Head string `json:"head"` HeadSize int `json:"head_size"` - Hash digest `json:"hash"` + Hash string `json:"hash"` } // markTail is the tail of a file read up to off, its first size bytes the @@ -30,10 +30,10 @@ func markTail(path string, off, skip, size int64) *tail { head = head[:size] } h := prefixHash(path, size) - if h == (digest{}) && size > 0 { + if h == "" && size > 0 { return nil } - return &tail{Off: off, Skip: skip, Size: size, Head: headDigest(head), HeadSize: len(head), Hash: h} + return &tail{Off: off, Skip: skip, Size: size, Head: hashHead(head), HeadSize: len(head), Hash: h} } // holds says whether the file at path is still the one t was read from,