Files
plugins/packages/agent-console/daemon/src/history/import.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

110 lines
3.9 KiB
TypeScript

// History import (§7.6): Claude sessions live in ~/.claude/projects/<encoded dir>/<sessionId>.jsonl.
// Don't guess the encoding rule: list every directory, read the first record with a cwd from each jsonl, match the project with samePath.
// Read-only throughout.
import { readdir, readFile, stat } from "node:fs/promises";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { samePath } from "../util/paths.js";
import { tr } from "../util/i18n.js";
const CLAUDE_ROOT = join(homedir(), ".claude", "projects");
type Rec = Record<string, unknown>;
const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
// One jsonl line → {cwd?, title?, isUserText}
function parseLine(line: string): { cwd?: string; userText?: string } | null {
let r: Rec;
try {
r = rec(JSON.parse(line));
} catch {
return null;
}
const cwd = str(r.cwd);
let userText: string | undefined;
if (r.type === "user") {
const content = rec(r.message).content;
if (typeof content === "string") userText = content;
else if (Array.isArray(content)) {
const t = content.map((p) => (rec(p).type === "text" ? str(rec(p).text) : undefined)).find(Boolean);
userText = t;
}
}
return { cwd, userText };
}
async function* linesOf(path: string): AsyncGenerator<string> {
const text = await readFile(path, "utf8").catch(() => "");
for (const line of text.split("\n")) {
if (line.trim()) yield line;
}
}
// Project cwd → that project's past sessions
export async function listClaudeHistory(cwd: string): Promise<{ sessionId: string; title: string; updatedAt: number; messageCount: number }[]> {
const out: { sessionId: string; title: string; updatedAt: number; messageCount: number }[] = [];
const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);
for (const d of dirs) {
const dirPath = join(CLAUDE_ROOT, d);
const files = (await readdir(dirPath).catch(() => [] as string[])).filter((f) => f.endsWith(".jsonl"));
for (const f of files) {
const path = join(dirPath, f);
let match = false;
let title = "";
let count = 0;
for await (const line of linesOf(path)) {
const p = parseLine(line);
if (!p) continue;
if (!match) {
if (!p.cwd) continue;
match = samePath(p.cwd, cwd);
if (!match) break;
}
if (p.userText && !title) title = p.userText.slice(0, 40);
if (p.userText) count++;
}
if (!match) continue;
const s = await stat(path).catch(() => null);
out.push({
sessionId: f.replace(/\.jsonl$/, ""),
title: title || tr("history.untitled"),
updatedAt: s ? Math.round(s.mtimeMs) : 0,
messageCount: count,
});
}
}
out.sort((a, b) => b.updatedAt - a.updatedAt);
return out;
}
// Read one session's jsonl → SDK message shape (so mapSdkMessage can be reused)
export async function readClaudeHistory(sessionId: string, cwd: string): Promise<Rec[]> {
const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);
for (const d of dirs) {
const path = join(CLAUDE_ROOT, d, `${sessionId}.jsonl`);
if (!existsSync(path)) continue;
// Confirm it belongs to this project (the first cwd record matches)
const msgs: Rec[] = [];
let matched = false;
for await (const line of linesOf(path)) {
const p = parseLine(line);
if (!matched) {
if (p?.cwd && samePath(p.cwd, cwd)) matched = true;
else continue;
}
let r: Rec;
try {
r = rec(JSON.parse(line));
} catch {
continue;
}
// Keep only user/assistant/result — same shape as the SDK's streamed messages, so mapSdkMessage can digest them
if (r.type === "user" || r.type === "assistant") msgs.push(r);
}
return msgs;
}
return [];
}