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/mainfbb1b36d1: - 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/mainfbb1b36d1(#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 base03f609e3f: every package ok but reds that fail the same at origin/main03f609e3falone: 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).
This commit is contained in:
+20
-1
@@ -2251,6 +2251,24 @@ a `data` folder beside it) records no path, and a copy moved since its
|
||||
last start leaves the old one: run the program where it is, such as
|
||||
`& "$HOME\Downloads\magpie-windows-amd64.exe" goroutines | Out-Host`.
|
||||
|
||||
`magpie log [--path] [-n N] [-f]` says where magpie's logs are. The app
|
||||
(its window, the menu bar or tray icon and the panel, opened from the
|
||||
Finder, the Dock, the Start menu or a terminal) writes what it logs to
|
||||
`app.log` as well as to stderr: `~/Library/Logs/magpie/app.log` on macOS,
|
||||
`%LOCALAPPDATA%\magpie\logs\app.log` on Windows,
|
||||
`$XDG_STATE_HOME/magpie/app.log` (`~/.local/state/magpie/app.log`) on Linux
|
||||
and the BSDs, and `logs/app.log` in a portable magpie's data folder. A
|
||||
panic's trace goes there too. At 5 MiB it becomes `app.old.log`, over the
|
||||
one before, so two files are kept at most. The file is readable by your
|
||||
user only, and what looks like a key or token is masked in it, though
|
||||
nothing magpie logs is meant to carry one. Settings › About › Log has its
|
||||
path and an Open that shows its folder. `magpie log` prints its path, the
|
||||
older file when there is one, the service's log when `magpie daemon` is
|
||||
installed and the log of a gateway `magpie tui` left running; `--path`
|
||||
prints the app's alone, `-n N` its last N lines and `-f` follows it,
|
||||
across a rotation, until Ctrl+C. `magpie serve`, `magpie web` and the TUI
|
||||
write no `app.log`: their log is the terminal's, or the service's.
|
||||
|
||||
A gateway key held to a budget, to some models or to some accounts is told
|
||||
none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
|
||||
`/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`,
|
||||
@@ -2675,7 +2693,8 @@ port is free.
|
||||
told so; run `magpie serve` under the manager it has.
|
||||
- **macOS:** a launch agent, `~/Library/LaunchAgents/com.yetone.magpie.serve.plist`,
|
||||
loaded with `launchctl bootstrap gui/$UID`. Its log:
|
||||
`~/Library/Logs/magpie/serve.log`.
|
||||
`~/Library/Logs/magpie/serve.log`, beside the app's own `app.log`
|
||||
(`magpie log`).
|
||||
- **Windows:** not a service; `magpie autostart on` opens magpie, which
|
||||
serves the gateway, when you log in. Inside WSL, `magpie daemon` works as
|
||||
on Linux.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -265,6 +265,37 @@ func Cache() string {
|
||||
return filepath.Join(mustHome(), ".cache", "magpie")
|
||||
}
|
||||
|
||||
// Logs is the folder the desktop app writes its log in, where each system
|
||||
// keeps an app's logs: ~/Library/Logs/magpie on a Mac (beside the launch
|
||||
// agent's serve.log, `magpie daemon install`), %LOCALAPPDATA%\magpie\logs
|
||||
// on Windows, and $XDG_STATE_HOME/magpie (~/.local/state/magpie) elsewhere;
|
||||
// portable, data/logs. A user asked for magpie's log finds it there
|
||||
// (rayem1w on X: the app opened from the Finder had written none).
|
||||
func Logs() string {
|
||||
return logsOn(runtime.GOOS)
|
||||
}
|
||||
|
||||
// logsOn is Logs as it is on goos, for tests of every system's folder.
|
||||
func logsOn(goos string) string {
|
||||
if p := Portable(); p != "" {
|
||||
return filepath.Join(p, "logs")
|
||||
}
|
||||
switch goos {
|
||||
case "darwin":
|
||||
return filepath.Join(mustHome(), "Library", "Logs", "magpie")
|
||||
case "windows":
|
||||
local := os.Getenv("LOCALAPPDATA")
|
||||
if !rooted(local) {
|
||||
local = filepath.Join(mustHome(), "AppData", "Local")
|
||||
}
|
||||
return filepath.Join(local, "magpie", "logs")
|
||||
}
|
||||
if x := os.Getenv("XDG_STATE_HOME"); rooted(x) {
|
||||
return filepath.Join(x, "magpie")
|
||||
}
|
||||
return filepath.Join(mustHome(), ".local", "state", "magpie")
|
||||
}
|
||||
|
||||
// WebView is the folder the Windows webview (WebView2) keeps its profile
|
||||
// in — its cache, cookies and the pages' storage — or "" for its own
|
||||
// default. Installed, that default is %APPDATA%\<exe name>, as it always
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package appdir
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Logs is where each system keeps an app's logs, and the data folder's
|
||||
// logs portable: the app opened from the Finder wrote none (rayem1w on X).
|
||||
func TestLogsOnEachSystem(t *testing.T) {
|
||||
t.Setenv("APPIMAGE", "")
|
||||
t.Cleanup(func() { UseExecutable("") })
|
||||
UseExecutable("")
|
||||
r := root(t)
|
||||
home, err := Home()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Setenv("LOCALAPPDATA", filepath.Join(r, "local"))
|
||||
t.Setenv("XDG_STATE_HOME", filepath.Join(r, "state"))
|
||||
for goos, want := range map[string]string{
|
||||
"darwin": filepath.Join(home, "Library", "Logs", "magpie"),
|
||||
"windows": filepath.Join(r, "local", "magpie", "logs"),
|
||||
"linux": filepath.Join(r, "state", "magpie"),
|
||||
"freebsd": filepath.Join(r, "state", "magpie"),
|
||||
} {
|
||||
if got := logsOn(goos); got != want {
|
||||
t.Errorf("%s: logs in %q, want %q", goos, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// unset or relative, the system's default under the home
|
||||
for _, v := range []string{"", "relative"} {
|
||||
t.Setenv("LOCALAPPDATA", v)
|
||||
t.Setenv("XDG_STATE_HOME", v)
|
||||
if got, want := logsOn("windows"), filepath.Join(home, "AppData", "Local", "magpie", "logs"); got != want {
|
||||
t.Errorf("windows, LOCALAPPDATA %q: logs in %q, want %q", v, got, want)
|
||||
}
|
||||
if got, want := logsOn("linux"), filepath.Join(home, ".local", "state", "magpie"); got != want {
|
||||
t.Errorf("linux, XDG_STATE_HOME %q: logs in %q, want %q", v, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
exe := touch(t, filepath.Join(r, "port", "magpie"))
|
||||
data := filepath.Join(r, "port", "data")
|
||||
mkdir(t, data)
|
||||
UseExecutable(exe)
|
||||
for _, goos := range []string{"darwin", "windows", "linux"} {
|
||||
if got, want := logsOn(goos), filepath.Join(data, "logs"); got != want {
|
||||
t.Errorf("portable on %s: logs in %q, want %q", goos, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// Package applog writes the desktop app's log to a file, as well as to
|
||||
// stderr. The app opened from the Finder, the Dock, the Start menu or a
|
||||
// desktop launcher has no terminal: what it logged went nowhere, so a user
|
||||
// asked for magpie's log had none to send (rayem1w on X, a Codex "hit a
|
||||
// snag" through the gateway, 0.1.2330). Only the launch agent
|
||||
// (`magpie daemon install`, serve.log) and a `magpie tui` that left the
|
||||
// gateway running (serve.log in magpie's cache) kept one.
|
||||
//
|
||||
// The file is app.log in appdir.Logs. It is the app's alone: the launch
|
||||
// agent's serve.log, in the same folder on a Mac, is written by launchd for
|
||||
// `magpie serve`, a process of its own. At 5 MiB app.log becomes
|
||||
// app.old.log, over the one before, so two files at most are kept. A
|
||||
// panic or fatal error's trace goes to the file too (debug.SetCrashOutput),
|
||||
// so a crash is in it.
|
||||
//
|
||||
// What is logged names no key or token (the gateway logs header names,
|
||||
// never values, and paths without their query); scrub masks what looks
|
||||
// like one anyway, in case a vendor's error carries it.
|
||||
package applog
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
)
|
||||
|
||||
const (
|
||||
// Name is the log's file name in appdir.Logs.
|
||||
Name = "app.log"
|
||||
// OldName is the log before the last rotation, kept beside it.
|
||||
OldName = "app.old.log"
|
||||
// Limit is the size at which the log is rotated.
|
||||
Limit = 5 << 20
|
||||
)
|
||||
|
||||
// Path is where the desktop app writes its log.
|
||||
func Path() string { return filepath.Join(appdir.Logs(), Name) }
|
||||
|
||||
// current is the log this process writes, "" when it writes none, and
|
||||
// active its file.
|
||||
var (
|
||||
current atomic.Pointer[string]
|
||||
active atomic.Pointer[file]
|
||||
)
|
||||
|
||||
// Current is the log this process writes, or "" when it writes none (the
|
||||
// TUI, `magpie serve`, a command).
|
||||
func Current() string {
|
||||
if p := current.Load(); p != nil {
|
||||
return *p
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Start sends the standard logger's output, and a crash's trace, to the
|
||||
// log as well as to stderr, and logs that this magpie started. It answers
|
||||
// the log's path; when the file can't be opened, the error, and the log
|
||||
// goes to stderr alone as before.
|
||||
func Start(version, how string) (string, error) {
|
||||
path := Path()
|
||||
w, err := open(path, Limit)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
log.SetOutput(io.MultiWriter(quiet{os.Stderr}, w))
|
||||
if was := active.Swap(w); was != nil {
|
||||
was.Close()
|
||||
}
|
||||
current.Store(&path)
|
||||
log.Printf("magpie %s started (%s, pid %d, %s/%s); this log: %s", version, how, os.Getpid(), runtime.GOOS, runtime.GOARCH, path)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// Stop sends the log to stderr alone again and closes the file: for
|
||||
// tests, whose home is removed after them (Windows removes no folder with
|
||||
// a file open in it).
|
||||
func Stop() {
|
||||
log.SetOutput(os.Stderr)
|
||||
_ = debug.SetCrashOutput(nil, debug.CrashOptions{})
|
||||
current.Store(nil)
|
||||
if w := active.Swap(nil); w != nil {
|
||||
w.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// file is a log file rotated at limit bytes.
|
||||
type file struct {
|
||||
mu sync.Mutex
|
||||
path string
|
||||
old string
|
||||
limit int64
|
||||
f *os.File
|
||||
size int64
|
||||
}
|
||||
|
||||
// open opens the log at path to append to, making its folder, readable by
|
||||
// the user alone.
|
||||
func open(path string, limit int64) (*file, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w := &file{path: path, old: filepath.Join(filepath.Dir(path), OldName), limit: limit}
|
||||
if err := w.reopen(false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// reopen opens the file at w.path, emptied when truncate is set, and
|
||||
// hands it to the runtime for a crash's trace.
|
||||
func (w *file) reopen(truncate bool) error {
|
||||
flag := os.O_CREATE | os.O_WRONLY | os.O_APPEND
|
||||
if truncate {
|
||||
flag |= os.O_TRUNC
|
||||
}
|
||||
f, err := os.OpenFile(w.path, flag, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.f, w.size = f, 0
|
||||
if fi, err := f.Stat(); err == nil {
|
||||
w.size = fi.Size()
|
||||
}
|
||||
_ = debug.SetCrashOutput(f, debug.CrashOptions{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Write writes p to the log, rotating it first when p would take it past
|
||||
// its limit. It answers len(p) for what it wrote, after masking, so an
|
||||
// io.MultiWriter goes on to stderr.
|
||||
func (w *file) Write(p []byte) (int, error) {
|
||||
n := len(p)
|
||||
p = scrub(p)
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.f == nil {
|
||||
return 0, errors.New("applog: the log is closed")
|
||||
}
|
||||
if w.size > 0 && w.size+int64(len(p)) > w.limit {
|
||||
w.rotate()
|
||||
}
|
||||
m, err := w.f.Write(p)
|
||||
w.size += int64(m)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// rotate makes the log app.old.log and starts a new one. When another
|
||||
// magpie rotated it already (an update's new process beside the old one),
|
||||
// the log at w.path is already new and is only opened. When it can't be
|
||||
// moved (Windows, while another process has it open), it is emptied, so
|
||||
// it stays bounded either way.
|
||||
func (w *file) rotate() {
|
||||
if at, err := os.Stat(w.path); err == nil {
|
||||
if mine, err := w.f.Stat(); err == nil && !os.SameFile(at, mine) {
|
||||
w.f.Close()
|
||||
if w.reopen(false) == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// the runtime holds a copy of the file for a crash's trace, and
|
||||
// Windows moves no file with a handle open
|
||||
_ = debug.SetCrashOutput(nil, debug.CrashOptions{})
|
||||
w.f.Close()
|
||||
moved := os.Rename(w.path, w.old)
|
||||
if err := w.reopen(moved != nil); err != nil {
|
||||
w.f = nil
|
||||
return
|
||||
}
|
||||
if moved != nil {
|
||||
n, _ := fmt.Fprintf(w.f, "applog: %s couldn't be kept as %s (%v): emptied instead\n", Name, OldName, moved)
|
||||
w.size += int64(n)
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the log; for tests.
|
||||
func (w *file) Close() error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.f == nil {
|
||||
return nil
|
||||
}
|
||||
err := w.f.Close()
|
||||
w.f = nil
|
||||
return err
|
||||
}
|
||||
|
||||
// quiet is stderr that never fails a write: the app opened from Windows
|
||||
// Explorer has no stderr at all, and io.MultiWriter stops at the first
|
||||
// writer that fails.
|
||||
type quiet struct{ w io.Writer }
|
||||
|
||||
func (q quiet) Write(p []byte) (int, error) {
|
||||
_, _ = q.w.Write(p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// secrets are what a key or token looks like in a line of text: a bearer
|
||||
// or basic credential, a query parameter naming one, and the shapes
|
||||
// vendors' keys have (sk-…, Google's AIza…, GitHub's gh?_…, a JWT). Each
|
||||
// keeps its first characters, for telling which it was, and masks the
|
||||
// rest.
|
||||
var secrets = []struct {
|
||||
re *regexp.Regexp
|
||||
keep string
|
||||
}{
|
||||
{regexp.MustCompile(`(?i)\b((?:bearer|basic)\s+)[A-Za-z0-9._~+/=-]{8,}`), "${1}…"},
|
||||
{regexp.MustCompile(`(?i)([?&](?:key|api[_-]?key|apikey|access_token|refresh_token|id_token|token|auth|sig|signature|code)=)[^&\s"'<>]+`), "${1}…"},
|
||||
{regexp.MustCompile(`\b(sk-(?:ant-|proj-)?)[A-Za-z0-9_-]{12,}`), "${1}…"},
|
||||
{regexp.MustCompile(`\b(AIza)[0-9A-Za-z_-]{20,}`), "${1}…"},
|
||||
{regexp.MustCompile(`\b(gh[opsur]_)[A-Za-z0-9]{20,}`), "${1}…"},
|
||||
{regexp.MustCompile(`\b(eyJ)[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}`), "${1}…"},
|
||||
}
|
||||
|
||||
// scrub is p with whatever looks like a key or token masked.
|
||||
func scrub(p []byte) []byte {
|
||||
for _, s := range secrets {
|
||||
p = s.re.ReplaceAll(p, []byte(s.keep))
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//go:build !nogui
|
||||
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/applog"
|
||||
)
|
||||
|
||||
// The desktop app, its window and its panel each write their log to
|
||||
// app.log before the app starts: opened from the Finder, the Dock or the
|
||||
// Start menu it has no terminal, and a user asked for its log had none to
|
||||
// send (rayem1w on X, 0.1.2330).
|
||||
func TestTheAppWritesItsLog(t *testing.T) {
|
||||
was, wasPanel := openApp, openPanel
|
||||
t.Cleanup(func() { openApp, openPanel = was, wasPanel; applog.Stop() })
|
||||
started := 0
|
||||
openApp = func(bool, string) error { started++; return nil }
|
||||
openPanel = func() error { started++; return nil }
|
||||
|
||||
for name, open := range map[string]func() error{
|
||||
"app": func() error { return runGUI(false, "") },
|
||||
"window": func() error { return runWindow("usage") },
|
||||
"panel": runPanel,
|
||||
} {
|
||||
applog.Stop()
|
||||
os.Remove(applog.Path())
|
||||
if err := open(); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
b, err := os.ReadFile(applog.Path())
|
||||
if err != nil {
|
||||
t.Fatalf("%s wrote no log: %v", name, err)
|
||||
}
|
||||
if !strings.Contains(string(b), "started (") {
|
||||
t.Errorf("%s's log says nothing of its start:\n%s", name, b)
|
||||
}
|
||||
if applog.Current() != applog.Path() {
|
||||
t.Errorf("%s: the log it writes is %q, want %q", name, applog.Current(), applog.Path())
|
||||
}
|
||||
}
|
||||
if started != 3 {
|
||||
t.Errorf("the app was started %d times, want 3", started)
|
||||
}
|
||||
}
|
||||
+29
-2
@@ -3,15 +3,25 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/yetone/magpie/internal/applog"
|
||||
"github.com/yetone/magpie/internal/gui"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
const hasGUI = true
|
||||
|
||||
// the desktop app may have been opened from the Finder, with none of the
|
||||
// PATH a terminal has
|
||||
// runGUI starts the desktop app, writing its log to a file (startLog).
|
||||
func runGUI(showMain bool, link string) error {
|
||||
startLog("app")
|
||||
return openApp(showMain, link)
|
||||
}
|
||||
|
||||
// openApp starts the desktop app; a var so a test can stand in for it.
|
||||
// The app may have been opened from the Finder, with none of the PATH a
|
||||
// terminal has.
|
||||
var openApp = func(showMain bool, link string) error {
|
||||
proc.UserPath()
|
||||
gui.Started = ownSignals // once Wails handles them: it quits through OnShutdown
|
||||
return gui.Run(version, showMain, link)
|
||||
@@ -27,8 +37,25 @@ func runWindow(view string) error {
|
||||
// runPanel starts the app with its quick panel open, or toggles the panel
|
||||
// of the one already running.
|
||||
func runPanel() error {
|
||||
startLog("panel")
|
||||
return openPanel()
|
||||
}
|
||||
|
||||
// openPanel starts the app with its panel open; a var so a test can stand
|
||||
// in for it.
|
||||
var openPanel = func() error {
|
||||
proc.UserPath()
|
||||
gui.OpenPanel = true
|
||||
gui.Started = ownSignals // once Wails handles them: it quits through OnShutdown
|
||||
return gui.Run(version, false, "")
|
||||
}
|
||||
|
||||
// startLog has the app write its log to a file as well as stderr
|
||||
// (applog): opened from the Finder, the Dock or the Start menu it has no
|
||||
// terminal, and what it logged went nowhere (rayem1w on X). A var so a
|
||||
// test can tell runGUI starts it without starting the app.
|
||||
var startLog = func(how string) {
|
||||
if _, err := applog.Start(version, how); err != nil {
|
||||
log.Println("log:", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,8 @@ func helpFor(args []string) string {
|
||||
return cpuUsage
|
||||
case "goroutines":
|
||||
return goroutinesUsage
|
||||
case "log", "logs":
|
||||
return logUsage
|
||||
case "sessions":
|
||||
return sessionsUsage
|
||||
case "search":
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package cli
|
||||
|
||||
// magpie log: where magpie's logs are, and the app's last lines. The app
|
||||
// opened from the Finder, the Dock or the Start menu writes its log to a
|
||||
// file (applog), which a user asked for it finds here or in Settings ›
|
||||
// About › Log (rayem1w on X had been told of serve.log, which only the
|
||||
// service writes).
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/applog"
|
||||
"github.com/yetone/magpie/internal/daemon"
|
||||
"github.com/yetone/magpie/internal/tui"
|
||||
)
|
||||
|
||||
const logUsage = `usage: magpie log [--path] [-n N] [-f]
|
||||
where magpie's logs are on this computer: the app's own (the app, the menu bar and the
|
||||
panel write it, wherever they were opened from), the one before it, and the logs of
|
||||
magpie serve as a service (magpie daemon) or left running by magpie tui, when there are.
|
||||
--path the app's log alone, its path only
|
||||
-n N the app log's last N lines (100 with -f)
|
||||
-f the app log's last lines, then each line as it is written, until Ctrl+C
|
||||
Send the app's log with a report. It holds what magpie did, not your keys, prompts or replies.`
|
||||
|
||||
// logCmd: magpie log [--path] [-n N] [-f]
|
||||
func logCmd(args []string) error {
|
||||
pathOnly, follow, lines := false, false, -1
|
||||
for i := 0; i < len(args); i++ {
|
||||
switch a := args[i]; {
|
||||
case a == "--path":
|
||||
pathOnly = true
|
||||
case a == "-f" || a == "--follow":
|
||||
follow = true
|
||||
case a == "-n" || a == "--lines":
|
||||
if i+1 == len(args) {
|
||||
return errors.New("-n takes a number of lines (magpie log -n 200)")
|
||||
}
|
||||
i++
|
||||
n, err := strconv.Atoi(args[i])
|
||||
if err != nil || n < 0 {
|
||||
return fmt.Errorf("-n takes a number of lines, not %q (magpie log -n 200)", args[i])
|
||||
}
|
||||
lines = n
|
||||
default:
|
||||
return fmt.Errorf("unknown argument %s (magpie log [--path] [-n N] [-f])", a)
|
||||
}
|
||||
}
|
||||
path := applog.Path()
|
||||
switch {
|
||||
case pathOnly && (follow || lines >= 0):
|
||||
return errors.New("--path prints the path alone: use it without -n or -f")
|
||||
case pathOnly:
|
||||
fmt.Println(path)
|
||||
return nil
|
||||
case follow || lines >= 0:
|
||||
if lines < 0 {
|
||||
lines = 100
|
||||
}
|
||||
return tailLog(os.Stdout, path, lines, follow, nil)
|
||||
}
|
||||
fmt.Print(logsHere(path))
|
||||
return nil
|
||||
}
|
||||
|
||||
// logsHere says where each of magpie's logs is: the app's, always, and
|
||||
// the others that are there.
|
||||
func logsHere(path string) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "%s\n", path)
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
fmt.Fprintf(&b, " the app's log: nothing yet; the app writes it once it is opened\n")
|
||||
} else {
|
||||
fmt.Fprintf(&b, " the app's log (Settings › About › Log); magpie log -f follows it\n")
|
||||
}
|
||||
if old := filepath.Join(filepath.Dir(path), applog.OldName); exists(old) {
|
||||
fmt.Fprintf(&b, "%s\n the app's log before it, kept once it reached %d MiB\n", old, applog.Limit>>20)
|
||||
}
|
||||
if st, err := daemon.Get(); err == nil && st.Installed && st.Logs != "" {
|
||||
fmt.Fprintf(&b, "%s\n magpie serve as a service (magpie daemon)\n", st.Logs)
|
||||
}
|
||||
if bg := tui.BackgroundLog(); exists(bg) {
|
||||
fmt.Fprintf(&b, "%s\n magpie serve left running by magpie tui as it quit\n", bg)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func exists(p string) bool {
|
||||
_, err := os.Stat(p)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// tailLog writes the last n lines of the log at path to w, then, with
|
||||
// follow, what is written to it after, until stop is closed (nil: until
|
||||
// magpie is ended). A log rotated meanwhile is read again from its start.
|
||||
func tailLog(w io.Writer, path string, n int, follow bool, stop <-chan struct{}) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) && follow {
|
||||
fmt.Fprintf(os.Stderr, "magpie: %s isn't there yet: waiting for the app to write it\n", path)
|
||||
} else if errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("%s isn't there yet: the app writes it once it is opened", path)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var at int64
|
||||
if f != nil {
|
||||
b, err := io.ReadAll(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
at = int64(len(b))
|
||||
w.Write(lastLines(b, n))
|
||||
}
|
||||
if !follow {
|
||||
if f != nil {
|
||||
f.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
tick := time.NewTicker(300 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
defer func() {
|
||||
if f != nil {
|
||||
f.Close()
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return nil
|
||||
case <-tick.C:
|
||||
}
|
||||
// a new file at path (rotated, or written for the first time):
|
||||
// read it from its start
|
||||
if fi, err := os.Stat(path); err == nil {
|
||||
var mine os.FileInfo
|
||||
if f != nil {
|
||||
mine, _ = f.Stat()
|
||||
}
|
||||
if f == nil || mine == nil || !os.SameFile(fi, mine) || fi.Size() < at {
|
||||
if nf, err := os.Open(path); err == nil {
|
||||
if f != nil {
|
||||
// what the old file got after the last read first
|
||||
io.Copy(w, f)
|
||||
f.Close()
|
||||
}
|
||||
f, at = nf, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if f == nil {
|
||||
continue
|
||||
}
|
||||
n, _ := io.Copy(w, bufio.NewReader(f))
|
||||
at += n
|
||||
}
|
||||
}
|
||||
|
||||
// lastLines is b's last n lines.
|
||||
func lastLines(b []byte, n int) []byte {
|
||||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
i := len(b)
|
||||
if i > 0 && b[i-1] == '\n' {
|
||||
i--
|
||||
}
|
||||
for ; n > 0; n-- {
|
||||
i = bytes.LastIndexByte(b[:i], '\n')
|
||||
if i < 0 {
|
||||
return b
|
||||
}
|
||||
}
|
||||
return b[i+1:]
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -121,6 +121,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie heap [<file>] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory
|
||||
magpie cpu [<file>] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU
|
||||
magpie goroutines [<file>] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something
|
||||
magpie log [--path] [-n N] [-f] where magpie's logs are, to send with a report: the app's (app.log), the service's; -n prints the app log's last N lines, -f follows it
|
||||
magpie gateway-key list|add <name> [--read-only]|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
|
||||
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads] a key's own limits, and what it used
|
||||
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
|
||||
@@ -306,6 +307,11 @@ func run(args []string) error {
|
||||
// the running magpie's goroutines: asks it, and moves nothing here
|
||||
return goroutinesCmd(args[1:])
|
||||
}
|
||||
if len(args) > 0 && (args[0] == "log" || args[0] == "logs") {
|
||||
// where magpie's logs are, and the app log's last lines: reads
|
||||
// files, and moves nothing
|
||||
return logCmd(args[1:])
|
||||
}
|
||||
if len(args) == 2 && args[0] == agent.DryRunArg {
|
||||
// an agent disconnected on a copy of its files under a temporary
|
||||
// home, for the Agents page to show what disconnecting changes
|
||||
|
||||
@@ -12,11 +12,30 @@ import (
|
||||
// TestGatewayStartsGetUserPath: every way magpie starts with a gateway
|
||||
// gives what it starts the node a version manager put on PATH only in the
|
||||
// shell's profile (#2685, #3803). magpie tui runs in a terminal, with its
|
||||
// PATH already.
|
||||
// PATH already. A start counts when it calls proc.UserPath, or calls a
|
||||
// function or func var of this package that does (runGUI's openApp, which
|
||||
// a test stands in for).
|
||||
func TestGatewayStartsGetUserPath(t *testing.T) {
|
||||
want := map[string]bool{"runGUI": false, "runPanel": false, "webCmd": false, "serveCmd": false}
|
||||
files, _ := filepath.Glob("*.go")
|
||||
fset := token.NewFileSet()
|
||||
direct := map[string]bool{} // calls proc.UserPath itself
|
||||
calls := map[string][]string{} // the package's names it calls
|
||||
look := func(name string, body ast.Node) {
|
||||
ast.Inspect(body, func(n ast.Node) bool {
|
||||
switch n := n.(type) {
|
||||
case *ast.SelectorExpr:
|
||||
if id, ok := n.X.(*ast.Ident); ok && id.Name == "proc" && n.Sel.Name == "UserPath" {
|
||||
direct[name] = true
|
||||
}
|
||||
case *ast.CallExpr:
|
||||
if id, ok := n.Fun.(*ast.Ident); ok {
|
||||
calls[name] = append(calls[name], id.Name)
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
continue
|
||||
@@ -26,25 +45,34 @@ func TestGatewayStartsGetUserPath(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, d := range file.Decls {
|
||||
fn, ok := d.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil {
|
||||
continue
|
||||
}
|
||||
if _, named := want[fn.Name.Name]; !named {
|
||||
continue
|
||||
}
|
||||
ast.Inspect(fn.Body, func(n ast.Node) bool {
|
||||
if sel, ok := n.(*ast.SelectorExpr); ok && sel.Sel.Name == "UserPath" {
|
||||
if id, ok := sel.X.(*ast.Ident); ok && id.Name == "proc" {
|
||||
want[fn.Name.Name] = true
|
||||
switch d := d.(type) {
|
||||
case *ast.FuncDecl:
|
||||
if d.Body != nil && d.Recv == nil {
|
||||
look(d.Name.Name, d.Body)
|
||||
}
|
||||
case *ast.GenDecl:
|
||||
for _, sp := range d.Specs {
|
||||
vs, ok := sp.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for i, v := range vs.Values {
|
||||
if fl, ok := v.(*ast.FuncLit); ok && i < len(vs.Names) {
|
||||
look(vs.Names[i].Name, fl.Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
for name, calls := range want {
|
||||
if !calls {
|
||||
for name := range want {
|
||||
want[name] = direct[name]
|
||||
for _, c := range calls[name] {
|
||||
want[name] = want[name] || direct[c]
|
||||
}
|
||||
}
|
||||
for name, ok := range want {
|
||||
if !ok {
|
||||
t.Errorf("%s doesn't call proc.UserPath", name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/applog"
|
||||
"github.com/yetone/magpie/internal/autostart"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
@@ -397,6 +398,9 @@ type settingsJSON struct {
|
||||
OnNetwork bool `json:"onNetwork,omitempty"`
|
||||
// Dir is the data folder beside a portable magpie (#508)
|
||||
Portable bool `json:"portable,omitempty"`
|
||||
// Log is the log the desktop app writes (applog), as shown; "" for a
|
||||
// magpie writing none (magpie web)
|
||||
Log string `json:"log,omitempty"`
|
||||
// WSL is whether there is WSL to look in for agents (Windows), for
|
||||
// Settings' Detect agents in WSL (#1264)
|
||||
WSL bool `json:"wsl,omitempty"`
|
||||
@@ -709,6 +713,7 @@ func codexWindowUnder(st settings.Settings, model string) *codexRunWindow {
|
||||
func settingsState() settingsJSON {
|
||||
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
|
||||
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
|
||||
s.Log = tilde(applog.Current())
|
||||
s.Builtins = builtinsState()
|
||||
s.PanelKeys = panelKeysState()
|
||||
s.JSRoutings = middleware.Routings()
|
||||
@@ -2645,6 +2650,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
// the app's log folder (applog), from Settings › About's Log row; the
|
||||
// page names no path here either
|
||||
mux.HandleFunc("POST /api/settings/log/reveal", func(rw http.ResponseWriter, r *http.Request) {
|
||||
path := applog.Current()
|
||||
if path == "" {
|
||||
fail(rw, errors.New("this magpie writes no log file"))
|
||||
return
|
||||
}
|
||||
if err := w.OpenFolder(filepath.Dir(path)); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
// the folder of the reports saved of requests held too long before
|
||||
// routing (gateway.HeldDir), from such a request's row on Routing
|
||||
mux.HandleFunc("POST /api/gateway/held/reveal", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -20057,6 +20057,12 @@ function renderSettings() {
|
||||
open.onclick = () => api("settings/reveal", {}).catch(statusErr);
|
||||
// portable (a data folder beside magpie, #508): everything is in there
|
||||
row(t("Config folder"), s.portable ? t("Portable: everything magpie keeps, in the data folder beside it") : t("providers, profiles and these settings"), s.dir, copyBtn(s.dir, t("Path")), open);
|
||||
// app.log (applog); magpie web writes none
|
||||
if (s.log) {
|
||||
const o = el("button", "text", t("Open"));
|
||||
o.onclick = () => api("settings/log/reveal", {}).catch(statusErr);
|
||||
row(t("Log"), t("What magpie has logged, to send with a bug report"), s.log, copyBtn(s.log, t("Path")), o).id = "logRow";
|
||||
}
|
||||
renderCLI(row(t("Command line"), t("Checking your shells…"), ""));
|
||||
// served to other machines (magpie web), the one they reach (noahhrreion)
|
||||
const gw = web && s.publicURL || s.gateway;
|
||||
|
||||
@@ -3269,6 +3269,8 @@ const I18N = {
|
||||
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 无法写入它所在的文件夹({dir}),所以无法自动更新;请把它移到你有写入权限的文件夹,再从那里打开。",
|
||||
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 运行在容器里,无法自动更新;请拉取新镜像(docker pull ghcr.io/yetone/magpie:latest)并重新创建容器。",
|
||||
"Config folder": "配置目录",
|
||||
"Log": "日志",
|
||||
"What magpie has logged, to send with a bug report": "magpie 记下的日志,报告问题时可附上",
|
||||
"Command line": "命令行",
|
||||
"Checking your shells…": "正在检查你的 shell…",
|
||||
"Add to PATH": "添加到 PATH",
|
||||
@@ -7488,6 +7490,8 @@ const I18N = {
|
||||
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie 無法寫入它所在的資料夾({dir}),所以無法自動更新;請把它移到你有寫入權限的資料夾,再從那裡開啟。",
|
||||
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie 在容器中執行,無法自動更新;請拉取新映像(docker pull ghcr.io/yetone/magpie:latest)並重新建立容器。",
|
||||
"Config folder": "設定目錄",
|
||||
"Log": "日誌",
|
||||
"What magpie has logged, to send with a bug report": "magpie 記下的日誌,回報問題時可附上",
|
||||
"Command line": "命令列",
|
||||
"Checking your shells…": "正在檢查你的 shell…",
|
||||
"Add to PATH": "新增到 PATH",
|
||||
@@ -11718,6 +11722,8 @@ const I18N = {
|
||||
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie は実行中のフォルダ({dir})に書き込めないため、自動アップデートできません。書き込み可能なフォルダに移動し、そこから開いてください。",
|
||||
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie はコンテナで実行されているため、自動アップデートできません。新しいイメージを取得し(docker pull ghcr.io/yetone/magpie:latest)、コンテナを作り直してください。",
|
||||
"Config folder": "設定フォルダ",
|
||||
"Log": "ログ",
|
||||
"What magpie has logged, to send with a bug report": "magpie が記録したログ。不具合の報告に添えてください",
|
||||
"Command line": "コマンドライン",
|
||||
"Checking your shells…": "シェルを確認しています…",
|
||||
"Add to PATH": "PATH に追加",
|
||||
@@ -15959,6 +15965,8 @@ const I18N = {
|
||||
"magpie can't write to the folder it runs from ({dir}), so it can't update itself; move it to a folder you can write to and open it from there.": "magpie kann nicht in den Ordner schreiben, aus dem es läuft ({dir}), und kann sich daher nicht selbst aktualisieren; verschieben Sie es in einen Ordner mit Schreibrechten und öffnen Sie es von dort.",
|
||||
"magpie runs in a container, so it can't update itself; pull the new image (docker pull ghcr.io/yetone/magpie:latest) and recreate the container.": "magpie läuft in einem Container und kann sich daher nicht selbst aktualisieren; laden Sie das neue Image (docker pull ghcr.io/yetone/magpie:latest) und erstellen Sie den Container neu.",
|
||||
"Config folder": "Konfigurationsordner",
|
||||
"Log": "Protokoll",
|
||||
"What magpie has logged, to send with a bug report": "Was magpie protokolliert hat, zum Mitschicken bei einem Fehlerbericht",
|
||||
"Command line": "Befehlszeile",
|
||||
"Checking your shells…": "Shells werden geprüft…",
|
||||
"Add to PATH": "Zum PATH hinzufügen",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,66 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { fixture } = require("./fixtures/caller-keys.cjs");
|
||||
const { openPart } = require("./reader.cjs");
|
||||
|
||||
// A user asked for magpie's log had none: the app opened from the Finder
|
||||
// wrote it nowhere (rayem1w on X). It writes app.log now, and Settings ›
|
||||
// About names it with a Log row whose Open shows its folder, in every
|
||||
// language and at the tray panel's width. magpie web writes none, and
|
||||
// shows no row.
|
||||
const words = {
|
||||
en: ["Log", "Open"], zh: ["日志", "打开"], "zh-TW": ["日誌", "開啟"], ja: ["ログ", "開く"], de: ["Protokoll", "Öffnen"],
|
||||
};
|
||||
const logPath = "~/Library/Logs/magpie/app.log";
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of Object.keys(words)) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}: About names the app's log`, 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(6000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const base = fixture(lang, "light", []);
|
||||
await page.route("**/*", (route, req) => {
|
||||
const url = new URL(req.url());
|
||||
if (url.pathname === "/api/settings/log/reveal") {
|
||||
return route.fulfill({ json: { ok: true } });
|
||||
}
|
||||
if (url.pathname !== "/api/settings") return base(route);
|
||||
// the fixture's settings, with the log this app writes
|
||||
return base({ request: () => req, fulfill: (o) => route.fulfill(o.json ? { ...o, json: { ...o.json, log: logPath } } : o) });
|
||||
});
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator("#prefs").click();
|
||||
await openPart(page, "about");
|
||||
const row = page.locator("#logRow");
|
||||
await row.waitFor();
|
||||
assert.equal(await row.locator(".who").first().textContent().then((s) => s.trim().startsWith(words[lang][0])), true, "the row is named " + words[lang][0]);
|
||||
assert.equal(await row.locator("code").textContent(), logPath);
|
||||
const opened = page.waitForRequest((r) => r.url().includes("/api/settings/log/reveal"));
|
||||
await row.locator("button.text", { hasText: words[lang][1] }).click();
|
||||
assert.equal((await opened).method(), "POST");
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "About wider than the window");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
test(`${engine}: magpie web writes no log, and About names none`, 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(6000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
await page.route("**/*", fixture("en", "light", []));
|
||||
await page.goto("http://magpie.test/");
|
||||
await page.locator("#prefs").click();
|
||||
await openPart(page, "about");
|
||||
await page.locator("#about .row", { has: page.locator(".who", { hasText: "Config folder" }) }).waitFor();
|
||||
assert.equal(await page.locator("#logRow").count(), 0);
|
||||
});
|
||||
}
|
||||
@@ -83,6 +83,10 @@ func keepGateway(connected bool) string {
|
||||
return msg
|
||||
}
|
||||
|
||||
// BackgroundLog is the log of a magpie serve that magpie tui left
|
||||
// running as it quit (serveInBackground).
|
||||
func BackgroundLog() string { return filepath.Join(appdir.Cache(), "serve.log") }
|
||||
|
||||
// serveInBackground starts `magpie serve` on its own, outliving this
|
||||
// process and its terminal, its output in a log in magpie's cache.
|
||||
func serveInBackground() (int, string, error) {
|
||||
@@ -90,7 +94,7 @@ func serveInBackground() (int, string, error) {
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
log := filepath.Join(appdir.Cache(), "serve.log")
|
||||
log := BackgroundLog()
|
||||
if err := os.MkdirAll(filepath.Dir(log), 0o700); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
</table></div>
|
||||
<p><code>install-id</code> と <code>stats-sent</code> は magpie のフォルダーにあります。macOS と Linux では <code>~/.config/magpie</code>、Windows では <code>%USERPROFILE%\.config\magpie</code>、<code>$XDG_CONFIG_HOME</code> が設定されていれば <code>$XDG_CONFIG_HOME/magpie</code>、ポータブル版ではそのデータフォルダーです。<code>partner-counts.json</code> は <code>~/.cache/magpie</code>(<code>$XDG_CACHE_HOME/magpie</code>、ポータブル版ではデータフォルダーの <code>cache</code>)にあります。どれも削除できます。<code>install-id</code> を消すと次の送信で新しいランダムな ID が作られ、新しいユーザーとして数えられます。カウントをオフにすれば、どれも再び書かれません。</p>
|
||||
<p>リクエストアーカイブ(<span class="ui">使用量</span>ページのリクエスト一覧の上にある<span class="ui">リクエストアーカイブ</span>スイッチ)は<b>既定でオフ</b>です。同期に S3 バケットがないときにオンにすると、ゲートウェイを通る各呼び出しのヘッダーと本文を、S3 アーカイブと同じようにシークレットを伏せて、magpie のフォルダーの <code>request-archive</code> に 1 呼び出し 1 ファイルで保存します。読めるのはあなたのユーザーだけです。上限は 1 GiB(settings.json の <code>requestArchiveLocalMB</code>)で、超えると古い呼び出しから削除します。このスイッチはこのコンピューターだけのもので、同期で別のコンピューターでオンになることはありません。S3 バケットがあるときはバケットに送られ、ここには何も書かれません。フォルダーはいつでも削除できます。</p>
|
||||
<p>アプリは自分のしたことをログ <code>app.log</code> に書きます。macOS では <code>~/Library/Logs/magpie</code>、Windows では <code>%LOCALAPPDATA%\magpie\logs</code>、Linux では <code>~/.local/state/magpie</code> です(<a href="/docs/ja/start#log">magpie のログはどこにありますか?</a>)。読めるのはあなたのユーザーだけです。magpie がしたことと出会ったエラーを記録し、キー、プロンプト、返答は記録しません。あなたが送らない限り、このコンピューターから出ません。上限は 5 MiB で、古いもの 1 つ(<code>app.old.log</code>)を残します。いつでも削除できます。</p>
|
||||
|
||||
<h2 id="site"><a class="anchor" href="#site">usemagpie.ai に見えるもの</a></h2>
|
||||
<p>magpie はプライバシー設定にかかわらず、どのアプリも自分の更新サーバーに尋ねるのと同じように、自分のサイトにいくつか尋ねます。どのリクエストにもインストール ID やアカウントは付きません。</p>
|
||||
|
||||
@@ -267,6 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
<tr><td><code>magpie usage 7d</code></td><td>エージェントとモデルごとのトークンとコスト</td></tr>
|
||||
<tr><td><code>magpie tools</code> · <code>magpie tool generate_image "…" -o hero.png</code></td><td>magpie が MCP でエージェントに渡すツール(画像生成、画像認識、Web 検索、プラグインのツール)を一覧し、直接呼び出す。生成した画像はファイルに保存</td></tr>
|
||||
<tr><td><code>magpie tray</code></td><td>メニューバーのアイコンだけで起動</td></tr>
|
||||
<tr><td><code>magpie log</code> · <code>magpie log -f</code></td><td>magpie のログの場所。不具合の報告に添えます。<code>-n 200</code> でアプリのログの末尾を表示、<code>-f</code> で追いかけます</td></tr>
|
||||
</table></div>
|
||||
|
||||
<h2 id="faq"><a class="anchor" href="#faq">よくある質問</a></h2>
|
||||
@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
<h3>GitHub に届かない環境で、インストールや更新をするには?</h3>
|
||||
<p>インストーラと <code>magpie update</code> にプロキシを渡します:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>、または <code>magpie update --proxy socks5://127.0.0.1:1080</code>(http・https・socks5・socks5h に対応。<code>HTTPS_PROXY</code> と <code>ALL_PROXY</code> も使われます)。<code>--mirror <prefix></code> を付けると、指定した GitHub ダウンロードミラーから <code><prefix>https://github.com/…</code> としてリリースファイルを取得します。<code>magpie update mirror <prefix></code> でアプリ自身の更新を含め毎回使い、<code>magpie update mirror off</code> で解除します。指定しない限りミラーは使われず、ファイルの SHA-256 はミラーではなく常に usemagpie.ai から取得するので、ミラーが書き換えたファイルはインストールされません。アプリ自身の更新は <span class="ui">Settings</span> → <span class="ui">Proxy</span> を通ります。</p>
|
||||
|
||||
<h3 id="log">magpie のログはどこにありますか?</h3>
|
||||
<p>アプリ(ウィンドウ、メニューバーやトレイのアイコン、パネル。どう開いたかによらず)は <code>app.log</code> を書きます。macOS では <code>~/Library/Logs/magpie/app.log</code>、Windows では <code>%LOCALAPPDATA%\magpie\logs\app.log</code>、Linux では <code>~/.local/state/magpie/app.log</code>(<code>$XDG_STATE_HOME</code> が設定されていれば <code>$XDG_STATE_HOME/magpie</code>)、ポータブル版ではデータフォルダーの <code>logs</code> です。<span class="ui">設定</span> → <span class="ui">情報</span> → <span class="ui">ログ</span>にパスがあり、<span class="ui">開く</span>でそのフォルダーを表示します。<code>magpie log</code> はパスを表示し、<code>magpie log -f</code> は追いかけます。5 MiB に達すると隣の <code>app.old.log</code> になり、残るのは最大 2 ファイルです。記録されるのは magpie がしたことと出会ったエラー(プロバイダーがリクエストを断った、再試行した、プラグインが起動しなかった)で、キー、プロンプト、返答は含みません。キーやトークンに見えるものも伏せられます。サービスとして動く <code>magpie serve</code> のログは別の場所です。macOS では <code>~/Library/Logs/magpie/serve.log</code>、Linux では <code>journalctl --user -u magpie</code>。<code>magpie log</code> はそれも示します。</p>
|
||||
|
||||
<h3 id="privacy">magpie は何を送信しますか?</h3>
|
||||
<p>プロンプト、返答、キー、アカウントは、使っているプロバイダーにだけ送られます。間に magpie 自身のサーバーはありません。リリース版の magpie は 1 日 1 回、使われていることを知らせます。何人が使っていて、何を優先して面倒を見るべきかを知るためです。送るのは、このコンピュータで作ったランダムな ID、magpie のバージョンとシステム、そして使っているエージェント、プロバイダー、モデルを magpie 自身の ID(<code>claude</code>、<code>deepseek</code>、<code>deepseek/deepseek-v4</code>)で、それぞれの数とともに。自分で追加したプロバイダーとそのモデルは <code>custom</code> とだけ記録します。プロバイダー追加シートの先頭に載るパートナーについては、1 日に表示された回数、開かれた回数、追加された回数も送ります(回数のみ)。名前、Base URL、アカウント、キー、プロンプト、使用量は送りません。<span class="ui">設定</span> → <span class="ui">プライバシー</span> → <span class="ui">使っているエージェント、プロバイダー、モデルを共有</span> でエージェント、プロバイダー、モデルとパートナーの回数を外せます。<span class="ui">ユーザー数に含める</span>、<code>DO_NOT_TRACK=1</code>、<code>MAGPIE_NO_STATS=1</code> のどれかですべてオフになります。ソースからのビルドは送信しません。パートナーの公式サイトと「キーを取得」のリンクは <code>usemagpie.ai/go/…</code> を経由し、移動の前にクリックを 1 回数えます(どのパートナーか、どのリンクか、国)。usemagpie.ai はパートナー一覧が取得された回数も数えます。これはサーバー自身が見るもので、どの Web サイトのアクセス集計とも同じく、上の設定には左右されません。ID、IP アドレス、アカウントは記録しません。プラグイン、インポートリンク、ライブラリが示すアイコンは <code>usemagpie.ai/api/icon</code> を経由して取得するので、アイコンのあるサーバーに見えるのはあなたの IP ではなく Cloudflare のアドレスです。このサーバーは画像を中継するだけで、数えることも記録することもしません。magpie が自分から送るものすべては、毎日のカウントの例、手元に残すファイル、各スイッチとともに<a href="/docs/ja/privacy">プライバシー</a>のページに挙げています。</p>
|
||||
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
</table></div>
|
||||
<p><code>install-id</code> and <code>stats-sent</code> are in magpie’s folder: <code>~/.config/magpie</code> on macOS and Linux, <code>%USERPROFILE%\.config\magpie</code> on Windows, <code>$XDG_CONFIG_HOME/magpie</code> when that is set, and the data folder of a portable magpie. <code>partner-counts.json</code> is in <code>~/.cache/magpie</code> (<code>$XDG_CACHE_HOME/magpie</code>, or <code>cache</code> in a portable magpie’s data folder). You can delete any of them: a deleted <code>install-id</code> is replaced by a new random one at the next send, so you are counted as a new user; with the count off, none of them is written again.</p>
|
||||
<p>The request archive (the <span class="ui">Request archive</span> switch on the <span class="ui">Usage</span> page, above the list of requests) is <b>off by default</b>. Turned on while sync has no S3 bucket, it keeps each gateway call’s headers and bodies, secrets masked as for the S3 archive, in <code>request-archive</code> in magpie’s folder, one file per call, readable by your user only. It grows to 1 GiB (<code>requestArchiveLocalMB</code> in settings.json) and the oldest calls are removed past that. The switch is this computer’s own: sync never turns it on at another computer. With an S3 bucket the calls go to the bucket instead, and nothing is written here. Delete the folder whenever you like.</p>
|
||||
<p>The app writes a log of what it did, <code>app.log</code>, in <code>~/Library/Logs/magpie</code> on macOS, <code>%LOCALAPPDATA%\magpie\logs</code> on Windows and <code>~/.local/state/magpie</code> on Linux (see <a href="/docs/start#log">Where is magpie’s log?</a>), readable by your user only. It names what magpie did and the errors it met, never keys, prompts or replies, and stays on your computer unless you send it. It is kept to 5 MiB, with one older file, <code>app.old.log</code>. Delete them whenever you like.</p>
|
||||
|
||||
<h2 id="site"><a class="anchor" href="#site">What usemagpie.ai sees</a></h2>
|
||||
<p>magpie asks its own site for a few things, whatever the privacy settings say, as any app asks its update server. None of these requests carries the install id or an account.</p>
|
||||
|
||||
@@ -267,6 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
<tr><td><code>magpie usage 7d</code></td><td>Tokens and cost per agent and model</td></tr>
|
||||
<tr><td><code>magpie tools</code> · <code>magpie tool generate_image "…" -o hero.png</code></td><td>The tools magpie gives agents over MCP (image generation, image recognition, web search, plugins’), listed and called directly; an image it makes is saved</td></tr>
|
||||
<tr><td><code>magpie tray</code></td><td>Start with the menu bar icon only</td></tr>
|
||||
<tr><td><code>magpie log</code> · <code>magpie log -f</code></td><td>Where magpie’s logs are, to send with a report; <code>-n 200</code> prints the app log’s last lines, <code>-f</code> follows it</td></tr>
|
||||
</table></div>
|
||||
|
||||
<h2 id="faq"><a class="anchor" href="#faq">FAQ</a></h2>
|
||||
@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
<h3>Installing or updating behind a firewall, or without access to GitHub?</h3>
|
||||
<p>Give the installer and <code>magpie update</code> a proxy: <code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>, or <code>magpie update --proxy socks5://127.0.0.1:1080</code> (http, https, socks5 and socks5h; <code>HTTPS_PROXY</code> and <code>ALL_PROXY</code> are honoured too). <code>--mirror <prefix></code> fetches the release file from a GitHub download mirror you choose, as <code><prefix>https://github.com/…</code>; <code>magpie update mirror <prefix></code> keeps it for every update, the app’s too, and <code>magpie update mirror off</code> removes it. No mirror is used unless you give one, and the file’s SHA-256 still comes from usemagpie.ai, never from the mirror: a file the mirror changed is refused. The app’s own updates go through <span class="ui">Settings</span> → <span class="ui">Proxy</span>.</p>
|
||||
|
||||
<h3 id="log">Where is magpie’s log?</h3>
|
||||
<p>The app (its window, the menu bar or tray icon and the panel, however it was opened) writes <code>app.log</code>: <code>~/Library/Logs/magpie/app.log</code> on macOS, <code>%LOCALAPPDATA%\magpie\logs\app.log</code> on Windows, <code>~/.local/state/magpie/app.log</code> on Linux (<code>$XDG_STATE_HOME/magpie</code> when that is set), and <code>logs</code> in a portable magpie’s data folder. <span class="ui">Settings</span> → <span class="ui">About</span> → <span class="ui">Log</span> has its path and an <span class="ui">Open</span> that shows its folder; <code>magpie log</code> prints it, and <code>magpie log -f</code> follows it. At 5 MiB it becomes <code>app.old.log</code> beside it, so two files at most are kept. It holds what magpie did and the errors it met (a provider refusing a request, a retry, a plugin that failed to start), not your keys, prompts or replies; what looks like a key or token is masked anyway. <code>magpie serve</code> run as a service logs elsewhere: <code>~/Library/Logs/magpie/serve.log</code> on macOS, <code>journalctl --user -u magpie</code> on Linux; <code>magpie log</code> names it too.</p>
|
||||
|
||||
<h3 id="privacy">What does magpie send about me?</h3>
|
||||
<p>Your prompts, replies, keys and accounts go only to the providers you use; magpie has no server of its own in the path. Once a day a released magpie tells us it is in use, so we know how many people use it and what to look after first: a random id made up on your computer, magpie’s version and your system, and which agents, providers and models it is used with, by magpie’s own ids (<code>claude</code>, <code>deepseek</code>, <code>deepseek/deepseek-v4</code>) with how many of each. A provider you added yourself, and a model on it, is only <code>custom</code>. For each partner listed first in the add sheet, how many times a day it was shown, opened and added from goes with them, as counts only. No names, base URLs, accounts, keys, prompts or usage are sent. <span class="ui">Settings</span> → <span class="ui">Privacy</span> → <span class="ui">Share the agents, providers and models I use</span> leaves out the agents, providers and models, and the partner counts; <span class="ui">Count me as a user</span>, <code>DO_NOT_TRACK=1</code> or <code>MAGPIE_NO_STATS=1</code> turns it all off. Builds from source never send it. A partner's website and key-page links go through <code>usemagpie.ai/go/…</code>, which counts the click (the partner, which link, and a country) before sending you on, and usemagpie.ai counts how many times the partner list is fetched. The server sees these whatever the settings say, as any website sees its visits; no id, address or account is kept with them. Icons named by a plugin, an import link or the library are fetched through <code>usemagpie.ai/api/icon</code>, so their hosts see Cloudflare's address, not yours; the server only passes the picture on, and counts and keeps nothing. The <a href="/docs/privacy">Privacy page</a> lists everything magpie sends by itself, with an example of the daily count, the files it keeps and every switch.</p>
|
||||
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
</table></div>
|
||||
<p><code>install-id</code> 和 <code>stats-sent</code> 在 magpie 的文件夹里:macOS 和 Linux 上是 <code>~/.config/magpie</code>,Windows 上是 <code>%USERPROFILE%\.config\magpie</code>,设置了 <code>$XDG_CONFIG_HOME</code> 时是 <code>$XDG_CONFIG_HOME/magpie</code>,便携版则在它的数据文件夹里。<code>partner-counts.json</code> 在 <code>~/.cache/magpie</code>(或 <code>$XDG_CACHE_HOME/magpie</code>,便携版数据文件夹里的 <code>cache</code>)。这些文件都可以删:删掉 <code>install-id</code> 后,下次发送会生成新的随机 ID,你会被算作新用户;关掉计数后,它们都不会再写入。</p>
|
||||
<p>请求存档(<span class="ui">用量</span>页请求列表上方的<span class="ui">请求存档</span>开关)<b>默认关闭</b>。同步没有 S3 存储桶时打开它,每次经过网关的调用的请求头和正文会存到 magpie 文件夹里的 <code>request-archive</code>,一次调用一个文件,只有你的用户能读,密钥按 S3 存档同样的方式遮掉。它最多占 1 GiB(settings.json 里的 <code>requestArchiveLocalMB</code>),超过后先删最早的调用。这个开关只属于这台电脑,同步不会在别的电脑上把它打开。有 S3 存储桶时调用存到桶里,这里不写任何东西。这个文件夹随时可以删。</p>
|
||||
<p>应用会把它做了什么写进日志 <code>app.log</code>:macOS 上在 <code>~/Library/Logs/magpie</code>,Windows 上在 <code>%LOCALAPPDATA%\magpie\logs</code>,Linux 上在 <code>~/.local/state/magpie</code>(见 <a href="/docs/zh/start#log">magpie 的日志在哪里?</a>),只有你的用户能读。它记下 magpie 做了什么和遇到的错误,从不记密钥、提示词或回复,除非你发出去,否则只留在你的电脑上。它最多 5 MiB,另留一个更早的 <code>app.old.log</code>。随时可以删。</p>
|
||||
|
||||
<h2 id="site"><a class="anchor" href="#site">usemagpie.ai 能看到什么</a></h2>
|
||||
<p>magpie 会向自己的网站请求几样东西,不受隐私设置影响,就像任何应用访问自己的更新服务器。这些请求都不带安装 ID 或账号。</p>
|
||||
|
||||
@@ -267,6 +267,7 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
<tr><td><code>magpie usage 7d</code></td><td>按 Agent 和模型统计 token 与费用</td></tr>
|
||||
<tr><td><code>magpie tools</code> · <code>magpie tool generate_image "…" -o hero.png</code></td><td>列出并直接调用 magpie 通过 MCP 给 Agent 的工具(生图、识图、联网搜索、插件的工具);生成的图片保存到文件</td></tr>
|
||||
<tr><td><code>magpie tray</code></td><td>只启动菜单栏图标</td></tr>
|
||||
<tr><td><code>magpie log</code> · <code>magpie log -f</code></td><td>magpie 的日志在哪里,报告问题时附上;<code>-n 200</code> 打印应用日志的最后几行,<code>-f</code> 持续跟随</td></tr>
|
||||
</table></div>
|
||||
|
||||
<h2 id="faq"><a class="anchor" href="#faq">常见问题</a></h2>
|
||||
@@ -283,6 +284,9 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
<h3>没有梯子,安装或更新连不上 GitHub 怎么办?</h3>
|
||||
<p>给安装脚本和 <code>magpie update</code> 加代理:<code>curl -fsSL https://usemagpie.ai/install.sh | sh -s -- --proxy http://127.0.0.1:7890</code>,或 <code>magpie update --proxy socks5://127.0.0.1:1080</code>(支持 http、https、socks5、socks5h;环境变量 <code>HTTPS_PROXY</code>、<code>ALL_PROXY</code> 同样生效)。<code>--mirror <前缀></code> 从你指定的 GitHub 下载镜像取发布文件,即 <code><前缀>https://github.com/…</code>;<code>magpie update mirror <前缀></code> 让之后每次更新(包括应用自己的更新)都用它,<code>magpie update mirror off</code> 取消。不指定就不用任何镜像;文件的 SHA-256 始终来自 usemagpie.ai,而不是镜像,镜像改过的文件会被拒绝安装。应用自己的更新走 <span class="ui">设置</span> → <span class="ui">代理</span>。</p>
|
||||
|
||||
<h3 id="log">magpie 的日志在哪里?</h3>
|
||||
<p>应用(窗口、菜单栏或托盘图标、快捷面板,不论怎样打开)写入 <code>app.log</code>:macOS 上是 <code>~/Library/Logs/magpie/app.log</code>,Windows 上是 <code>%LOCALAPPDATA%\magpie\logs\app.log</code>,Linux 上是 <code>~/.local/state/magpie/app.log</code>(设置了 <code>$XDG_STATE_HOME</code> 时是 <code>$XDG_STATE_HOME/magpie</code>),便携版则在数据文件夹的 <code>logs</code> 里。<span class="ui">设置</span> → <span class="ui">关于</span> → <span class="ui">日志</span>里有它的路径,<span class="ui">打开</span>会显示它所在的文件夹;<code>magpie log</code> 打印路径,<code>magpie log -f</code> 持续跟随。满 5 MiB 后它变成旁边的 <code>app.old.log</code>,最多保留两个文件。它记的是 magpie 做了什么、遇到了哪些错误(服务商拒绝请求、重试、插件没能启动),不含你的密钥、提示词或回复;看起来像密钥或令牌的内容也会被遮掉。作为服务运行的 <code>magpie serve</code> 日志在别处:macOS 上是 <code>~/Library/Logs/magpie/serve.log</code>,Linux 上是 <code>journalctl --user -u magpie</code>;<code>magpie log</code> 也会列出它。</p>
|
||||
|
||||
<h3 id="privacy">magpie 会发送我的哪些信息?</h3>
|
||||
<p>你的提示词、回复、密钥和账号只发给你用的供应商,中间没有 magpie 自己的服务器。正式发布的 magpie 每天告诉我们一次它在用,好让我们知道有多少人在用、该先照顾哪些:本机随机生成的 ID、magpie 版本和系统,以及用了哪些 agent、供应商和模型,只用 magpie 自己的 ID(<code>claude</code>、<code>deepseek</code>、<code>deepseek/deepseek-v4</code>)和各自的数量。你自己添加的供应商及其上的模型只记作 <code>custom</code>。添加供应商页里排在最前的合作伙伴,每天被展示、打开和添加的次数也一并发送,只有次数。不发送名称、Base URL、账号、密钥、提示词和用量。<span class="ui">设置</span> → <span class="ui">隐私</span> → <span class="ui">分享我用的 agent、provider 和模型</span> 可以去掉 agent、供应商、模型和合作伙伴次数这部分;<span class="ui">计入用户数</span>、<code>DO_NOT_TRACK=1</code> 或 <code>MAGPIE_NO_STATS=1</code> 全部关闭。从源码构建的版本从不发送。合作伙伴的官网和「获取 Key」链接经 <code>usemagpie.ai/go/…</code> 跳转,跳转前记一次点击(哪个合作伙伴、哪个链接、哪个国家),usemagpie.ai 也会统计合作伙伴列表被拉取的次数。这部分是服务器本身看到的,和任何网站统计访问一样,不受上面的设置影响;不记录 ID、IP 和账号。插件、导入链接和库里的图标经 <code>usemagpie.ai/api/icon</code> 获取,图标所在的服务器只看到 Cloudflare 的地址,看不到你的 IP;这台服务器只转发图片,不计数也不记录。<a href="/docs/zh/privacy">隐私页</a>列出了 magpie 自己发出的所有内容,附每日计数的示例、它在本机留下的文件和每个开关。</p>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user