Files
magpie/internal/applog/applog_test.go
T
yetone ceeb73a0f1 app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log
while chasing a Codex "hit a snag" through the gateway, and had no such
folder. Only the launch agent (magpie daemon install, written by launchd)
and a gateway magpie tui left running wrote a log; the app opened from the
Finder, the Dock or the Start menu logged to a stderr nobody reads, on
every system.

Now runGUI and runPanel (magpie, app, tray, panel, a window view, a
magpie: link) call applog.Start before gui.Run. It sends the standard
logger (the gateway, the plugin host, providers and Wails' error handler
all log through it) to app.log as well as stderr, and points
debug.SetCrashOutput at it so a panic's trace is there too:

  macOS    ~/Library/Logs/magpie/app.log
  Windows  %LOCALAPPDATA%\magpie\logs\app.log
  Linux    $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log
  portable data/logs/app.log

app.log, not serve.log: on a Mac launchd writes serve.log for the service,
another process. The file is 0600. At 5 MiB it becomes app.old.log (two
files at most); when another magpie (an update's new process) rotated it
already, it is only opened again; when it can't be moved it is emptied.
stderr goes first, through a writer that never fails, since io.MultiWriter
stops at a failed writer and an app opened from Explorer has no stderr.

Secrets: the log calls name header names and paths without queries; no
key or token was found logged (grep of log.Print* in gateway, provider,
plugin, gui, agent). scrub masks bearer/basic credentials, key/token query
parameters and sk-, AIza, gh?_ and JWT shapes anyway.

How a user finds it: Settings › About › Log, with the path, Copy and an
Open that shows its folder (POST /api/settings/log/reveal; the row is
hidden in magpie web, which writes no file). magpie log prints where every
log is (the app's, app.old.log, the service's, the tui's background
serve.log); --path the app's alone, -n N its last lines, -f follows it
across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where
is magpie's log?" and the CLI table) and privacy (files on your computer),
en/zh/ja.

Run:
At 227ce6074 on origin/main fbb1b36d1:
- mote: go test ./internal/applog ./internal/appdir ./internal/cli ok;
  -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet
  ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok;
  gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and
  no row without a log), about-website, i18n-keys: 24 of 25, the one red
  "a plugin's words are its own" ("Unmarked") is the same at origin/main
  fbb1b36d1 (#4524).
- WSL (magpie-desktop), webkit: about-log and about-website 21 of 21.
- Windows (win-run): applog, appdir, tui ok; cli ok but
  TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change).
- WSL full go test -tags nogui -timeout 45m ./... at the previous base
  03f609e3f: every package ok but reds that fail the same at origin/main
  03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514),
  TestNoCommandBypassesProc (#4491), internal/agent's install-detection
  tests (#4033, #3548), and TestCoreScriptBudget, which was this change
  (app.js 321 over): its comment is cut to one line and both budgets
  are raised by the remaining 124 bytes, with no room added.
- Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog
  is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such
  file or directory"); with proc.UserPath taken out of openApp,
  TestGatewayStartsGetUserPath is red ("runGUI doesn't call
  proc.UserPath"). The guard now follows a start into a function or func
  var of this package, since the Wails start sits behind openApp for the
  test.
- Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote
  ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie
  log and magpie log -n 3 printed it.
Not tried: the app opened from Windows Explorer or a Linux desktop
launcher for real (the paths are unit-tested per OS, the writer on
Windows and Linux); the full GUI suite (running on WSL after the push,
reds filed if they fail at origin/main too).
2026-10-31 14:45:22 +08:00

182 lines
6.4 KiB
Go

package applog
import (
"bytes"
"io"
"log"
"os"
"path/filepath"
"runtime/debug"
"strings"
"testing"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { os.Exit(testenv.RunIn(m, nil)) }
// opened is open for a test, closed with the runtime's copy of it let go
// after the test: Windows removes no folder with a file open in it.
func opened(t *testing.T, path string, limit int64) *file {
t.Helper()
w, err := open(path, limit)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = debug.SetCrashOutput(nil, debug.CrashOptions{})
w.Close()
})
return w
}
func read(t *testing.T, p string) string {
t.Helper()
b, err := os.ReadFile(p)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// What the app logs goes to app.log in the system's logs folder, as well
// as to stderr: the app opened from the Finder had no terminal, and a
// user asked for its log had none (rayem1w on X).
func TestStartWritesTheLog(t *testing.T) {
t.Cleanup(Stop)
path, err := Start("0.1.test", "app")
if err != nil {
t.Fatal(err)
}
if want := filepath.Join(appdir.Logs(), Name); path != want || Current() != want {
t.Fatalf("Start wrote %q (Current %q), want %q", path, Current(), want)
}
log.Println("gateway: a line the app logged")
got := read(t, path)
for _, want := range []string{"magpie 0.1.test started (app, pid", "this log: " + path, "gateway: a line the app logged"} {
if !strings.Contains(got, want) {
t.Errorf("the log has no %q:\n%s", want, got)
}
}
if fi, err := os.Stat(path); err != nil {
t.Fatal(err)
} else if os.PathSeparator == '/' && fi.Mode().Perm() != 0o600 {
t.Errorf("the log is %v, want 0600: it is the user's alone", fi.Mode().Perm())
}
// a second Start (the app opened again in this process) goes on in the
// same file
if _, err := Start("0.1.test", "panel"); err != nil {
t.Fatal(err)
}
log.Println("after the second start")
if got := read(t, path); !strings.Contains(got, "gateway: a line the app logged") || !strings.Contains(got, "after the second start") {
t.Errorf("the second start lost a line:\n%s", got)
}
Stop()
log.Println("after Stop")
if Current() != "" || strings.Contains(read(t, path), "after Stop") {
t.Errorf("after Stop the log is still written (Current %q)", Current())
}
}
// The log goes to stderr as well, as before; a stderr that fails (the app
// opened from Explorer has none) never keeps a line from the file.
func TestStderrToo(t *testing.T) {
dir := t.TempDir()
w := opened(t, filepath.Join(dir, Name), Limit)
var errOut bytes.Buffer
l := log.New(io.MultiWriter(quiet{&errOut}, w), "", 0)
l.Println("both")
l2 := log.New(io.MultiWriter(quiet{failing{}}, w), "", 0)
l2.Println("stderr gone")
if !strings.Contains(errOut.String(), "both") {
t.Errorf("stderr got %q", errOut.String())
}
if got := read(t, filepath.Join(dir, Name)); !strings.Contains(got, "both") || !strings.Contains(got, "stderr gone") {
t.Errorf("the file got %q", got)
}
}
type failing struct{}
func (failing) Write([]byte) (int, error) { return 0, os.ErrClosed }
// At its limit the log becomes app.old.log, over the one before, and a
// new one starts: two files at most, each about the limit.
func TestRotates(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, Name)
w := opened(t, path, 100)
line := strings.Repeat("x", 39) + "\n" // 40 bytes
for i := 0; i < 10; i++ {
if n, err := w.Write([]byte(line)); err != nil || n != len(line) {
t.Fatalf("write %d: %d, %v", i, n, err)
}
}
for _, p := range []string{path, filepath.Join(dir, OldName)} {
fi, err := os.Stat(p)
if err != nil {
t.Fatalf("%s: %v", filepath.Base(p), err)
}
if fi.Size() > 100 || fi.Size() == 0 {
t.Errorf("%s is %d bytes, want 1..100", filepath.Base(p), fi.Size())
}
}
ents, _ := os.ReadDir(dir)
if len(ents) != 2 {
t.Errorf("the folder has %d files, want 2", len(ents))
}
}
// Another magpie that rotated the log already (an update's new process
// beside the old) leaves this one to open the new file, not to rotate it
// again over the old one.
func TestRotatedByAnother(t *testing.T) {
if os.PathSeparator == '\\' {
t.Skip("Windows moves no file another process has open")
}
dir := t.TempDir()
path := filepath.Join(dir, Name)
w := opened(t, path, 100)
w.Write([]byte(strings.Repeat("a", 80) + "\n"))
// the other process: closes nothing of ours, moves the file and starts
// its own
if err := os.Rename(path, filepath.Join(dir, OldName)); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte("other\n"), 0o600); err != nil {
t.Fatal(err)
}
w.Write([]byte(strings.Repeat("b", 40) + "\n"))
if got := read(t, filepath.Join(dir, OldName)); strings.Contains(got, "other") || strings.Contains(got, "b") {
t.Errorf("app.old.log was rotated over: %q", got)
}
if got := read(t, path); !strings.HasPrefix(got, "other\n") || !strings.Contains(got, "bbbb") {
t.Errorf("app.log %q, want the other's line, then ours", got)
}
}
// What looks like a key or token is masked in the log, its first
// characters kept; the rest of the line is as written.
func TestScrub(t *testing.T) {
for in, want := range map[string]string{
"Authorization: Bearer abcdefghijklmnop1234": "Authorization: Bearer …",
"GET https://x.example/v1/models?key=AIzaSyAbc123&alt=sse": "GET https://x.example/v1/models?key=…&alt=sse",
"refresh https://auth.example/t?refresh_token=rt.abcdef done": "refresh https://auth.example/t?refresh_token=… done",
"upstream said: invalid key sk-ant-api03-abcdefghijklmnopqrstuv": "upstream said: invalid key sk-ant-…",
"key sk-proj-abcdefghijklmnopqrstuvwx refused": "key sk-proj-… refused",
"google AIzaSyA1234567890abcdefghijklmnopq": "google AIza…",
"github gho_abcdefghijklmnopqrstuvwxyz0123 expired": "github gho_… expired",
"jwt eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N": "jwt eyJ…",
"gateway: claude/claude-sonnet-4-5 200 in 1.2s (codex, 3 tries)": "gateway: claude/claude-sonnet-4-5 200 in 1.2s (codex, 3 tries)",
"provider: sk-short is not a key": "provider: sk-short is not a key",
} {
if got := string(scrub([]byte(in))); got != want {
t.Errorf("scrub(%q) = %q, want %q", in, got, want)
}
}
}