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.
This commit is contained in:
qingnian108
2026-11-01 00:37:07 +08:00
committed by GitHub
parent 6727a1e68c
commit 08ad5e3956
77 changed files with 3541 additions and 1251 deletions
+16
View File
@@ -1,5 +1,19 @@
# Agent Console
**把终端里的 Agent CLI 搬进 magpie 窗口,直接对话使用。**
作者 qingnian108,源码在 [qingnian108/magpie-agent-console](https://github.com/qingnian108/magpie-agent-console),欢迎提问题和建议。
支持 Claude Code、Codex、Cursor 等,直接用你电脑上已安装的 CLI。左边是项目和对话,中间聊天,右边看改动、文件和终端。
**Use your terminal Agent CLIs right inside magpie, by chat.**
By qingnian108. Source: [qingnian108/magpie-agent-console](https://github.com/qingnian108/magpie-agent-console). Issues welcome.
Works with Claude Code, Codex, Cursor and more, using the CLIs you already have.
---
A Magpie page plugin that drives real local Agent CLIs (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh). Each conversation is a **persistent Agent session** on a standalone Node daemon. Close or refresh the page — the Agent keeps running while Magpie is open. Reopen the page and you pick up where you left off. When Magpie quits, the daemon and its Agents stop; threads are persisted and can be resumed next time.
## Install
@@ -68,12 +82,14 @@ The daemon can run Agents with full access to your machine, so the token that un
- **Host is checked on every request and WebSocket upgrade** (gate and daemon): it must be `127.0.0.1:<port>` or `localhost:<port>` with the actually bound port, otherwise 421. This blocks DNS rebinding, where the attacker's requests carry no `Origin` at all.
- The gate answers only `GET /open?k=<gate key>` (the daemon token is not accepted there), refuses any request that carries an `Origin` header, and sends `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`.
- WebSocket connections must send `hello` with the token within 5 seconds, otherwise they are closed with code 4401.
- **Coming back after a plugin host restart.** Magpie restarts its plugin host from time to time; the old host's daemon exits with it and the new host has a new gate key. `boot.js` passes its own page URL to the gate as `back`; the gate accepts it only if it is a loopback `/_magpie/plugin/<id>/index.html` URL and forwards it **only in the fragment** (`#t=…&b=…`). When the daemon page can't reconnect for 5 seconds (or on 重试 / Retry) it navigates back to that page, which reads the fresh `session.js` and opens the new gate. To tell a live host's `session.js` from one a killed host left behind (a hard kill can't delete it), the file carries `ts` and `beat`: from the first page open on, the host rewrites it every 4 s, and after a lost connection `boot.js` only takes a file written after the loss; a host that was never opened doesn't rewrite it, and a new host deletes a file whose writer (pid in `session-owner.json`, outside the page folder) is gone before Magpie serves the page. The daemon page checks the URL again before following it, so it is never an open redirect, and the token never leaves its own fragment.
## Lifecycle
- Importing `index.mjs` has no side effects (no port, no process, no files).
- `server()` (called by Magpie's plugin host at host start-up — this includes short-lived hosts started by CLI commands such as `magpie plugin add` or `magpie plugin list`) binds the gate and writes `page/session.js`. If the port is busy it retries every 2 s in the background without blocking the host; a detached 0.1.0 daemon still holding the port is shut down once, only after it proves its identity by answering `/api/ping` with the token from `daemon.json`.
- The daemon starts when the page is opened for the first time and is reused for later opens. It is a normal (non-detached) child of the plugin host.
- `server()` waits ~1.2 s before binding the gate (`AGENT_CONSOLE_BIND_DELAY_MS`), so the short-lived hosts started by `magpie` CLI commands usually exit before they take the gate or write `session.js`; a gate port held by the long-lived host is logged only if it stays busy for ~10 s.
- The daemon exits when its stdin pipe closes or its parent pid disappears (checked every 2 s) — i.e. when Magpie quits or the plugin host restarts — and after 60 minutes idle.
- Magpie's plugin host treats the value returned by `server()` as OpenCode hooks and never calls `stop()`; it exits the Bun process when Magpie closes its stdin. A synchronous `exit` handler therefore closes the daemon's lifeline, signals it, and removes the `session.js` this host wrote. `stop()` (used by tests and other hosts) closes the gate, ends the daemon (graceful, then forced) and removes `session.js`.
- Agents stop with the daemon. Threads are persisted and can be resumed after reopening the page. On macOS/Linux every Agent CLI, the Codex app-server and the no-PTY shell run in their own process group, so stopping one ends everything it started; on Windows the same is done with `taskkill /T`. A process `exit` hook reaps any tree still alive when the daemon exits.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6 -8
View File
@@ -1,10 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="28" fill="#0d9488"/>
<path d="M34 44h60a8 8 0 0 1 8 8v24a8 8 0 0 1-8 8H62l-14 12v-12H34a8 8 0 0 1-8-8V52a8 8 0 0 1 8-8z" fill="#fff"/>
<g fill="#0d9488">
<circle cx="48" cy="62" r="5"/>
<circle cx="64" cy="62" r="5"/>
<circle cx="80" cy="62" r="5"/>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<rect width="64" height="64" rx="15" fill="#26292b"/>
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="4">
<path d="M14 20.5 25 31 14 41.5" stroke="#fff"/>
<path d="M29.14 23.61A12 12 0 1 1 46.63 39.92L48.6 47.6 39.85 42.93A12 12 0 0 1 29.14 38.39" stroke="#fff"/>
<path d="M35.6 35.4h6" stroke="#2dd4bf"/>
</g>
<path d="M40 96l-8 12M88 96l8 12" stroke="#fff" stroke-width="6" stroke-linecap="round"/>
</svg>

Before

Width:  |  Height:  |  Size: 497 B

After

Width:  |  Height:  |  Size: 448 B

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -1,6 +1,7 @@
// Tool name → kind / title / detail mapping (ported from lib/agents/kinds.mjs).
// Adapters call callInfo(name, input, cwd) to get {kind, title, detail}; the frontend renders by kind.
import type { ToolKind } from "../timeline/types.js";
import { tr } from "../util/i18n.js";
const MAX_CMD = 80;
const trunc = (s: string, n = MAX_CMD): string => (s.length > n ? s.slice(0, n - 1) + "…" : s);
@@ -28,44 +29,44 @@ export function callInfo(name: string, input: ToolInput = {}, cwd = ""): CallInf
switch (t) {
case "Read":
return f("read", `读取 ${relPath(file, cwd)}`, { path: file, offset: input.offset, limit: input.limit });
return f("read", tr("tool.read", { x: relPath(file, cwd) }), { path: file, offset: input.offset, limit: input.limit });
case "Edit":
return f("edit", `编辑 ${relPath(file, cwd)}`, { path: file, old: input.old_string, new: input.new_string });
return f("edit", tr("tool.edit", { x: relPath(file, cwd) }), { path: file, old: input.old_string, new: input.new_string });
case "MultiEdit":
return f("edit", `编辑 ${relPath(file, cwd)}(${((input.edits as unknown[]) || []).length} 处)`, { path: file, edits: input.edits ?? [] });
return f("edit", tr("tool.multiEdit", { x: relPath(file, cwd), n: ((input.edits as unknown[]) || []).length }), { path: file, edits: input.edits ?? [] });
case "Write":
return f("write", `${input._exists ? "覆盖" : "新建"} ${relPath(file, cwd)}`, { path: file, content: input.content });
return f("write", tr(input._exists ? "tool.overwrite" : "tool.create", { x: relPath(file, cwd) }), { path: file, content: input.content });
case "NotebookEdit":
return f("edit", `编辑笔记本 ${relPath(String(input.notebook_path || file), cwd)}`, { path: input.notebook_path ?? file });
return f("edit", tr("tool.notebook", { x: relPath(String(input.notebook_path || file), cwd) }), { path: input.notebook_path ?? file });
case "Bash":
return f("bash", `运行 ${trunc(String(input.command ?? ""))}`, { command: input.command, description: input.description });
return f("bash", tr("tool.run", { x: trunc(String(input.command ?? "")) }), { command: input.command, description: input.description });
case "BashOutput":
return f("bash", `查看输出 ${String(input.bash_id ?? "")}`, { bashId: input.bash_id });
return f("bash", tr("tool.output", { x: String(input.bash_id ?? "") }), { bashId: input.bash_id });
case "KillShell":
return f("bash", `结束进程 ${String(input.shell_id ?? "")}`, { shellId: input.shell_id });
return f("bash", tr("tool.kill", { x: String(input.shell_id ?? "") }), { shellId: input.shell_id });
case "Grep":
return f("search", `搜索 "${trunc(String(input.pattern ?? ""), 40)}"`, { pattern: input.pattern, path: input.path, glob: input.glob });
return f("search", tr("tool.grep", { x: trunc(String(input.pattern ?? ""), 40) }), { pattern: input.pattern, path: input.path, glob: input.glob });
case "Glob":
case "LS":
return f("glob", `查找 ${trunc(String(input.pattern ?? input.path ?? ""), 40)}`, { pattern: input.pattern, path: input.path });
return f("glob", tr("tool.glob", { x: trunc(String(input.pattern ?? input.path ?? ""), 40) }), { pattern: input.pattern, path: input.path });
case "WebFetch":
return f("web", `打开 ${hostOf(String(input.url ?? ""))}`, { url: input.url });
return f("web", tr("tool.fetch", { x: hostOf(String(input.url ?? "")) }), { url: input.url });
case "WebSearch":
return f("web", `搜索网页 "${trunc(String(input.query ?? ""), 40)}"`, { query: input.query });
return f("web", tr("tool.webSearch", { x: trunc(String(input.query ?? ""), 40) }), { query: input.query });
case "TodoWrite": {
const items = todoItems((input.todos as { content?: string; text?: string; status?: string }[]) ?? []);
const done = items.filter((x) => x.status === "done").length;
return f("todo", `更新待办(${done}/${items.length})`, { items });
return f("todo", tr("tool.todo", { done, n: items.length }), { items });
}
case "Task":
case "Agent":
return f("task", `子任务:${trunc(String(input.description ?? input.prompt ?? ""), 40)}`, { description: input.description });
return f("task", tr("tool.task", { x: trunc(String(input.description ?? input.prompt ?? ""), 40) }), { description: input.description });
default:
break;
}
const m = /^mcp__([^_]+)__(.+)$/.exec(t);
if (m) return f("mcp", `${m[1]} · ${m[2]}`, { server: m[1], tool: m[2] });
return f("other", t || "工具", {});
return f("other", t || tr("tool.generic"), {});
}
function hostOf(url: string): string {
@@ -5,6 +5,8 @@ import type { ProjectsStore } from "../store/projects.js";
import type { SettingsStore } from "../store/settings.js";
import type { AttachmentStore } from "../store/attachments.js";
import type { Provider, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../providers/types.js";
import { launchFromSettings } from "../providers/launch.js";
import { clampMode } from "../providers/modes.js";
import { resolveAttachmentRefs } from "../util/attachmentRefs.js";
import { getProvider } from "../providers/registry.js";
import { catalogById, providerCreatable } from "../providers/catalog.js";
@@ -21,6 +23,8 @@ import {
} from "../providers/codex/commands.js";
const SLASH_CACHE_TTL_MS = 10 * 60 * 1000;
/** Idle Agent processes kept warm at most (one per conversation); older idle ones are closed (resumed on the next message) */
export const MAX_WARM_IDLE = 3;
type QueuedMessage = { id: string; text: string; attachments: { path: string; mime: string; name?: string }[] };
type PendingRequest = {
@@ -46,6 +50,9 @@ type Runtime = {
starting: boolean; // startTurn in progress (session is still null while it is being created)
commands: SlashCommand[];
sessionCreating: Promise<ProviderSession> | null;
/** Text streamed as deltas only (ACP Agents): saved per segment as assistant_message / reasoning (B1) */
pendingText: Map<string, { type: "assistant" | "reasoning"; itemId: string; text: string }>;
deltasOnly: boolean;
};
type DeltaType = "assistant_delta" | "reasoning_delta" | "tool_output_delta";
@@ -136,6 +143,17 @@ export class AgentManager {
return false;
}
/** Drop a queued message that hasn't been sent yet (the × on the composer's queue list) */
removeQueued(threadId: string, queueId: string): boolean {
const rt = this.runtimes.get(threadId);
if (!rt) return false;
const before = rt.queue.length;
rt.queue = rt.queue.filter((q) => q.id !== queueId);
if (rt.queue.length === before) return false;
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
return true;
}
runtimeInfo(threadId: string): { status: string; queue: unknown[]; pending: unknown[] } | null {
const rt = this.runtimes.get(threadId);
if (!rt) return null;
@@ -168,6 +186,8 @@ export class AgentManager {
starting: false,
commands: [],
sessionCreating: null,
pendingText: new Map(),
deltasOnly: false,
};
this.runtimes.set(threadId, r);
}
@@ -187,7 +207,7 @@ export class AgentManager {
}
// ---- send ----
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior: SendBehavior = "queue"): Promise<void> {
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior: SendBehavior = "queue"): Promise<"started" | "steered" | "queued"> {
const meta = await this.mustThread(threadId);
if (meta.archived) {
await this.threads.patch(threadId, { archived: false });
@@ -219,19 +239,20 @@ export class AgentManager {
steered: true,
attachments: this.attachmentLabels(attachmentRefs),
});
return;
return "steered";
} catch (e) {
// Steering failed (e.g. the turn hasn't really started yet) → fall back to queueing so the message isn't lost
log("info", `thread ${threadId} 插话失败,改为排队:${String(e)}`);
}
}
const q: QueuedMessage = { id: "q" + Date.now().toString(36), text: input.text, attachments: attachmentRefs };
const q: QueuedMessage = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs };
rt.queue.push(q);
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
return;
return "queued";
}
await this.startTurn(threadId, input.text, attachmentRefs);
return "started";
}
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[]): Promise<void> {
@@ -337,14 +358,24 @@ export class AgentManager {
return;
}
if (ev.type === "assistant_delta" || ev.type === "reasoning_delta" || ev.type === "tool_output_delta") {
// Goes through the coalescer, not persisted
// Goes through the coalescer, not persisted; Agents that never send the complete message get it saved from the deltas
if (rt.deltasOnly && ev.type !== "tool_output_delta") {
const key = `${ev.type === "assistant_delta" ? "assistant" : "reasoning"}\0${ev.itemId}`;
const prior = rt.pendingText.get(key);
rt.pendingText.set(key, { type: ev.type === "assistant_delta" ? "assistant" : "reasoning", itemId: ev.itemId, text: (prior?.text ?? "") + ev.text });
}
rt.coalescer.push(deltaKey(ev.type, ev.itemId), ev.text);
return;
}
// Before persisting a complete event, flush that itemId's pending deltas first (keeps ordering)
const evItemId = (ev as { itemId?: unknown }).itemId;
if (typeof evItemId === "string") this.flushDeltas(rt, evItemId);
// Another item starts (tool call, plan, permission …) or the turn ends: the text streamed so far is complete, save it first
if (rt.pendingText.size && ev.type !== "usage" && ev.type !== "assistant_message" && ev.type !== "reasoning") {
await this.persistPendingText(threadId, rt);
}
if (ev.type === "assistant_message" || ev.type === "reasoning") {
rt.pendingText.delete(`${ev.type === "assistant_message" ? "assistant" : "reasoning"}\0${ev.itemId}`);
await this.appendRaw(threadId, ev);
return;
}
@@ -405,6 +436,7 @@ export class AgentManager {
await this.setStatus(threadId, "idle");
// Next queued message
const next = rt.queue.shift();
if (!next) void this.recycleIdle().catch(() => {});
if (next) {
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
// A queued message that fails to start is only logged; it must not break the event pump (startTurn already wrote notice/turn_ended)
@@ -418,6 +450,16 @@ export class AgentManager {
await this.appendRaw(threadId, ev);
}
private async persistPendingText(threadId: string, rt: Runtime): Promise<void> {
const pending = [...rt.pendingText.values()];
rt.pendingText.clear();
for (const p of pending) {
if (!p.text) continue;
this.flushDeltas(rt, p.itemId);
await this.appendRaw(threadId, { type: p.type === "assistant" ? "assistant_message" : "reasoning", itemId: p.itemId, text: p.text });
}
}
private alive(_s: ProviderSession): boolean {
return true; // mock /exit closes the queue; end of the event stream is handled separately
}
@@ -426,10 +468,10 @@ export class AgentManager {
async respond(threadId: string, requestId: string, answer: RespondAnswer): Promise<void> {
const rt = this.rt(threadId);
const pending = rt.pending.get(requestId);
if (!pending) throw new ApiError("not_found", "授权/提问不存在或已回应");
if (!pending) throw new ApiError("not_found", tr("err.requestGone"));
if (pending.kind === "permission" && answer.optionId) {
const valid = pending.options.some((o) => o.id === answer.optionId);
if (!valid) throw new ApiError("bad_params", `optionId 非法:${answer.optionId}`);
if (!valid) throw new ApiError("bad_params", tr("err.badOption", { id: String(answer.optionId) }));
}
rt.pending.delete(requestId);
if (pending.kind === "permission") {
@@ -527,7 +569,7 @@ export class AgentManager {
patch: { cursorFast?: boolean; cursorAutoReview?: boolean },
): Promise<void> {
const meta = await this.mustThread(threadId);
if (meta.provider !== "cursor") throw new ApiError("bad_params", "仅 Cursor 对话支持该选项");
if (meta.provider !== "cursor") throw new ApiError("bad_params", tr("err.cursorOnly"));
const next = await this.threads.patch(threadId, patch);
const rt = this.rt(threadId);
const sess = rt.session as { updateCursorOpts?(f: boolean, a: boolean): Promise<void> } | null;
@@ -541,14 +583,14 @@ export class AgentManager {
async setProvider(threadId: string, providerId: string): Promise<void> {
await this.mustThread(threadId);
const meta = await this.threads.get(threadId);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
const rt = this.rt(threadId);
if (rt.status === "running" || rt.status === "initializing" || rt.starting) {
throw new ApiError("busy", "对话运行中,不能更换 Agent");
throw new ApiError("busy", tr("err.busySwitch"));
}
const events = await this.threads.readEvents(threadId, 0, 5000);
if (events.some((e) => e.type === "user_message")) {
throw new ApiError("bad_params", "已有消息,不能更换 Agent");
throw new ApiError("bad_params", tr("err.hasMessages"));
}
const p = await this.assertProviderUsable(providerId);
if (rt.session) {
@@ -562,7 +604,7 @@ export class AgentManager {
await this.threads.patch(threadId, {
provider: providerId,
model: null,
mode: p.capabilities.modes.includes(meta.mode) ? meta.mode : (p.capabilities.modes[0] ?? "default"),
mode: clampMode(p.capabilities.modes, meta.mode),
effort: null,
providerSessionId: null,
status: "idle",
@@ -684,7 +726,7 @@ export class AgentManager {
if (rt.session) return rt.session;
const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId });
const proj = await this.projects.get(meta.projectId);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
let model = meta.model;
// DSH model IDs come from ACP; old conversations may still hold a model ID from another Agent.
// Clear that stale value so it isn't sent to the wrong Magpie provider route.
@@ -705,16 +747,13 @@ export class AgentManager {
}
if (opts.updateStatus) await this.setStatus(threadId, "initializing");
const settings = await this.settings.get();
const custom = settings.providerCommand?.[meta.provider];
const launch =
custom?.executable?.trim()
? { cmd: custom.executable.trim(), prefixArgs: custom.args ?? [] }
: undefined;
const launch = launchFromSettings(settings, meta.provider);
rt.deltasOnly = !!provider.capabilities.deltasOnly;
rt.session = await provider.createSession({
threadId,
cwd: proj.path,
model,
mode: meta.mode,
mode: clampMode(provider.capabilities.modes, meta.mode),
effort: meta.effort,
resumeId: meta.providerSessionId,
cursorFast: meta.cursorFast,
@@ -734,7 +773,7 @@ export class AgentManager {
// ---- internals ----
private async mustThread(threadId: string): Promise<ThreadMeta> {
const meta = await this.threads.get(threadId);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
return meta;
}
@@ -744,17 +783,17 @@ export class AgentManager {
private async assertProviderUsable(providerId: string, opts: { allowDisabled?: boolean } = {}): Promise<Provider> {
const p = getProvider(providerId);
if (!p) throw new ApiError("bad_params", `未知 Agent:${providerId}`);
if (!p) throw new ApiError("bad_params", tr("provider.unknown", { id: providerId }));
const s = await this.settings.get();
if (!opts.allowDisabled && !isProviderEnabled(s, providerId)) {
throw new ApiError("bad_params", `${p.name} 已在设置中禁用`);
throw new ApiError("bad_params", tr("provider.disabledNamed", { name: p.name }));
}
const entry = catalogById(providerId);
if (entry && !providerCreatable(entry.status)) {
throw new ApiError("bad_params", `${p.name} 尚未接入,暂不能新建对话`);
throw new ApiError("bad_params", tr("provider.plannedNamed", { name: p.name }));
}
const det = await cachedDetect(p);
if (!det.available) throw new ApiError("bad_params", det.reason ?? `${p.name} 未安装或不可用`);
const det = await cachedDetect(p, launchFromSettings(s, providerId));
if (!det.available) throw new ApiError("bad_params", det.reason ?? tr("provider.unavailable", { name: p.name }));
return p;
}
@@ -780,14 +819,34 @@ export class AgentManager {
this.gw.publish(`thread:${threadId}`, { type: "event", event: full });
}
private async recycleIdle(): Promise<void> {
const s = await this.settings.get();
const limit = (s.idleCloseMinutes ?? 30) * 60_000;
for (const rt of this.runtimes.values()) {
if (rt.status === "idle" && rt.pending.size === 0 && Date.now() - rt.lastActivity > limit) {
log("info", `空闲回收 thread ${rt.threadId}`);
await this.close(rt.threadId);
/** B17: idle Agent processes are closed after idleCloseMinutes, and at most MAX_WARM_IDLE of them stay warm
* (least recently used go first). A running turn, one starting, or one waiting on an approval is never touched. */
private recycling = false;
async recycleIdle(): Promise<void> {
if (this.recycling) return;
this.recycling = true;
try {
const s = await this.settings.get();
const minutes = Number(s.idleCloseMinutes);
const limit = (Number.isFinite(minutes) && minutes > 0 ? minutes : 30) * 60_000;
const idle = [...this.runtimes.values()]
.filter((rt) => rt.session && rt.status === "idle" && !rt.starting && !rt.sessionCreating && rt.pending.size === 0 && rt.queue.length === 0)
.sort((a, b) => b.lastActivity - a.lastActivity);
const now = Date.now();
for (const [i, rt] of idle.entries()) {
const expired = now - rt.lastActivity > limit;
if (!expired && i < MAX_WARM_IDLE) continue;
log("info", `idle cleanup: closing thread ${rt.threadId} (${expired ? "idle timeout" : "over the warm limit"})`);
try {
await this.close(rt.threadId);
} catch (e) {
// The conversation may have been deleted meanwhile: just forget its runtime
log("info", `idle cleanup: thread ${rt.threadId}: ${String((e as Error)?.message ?? e)}`);
this.runtimes.delete(rt.threadId);
}
}
} finally {
this.recycling = false;
}
}
}
@@ -4,6 +4,7 @@
import { readdir, readFile, stat } from "node:fs/promises";
import { join, normalize, sep, relative, extname } from "node:path";
import ignore from "ignore";
import { tr } from "../util/i18n.js";
export type TreeEntry = { name: string; path: string; isDir: boolean };
export type ReadResult = {
@@ -77,13 +78,13 @@ export class FileService {
async tree(projectPath: string, dir: string): Promise<{ entries?: TreeEntry[]; error?: string }> {
const rel = insidePath(projectPath, dir);
if (rel === null) return { error: "路径不允许" };
if (rel === null) return { error: tr("fs.pathDenied") };
const abs = join(projectPath, rel);
const s = await stat(abs).catch(() => null);
if (!s?.isDirectory()) return { error: "目录不存在" };
if (!s?.isDirectory()) return { error: tr("fs.dirMissing") };
const ig = await this.igFor(projectPath);
const dirents = await readdir(abs, { withFileTypes: true }).catch(() => null);
if (!dirents) return { error: "无法读取目录" };
if (!dirents) return { error: tr("fs.dirUnreadable") };
const out: TreeEntry[] = [];
for (const d of dirents) {
if (out.length >= MAX_PER_LEVEL) break;
@@ -111,14 +112,14 @@ export class FileService {
async read(projectPath: string, p: string): Promise<ReadResult> {
const rel = insidePath(projectPath, p);
if (rel === null) return { error: "路径不允许" };
if (rel === null) return { error: tr("fs.pathDenied") };
const abs = join(projectPath, rel);
const s = await stat(abs).catch(() => null);
if (!s) return { error: "文件不存在" };
if (!s.isFile()) return { error: "不是文件" };
if (!s) return { error: tr("fs.fileMissing") };
if (!s.isFile()) return { error: tr("fs.notFile") };
if (s.size > MAX_READ) return { tooLarge: true };
const buf = await readFile(abs).catch(() => null);
if (!buf) return { error: "无法读取" };
if (!buf) return { error: tr("fs.unreadable") };
const head = buf.subarray(0, 8192);
if (head.includes(0)) return { binary: true };
const { text, encoding } = decodeText(buf);
@@ -3,6 +3,7 @@ import { execFile } from "node:child_process";
import { existsSync } from "node:fs";
import { cp, mkdir, readFile, rename, rm, stat } from "node:fs/promises";
import { join, normalize, sep } from "node:path";
import { tr } from "../util/i18n.js";
export type GitFileEntry = {
path: string;
@@ -21,7 +22,7 @@ function runGit(cwd: string, args: string[]): Promise<{ code: number; out: strin
execFile("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (e, stdout, stderr) => {
const code = e && typeof (e as { code?: number }).code === "number" ? (e as { code: number }).code! : e ? 1 : 0;
const missing = (e as NodeJS.ErrnoException | null)?.code === "ENOENT";
res({ code, out: String(stdout ?? ""), err: missing ? "找不到 git(请先安装 git 并加入 PATH)" : String(stderr || (e?.message ?? "")) });
res({ code, out: String(stdout ?? ""), err: missing ? tr("git.missing") : String(stderr || (e?.message ?? "")) });
});
});
}
@@ -84,18 +85,18 @@ export class GitService {
// Unified diff text; {tooLarge:true} when the diff is > 1MB
async diff(projectPath: string, p: string): Promise<{ diff?: string; tooLarge?: boolean; untracked?: boolean; error?: string }> {
const rel = insidePath(projectPath, p);
if (!rel) return { error: "路径不允许" };
if (!rel) return { error: tr("fs.pathDenied") };
// Check untracked first (git diff prints nothing for untracked files)
const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]);
if (ls.code !== 0) {
// Untracked/not in the index: treat the whole file as added
const full = join(projectPath, rel);
if (!existsSync(full)) return { error: "文件不存在" };
if (!existsSync(full)) return { error: tr("fs.fileMissing") };
const s = await stat(full);
if (!s.isFile()) return { error: "不是文件" };
if (!s.isFile()) return { error: tr("fs.notFile") };
if (s.size > DIFF_LIMIT) return { tooLarge: true };
const text = await readFile(full, "utf8").catch(() => null);
if (text === null) return { error: "二进制或无法读取" };
if (text === null) return { error: tr("git.binary") };
const lines = text.split("\n").map((l) => "+" + l).join("\n");
return { untracked: true, diff: `--- /dev/null\n+++ b/${rel}\n@@ -0,0 +1,${text.split("\n").length} @@\n${lines}` };
}
@@ -112,9 +113,9 @@ export class GitService {
// Tracked → git restore; untracked → move to trash/discarded/<ts>/<relpath>
async discard(projectPath: string, p: string, dataDir: string): Promise<{ ok: boolean; trashedTo?: string; error?: string }> {
const rel = insidePath(projectPath, p);
if (!rel) return { ok: false, error: "路径不允许" };
if (!rel) return { ok: false, error: tr("fs.pathDenied") };
// Only discard a single file: an empty path / "." would make git restore act on the whole repository
if (rel === "." || rel === "" || rel === "./") return { ok: false, error: "路径不允许" };
if (rel === "." || rel === "" || rel === "./") return { ok: false, error: tr("fs.pathDenied") };
const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]);
if (ls.code === 0) {
let r = await runGit(projectPath, ["restore", "--staged", "--worktree", "--", rel]);
@@ -123,7 +124,7 @@ export class GitService {
return { ok: true };
}
const full = join(projectPath, rel);
if (!existsSync(full)) return { ok: false, error: "文件不存在" };
if (!existsSync(full)) return { ok: false, error: tr("fs.fileMissing") };
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const dest = join(dataDir, "trash", "discarded", stamp, rel);
await mkdir(join(dest, ".."), { recursive: true });
@@ -5,6 +5,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path";
import { homedir } from "node:os";
import { samePath } from "../util/paths.js";
import { tr } from "../util/i18n.js";
const CODEX_ROOT = join(homedir(), ".codex", "sessions");
@@ -77,7 +78,7 @@ export async function listCodexHistory(cwd: string): Promise<CodexHistItem[]> {
}
if (!match) continue;
const s = await stat(path).catch(() => null);
out.push({ sessionId, title: title || "(无标题)", updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count });
out.push({ sessionId, title: title || tr("history.untitled"), updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count });
}
out.sort((a, b) => b.updatedAt - a.updatedAt);
return out;
@@ -135,7 +136,7 @@ export async function readCodexHistory(sessionId: string, cwd: string): Promise<
}
} else if (p.type === "function_call" || p.type === "custom_tool_call") {
const name = str(p.name) ?? "tool";
out.push({ type: "notice", level: "info", message: `(历史)调用 ${name}` });
out.push({ type: "notice", level: "info", message: tr("history.toolCall", { name }) });
}
continue;
}
@@ -161,7 +162,7 @@ export async function readCodexHistory(sessionId: string, cwd: string): Promise<
if (p2.type === "function_call" || p2.type === "custom_tool_call") {
// Tool steps collapse into a one-line notice (§7.6, Codex part)
const name = str(p2.name) ?? "tool";
out.push({ type: "notice", level: "info", message: `(历史)调用 ${name}` });
out.push({ type: "notice", level: "info", message: tr("history.toolCall", { name }) });
}
}
out.push({ type: "turn_ended", turnId: "import", status: "completed" });
@@ -6,6 +6,7 @@ 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");
@@ -68,7 +69,7 @@ export async function listClaudeHistory(cwd: string): Promise<{ sessionId: strin
const s = await stat(path).catch(() => null);
out.push({
sessionId: f.replace(/\.jsonl$/, ""),
title: title || "(无标题)",
title: title || tr("history.untitled"),
updatedAt: s ? Math.round(s.mtimeMs) : 0,
messageCount: count,
});
+16 -15
View File
@@ -7,6 +7,7 @@ import { checkHost, classifyOrigin, tokenEqual } from "./security.js";
import type { Config } from "./config.js";
import type { AttachmentStore } from "./store/attachments.js";
import { log } from "./log.js";
import { tr } from "./util/i18n.js";
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
@@ -61,7 +62,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
await route(req, res);
} catch (e) {
log("error", "HTTP 处理异常", { url: req.url, err: String(e) });
if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: "internal", message: "服务内部错误" } });
if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: "internal", message: tr("http.internal") } });
else res.end();
}
});
@@ -81,7 +82,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
}
const origin = classifyOrigin(req.headers.origin, cfg.port);
if (origin === "foreign") {
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "来源不允许" } });
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: tr("http.badOrigin") } });
return;
}
@@ -95,7 +96,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
// the preflight itself returns no data, and the real request still has to pass the token check.
if (req.method === "OPTIONS") {
if (pathname !== "/api/upload" || origin === "none") {
sendJson(res, 403, { ok: false, e: { code: "bad_preflight", message: "预检不允许" } });
sendJson(res, 403, { ok: false, e: { code: "bad_preflight", message: tr("http.badPreflight") } });
return;
}
send(res, 204, "", {
@@ -117,7 +118,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
(typeof headerToken === "string" && tokenEqual(headerToken, cfg.token)) ||
(typeof queryToken === "string" && tokenEqual(queryToken, cfg.token));
if (!validToken) {
sendJson(res, 403, { ok: false, e: { code: "bad_token", message: "令牌无效" } });
sendJson(res, 403, { ok: false, e: { code: "bad_token", message: tr("http.badToken") } });
return;
}
// In a sandbox iframe (no allow-same-origin) the page's origin is null, so even a same-address fetch is cross-origin:
@@ -134,7 +135,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
const id = safeDecode(pathname.slice("/attachments/".length));
const a = id === null ? null : await attachments.get(id);
if (!a) {
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "附件不存在" } });
sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noAttachment") } });
return;
}
const data = await attachments.read(a.id);
@@ -145,11 +146,11 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
// Static assets: refuse Origin: null. Ordinary navigations and <script src>/<link> subresource requests carry no Origin;
// one with null can only be someone else's sandboxed/data:/file: page doing a fetch — give it nothing, and no CORS headers.
if (origin === "opaque") {
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "来源不允许" } });
sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: tr("http.badOrigin") } });
return;
}
if (req.method !== "GET" && req.method !== "HEAD") {
sendJson(res, 405, { ok: false, e: { code: "method", message: "方法不允许" } });
sendJson(res, 405, { ok: false, e: { code: "method", message: tr("http.method") } });
return;
}
if (pathname === "/" || pathname === "/index.html") {
@@ -158,24 +159,24 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
const html = await readFile(join(appDir, "index.html"), "utf8");
send(res, 200, html, { ...STATIC_HEADERS, "content-type": "text/html; charset=utf-8" });
} catch {
send(res, 503, "app 还没构建(缺 app/index.html)", { ...STATIC_HEADERS, "content-type": "text/plain; charset=utf-8" });
send(res, 503, tr("http.noApp"), { ...STATIC_HEADERS, "content-type": "text/plain; charset=utf-8" });
}
return;
}
// Other static files must be inside app/
const decoded = safeDecode(pathname);
if (decoded === null) {
sendJson(res, 400, { ok: false, e: { code: "bad_path", message: "路径不合法" } });
sendJson(res, 400, { ok: false, e: { code: "bad_path", message: tr("http.badPath") } });
return;
}
const rel = normalize(decoded).replace(/^([\\/])+/, "");
const full = normalize(join(appDir, rel));
if (!full.startsWith(normalize(appDir)) || rel.includes("..")) {
sendJson(res, 403, { ok: false, e: { code: "bad_path", message: "路径不允许" } });
sendJson(res, 403, { ok: false, e: { code: "bad_path", message: tr("http.pathDenied") } });
return;
}
if (!existsSync(full) || !(await stat(full)).isFile()) {
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "文件不存在" } });
sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noFile") } });
return;
}
const data = await readFile(full);
@@ -190,14 +191,14 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
if (pathname === "/api/upload" && req.method === "POST") {
const name = url.searchParams.get("name") ?? "";
if (!attachments.allowedExt(name)) {
sendJson(res, 400, { ok: false, e: { code: "bad_type", message: "不支持的文件类型" } });
sendJson(res, 400, { ok: false, e: { code: "bad_type", message: tr("http.badType") } });
return;
}
// The declared size is already over the limit: reject without reading the body
const declared = Number(req.headers["content-length"] ?? 0);
if (declared > MAX_UPLOAD) {
res.setHeader("connection", "close");
sendJson(res, 413, { ok: false, e: { code: "too_large", message: "文件太大(上限 50MB)" } });
sendJson(res, 413, { ok: false, e: { code: "too_large", message: tr("http.tooLarge") } });
req.resume();
return;
}
@@ -208,7 +209,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
size += b.length;
if (size > MAX_UPLOAD) {
res.setHeader("connection", "close");
sendJson(res, 413, { ok: false, e: { code: "too_large", message: "文件太大(上限 50MB)" } });
sendJson(res, 413, { ok: false, e: { code: "too_large", message: tr("http.tooLarge") } });
return;
}
chunks.push(b);
@@ -217,7 +218,7 @@ export function createHttpServer(cfg: Config, appDir: string, attachments: Attac
sendJson(res, 200, { ok: true, id: a.id, name: a.name, mime: a.mime, size: a.size });
return;
}
sendJson(res, 404, { ok: false, e: { code: "not_found", message: "接口不存在" } });
sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noRoute") } });
}
if (hooks.onUpgrade) {
+26 -1
View File
@@ -29,6 +29,23 @@ export function initLog(dataDir: string): void {
} 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 {
@@ -40,8 +57,16 @@ export function log(level: "info" | "warn" | "error", msg: string, extra?: unkno
}
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;
fn(`[agent-console] ${msg}`, extra !== undefined ? extra : "");
try {
fn(`[agent-console] ${msg}`, extra !== undefined ? extra : "");
} catch {
consoleGone = true;
}
}
function safeJson(v: unknown): string {
+20 -4
View File
@@ -34,6 +34,8 @@ const cfg = parseConfig(process.argv.slice(2));
// Top-level safety net: log, don't exit
process.on("uncaughtException", (e) => {
// A console write after the host's pipe closed (EPIPE) is expected while exiting, not a crash worth logging
if ((e as NodeJS.ErrnoException)?.code === "EPIPE") return;
log("error", "uncaughtException", { err: String(e?.stack ?? e) });
});
process.on("unhandledRejection", (e) => {
@@ -129,7 +131,12 @@ async function main(): Promise<void> {
chmodSync(daemonJsonPath, 0o600);
log("info", `daemon 已启动 端口 ${cfg.port} 数据目录 ${cfg.dataDir} 版本 ${cfg.version} pid ${process.pid}`);
// Standalone dev mode: print the open URL with the token to the console (console only, never the log file)
if (!cfg.parentPid) console.log(`[agent-console] 打开 http://127.0.0.1:${cfg.port}/#t=${cfg.token}`);
// B20: standalone (dev) runs only: the token goes to an interactive terminal, never to a redirected stdout or a log
if (!cfg.parentPid) {
console.log(process.stdout.isTTY
? `[agent-console] open http://127.0.0.1:${cfg.port}/#t=${cfg.token}`
: `[agent-console] listening on http://127.0.0.1:${cfg.port}/ (token not printed: stdout is not a terminal)`);
}
// Idle exit: check every minute; no WS connection + no running conversation + no open terminal → exit after idleExitMinutes
let idleSince = Date.now();
@@ -173,9 +180,18 @@ async function main(): Promise<void> {
}
}, 2000);
parentWatch.unref();
process.stdin.on("end", () => shutdown(0));
process.stdin.on("close", () => shutdown(0));
process.stdin.on("error", () => shutdown(0));
// Logged so a daemon that went away with its plugin host (Magpie restarting it) can be told from an idle exit
// 'end' and 'close' both fire when the pipe goes away: handle it once
let lifelineGone = false;
const lifelineClosed = () => {
if (lifelineGone) return;
lifelineGone = true;
log("info", "plugin host closed the lifeline (stdin); daemon exiting with it");
shutdown(0);
};
process.stdin.on("end", lifelineClosed);
process.stdin.on("close", lifelineClosed);
process.stdin.on("error", lifelineClosed);
process.stdin.resume();
}
}
@@ -1,4 +1,5 @@
import type { ModelInfo } from "../types.js";
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
export function runCli(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 25000): Promise<string> {
@@ -33,7 +34,7 @@ export function parseDevinModelsList(text: string): ModelInfo[] {
if (!id || id.length < 3) continue;
models.push({ id, name });
}
if (!models.length) return [{ id: "default", name: "默认", isDefault: true }];
if (!models.length) return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];
const adaptive = models.find((x) => x.id === "adaptive");
if (adaptive) adaptive.isDefault = true;
else models[0]!.isDefault = true;
@@ -50,7 +51,7 @@ export function parseOpencodeModels(text: string): ModelInfo[] {
const name = id.includes("/") ? id.split("/").slice(1).join("/") : id;
models.push({ id, name: name.replace(/-/g, " ") });
}
if (!models.length) return [{ id: "default", name: "默认", isDefault: true }];
if (!models.length) return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];
models[0]!.isDefault = true;
return models;
}
@@ -3,6 +3,7 @@ import type { ClientApp } from "@agentclientprotocol/sdk";
import { methods } from "@agentclientprotocol/sdk";
import type { RespondAnswer } from "../types.js";
import type { ProviderEvent } from "../../timeline/types.js";
import { tr } from "../../util/i18n.js";
export type PermBridge = {
push(ev: ProviderEvent): void;
@@ -36,7 +37,7 @@ export function registerAcpClientHandlers(app: ClientApp, bridge: PermBridge): v
bridge.push({
type: "permission_request",
requestId,
title: tc.title ?? tc.name ?? "需要授权",
title: tc.title ?? tc.name ?? tr("tool.needsApproval"),
kind: tc.kind ?? "tool",
detail: tc.rawInput ?? undefined,
options,
@@ -30,10 +30,19 @@ function textFromContent(content: schema.ContentBlock): string {
return "";
}
export type MapCtx = { itemPrefix: string; messageIds: Map<string, string> };
/** seg: text segment number, bumped when a tool call / plan comes between two runs of text, so the text before and
* after a tool call are separate items (live and persisted alike: the manager saves each segment when the next item starts). */
export type MapCtx = { itemPrefix: string; messageIds: Map<string, string>; seg: number; lastWasText: boolean };
export function newMapCtx(): MapCtx {
return { itemPrefix: "a" + rid() + "_", messageIds: new Map() };
return { itemPrefix: "a" + rid() + "_", messageIds: new Map(), seg: 0, lastWasText: false };
}
function endTextSegment(ctx: MapCtx): void {
if (ctx.lastWasText) {
ctx.seg++;
ctx.lastWasText = false;
}
}
export function mapSessionUpdate(update: schema.SessionUpdate, ctx: MapCtx): ProviderEvent[] {
@@ -44,19 +53,22 @@ export function mapSessionUpdate(update: schema.SessionUpdate, ctx: MapCtx): Pro
case "agent_message_chunk": {
const text = textFromContent(update.content);
if (!text) break;
const itemId = mid ? ctx.messageIds.get(mid) ?? ctx.itemPrefix + mid : ctx.itemPrefix + "msg";
const itemId = `${ctx.itemPrefix}${mid ?? "msg"}_${ctx.seg}`;
if (mid) ctx.messageIds.set(mid, itemId);
ctx.lastWasText = true;
out.push({ type: "assistant_delta", itemId, text });
break;
}
case "agent_thought_chunk": {
const text = textFromContent(update.content);
if (!text) break;
const itemId = mid ? ctx.itemPrefix + "t_" + mid : ctx.itemPrefix + "think";
const itemId = `${ctx.itemPrefix}t_${mid ?? "think"}_${ctx.seg}`;
ctx.lastWasText = true;
out.push({ type: "reasoning_delta", itemId, text });
break;
}
case "tool_call":
endTextSegment(ctx);
out.push({
type: "tool_call",
itemId: ctx.itemPrefix + update.toolCallId,
@@ -67,17 +79,19 @@ export function mapSessionUpdate(update: schema.SessionUpdate, ctx: MapCtx): Pro
});
break;
case "tool_call_update":
endTextSegment(ctx);
out.push({
type: "tool_call",
itemId: ctx.itemPrefix + update.toolCallId,
kind: mapToolKind(update.kind),
title: update.title ?? update.name ?? "tool",
title: update.title ?? update.name ?? "",
status: mapToolStatus(update.status),
input: update.rawInput,
output: typeof update.rawOutput === "string" ? update.rawOutput : undefined,
});
break;
case "plan":
endTextSegment(ctx);
out.push({
type: "plan",
itemId: ctx.itemPrefix + "plan",
@@ -176,9 +176,9 @@ export function cursorCatalogToModels(catalog: CursorCatalog, currentModel: stri
}
export function cursorProbeModels(acpArgs: string[], providerId?: string) {
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise<ModelInfo[]> => {
try {
const { parsed, ext, promptCaps } = await probeAcpRaw(r, acpArgs, 40000, "cursor/list_available_models");
const { parsed, ext, promptCaps } = await probeAcpRaw(r, [...acpArgs, ...launchArgs], 40000, "cursor/list_available_models");
rememberPromptCaps(providerId, promptCaps);
const fromCatalog = ext ? cursorCatalogToModels(ext as CursorCatalog, parsed.currentModel) : [];
// If the extension method is unavailable (older Cursor CLI), fall back to the model list reported by the session (no levels)
@@ -195,13 +195,13 @@ export function cursorProbeModels(acpArgs: string[], providerId?: string) {
* route a new conversation uses (dsh answers for the route it starts on, see dsh.ts).
*/
export function dshProbeModels(providerId?: string) {
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise<ModelInfo[]> => {
try {
const first = await probeAcpRaw(r, DSH_ACP_ARGS, 30000);
const first = await probeAcpRaw(r, [...DSH_ACP_ARGS, ...launchArgs], 30000);
let caps = first.promptCaps;
const start = dshDefaultModel(first.parsed.models, first.parsed.currentModel);
if (start && start !== first.parsed.currentModel && dshRoute(start)) {
caps = await probeAcpRaw(r, await dshAcpArgs(start), 30000).then((x) => x.promptCaps, () => caps);
caps = await probeAcpRaw(r, [...await dshAcpArgs(start), ...launchArgs], 30000).then((x) => x.promptCaps, () => caps);
}
rememberPromptCaps(providerId, caps);
return probeToModels(first.parsed);
@@ -213,9 +213,9 @@ export function dshProbeModels(providerId?: string) {
}
export function acpProbeModels(acpArgs: string[], providerId?: string) {
return async (r: ResolveResult & { ok: true }): Promise<ModelInfo[]> => {
return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise<ModelInfo[]> => {
try {
return probeToModels(await probeAcp(r, acpArgs, 30000, providerId));
return probeToModels(await probeAcp(r, [...acpArgs, ...launchArgs], 30000, providerId));
} catch (e) {
log("warn", "ACP 探测模型失败", { err: String(e) });
return [];
@@ -1,6 +1,8 @@
import type { Provider, DetectResult, ModelInfo, Capabilities, Mode } from "../types.js";
import type { Provider, DetectResult, ModelInfo, Capabilities, Mode, LaunchCommand } from "../types.js";
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
import { resolveFirstBin } from "../../util/bin.js";
import { resolveLaunch } from "../launch.js";
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
import { AcpSession } from "./session.js";
import { knownPromptCaps } from "./promptCaps.js";
@@ -19,7 +21,7 @@ export type AcpProviderConfig = {
appVersion?: string;
flavor?: "cursor" | "generic";
capabilities?: Capabilities;
fetchModels?: (r: ResolveResult & { ok: true }) => Promise<ModelInfo[]>;
fetchModels?: (r: ResolveResult & { ok: true }, launchArgs?: string[]) => Promise<ModelInfo[]>;
/** Our permission modes → this Agent's mode names over ACP; when given, only modes in the table are shown */
modeMap?: Partial<Record<Mode, string>>;
/** Mode names shown in the UI (the Agent's own naming) */
@@ -36,6 +38,7 @@ export const acpCapabilities: Capabilities = {
cost: false,
effort: [],
modes: ["plan", "default", "acceptEdits", "bypassPermissions"],
deltasOnly: true,
};
export const cursorAcpCapabilities: Capabilities = {
@@ -85,30 +88,32 @@ export function createAcpProvider(cfg: AcpProviderConfig): Provider {
const learned = knownPromptCaps(cfg.id);
return learned ? { ...caps, images: learned.image, imagesKnown: true } : { ...caps, images: false, imagesKnown: false };
},
async detect(): Promise<DetectResult> {
const r = await resolveProviderBin(cfg);
async detect(launch?: LaunchCommand): Promise<DetectResult> {
const r = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg);
if (!r.ok) {
return { available: false, reason: r.reason, installHint: cfg.installHint };
}
let version: string | undefined;
const versionArgs = cfg.id === "devin" ? ["version"] : ["cursor", "opencode"].includes(cfg.id) ? ["--version"] : null;
try {
if (cfg.id === "cursor") {
version = (await runVersion(r, ["--version"])).split(/\r?\n/)[0]?.trim();
} else if (cfg.id === "devin") {
version = (await runVersion(r, ["version"])).split(/\r?\n/)[0]?.trim();
} else if (cfg.id === "opencode") {
version = (await runVersion(r, ["--version"])).split(/\r?\n/)[0]?.trim();
if (versionArgs) {
// Only the internal prefix: the user's extra args are meant for the ACP command, not for --version
version = (await runVersion(r, [...(launch?.prefixArgs ?? []), ...versionArgs])).split(/\r?\n/)[0]?.trim();
}
} catch {
/* Having the binary is enough */
}
return { available: true, bin: r.display, version };
},
async listModels(): Promise<ModelInfo[]> {
const r = await resolveProviderBin(cfg);
if (!r.ok) return [{ id: "default", name: "默认", isDefault: true }];
if (cfg.fetchModels) return cfg.fetchModels(r);
return [{ id: "default", name: "默认", isDefault: true }];
async listModels(launch?: LaunchCommand): Promise<ModelInfo[]> {
const resolved = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg);
if (!resolved.ok) return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];
// The internal prefix rides on the resolution (fetchModels puts its own ACP args after it), the user's args go last
const r = launch?.prefixArgs?.length && resolved.via !== "cmd-shim"
? { ...resolved, prefixArgs: [...resolved.prefixArgs, ...launch.prefixArgs] }
: resolved;
if (cfg.fetchModels) return cfg.fetchModels(r, launch?.args ?? []);
return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];
},
async createSession(o) {
return new AcpSession({
@@ -2,11 +2,12 @@
import type { ActiveSession, ClientConnection, ClientContext } from "@agentclientprotocol/sdk";
import { client, methods, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
import type { ChildProcess } from "node:child_process";
import type { ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import { mapAcpAvailableCommands, sortSlashCommands } from "../slash.js";
import type { ProviderEvent } from "../../timeline/types.js";
import { AsyncQueue } from "../../util/queue.js";
import { resolveFirstBin, type ResolveResult } from "../../util/bin.js";
import { launchArgv, resolveLaunch } from "../launch.js";
import { absCwd, acpStreamFromChild, killAcpChild, spawnResolved } from "./spawn.js";
import { registerAcpClientHandlers } from "./clientHandlers.js";
import { mapSessionUpdate, newMapCtx, stopToTurnEnd, type MapCtx } from "./mapUpdate.js";
@@ -45,7 +46,7 @@ export type AcpSessionOpts = {
modeMap?: Partial<Record<Mode, string>>;
cursorFast?: boolean;
cursorAutoReview?: boolean;
launch?: { cmd: string; prefixArgs: string[] };
launch?: LaunchCommand;
};
export class AcpSession implements ProviderSession {
@@ -91,18 +92,11 @@ export class AcpSession implements ProviderSession {
private async boot(): Promise<void> {
const bin = this.o.launch
? ({
ok: true as const,
cmd: this.o.launch.cmd,
prefixArgs: this.o.launch.prefixArgs,
display: this.o.launch.cmd,
via: "custom",
binName: "custom",
} satisfies ResolveResult & { ok: true; binName: string })
? await resolveLaunch(this.o.launch).then((r) => r.ok ? ({ ...r, binName: "custom" } as ResolveResult & { ok: true; binName: string }) : r)
: await resolveFirstBin(this.o.binCandidates?.length ? this.o.binCandidates : [this.o.binName]);
if (!bin.ok) throw new Error(bin.reason);
try {
this.child = spawnResolved(bin, this.o.acpArgs, { cwd: this.o.cwd });
this.child = spawnResolved(bin, launchArgv(this.o.acpArgs, this.o.launch), { cwd: this.o.cwd });
this.child.stderr?.on("data", (d: Buffer) => {
const t = d.toString().trim();
if (t) log("info", `[${this.o.binName} acp] ${t.slice(0, 500)}`);
@@ -110,7 +104,7 @@ export class AcpSession implements ProviderSession {
this.child.on("error", (e) => this.failInit(e));
this.child.on("close", (code) => {
if (!this.closed && code !== 0) {
this.q.push({ type: "notice", level: "error", message: `${this.o.binName} 进程退出 (${code})` });
this.q.push({ type: "notice", level: "error", message: tr("acp.exited", { name: this.o.binName, code: String(code) }) });
}
});
@@ -1,3 +1,4 @@
import { tr } from "../util/i18n.js";
/** Provider catalog (fixed, 8 entries).
* status: verified=accepted on a real machine | experimental=usable but not guaranteed | planned=integration not confirmed
* All 8 are currently verified; default toggle: verified ones are on by default (see enabled.ts). */
@@ -13,12 +14,12 @@ export type ProviderCatalogEntry = {
export const PROVIDER_CATALOG: ProviderCatalogEntry[] = [
{ id: "claude", name: "Claude Code", bins: ["claude"], installHint: "npm i -g @anthropic-ai/claude-code", status: "verified" },
{ id: "codex", name: "Codex", bins: ["codex"], installHint: "见 OpenAI Codex CLI 安装说明", status: "verified" },
{ id: "cursor", name: "Cursor", bins: ["cursor-agent", "cursor"], installHint: "安装 Cursor 并确保 CLI 在 PATH", status: "verified" },
{ id: "copilot", name: "Copilot", bins: ["copilot"], installHint: "GitHub Copilot CLI 安装说明", status: "verified" },
{ id: "opencode", name: "OpenCode", bins: ["opencode"], installHint: "npm i -g opencode / 见 OpenCode 文档", status: "verified" },
{ id: "pi", name: "Pi", bins: ["pi-acp", "pi", "pi-coding-agent"], installHint: "npm i -g pi-acp(或 Pi coding agent + ACP 适配器)", status: "verified" },
{ id: "devin", name: "Devin CLI", bins: ["devin"], installHint: "Devin CLI 官方安装", status: "verified" },
{ id: "codex", name: "Codex", bins: ["codex"], installHint: "npm i -g @openai/codex", status: "verified" },
{ id: "cursor", name: "Cursor", bins: ["cursor-agent", "cursor"], installHint: "curl https://cursor.com/install -fsS | bash", status: "verified" },
{ id: "copilot", name: "Copilot", bins: ["copilot"], installHint: "npm i -g @github/copilot", status: "verified" },
{ id: "opencode", name: "OpenCode", bins: ["opencode"], installHint: "npm i -g opencode-ai", status: "verified" },
{ id: "pi", name: "Pi", bins: ["pi-acp", "pi", "pi-coding-agent"], installHint: "npm i -g pi-acp", status: "verified" },
{ id: "devin", name: "Devin CLI", bins: ["devin"], installHint: "https://docs.devin.ai/cli", status: "verified" },
{ id: "dsh", name: "dsh", bins: ["dsh"], installHint: "npm i -g @deepseek-ai/dsh", status: "verified" },
];
@@ -8,6 +8,8 @@
// ← {type:"control_request", request_id, request:{subtype:"can_use_tool", tool_name, input, tool_use_id, ...}}
// → {type:"control_response", response:{subtype:"success", request_id, response:{behavior:"allow", updatedInput} | {behavior:"deny", message, interrupt?}}}
// ← {type:"control_cancel_request", request_id} (the CLI no longer waits for that answer)
import type { LaunchCommand } from "../types.js";
import { launchArgv } from "../launch.js";
import type { ChildProcess } from "node:child_process";
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
import { AsyncQueue } from "../../util/queue.js";
@@ -23,6 +25,8 @@ export type ClaudeCliOpts = {
effort: string | null;
resume: string | null;
env?: NodeJS.ProcessEnv;
/** Settings › Launch command: internal prefix before, user args after the built-in flags */
launch?: LaunchCommand;
};
export type PermissionDecision =
@@ -78,7 +82,7 @@ export class ClaudeCli {
private spawnError: Error | null = null;
constructor(private o: ClaudeCliOpts, private canUseTool: CanUseTool) {
const args = claudeArgs(o);
const args = launchArgv(claudeArgs(o), o.launch);
this.child = spawnBin(o.bin, args, {
cwd: o.cwd,
env: { ...(o.env ?? process.env), NO_COLOR: "1", FORCE_COLOR: "0" },
@@ -2,6 +2,7 @@
import type { ProviderEvent } from "../../timeline/types.js";
import { callInfo, todoItems } from "../../agents/kinds.js";
import { editDetail } from "../../agents/diff.js";
import { tr } from "../../util/i18n.js";
const MAX_OUTPUT = 20 * 1024;
const ANSI_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07/g;
@@ -41,6 +42,14 @@ const rec = (v: unknown): Rec => (v && typeof v === "object" ? (v as Rec) : {});
const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined);
// One stream-json message → 0..n unified events
/** total_cost_usd is Claude Code's estimate at Anthropic's prices. For another vendor's model behind a gateway (DeepSeek through
* magpie, say) it is meaningless, so it is only kept when every model the turn used is a Claude model (B14). */
export function costIsReal(modelUsage: unknown): boolean {
if (!modelUsage || typeof modelUsage !== "object") return true;
const names = Object.keys(modelUsage as Record<string, unknown>);
return names.every((n) => /claude|opus|sonnet|haiku/i.test(n));
}
export function mapSdkMessage(m: unknown, st: MapState, cwd: string): ProviderEvent[] {
const out: ProviderEvent[] = [];
if (!m || typeof m !== "object") return out;
@@ -53,10 +62,10 @@ export function mapSdkMessage(m: unknown, st: MapState, cwd: string): ProviderEv
}
// compact_boundary / status / api_retry etc. → lightweight notices
if (r.subtype === "api_retry") {
out.push({ type: "notice", level: "warn", message: `API 重试中(第 ${r.attempt ?? "?"} 次)` });
out.push({ type: "notice", level: "warn", message: tr("notice.apiRetry", { n: String(r.attempt ?? "?") }) });
}
if (r.subtype === "compact_boundary") {
out.push({ type: "notice", level: "info", message: "上下文已压缩" });
out.push({ type: "notice", level: "info", message: tr("notice.compacted") });
}
return out;
}
@@ -147,7 +156,7 @@ export function mapSdkMessage(m: unknown, st: MapState, cwd: string): ProviderEv
inputTokens: num("input_tokens"),
outputTokens: num("output_tokens"),
cacheReadTokens: num("cache_read_input_tokens"),
costUsd: typeof r.total_cost_usd === "number" ? r.total_cost_usd : 0,
costUsd: typeof r.total_cost_usd === "number" && costIsReal(r.modelUsage) ? r.total_cost_usd : 0,
});
const subtype = str(r.subtype) ?? "";
const interrupted = st.sawInterrupt || /interrupt/i.test(subtype);
@@ -1,5 +1,5 @@
// Claude Provider (§7.2): detection + createSession(ClaudeSession).
import type { Provider, ProviderSession, DetectResult, ModelInfo, HistoryItem } from "../types.js";
import type { Provider, ProviderSession, DetectResult, ModelInfo, HistoryItem, LaunchCommand } from "../types.js";
import { resolveBin, killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
import { ClaudeSession } from "./session.js";
import { listClaudeModels } from "./models.js";
@@ -7,6 +7,7 @@ import { listClaudeHistory, readClaudeHistory } from "../../history/import.js";
import { mapSdkMessage, newMapState } from "./map.js";
import type { ProviderEvent } from "../../timeline/types.js";
import { tr } from "../../util/i18n.js";
import { resolveLaunch } from "../launch.js";
const INSTALL_HINT = "npm i -g @anthropic-ai/claude-code";
@@ -43,16 +44,18 @@ function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs =
});
}
export function createClaudeProvider(): Provider {
export function createClaudeProvider(opts: { resolve?: (name: string) => Promise<ResolveResult> } = {}): Provider {
const resolve = opts.resolve ?? resolveBin;
const resolveCustom = opts.resolve ? (l: LaunchCommand) => opts.resolve!(l.cmd) : resolveLaunch;
return {
id: "claude",
name: "Claude Code",
capabilities: claudeCapabilities,
async detect(): Promise<DetectResult> {
const bin = await resolveBin("claude");
async detect(launch?: LaunchCommand): Promise<DetectResult> {
const bin = launch ? await resolveCustom(launch) : await resolve("claude");
if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT };
try {
const version = await runVersion(bin, ["--version"]);
const version = await runVersion(bin, [...(launch?.prefixArgs ?? []), "--version"]);
return { available: true, bin: bin.display, version: version.trim().split("\n")[0] || "" };
} catch {
return { available: true, bin: bin.display, version: "" };
@@ -62,7 +65,7 @@ export function createClaudeProvider(): Provider {
return listClaudeModels();
},
async createSession(o): Promise<ProviderSession> {
const bin = await resolveBin("claude");
const bin = o.launch ? await resolveCustom(o.launch) : await resolve("claude");
if (!bin.ok) throw new Error(tr("claude.notFound", { detail: bin.reason, hint: INSTALL_HINT }));
return new ClaudeSession({
threadId: o.threadId,
@@ -72,6 +75,7 @@ export function createClaudeProvider(): Provider {
effort: o.effort,
resumeId: o.resumeId,
bin,
launch: o.launch,
});
},
// §7.6: jsonl sessions under ~/.claude/projects matched by cwd
@@ -1,6 +1,6 @@
// Claude ProviderSession (§7.2.2/7.2.4/7.2.5/7.2.6): the user's own `claude` CLI over stream-json (./cli.ts),
// one process per conversation, streaming, permissions, interrupt, hot switching. No SDK.
import type { ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import type { ProviderEvent } from "../../timeline/types.js";
import { AsyncQueue } from "../../util/queue.js";
import { callInfo } from "../../agents/kinds.js";
@@ -30,6 +30,7 @@ export type ClaudeSessionOpts = {
resumeId: string | null;
/** The user's claude, as resolveBin found it (a .cmd / .ps1 shim is started through cmd.exe / PowerShell by spawnBin) */
bin: ClaudeBin;
launch?: LaunchCommand;
/** Environment for the CLI (tests point it at a stand-in); process.env when absent */
env?: NodeJS.ProcessEnv;
onModeChange?: (mode: Mode) => void; // Callback when a plan is approved → default (the manager updates meta)
@@ -71,6 +72,7 @@ export class ClaudeSession implements ProviderSession {
effort,
resume: this.sessionId,
env: this.o.env,
launch: this.o.launch,
},
(req) => this.canUseTool(req),
);
@@ -172,9 +174,9 @@ export class ClaudeSession implements ProviderSession {
kind: "tool",
detail,
options: [
{ id: "allow", label: "允许", kind: "allow_once" },
{ id: "allow_always", label: "本对话都允许", kind: "allow_always" },
{ id: "deny", label: "拒绝", kind: "reject_once" },
{ id: "allow", label: tr("perm.allow"), kind: "allow_once" },
{ id: "allow_always", label: tr("perm.allowSession"), kind: "allow_always" },
{ id: "deny", label: tr("perm.deny"), kind: "reject_once" },
],
});
return new Promise<PermissionDecision>((resolve) => {
@@ -182,7 +184,7 @@ export class ClaudeSession implements ProviderSession {
signal.addEventListener("abort", () => {
if (this.pending.delete(requestId)) {
this.emit({ type: "permission_resolved", requestId, cancelled: true });
resolve({ behavior: "deny", message: "已取消", interrupt: true });
resolve({ behavior: "deny", message: "Cancelled by the user", interrupt: true });
}
}, { once: true });
});
@@ -190,7 +192,7 @@ export class ClaudeSession implements ProviderSession {
private toPermissionDecision(a: RespondAnswer, input: Record<string, unknown>): PermissionDecision {
if (a.cancelled || a.optionId === "deny") {
return { behavior: "deny", message: "用户拒绝了此操作", ...(a.cancelled ? { interrupt: true } : {}) };
return { behavior: "deny", message: "The user denied this action", ...(a.cancelled ? { interrupt: true } : {}) };
}
return { behavior: "allow", updatedInput: input };
}
@@ -203,12 +205,12 @@ export class ClaudeSession implements ProviderSession {
this.emit({
type: "permission_request",
requestId,
title: "Agent 提交了计划",
title: tr("perm.plan"),
kind: "plan",
detail: { plan: planText },
options: [
{ id: "implement", label: "实施", kind: "allow_once" },
{ id: "reject", label: "拒绝", kind: "reject_once" },
{ id: "implement", label: tr("perm.implement"), kind: "allow_once" },
{ id: "reject", label: tr("perm.deny"), kind: "reject_once" },
],
});
const answer = await new Promise<RespondAnswer>((resolve) => {
@@ -221,7 +223,7 @@ export class ClaudeSession implements ProviderSession {
}, { once: true });
});
if (answer.cancelled || answer.optionId === "reject") {
return { behavior: "deny", message: "用户拒绝了计划,请根据反馈修改", ...(answer.cancelled ? { interrupt: true } : {}) };
return { behavior: "deny", message: "The user rejected the plan; revise it based on their feedback", ...(answer.cancelled ? { interrupt: true } : {}) };
}
// implement: switch back to default mode
try {
@@ -246,7 +248,7 @@ export class ClaudeSession implements ProviderSession {
}, { once: true });
});
if (answer.cancelled) {
return { behavior: "deny", message: "用户取消了提问", interrupt: true };
return { behavior: "deny", message: "The user cancelled the question", interrupt: true };
}
// answers are keyed by the question text (Claude's AskUserQuestion schema keys answers by question text)
const questions = (input.questions as { question?: string; header?: string }[]) ?? [];
@@ -1,5 +1,6 @@
// Codex app-server notifications → ProviderEvent (§7.3.4). Method and field names follow the generated schema.
import type { ProviderEvent } from "../../timeline/types.js";
import { tr } from "../../util/i18n.js";
const MAX_OUTPUT = 20 * 1024;
const trunc = (s: string, n = 80): string => (s.length > n ? s.slice(0, n - 1) + "…" : s);
@@ -12,10 +13,13 @@ export type CodexMapState = {
currentTurnId: string | null;
filesChanged: number;
diffText: string;
fileChangesByItemId: Map<string, unknown[]>;
/** Raw reasoning text streamed per item (DeepSeek and others send no summary): saved when the item completes (B15) */
reasoningRaw: Map<string, string>;
};
export function newCodexMapState(): CodexMapState {
return { currentTurnId: null, filesChanged: 0, diffText: "" };
return { currentTurnId: null, filesChanged: 0, diffText: "", fileChangesByItemId: new Map(), reasoningRaw: new Map() };
}
// One server notification → 0..n unified events. Server requests (approvals) don't go through here.
@@ -30,6 +34,8 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
if (tid) st.currentTurnId = tid;
st.filesChanged = 0;
st.diffText = "";
st.fileChangesByItemId.clear();
st.reasoningRaw.clear();
break;
}
case "item/agentMessage/delta": {
@@ -46,7 +52,10 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
case "item/reasoning/textDelta": {
const itemId = str(params.itemId) ?? "";
const delta = str(params.delta) ?? "";
if (itemId && delta) out.push({ type: "reasoning_delta", itemId, text: delta });
if (itemId && delta) {
if (method === "item/reasoning/textDelta") st.reasoningRaw.set(itemId, (st.reasoningRaw.get(itemId) ?? "") + delta);
out.push({ type: "reasoning_delta", itemId, text: delta });
}
break;
}
case "item/commandExecution/outputDelta":
@@ -65,14 +74,15 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
const cmd = str(item.command) ?? "";
out.push({
type: "tool_call", itemId, kind: "bash",
title: `运行 ${trunc(cmd)}`, status: "running",
title: tr("tool.run", { x: trunc(cmd) }), status: "running",
detail: { command: cmd, cwd: str(item.cwd) },
});
} else if (type === "fileChange") {
const changes = Array.isArray(item.changes) ? item.changes : [];
if (itemId) st.fileChangesByItemId.set(itemId, changes);
out.push({
type: "tool_call", itemId, kind: "edit",
title: `修改 ${changes.length} 个文件`, status: "running",
title: tr("tool.editFiles", { n: changes.length }), status: "running",
detail: { changes },
});
} else if (type === "mcpToolCall" || type === "dynamicToolCall") {
@@ -85,7 +95,7 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
} else if (type === "webSearch") {
out.push({
type: "tool_call", itemId, kind: "web",
title: `搜索网页 "${trunc(str(item.query) ?? "", 40)}"`, status: "running",
title: tr("tool.webSearch", { x: trunc(str(item.query) ?? "", 40) }), status: "running",
});
}
// agentMessage/reasoning/userMessage/plan etc.: wait for a delta or completed
@@ -100,7 +110,11 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
if (text) out.push({ type: "assistant_message", itemId, text });
} else if (type === "reasoning") {
const summary = Array.isArray(item.summary) ? item.summary : [];
const text = summary.filter((s): s is string => typeof s === "string").join("\n");
const content = Array.isArray(item.content) ? item.content : [];
const strings = (a: unknown[]) => a.filter((s): s is string => typeof s === "string").join("\n");
// The summary when there is one, else the raw reasoning (on the item, or as streamed)
const text = strings(summary) || strings(content) || st.reasoningRaw.get(itemId) || "";
st.reasoningRaw.delete(itemId);
if (text) out.push({ type: "reasoning", itemId, text });
} else if (type === "commandExecution") {
const cmd = str(item.command) ?? "";
@@ -108,7 +122,7 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
const output = str(item.aggregatedOutput) ?? "";
out.push({
type: "tool_call", itemId, kind: "bash",
title: `运行 ${trunc(cmd)}`,
title: tr("tool.run", { x: trunc(cmd) }),
status: exitCode === 0 ? "ok" : "failed",
output: output.length > MAX_OUTPUT ? output.slice(0, MAX_OUTPUT) : output,
exitCode,
@@ -116,11 +130,12 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
});
} else if (type === "fileChange") {
const changes = Array.isArray(item.changes) ? item.changes : [];
if (itemId) st.fileChangesByItemId.set(itemId, changes);
const istatus = str(item.status);
st.filesChanged += changes.length;
out.push({
type: "tool_call", itemId, kind: "edit",
title: `修改 ${changes.length} 个文件`,
title: tr("tool.editFiles", { n: changes.length }),
status: istatus === "failed" ? "failed" : "ok",
detail: { changes },
});
@@ -138,7 +153,7 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
} else if (type === "webSearch") {
out.push({
type: "tool_call", itemId, kind: "web",
title: `搜索网页 "${trunc(str(item.query) ?? "", 40)}"`, status: "ok",
title: tr("tool.webSearch", { x: trunc(str(item.query) ?? "", 40) }), status: "ok",
});
} else if (type === "plan") {
const text = str(item.text) ?? "";
@@ -194,7 +209,7 @@ export function mapNotification(method: string, params: Rec, st: CodexMapState):
break;
}
case "error": {
const msg = str(params.message) ?? "Codex 错误";
const msg = str(params.message) ?? tr("codex.error");
out.push({ type: "notice", level: "error", message: msg });
break;
}
@@ -1,11 +1,17 @@
// Codex Provider (§7.3): detect + listModels (temporary app-server → model/list, cached 10 minutes) + createSession.
import type { Provider, ProviderSession, DetectResult, ModelInfo, Capabilities, HistoryItem } from "../types.js";
import type { Provider, ProviderSession, DetectResult, ModelInfo, Capabilities, HistoryItem, LaunchCommand } from "../types.js";
import type { ProviderEvent } from "../../timeline/types.js";
import { listCodexHistory, readCodexHistory } from "../../history/codex.js";
import { argvFor, resolveBin, killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
import { CodexRpc, CodexProcessExitedError } from "./rpc.js";
import { CodexSession } from "./session.js";
import { log } from "../../log.js";
import { tr } from "../../util/i18n.js";
import { launchArgv, resolveLaunch } from "../launch.js";
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
import { homedir } from "node:os";
import { join } from "node:path";
import { readFile } from "node:fs/promises";
const INSTALL_HINT = "npm i -g @openai/codex";
@@ -18,7 +24,9 @@ export const codexCapabilities: Capabilities = {
questions: true,
cost: false, // tokenUsage yes, cost no
effort: [], // effort values depend on the model — filled from model/list after detect
modes: ["plan", "default", "acceptEdits", "bypassPermissions"],
// No "plan": app-server 0.16x has no plan/collaboration mode on turn/start, and a read-only "plan" was the same preset as default (B9)
modes: ["default", "acceptEdits", "bypassPermissions"],
modeLabels: { default: "Read Only", acceptEdits: "Auto", bypassPermissions: "Full Access" },
};
let modelCache: { at: number; models: ModelInfo[] } | null = null;
@@ -55,8 +63,8 @@ export function normalizeEfforts(raw: unknown[] | undefined): string[] {
return out;
}
async function fetchModels(r: ResolveResult & { ok: true }, cwd: string): Promise<ModelInfo[]> {
const rpc = new CodexRpc(argvFor(r, ["app-server"]), { cwd });
async function fetchModels(r: ResolveResult & { ok: true }, cwd: string, launch?: LaunchCommand): Promise<ModelInfo[]> {
const rpc = new CodexRpc(argvFor(r, launchArgv(["app-server"], launch)), { cwd });
try {
await rpc.request("initialize", {
clientInfo: { name: "agent-console", title: "Agent Console", version: "0" },
@@ -94,40 +102,97 @@ async function fetchModels(r: ResolveResult & { ok: true }, cwd: string): Promis
}
}
export type CodexConfig = { modelProvider: string | null; model: string | null; providerModels: string[] };
function tomlValue(raw: string): string | string[] | null {
const v = raw.trim().replace(/\s+#.*$/, "");
const quoted = v.match(/^"([\s\S]*)"$/) ?? v.match(/^'([\s\S]*)'$/);
if (quoted) return quoted[1];
if (v.startsWith("[") && v.endsWith("]")) {
return v.slice(1, -1).split(",").map((x) => tomlValue(x)).filter((x): x is string => typeof x === "string");
}
return null;
}
export function parseCodexConfig(text: string): CodexConfig {
let section = "";
const values = new Map<string, string | string[]>();
for (const line of text.split(/\r?\n/)) {
const s = line.trim();
if (!s || s.startsWith("#")) continue;
const header = s.match(/^\[([^\]]+)\]$/);
if (header) { section = header[1]; continue; }
const m = s.match(/^([A-Za-z0-9_.-]+)\s*=\s*(.+)$/);
if (!m) continue;
const value = tomlValue(m[2]);
if (typeof value === "string" || Array.isArray(value)) values.set(`${section}\0${m[1]}`, value);
}
const top = (key: string) => values.get(`\0${key}`);
const profile = top("profile");
const profileName = typeof profile === "string" ? profile : null;
const profileValue = (key: string) => profileName ? values.get(`profiles.${profileName}\0${key}`) : undefined;
const modelProvider = (profileValue("model_provider") ?? top("model_provider"));
const model = (profileValue("model") ?? top("model"));
const provider = typeof modelProvider === "string" ? modelProvider : null;
const models = new Set<string>();
if (typeof model === "string" && model) models.add(model);
for (const [key, value] of values) {
if (provider && key === `model_providers.${provider}\0models` && Array.isArray(value)) {
for (const m of value) models.add(m);
}
}
return { modelProvider: provider, model: typeof model === "string" ? model : null, providerModels: [...models] };
}
async function readCodexConfig(): Promise<CodexConfig> {
const home = process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");
const file = home.toLowerCase().endsWith(".toml") ? home : join(home, "config.toml");
try { return parseCodexConfig(await readFile(file, "utf8")); } catch { return { modelProvider: null, model: null, providerModels: [] }; }
}
function isChatGptProvider(id: string | null): boolean {
return !id || /^(openai|chatgpt)$/i.test(id);
}
export function createCodexProvider(version: string): Provider {
return {
id: "codex",
name: "Codex",
capabilities: codexCapabilities,
async detect(): Promise<DetectResult> {
const bin = await resolveBin("codex");
async detect(launch?: LaunchCommand): Promise<DetectResult> {
const bin = launch ? await resolveLaunch(launch) : await resolveBin("codex");
if (!bin.ok) {
return { available: false, reason: bin.reason, installHint: INSTALL_HINT };
}
try {
const v = await runVersion(bin, ["--version"]);
const v = await runVersion(bin, [...(launch?.prefixArgs ?? []), "--version"]);
return { available: true, bin: bin.display, version: v.trim().split("\n")[0] || "" };
} catch (e) {
return { available: true, bin: bin.display, version: "", reason: String(e) };
}
},
async listModels(): Promise<ModelInfo[]> {
if (modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;
const bin = await resolveBin("codex");
if (!bin.ok) return [{ id: "", name: "默认" }];
async listModels(launch?: LaunchCommand): Promise<ModelInfo[]> {
const config = await readCodexConfig();
if (!isChatGptProvider(config.modelProvider)) {
const rows = config.providerModels.map((id, i) => ({ id, name: id, isDefault: i === 0 }));
return rows.length ? rows : [{ id: "", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }];
}
if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;
const bin = launch ? await resolveLaunch(launch) : await resolveBin("codex");
if (!bin.ok) return [{ id: "", name: PLACEHOLDER_MODEL_NAME }];
try {
const models = await fetchModels(bin, process.cwd());
const models = await fetchModels(bin, process.cwd(), launch);
modelCache = { at: Date.now(), models };
return models;
} catch (e) {
// Gateway region errors etc. — the frontend shows a single "Default" entry (§7.3.6)
log("warn", "codex model/list 失败", { err: String(e) });
return [{ id: "", name: "默认" }];
return [{ id: "", name: PLACEHOLDER_MODEL_NAME }];
}
},
async createSession(o): Promise<ProviderSession> {
const bin = await resolveBin("codex");
if (!bin.ok) throw new Error(`找不到 codex:${bin.reason}`);
const bin = o.launch ? await resolveLaunch(o.launch) : await resolveBin("codex");
if (!bin.ok) throw new Error(tr("codex.notFound", { detail: bin.reason, hint: INSTALL_HINT }));
return new CodexSession({
threadId: o.threadId,
cwd: o.cwd,
@@ -139,6 +204,7 @@ export function createCodexProvider(version: string): Provider {
binPrefixArgs: bin.prefixArgs,
binVia: bin.via,
binShim: bin.shim,
launch: o.launch,
version,
});
},
@@ -1,5 +1,5 @@
// Codex ProviderSession (§7.3.3/7.3.5): codex app-server JSON-RPC session.
import type { ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
import { buildCodexInput } from "./input.js";
import { tr } from "../../util/i18n.js";
import type { ProviderEvent } from "../../timeline/types.js";
@@ -14,6 +14,7 @@ import {
type CodexSlashEntry,
} from "./commands.js";
import { log } from "../../log.js";
import { launchArgv } from "../launch.js";
const rid = () => Math.random().toString(36).slice(2, 10);
@@ -60,6 +61,7 @@ export class CodexSession implements ProviderSession {
binVia?: string;
binShim?: string;
version: string;
launch?: LaunchCommand;
},
) {
this.events = this.q;
@@ -85,7 +87,7 @@ export class CodexSession implements ProviderSession {
const rpc = new CodexRpc(
argvFor(
{ ok: true, cmd: this.o.binCmd, prefixArgs: this.o.binPrefixArgs, display: this.o.binCmd, via: this.o.binVia ?? "path", shim: this.o.binShim },
["app-server"],
launchArgv(["app-server"], this.o.launch),
),
{ cwd: this.o.cwd },
);
@@ -148,7 +150,7 @@ export class CodexSession implements ProviderSession {
}
async send(input: SendInput): Promise<void> {
if (this.closed) throw new Error("会话已关闭");
if (this.closed) throw new Error(tr("codex.closed"));
await this.start();
const rpc = this.rpc!;
const preset = MODE_PRESETS[this.o.mode];
@@ -191,7 +193,7 @@ export class CodexSession implements ProviderSession {
async steer(input: SendInput): Promise<void> {
// No Codex turnId yet (turn/started hasn't arrived) → throw; the manager queues instead so the message isn't lost
if (!this.rpc || !this.st.currentTurnId) throw new Error("当前轮次还没开始,无法插话");
if (!this.rpc || !this.st.currentTurnId) throw new Error(tr("codex.noTurnSteer"));
const { items, warnings } = await buildCodexInput(input.text, input.images ?? []);
for (const w of warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
try {
@@ -243,13 +245,13 @@ export class CodexSession implements ProviderSession {
this.emit({
type: "permission_request",
requestId,
title: `运行 ${command.slice(0, 80)}`,
title: tr("tool.run", { x: command.slice(0, 80) }),
kind: "tool",
detail: { command, cwd: params.cwd, reason: params.reason, approvalId: params.approvalId, itemId: params.itemId },
options: [
{ id: "accept", label: "允许", kind: "allow_once" },
{ id: "acceptForSession", label: "本对话都允许", kind: "allow_always" },
{ id: "decline", label: "拒绝", kind: "reject_once" },
{ id: "accept", label: tr("perm.allow"), kind: "allow_once" },
{ id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" },
{ id: "decline", label: tr("perm.deny"), kind: "reject_once" },
],
});
const a = await this.waitFor(requestId);
@@ -258,18 +260,21 @@ export class CodexSession implements ProviderSession {
return { decision: opt };
}
case "item/fileChange/requestApproval": {
const changes = Array.isArray(params.changes) ? params.changes : [];
const itemId = typeof params.itemId === "string" ? params.itemId : "";
const changes = Array.isArray(params.changes) && params.changes.length
? params.changes
: (itemId ? this.st.fileChangesByItemId.get(itemId) ?? [] : []);
const requestId = "perm_" + rid();
this.emit({
type: "permission_request",
requestId,
title: "修改文件",
title: tr("perm.editFiles"),
kind: "tool",
detail: { changes, approvalId: params.approvalId, itemId: params.itemId, reason: params.reason },
options: [
{ id: "accept", label: "允许", kind: "allow_once" },
{ id: "acceptForSession", label: "本对话都允许", kind: "allow_always" },
{ id: "decline", label: "拒绝", kind: "reject_once" },
{ id: "accept", label: tr("perm.allow"), kind: "allow_once" },
{ id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" },
{ id: "decline", label: tr("perm.deny"), kind: "reject_once" },
],
});
const a = await this.waitFor(requestId);
@@ -1,7 +1,11 @@
// In-memory cache of Provider detection results and model lists.
// detect / listModels often have to start a CLI (seconds); without a cache every page open and model pick would wait.
import type { Provider, DetectResult, ModelInfo } from "./types.js";
import type { Provider, DetectResult, ModelInfo, LaunchCommand } from "./types.js";
import { PLACEHOLDER_MODEL_NAME } from "./types.js";
import { withMagpie } from "./magpieGateway.js";
import { launchKey } from "./launch.js";
import { tr } from "../util/i18n.js";
const DETECT_MS = 60 * 1000;
const MODELS_MS = 10 * 60 * 1000;
@@ -24,41 +28,48 @@ function fresh<T>(e: Entry<T>, ttl: number): e is { at: number; value: T } {
return !!e && Date.now() - e.at < ttl;
}
export async function cachedDetect(p: Provider): Promise<DetectResult> {
const hit = detects.get(p.id);
function cacheKey(p: Provider, launch?: LaunchCommand): string {
return launch ? `${p.id}\0${launchKey(launch)}` : p.id;
}
export async function cachedDetect(p: Provider, launch?: LaunchCommand): Promise<DetectResult> {
const key = cacheKey(p, launch);
const hit = detects.get(key);
if (fresh(hit, DETECT_MS)) return hit.value;
let job = inflightDetect.get(p.id);
let job = inflightDetect.get(key);
if (!job) {
const timedOut: DetectResult = { available: false, reason: tr("provider.timeout") };
job = withTimeout(
p.detect().catch((e): DetectResult => ({ available: false, reason: String((e as Error)?.message ?? e) })),
p.detect(launch).catch((e): DetectResult => ({ available: false, reason: String((e as Error)?.message ?? e) })),
STEP_TIMEOUT_MS,
{ available: false, reason: "检测超时" },
timedOut,
).then((v) => {
// Don't cache a timeout; try again next time
if (v.reason !== "检测超时") detects.set(p.id, { at: Date.now(), value: v });
if (v !== timedOut) detects.set(key, { at: Date.now(), value: v });
return v;
}).finally(() => inflightDetect.delete(p.id));
inflightDetect.set(p.id, job);
}).finally(() => inflightDetect.delete(key));
inflightDetect.set(key, job);
}
return job;
}
export async function cachedModels(p: Provider): Promise<ModelInfo[]> {
const hit = models.get(p.id);
export async function cachedModels(p: Provider, launch?: LaunchCommand): Promise<ModelInfo[]> {
const key = cacheKey(p, launch);
const hit = models.get(key);
if (fresh(hit, MODELS_MS)) return hit.value;
let job = inflightModels.get(p.id);
let job = inflightModels.get(key);
if (!job) {
job = withTimeout<ModelInfo[] | null>(p.listModels().catch(() => []), MODELS_TIMEOUT_MS, null)
job = withTimeout<ModelInfo[] | null>(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null)
.then(async (v) => {
// Timeout: don't cache, fall back to the old value for now
if (v === null) return models.get(p.id)?.value ?? [];
if (v === null) return models.get(key)?.value ?? [];
// Agents behind the magpie gateway: fill in gateway models, the default model and thinking levels
const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v));
models.set(p.id, { at: Date.now(), value: list });
models.set(key, { at: Date.now(), value: list });
return list;
})
.finally(() => inflightModels.delete(p.id));
inflightModels.set(p.id, job);
.finally(() => inflightModels.delete(key));
inflightModels.set(key, job);
}
return job;
}
@@ -66,7 +77,7 @@ export async function cachedModels(p: Provider): Promise<ModelInfo[]> {
/** A list holding only our own "Default" placeholder (id=default, name "默认") counts as having no real models.
* An auto / Auto the Agent itself reports (e.g. Copilot) is a real option and is kept. */
export function dropPlaceholder(list: ModelInfo[]): ModelInfo[] {
if (list.length === 1 && list[0].id === "default" && list[0].name === "默认") return [];
if (list.length === 1 && list[0].id === "default" && (list[0].name === "默认" || list[0].name === PLACEHOLDER_MODEL_NAME)) return [];
return list;
}
@@ -77,8 +88,9 @@ export function peekModels(id: string): ModelInfo[] | undefined {
export function clearProviderCache(id?: string): void {
if (id) {
detects.delete(id);
models.delete(id);
for (const m of [detects, models] as Map<string, unknown>[]) {
for (const k of [...m.keys()]) if (k === id || k.startsWith(id + "\0")) m.delete(k);
}
} else {
detects.clear();
models.clear();
@@ -0,0 +1,31 @@
// Settings › Launch command: a custom executable for an Agent plus extra arguments.
// The arguments the user types are APPENDED after the built-in ones (e.g. `opencode acp --foo`, `codex app-server --foo`,
// `claude <stream-json flags> --foo`). prefixArgs is internal (tests run `node fixture.mjs`) and goes before the built-ins.
import type { LaunchCommand } from "./types.js";
import type { Settings } from "../store/settings.js";
import { resolveBin, type ResolveResult } from "../util/bin.js";
import { tr } from "../util/i18n.js";
export function launchFromSettings(settings: Settings, providerId: string): LaunchCommand | undefined {
const c = settings.providerCommand?.[providerId];
const cmd = typeof c?.executable === "string" ? c.executable.trim() : "";
if (!cmd) return undefined;
const args = Array.isArray(c?.args) ? c!.args.filter((a): a is string => typeof a === "string") : [];
return { cmd, args };
}
/** Built-in arguments wrapped with the launch command's internal prefix and the user's extra arguments. */
export function launchArgv(builtin: string[], launch?: LaunchCommand): string[] {
return [...(launch?.prefixArgs ?? []), ...builtin, ...(launch?.args ?? [])];
}
/** Resolve a custom executable (absolute path or a name on PATH; Windows .cmd/.ps1 shims are handled by resolveBin). */
export async function resolveLaunch(launch: LaunchCommand): Promise<ResolveResult> {
const r = await resolveBin(launch.cmd);
if (r.ok) return r;
return { ok: false, reason: tr("launch.notFound", { cmd: launch.cmd }) };
}
export function launchKey(launch?: LaunchCommand): string {
return launch ? `${launch.cmd}\0${(launch.prefixArgs ?? []).join("\0")}\0\0${(launch.args ?? []).join("\0")}` : "";
}
@@ -1,5 +1,6 @@
// MockProvider: registered only with AGENT_CONSOLE_MOCK=1. Persistent session, interruptible, with permissions and steering.
// Scripts by message prefix: default /perm /plan /ask /slow /error /long /exit; supports steer/interrupt/resume.
import { tr } from "../util/i18n.js";
import type { Provider, ProviderSession, DetectResult, ModelInfo,
Mode, SendInput, RespondAnswer, SlashCommand,
} from "./types.js";
@@ -259,9 +260,9 @@ async function scriptPerm(ctx: Ctx): Promise<void> {
kind: "tool",
detail: { command: "npm test", cwd: ".", toolName: "Bash" },
options: [
{ id: "accept", label: "允许", kind: "allow_once" },
{ id: "acceptForSession", label: "本对话都允许", kind: "allow_always" },
{ id: "decline", label: "拒绝", kind: "reject_once" },
{ id: "accept", label: tr("perm.allow"), kind: "allow_once" },
{ id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" },
{ id: "decline", label: tr("perm.deny"), kind: "reject_once" },
],
});
const ans = await ctx.waitFor(requestId);
@@ -297,7 +298,7 @@ async function scriptPlan(ctx: Ctx): Promise<void> {
detail: { markdown: "见上方计划" },
options: [
{ id: "implement", label: "开始实施", kind: "allow_once" },
{ id: "reject", label: "拒绝", kind: "reject_once" },
{ id: "reject", label: tr("perm.deny"), kind: "reject_once" },
],
});
const ans = await ctx.waitFor(requestId);
@@ -0,0 +1,8 @@
import type { Mode } from "./types.js";
/** Map a permission mode onto an Agent's modes: kept when it has it, else that Agent's "default", else its first mode. */
export function clampMode(modes: Mode[], mode: Mode | null | undefined): Mode {
if (mode && modes.includes(mode)) return mode;
if (modes.includes("default")) return "default";
return modes[0] ?? "default";
}
@@ -3,6 +3,7 @@ import { resolveBin } from "../util/bin.js";
import type { Provider, DetectResult, ModelInfo, ProviderSession } from "./types.js";
import type { ProviderCatalogEntry } from "./catalog.js";
import type { Capabilities } from "./types.js";
import { tr } from "../util/i18n.js";
const stubCapabilities: Capabilities = {
resume: false,
@@ -18,7 +19,7 @@ const stubCapabilities: Capabilities = {
function notReadySession(): ProviderSession {
const err = () => {
throw new Error("该 Agent 尚未在 Agent Console 接入,敬请期待");
throw new Error(tr("stub.planned"));
};
return {
events: (async function* () {})(),
@@ -45,17 +46,17 @@ export function createStubProvider(entry: ProviderCatalogEntry): Provider {
return {
available: true,
bin: r.display,
reason: entry.status === "verified" ? undefined : "已检测到 CLI,会话驱动尚未完全验证",
reason: entry.status === "verified" ? undefined : tr("stub.unverified"),
};
}
}
return { available: false, reason: `未找到 ${entry.bins[0]}`, installHint: entry.installHint };
return { available: false, reason: tr("stub.notFound", { bin: entry.bins[0] }), installHint: entry.installHint };
},
async listModels(): Promise<ModelInfo[]> {
return [];
},
async createSession() {
if (entry.status === "planned") throw new Error("该 Agent 尚未在 Agent Console 接入,敬请期待");
if (entry.status === "planned") throw new Error(tr("stub.planned"));
return notReadySession();
},
};
@@ -19,6 +19,8 @@ export type Capabilities = {
modes: Mode[];
/** Each mode's name in this Agent (like Paseo, show the Agent's own naming); our default names are used when absent */
modeLabels?: Partial<Record<Mode, string>>;
/** The Agent only streams text deltas and never sends the complete message (ACP): the manager saves each text segment itself */
deltasOnly?: boolean;
};
export type ThinkingOption = { id: string; label: string };
@@ -35,6 +37,8 @@ export type ModelInfo = {
thinkingParam?: string;
};
export type DetectResult = { available: boolean; bin?: string; version?: string; reason?: string; installHint?: string };
/** Custom launch (Settings › Launch command). args are appended after the built-in arguments; prefixArgs (internal) go before them. */
export type LaunchCommand = { cmd: string; prefixArgs?: string[]; args?: string[] };
export type HistoryItem = { provider: string; sessionId: string; title: string; updatedAt: number; messageCount: number; imported: boolean };
export type SendInput = { text: string; images: { path: string; mime: string }[] };
export type RespondAnswer = { optionId?: string; answers?: Record<string, string>; cancelled?: boolean };
@@ -43,8 +47,8 @@ export interface Provider {
id: string;
name: string;
capabilities: Capabilities;
detect(): Promise<DetectResult>;
listModels(): Promise<ModelInfo[]>;
detect(launch?: LaunchCommand): Promise<DetectResult>;
listModels(launch?: LaunchCommand): Promise<ModelInfo[]>;
createSession(o: {
threadId: string;
cwd: string;
@@ -54,7 +58,7 @@ export interface Provider {
resumeId: string | null;
cursorFast?: boolean;
cursorAutoReview?: boolean;
launch?: { cmd: string; prefixArgs: string[] };
launch?: LaunchCommand;
}): Promise<ProviderSession>;
listHistory?(cwd: string): Promise<HistoryItem[]>;
readHistory?(sessionId: string, cwd: string): Promise<ProviderEvent[]>;
@@ -74,3 +78,6 @@ export interface ProviderSession {
}
export type { SlashCommand, SlashCommandKind } from "./slash.js";
/** Name of our own "Default" placeholder model row (id "default") */
export const PLACEHOLDER_MODEL_NAME = "Default";
@@ -1,19 +1,17 @@
// settings.json: defaults per EXEC §5.6; unknown fields are preserved on read.
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { z } from "zod";
import { writeJsonAtomic } from "../util/atomic.js";
export type Settings = {
defaultProvider: string;
defaultMode: "plan" | "default" | "acceptEdits" | "bypassPermissions" | "ask";
defaultEffort: string | null;
sendKey: "enter" | "ctrlEnter";
runningSend: "queue" | "steer";
showThinking: boolean;
density: "comfortable" | "compact";
theme: "auto" | "light" | "dark";
idleCloseMinutes: number;
idleExitMinutes: number;
collapsedProjects: string[];
panel: { open: boolean; tab: string; width: number };
sidebarWidth: number;
@@ -31,14 +29,11 @@ export type Settings = {
export const DEFAULT_SETTINGS: Settings = {
defaultProvider: "claude",
defaultMode: "default",
defaultEffort: null,
sendKey: "enter",
runningSend: "queue",
showThinking: true,
density: "comfortable",
theme: "auto",
idleCloseMinutes: 30,
idleExitMinutes: 60,
collapsedProjects: [],
panel: { open: false, tab: "changes", width: 440 },
sidebarWidth: 248,
@@ -47,6 +42,69 @@ export const DEFAULT_SETTINGS: Settings = {
recentDirs: [],
};
export const IDLE_CLOSE_MIN = 5;
export const IDLE_CLOSE_MAX = 240;
const mode = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]);
const id = z.string().min(1).max(200);
/** B18: what settings.set accepts. Every key the UI writes is listed; anything else or a wrong type is refused. */
export const settingsPatchSchema = z
.object({
defaultProvider: z.string().min(1).max(64),
defaultMode: mode,
sendKey: z.enum(["enter", "ctrlEnter"]),
runningSend: z.enum(["queue", "steer"]),
showThinking: z.boolean(),
// auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it
theme: z.enum(["auto", "light", "dark"]),
idleCloseMinutes: z.number().int().min(IDLE_CLOSE_MIN).max(IDLE_CLOSE_MAX),
collapsedProjects: z.array(id).max(1000),
panel: z.object({ open: z.boolean(), tab: z.string().max(40), width: z.number().min(0).max(5000) }).partial(),
sidebarWidth: z.number().min(0).max(5000),
lastProjectId: id.nullable(),
lastThreadId: id.nullable(),
recentDirs: z.array(z.string().max(4096)).max(50),
providerEnabled: z.record(z.string().max(64), z.boolean()),
providerCommand: z.record(
z.string().max(64),
z.object({ executable: z.string().max(4096).optional(), args: z.array(z.string().max(4096)).max(64).optional() }).strict(),
),
v1Migrated: z.boolean(),
})
.partial()
.strict();
export type SettingsPatch = z.infer<typeof settingsPatchSchema>;
/** Validate a patch from the page; returns the parsed patch or a readable error. */
export function parseSettingsPatch(patch: unknown): { ok: true; patch: SettingsPatch } | { ok: false; error: string } {
const r = settingsPatchSchema.safeParse(patch);
if (r.success) return { ok: true, patch: r.data };
return {
ok: false,
error: r.error.issues.map((i) => `${i.path.join(".") || "(patch)"}: ${i.message}`).join("; "),
};
}
/** Values in settings.json that have the wrong type (hand edits, older builds) fall back to the default; unknown keys are kept. */
export function sanitizeStored(raw: Record<string, unknown>): Record<string, unknown> {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const shape = settingsPatchSchema.shape as Record<string, z.ZodType>;
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(raw)) {
const field = shape[k];
if (field && k !== "idleCloseMinutes" && !field.safeParse(v).success) continue;
if (k === "idleCloseMinutes") {
const n = Number(v);
if (!Number.isFinite(n)) continue;
out[k] = Math.min(IDLE_CLOSE_MAX, Math.max(IDLE_CLOSE_MIN, Math.round(n)));
continue;
}
out[k] = v;
}
return out;
}
export class SettingsStore {
private file: string;
private cache: Settings | null = null;
@@ -60,6 +118,7 @@ export class SettingsStore {
try {
raw = JSON.parse(await readFile(this.file, "utf8"));
} catch {}
raw = sanitizeStored(raw);
this.cache = { ...DEFAULT_SETTINGS, ...raw, panel: { ...DEFAULT_SETTINGS.panel, ...(raw.panel as object | undefined) } };
return this.cache;
}
@@ -10,6 +10,7 @@ import { StringDecoder } from "node:string_decoder";
import { findOnPath } from "../../../lib/pathscan.mjs";
import type { Gateway } from "../ws/gateway.js";
import { log } from "../log.js";
import { tr } from "../util/i18n.js";
type Pty = {
write(data: string): void;
@@ -144,10 +145,10 @@ export class TerminalService {
async create(projectId: string, cwd: string, cols: number, rows: number): Promise<{ id: string; index: number; simple: boolean } | { error: string }> {
const alive = [...this.terms.values()].filter((t) => t.projectId === projectId && t.alive);
if (alive.length >= MAX_TERMS_PER_PROJECT) return { error: `每个项目最多 ${MAX_TERMS_PER_PROJECT} 个终端` };
if (alive.length >= MAX_TERMS_PER_PROJECT) return { error: tr("term.max", { n: MAX_TERMS_PER_PROJECT }) };
const shell = pickShell();
const term: Term = {
id: rid(), index: nextIndex++, projectId, cwd, title: `终端 ${alive.length + 1}`,
id: rid(), index: nextIndex++, projectId, cwd, title: tr("term.title", { n: alive.length + 1 }),
alive: true, simple: false, pty: null, proc: null, buf: "", pend: "", timer: null,
};
const pty = await this.loadPty();
@@ -194,7 +195,7 @@ export class TerminalService {
error?: string;
} {
const t = this.terms.get(id);
if (!t) return { error: "终端不存在" };
if (!t) return { error: tr("err.terminalMissing") };
// Last 5000 lines
const lines = t.buf.split("\n");
const snapshot = lines.length > SNAP_LINES ? lines.slice(-SNAP_LINES).join("\n") : t.buf;
@@ -6,6 +6,7 @@ import { findOnPath, findNode as findNodeOnPath, isNodeExecutable } from "../../
import { readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { tr } from "./i18n.js";
const IS_WIN = process.platform === "win32";
const cache = new Map<string, { out: ResolveResult; at: number }>();
@@ -161,7 +162,7 @@ export async function resolveFirstBin(names: string[]): Promise<ResolvedBin | Re
if (r.ok) return { ...r, binName };
}
const label = uniq[0] ?? "cli";
return { ok: false, reason: `PATH 里找不到 ${uniq.length > 1 ? uniq.join(" 或 ") : label}` };
return { ok: false, reason: tr("bin.notOnPath", { name: uniq.length > 1 ? uniq.join(tr("bin.or")) : label }) };
}
export function clearBinCache(name?: string): void {
@@ -189,7 +190,7 @@ export async function resolveBinWith(name: string, deps: ResolveDeps = {}): Prom
const P = win ? path.win32 : path.posix;
const exists = deps.exists ?? existsSync;
const hits = (deps.find ?? which)(name);
if (!hits.length) return { ok: false, reason: `PATH 里找不到 ${name}` };
if (!hits.length) return { ok: false, reason: tr("bin.notOnPath", { name }) };
// Take the first hit in PATH order (same as typing the command in a terminal; within one directory on Windows, PATHEXT order)
const first = hits[0];
if (!win) return { ok: true, cmd: first, prefixArgs: [], display: first, via: "path" };
@@ -42,6 +42,92 @@ const dict: Record<AppLocale, Record<string, string>> = {
"claude.notRunning": "claude 没有在运行,消息未发出",
"claude.closed": "会话已关闭",
"export.defaultModel": "默认",
"bin.notOnPath": "PATH 里找不到 {name}",
"bin.or": " 或 ",
"launch.notFound": "找不到自定义的可执行文件:{cmd}(请填写绝对路径,或 PATH 里能找到的命令名)",
"codex.notFound": "找不到 codex({detail})。请先安装:{hint}",
"provider.disabled": "已在设置中禁用",
"provider.planned": "尚未接入",
"provider.disabledNamed": "{name} 已在设置中禁用",
"provider.plannedNamed": "{name} 尚未接入,暂不能新建对话",
"provider.unavailable": "{name} 未安装或不可用",
"provider.unknown": "未知 Agent:{id}",
"provider.timeout": "检测超时",
"err.projectMissing": "项目不存在",
"err.threadMissing": "对话不存在",
"err.dirMissing": "目录不存在或不是文件夹",
"err.projectDirGone": "项目目录已不存在",
"err.terminalMissing": "终端不存在",
"err.noManager": "会话管理器未启动",
"err.badParams": "参数不对:{detail}",
"export.me": "我",
"export.steered": "(插话)",
"export.reasoning": "思考",
"export.plan": "计划",
"export.todo": "待办",
"err.requestGone": "授权/提问不存在或已回应",
"err.badOption": "optionId 非法:{id}",
"err.cursorOnly": "仅 Cursor 对话支持该选项",
"err.busySwitch": "对话运行中,不能更换 Agent",
"err.hasMessages": "已有消息,不能更换 Agent",
"tool.read": "读取 {x}",
"tool.edit": "编辑 {x}",
"tool.multiEdit": "编辑 {x}({n} 处)",
"tool.overwrite": "覆盖 {x}",
"tool.create": "新建 {x}",
"tool.notebook": "编辑笔记本 {x}",
"tool.run": "运行 {x}",
"tool.output": "查看输出 {x}",
"tool.kill": "结束进程 {x}",
"tool.grep": "搜索 \"{x}\"",
"tool.glob": "查找 {x}",
"tool.fetch": "打开 {x}",
"tool.webSearch": "搜索网页 \"{x}\"",
"tool.todo": "更新待办({done}/{n})",
"tool.task": "子任务:{x}",
"tool.generic": "工具",
"tool.editFiles": "修改 {n} 个文件",
"tool.needsApproval": "需要授权",
"perm.editFiles": "修改文件",
"perm.allow": "允许",
"perm.allowSession": "本对话都允许",
"perm.deny": "拒绝",
"perm.plan": "Agent 提交了计划",
"perm.implement": "实施",
"http.internal": "服务内部错误",
"http.badOrigin": "来源不允许",
"http.badPreflight": "预检不允许",
"http.badToken": "令牌无效",
"http.noAttachment": "附件不存在",
"http.method": "方法不允许",
"http.noApp": "app 还没构建(缺 app/index.html)",
"http.badPath": "路径不合法",
"http.pathDenied": "路径不允许",
"http.noFile": "文件不存在",
"http.badType": "不支持的文件类型",
"http.tooLarge": "文件太大(上限 50MB)",
"http.noRoute": "接口不存在",
"codex.error": "Codex 错误",
"codex.closed": "会话已关闭",
"codex.noTurnSteer": "当前轮次还没开始,无法插话",
"acp.exited": "{name} 进程退出 ({code})",
"notice.apiRetry": "API 重试中(第 {n} 次)",
"notice.compacted": "上下文已压缩",
"term.max": "每个项目最多 {n} 个终端",
"term.title": "终端 {n}",
"stub.planned": "该 Agent 尚未在 Agent Console 接入,敬请期待",
"stub.unverified": "已检测到 CLI,会话驱动尚未完全验证",
"stub.notFound": "未找到 {bin}",
"history.untitled": "(无标题)",
"history.toolCall": "(历史)调用 {name}",
"fs.pathDenied": "路径不允许",
"fs.dirMissing": "目录不存在",
"fs.dirUnreadable": "无法读取目录",
"fs.fileMissing": "文件不存在",
"fs.notFile": "不是文件",
"fs.unreadable": "无法读取",
"git.missing": "找不到 git(请先安装 git 并加入 PATH)",
"git.binary": "二进制或无法读取",
},
en: {
"thread.defaultTitle": "New chat",
@@ -62,6 +148,92 @@ const dict: Record<AppLocale, Record<string, string>> = {
"claude.notRunning": "claude is not running; the message was not sent",
"claude.closed": "The session is closed",
"export.defaultModel": "Default",
"bin.notOnPath": "{name} was not found on PATH",
"bin.or": " or ",
"launch.notFound": "Custom executable not found: {cmd} (use an absolute path or a command name on PATH)",
"codex.notFound": "codex was not found ({detail}). Install it first: {hint}",
"provider.disabled": "Disabled in Settings",
"provider.planned": "Not supported yet",
"provider.disabledNamed": "{name} is disabled in Settings",
"provider.plannedNamed": "{name} is not supported yet; it can't start new conversations",
"provider.unavailable": "{name} is not installed or not available",
"provider.unknown": "Unknown agent: {id}",
"provider.timeout": "Detection timed out",
"err.projectMissing": "Project not found",
"err.threadMissing": "Conversation not found",
"err.dirMissing": "The folder does not exist or is not a folder",
"err.projectDirGone": "The project folder no longer exists",
"err.terminalMissing": "Terminal not found",
"err.noManager": "The session manager is not running",
"err.badParams": "Invalid parameters: {detail}",
"export.me": "Me",
"export.steered": " (steer)",
"export.reasoning": "Reasoning",
"export.plan": "Plan",
"export.todo": "Todos",
"err.requestGone": "That approval or question no longer exists or was already answered",
"err.badOption": "Invalid optionId: {id}",
"err.cursorOnly": "Only Cursor conversations support this option",
"err.busySwitch": "The conversation is running; the agent can't be changed",
"err.hasMessages": "The conversation already has messages; the agent can't be changed",
"tool.read": "Read {x}",
"tool.edit": "Edit {x}",
"tool.multiEdit": "Edit {x} ({n} edits)",
"tool.overwrite": "Overwrite {x}",
"tool.create": "Create {x}",
"tool.notebook": "Edit notebook {x}",
"tool.run": "Run {x}",
"tool.output": "Read output {x}",
"tool.kill": "Stop process {x}",
"tool.grep": "Search \"{x}\"",
"tool.glob": "Find {x}",
"tool.fetch": "Open {x}",
"tool.webSearch": "Web search \"{x}\"",
"tool.todo": "Update todos ({done}/{n})",
"tool.task": "Subtask: {x}",
"tool.generic": "Tool",
"tool.editFiles": "Edit {n} file(s)",
"tool.needsApproval": "Needs approval",
"perm.editFiles": "Edit files",
"perm.allow": "Allow",
"perm.allowSession": "Allow for this chat",
"perm.deny": "Deny",
"perm.plan": "The agent proposed a plan",
"perm.implement": "Implement",
"http.internal": "Internal error",
"http.badOrigin": "Origin not allowed",
"http.badPreflight": "Preflight not allowed",
"http.badToken": "Invalid token",
"http.noAttachment": "Attachment not found",
"http.method": "Method not allowed",
"http.noApp": "The app is not built (app/index.html is missing)",
"http.badPath": "Invalid path",
"http.pathDenied": "Path not allowed",
"http.noFile": "File not found",
"http.badType": "Unsupported file type",
"http.tooLarge": "File too large (50 MB max)",
"http.noRoute": "No such endpoint",
"codex.error": "Codex error",
"codex.closed": "The session is closed",
"codex.noTurnSteer": "The turn hasn't started yet; can't steer",
"acp.exited": "{name} exited ({code})",
"notice.apiRetry": "Retrying the API (attempt {n})",
"notice.compacted": "Context compacted",
"term.max": "At most {n} terminals per project",
"term.title": "Terminal {n}",
"stub.planned": "This agent isn't supported in Agent Console yet",
"stub.unverified": "CLI found; its session driver isn't fully verified yet",
"stub.notFound": "{bin} was not found",
"history.untitled": "(untitled)",
"history.toolCall": "(history) called {name}",
"fs.pathDenied": "Path not allowed",
"fs.dirMissing": "Folder not found",
"fs.dirUnreadable": "Can't read the folder",
"fs.fileMissing": "File not found",
"fs.notFile": "Not a file",
"fs.unreadable": "Can't read the file",
"git.missing": "git was not found (install git and add it to PATH)",
"git.binary": "Binary or unreadable",
},
};
+68 -37
View File
@@ -2,7 +2,8 @@
import { z } from "zod";
import type { Gateway, ConnCtx } from "./gateway.js";
import type { Config } from "../config.js";
import type { SettingsStore } from "../store/settings.js";
import type { SettingsStore, Settings } from "../store/settings.js";
import { parseSettingsPatch } from "../store/settings.js";
import type { ProjectsStore } from "../store/projects.js";
import type { ThreadsStore } from "../store/threads.js";
import { listProviders, getProvider } from "../providers/registry.js";
@@ -20,6 +21,9 @@ import { execFile } from "node:child_process";
import { pickFolder } from "../util/pickFolder.js";
import { clearBinCache } from "../util/bin.js";
import { cachedDetect, cachedModels, clearProviderCache } from "../providers/infoCache.js";
import { launchFromSettings } from "../providers/launch.js";
import { clampMode } from "../providers/modes.js";
import { tr, intlLocale } from "../util/i18n.js";
const threadModeSchema = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]);
@@ -35,7 +39,7 @@ export type Services = {
// AgentManager provides runtime info once wired in at P1-4; may be empty (no session started)
runtime?: (threadId: string) => { status: string; queue: unknown[]; pending: unknown[] } | null;
manager?: {
send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior?: "queue" | "steer"): Promise<void>;
send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior?: "queue" | "steer"): Promise<"started" | "steered" | "queued" | void>;
interrupt(threadId: string): Promise<void>;
respond(threadId: string, requestId: string, answer: { optionId?: string; answers?: Record<string, string>; cancelled?: boolean }): Promise<void>;
setModel(threadId: string, model: string | null): Promise<void>;
@@ -46,6 +50,7 @@ export type Services = {
close(threadId: string): Promise<void>;
deleteThread(threadId: string): Promise<void>;
listCommands(threadId: string, opts?: { load?: boolean }): Promise<SlashCommand[]>;
removeQueued(threadId: string, queueId: string): boolean;
};
};
@@ -61,7 +66,7 @@ function wrap<T extends z.ZodType>(schema: T, fn: (p: z.infer<T>, ctx: ConnCtx)
return (params: unknown, ctx: ConnCtx) => {
const r = schema.safeParse(params ?? {});
if (!r.success) {
throw new ApiError("bad_params", "参数不对:" + r.error.issues.map((i) => i.message).join(";"));
throw new ApiError("bad_params", tr("err.badParams", { detail: r.error.issues.map((i) => i.message).join("; ") }));
}
return fn(r.data, ctx);
};
@@ -84,9 +89,19 @@ export function registerMethods(gw: Gateway, svc: Services): void {
gw.method("settings.get", wrap(zEmpty, () => svc.settings.get()));
gw.method("settings.set", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), (p) =>
svc.settings.set(p.patch)
));
gw.method("settings.set", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), async (p) => {
const checked = parseSettingsPatch(p.patch);
if (!checked.ok) throw new ApiError("bad_params", `Invalid setting: ${checked.error}`);
const before = await svc.settings.get();
const next = await svc.settings.set(checked.patch as Partial<Settings>);
// A changed launch command only invalidates that Agent's detection / model cache (B2: toggling never wipes the rest)
for (const id of Object.keys(checked.patch.providerCommand ?? {})) {
if (JSON.stringify(before.providerCommand?.[id] ?? null) !== JSON.stringify(next.providerCommand?.[id] ?? null)) {
clearProviderCache(id);
}
}
return next;
}));
gw.method("sub.add", wrap(
z.object({ ch: z.string().min(1).max(120), afterSeq: z.number().int().nonnegative().optional() }),
@@ -121,12 +136,13 @@ export function registerMethods(gw: Gateway, svc: Services): void {
listProviders().map(async (p) => {
const entry = catalogById(p.id);
const enabled = isProviderEnabled(settings, p.id);
const launch = launchFromSettings(settings, p.id);
// Disabled / not-integrated ones are neither detected nor asked for models (saves seconds of CLI startup)
const skip = !enabled || entry?.status === "planned";
const det: import("../providers/types.js").DetectResult = skip
? { available: false, reason: !enabled ? "已在设置中禁用" : "尚未接入" }
: await cachedDetect(p);
const models = !skip && det.available ? await cachedModels(p) : [];
? { available: false, reason: !enabled ? tr("provider.disabled") : tr("provider.planned") }
: await cachedDetect(p, launch);
const models = !skip && det.available ? await cachedModels(p, launch) : [];
return {
id: p.id,
name: p.name,
@@ -136,7 +152,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
ready: entry?.status === "verified",
bin: det.bin,
version: det.version,
reason: !enabled ? "已在设置中禁用" : det.reason,
reason: !enabled ? tr("provider.disabled") : det.reason,
installHint: det.installHint,
capabilities: p.capabilities,
models,
@@ -176,7 +192,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
gw.method("projects.remove", wrap(z.object({ id: z.string() }), async (p) => {
const proj = await svc.projects.get(p.id);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
// Move all of the project's conversations to the trash
for (const t of await svc.threads.list()) {
if (t.projectId === p.id) {
@@ -191,8 +207,8 @@ export function registerMethods(gw: Gateway, svc: Services): void {
gw.method("projects.open", wrap(z.object({ id: z.string() }), async (p) => {
const proj = await svc.projects.get(p.id);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!existsSync(proj.path)) throw new ApiError("bad_path", "目录不存在或不是文件夹");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
if (!existsSync(proj.path)) throw new ApiError("bad_path", tr("err.dirMissing"));
const cmd = process.platform === "win32" ? "explorer.exe" : process.platform === "darwin" ? "open" : "xdg-open";
// explorer.exe doesn't understand forward-slash paths (it opens "Documents"); a missing xdg-open must not make the daemon throw either
const target = process.platform === "win32" ? win32Path.normalize(proj.path) : proj.path;
@@ -238,17 +254,20 @@ export function registerMethods(gw: Gateway, svc: Services): void {
}),
async (p) => {
const proj = await svc.projects.get(p.projectId);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!existsSync(proj.path)) throw new ApiError("bad_path", "项目目录已不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
if (!existsSync(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
// New conversations must use an enabled Agent (except imported sessions, which already ran)
if (!p.providerSessionId && !isProviderEnabled(await svc.settings.get(), p.provider)) {
throw new ApiError("bad_params", "该 Agent 已在设置中禁用");
throw new ApiError("bad_params", tr("provider.disabledNamed", { name: catalogById(p.provider)?.name ?? p.provider }));
}
const cat = catalogById(p.provider);
if (!p.providerSessionId && cat && !providerCreatable(cat.status)) {
throw new ApiError("bad_params", `${cat.name} 尚未接入,暂不能新建对话`);
throw new ApiError("bad_params", tr("provider.plannedNamed", { name: cat.name }));
}
const meta = await svc.threads.create(p);
// B8: the default permission mode is mapped onto this Agent's own modes (same rule as thread.setProvider)
const provider = getProvider(p.provider);
const mode = clampMode(provider?.capabilities.modes ?? [], p.mode);
const meta = await svc.threads.create({ ...p, mode });
gw.publish("sidebar", { type: "thread.upsert", thread: meta });
return meta;
}
@@ -258,7 +277,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
z.object({ id: z.string(), afterSeq: z.number().int().nonnegative().optional() }),
async (p) => {
const meta = await svc.threads.get(p.id);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
const events = await svc.threads.readEvents(p.id, p.afterSeq ?? 0, 5000);
const rt = svc.runtime?.(p.id) ?? null;
return {
@@ -280,7 +299,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
}),
async (p) => {
const meta = await svc.threads.get(p.id);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
const patch: Record<string, unknown> = {};
if (p.title !== undefined) {
patch.title = p.title.trim() || meta.title;
@@ -296,7 +315,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
gw.method("threads.delete", wrap(z.object({ id: z.string() }), async (p) => {
const meta = await svc.threads.get(p.id);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
if (svc.manager) await svc.manager.deleteThread(p.id);
else await svc.threads.delete(p.id);
gw.publish("sidebar", { type: "thread.remove", id: p.id });
@@ -306,8 +325,8 @@ export function registerMethods(gw: Gateway, svc: Services): void {
// ---- git.* (§5.8) ----
const projectPath = async (projectId: string): Promise<string> => {
const proj = await svc.projects.get(projectId);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!existsSync(proj.path)) throw new ApiError("bad_path", "项目目录已不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
if (!existsSync(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone"));
return proj.path;
};
@@ -335,7 +354,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
// ---- history.* (§7.6) ----
gw.method("history.list", wrap(z.object({ projectId: z.string() }), async (p) => {
const proj = await svc.projects.get(p.projectId);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
const imported = new Set(
(await svc.threads.list())
.filter((t) => t.projectId === p.projectId && t.providerSessionId)
@@ -357,7 +376,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
}),
async (p) => {
const proj = await svc.projects.get(p.projectId);
if (!proj) throw new ApiError("not_found", "项目不存在");
if (!proj) throw new ApiError("not_found", tr("err.projectMissing"));
const metas = [];
for (const item of p.items) {
const provider = getProvider(item.provider);
@@ -403,7 +422,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
gw.method("terminal.attach", wrap(z.object({ id: z.string() }), async (p, ctx) => {
const r = svc.terminals.attach(p.id);
if (r.error || r.index == null) throw new ApiError("not_found", r.error ?? "终端不存在");
if (r.error || r.index == null) throw new ApiError("not_found", r.error ?? tr("err.terminalMissing"));
// attach also subscribes to the terminal:<index> channel (input frames are gated on that subscription too)
svc.gateway.subscribe(ctx.conn, `terminal:${r.index}`);
return r;
@@ -417,7 +436,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
// ---- thread.* (runtime operations, need the manager) ----
const needManager = () => {
if (!svc.manager) throw new ApiError("unavailable", "会话管理器未启动");
if (!svc.manager) throw new ApiError("unavailable", tr("err.noManager"));
return svc.manager;
};
@@ -429,11 +448,17 @@ export function registerMethods(gw: Gateway, svc: Services): void {
behavior: z.enum(["queue", "steer"]).optional(),
}),
async (p) => {
await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue");
return { ok: true };
// delivered tells the composer what happened: a steer an Agent can't take is queued (B7)
const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue");
return { ok: true, delivered: delivered ?? "started" };
}
));
// The composer's queue list has a remove button; it used to call a method that didn't exist
gw.method("thread.queueRemove", wrap(z.object({ id: z.string(), queueId: z.string() }), async (p) => {
return { ok: needManager().removeQueued(p.id, p.queueId) };
}));
gw.method("thread.interrupt", wrap(z.object({ id: z.string() }), async (p) => {
await needManager().interrupt(p.id);
return { ok: true };
@@ -501,23 +526,23 @@ export function registerMethods(gw: Gateway, svc: Services): void {
// ---- thread.exportMarkdown (P2-7): persisted events → Markdown text ----
gw.method("thread.exportMarkdown", wrap(z.object({ id: z.string() }), async (p) => {
const meta = await svc.threads.get(p.id);
if (!meta) throw new ApiError("not_found", "对话不存在");
if (!meta) throw new ApiError("not_found", tr("err.threadMissing"));
const events = await svc.threads.readEvents(p.id, 0, 20000);
const L: string[] = [];
L.push(`# ${meta.title}`, "");
L.push(`> ${meta.provider} · ${meta.model ?? "默认"} · ${meta.mode} · ${new Date(meta.createdAt).toLocaleString("zh-CN")}`, "");
L.push(`> ${meta.provider} · ${meta.model ?? tr("export.defaultModel")} · ${meta.mode} · ${new Date(meta.createdAt).toLocaleString(intlLocale())}`, "");
for (const e of events) {
switch (e.type) {
case "user_message": L.push(`**我**${e.steered ? "(插话)" : ""}:\n\n${e.text}`, ""); break;
case "user_message": L.push(`**${tr("export.me")}**${e.steered ? tr("export.steered") : ""}:\n\n${e.text}`, ""); break;
case "assistant_message": L.push(e.text, ""); break;
case "reasoning": L.push(`<details><summary>思考</summary>\n\n${e.text}\n</details>`, ""); break;
case "reasoning": L.push(`<details><summary>${tr("export.reasoning")}</summary>\n\n${e.text}\n</details>`, ""); break;
case "tool_call": {
const icon = e.status === "ok" ? "✓" : e.status === "failed" ? "✗" : "…";
L.push(`- \`${e.kind}\` ${icon} ${e.title}${e.output ? `\n \`\`\`\n ${e.output.slice(0, 2000)}\n \`\`\`` : ""}`);
break;
}
case "plan": L.push("### 计划\n\n" + e.markdown, ""); break;
case "todo": L.push("### 待办\n\n" + e.items.map((i) => `- [${i.status === "done" || i.status === "completed" ? "x" : " "}] ${i.text}`).join("\n"), ""); break;
case "plan": L.push(`### ${tr("export.plan")}\n\n` + e.markdown, ""); break;
case "todo": L.push(`### ${tr("export.todo")}\n\n` + e.items.map((i) => `- [${i.status === "done" || i.status === "completed" ? "x" : " "}] ${i.text}`).join("\n"), ""); break;
case "notice": L.push(`_${e.message}_`, ""); break;
case "turn_ended": L.push(`— ${e.status}${e.durationMs ? ` · ${Math.round(e.durationMs / 1000)}s` : ""}${e.error ? ` · ${e.error}` : ""} —`, ""); break;
default: break;
@@ -526,8 +551,14 @@ export function registerMethods(gw: Gateway, svc: Services): void {
const markdown = L.join("\n");
const safe = meta.title.replace(/[\\/:*?"<>|\s]+/g, "_").slice(0, 60) || "thread";
const filename = `${safe}.md`;
const dir = join(homedir(), "Downloads");
await mkdir(dir, { recursive: true });
// ~/Downloads when it can be used, else <data>/exports (B21); the file is revealed with execFile (no shell)
let dir = join(homedir(), "Downloads");
try {
await mkdir(dir, { recursive: true });
} catch {
dir = join(svc.cfg.dataDir, "exports");
await mkdir(dir, { recursive: true });
}
let dest = join(dir, filename);
if (existsSync(dest)) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
+89 -5
View File
@@ -40,6 +40,13 @@ const DEFAULT_PORT = 3488;
// Longest wait for the daemon's ready line (Windows cold start + antivirus scanning can be slow)
const READY_TIMEOUT_MS = 15000;
const BIND_RETRY_MS = 2000;
const SESSION_BEAT_MS = 4000;
// A port still busy after this many tries (~10 s) is worth a log line (see bindLoop)
const BUSY_LOG_AFTER = 5;
function bindDelayMs() {
const v = Number(process.env.AGENT_CONSOLE_BIND_DELAY_MS);
return Number.isFinite(v) && v >= 0 ? v : 1200;
}
// Paths are computed again inside server(): tests change environment variables after import
function paths() {
@@ -51,6 +58,8 @@ function paths() {
logsDir: join(dataDir, "logs"),
spawnLog: join(dataDir, "logs", "daemon-spawn.log"),
daemonJson: join(dataDir, "daemon.json"),
// pid of the host that wrote page/session.js (kept out of the page directory, which any page can read)
sessionOwner: join(dataDir, "session-owner.json"),
pageDir: process.env.AGENT_CONSOLE_PAGE_DIR || join(here, "page"),
};
}
@@ -182,14 +191,47 @@ async function shutdownLegacy(info, log) {
// session.js is a script file holding only the gate port (a number) and the gate key (hex); "<" is still escaped just in case.
// Any page that knows Magpie's page path can read it with <script src>, so the daemon token must never go here.
function writeSession(pageDir, port, key) {
// ts: when it was written. beat: whether this host keeps refreshing it (every SESSION_BEAT_MS, from the first page open on).
// A host that is killed hard (Magpie restarting it, Windows) can't delete its session.js:
// - boot.js treats a beating file whose ts stopped moving as stale, and after a lost connection (ac_lost) takes only a file written
// after the loss, so it waits for the new host's file instead of opening a dead gate;
// - a file that never beat (the page was never opened) says nothing by its age, so the next host deletes it at startup when the
// host that wrote it is gone (removeDeadSession), before Magpie serves the page.
function writeSession(pageDir, port, key, beat = false) {
mkdirSync(pageDir, { recursive: true });
const json = JSON.stringify({ v: 2, port, key }).replace(/</g, "\\u003c");
const json = JSON.stringify({ v: 2, port, key, ts: Date.now(), beat }).replace(/</g, "\\u003c");
const temp = join(pageDir, `.session-${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
writeFileSync(temp, `globalThis.AgentConsoleSession = ${json};\n`, { mode: 0o600 });
renameSync(temp, join(pageDir, "session.js"));
}
// At host startup (synchronously, so before Magpie serves the page that made it start this host): a session.js left by a host
// that is no longer running points at a dead gate; delete it so boot.js waits for this host's file.
// session-owner.json holds the writer's pid; a live writer (another host, e.g. Magpie's own while a `magpie` CLI command runs) is left alone.
function removeDeadSession(p) {
const sessionPath = join(p.pageDir, "session.js");
let owner;
try {
owner = JSON.parse(readFileSync(p.sessionOwner, "utf8"));
} catch {
return;
}
if (!owner || !Number.isInteger(owner.pid) || owner.pid === process.pid || pidAlive(owner.pid)) return;
try {
const cur = readFileSync(sessionPath, "utf8");
if (typeof owner.key === "string" && owner.key && !cur.includes(owner.key)) return;
unlinkSync(sessionPath);
} catch {}
}
function writeSessionOwner(p, key) {
try {
mkdirSync(p.dataDir, { recursive: true });
// Only the first 16 hex chars of the gate key: enough to recognise the file, useless for opening the gate
writeFileSync(p.sessionOwner, JSON.stringify({ pid: process.pid, key: key.slice(0, 16) }), { mode: 0o600 });
} catch {}
}
function removeSession(pageDir, key) {
const sessionPath = join(pageDir, "session.js");
try {
@@ -236,6 +278,25 @@ function createHost(port) {
let starting = null;
let legacyChecked = false;
let wakeBindLoop = null;
let beat = null;
let bound = false;
removeDeadSession(p);
// From the first page open on, session.js is rewritten every SESSION_BEAT_MS (only while it is still ours), so a page that lost
// its connection can tell this live host's file from a dead host's. Before that there is nothing to tell apart: no writes.
function startBeat() {
if (beat || stopped || !bound) return;
const refresh = () => {
if (stopped) return;
try {
const cur = readFileSync(join(p.pageDir, "session.js"), "utf8");
if (cur.includes(key)) writeSession(p.pageDir, port, key, true);
} catch { /* deleted or unreadable: leave it */ }
};
refresh();
beat = setInterval(refresh, SESSION_BEAT_MS);
beat.unref?.();
}
async function checkLegacyOnce() {
if (legacyChecked) return;
@@ -366,7 +427,14 @@ function createHost(port) {
return { port: await starting };
}
const gate = createGate({ port, key, token, ensureDaemon });
// The gate calls this only for an /open with the right key
const gate = createGate({
port, key, token,
ensureDaemon: () => {
startBeat();
return ensureDaemon();
},
});
function waitForRetry() {
return new Promise((resolve) => {
@@ -380,12 +448,25 @@ function createHost(port) {
async function bindLoop() {
const loggedCodes = new Set();
let busyTries = 0;
// B16: every `magpie` CLI command starts a short-lived plugin host that calls server() too. Waiting a moment before binding
// means such a host usually exits before it takes the gate or writes session.js, and a port held by the long-lived host
// (EADDRINUSE) is only logged once it has stayed busy for a while, not once per CLI command.
const delay = bindDelayMs();
if (delay > 0) {
await new Promise((resolve) => {
const timer = setTimeout(resolve, delay);
wakeBindLoop = () => { clearTimeout(timer); resolve(); };
});
}
while (!stopped) {
try {
await gate.listen();
} catch (error) {
const code = error?.code || String(error);
if (!loggedCodes.has(code)) {
if (code === "EADDRINUSE") busyTries++;
const quiet = code === "EADDRINUSE" && busyTries < BUSY_LOG_AFTER;
if (!quiet && !loggedCodes.has(code)) {
loggedCodes.add(code);
log(`gate port ${port} bind failed (${code}); retrying every ${BIND_RETRY_MS / 1000}s`);
}
@@ -404,7 +485,9 @@ function createHost(port) {
return;
}
try {
writeSession(p.pageDir, port, key);
writeSession(p.pageDir, port, key, false);
writeSessionOwner(p, key);
bound = true;
liveSessions.set(p.pageDir, key);
installExitHook();
log(`gate listening on 127.0.0.1:${port}; session.js written`);
@@ -432,6 +515,7 @@ function createHost(port) {
async function stop() {
stopped = true;
if (beat) clearInterval(beat);
wakeBindLoop?.();
await binding;
await gate.close();
+21 -1
View File
@@ -56,6 +56,24 @@ export function failureHtml(error) {
);
}
/**
* The Magpie plugin page boot.js came from (?back=), so the daemon page can go back through it after the plugin host restarts
* (fresh session.js → new gate → new daemon). Only a loopback Magpie plugin page is accepted, so the daemon page can't be turned
* into an open redirect; it travels in the 302's # fragment next to the token and never reaches a server.
* Keep in sync with web/src/api/backToMagpie.ts.
*/
export function safeBackUrl(raw) {
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
let u;
try { u = new URL(raw); } catch { return null; }
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
if (u.username || u.password) return null;
const hostname = u.hostname.toLowerCase();
if (hostname !== "127.0.0.1" && hostname !== "localhost" && hostname !== "[::1]") return null;
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
}
const REOPEN_HTML =
"<!doctype html><meta charset=utf-8><p>Agent Console: 链接已失效,请在 Magpie 里重新打开插件页。" +
"<br>The link is no longer valid. Please reopen the Agent Console page in Magpie.</p>";
@@ -117,7 +135,9 @@ export function createGate({ port, key, token, ensureDaemon, host = "127.0.0.1"
for (const name of ["theme", "lang", "tokens"]) {
if (url.searchParams.has(name)) query.set(name, url.searchParams.get(name));
}
const location = `http://127.0.0.1:${daemon.port}/?${query}#t=${encodeURIComponent(token)}`;
const back = safeBackUrl(url.searchParams.get("back"));
const fragment = `t=${encodeURIComponent(token)}` + (back ? `&b=${encodeURIComponent(back)}` : "");
const location = `http://127.0.0.1:${daemon.port}/?${query}#${fragment}`;
res.writeHead(302, { ...SAFE_HEADERS, location });
res.end();
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.0.0",
"version": "1.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/page-agent-console",
"version": "1.0.0",
"version": "1.1.0",
"license": "MIT",
"dependencies": {
"@agentclientprotocol/sdk": "2.1.0",
+3 -3
View File
@@ -1,9 +1,9 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.0.0",
"version": "1.1.0",
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
"author": "qingnian108 (https://github.com/qingnian108)",
"homepage": "https://github.com/magpie-community/plugins/tree/main/packages/agent-console#readme",
"homepage": "https://github.com/qingnian108/magpie-agent-console",
"bugs": {
"url": "https://github.com/magpie-community/plugins/issues"
},
@@ -36,7 +36,7 @@
],
"license": "MIT",
"magpie": {
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCI+CiAgPHJlY3Qgd2lkdGg9IjEyOCIgaGVpZ2h0PSIxMjgiIHJ4PSIyOCIgZmlsbD0iIzBkOTQ4OCIvPgogIDxwYXRoIGQ9Ik0zNCA0NGg2MGE4IDggMCAwIDEgOCA4djI0YTggOCAwIDAgMS04IDhINjJsLTE0IDEydi0xMkgzNGE4IDggMCAwIDEtOC04VjUyYTggOCAwIDAgMSA4LTh6IiBmaWxsPSIjZmZmIi8+CiAgPGcgZmlsbD0iIzBkOTQ4OCI+CiAgICA8Y2lyY2xlIGN4PSI0OCIgY3k9IjYyIiByPSI1Ii8+CiAgICA8Y2lyY2xlIGN4PSI2NCIgY3k9IjYyIiByPSI1Ii8+CiAgICA8Y2lyY2xlIGN4PSI4MCIgY3k9IjYyIiByPSI1Ii8+CiAgPC9nPgogIDxwYXRoIGQ9Ik00MCA5NmwtOCAxMk04OCA5Nmw4IDEyIiBzdHJva2U9IiNmZmYiIHN0cm9rZS13aWR0aD0iNiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+Cjwvc3ZnPgo=",
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCIgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0Ij48cmVjdCB3aWR0aD0iNjQiIGhlaWdodD0iNjQiIHJ4PSIxNSIgZmlsbD0iIzI2MjkyYiIvPjxnIGZpbGw9Im5vbmUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSI0Ij48cGF0aCBkPSJNMTQgMjAuNSAyNSAzMSAxNCA0MS41IiBzdHJva2U9IiNmZmYiLz48cGF0aCBkPSJNMjkuMTQgMjMuNjFBMTIgMTIgMCAxIDEgNDYuNjMgMzkuOTJMNDguNiA0Ny42IDM5Ljg1IDQyLjkzQTEyIDEyIDAgMCAxIDI5LjE0IDM4LjM5IiBzdHJva2U9IiNmZmYiLz48cGF0aCBkPSJNMzUuNiAzNS40aDYiIHN0cm9rZT0iIzJkZDRiZiIvPjwvZz48L3N2Zz4=",
"page": {
"title": "Agent Console",
"titles": {
+27 -3
View File
@@ -27,6 +27,17 @@
if (said) said.textContent = zh ? "正在启动本地服务…" : "Starting local service…";
if (brand) brand.textContent = zh ? "Agent 控制台" : "Agent Console";
// ts: when the host wrote the file. beat: true once the host refreshes it every few seconds (from the first page open on);
// a beating file whose ts stopped moving belongs to a host that was killed (Magpie restarting it) and its gate is gone, so wait
// for the new host's file instead of navigating to a dead port. A file that doesn't beat (the page was never opened) can be old
// and still live; a dead host's one is deleted by the next host when it starts.
const STALE_MS = 12000;
// ac_lost: set by the daemon page when it lost its connection and came back here. The old host's file was last refreshed before
// that moment, so only a session.js refreshed after it (a live host's) is used.
const here = new URL(location.href);
const lostAt = Number(here.searchParams.get("ac_lost")) || 0;
here.searchParams.delete("ac_lost");
here.hash = "";
function validSession(s) {
return (
s &&
@@ -35,9 +46,16 @@
s.port > 0 &&
s.port <= 65535 &&
typeof s.key === "string" &&
/^[0-9a-f]{64}$/.test(s.key)
/^[0-9a-f]{64}$/.test(s.key) &&
fresh(s)
);
}
function fresh(s) {
if (typeof s.ts !== "number") return true; // a host from before ts
if (lostAt && !(s.ts > lostAt)) return false;
if (s.beat === false) return true;
return Math.abs(Date.now() - s.ts) < STALE_MS;
}
// Reload an uncached copy of session.js (the key changes after the plugin host restarts).
// Returns null when the file doesn't exist (the host isn't up yet or the port isn't bound yet).
@@ -62,8 +80,8 @@
const preloaded = validSession(globalThis.AgentConsoleSession) ? globalThis.AgentConsoleSession : null;
let session = await loadFreshSession(0);
if (!session && preloaded) session = preloaded;
// Right after the host starts the file may not be written yet: retry every 500ms for about 10 seconds
for (let attempt = 1; !session && attempt <= 20; attempt++) {
// Right after the host starts (or restarts) the file may be missing or stale: retry every 500ms for about 30 seconds
for (let attempt = 1; !session && attempt <= 60; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 500));
session = await loadFreshSession(attempt);
}
@@ -94,6 +112,12 @@
if (Object.keys(slim).length) {
try { q.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim))))); } catch { /* fine if it can't be passed along */ }
}
// This page's own URL: when Magpie restarts the plugin host (new gate key, the old daemon exits), the daemon page comes back here
// to read the fresh session.js. The gate checks it and puts it only in the # fragment.
try {
const back = here.toString();
if (back.length <= 2048) q.set("back", back);
} catch { /* no self-heal, the page still works */ }
location.replace("http://127.0.0.1:" + session.port + "/open?" + q.toString());
})();
+396
View File
@@ -0,0 +1,396 @@
// 1.1.0 fixes (QA B1–B21) and the self-heal after a plugin host restart.
import { describe, expect, it, beforeEach, afterEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { freePort, request } from "./helpers-net.js";
import { launchArgv, launchFromSettings, launchKey } from "../../daemon/src/providers/launch.js";
import { clampMode } from "../../daemon/src/providers/modes.js";
import { parseSettingsPatch, sanitizeStored, SettingsStore } from "../../daemon/src/store/settings.js";
import { mapSessionUpdate, newMapCtx } from "../../daemon/src/providers/acp/mapUpdate.js";
import { parseCodexConfig } from "../../daemon/src/providers/codex/provider.js";
import { mapNotification, newCodexMapState } from "../../daemon/src/providers/codex/map.js";
import { costIsReal } from "../../daemon/src/providers/claude/map.js";
import { setAppLocale as setLocale, tr } from "../../daemon/src/util/i18n.js";
import { safeBackUrl as webSafeBackUrl, backUrlFromHash, backTarget, watchReconnect } from "../../web/src/api/backToMagpie.js";
import { resolveTheme, normalizeThemeSetting } from "../../web/src/layout/theme.js";
import { parseArgsDraft, parseIdleDraft } from "../../web/src/components/settingsFields.js";
const gateUrl = pathToFileURL(join(resolve(__dirname, "..", ".."), "lib", "gate.mjs")).href;
describe("launch command (B3/B5)", () => {
it("appends the user's args after the built-in ones; prefixArgs go first", () => {
expect(launchArgv(["acp"], { cmd: "opencode", args: ["--foo"] })).toEqual(["acp", "--foo"]);
expect(launchArgv(["app-server"], { cmd: "node", prefixArgs: ["fx.mjs"], args: ["-v"] })).toEqual(["fx.mjs", "app-server", "-v"]);
expect(launchArgv(["x"])).toEqual(["x"]);
});
it("reads the settings and ignores an empty executable", () => {
const s = { providerCommand: { codex: { executable: " /opt/codex ", args: ["a", 3 as unknown as string] }, claude: { executable: " " } } };
expect(launchFromSettings(s as never, "codex")).toEqual({ cmd: "/opt/codex", args: ["a"] });
expect(launchFromSettings(s as never, "claude")).toBeUndefined();
expect(launchFromSettings({} as never, "codex")).toBeUndefined();
});
it("cache key changes with the command", () => {
expect(launchKey()).toBe("");
expect(launchKey({ cmd: "a", args: ["1"] })).not.toBe(launchKey({ cmd: "a", args: ["2"] }));
});
});
describe("clampMode (B8/B9)", () => {
it("keeps a supported mode, else default, else the first", () => {
expect(clampMode(["default", "acceptEdits", "bypassPermissions"], "acceptEdits")).toBe("acceptEdits");
expect(clampMode(["default", "acceptEdits", "bypassPermissions"], "plan")).toBe("default");
expect(clampMode(["plan", "build"] as never, "acceptEdits")).toBe("plan");
expect(clampMode(["default"], undefined)).toBe("default");
});
});
describe("settings schema (B18, B6)", () => {
it("accepts known fields and rejects bad ones", () => {
expect(parseSettingsPatch({ theme: "dark", idleCloseMinutes: 45 }).ok).toBe(true);
expect(parseSettingsPatch({ theme: "purple" }).ok).toBe(false);
expect(parseSettingsPatch({ idleCloseMinutes: 2 }).ok).toBe(false);
expect(parseSettingsPatch({ idleCloseMinutes: 241 }).ok).toBe(false);
expect(parseSettingsPatch({ idleCloseMinutes: 7.5 }).ok).toBe(false);
expect(parseSettingsPatch({ nope: 1 }).ok).toBe(false);
expect(parseSettingsPatch({ providerCommand: { opencode: { executable: "/x", args: ["--a"] } } }).ok).toBe(true);
expect(parseSettingsPatch({ providerCommand: { opencode: { args: "--a" } } }).ok).toBe(false);
expect(parseSettingsPatch({ providerEnabled: { codex: "yes" } }).ok).toBe(false);
});
it("drops wrongly typed stored values and clamps idle minutes", () => {
const s = sanitizeStored({ theme: 3, showThinking: "no", idleCloseMinutes: 1, sendKey: "enter" });
expect(s.theme).toBeUndefined();
expect(s.showThinking).toBeUndefined();
expect(s.sendKey).toBe("enter");
expect(s.idleCloseMinutes).toBe(5);
expect(sanitizeStored({ idleCloseMinutes: 9999 }).idleCloseMinutes).toBe(240);
});
it("store: removed settings are gone from the defaults", async () => {
const dir = mkdtempSync(join(tmpdir(), "ac11-"));
try {
const st = new SettingsStore(dir);
const s = (await st.get()) as Record<string, unknown>;
expect("defaultEffort" in s).toBe(false);
expect("density" in s).toBe(false);
expect("idleExitMinutes" in s).toBe(false);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
});
describe("ACP text around tool calls (B1)", () => {
it("text before and after a tool call are separate items", () => {
const ctx = newMapCtx();
const a = mapSessionUpdate({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "before" } } as never, ctx);
mapSessionUpdate({ sessionUpdate: "tool_call", toolCallId: "t1", title: "ls", kind: "execute", status: "pending" } as never, ctx);
mapSessionUpdate({ sessionUpdate: "tool_call_update", toolCallId: "t1", status: "completed" } as never, ctx);
const b = mapSessionUpdate({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "after" } } as never, ctx);
const ida = (a[0] as { itemId: string }).itemId;
const idb = (b[0] as { itemId: string }).itemId;
expect(ida).not.toBe(idb);
// consecutive chunks stay in one item
const c = mapSessionUpdate({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "!" } } as never, ctx);
expect((c[0] as { itemId: string }).itemId).toBe(idb);
});
});
describe("Codex (B10, B11, B15)", () => {
it("reads model_provider/model and the provider's models, profile first", () => {
const cfg = parseCodexConfig([
'model = "gpt-5"', 'model_provider = "openai"', 'profile = "ds"',
"[profiles.ds]", 'model = "deepseek-chat"', 'model_provider = "magpie"',
"[model_providers.magpie]", 'models = ["deepseek-chat", "deepseek-reasoner"]',
"[model_providers.other]", 'models = ["nope"]',
].join("\n"));
expect(cfg.modelProvider).toBe("magpie");
expect(cfg.model).toBe("deepseek-chat");
expect(cfg.providerModels).toEqual(["deepseek-chat", "deepseek-reasoner"]);
});
it("saves raw reasoning when there is no summary", () => {
const st = newCodexMapState();
mapNotification("item/reasoning/textDelta", { itemId: "r1", delta: "think " }, st);
mapNotification("item/reasoning/textDelta", { itemId: "r1", delta: "hard" }, st);
const evs = mapNotification("item/completed", { item: { type: "reasoning", id: "r1", summary: [], content: [] } }, st);
expect(evs).toContainEqual({ type: "reasoning", itemId: "r1", text: "think hard" });
});
it("remembers a fileChange item's changes for the approval card", () => {
const st = newCodexMapState();
const changes = [{ path: "a.txt", kind: { type: "add" }, diff: "hi" }];
mapNotification("item/started", { item: { type: "fileChange", id: "f1", changes } }, st);
expect(st.fileChangesByItemId.get("f1")).toEqual(changes);
});
});
describe("Claude cost (B14)", () => {
it("keeps Claude Code's cost only for Claude models", () => {
expect(costIsReal({ "claude-sonnet-4-5": {} })).toBe(true);
expect(costIsReal({ "deepseek-chat": {} })).toBe(false);
expect(costIsReal({ "claude-haiku": {}, "deepseek-chat": {} })).toBe(false);
expect(costIsReal(undefined)).toBe(true);
});
});
describe("daemon i18n (B13)", () => {
afterEach(() => setLocale("zh"));
it("permission options follow the UI language", () => {
setLocale("en");
expect(tr("perm.allow")).toBe("Allow");
expect(tr("http.tooLarge")).toContain("50 MB");
setLocale("zh");
expect(tr("perm.allow")).toBe("允许");
});
});
describe("self-heal back URL (host restart)", () => {
const good = "http://127.0.0.1:3430/_magpie/plugin/6434536d5169e4148a4e62c188afe049/index.html";
const cases: [string, string | null][] = [
[good, good],
[good + "#frag", good],
["http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1", "http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1"],
["http://[::1]:3430/_magpie/plugin/abc/index.html", "http://[::1]:3430/_magpie/plugin/abc/index.html"],
["https://evil.example/_magpie/plugin/abc/index.html", null],
["http://127.0.0.1.evil.example/_magpie/plugin/abc/index.html", null],
["http://user:pw@127.0.0.1:3430/_magpie/plugin/abc/index.html", null],
["javascript:alert(1)//127.0.0.1/_magpie/plugin/a/index.html", null],
["file:///_magpie/plugin/abc/index.html", null],
["http://127.0.0.1:3430/other/index.html", null],
["http://127.0.0.1:3430/_magpie/plugin/../../x/index.html", null],
["http://127.0.0.1:3430/_magpie/plugin/abc/evil.html", null],
["", null],
];
it("web and gate accept only a loopback Magpie plugin page", async () => {
const { safeBackUrl } = await import(/* @vite-ignore */ gateUrl);
for (const [input, want] of cases) {
expect(webSafeBackUrl(input), input).toBe(want);
expect(safeBackUrl(input), input).toBe(want);
}
});
it("reads b= from the fragment next to the token", () => {
expect(backUrlFromHash(`#t=abc&b=${encodeURIComponent(good)}`)).toBe(good);
expect(backUrlFromHash("#t=abc")).toBeNull();
expect(backUrlFromHash(`#t=abc&b=${encodeURIComponent("https://evil.example/")}`)).toBeNull();
});
it("going back carries the moment the connection dropped", () => {
expect(backTarget(`#t=x&b=${encodeURIComponent(good)}`, 1234)).toBe(good + "?ac_lost=1234");
expect(backTarget(`#t=x&b=${encodeURIComponent(good)}`, 0)).toBe(good);
expect(backTarget("#t=x", 1234)).toBeNull();
});
it("gate forwards a valid back URL only in the fragment", async () => {
const { createGate } = await import(/* @vite-ignore */ gateUrl);
const port = await freePort();
const daemonPort = await freePort();
const key = "c".repeat(64);
const token = "a".repeat(64);
const gate = createGate({ port, key, token, ensureDaemon: async () => ({ port: daemonPort }) });
await gate.listen();
try {
const ok = await request(port, `/open?k=${key}&theme=dark&back=${encodeURIComponent(good)}`);
expect(ok.status).toBe(302);
expect(ok.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?theme=dark#t=${token}&b=${encodeURIComponent(good)}`);
const bad = await request(port, `/open?k=${key}&back=${encodeURIComponent("https://evil.example/")}`);
expect(bad.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?#t=${token}`);
// without the key there's still nothing
expect((await request(port, `/open?back=${encodeURIComponent(good)}`)).status).toBe(403);
} finally {
await gate.close();
}
});
it("goes back after the connection stays down, not on a short blip", async () => {
let listener: (s: string) => void = () => {};
let state = "open";
const fake = { onState: (fn: (s: string) => void) => { listener = fn; return () => {}; }, getState: () => state };
let stuck = 0;
watchReconnect(fake, () => stuck++, 40);
state = "reconnecting"; listener(state);
await new Promise((r) => setTimeout(r, 15));
state = "open"; listener(state);
await new Promise((r) => setTimeout(r, 60));
expect(stuck).toBe(0);
state = "reconnecting"; listener(state);
listener("reconnecting");
await new Promise((r) => setTimeout(r, 70));
expect(stuck).toBe(1);
});
});
describe("theme (B4)", () => {
it("explicit light/dark wins over the host; auto follows the host, then the OS", () => {
expect(resolveTheme("light", "dark", "dark")).toEqual({ theme: "light", hostColors: false });
expect(resolveTheme("dark", "dark", "light")).toEqual({ theme: "dark", hostColors: true });
expect(resolveTheme("auto", "dark", "light")).toEqual({ theme: "dark", hostColors: true });
expect(resolveTheme("auto", null, "dark")).toEqual({ theme: "dark", hostColors: false });
expect(normalizeThemeSetting("bogus")).toBe("auto");
});
});
describe("settings fields (B5, B6)", () => {
it("args: JSON string array or empty", () => {
expect(parseArgsDraft("")).toBeUndefined();
expect(parseArgsDraft(' ["--foo", "bar"] ')).toEqual(["--foo", "bar"]);
expect(parseArgsDraft("[")).toBeNull();
expect(parseArgsDraft("[1]")).toBeNull();
expect(parseArgsDraft('"--foo"')).toBeNull();
});
it("idle minutes: whole number 5–240", () => {
expect(parseIdleDraft("1")).toBeNull();
expect(parseIdleDraft("5")).toBe(5);
expect(parseIdleDraft("240")).toBe(240);
expect(parseIdleDraft("241")).toBeNull();
expect(parseIdleDraft("12.5")).toBeNull();
expect(parseIdleDraft("")).toBeNull();
});
});
describe("boot.js (self-heal)", () => {
async function runBoot(sessions: unknown[], href = "http://127.0.0.1:3430/_magpie/plugin/abc/index.html"): Promise<string | null> {
const { readFileSync } = await import("node:fs");
const vm = await import("node:vm");
const code = readFileSync(join(resolve(__dirname, "..", ".."), "page", "boot.js"), "utf8");
let replaced: string | null = null;
let n = 0;
const ctx: Record<string, unknown> = {
setTimeout: (fn: () => void) => setImmediate(fn),
location: { href, replace: (u: string) => { replaced = u; } },
document: {
getElementById: () => null, querySelector: () => null,
createElement: () => ({ remove() {} }),
head: { appendChild(s: { onload?: () => void }) { ctx.AgentConsoleSession = sessions[Math.min(n++, sessions.length - 1)]; setImmediate(() => s.onload?.()); } },
},
URLSearchParams, URL, Date, Object, String, JSON, Math, Number, encodeURIComponent, unescape, btoa,
};
ctx.globalThis = ctx;
ctx.window = ctx;
vm.runInNewContext(code, ctx);
for (let i = 0; i < 200 && !replaced; i++) await new Promise((r) => setImmediate(r));
return replaced;
}
const key1 = "1".repeat(64), key2 = "2".repeat(64);
it("skips a killed host's stale session.js and opens the new gate, passing its own page as back", async () => {
const url = await runBoot([
{ v: 2, port: 3488, key: key1, ts: Date.now() - 60_000, beat: true },
{ v: 2, port: 3488, key: key1, ts: Date.now() - 60_000, beat: true },
{ v: 2, port: 3488, key: key2, ts: Date.now(), beat: false },
]);
expect(url).toBeTruthy();
const u = new URL(url!);
expect(u.searchParams.get("k")).toBe(key2);
expect(u.searchParams.get("back")).toBe("http://127.0.0.1:3430/_magpie/plugin/abc/index.html");
});
it("after a lost connection, ignores a session.js refreshed before it (the killed host's)", async () => {
const lost = Date.now() - 3000;
const url = await runBoot([
{ v: 2, port: 3488, key: key1, ts: lost - 1000 },
{ v: 2, port: 3488, key: key2, ts: Date.now() },
], `http://127.0.0.1:3430/_magpie/plugin/abc/index.html?ac_lost=${lost}`);
const u = new URL(url!);
expect(u.searchParams.get("k")).toBe(key2);
// ac_lost isn't passed on, so it can't pile up
expect(u.searchParams.get("back")).toBe("http://127.0.0.1:3430/_magpie/plugin/abc/index.html");
});
it("accepts an old session.js that never beat (page never opened) on a normal load", async () => {
const url = await runBoot([{ v: 2, port: 3488, key: key1, ts: Date.now() - 3_600_000, beat: false }]);
expect(new URL(url!).searchParams.get("k")).toBe(key1);
});
it("after a lost connection, waits for a beat newer than the loss (gate still up, daemon crashed)", async () => {
const lost = Date.now() - 2000;
const url = await runBoot([
{ v: 2, port: 3488, key: key1, ts: lost - 3000, beat: true },
{ v: 2, port: 3488, key: key1, ts: lost - 3000, beat: true },
{ v: 2, port: 3488, key: key1, ts: Date.now(), beat: true },
], `http://127.0.0.1:3430/_magpie/plugin/abc/index.html?ac_lost=${lost}`);
expect(new URL(url!).searchParams.get("k")).toBe(key1);
});
it("after a lost connection, a new host's first (non-beating) file written after the loss is used", async () => {
const lost = Date.now() - 4000;
const url = await runBoot([
{ v: 2, port: 3488, key: key1, ts: lost - 1000, beat: true },
{ v: 2, port: 3488, key: key2, ts: lost + 2500, beat: false },
], `http://127.0.0.1:3430/_magpie/plugin/abc/index.html?ac_lost=${lost}`);
expect(new URL(url!).searchParams.get("k")).toBe(key2);
});
it("still accepts a session.js without ts (older host)", async () => {
const url = await runBoot([{ v: 2, port: 3488, key: key1 }]);
expect(new URL(url!).searchParams.get("k")).toBe(key1);
});
});
describe("turn end duration fallback (ACP agents report none)", () => {
it("uses turn_started → turn_ended timestamps when durationMs is missing", async () => {
const { newTimelineState, applyEvent } = await import("../../web/src/timeline/reducer.js");
const st = newTimelineState();
applyEvent(st, { seq: 1, ts: 1000, threadId: "t", turnId: "u", type: "turn_started", model: null, mode: "default", effort: null } as never);
applyEvent(st, { seq: 2, ts: 5200, threadId: "t", turnId: "u", type: "turn_ended", status: "completed" } as never);
const te = st.items.find((i) => i.kind === "turnend") as { durationMs?: number };
expect(te.durationMs).toBe(4200);
});
});
describe("daemon log: a closed console pipe (host killed hard) is not a crash", () => {
it("swallows EPIPE on stdout and stops writing to the console", async () => {
const { log, consoleClosed } = await import("../../daemon/src/log.js");
log("info", "before");
expect(consoleClosed()).toBe(false);
const err = Object.assign(new Error("write EPIPE"), { code: "EPIPE" });
// Without a listener this emit would throw (and in the daemon become an uncaughtException)
expect(() => process.stdout.emit("error", err)).not.toThrow();
expect(consoleClosed()).toBe(true);
expect(() => log("info", "after")).not.toThrow();
});
});
describe("monochrome accent: Magpie's accent is ignored, neutrals still follow Magpie", () => {
it("drops accent tokens (named or bare) but passes every other token through", async () => {
const { applyMagpieTokensFromSearch, isAccentToken } = await import("../../web/src/layout/applyMagpieTokens.js");
const g = globalThis as Record<string, unknown>;
const saved = g.document;
const set = new Map<string, string>();
g.document = { documentElement: { style: { setProperty: (k: string, v: string) => set.set(k, v) } } };
try {
const enc = (o: object) => "?tokens=" + Buffer.from(JSON.stringify(o)).toString("base64");
applyMagpieTokensFromSearch(enc({ accent: "#4f46e5", "accent-soft": "#eeedfd", "accent-fg": "#ffffff", bg: "#f4f4f6", fg: "#1c1c21", line: "#e3e3e8", red: "#d64545", font: "system-ui" }));
expect(set.has("--magpie-accent")).toBe(false);
expect(set.has("--magpie-accent-soft")).toBe(false);
expect(set.has("--magpie-accent-fg")).toBe(false);
expect(set.get("--magpie-bg")).toBe("#f4f4f6");
expect(set.get("--magpie-fg")).toBe("#1c1c21");
expect(set.get("--magpie-line")).toBe("#e3e3e8");
expect(set.get("--magpie-red")).toBe("#d64545");
expect(set.get("--magpie-font")).toBe("system-ui");
applyMagpieTokensFromSearch(enc({ "--accent": "#ff0000", "--accent-2": "#ff0000", "magpie-accent": "#ff0000", "--magpie-accent-fg": "#000" }));
expect([...set.keys()].some((k) => /accent/i.test(k))).toBe(false);
expect(isAccentToken("accent")).toBe(true);
expect(isAccentToken("--accent-soft")).toBe(true);
expect(isAccentToken("accented")).toBe(false);
expect(isAccentToken("bg")).toBe(false);
} finally {
g.document = saved;
}
});
it("tokens.css: neutral accent, no teal, no --magpie-accent anywhere in web/src styles", async () => {
const { readFileSync, readdirSync } = await import("node:fs");
const stylesDir = join(resolve(__dirname, "..", ".."), "web", "src", "styles");
const css = readFileSync(join(stylesDir, "tokens.css"), "utf8");
const decl = (block: string, v: string) => new RegExp(`${v}:\\s*([^;]+);`).exec(block)?.[1]?.trim() ?? "";
const light = css.slice(css.indexOf(":root {"), css.indexOf(":root[data-theme=\"dark\"]"));
const dark = css.slice(css.indexOf(":root[data-theme=\"dark\"]"), css.indexOf(":root[data-host-colors]"));
const isGrey = (c: string) => {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(c);
return !!m && m[1] === m[2] && m[2] === m[3];
};
for (const block of [light, dark]) {
for (const v of ["--accent", "--accent-2", "--accent-fg", "--accent-soft", "--run-bg", "--run-fg", "--cp-focus"]) {
expect(isGrey(decl(block, v)), `${v} = ${decl(block, v)}`).toBe(true);
}
}
// light: charcoal accent with white text; dark: light accent with dark text
expect(parseInt(decl(light, "--accent").slice(1, 3), 16)).toBeLessThan(0x50);
expect(decl(light, "--accent-fg").toLowerCase()).toBe("#ffffff");
expect(parseInt(decl(dark, "--accent").slice(1, 3), 16)).toBeGreaterThan(0xc0);
expect(parseInt(decl(dark, "--accent-fg").slice(1, 3), 16)).toBeLessThan(0x40);
for (const f of readdirSync(stylesDir)) {
const src = readFileSync(join(stylesDir, f), "utf8");
expect(src, f).not.toMatch(/#(0f766e|14b8a6|2dd4bf|0d9488|115e59|5eead4|99f6e4|ccfbf1|04201c)\b/i);
expect(src, f).not.toMatch(/--magpie-accent/);
}
});
});
@@ -8,7 +8,6 @@ import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { ClaudeSession } from "../../daemon/src/providers/claude/session.js";
import { createClaudeProvider } from "../../daemon/src/providers/claude/provider.js";
import { clearBinCache } from "../../daemon/src/util/bin.js";
import { setAppLocale } from "../../daemon/src/util/i18n.js";
import type { ProviderEvent } from "../../daemon/src/timeline/types.js";
@@ -246,15 +245,8 @@ describe("claude over stream-json", () => {
});
it("no claude on PATH: createSession says, in English, that Claude Code is not bundled and how to install it", async () => {
const path = process.env.PATH;
process.env.PATH = join(dir, "empty");
clearBinCache("claude");
try {
await expect(createClaudeProvider().createSession({ threadId: "t", cwd: dir, model: null, mode: "default", effort: null, resumeId: null }))
.rejects.toThrow(/^claude was not found .*Claude Code is not bundled with this plugin; install it first: npm i -g @anthropic-ai\/claude-code/);
} finally {
process.env.PATH = path;
clearBinCache("claude");
}
const missing = { ok: false as const, reason: "PATH has no claude" };
await expect(createClaudeProvider({ resolve: async () => missing }).createSession({ threadId: "t", cwd: dir, model: null, mode: "default", effort: null, resumeId: null }))
.rejects.toThrow(/^claude was not found .*Claude Code is not bundled with this plugin; install it first: npm i -g @anthropic-ai\/claude-code/);
});
});
@@ -207,4 +207,29 @@ describe("AgentManager", () => {
await (manager as unknown as { recycleIdle(): Promise<void> }).recycleIdle();
expect((await threads.get(threadId))?.status).toBe("closed");
}, 15000);
it("B17: at most MAX_WARM_IDLE idle agent processes stay warm", async () => {
const proj = (await projects.list())[0]!;
const ids = [threadId];
for (let i = 0; i < 4; i++) ids.push((await threads.create({ projectId: proj.id, provider: "mock" })).id);
for (const id of ids) {
await manager.send(id, { text: "hi" });
await waitFor(async () => (await threads.get(id))?.status === "idle", 20000);
}
await manager.recycleIdle();
const warm = [...(manager as unknown as { runtimes: Map<string, { session: unknown }> }).runtimes.values()].filter((r) => r.session);
expect(warm.length).toBeLessThanOrEqual(3);
}, 60000);
it("a queued message can be removed before it is sent", async () => {
await manager.send(threadId, { text: "/slow" });
await waitFor(async () => (await threads.get(threadId))?.status === "running");
expect(await manager.send(threadId, { text: "later" })).toBe("queued");
const q = manager.runtimeInfo(threadId)!.queue as { id: string }[];
expect(q.length).toBe(1);
expect(manager.removeQueued(threadId, q[0]!.id)).toBe(true);
expect(manager.runtimeInfo(threadId)!.queue.length).toBe(0);
expect(manager.removeQueued(threadId, "nope")).toBe(false);
await manager.interrupt(threadId);
}, 20000);
});
@@ -1,7 +1,7 @@
// Plugin entry (index.mjs): import has no side effects; server() → session.js → /open → daemon → stop() end to end.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { spawn } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
@@ -10,7 +10,7 @@ import { canBind, freePort, pidAlive, request, waitFor } from "./helpers-net.js"
const repo = resolve(__dirname, "..", "..");
const entryUrl = pathToFileURL(join(repo, "index.mjs")).href;
const hasDist = existsSync(join(repo, "daemon", "dist", "main.js"));
const ENV_KEYS = ["AGENT_CONSOLE_PAGE_DIR", "XDG_CONFIG_HOME", "AGENT_CONSOLE_PORT", "AGENT_CONSOLE_MOCK"];
const ENV_KEYS = ["AGENT_CONSOLE_PAGE_DIR", "XDG_CONFIG_HOME", "AGENT_CONSOLE_PORT", "AGENT_CONSOLE_MOCK", "AGENT_CONSOLE_BIND_DELAY_MS"];
let savedEnv: Record<string, string | undefined> = {};
let tempDirs: string[] = [];
@@ -18,7 +18,7 @@ let pageDir = "";
let leftoverPids: number[] = [];
let stopHost: (() => Promise<void>) | null = null;
function parseSession(text: string): { v: number; port: number; key: string; token?: string } {
function parseSession(text: string): { v: number; port: number; key: string; token?: string; ts?: number } {
const match = /^globalThis\.AgentConsoleSession = (\{.*\});\n$/.exec(text);
if (!match) throw new Error(`unexpected session.js: ${text}`);
return JSON.parse(match[1]);
@@ -64,6 +64,35 @@ describe("plugin entry (index.mjs)", () => {
expect(existsSync(join(process.env.XDG_CONFIG_HOME!, "magpie", "agent-console"))).toBe(false);
});
it("a session.js left by a host that is gone is deleted when the next host starts; a live host's is kept", async () => {
const sessionPath = join(pageDir, "session.js");
const dataDir = join(process.env.XDG_CONFIG_HOME!, "magpie", "agent-console");
mkdirSync(dataDir, { recursive: true });
const stale = `globalThis.AgentConsoleSession = {"v":2,"port":1,"key":"${"ab".repeat(32)}","ts":1,"beat":false};\n`;
// a pid that can't be running
const dead = spawnSync(process.execPath, ["-e", "process.pid"]).pid!;
process.env.AGENT_CONSOLE_PORT = String(await freePort());
process.env.AGENT_CONSOLE_BIND_DELAY_MS = "60000";
writeFileSync(sessionPath, stale);
writeFileSync(join(dataDir, "session-owner.json"), JSON.stringify({ pid: process.ppid, key: "abababababababab" }));
vi.resetModules();
let mod = await import(/* @vite-ignore */ `${entryUrl}?live=${Date.now()}`);
let host = await mod.default.server({}, {});
expect(readFileSync(sessionPath, "utf8")).toBe(stale);
await host.stop();
writeFileSync(sessionPath, stale);
writeFileSync(join(dataDir, "session-owner.json"), JSON.stringify({ pid: dead, key: "abababababababab" }));
vi.resetModules();
mod = await import(/* @vite-ignore */ `${entryUrl}?dead=${Date.now()}`);
host = await mod.default.server({}, {});
// synchronously, before server() even returns its first bind attempt
expect(existsSync(sessionPath)).toBe(false);
await host.stop();
delete process.env.AGENT_CONSOLE_BIND_DELAY_MS;
});
it.skipIf(!hasDist)(
"end to end: server() → session.js → /open → daemon → stop()",
async () => {
@@ -83,7 +112,10 @@ describe("plugin entry (index.mjs)", () => {
expect(session.key).toMatch(/^[0-9a-f]{64}$/);
// Any page that knows Magpie's page path can read session.js via <script src>: it must not contain the daemon token
expect(session.token).toBeUndefined();
expect(Object.keys(session).sort()).toEqual(["key", "port", "v"]);
expect(Object.keys(session).sort()).toEqual(["beat", "key", "port", "ts", "v"]);
expect(Math.abs(Date.now() - (session as { ts?: number }).ts!)).toBeLessThan(10000);
// No page has opened yet: the file isn't refreshed (no writes every few seconds for a page nobody uses)
expect((session as { beat?: boolean }).beat).toBe(false);
const key = session.key;
// Gate: /open → 302 to the daemon, token only in the # fragment
@@ -94,6 +126,10 @@ describe("plugin entry (index.mjs)", () => {
const daemonPort = Number(location.port);
expect(daemonPort).toBeGreaterThan(0);
expect(daemonPort).not.toBe(port);
// From the first open on the host refreshes session.js (beat), so a page that lost its connection can tell it from a dead host's
const beating = parseSession(readFileSync(sessionPath, "utf8")) as { beat?: boolean; key: string };
expect(beating.beat).toBe(true);
expect(beating.key).toBe(key);
expect(location.searchParams.get("theme")).toBe("dark");
expect(location.searchParams.has("t")).toBe(false);
const token = new URLSearchParams(location.hash.slice(1)).get("t") ?? "";
+2 -1
View File
@@ -12,6 +12,7 @@ import { Panel } from "./components/Panel";
import { SettingsDialog } from "./components/Settings";
import { Toasts } from "./components/Toast";
import { t } from "./i18n/index.js";
import { goBackToMagpie } from "./api/backToMagpie.js";
export function App() {
const { state, version } = useConnection();
@@ -42,7 +43,7 @@ export function App() {
<div className="boot-screen">
<div className="boot-wrap">
<span>{t("boot.serviceDown")}</span>
<button className="btn primary" onClick={() => location.reload()}>{t("boot.retry")}</button>
<button className="btn primary" onClick={() => { if (!goBackToMagpie()) location.reload(); }}>{t("boot.retry")}</button>
</div>
</div>
);
+3 -4
View File
@@ -3,6 +3,7 @@
import { useEffect, useRef, useState } from "react";
import { useConnection } from "./stores/connection";
import { ws } from "./main";
import { SelectMenu } from "./components/SelectMenu";
type Project = { id: string; name: string; path: string };
type ThreadMeta = {
@@ -130,10 +131,8 @@ export function DebugApp() {
<div style={{ display: "flex", height: "100vh", font: "13px/1.5 system-ui", color: "var(--fg)" }}>
<div style={{ width: 260, borderRight: "1px solid var(--border)", padding: 12, overflowY: "auto" }}>
<div style={{ marginBottom: 8 }}>{state === "open" ? `已连接 · ${version ?? ""}` : "连接中…"}</div>
<select value={projectId} onChange={(e) => setProjectId(e.target.value)} style={{ width: "100%" }}>
<option value="">选择项目</option>
{projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
</select>
<SelectMenu className="tinput sm-field" matchWidth ariaLabel="选择项目" value={projectId} onChange={setProjectId}
options={[{ value: "", label: "选择项目" }, ...projects.map((p) => ({ value: p.id, label: p.name }))]} />
<button onClick={() => void createThread()} disabled={!projectId} style={{ width: "100%", marginTop: 8 }}>新建对话(mock)</button>
<div style={{ marginTop: 12 }}>
{threads.filter((t) => !projectId || t.projectId === projectId).map((t) => (
@@ -0,0 +1,62 @@
// Self-heal after the plugin host restarts (Magpie restarts its Bun plugin host from time to time; the old host's daemon exits with it
// and the gate key / port change). This page was opened by the gate with the Magpie plugin page URL in the fragment (#t=…&b=…).
// When the daemon can't be reached for a few seconds, the page goes back to that Magpie page: boot.js reads the fresh session.js and
// opens the new gate, which starts a new daemon. Only a loopback Magpie plugin page URL is ever followed (no open redirect),
// and the token is never put anywhere but this page's own fragment.
/** The same check as lib/gate.mjs safeBackUrl: http(s), loopback host, no credentials, /_magpie/plugin/<id>/[page/]index.html */
export function safeBackUrl(raw: string | null | undefined): string | null {
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
let u: URL;
try { u = new URL(raw); } catch { return null; }
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
if (u.username || u.password) return null;
const host = u.hostname.toLowerCase();
if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]") return null;
if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null;
return `${u.protocol}//${u.host}${u.pathname}${u.search}`;
}
export function backUrlFromHash(hash: string): string | null {
const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
return safeBackUrl(new URLSearchParams(fragment).get("b"));
}
let lostAt = 0;
/** The URL to go back to, with ac_lost = when the connection dropped: boot.js then ignores a session.js last refreshed before
* that (the killed host's) and waits for the new host's. */
export function backTarget(hash: string, lost: number): string | null {
const b = backUrlFromHash(hash);
if (!b) return null;
const u = new URL(b);
if (lost > 0) u.searchParams.set("ac_lost", String(Math.floor(lost)));
return u.toString();
}
/** Navigate back through the Magpie plugin page; false when this page doesn't know it (opened some other way) */
export function goBackToMagpie(): boolean {
const target = backTarget(location.hash, lostAt);
if (!target) return false;
location.replace(target);
return true;
}
/** Calls onStuck once the connection has been down for `ms` without coming back */
export function watchReconnect(
ws: { onState(fn: (s: string) => void): () => void; getState(): string },
onStuck: () => void,
ms = 5000,
): () => void {
let timer: ReturnType<typeof setTimeout> | null = null;
const off = ws.onState((s) => {
if (s === "reconnecting" || s === "down") {
if (!lostAt) lostAt = Date.now();
if (!timer) timer = setTimeout(() => { timer = null; if (ws.getState() !== "open") onStuck(); }, ms);
} else if (s === "open") {
lostAt = 0;
if (timer) { clearTimeout(timer); timer = null; }
}
});
return () => { off(); if (timer) clearTimeout(timer); };
}
+3 -3
View File
@@ -93,7 +93,7 @@ export class WsClient {
// Reject all pending requests
for (const [id, p] of this.pending) {
clearTimeout(p.timer);
p.rej(new Error("连接中断"));
p.rej(new Error(t("api.connClosed")));
this.pending.delete(id);
}
if (this.closed) return;
@@ -114,13 +114,13 @@ export class WsClient {
return new Promise((res, rej) => {
const ws = this.ws;
if (!ws || ws.readyState !== WebSocket.OPEN) {
rej(new Error("连接未建立"));
rej(new Error(t("api.notConnected")));
return;
}
const id = ++this.seq;
const timer = setTimeout(() => {
this.pending.delete(id);
rej(new Error("请求超时"));
rej(new Error(t("api.timeout")));
}, timeoutMs);
this.pending.set(id, { res, rej, timer });
ws.send(JSON.stringify({ t: "req", id, m: method, p: params ?? {} }));
@@ -101,20 +101,33 @@ export function Chat() {
if (!activeThreadId) {
return (
<div className="scroll" ref={scrollRef}>
<div className="empty-wrap">
{project ? (
<>
<div className="cp-hero-t">{tf("chat.newInProject", { name: project.name })}</div>
<EmptyComposer projectId={project.id} />
</>
) : (
<WorkspaceEmpty kind="no-projects" />
)}
</div>
{project ? (
<div className="empty-wrap">
<div className="cp-hero-t">{tf("chat.newInProject", { name: project.name })}</div>
<EmptyComposer projectId={project.id} />
</div>
) : (
// Projects exist but none is selected (B12): don't claim there are no projects
<WorkspaceEmpty kind="pick-project" />
)}
</div>
);
}
let lastTurnEnd = -1;
for (let i = items.length - 1; i >= 0; i--) if (items[i]!.kind === "turnend") { lastTurnEnd = i; break; }
/** Text of the reply a turn-end row belongs to (for its copy button) */
const replyTextBefore = (idx: number): string => {
const parts: string[] = [];
for (let i = idx - 1; i >= 0; i--) {
const it = items[i]!;
if (it.kind === "user" || it.kind === "turnend") break;
if (it.kind === "assistant") parts.unshift(it.text);
}
return parts.join("\n\n");
};
return (
<>
<div className="scroll" ref={scrollRef} onScroll={onScroll}>
@@ -130,7 +143,9 @@ export function Chat() {
ref={virt.measureElement}
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)` }}
>
<TimelineRow it={it} threadId={activeThreadId} onEditResend={resend} onRetryLast={retryLast} />
<TimelineRow it={it} threadId={activeThreadId} onEditResend={resend}
onRetryLast={v.index === lastTurnEnd ? retryLast : undefined}
replyText={it.kind === "turnend" ? replyTextBefore(v.index) : undefined} />
</div>
);
})}
@@ -153,12 +168,12 @@ export function Chat() {
}
/** No project / nothing selected: centered onboarding matching the sidebar's empty state, no Composer at the bottom */
function WorkspaceEmpty({ kind }: { kind: "no-projects" }) {
void kind;
function WorkspaceEmpty({ kind }: { kind: "no-projects" | "pick-project" }) {
const pick = kind === "pick-project";
return (
<div className="empty-wrap workspace-empty">
<div className="cp-hero-t">{tr("sidebar.noProjectsTitle")}</div>
<div className="cp-hero-s">{tr("sidebar.noProjectsSub")}</div>
<div className="cp-hero-t">{tr(pick ? "chat.pickProjectTitle" : "sidebar.noProjectsTitle")}</div>
<div className="cp-hero-s">{tr(pick ? "chat.pickProjectSub" : "sidebar.noProjectsSub")}</div>
<div className="empty-actions">
<button type="button" className="btn primary" onClick={() => window.dispatchEvent(new CustomEvent("open-new-project"))}>
{tr("sidebar.newProject")}
@@ -179,10 +194,10 @@ function EmptyComposer({ projectId }: { projectId: string }) {
setBusy(true);
try {
const provider = await pickDefaultProvider();
const s = (await ws.call("settings.get")) as { defaultMode?: string; defaultEffort?: string | null };
const s = (await ws.call("settings.get")) as { defaultMode?: string };
const created = (await ws.call("threads.create", {
projectId, provider, model: null,
mode: s.defaultMode ?? "default", effort: s.defaultEffort ?? null,
mode: s.defaultMode ?? "default",
})) as { id: string };
ui.select(projectId, created.id);
await ws.call("thread.send", { id: created.id, text: text.trim() });
@@ -1,4 +1,5 @@
// Command palette (§8.6 Ctrl+K): filter projects/conversations/actions, ↑↓ to select, Enter to run.
import { applyTheme, currentTheme } from "../layout/theme.js";
import { useEffect, useMemo, useRef, useState } from "react";
import { isImeComposing } from "../composer/ime";
import { createPortal } from "react-dom";
@@ -61,9 +62,9 @@ export function CommandPalette({ onClose }: { onClose: () => void }) {
async function newThread(projectId: string) {
try {
const s = (await ws.call("settings.get")) as { defaultProvider?: string; defaultMode?: string; defaultEffort?: string | null };
const s = (await ws.call("settings.get")) as { defaultProvider?: string; defaultMode?: string };
const provider = await pickDefaultProvider();
const th = (await ws.call("threads.create", { projectId, provider, mode: s.defaultMode ?? "default", effort: s.defaultEffort ?? null })) as { id: string };
const th = (await ws.call("threads.create", { projectId, provider, mode: s.defaultMode ?? "default" })) as { id: string };
useUi.getState().select(projectId, th.id);
} catch (e) { toast(t("palette.failNew") + errMsg(e), true); }
}
@@ -92,7 +93,9 @@ export function CommandPalette({ onClose }: { onClose: () => void }) {
}
async function cycleTheme() {
const cur = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = cur;
try { await ws.call("settings.set", { patch: { theme: cur } }); } catch {}
const next = currentTheme() === "dark" ? "light" : "dark";
applyTheme(next);
try {
await ws.call("settings.set", { patch: { theme: next } });
} catch {}
}
@@ -13,7 +13,9 @@ import type { Mode, ModelInfo } from "../types/models";
import type { SlashCommand } from "../composer/slashMenu";
import { toast } from "./Toast";
import { useLiveSettings } from "./Settings";
import { permissionModes, composerModeOptions } from "../i18n/modes.js";
import { composerModeOptions, effortLabel } from "../i18n/modes.js";
import { Logo } from "./Logo";
import { SelectMenu } from "./SelectMenu";
import { errMsg, t as tr, tf } from "../i18n/index.js";
import {
applySlashPick,
@@ -181,12 +183,15 @@ export function Composer() {
if (running && behavior === "queue") setLastSent((s) => [...s, msg]);
setText("");
try {
await ws.call("thread.send", {
const r = (await ws.call("thread.send", {
id, text: msg,
attachments: attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })),
behavior: running && behavior === "steer" && steerOk ? "steer" : "queue",
});
})) as { delivered?: "started" | "steered" | "queued" } | undefined;
setAttachments([]);
// Say what really happened to a message sent mid-turn (B7: agents without steer queue it)
if (r?.delivered === "queued" && running) toast(tr("composer.queuedToast"));
else if (r?.delivered === "steered") toast(tr("composer.steeredToast"));
if (!running) setLastSent((s) => [...s.slice(-9), msg]);
} catch (e) {
setText(msg);
@@ -323,7 +328,7 @@ export function Composer() {
const modelLabel = (() => {
if (!thread?.model) {
const d = provider?.models?.find((x) => x.isDefault);
return d ? `${tr("composer.defaultModel")} · ${d.name}` : tr("composer.defaultModel");
return d ? d.name : tr("composer.defaultModel");
}
const m = provider?.models?.find((x) => x.id === thread.model);
let name = m?.name ?? thread.model;
@@ -417,7 +422,7 @@ export function Composer() {
ref={taRef}
className="cp-ta"
rows={1}
placeholder={waiting ? tr("composer.waitPerm") : running ? tr("composer.queuePlaceholder") : tr("composer.inputPlaceholder")}
placeholder={waiting ? tr("composer.waitPerm") : running ? tr(steerOk ? "composer.queuePlaceholder" : "composer.queuePlaceholderNoSteer") : tr("composer.inputPlaceholder")}
value={text}
disabled={waiting}
onChange={(e) => {
@@ -431,9 +436,11 @@ export function Composer() {
<div className="cp-bar">
{/* Agent·model pill */}
<div className="pill-wrap" ref={pickerRef}>
<button className="pill" onClick={() => openPicker(!agentPop)} title={tr("composer.agentModel")}>
<button className="pill chip" onClick={() => openPicker(!agentPop)} title={tr("composer.agentModel")}>
<Logo size={18} className="chip-logo" />
<span className="p-a">{provider?.name ?? thread?.provider ?? tr("composer.agent")}</span>
<span className="p-t">{modelLabel}</span>
<svg className="chip-caret" width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="M2.5 4l2.5 2.5L7.5 4" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>
</button>
{agentPop && (
<div className="pop agent-pop agent-picker">
@@ -557,44 +564,74 @@ export function Composer() {
</div>
)}
</div>
{/* thinking level */}
{/* thinking level: icon + short label; the menu is the page's own (SelectMenu), opening upwards */}
{showThinking && (
<select className="pill sel" value={thread?.effort ?? ""} title={tr("composer.effortTitle")}
onChange={(e) => setEffort(e.target.value || null)}>
<option value="">
{defaultThinking
? tf("composer.defaultEffortNamed", { level: defaultThinking })
: tr("composer.defaultEffort")}
</option>
{thinkingOpts.map((e) => <option key={e.id} value={e.id}>{e.label}</option>)}
</select>
<SelectMenu
className="pill ipill"
title={tr("composer.effortTitle")}
ariaLabel={tr("composer.effortTitle")}
prefer="up"
upAnchor=".cp-card"
value={thread?.effort ?? ""}
onChange={(v) => setEffort(v || null)}
options={[
{
value: "",
label: defaultThinking
? tf("composer.defaultEffortNamed", { level: effortLabel(defaultThinking) })
: tr("composer.defaultEffort"),
},
// an Agent's own "default" level is the same thing as the first entry
...thinkingOpts.filter((e) => e.id !== "default").map((e) => ({ value: e.id, label: effortLabel(e.id, e.label) })),
]}
>
<Icon name="gauge" size={14} />
<span className="ip-l">{(() => {
const cur = thread?.effort ?? defaultThinking;
if (!cur) return tr("composer.defaultEffort");
return effortLabel(cur, thinkingOpts.find((o) => o.id === cur)?.label);
})()}</span>
</SelectMenu>
)}
{/* permission mode: list only the modes this Agent really has; hidden when there is only one (e.g. Pi has no modes) */}
{modes.length > 1 && (
<select
className={`pill sel${mode === "bypassPermissions" ? " danger" : ""}`}
// The mode stored on the conversation doesn't exist for this Agent (e.g. the default setting is Accept File Edits but OpenCode only has build/plan) → show the first one it will actually use
value={modes.some((m) => m.id === mode) ? mode : modes[0].id}
title={modeMeta?.desc}
onChange={(e) => setMode(e.target.value as Mode)}
>
{modes.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</select>
)}
{/* Cursor speed (like Paseo's Fast toggle); the old shield (auto-accept permissions) was removed */}
{modes.length > 1 && (() => {
// The mode stored on the conversation doesn't exist for this Agent → show the one it will actually use
const shown = modes.find((m) => m.id === mode) ?? modes[0]!;
return (
<SelectMenu
className={`pill ipill${shown.danger ? " danger" : ""}`}
title={shown.desc}
ariaLabel={tr("composer.modeTitle")}
prefer="up"
upAnchor=".cp-card"
menuClassName="mode-menu"
value={shown.id}
onChange={(v) => setMode(v as Mode)}
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc, danger: m.danger }))}
>
<Icon name="shield" size={14} />
<span className="ip-l">{shown.label}</span>
</SelectMenu>
);
})()}
{/* Cursor speed (like Paseo's Fast toggle) */}
{thread?.provider === "cursor" && (
<select
className="pill sel cursor-fast"
value={thread.cursorFast ? "fast" : "off"}
<SelectMenu
className="pill ipill cursor-fast"
title="Fast"
onChange={(e) => setCursorOpts({ cursorFast: e.target.value === "fast" })}
ariaLabel="Fast"
prefer="up"
upAnchor=".cp-card"
value={thread.cursorFast ? "fast" : "off"}
onChange={(v) => setCursorOpts({ cursorFast: v === "fast" })}
options={[{ value: "off", label: "Fast: Off" }, { value: "fast", label: "Fast: On" }]}
>
<option value="off">Fast: Off</option>
<option value="fast">Fast: On</option>
</select>
<span className="ip-l">{thread.cursorFast ? "Fast: On" : "Fast: Off"}</span>
</SelectMenu>
)}
<span className="cp-div" aria-hidden="true" />
{/* attachments */}
<button className="ibtn" title={tr("composer.attachTitle")} onClick={() => fileRef.current?.click()}>
<button className="ibtn cp-attach" title={tr("composer.attachTitle")} onClick={() => fileRef.current?.click()}>
<Icon name="attach" />
</button>
<input ref={fileRef} type="file" hidden multiple accept="image/*,.txt,.md,.log,.json,.csv"
@@ -603,19 +640,29 @@ export function Composer() {
{running ? (
<>
<span className="cp-clock">{elapsed}s</span>
{(text.trim() || attachments.length > 0) && (
<button className="cp-send" title={tr(steerOk && prefs.runningSend === "steer" ? "settings.steer" : "settings.queue")}
disabled={waiting || attachments.some((a) => a.uploading)}
onClick={() => void send(prefs.runningSend === "steer" && steerOk ? "steer" : "queue")}>
<Icon name="arrowUp" />
</button>
)}
<button className="cp-stop" title={tr("common.stop")} onClick={() => void ws.call("thread.interrupt", { id: thread?.id })}>
<Icon name="stop" />
<Icon name="stopFill" />
</button>
</>
) : (
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0) || attachments.some((a) => a.uploading)}
onClick={() => void send("queue")}>
<Icon name="send" />
<Icon name="arrowUp" />
</button>
)}
</div>
</div>
</div>
{running && !steerOk && prefs.runningSend === "steer" && (
<div className="cp-hint">{tf("composer.steerUnsupported", { agent: provider?.name ?? thread?.provider ?? "" })}</div>
)}
</div>
);
}
@@ -14,7 +14,8 @@ export function Dialog({
}) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") { e.stopPropagation(); onClose(); }
// An open dropdown (SelectMenu) inside the dialog takes Esc first: it closes itself, not the dialog
if (e.key === "Escape" && !document.querySelector("[data-select-menu]")) { e.stopPropagation(); onClose(); }
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
@@ -16,17 +16,23 @@ const PATHS: Record<string, string> = {
refresh: "M20 11a8 8 0 1 0-2.3 6.3M20 5v6h-6",
copy: "M8 8h11v12H8zM5 16V4h11",
check: "M5 13l4 4L19 7",
gauge: "M5.6 18.4a9 9 0 1 1 12.8 0M12 13l3.5-3.5M12 13h.01",
arrowUp: "M12 19V5m-6 6 6-6 6 6",
stopFill: "M8 8h8v8H8z",
shield: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",
zap: "M13 2L4 14h7l-1 8 9-12h-7l1-8z",
settings: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z",
};
const FILLED = new Set(["stopFill"]);
const BOLD = new Set(["arrowUp"]);
export function Icon({ name, size = 16 }: { name: keyof typeof PATHS | string; size?: number }) {
const d = PATHS[name];
if (!d) return null;
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<svg width={size} height={size} viewBox="0 0 24 24" fill={FILLED.has(name) ? "currentColor" : "none"} stroke="currentColor"
strokeWidth={BOLD.has(name) ? "2.2" : "1.6"} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={d} />
</svg>
);
@@ -0,0 +1,13 @@
// Agent Console logo (same drawing as assets/icon.svg; strokes a little bolder so it still reads at 16–20px).
export function Logo({ size = 18, className }: { size?: number; className?: string }) {
return (
<svg className={className} width={size} height={size} viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#26292b" />
<g fill="none" strokeLinecap="round" strokeLinejoin="round" strokeWidth="5.2">
<path d="M14 20.5 25 31 14 41.5" stroke="#fff" />
<path d="M29.14 23.61A12 12 0 1 1 46.63 39.92L48.6 47.6 39.85 42.93A12 12 0 0 1 29.14 38.39" stroke="#fff" />
<path d="M35.6 35.4h6" stroke="#2dd4bf" />
</g>
</svg>
);
}
@@ -0,0 +1,207 @@
// The page's own dropdown (Magpie's UI never shows a native <select> popup): a button trigger plus a small listbox menu.
// Keyboard: on the trigger ArrowDown/ArrowUp/Enter/Space open it; in the menu ArrowUp/ArrowDown/Home/End move, a letter jumps,
// Enter/Space pick, Esc/Tab close (Esc returns focus to the trigger). Click outside closes. The menu is portaled to <body> with
// fixed positioning, opens below the trigger or flips above it when there's no room (the composer sits at the bottom), and is
// kept inside the window; no browser popup is involved, so it behaves the same inside Magpie's sandboxed iframe.
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
export type SelectOption<T extends string = string> = {
value: T;
label: string;
hint?: string;
disabled?: boolean;
danger?: boolean;
};
const GAP = 4;
const EDGE = 8;
export function SelectMenu<T extends string>({
value, options, onChange, ariaLabel, title, className, children, prefer = "down", matchWidth = false, menuClassName, upAnchor,
}: {
value: T;
options: SelectOption<T>[];
onChange: (v: T) => void;
ariaLabel: string;
title?: string;
className?: string;
/** trigger content (icon + label); defaults to the selected option's label */
children?: ReactNode;
/** "up" for triggers at the bottom of the window (composer) */
prefer?: "down" | "up";
/** menu at least as wide as the trigger (form fields) */
matchWidth?: boolean;
menuClassName?: string;
/** when opening upwards, sit above this ancestor of the trigger (e.g. ".cp-card": above the whole composer, not over its text) */
upAnchor?: string;
}) {
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const [pos, setPos] = useState<{ left: number; top: number; minWidth: number; maxHeight: number } | null>(null);
const btnRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const id = useId();
const cur = options.find((o) => o.value === value);
const enabled = (i: number) => i >= 0 && i < options.length && !options[i]!.disabled;
const step = useCallback((from: number, dir: 1 | -1) => {
for (let k = 1; k <= options.length; k++) {
const i = (from + dir * k + options.length * 2) % options.length;
if (!options[i]!.disabled) return i;
}
return from;
}, [options]);
const show = (at?: "first" | "last") => {
const sel = options.findIndex((o) => o.value === value);
let i = at === "first" ? step(-1, 1) : at === "last" ? step(0, -1) : sel;
if (!enabled(i)) i = step(-1, 1);
setActive(i);
setPos(null);
setOpen(true);
};
const close = (refocus: boolean) => {
setOpen(false);
if (refocus) btnRef.current?.focus();
};
const pick = (i: number) => {
if (!enabled(i)) return;
close(true);
if (options[i]!.value !== value) onChange(options[i]!.value);
};
// Position: below or above the trigger, whichever fits (prefer first), clamped to the window
useLayoutEffect(() => {
if (!open) return;
const b = btnRef.current?.getBoundingClientRect();
const m = menuRef.current;
if (!b || !m) return;
const vw = window.innerWidth;
const vh = window.innerHeight;
const minWidth = matchWidth ? b.width : 0;
m.style.minWidth = `${minWidth}px`;
const w = m.offsetWidth;
const h = m.scrollHeight;
const below = vh - b.bottom - GAP - EDGE;
const anchorTop = (upAnchor && btnRef.current?.closest(upAnchor)?.getBoundingClientRect().top) || b.top;
const above = anchorTop - GAP - EDGE;
const up = prefer === "up" ? !(above < h && below > above) : below < h && above > below;
const room = up ? above : below;
const height = Math.min(h, room);
const top = up ? anchorTop - GAP - height : b.bottom + GAP;
const left = Math.max(EDGE, Math.min(b.left, vw - w - EDGE));
setPos({ left, top: Math.max(EDGE, top), minWidth, maxHeight: Math.max(80, room) });
}, [open, prefer, matchWidth, options.length, upAnchor]);
// Focus the menu once it is placed, and keep the active option in view
useEffect(() => {
if (open && pos) menuRef.current?.focus({ preventScroll: true });
}, [open, pos]);
useEffect(() => {
if (!open || active < 0) return;
menuRef.current?.querySelector<HTMLElement>(`[data-i="${active}"]`)?.scrollIntoView({ block: "nearest" });
}, [open, active]);
// Outside click / window resize close it
useEffect(() => {
if (!open) return;
const onDown = (e: PointerEvent) => {
const t = e.target as Node;
if (menuRef.current?.contains(t) || btnRef.current?.contains(t)) return;
close(false);
};
const onResize = () => close(false);
window.addEventListener("pointerdown", onDown, true);
window.addEventListener("resize", onResize);
window.addEventListener("blur", onResize);
return () => {
window.removeEventListener("pointerdown", onDown, true);
window.removeEventListener("resize", onResize);
window.removeEventListener("blur", onResize);
};
}, [open]);
const onTriggerKey = (e: React.KeyboardEvent) => {
if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Enter" || e.key === " ") {
e.preventDefault();
if (open) close(false);
else show(e.key === "ArrowUp" ? "last" : undefined);
}
};
const onMenuKey = (e: React.KeyboardEvent) => {
const k = e.key;
if (k === "ArrowDown") setActive((i) => step(i < 0 ? -1 : i, 1));
else if (k === "ArrowUp") setActive((i) => step(i < 0 ? 0 : i, -1));
else if (k === "Home") setActive(step(-1, 1));
else if (k === "End") setActive(step(0, -1));
else if (k === "Enter" || k === " ") pick(active);
else if (k === "Escape") close(true);
else if (k === "Tab") { close(true); return; }
else if (k.length === 1 && /\S/.test(k)) {
const ch = k.toLowerCase();
for (let n = 1; n <= options.length; n++) {
const i = (Math.max(active, 0) + n) % options.length;
if (!options[i]!.disabled && options[i]!.label.toLowerCase().startsWith(ch)) { setActive(i); break; }
}
} else return;
e.preventDefault();
e.stopPropagation();
};
return (
<>
<button
ref={btnRef}
type="button"
className={className}
title={title}
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? `${id}-lb` : undefined}
onClick={() => (open ? close(false) : show())}
onKeyDown={onTriggerKey}
>
{children ?? <span className="sm-val">{cur?.label ?? ""}</span>}
</button>
{open && createPortal(
<div
ref={menuRef}
id={`${id}-lb`}
className={`menu select-menu${menuClassName ? ` ${menuClassName}` : ""}`}
role="listbox"
aria-label={ariaLabel}
aria-activedescendant={active >= 0 ? `${id}-o${active}` : undefined}
tabIndex={-1}
data-select-menu=""
style={pos ? { left: pos.left, top: pos.top, minWidth: pos.minWidth, maxHeight: pos.maxHeight } : { left: -9999, top: 0, visibility: "hidden" }}
onKeyDown={onMenuKey}
>
{options.map((o, i) => (
<div
key={o.value}
id={`${id}-o${i}`}
data-i={i}
role="option"
aria-selected={o.value === value}
aria-disabled={o.disabled || undefined}
className={`mi sm-opt${i === active ? " on" : ""}${o.disabled ? " off" : ""}${o.danger ? " danger" : ""}${o.hint ? " has-hint" : ""}`}
onPointerMove={() => { if (!o.disabled && active !== i) setActive(i); }}
onClick={() => pick(i)}
>
<span className="sm-text">
<span className="sm-label">{o.label}</span>
{o.hint && <span className="sm-hint">{o.hint}</span>}
</span>
<span className="sm-check" aria-hidden="true">{o.value === value ? (
<svg width="12" height="12" viewBox="0 0 12 12"><path d="M2.5 6.2 5 8.6l4.5-5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
) : null}</span>
</div>
))}
</div>,
document.body,
)}
</>
);
}
@@ -1,17 +1,20 @@
// Settings dialog (§8.6): fields = §5.6; saved on change; version/data directory/PID at the bottom.
import { useEffect, useState } from "react";
import { Dialog } from "./Dialog";
import { SelectMenu } from "./SelectMenu";
import { ws } from "../main";
import { toast } from "./Toast";
import { permissionModes } from "../i18n/modes.js";
import { errMsg, t, tf } from "../i18n/index.js";
import type { ProviderInfo } from "../types/models.js";
import { useData } from "../stores/data.js";
import { IDLE_MAX, IDLE_MIN, parseArgsDraft, parseIdleDraft } from "./settingsFields.js";
import { applyTheme, embeddedInMagpie, normalizeThemeSetting } from "../layout/theme.js";
type Settings = {
defaultProvider?: string; defaultMode?: string; defaultEffort?: string | null;
sendKey?: string; runningSend?: string; showThinking?: boolean; density?: string;
theme?: string; idleCloseMinutes?: number; idleExitMinutes?: number;
defaultProvider?: string; defaultMode?: string;
sendKey?: string; runningSend?: string; showThinking?: boolean;
theme?: string; idleCloseMinutes?: number;
providerEnabled?: Record<string, boolean>;
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
[k: string]: unknown;
@@ -30,11 +33,24 @@ function statusLabel(p: ProviderInfo): string {
return t("settings.providerPending");
}
/** Refresh the provider list in the background (no forced re-detect of every agent) */
function refreshProviders(): void {
void ws.call("providers.list").then((list) => {
useData.setState({ providers: list as ProviderInfo[] });
}).catch(() => {});
}
export function SettingsDialog({ onClose, providers }: { onClose: () => void; providers: ProviderInfo[] }) {
const wsClient = useData((s) => s.ws);
const [s, setS] = useState<Settings | null>(null);
const [info, setInfo] = useState<{ version?: string; dataDir?: string; pid?: number }>({});
const [expanded, setExpanded] = useState<string | null>(null);
// Optimistic on/off per agent until providers.list catches up (B2)
const [enabledDraft, setEnabledDraft] = useState<Record<string, boolean>>({});
// Text drafts for the launch fields and the idle minutes, committed on blur / Enter (B5, B6)
const [exeDraft, setExeDraft] = useState<Record<string, string>>({});
const [argsDraft, setArgsDraft] = useState<Record<string, string>>({});
const [argsErr, setArgsErr] = useState<Record<string, boolean>>({});
const [idleDraft, setIdleDraft] = useState<string | null>(null);
const modes = permissionModes();
useEffect(() => {
@@ -42,26 +58,41 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
void ws.call("app.info").then((v) => setInfo(v as typeof info)).catch(() => {});
}, []);
const set = async (patch: Partial<Settings>) => {
const set = async (patch: Partial<Settings>): Promise<boolean> => {
const prev = s;
const next = { ...s, ...patch } as Settings;
setS(next);
if (patch.theme) applyTheme(patch.theme);
try {
await ws.call("settings.set", { patch });
window.dispatchEvent(new CustomEvent("settings-changed", { detail: next }));
if (patch.theme) applyTheme(patch.theme as string);
if (patch.providerEnabled && wsClient) {
void ws.call("providers.list", { refresh: true }).then((list) => {
useData.setState({ providers: list as ProviderInfo[] });
});
}
return true;
} catch (e) {
setS(prev);
if (patch.theme) applyTheme(prev?.theme);
toast(t("settings.failSave") + errMsg(e), true);
return false;
}
};
const toggleProvider = (id: string, on: boolean) => {
const toggleProvider = async (id: string, on: boolean) => {
setEnabledDraft((d) => ({ ...d, [id]: on }));
const cur = s?.providerEnabled ?? {};
void set({ providerEnabled: { ...cur, [id]: on } });
const prev = s;
const next = { ...s, providerEnabled: { ...cur, [id]: on } } as Settings;
setS(next);
try {
await ws.call("settings.set", { patch: { providerEnabled: next.providerEnabled } });
window.dispatchEvent(new CustomEvent("settings-changed", { detail: next }));
// Only this change is reflected locally; the list refreshes quietly (newly enabled agents get detected then)
if (!on) useData.setState((st) => ({ providers: st.providers.map((p) => (p.id === id ? { ...p, enabled: false } : p)) }));
refreshProviders();
} catch (e) {
setS(prev);
toast(t("settings.providerToggleFailed") + errMsg(e), true);
} finally {
setEnabledDraft((d) => { const n = { ...d }; delete n[id]; return n; });
}
};
const redetect = () => {
@@ -71,14 +102,45 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
}).catch((e) => toast(errMsg(e), true));
};
const setLaunch = (id: string, patch: { executable?: string; args?: string[] }) => {
const setLaunch = async (id: string, patch: { executable?: string; args?: string[] }) => {
const cur = { ...(s?.providerCommand ?? {}) };
cur[id] = { ...cur[id], ...patch };
void set({ providerCommand: cur });
const merged = { ...cur[id], ...patch };
if (!merged.executable) delete merged.executable;
if (!merged.args || merged.args.length === 0) delete merged.args;
const same = JSON.stringify(cur[id] ?? {}) === JSON.stringify(merged);
if (same) return;
cur[id] = merged;
if (await set({ providerCommand: cur })) refreshProviders();
};
const providerStatus = (p: ProviderInfo) => {
if (p.enabled === false) return { dot: "off", text: t("settings.providerOff") };
const commitExe = (id: string) => {
const v = exeDraft[id];
if (v === undefined) return;
void setLaunch(id, { executable: v.trim() || undefined });
setExeDraft((d) => { const n = { ...d }; delete n[id]; return n; });
};
const commitArgs = (id: string) => {
const v = argsDraft[id];
if (v === undefined) return;
const parsed = parseArgsDraft(v);
if (parsed === null) { setArgsErr((e) => ({ ...e, [id]: true })); return; }
setArgsErr((e) => ({ ...e, [id]: false }));
void setLaunch(id, { args: parsed });
setArgsDraft((d) => { const n = { ...d }; delete n[id]; return n; });
};
const commitIdle = () => {
if (idleDraft === null) return;
const n = parseIdleDraft(idleDraft);
if (n === null) return; // stays in the field with the error shown
setIdleDraft(null);
if (n !== s?.idleCloseMinutes) void set({ idleCloseMinutes: n });
};
const providerStatus = (p: ProviderInfo, on: boolean) => {
if (!on) return { dot: "off", text: t("settings.providerOff") };
if (p.enabled === false) return { dot: "pending", text: t("settings.providerPending") };
if (!p.available) return { dot: "off", text: p.reason ?? t("common.notDetected") };
const n = p.models?.length ?? 0;
const base = statusLabel(p);
@@ -88,27 +150,30 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
if (!s) return <Dialog title={t("settings.title")} onClose={onClose}><div className="dlg-hint">{t("common.loading")}</div></Dialog>;
const row = (label: string, el: React.ReactNode) => (
<div className="dlg-row"><label>{label}</label>{el}</div>
const row = (label: string, el: React.ReactNode, hint?: string) => (
<div className="dlg-row"><label>{label}</label>{el}{hint && <div className="dlg-hint" style={{ marginTop: 4 }}>{hint}</div>}</div>
);
const idleBad = idleDraft !== null && parseIdleDraft(idleDraft) === null;
const enterCommits = (fn: () => void) => (e: React.KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); fn(); } };
return (
<Dialog title={t("settings.title")} onClose={onClose} wide
footer={<button className="btn primary" onClick={onClose}>{t("common.done")}</button>}>
{row(t("settings.defaultAgent"), (
<select className="tinput" value={s.defaultProvider ?? "claude"} onChange={(e) => void set({ defaultProvider: e.target.value })}>
{providers.map((p) => <option key={p.id} value={p.id} disabled={!providerUsable(p)}>{p.name}{!providerUsable(p) ? t("common.notInstalled") : ""}</option>)}
</select>
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.defaultAgent")}
value={s.defaultProvider ?? "claude"} onChange={(v) => void set({ defaultProvider: v })}
options={providers.map((p) => ({ value: p.id, label: p.name + (!providerUsable(p) ? t("common.notInstalled") : ""), disabled: !providerUsable(p) }))} />
))}
<div className="dlg-row dlg-row-top">
<label>{t("settings.providers")}</label>
<div className="provider-list">
<button type="button" className="btn sm provider-redetect" onClick={redetect}>{t("settings.providerRedetect")}</button>
{providers.map((p) => {
const st = providerStatus(p);
const on = p.enabled !== false;
const on = enabledDraft[p.id] ?? (s.providerEnabled?.[p.id] ?? p.enabled !== false);
const st = providerStatus(p, on);
const open = expanded === p.id;
const cmd = s.providerCommand?.[p.id];
const argsText = argsDraft[p.id] ?? (cmd?.args?.length ? JSON.stringify(cmd.args) : "");
return (
<div key={p.id} className={`provider-row${open ? " open" : ""}`}>
<button type="button" className="provider-head" onClick={() => setExpanded(open ? null : p.id)}>
@@ -120,27 +185,30 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
<span className="mi-caret">{open ? "▾" : "▸"}</span>
</button>
<label className="provider-switch" title={p.name}>
<input type="checkbox" checked={on} onChange={(e) => toggleProvider(p.id, e.target.checked)} />
<input type="checkbox" checked={on} disabled={enabledDraft[p.id] !== undefined}
onChange={(e) => void toggleProvider(p.id, e.target.checked)} />
</label>
{open && (
<div className="provider-detail">
{p.bin && <div className="dlg-hint">{p.bin}{p.version ? ` · ${p.version}` : ""}</div>}
{p.installHint && (
<div className="provider-hint-row">
<span className="dlg-hint">{p.installHint}</span>
<code className="dlg-hint">{p.installHint}</code>
<button type="button" className="te-files" onClick={() => void navigator.clipboard?.writeText(p.installHint ?? "").then(() => toast(t("common.copied")))}>{t("settings.providerCopyHint")}</button>
</div>
)}
<div className="dlg-hint">{t("settings.providerLaunchCmd")}</div>
<input className="tinput" placeholder={t("settings.providerLaunchExe")} value={cmd?.executable ?? ""}
onChange={(e) => setLaunch(p.id, { executable: e.target.value || undefined })} />
<input className="tinput" placeholder='["--acp"]' value={cmd?.args ? JSON.stringify(cmd.args) : ""}
onChange={(e) => {
try {
const v = e.target.value.trim();
setLaunch(p.id, { args: v ? (JSON.parse(v) as string[]) : undefined });
} catch { /* typing */ }
}} />
<input className="tinput" placeholder={t("settings.providerLaunchExe")} aria-label={t("settings.providerLaunchExe")}
value={exeDraft[p.id] ?? cmd?.executable ?? ""}
onChange={(e) => { const v = e.target.value; setExeDraft((d) => ({ ...d, [p.id]: v })); }}
onBlur={() => commitExe(p.id)} onKeyDown={enterCommits(() => commitExe(p.id))} />
<input className={`tinput${argsErr[p.id] ? " err" : ""}`} placeholder='["--foo"]' aria-label={t("settings.providerLaunchArgs")}
value={argsText}
onChange={(e) => { const v = e.target.value; setArgsDraft((d) => ({ ...d, [p.id]: v })); if (argsErr[p.id]) setArgsErr((x) => ({ ...x, [p.id]: parseArgsDraft(v) === null })); }}
onBlur={() => commitArgs(p.id)} onKeyDown={enterCommits(() => commitArgs(p.id))} />
<div className={`dlg-hint${argsErr[p.id] ? " err" : ""}`}>
{argsErr[p.id] ? t("settings.providerArgsInvalid") : t("settings.providerLaunchArgsHint")}
</div>
</div>
)}
</div>
@@ -149,29 +217,31 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
</div>
</div>
{row(t("settings.defaultMode"), (
<select className="tinput" value={s.defaultMode ?? "default"} onChange={(e) => void set({ defaultMode: e.target.value })}>
{modes.map((m) => <option key={m.id} value={m.id}>{m.label}</option>)}
</select>
))}
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.defaultMode")}
value={s.defaultMode ?? "default"} onChange={(v) => void set({ defaultMode: v })}
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc }))}>
<span className="sm-val">{(() => { const m = modes.find((x) => x.id === (s.defaultMode ?? "default")); return m ? `${m.label} — ${m.desc}` : ""; })()}</span>
</SelectMenu>
), t("settings.defaultModeHint"))}
{row(t("settings.theme"), (
<select className="tinput" value={s.theme ?? "auto"} onChange={(e) => void set({ theme: e.target.value })}>
<option value="auto">{t("settings.themeAuto")}</option>
<option value="light">{t("settings.themeLight")}</option>
<option value="dark">{t("settings.themeDark")}</option>
</select>
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.theme")}
value={normalizeThemeSetting(s.theme)} onChange={(v) => void set({ theme: v })}
options={[
{ value: "auto", label: embeddedInMagpie() ? t("settings.themeMagpie") : t("settings.themeAuto") },
{ value: "light", label: t("settings.themeLight") },
{ value: "dark", label: t("settings.themeDark") },
]} />
))}
{row(t("settings.sendKey"), (
<select className="tinput" value={s.sendKey ?? "enter"} onChange={(e) => void set({ sendKey: e.target.value })}>
<option value="enter">{t("settings.sendEnter")}</option>
<option value="ctrlEnter">{t("settings.sendCtrl")}</option>
</select>
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.sendKey")}
value={s.sendKey ?? "enter"} onChange={(v) => void set({ sendKey: v })}
options={[{ value: "enter", label: t("settings.sendEnter") }, { value: "ctrlEnter", label: t("settings.sendCtrl") }]} />
))}
{row(t("settings.runningSend"), (
<select className="tinput" value={s.runningSend ?? "queue"} onChange={(e) => void set({ runningSend: e.target.value })}>
<option value="queue">{t("settings.queue")}</option>
<option value="steer">{t("settings.steer")}</option>
</select>
))}
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.runningSend")}
value={s.runningSend ?? "queue"} onChange={(v) => void set({ runningSend: v })}
options={[{ value: "queue", label: t("settings.queue") }, { value: "steer", label: t("settings.steer") }]} />
), t("settings.steerHint"))}
{row(t("settings.thinking"), (
<label style={{ display: "flex", gap: 8, alignItems: "center", fontSize: "var(--fs-m)", color: "var(--fg)" }}>
<input type="checkbox" checked={s.showThinking !== false} onChange={(e) => void set({ showThinking: e.target.checked })} />
@@ -180,12 +250,14 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
))}
{row(t("settings.idleClose"), (
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<input className="tinput" type="number" min={5} max={240} style={{ width: 90 }}
value={s.idleCloseMinutes ?? 30}
onChange={(e) => void set({ idleCloseMinutes: Math.max(5, Number(e.target.value) || 30) })} />
<input className={`tinput${idleBad ? " err" : ""}`} type="number" min={IDLE_MIN} max={IDLE_MAX} step={1} style={{ width: 90, flex: "none" }}
aria-label={t("settings.idleClose")}
value={idleDraft ?? String(s.idleCloseMinutes ?? 30)}
onChange={(e) => setIdleDraft(e.target.value)}
onBlur={commitIdle} onKeyDown={enterCommits(commitIdle)} />
<span className="dlg-hint">{t("settings.idleMinutes")}</span>
</div>
))}
), idleBad ? t("settings.idleInvalid") : undefined)}
<div className="msep" />
<div className="dlg-hint">
{tf("settings.versionLine", { ver: info.version ?? "?", pid: info.pid ?? "?" })}<br />
@@ -195,12 +267,6 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
);
}
export function applyTheme(theme: string) {
const preferDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches;
document.documentElement.dataset.theme =
theme === "light" || theme === "dark" ? theme : preferDark ? "dark" : "light";
}
export type LiveSettings = {
sendKey: "enter" | "ctrlEnter";
runningSend: "queue" | "steer";
@@ -91,7 +91,6 @@ export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
provider,
model: null,
mode: (s.defaultMode as string) ?? "default",
effort: (s.defaultEffort as string | null) ?? null,
})) as ThreadMeta;
ui.select(projectId, t.id);
} catch (e) {
@@ -155,7 +154,7 @@ export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
<>
<div className="sb-row">
<button className="sb-new" onClick={() => setNewProjOpen(true)}>
<Icon name="plus" /> {tr("sidebar.newProject")}
<span className="sb-new-tile"><Icon name="plus" size={12} /></span>{tr("sidebar.newProject")}
</button>
<button className="ibtn" title={tr("common.settings")} onClick={() => window.dispatchEvent(new CustomEvent("open-settings"))}>
<Icon name="settings" />
@@ -164,8 +163,9 @@ export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
<Icon name="search" />
</button>
</div>
<div className="sb-row" style={{ height: 32, paddingTop: 0 }}>
<div className="sb-row sb-row-search">
<div className="sb-search">
<Icon name="search" size={13} />
<input
ref={filterRef}
placeholder={tr("sidebar.filterPlaceholder")}
@@ -10,6 +10,7 @@ import { normalizeHunks } from "../timeline/diffHunks";
import { fmtDur, fmtTokens, fmtCost } from "../util/format";
import { useUi } from "../stores/ui";
import { localizeDaemonMessage, t, tf } from "../i18n/index.js";
import { toast } from "./Toast";
const token = () => getToken();
@@ -117,7 +118,7 @@ function ToolStepRow({ s }: { s: ToolStep }) {
<div className="ts">
<button className="ts-head" onClick={() => hasDetail && setOpen(!open)}>
<span className={`ts-ic ${cls}`}>{icon}</span>
<span className="ts-title">{s.title}</span>
<span className="ts-title">{s.title || toolKind(s.kind)}</span>
{s.durationMs != null && <span className="ts-meta">{fmtDur(s.durationMs)}</span>}
{s.exitCode != null && s.exitCode !== 0 && <span className="ts-meta err">exit {s.exitCode}</span>}
</button>
@@ -289,7 +290,7 @@ export function QuestionItem({ it, threadId }: { it: Extract<DisplayItem, { kind
}
// ---------- error / turn end ----------
export function TurnEndItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "turnend" }>; onRetry?: () => void }) {
export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayItem, { kind: "turnend" }>; onRetry?: () => void; replyText?: string }) {
const ui = useUi();
const [showErr, setShowErr] = useState(false);
if (it.status === "failed") {
@@ -316,7 +317,17 @@ export function TurnEndItem({ it, onRetry }: { it: Extract<DisplayItem, { kind:
if (it.status === "interrupted") parts.push(t("timeline.interrupted"));
return (
<div className="te">
<span>{parts.join(" · ") || it.status}</span>
{parts.length > 0 && <span className="te-meta">{parts.join(" · ")}</span>}
{replyText && (
<button className="te-act" title={t("common.copy")} onClick={() => void copyText(replyText).then(() => toast(t("common.copied")))}>
<Icon name="copy" size={13} /><span>{t("common.copy")}</span>
</button>
)}
{onRetry && (
<button className="te-act" title={t("common.retry")} onClick={onRetry}>
<Icon name="refresh" size={13} /><span>{t("common.retry")}</span>
</button>
)}
{it.filesChanged != null && it.filesChanged > 0 && (
<button className="te-files" onClick={() => ui.openPanel("changes")}>
{tf("timeline.filesChanged", { n: it.filesChanged })}
@@ -327,8 +338,8 @@ export function TurnEndItem({ it, onRetry }: { it: Extract<DisplayItem, { kind:
}
// ---------- dispatch ----------
export function TimelineRow({ it, threadId, onEditResend, onRetryLast }: {
it: DisplayItem; threadId: string;
export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText }: {
it: DisplayItem; threadId: string; replyText?: string;
onEditResend?: (text: string) => void;
onRetryLast?: () => void;
}) {
@@ -342,7 +353,7 @@ export function TimelineRow({ it, threadId, onEditResend, onRetryLast }: {
case "permission": return <PermissionItem it={it} threadId={threadId} />;
case "question": return <QuestionItem it={it} threadId={threadId} />;
case "notice": return <div className={`nt ${it.level}`}>{localizeDaemonMessage(it.message)}</div>;
case "turnend": return <TurnEndItem it={it} onRetry={onRetryLast} />;
case "turnend": return <TurnEndItem it={it} onRetry={onRetryLast} replyText={replyText} />;
case "gone": return null;
default: return null;
}
@@ -104,7 +104,7 @@ export function Topbar({ pendingCount }: { pendingCount: number }) {
) : (
<span className="tb-title ghost">{project ? t("topbar.pickThread") : t("app.title")}</span>
)}
{pill && <span className={`tb-pill ${pill.cls}`}>{pill.text}</span>}
{pill && <span className={`tb-pill ${pill.cls}`}>{pill.cls === "run" && <span className="tb-pill-dot" />}{pill.text}</span>}
<div className="tb-right">
{thread?.model && <span className="tb-model">{thread.model}</span>}
{panelBtns.map((b) => (
@@ -0,0 +1,23 @@
// Settings text fields (pure, unit-tested): parsed when the field is committed, not on every keystroke.
export const IDLE_MIN = 5;
export const IDLE_MAX = 240;
/** Args field (B5): a JSON array of strings, or empty = no extra args. null = invalid. */
export function parseArgsDraft(text: string): string[] | undefined | null {
const v = text.trim();
if (!v) return undefined;
try {
const arr = JSON.parse(v) as unknown;
if (Array.isArray(arr) && arr.every((x) => typeof x === "string")) return arr as string[];
} catch { /* fallthrough */ }
return null;
}
/** Idle minutes field (B6): whole number 5–240, else null */
export function parseIdleDraft(text: string): number | null {
const v = text.trim();
if (!/^\d+$/.test(v)) return null;
const n = Number(v);
return n >= IDLE_MIN && n <= IDLE_MAX ? n : null;
}
+50 -18
View File
@@ -18,7 +18,8 @@ export const messages: Record<LocaleId, MessageTree> = {
},
boot: {
connecting: "正在连接…", serviceDown: "本地服务未启动", retry: "重试",
reconnecting: "连接中断,正在重连…", starting: "正在启动本地服务…",
reconnecting: "连接中断,正在重新连接…", starting: "正在启动本地服务…",
reopening: "本地服务已重启,正在重新连接…",
},
topbar: {
pickThread: "选择一个对话", sidebar: "侧栏(Ctrl+B)", clickRename: "点击改名",
@@ -52,20 +53,24 @@ export const messages: Record<LocaleId, MessageTree> = {
chat: {
newInProject: "在 {name} 中新建对话", emptyHint: "对话还没有消息,下面输入开始。",
jumpBottom: "回到底部", emptyPlaceholder: "输入任务,Enter 发送", autoNewThread: "将自动新建对话",
pickProjectTitle: "选择一个项目", pickProjectSub: "在左侧选一个项目,或新建一个,然后开始对话。",
failSend: "发送失败:",
},
composer: {
waitPerm: "等待你确认上面的授权请求", queuePlaceholder: "输入排队消息(Ctrl+Enter 插话)",
queuePlaceholderNoSteer: "继续补充要求,回车排队发送…",
steerUnsupported: "{agent} 不支持插话:运行中发的消息会排队,本回合结束后再发送。",
queuedToast: "已排队:本回合结束后发送", steeredToast: "已插话",
inputPlaceholder: "输入消息…", bypassWarn: "Bypass:Agent 的所有操作不会再问你。",
imagesByPath: "{agent} 不能直接看图片:会把图片的文件路径发给它(它能用文件工具打开)。",
agentModel: "Agent & model", agentLocked: "Agent (locked)", agent: "Agent",
model: "Model", searchModel: "Search", searchAllModels: "Search models…", providers: "Providers",
model: "Model", searchModel: "Search", searchAllModels: "Search models…", providers: "Agent",
agentLockedHint: "已开始的对话不能更换 Agent;要用别的 Agent 请新建对话。",
providersLoading: "正在检测 Agent…", moreModels: "还有 {n} 个模型,请用上方搜索",
pickModel: "选择模型", noModelMatch: "没有匹配的模型",
// Options below the composer are English throughout (as in Paseo); hint text stays Chinese
defaultModel: "Default", defaultEffort: "Default", defaultEffortNamed: "Default ({level})",
effortTitle: "思考强度", attachTitle: "附件(图片/文本)",
defaultModel: "默认", defaultEffort: "默认", defaultEffortNamed: "默认({level})",
effortTitle: "思考强度", modeTitle: "权限模式", attachTitle: "附件(图片/文本)",
failSwitchAgent: "切换 Agent 失败:", failSend: "发送失败:", failUpload: "附件上传失败:",
uploadFailed: "上传失败", steerTag: "插话",
cursorAutoReview: "自动接受权限提示(Auto-review)",
@@ -74,27 +79,39 @@ export const messages: Record<LocaleId, MessageTree> = {
slashNoCommands: "该 Agent 未提供命令",
slashLoading: "正在获取命令…",
mode: {
plan: { label: "Plan Mode", desc: "只分析代码库,不执行工具或修改" },
default: { label: "Always Ask", desc: "首次使用工具时会请求授权" },
acceptEdits: { label: "Accept File Edits", desc: "自动批准编辑类工具,不再逐项询问" },
bypass: { label: "Bypass", desc: "跳过所有授权提示(请谨慎使用)" },
plan: { label: "规划", desc: "只分析代码库,不执行工具或修改" },
default: { label: "每次询问", desc: "首次使用工具时会请求授权" },
acceptEdits: { label: "接受编辑", desc: "自动批准编辑类工具,不再逐项询问" },
bypass: { label: "全部放行", desc: "跳过所有授权提示(请谨慎使用)" },
cursorAgent: { label: "Agent", desc: "完整 Agent:可读写、执行工具" },
cursorPlan: { label: "Plan", desc: "只读规划:分析并提出方案,不改文件" },
cursorAsk: { label: "Ask", desc: "问答模式:解释与讨论,只读" },
cursorPlan: { label: "规划", desc: "只读规划:分析并提出方案,不改文件" },
cursorAsk: { label: "问答", desc: "问答模式:解释与讨论,只读" },
},
// Agent-specific mode names reported by the daemon
agentMode: {
"Plan": "规划", "Build": "构建", "Ask": "询问", "Code": "编码", "Agent": "Agent",
"Allow All": "全部允许", "Bypass Permissions": "跳过授权", "Read Only": "只读", "Auto": "自动", "Full Access": "完全访问",
},
effort: { low: "低", medium: "中", high: "高", xhigh: "超高", max: "最高", minimal: "最低", none: "关闭" },
},
settings: {
title: "设置", defaultAgent: "默认 Agent", defaultMode: "默认权限模式", theme: "主题",
themeAuto: "跟随系统", themeLight: "浅色", themeDark: "深色",
themeAuto: "跟随系统", themeMagpie: "跟随 Magpie", themeLight: "浅色", themeDark: "深色",
sendKey: "发送键", sendEnter: "Enter 发送 / Shift+Enter 换行", sendCtrl: "Ctrl+Enter 发送 / Enter 换行",
runningSend: "运行中再发送", queue: "排队(发完自动继续)", steer: "插话(立即打断当前思路)",
steerHint: "插话只对支持的 Agent 生效(目前是 Codex);其他 Agent 仍会排队,输入框下方会提示。",
defaultModeHint: "新对话使用;每个 Agent 会换成自己最接近的模式(例如 OpenCode 只有 Plan / Build,Build 会直接改文件)。",
thinking: "思考过程", showThinking: "显示 Agent 的思考/推理内容",
idleClose: "空闲回收", idleMinutes: "分钟后自动关闭空闲会话",
idleClose: "空闲回收", idleMinutes: "分钟后自动关闭空闲会话(5–240;最多保留 3 个空闲 Agent 进程)",
idleInvalid: "请输入 5 到 240 之间的整数",
versionLine: "版本 v{ver} · PID {pid}", dataDir: "数据目录:", failSave: "保存失败:",
providers: "Providers", providerOn: "可用", providerOff: "已禁用", providerPending: "尚未接入",
providers: "Agent", providerOn: "可用", providerOff: "已禁用", providerPending: "尚未接入",
providerVerified: "已验证", providerExperimental: "实验性", providerPlanned: "未接入",
providerModels: "{n} 个 Model", providerRedetect: "重新检测", providerCopyHint: "复制安装提示",
providerLaunchCmd: "自定义启动(高级)", providerLaunchExe: "可执行文件路径", providerLaunchArgs: "参数(JSON 数组)",
providerLaunchCmd: "自定义启动(高级)", providerLaunchExe: "可执行文件路径(留空 = 自动查找)", providerLaunchArgs: "附加参数(JSON 数组)",
providerLaunchArgsHint: "追加在内置参数之后,例如 [\"--foo\"];回车或离开输入框时保存。新对话生效。",
providerArgsInvalid: "需要 JSON 字符串数组,例如 [\"--foo\"]",
providerToggleFailed: "切换失败,已恢复:",
},
palette: {
aria: "命令面板", placeholder: "搜索对话、项目或动作…", noMatch: "没有匹配项",
@@ -141,6 +158,7 @@ export const messages: Record<LocaleId, MessageTree> = {
api: {
requestFailed: "请求失败", bad_params: "参数不正确", not_found: "未找到",
busy: "正忙,请稍后再试", bad_path: "路径无效",
connClosed: "连接中断", notConnected: "连接未建立", timeout: "请求超时",
},
},
en: {
@@ -158,6 +176,7 @@ export const messages: Record<LocaleId, MessageTree> = {
boot: {
connecting: "Connecting…", serviceDown: "Local service is not running", retry: "Retry",
reconnecting: "Connection lost. Reconnecting…", starting: "Starting local service…",
reopening: "The local service restarted. Reconnecting…",
},
topbar: {
pickThread: "Select a conversation", sidebar: "Sidebar (Ctrl+B)", clickRename: "Click to rename",
@@ -196,9 +215,13 @@ export const messages: Record<LocaleId, MessageTree> = {
newInProject: "New conversation in {name}", emptyHint: "No messages yet — type below to start.",
jumpBottom: "Jump to bottom", emptyPlaceholder: "Describe a task — Enter to send",
autoNewThread: "A new conversation will be created", failSend: "Send failed: ",
pickProjectTitle: "Pick a project", pickProjectSub: "Choose a project in the sidebar, or create one, to start a conversation.",
},
composer: {
waitPerm: "Waiting for your approval above", queuePlaceholder: "Queue a message (Ctrl+Enter to steer)",
queuePlaceholderNoSteer: "Add to the task — Enter queues it…",
steerUnsupported: "{agent} can't steer: messages sent while it runs are queued and sent after this turn.",
queuedToast: "Queued — sends after this turn", steeredToast: "Steered",
inputPlaceholder: "Message…", bypassWarn: "Bypass: the agent will not ask for permission.",
imagesByPath: "{agent} can't see images directly: it gets the image's file path instead (it can open it with its file tools).",
agentModel: "Agent & model", agentLocked: "Agent (locked after first message)", agent: "Agent",
@@ -207,7 +230,7 @@ export const messages: Record<LocaleId, MessageTree> = {
providersLoading: "Detecting agents…", moreModels: "{n} more models — use search above",
pickModel: "Choose model", noModelMatch: "No matching models",
defaultModel: "Default", defaultEffort: "Default", defaultEffortNamed: "Default ({level})",
effortTitle: "Reasoning effort", attachTitle: "Attachments (images / text)",
effortTitle: "Reasoning effort", modeTitle: "Permission mode", attachTitle: "Attachments (images / text)",
failSwitchAgent: "Could not switch agent: ", failSend: "Send failed: ",
failUpload: "Upload failed: ", uploadFailed: "Upload failed", steerTag: "Steer",
cursorAutoReview: "Auto accept permission prompts",
@@ -224,20 +247,28 @@ export const messages: Record<LocaleId, MessageTree> = {
cursorPlan: { label: "Plan", desc: "Read-only planning and analysis" },
cursorAsk: { label: "Ask", desc: "Q&A style explanations (read-only)" },
},
agentMode: {},
effort: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max", minimal: "Minimal", none: "Off" },
},
settings: {
title: "Settings", defaultAgent: "Default agent", defaultMode: "Default permission mode", theme: "Theme",
themeAuto: "System", themeLight: "Light", themeDark: "Dark",
themeAuto: "System", themeMagpie: "Follow Magpie", themeLight: "Light", themeDark: "Dark",
sendKey: "Send shortcut", sendEnter: "Enter sends / Shift+Enter newline",
sendCtrl: "Ctrl+Enter sends / Enter newline",
runningSend: "While running", queue: "Queue (run after current turn)", steer: "Steer (interrupt now)",
steerHint: "Steer only works for agents that support it (Codex today); other agents still queue, and the composer says so.",
defaultModeHint: "For new conversations. Each agent maps it to its own nearest mode (OpenCode only has Plan / Build, and Build edits without asking).",
thinking: "Reasoning", showThinking: "Show agent reasoning/thinking",
idleClose: "Idle cleanup", idleMinutes: "minutes before closing idle sessions",
idleClose: "Idle cleanup", idleMinutes: "minutes before closing idle sessions (5–240; at most 3 idle agent processes are kept)",
idleInvalid: "Enter a whole number from 5 to 240",
versionLine: "Version v{ver} · PID {pid}", dataDir: "Data: ", failSave: "Could not save: ",
providers: "Providers", providerOn: "Available", providerOff: "Disabled", providerPending: "Not wired yet",
providerVerified: "Verified", providerExperimental: "Experimental", providerPlanned: "Planned",
providerModels: "{n} models", providerRedetect: "Re-detect", providerCopyHint: "Copy install hint",
providerLaunchCmd: "Custom launch (advanced)", providerLaunchExe: "Executable path", providerLaunchArgs: "Args (JSON array)",
providerLaunchCmd: "Custom launch (advanced)", providerLaunchExe: "Executable path (empty = find it automatically)", providerLaunchArgs: "Extra args (JSON array)",
providerLaunchArgsHint: "Added after the built-in arguments, e.g. [\"--foo\"]. Saved on Enter or when you leave the field. Applies to new sessions.",
providerArgsInvalid: "Needs a JSON array of strings, e.g. [\"--foo\"]",
providerToggleFailed: "Could not switch it; reverted: ",
},
palette: {
aria: "Command palette", placeholder: "Search conversations, projects, actions…", noMatch: "No matches",
@@ -284,6 +315,7 @@ export const messages: Record<LocaleId, MessageTree> = {
api: {
requestFailed: "Request failed", bad_params: "Invalid parameters", not_found: "Not found",
busy: "Busy — try again later", bad_path: "Invalid path",
connClosed: "Connection lost", notConnected: "Not connected", timeout: "Request timed out",
},
},
};
+13 -1
View File
@@ -30,5 +30,17 @@ export function composerModeOptions(
// As in Paseo: when an Agent has its own mode names, use them (Copilot shows Agent rather than Always Ask)
return base
.filter((m) => allowed.includes(m.id))
.map((m) => (labels?.[m.id] ? { ...m, label: labels[m.id]! } : m));
.map((m) => (labels?.[m.id] ? { ...m, label: agentModeLabel(labels[m.id]!) } : m));
}
/** An Agent's own mode name (from the daemon, English) in the UI language when we know it */
export function agentModeLabel(name: string): string {
const v = t(`composer.agentMode.${name}`);
return v.startsWith("composer.agentMode.") ? name : v;
}
/** Reasoning effort id → short label in the UI language (unknown ids are shown as given) */
export function effortLabel(id: string, fallback?: string): string {
const v = t(`composer.effort.${id}`);
return v.startsWith("composer.effort.") ? fallback ?? id : v;
}
@@ -1,4 +1,9 @@
/** Parse the ?tokens= (base64 JSON) passed by boot.js and write --magpie-* CSS variables */
/** Magpie accent tokens (accent, accent-soft, accent-fg, and a bare --accent*) are dropped: the page's accent is monochrome on purpose. */
export function isAccentToken(key: string): boolean {
return /^accent(-|$)/i.test(key.replace(/^--/, "").replace(/^magpie-/i, ""));
}
/** Parse the ?tokens= (base64 JSON) passed by boot.js and write --magpie-* CSS variables (neutrals, fonts, semantic colors; never the accent) */
export function applyMagpieTokensFromSearch(search: string): void {
const raw = new URLSearchParams(search).get("tokens");
if (!raw) return;
@@ -11,7 +16,7 @@ export function applyMagpieTokensFromSearch(search: string): void {
const root = document.documentElement;
for (const [k, v] of Object.entries(obj)) {
const s = String(v ?? "").trim();
if (!s) continue;
if (!s || isAccentToken(k)) continue;
const varName = k.startsWith("--") ? k : k.startsWith("magpie-") ? `--${k}` : `--magpie-${k}`;
root.style.setProperty(varName, s);
}
@@ -0,0 +1,52 @@
// Theme (B4). The saved setting: "auto" = follow the host (Magpie's light/dark when the page runs inside Magpie, the OS otherwise),
// "light" / "dark" = always that one, even inside Magpie. Magpie's injected colors (--magpie-bg/fg/…) only apply while the page
// shows the same light/dark as Magpie (data-host-colors); otherwise our own palette is used. Magpie's font always applies.
export type ThemeSetting = "auto" | "light" | "dark";
export type Theme = "light" | "dark";
let hostTheme: Theme | null = null;
let current: ThemeSetting = "auto";
let mq: MediaQueryList | null = null;
function osTheme(): Theme {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
export function normalizeThemeSetting(v: unknown): ThemeSetting {
return v === "light" || v === "dark" ? v : "auto";
}
/** What the page shows for a setting, given the host's theme (null outside Magpie) and the OS's */
export function resolveTheme(setting: ThemeSetting, host: Theme | null, os: Theme): { theme: Theme; hostColors: boolean } {
const theme = setting === "light" || setting === "dark" ? setting : host ?? os;
return { theme, hostColors: host !== null && theme === host };
}
/** Startup: ?theme= is Magpie's light/dark (boot.js passes it). Shows the host theme until the saved setting arrives. */
export function initTheme(search: string): void {
const p = new URLSearchParams(search).get("theme");
hostTheme = p === "light" || p === "dark" ? p : null;
applyTheme("auto");
if (typeof window !== "undefined" && window.matchMedia) {
mq = window.matchMedia("(prefers-color-scheme: dark)");
mq.addEventListener?.("change", () => applyTheme(current));
}
}
/** Inside Magpie (it passed its theme): the "auto" option reads "Follow Magpie" */
export function embeddedInMagpie(): boolean {
return hostTheme !== null;
}
export function applyTheme(setting: unknown): void {
current = normalizeThemeSetting(setting);
const { theme, hostColors } = resolveTheme(current, hostTheme, osTheme());
const root = document.documentElement;
root.dataset.theme = theme;
if (hostColors) root.dataset.hostColors = "1";
else delete root.dataset.hostColors;
}
export function currentTheme(): Theme {
return document.documentElement.dataset.theme === "dark" ? "dark" : "light";
}
+7 -10
View File
@@ -6,6 +6,8 @@ import "./styles/chat.css";
import "./styles/composer.css";
import { createRoot } from "react-dom/client";
import { applyMagpieTokensFromSearch } from "./layout/applyMagpieTokens.js";
import { applyTheme, initTheme } from "./layout/theme.js";
import { goBackToMagpie, watchReconnect } from "./api/backToMagpie.js";
import { initLocale, getLocale } from "./i18n/index.js";
import { WsClient } from "./api/ws";
import { useConnection } from "./stores/connection";
@@ -17,14 +19,11 @@ import { DebugApp } from "./Debug";
import { getToken } from "./api/token";
const token = getToken();
// Theme: ?theme=light|dark first, otherwise follow the system (settings.theme override happens after hydrate, completed in P2-6)
// Theme: Magpie's ?theme= (or the OS) until the saved setting arrives; an explicit Light/Dark setting then wins (B4)
const params = new URLSearchParams(location.search);
const themeParam = params.get("theme");
initLocale(location.search);
applyMagpieTokensFromSearch(location.search);
const preferDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches;
document.documentElement.dataset.theme =
themeParam === "light" || themeParam === "dark" ? themeParam : preferDark ? "dark" : "light";
initTheme(location.search);
export const ws = new WsClient(token, getLocale());
// For the debug page (P1-8) and e2e driving: expose the authenticated client and internal stores.
@@ -34,6 +33,8 @@ void import("./stores/timeline").then((m) => {
(window as unknown as { __tl?: unknown }).__tl = m.useTimeline;
});
ws.onState((s) => useConnection.getState().set({ state: s }));
// Daemon gone for 5s (usually: Magpie restarted the plugin host) → back through the Magpie page to the new gate
watchReconnect(ws, () => { goBackToMagpie(); });
ws.connect();
ws.waitHello().then(async (h) => {
useConnection.getState().set({ version: (h as { version?: string }).version ?? null });
@@ -42,11 +43,7 @@ ws.waitHello().then(async (h) => {
try {
const s = (await ws.call("settings.get")) as Record<string, unknown>;
useUi.getState().hydrate(s);
// settings.theme override (only without a ?theme= parameter)
if (!themeParam) {
const { applyTheme } = await import("./components/Settings");
applyTheme((s.theme as string) ?? "auto");
}
applyTheme(s.theme);
} catch {}
// Fetch the project/conversation/provider lists and subscribe to the sidebar channel
await useData.getState().bind(ws);
+22 -6
View File
@@ -9,7 +9,7 @@
* { box-sizing: border-box; }
#root { height: 100%; }
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
input, textarea, select { font: inherit; color: inherit; }
input, textarea { font: inherit; color: inherit; }
a { color: var(--accent); }
:focus-visible { outline: 2px solid color-mix(in oklab, var(--accent) 55%, var(--bg)); outline-offset: -1px; }
}
@@ -55,10 +55,6 @@
.tinput.err { border-color: var(--danger); }
.tinput::placeholder { color: var(--muted); }
textarea.tinput { height: auto; min-height: 60px; padding: 6px 10px; resize: vertical; }
select.tinput { padding-right: 26px; appearance: none;
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-position: calc(100% - 14px) 50%, calc(100% - 10px) 50%; background-size: 4px 4px; background-repeat: no-repeat;
}
/* Dropdown/context menus and popovers */
.menu {
@@ -123,7 +119,7 @@ select.tinput { padding-right: 26px; appearance: none;
/* Status dot */
.dot { width: 6px; height: 6px; border-radius: 50%; flex: none; background: var(--muted); }
.dot.run { background: var(--accent); animation: breathe 1.6s infinite; }
.dot.run { background: var(--accent-2); animation: breathe 1.6s infinite; }
.dot.err { background: var(--danger); }
.dot.wait { background: var(--warn); animation: breathe 1.6s infinite; }
@keyframes breathe { 50% { opacity: .35; } }
@@ -144,3 +140,23 @@ select.tinput { padding-right: 26px; appearance: none;
/* Hidden but visible to a11y/screenshot audits */
.vh { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
/* SelectMenu (components/SelectMenu.tsx): the page's own dropdown in place of native <select> */
.menu.select-menu { z-index: 80; overflow-y: auto; outline: none; max-width: 320px; }
.sm-opt { cursor: pointer; user-select: none; height: auto; min-height: 28px; padding: 4px 8px 4px 10px; }
.sm-opt.on { background: var(--surface-hover); }
.sm-opt.off { color: var(--muted); cursor: default; }
.sm-opt.off:hover { background: none; }
.sm-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
.sm-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sm-hint { font-size: var(--fs-s); color: var(--muted); white-space: normal; line-height: 1.4; }
.sm-check { flex: none; width: 14px; display: inline-flex; color: var(--accent); }
.sm-opt[aria-selected="true"] .sm-label { font-weight: 500; }
/* Form-field trigger (Settings): looks like .tinput with a caret */
.tinput.sm-field {
display: flex; align-items: center; text-align: left; padding-right: 26px; cursor: pointer; position: relative; color: var(--fg);
background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-position: calc(100% - 14px) 50%, calc(100% - 10px) 50%; background-size: 4px 4px; background-repeat: no-repeat;
}
.tinput.sm-field[aria-expanded="true"] { border-color: color-mix(in oklab, var(--accent) 55%, var(--bg)); }
.sm-field .sm-val { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
+46 -34
View File
@@ -1,11 +1,12 @@
/* Conversation items (§8.6): user bubble, body, thinking, tool group, cards, turn end, Markdown */
/* User message: bubble on the right */
.um-row { display: flex; flex-direction: column; align-items: flex-end; margin: 10px 0; }
.um-row { display: flex; flex-direction: column; align-items: flex-end; margin: 4px 0 16px; }
.um {
position: relative; max-width: 78%; min-width: min(100%, 12em);
background: var(--accent-soft); border-radius: var(--r-l) var(--r-l) 4px var(--r-l);
padding: 7px 12px; white-space: pre-wrap; word-break: normal; overflow-wrap: break-word;
position: relative; max-width: 78%;
background: var(--accent-soft); border-radius: 14px 14px 4px 14px; color: var(--fg);
padding: 6px 12px; font-size: var(--fs-l); line-height: 1.6;
white-space: pre-wrap; word-break: normal; overflow-wrap: break-word;
}
.um:hover .um-act { display: flex; }
.um-act { position: absolute; left: -62px; top: 4px; display: none; gap: 2px; }
@@ -14,18 +15,21 @@
.um-tag { font-size: var(--fs-s); color: var(--muted); margin-top: 2px; }
/* Streaming cursor for the body */
.as { margin: 10px 0; }
.as { margin: 4px 0; }
.md.streaming::after { content: "▍"; color: var(--accent); animation: breathe 1s infinite; }
/* Markdown */
.md { font-size: var(--fs-m); word-break: normal; overflow-wrap: break-word; }
.md p { margin: 6px 0; }
.md { font-size: var(--fs-l); line-height: 1.75; color: var(--text); word-break: normal; overflow-wrap: break-word; }
.md p { margin: 0 0 8px; }
.md > :last-child { margin-bottom: 0; }
.md a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; text-decoration-color: color-mix(in oklab, var(--accent) 40%, transparent); }
.md a:hover { text-decoration: underline; }
.md pre {
position: relative; background: var(--code-bg); border-radius: var(--r-s);
position: relative; background: var(--code-bg); border: 1px solid var(--code-line); border-radius: var(--r-m);
padding: 10px 12px; overflow-x: auto; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.55;
}
.md code { font-family: var(--font-mono); font-size: .92em; background: var(--code-bg); padding: 1px 5px; border-radius: 4px; }
.md pre code { background: none; padding: 0; }
.md code { font-family: var(--font-mono); font-size: 12.5px; background: var(--code-bg); color: var(--code-fg); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--code-line); }
.md pre code { background: none; padding: 0; border: 0; color: inherit; }
.md ul, .md ol { margin: 6px 0; padding-left: 22px; }
.md h1, .md h2, .md h3, .md h4 { margin: 12px 0 6px; font-size: var(--fs-l); font-weight: 600; }
.md blockquote { margin: 6px 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); }
@@ -39,41 +43,41 @@
.cb-copy:hover { color: var(--fg); }
/* Thinking (collapsed gray text) / todo */
.rs-item { margin: 8px 0; }
.rs-item { margin: 4px 0 6px; }
.rs-head {
display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 8px;
border-radius: var(--r-s); color: var(--muted); font-size: var(--fs-s);
display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0;
color: var(--meta); font-size: var(--fs-s);
}
.rs-head:hover { background: var(--surface-hover); color: var(--fg); }
.rs-head:hover { color: var(--fg); }
.rs-head .caret { display: inline-block; transition: transform var(--dur-1); }
.rs-head .caret.open { transform: rotate(90deg); }
.rs-body { margin: 4px 0 4px 14px; padding-left: 12px; border-left: 2px solid var(--line); color: var(--muted); font-size: var(--fs-s); white-space: pre-wrap; }
.todo-list { margin: 4px 0 4px 14px; padding-left: 12px; border-left: 2px solid var(--line); list-style: none; font-size: var(--fs-s); }
.rs-body { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--fs-s); line-height: 1.65; white-space: pre-wrap; }
.todo-list { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); list-style: none; font-size: var(--fs-s); }
.todo { color: var(--muted); }
.todo.in_progress { color: var(--fg); }
/* Tool group */
.tg { margin: 8px 0; }
.tg { margin: 4px 0 10px; }
.tg-head {
display: flex; align-items: center; gap: 6px; width: 100%; height: 26px; padding: 0 8px;
border-radius: var(--r-s); color: var(--muted); font-size: var(--fs-s); text-align: left;
display: flex; align-items: center; gap: 6px; width: 100%; height: 24px; padding: 0;
color: var(--meta); font-size: var(--fs-s); text-align: left;
}
.tg-head:hover { background: var(--surface-hover); color: var(--fg); }
.tg-head:hover { color: var(--fg); }
.tg-head .caret { transition: transform var(--dur-1); }
.tg-head .caret.open { transform: rotate(90deg); }
.tg-live { margin-left: auto; color: var(--accent); }
.tg-list { margin: 2px 0 4px 14px; border-left: 2px solid var(--line); padding-left: 4px; }
.tg-live { margin-left: auto; color: var(--accent); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.tg-list { margin: 2px 0 0 5px; border-left: 1px solid var(--line); padding-left: 6px; }
.ts-head {
display: flex; align-items: center; gap: 8px; width: 100%; height: 26px; padding: 0 8px;
border-radius: var(--r-s); font-size: var(--fs-s); text-align: left; color: var(--fg);
display: flex; align-items: center; gap: 8px; width: 100%; height: 26px; padding: 0 6px;
border-radius: var(--r-s); font-size: 12.5px; text-align: left; color: var(--text);
}
.ts-head:hover { background: var(--surface-hover); }
.ts-ic { width: 14px; flex: none; text-align: center; }
.ts-ic.ok { color: var(--ok); }
.ts-ic.fail { color: var(--danger); }
.ts-ic.run { color: var(--accent); animation: breathe 1.2s infinite; }
.ts-ic.run { color: var(--accent-2); animation: breathe 1.2s infinite; }
.ts-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ts-meta { flex: none; color: var(--muted); }
.ts-meta { flex: none; color: var(--meta); font-variant-numeric: tabular-nums; }
.ts-meta.err { color: var(--danger); }
.ts-out { margin: 2px 8px 6px 30px; }
.ts-out pre {
@@ -84,18 +88,18 @@
.ts-more { font-size: var(--fs-s); color: var(--accent); margin-bottom: 4px; }
/* diff (unified view, red/green backgrounds) */
.diff { margin: 4px 8px 8px 30px; border: 1px solid var(--line); border-radius: var(--r-s); overflow: hidden; }
.diff { margin: 2px 6px 6px 22px; border: 1px solid var(--line); border-radius: var(--r-m); overflow: hidden; }
.diff-path { padding: 4px 10px; font-size: var(--fs-s); color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--line); font-family: var(--font-mono); }
.diff-pre { margin: 0; padding: 6px 0; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.5; overflow-x: auto; }
.dh-head { display: block; color: var(--muted); padding: 0 10px; }
.dl { display: block; padding: 0 10px; white-space: pre-wrap; word-break: break-all; }
.dl.add { background: color-mix(in oklab, var(--ok) 14%, transparent); }
.dl.del { background: color-mix(in oklab, var(--danger) 12%, transparent); }
.dl.add { background: var(--add-bg); }
.dl.del { background: var(--del-bg); }
/* Cards (plan/permission/question/error) */
.card { margin: 10px 0; border-radius: var(--r-m); padding: 10px 12px; }
.card { margin: 8px 0; border-radius: 10px; padding: 12px 14px; }
.card.plan { border: 1px solid var(--line); }
.card.perm { border: 1px solid color-mix(in oklab, var(--warn) 45%, var(--bg)); }
.card.perm { border: 1px solid color-mix(in oklab, var(--warn) 30%, var(--bg)); background: color-mix(in oklab, var(--warn) 3%, var(--bg)); }
.card.perm.done { border-color: var(--line); opacity: .75; }
.card.ask { border: 1px solid color-mix(in oklab, var(--info) 45%, var(--bg)); }
.card.ask.done { border-color: var(--line); opacity: .75; }
@@ -121,8 +125,16 @@
.nt.error { color: var(--danger); }
/* Turn end: small right-aligned text */
.te { display: flex; justify-content: flex-end; align-items: center; gap: 8px; margin: 10px 0 4px; font-size: var(--fs-s); color: var(--muted); }
.te-files { color: var(--accent); font-size: var(--fs-s); }
/* Turn end: "3s · copy · retry" left-aligned under the reply */
.te { display: flex; justify-content: flex-start; align-items: center; gap: 2px; margin: 4px 0 18px -6px; font-size: var(--fs-s); color: var(--meta); }
.te-meta { padding: 0 6px; font-variant-numeric: tabular-nums; }
.te-act {
height: 24px; min-width: 24px; display: inline-flex; align-items: center; justify-content: center; gap: 4px;
padding: 0 5px; border-radius: var(--r-s); color: var(--meta);
}
.te-act span { display: none; }
.te-act:hover { background: var(--surface-hover); color: var(--fg); }
.te-files { color: var(--accent); font-size: var(--fs-s); margin-left: 6px; }
.te-files:hover { text-decoration: underline; }
/* Empty state */
@@ -136,7 +148,7 @@
.workspace-empty { padding-bottom: 10vh; }
/* queue list */
.q-list { max-width: 680px; margin: 0 auto 6px; display: flex; flex-direction: column; gap: 4px; }
.q-list { max-width: var(--col); margin: 0 auto 6px; display: flex; flex-direction: column; gap: 4px; }
.q-item {
display: flex; align-items: center; gap: 8px; padding: 4px 10px;
background: var(--surface); border-radius: var(--r-s); font-size: var(--fs-s);
@@ -1,17 +1,19 @@
/* Input area (§8.6 Composer) */
.composer { flex: none; padding: 0 16px 12px; }
/* Input area (§8.6 Composer) — option B: white card, 1px border, 14px radius, neutral grey focus ring */
.composer { flex: none; padding: 0 16px 16px; }
.cp-card {
width: 100%; max-width: 680px; margin: 0 auto;
background: var(--surface); border-radius: var(--r-l); border: 1px solid transparent;
padding: 8px 10px 6px; transition: border-color var(--dur-2) var(--ease);
width: 100%; max-width: var(--col); margin: 0 auto;
background: var(--bg); border-radius: 14px; border: 1px solid var(--cp-line);
padding: 12px 12px 8px 14px; box-shadow: 0 1px 2px rgb(0 0 0 / .04);
transition: border-color var(--dur-2) var(--ease), box-shadow var(--dur-2) var(--ease);
}
.cp-card:focus-within { border-color: color-mix(in oklab, var(--fg) 18%, var(--bg)); }
.cp-card.waiting { box-shadow: inset 2px 0 0 var(--warn); }
.cp-card.danger { box-shadow: inset 2px 0 0 var(--danger); }
.cp-card:focus-within { border-color: var(--cp-focus); box-shadow: 0 0 0 3px var(--cp-ring), 0 1px 2px rgb(0 0 0 / .04); }
.cp-card.waiting { border-color: color-mix(in oklab, var(--warn) 45%, var(--bg)); }
.cp-card.danger { border-color: color-mix(in oklab, var(--danger) 40%, var(--bg)); }
.cp-danger {
max-width: 680px; margin: 0 auto 6px; display: flex; align-items: center; gap: 6px;
max-width: var(--col); margin: 0 auto 6px; display: flex; align-items: center; gap: 6px;
color: var(--danger); font-size: var(--fs-s); padding: 0 2px;
}
.cp-hint { max-width: var(--col); margin: 6px auto 0; font-size: 11.5px; color: var(--meta); text-align: center; }
.att-note { padding: 6px 10px 0; color: var(--muted); font-size: var(--fs-s); }
.cp-ta-wrap { position: relative; }
.slash-pop {
@@ -34,46 +36,52 @@
.slash-pop .mi.slash-item.sel { background: var(--surface-hover); }
.cp-ta {
width: 100%; border: 0; resize: none; background: none; outline: none;
font-size: var(--fs-m); line-height: 1.55; max-height: calc(1.7em * 10); overflow-y: auto;
display: block;
width: 100%; border: 0; resize: none; background: none; outline: none; color: var(--text);
font-size: var(--fs-l); line-height: 22px; min-height: 34px; max-height: calc(22px * 12); overflow-y: auto;
display: block; padding: 0;
}
.cp-ta::placeholder { color: var(--muted); }
.cp-ta::placeholder { color: var(--meta); }
.cp-bar {
display: flex; align-items: center; flex-wrap: wrap; gap: 4px 6px;
margin-top: 4px; min-width: 0;
display: flex; align-items: center; flex-wrap: wrap; gap: 2px;
margin: 4px 0 0 -6px; min-width: 0;
}
/* Pill controls */
/* Pill controls: 26px, 7px radius, 12px text; the agent·model chip is filled, the others are icon + label */
.pill-wrap { position: relative; flex: 0 1 auto; min-width: 0; max-width: 100%; }
.pill {
display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px;
border-radius: var(--r-full); background: var(--surface-hover); color: var(--fg);
font-size: var(--fs-s); max-width: min(220px, 100%); min-width: 0;
position: relative; display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 8px;
border-radius: 7px; background: none; color: var(--pill-fg, var(--muted)); border: 1px solid transparent;
font-size: var(--fs-s); max-width: min(240px, 100%); min-width: 0; white-space: nowrap; cursor: pointer;
transition: background var(--dur-1);
}
.pill .p-a { font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.pill .p-t { color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1 1 auto; }
.pill.sel {
appearance: none; border: 0; padding: 0 22px 0 10px; cursor: pointer;
max-width: min(140px, 100%); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
background: var(--surface-hover) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath fill='%23737373' d='M1 1l4 4 4-4'/%3E%3C/svg%3E") no-repeat right 8px center;
}
.pill.sel.danger { color: var(--danger); }
.pill.cursor-shield { padding: 0 8px; color: var(--muted); border: 0; cursor: pointer; }
.pill.cursor-shield.on { color: var(--ok, #3ecf8e); background: color-mix(in oklab, var(--ok, #3ecf8e) 14%, var(--surface-hover)); }
.pill.sel.cursor-fast { max-width: min(72px, 100%); }
.pill:hover { background: var(--surface-hover); }
.pill svg { flex: none; }
.pill.chip { background: var(--chip-bg); border-color: var(--chip-line); padding: 0 8px 0 4px; gap: 6px; max-width: min(300px, 100%); }
.pill.chip:hover { background: var(--surface-hover); }
.chip-logo { border-radius: 5px; }
.chip-caret { color: var(--meta); }
.pill .p-a { font-weight: 500; color: var(--fg); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 0 0 auto; max-width: 120px; }
.pill .p-t { color: var(--meta); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1 1 auto; }
.pill .p-t::before { content: "·"; margin-right: 5px; }
.ipill .ip-l { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.ipill:focus-visible { outline: 2px solid color-mix(in oklab, var(--accent) 45%, var(--bg)); outline-offset: -1px; }
.ipill[aria-expanded="true"] { background: var(--surface-hover); }
.ipill.danger { color: var(--danger); }
.mode-menu { max-width: 300px; }
.cp-div { width: 1px; height: 14px; background: var(--line); margin: 0 4px; flex: none; }
.cp-bar > .ibtn { flex: none; }
.cp-attach { color: var(--pill-fg, var(--muted)); }
/* When the composer gets narrow (depends on the middle column's width, not the window) */
.cp-card { container-type: inline-size; container-name: composer; }
@container composer (max-width: 520px) {
.pill .p-t { display: none; }
.pill { max-width: min(160px, 100%); }
.pill.sel { max-width: min(104px, 100%); font-size: 11px; padding-right: 20px; }
.ipill .ip-l { max-width: 64px; }
}
@container composer (max-width: 380px) {
.pill { max-width: min(120px, 100%); padding: 0 8px; }
.pill.sel { max-width: min(80px, 100%); padding-left: 7px; padding-right: 18px; }
.pill { max-width: min(120px, 100%); padding: 0 6px; }
.ipill .ip-l { display: none; }
}
/* Agent·model popover */
@@ -181,15 +189,15 @@
.att-x:hover { color: var(--fg); }
.cp-right { margin-left: auto; flex: none; display: flex; align-items: center; gap: 8px; }
.cp-clock { font-size: var(--fs-s); color: var(--muted); }
.cp-clock { font-size: var(--fs-s); color: var(--meta); font-variant-numeric: tabular-nums; }
.cp-send, .cp-stop {
width: 28px; height: 28px; border-radius: 50%; flex: none;
width: 30px; height: 30px; border-radius: 50%; flex: none;
display: inline-flex; align-items: center; justify-content: center;
transition: filter var(--dur-1), opacity var(--dur-1);
}
.cp-send { background: var(--accent); color: var(--accent-fg); }
.cp-send:hover { filter: brightness(1.08); }
.cp-send[disabled] { opacity: .3; cursor: default; filter: none; }
.cp-send[disabled] { opacity: .35; cursor: default; filter: none; }
.cp-stop { background: var(--fg); color: var(--bg); }
.cp-stop:hover { filter: brightness(1.15); }
@@ -6,63 +6,71 @@
/* ---- sidebar ---- */
.sidebar {
width: var(--sb-w, 248px); flex: none; display: flex; flex-direction: column;
background: var(--surface); border-right: 1px solid var(--line);
background: var(--sb-bg); border-right: 1px solid var(--line);
}
.sb-row { display: flex; align-items: center; gap: 2px; height: 40px; padding: 6px 6px 4px; flex: none; }
.sb-row { display: flex; align-items: center; gap: 2px; height: 40px; padding: 8px 8px 4px; flex: none; }
.sb-row-search { height: 36px; padding: 0 8px 4px; }
.sb-new {
flex: 1; display: flex; align-items: center; gap: 6px; height: 28px;
padding: 0 8px; border-radius: var(--r-s); font-size: var(--fs-m); text-align: left;
transition: background var(--dur-1);
flex: 1; display: flex; align-items: center; gap: 8px; height: 28px; min-width: 0;
padding: 0 8px 0 5px; border-radius: var(--r-s); font-size: var(--fs-m); font-weight: 500; text-align: left;
transition: background var(--dur-1); white-space: nowrap; overflow: hidden;
}
.sb-new-tile {
width: 18px; height: 18px; flex: none; border-radius: 5px; background: var(--tile-bg); color: var(--tile-fg);
display: inline-flex; align-items: center; justify-content: center;
}
.sb-new-tile svg { stroke-width: 2.2; }
.sb-new:hover { background: var(--surface-hover); }
.sb-row .ibtn { width: 28px; height: 28px; }
.sb-search {
flex: 1; display: flex; align-items: center; gap: 6px; height: 28px;
padding: 0 8px; border-radius: var(--r-s); background: var(--surface-hover); color: var(--muted);
padding: 0 8px; border-radius: var(--r-s); background: var(--search-bg); color: var(--meta);
}
.sb-search input::placeholder { color: var(--meta); }
.sb-search input { flex: 1; min-width: 0; border: 0; background: none; font-size: var(--fs-s); outline: none; color: var(--fg); }
.sb-list { flex: 1; overflow-y: auto; padding: 0 6px 8px; }
.sb-list { flex: 1; overflow-y: auto; padding: 0 8px 8px; }
/* Project group */
.pj-group { margin-top: 2px; }
.pj { display: flex; align-items: center; gap: 2px; height: 30px; padding: 0 4px 0 0; border-radius: var(--r-s); }
.pj { display: flex; align-items: center; gap: 2px; height: var(--row); padding: 0 4px 0 0; border-radius: var(--r-s); }
.pj:hover { background: var(--surface-hover); }
.pj-toggle { flex: 1; min-width: 0; height: 100%; display: flex; align-items: center; gap: 6px; padding-left: 2px; text-align: left; font-size: var(--fs-m); font-weight: 500; }
.pj-caret { width: 14px; flex: none; display: inline-flex; justify-content: center; color: var(--muted); transition: transform var(--dur-1); }
.pj-caret.open { transform: rotate(90deg); }
.pj-badge {
width: 20px; height: 20px; flex: none; border-radius: 5px;
width: 18px; height: 18px; flex: none; border-radius: 5px;
display: inline-flex; align-items: center; justify-content: center;
background: var(--surface-hover); color: var(--fg); font-size: var(--fs-s); font-weight: 600; line-height: 1;
background: var(--badge-bg); color: var(--badge-fg); font-size: 11px; font-weight: 600; line-height: 1;
text-transform: uppercase;
}
.pj:hover .pj-badge { background: var(--bg); }
.pj-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-count { flex: none; padding: 0 6px; font-size: var(--fs-s); color: var(--muted); }
.pj-count { flex: none; padding: 0 6px; font-size: var(--fs-s); color: var(--meta); }
.pj-act { width: 22px; height: 22px; flex: none; display: none; align-items: center; justify-content: center; border-radius: var(--r-s); color: var(--muted); }
.pj:hover .pj-act, .pj-act:focus-visible { display: inline-flex; }
.pj:hover .pj-count { display: none; }
.pj-act:hover { background: var(--bg); color: var(--fg); }
.pj-sessions { padding: 1px 0 4px 22px; }
.pj-sessions { padding: 1px 0 4px 22px; display: flex; flex-direction: column; gap: 1px; }
.pj-more, .pj-empty { display: flex; align-items: center; width: 100%; height: 26px; padding: 0 8px 0 21px; font-size: var(--fs-s); color: var(--muted); text-align: left; border-radius: var(--r-s); }
.pj-more:hover { background: var(--surface-hover); color: var(--fg); }
/* Conversation row */
.t-item {
display: flex; align-items: center; gap: 8px; width: 100%; height: 28px;
display: flex; align-items: center; gap: 8px; width: 100%; height: var(--row);
padding: 0 4px 0 8px; border-radius: var(--r-s); position: relative; text-align: left;
font-size: var(--fs-m); transition: background var(--dur-1);
}
.t-item:hover { background: var(--surface-hover); }
.t-item.on { background: var(--surface-hover); }
/* Active conversation: white card, 1px outline, 2px dark-grey bar on the left */
.t-item.on { background: var(--active-bg); box-shadow: 0 0 0 1px var(--active-line), 0 1px 2px rgb(0 0 0 / .04); font-weight: 500; }
.t-item.on::before { content: ""; position: absolute; left: -1px; top: 7px; bottom: 7px; width: 2px; border-radius: 2px; background: var(--accent-2); }
.t-item.archived { opacity: 0.55; }
.t-item.archived .t-title { font-style: italic; }
.t-item .dot { width: 5px; height: 5px; }
.t-pin { width: 12px; flex: none; display: inline-flex; color: var(--muted); }
.t-pin svg { width: 10px; height: 10px; }
.t-title { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.t-time { flex: none; font-size: var(--fs-s); color: var(--muted); }
.t-time { flex: none; font-size: 11.5px; color: var(--meta); font-weight: 400; }
.t-item:hover .t-time { display: none; }
.t-more {
flex: none; width: 22px; height: 22px; display: none; align-items: center; justify-content: center;
@@ -112,7 +120,8 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
flex: none; display: inline-flex; align-items: center; gap: 6px; height: 22px; padding: 0 9px;
border-radius: var(--r-full); font-size: var(--fs-s); background: var(--surface); color: var(--muted);
}
.tb-pill.run { color: var(--accent); }
.tb-pill.run { background: var(--run-bg); color: var(--run-fg); }
.tb-pill-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-2); box-shadow: 0 0 0 3px color-mix(in oklab, var(--accent-2) 20%, transparent); animation: breathe 1.6s infinite; }
.tb-pill.wait { color: var(--warn); }
.tb-pill.err { color: var(--danger); }
.tb-right { margin-left: auto; display: flex; align-items: center; gap: 2px; }
@@ -125,7 +134,8 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
/* Timeline: content max width 760, centered */
.scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; position: relative; }
.tl-wrap { max-width: 760px; min-width: 0; margin: 0 auto; padding: 16px 20px 12px; }
/* Conversation and composer share one 720px column */
.tl-wrap { max-width: calc(var(--col) + 40px); min-width: 0; margin: 0 auto; padding: 24px 20px 16px; }
/* ↓ jump-to-bottom button */
.jump {
@@ -176,12 +186,12 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
}
.chg-kind.k-modified { color: var(--warn, #b45309); }
.chg-kind.k-added, .chg-kind.k-untracked { color: var(--ok, #15803d); }
.chg-kind.k-deleted { color: var(--err, #b91c1c); }
.chg-kind.k-deleted { color: var(--danger); }
.chg-kind.k-renamed { color: var(--accent); }
.chg-path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; direction: rtl; text-align: left; }
.chg-stat { flex: none; font-style: normal; font-size: var(--fs-s); font-variant-numeric: tabular-nums; }
.chg-stat .add { color: var(--ok, #15803d); font-style: normal; }
.chg-stat .del { color: var(--err, #b91c1c); font-style: normal; }
.chg-stat .del { color: var(--danger); font-style: normal; }
.chg-discard { flex: none; opacity: 0; }
.chg-row:hover .chg-discard { opacity: 1; }
.chg-diff { flex: 1; min-height: 0; overflow: auto; }
@@ -1,43 +1,78 @@
/* Design tokens (ported from ui/styles/tokens.css, not a single color changed).
The magpie theme injects --magpie-* variables via ?tokens=; every one falls back to our own value here.
Font sizes across the app are only 12/13/14 (+ 18 for empty-state titles), weights only 400/500/600, borders only --line, shadows only on popovers. */
/* Design tokens — "option B": quiet neutrals, one accent.
Magpie passes its palette as --magpie-* (?tokens=). Its font always applies; its surface colors apply only while this page
shows the same light/dark as Magpie (html[data-host-colors], set by layout/theme.ts), so an explicit Light/Dark setting never mixes palettes.
The accent is deliberately monochrome: charcoal in light mode, light grey in dark mode. Magpie's accent tokens are ignored
(layout/applyMagpieTokens.ts drops them), so the page never picks up a hue. Only semantic colors (ok/warn/danger/info, diff) carry color.
Font sizes are 12/13/14 (+ 18 for empty-state titles), weights 400/500/600. */
:root {
--bg: var(--magpie-bg, #ffffff);
--fg: var(--magpie-fg, #1f1f1f);
--muted: var(--magpie-muted, #737373);
--accent: var(--magpie-accent, #0d9488);
--own-bg: #ffffff; --own-sb: #f8f8f7; --own-fg: #1f1f1f; --own-muted: #737373; --own-line: #ececec;
--bg: var(--own-bg);
--sb-bg: var(--own-sb);
--fg: var(--own-fg);
--muted: var(--own-muted);
--line: var(--own-line);
--meta: #a3a3a3;
--text: #262626;
--accent: #262626; /* charcoal: send, primary buttons, links, active marker, running dot */
--accent-2: #525252; /* dark grey: active bar, running dot */
--accent-fg: #ffffff;
--accent-soft: color-mix(in oklab, var(--accent) 12%, var(--bg));
--accent-soft: #f0f0f0; /* user bubble: light neutral grey */
--surface: color-mix(in oklab, var(--fg) 3%, var(--bg));
--surface-hover: color-mix(in oklab, var(--fg) 6%, var(--bg));
--line: color-mix(in oklab, var(--fg) 9%, var(--bg));
--chip-bg: #f4f5f5; --chip-line: #ececec; --pill-fg: #525252;
--search-bg: #efefee;
--tile-bg: color-mix(in oklab, var(--fg) 90%, var(--bg)); --tile-fg: var(--bg);
--badge-bg: color-mix(in oklab, var(--fg) 7%, var(--bg)); --badge-fg: color-mix(in oklab, var(--fg) 80%, var(--bg));
--run-bg: #f0f0f0; --run-fg: #404040;
--cp-line: color-mix(in oklab, var(--fg) 11%, var(--bg));
--cp-focus: #a3a3a3; /* neutral grey focus border */
--cp-ring: rgb(0 0 0 / .06);
--active-bg: #ffffff; --active-line: #e6e6e6;
--ok: #16a34a; --warn: #d97706; --danger: #dc2626; --info: #2563eb;
--code-bg: color-mix(in oklab, var(--fg) 4%, var(--bg));
--code-bg: #f4f5f5; --code-line: #eaeceb; --code-fg: #404040;
--add-bg: #ecfdf3; --del-bg: #fef2f2;
--r-s: 6px; --r-m: 8px; --r-l: 12px; --r-full: 999px;
--font-ui: var(--magpie-font, "Segoe UI Variable Text", "Segoe UI", -apple-system, "PingFang SC", "Microsoft YaHei UI", system-ui, sans-serif);
--font-mono: "Cascadia Code", "Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace;
--font-mono: var(--magpie-code, "Cascadia Code", "Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace);
--fs-s: 12px; --fs-m: 13px; --fs-l: 14px;
--fs-hero: 18px;
--lh: 1.6;
--col: 720px;
--row: 26px;
--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .16), 0 0 0 1px var(--line);
--term-bg: #ffffff;
--term-fg: #1e1e1e;
--ease: cubic-bezier(.2,.7,.2,1);
--dur-1: 120ms; --dur-2: 200ms;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: var(--magpie-bg, #1a1a1a); --fg: var(--magpie-fg, #ececec); --muted: var(--magpie-muted, #9b9b9b);
--accent: var(--magpie-accent, #2dd4bf); --accent-fg: #04201c; --info: #60a5fa;
--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);
--term-bg: #0c0c0c;
--term-fg: #cccccc;
}
}
[data-theme="dark"] {
--bg: var(--magpie-bg, #1a1a1a); --fg: var(--magpie-fg, #ececec); --muted: var(--magpie-muted, #9b9b9b);
--accent: var(--magpie-accent, #2dd4bf); --accent-fg: #04201c; --info: #60a5fa;
:root[data-theme="dark"] {
--own-bg: #1a1a1a; --own-sb: #151515; --own-fg: #ececec; --own-muted: #9b9b9b; --own-line: #2c2c2c;
--meta: #7c7c7c;
--text: #e2e2e2;
--accent: #e5e5e5; /* light grey / near-white */
--accent-2: #b3b3b3;
--accent-fg: #171717; /* dark icon/text on light accent */
--accent-soft: #2e2e2e;
--chip-bg: #252727; --chip-line: #323434; --pill-fg: #bdbdbd;
--search-bg: #242424;
--run-bg: #2e2e2e; --run-fg: #d4d4d4;
--cp-focus: #6b6b6b;
--cp-ring: rgb(255 255 255 / .07);
--active-bg: #242424; --active-line: #333333;
--info: #60a5fa;
--code-bg: #232323; --code-line: #303030; --code-fg: #d4d4d4;
--add-bg: rgb(22 163 74 / .16); --del-bg: rgb(220 38 38 / .16);
--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);
--term-bg: #0c0c0c;
--term-fg: #cccccc;
color-scheme: dark;
}
/* Same light/dark as Magpie: use its surfaces and text colors (card = content, bg = sidebar) */
:root[data-host-colors] {
--bg: var(--magpie-card, var(--magpie-bg, var(--own-bg)));
--sb-bg: var(--magpie-bg, var(--own-sb));
--fg: var(--magpie-fg, var(--own-fg));
--muted: var(--magpie-muted, var(--own-muted));
--line: var(--magpie-line, var(--own-line));
}
@@ -2,7 +2,7 @@
// Rules: dedup by seq; deltas merge by itemId, complete events replace them and set streaming=false;
// consecutive tool_calls go into one ToolGroupItem (interrupted by text/plan/permission etc. -> new group);
// a permission shows "cancelled" when runtimeStatus is not running and it is unresolved.
import type { TimelineEvent } from "./types";
import type { TimelineEvent } from "./types.js";
export type ToolStep = {
itemId: string; kind: string; title: string;
@@ -41,6 +41,8 @@ type State = {
turnUsage: Map<string, TurnUsage>;
// turnId -> index of the last user message (for the error card's "Retry")
lastUserIdx: Map<string, number>;
// turnId -> turn_started ts (fallback duration for agents that don't report one, e.g. ACP)
turnStart: Map<string, number>;
};
export function newTimelineState(): State {
@@ -53,6 +55,7 @@ export function newTimelineState(): State {
reqLoc: new Map(),
turnUsage: new Map(),
lastUserIdx: new Map(),
turnStart: new Map(),
};
}
@@ -246,12 +249,14 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
breakGroup(st);
st.items.push({
kind: "turnend", key: `te:${ev.seq}`, status: ev.status,
durationMs: ev.durationMs, error: ev.error, filesChanged: ev.filesChanged,
durationMs: ev.durationMs ?? (st.turnStart.has(ev.turnId) ? Math.max(0, ev.ts - st.turnStart.get(ev.turnId)!) : undefined),
error: ev.error, filesChanged: ev.filesChanged,
usage: st.turnUsage.get(ev.turnId),
});
return;
case "turn_started":
// not shown as an item; the status pill uses status events / runtime
st.turnStart.set(ev.turnId, ev.ts);
return;
case "status":
return;
+2 -2
View File
@@ -165,8 +165,8 @@
"kind": "page",
"community": true,
"summary": {
"en": "A page in magpie's window that drives the Agent CLIs on this computer (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh) through a local daemon on 127.0.0.1, with a structured timeline, Git, files and a terminal. The daemon starts when the page opens and stops with magpie; only its own page gets its token. Cold install ~46 MB (mostly node-pty ~26 MB); Claude Code is not bundled — install the `claude` CLI yourself to use it.",
"zh": "在 magpie 窗口里驱动本机的 Agent CLI(Claude Code、Codex、Cursor、Copilot、OpenCode、Pi、Devin、dsh):本地服务只在 127.0.0.1,带结构化时间线、Git、文件和终端。打开页面时才启动,随 magpie 退出;令牌只交给自己的页面。冷安装约 46 MB(主要是 node-pty 约 26 MB);不附带 Claude Code,使用该 Agent 请自行安装 `claude` CLI。"
"en": "Use your terminal Agent CLIs right inside magpie, by chat. Runs a local service on 127.0.0.1 that starts when the page opens and stops with magpie; only its own page gets the token. First install ~46 MB; Claude Code isn't bundled, so install the `claude` CLI yourself.",
"zh": "把终端里的 Agent CLI 搬进 magpie 窗口,直接对话使用。会在本机 127.0.0.1 跑一个后台服务,打开页面才启动,随 magpie 退出;令牌只交给自己的页面。首次安装约 46 MB;不自带 Claude Code,要用请自己装 `claude` CLI。"
}
}
]