Files
plugins/packages/agent-console/daemon/src/log.ts
T
qingnian108 08ad5e3956 page-agent-console 1.1.0: QA fixes, neutral accent, own dropdown menus, self-heal after a host restart, by qingnian108 (#569)
page-agent-console 1.1.0, by qingnian108 (#569).

QA fixes B1-B21, a reworked UI, a new logo, and self-heal after a plugin host restart. In this version:
- Accent: a fixed neutral grey (charcoal in light mode, light grey in dark mode). Magpie's accent tokens are dropped on purpose. Surfaces, text, lines, fonts and semantic colours still follow magpie.
- Every native <select> (composer effort/mode/Cursor fast, Settings, Debug) is now the page's own SelectMenu, a button plus a listbox.
- The registry summary again discloses the 127.0.0.1 service and its lifecycle, that only its own page gets the token, the ~46 MB first install, and that Claude Code isn't bundled (en, zh).
- session.js is written once at bind with beat:false, and beats every 4s only after the first /open. A new host deletes a dead host's session.js at startup (owner pid in session-owner.json, outside the page folder).
- The daemon swallows console EPIPE after a hard host kill and handles a lifeline close once.

Run at 930c6e2 on macOS (mote, Node 22), in a fresh copy:
- npm ci, then npm run check (tsc daemon + web): ok
- npx vitest run: 46 files, 288 passed, 17 skipped
- npm run verify:build: app.js, app.css, index.html and daemon/dist/main.js(.map) rebuild byte-identical
- bun scripts/check.mjs agent-console: ok
- Playwright Chromium and WebKit, light and dark, sandbox HOME, page served under /_magpie/plugin/<id>/page with a stub bridge passing accent #ff0000:
  - accent: --accent and the primary button stay grey (rgb(38,38,38) light, rgb(229,229,229) dark); no <select> anywhere.
  - Settings menus: click opens the menu inside the window; ArrowDown+Enter picks, closes and refocuses the trigger; the pick persists through the daemon.
  - Esc closes the menu, not the dialog, and then closes the dialog. Clicking an option keeps the dialog open; a click outside closes the menu.
  - A host that was never opened writes beat:false and doesn't rewrite session.js. SIGKILL it, start a new host: the stale file is removed and the page reaches the new daemon.
  - After an open, session.js beats. SIGKILL the host: the page heals in ~5.3s and stays. A daemon-only crash heals in ~5.3s.
  - Daemon logs: no uncaughtException or EPIPE, one lifeline line per daemon exit.
Not tried: the composer pickers in a browser (they need a thread with an installed agent; same SelectMenu component), magpie's real sandboxed frame, Windows and Linux.
2026-11-01 00:37:07 +08:00

79 lines
2.6 KiB
TypeScript

// Simple logging: writes dataDir/logs/daemon-YYYY-MM-DD.log (kept 7 days) and to the console.
import { appendFileSync, mkdirSync, readdirSync, rmSync } from "node:fs";
import { join } from "node:path";
let logDir = "";
let today = "";
let logFile = "";
function fileName(d: Date): string {
const p = (n: number) => String(n).padStart(2, "0");
return `daemon-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.log`;
}
export function initLog(dataDir: string): void {
logDir = join(dataDir, "logs");
mkdirSync(logDir, { recursive: true });
// Keep 7 days
try {
const keep = new Set<string>();
const now = new Date();
for (let i = 0; i < 7; i++) {
keep.add(fileName(new Date(now.getTime() - i * 86400000)));
}
for (const f of readdirSync(logDir)) {
if (/^daemon-\d{4}-\d{2}-\d{2}\.log$/.test(f) && !keep.has(f)) {
rmSync(join(logDir, f), { force: true });
}
}
} catch {}
}
// The console is a pipe to the plugin host. When the host is killed hard, the reader is gone and a write fails with EPIPE
// (asynchronously, as an 'error' event on the stream): without a listener that becomes an uncaughtException. Once that happens
// the console is dropped and only the log file is written.
let consoleGone = false;
let guarded = false;
function guardConsole(): void {
if (guarded) return;
guarded = true;
for (const stream of [process.stdout, process.stderr]) {
// EPIPE, EIO, ERR_STREAM_DESTROYED…: any write error means the reader is gone; logging must never take the daemon down
stream?.on?.("error", () => { consoleGone = true; });
}
}
export function consoleClosed(): boolean {
return consoleGone;
}
export function log(level: "info" | "warn" | "error", msg: string, extra?: unknown): void {
const line = `[${new Date().toISOString()}] [${level}] ${msg}${extra !== undefined ? " " + safeJson(extra) : ""}`;
try {
const d = new Date();
const name = fileName(d);
if (name !== today && logDir) {
today = name;
logFile = join(logDir, name);
}
if (logFile) appendFileSync(logFile, line + "\n", "utf8");
} catch {}
guardConsole();
if (consoleGone) return;
const stream = level === "info" ? process.stdout : process.stderr;
if (stream?.destroyed || stream?.writableEnded) { consoleGone = true; return; }
const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log;
try {
fn(`[agent-console] ${msg}`, extra !== undefined ? extra : "");
} catch {
consoleGone = true;
}
}
function safeJson(v: unknown): string {
try {
return JSON.stringify(v);
} catch {
return String(v);
}
}