Files
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

143 lines
4.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
import (
"bytes"
"io"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/applog"
)
// logOut runs `magpie log` with args and returns what it printed.
func logOut(t *testing.T, args ...string) (string, error) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
done := make(chan string)
go func() { b, _ := io.ReadAll(r); done <- string(b) }()
err = run(append([]string{"log"}, args...))
w.Close()
os.Stdout = old
out := <-done
r.Close()
return out, err
}
func writeLog(t *testing.T, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(applog.Path()), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(applog.Path(), []byte(s), 0o600); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Remove(applog.Path()) })
}
// `magpie log` says where the app's log is, there or not yet; --path
// prints the path alone, for a script or a reply to paste it in.
func TestLogSaysWhere(t *testing.T) {
os.Remove(applog.Path())
out, err := logOut(t)
if err != nil || !strings.HasPrefix(out, applog.Path()+"\n") || !strings.Contains(out, "nothing yet") {
t.Fatalf("magpie log, no log yet: %v\n%s", err, out)
}
writeLog(t, "one\n")
if out, err = logOut(t); err != nil || !strings.Contains(out, "Settings › About › Log") {
t.Errorf("magpie log: %v\n%s", err, out)
}
if out, err = logOut(t, "--path"); err != nil || out != applog.Path()+"\n" {
t.Errorf("magpie log --path: %v, %q, want the path alone", err, out)
}
}
// -n prints the app log's last lines.
func TestLogLastLines(t *testing.T) {
writeLog(t, "one\ntwo\nthree\nfour\n")
for n, want := range map[string]string{"2": "three\nfour\n", "0": "", "9": "one\ntwo\nthree\nfour\n"} {
if out, err := logOut(t, "-n", n); err != nil || out != want {
t.Errorf("magpie log -n %s: %v, %q, want %q", n, err, out, want)
}
}
os.Remove(applog.Path())
if _, err := logOut(t, "-n", "5"); err == nil || !strings.Contains(err.Error(), "isn't there yet") {
t.Errorf("magpie log -n with no log: %v", err)
}
}
// A flag or value it doesn't know is refused, never taken for something.
func TestLogRefusesWhatItDoesntKnow(t *testing.T) {
for _, args := range [][]string{{"--bogus"}, {"-n"}, {"-n", "many"}, {"-n", "-3"}, {"--path", "-f"}, {"app.log"}} {
if out, err := logOut(t, args...); err == nil {
t.Errorf("magpie log %v: no error\n%s", args, out)
}
}
if !strings.Contains(helpFor([]string{"log", "--help"}), "usage: magpie log") {
t.Errorf("magpie log --help: %q", helpFor([]string{"log", "--help"}))
}
}
// -f prints what is written after, and a log rotated meanwhile is read
// from its start.
func TestLogFollows(t *testing.T) {
writeLog(t, "old\n")
var mu syncBuf
stop := make(chan struct{})
done := make(chan error)
go func() { done <- tailLog(&mu, applog.Path(), 1, true, stop) }()
until(t, &mu, "old\n")
f, err := os.OpenFile(applog.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
f.WriteString("appended\n")
f.Close()
until(t, &mu, "old\nappended\n")
os.Rename(applog.Path(), filepath.Join(filepath.Dir(applog.Path()), applog.OldName))
t.Cleanup(func() { os.Remove(filepath.Join(filepath.Dir(applog.Path()), applog.OldName)) })
os.WriteFile(applog.Path(), []byte("rotated\n"), 0o600)
until(t, &mu, "old\nappended\nrotated\n")
close(stop)
if err := <-done; err != nil {
t.Fatal(err)
}
}
type syncBuf struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuf) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuf) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
// until waits for b to read want, the state the test is about.
func until(t *testing.T, b *syncBuf, want string) {
t.Helper()
deadline := time.Now().Add(20 * time.Second)
for b.String() != want {
if time.Now().After(deadline) {
t.Fatalf("followed %q, want %q", b.String(), want)
}
time.Sleep(20 * time.Millisecond)
}
}