This carries #727's reviewed part forward, without auto-approve (that comes as its own PR). Permission behaviour is the same as 1.2. - Windows Git Bash detection, never the WSL System32 bash. It can be overridden in Settings and is passed per spawn only. - GBK / system code page decoding of raw process output. - Folded tool steps that don't wrap at ~600px. - Select-to-quote, and copy/edit under the user bubble. - Instant send with the echo replacing the bubble in place, and retry when a send fails. - `/app` heals itself after sleep/wake. `frame-ancestors` is limited to loopback and Magpie's window. - Grayscale timeline polish: one-line tool rows, a task-list pill, a reply footer and code blocks. - Test fixes: - The `initializing` push is awaited. - `afterEach` waits for the thread store's writes. - `runtimeInfo().starting` is exposed, and the steer test waits on it. - "idle recycling" waits for closed. Run on mote (macOS) at 65ab7c94: - `npm ci`, `npm run check` and `build` are ok; `verify:build` gives 5/5 OK. - Full `vitest run` x5: 4 green (427 passed). One red, "send while running → queued", is a race that is on main too. - Cause: `setStatus(idle)` runs before `queue.shift()`. - A 300ms pause injected there makes it red 3/3 on main and on this head. - Filed on #585 with the cause and the repro. - Focused send-latency + manager runs: 12/12. `e2e:v1`: 25/25, with no pageerror or console error. - Broken by hand: - With the old steer wait and the mock send held 400ms, the test is red 3/3; the new wait passes 3/3. - With `recycleIdle` made a no-op, "idle recycling" goes red. - Playwright render: - Chromium and WebKit × zh/en × light/dark × 1280/420. - No gradients, no coloured left borders, no `<select>`, no page errors. - At 420 the page scrolls sideways (scrollWidth 480), the same as main. Not tried: Windows (Git Bash detection, GBK decoding) and a real agent, rather than the mock.
This commit is contained in:
@@ -41,7 +41,8 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
- **Persistent sessions**: each thread binds to a long-lived Agent process; after a daemon restart, running threads are marked closed and can be resumed (`--resume` / `thread/resume`)
|
||||
- **Multiple Agents**: Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh; missing CLIs show an install hint
|
||||
- **Model / permission / thinking**: per-thread; four permission modes and five thinking levels (what each Agent actually supports)
|
||||
- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card
|
||||
- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card. Since 1.3 every tool call is one compact row: a type icon, the command or path (monospace, relative to the project, never wrapping), `+N -M` for an edit and the status on the right; click a row for its output or diff, and a failed step opens by itself. A run of more than 6 tool calls (with the short thinking between them) folds into one summary row (改动 2 · 运行 3 · 读取 4 · 搜索 1 · 1 失败) that expands to the same rows; while it runs, one line shows the current step (正在运行:npm test…). The Agent's step list (Claude Code TodoWrite, Codex plan updates, an ACP agent's plan) is a checklist with N/M, and while it has open items an "N/M 个任务" pill above the composer jumps to it. Each reply ends with 复制 · model · time · duration (plus tokens / cost when the Agent reports them). Code blocks have a language label, line numbers, a wrap toggle and a copy button (the copy is the raw code). The look is grayscale and was inspired by [Better Paseo](https://github.com/RoundRedDot/better-paseo) (MIT); no code was copied
|
||||
- **Instant send (1.3)**: your message shows in the timeline the moment you click 发送 and the composer switches to working at once. The daemon saves and pushes the message before it starts the Agent (spawn + ACP `initialize` / `session/new`, seconds on Windows) instead of after; the page draws it right away and swaps in the daemon's copy by a client message id, so it neither doubles nor jumps. A send that fails stays in place marked 发送失败 with 重试 / 移除. A message sent while a turn runs still goes to the queue list
|
||||
- **Steer and queue**: steer while running, queue the next message, interrupt
|
||||
- **Changes panel**: git status refresh every 3s, unified per-file diffs; discarded untracked files go to trash instead of a hard delete
|
||||
- **Files panel**: lazy directory tree (respects `.gitignore`), syntax-highlighted preview
|
||||
@@ -52,9 +53,9 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
- **Preview tab** (1.2): a small browser in the right panel for local dev servers (`localhost`, `127.0.0.1`, `[::1]`, `*.localhost`, `0.0.0.0`): address bar, back / forward, reload, open in the system browser, widen the panel. The address is remembered per conversation. Pages load through the daemon's local preview proxy (see the security model), so module scripts, `fetch` and HMR WebSockets work inside Magpie's sandboxed frame. Limits: popups, `alert` and native form posts don't run in the sandbox; `localStorage` / `sessionStorage` / `document.cookie` are in-memory and reset on reload, and cookies are not passed (use 用浏览器打开 / Open in browser for logins)
|
||||
- **Links in chat** (1.2): local addresses in agent text, rendered Markdown and tool output (`localhost:5173`, `http://127.0.0.1:8080/x`, …) become links that open in the Preview tab; Ctrl/⌘+click, and any other `http(s)` link, opens the system browser through the daemon (`app.openExternal`: http/https only, re-serialized, run with `execFile` and no shell: `rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `xdg-open` on Linux; if that fails the link is copied). The terminal is not linkified
|
||||
- **File chips** (1.2): drag a row from the Files tab into the composer, or right-click → 插入到聊天 / Add to chat, to attach a path chip. Chips are sent as project-relative paths, checked by the daemon (inside the project, no `..`, no symlink escape, must exist, at most 50), and reach the Agent as a "Referenced files" section with absolute paths after your text (plus `resource_link` blocks for ACP Agents). Dropping files from the OS file manager still uploads them as attachments
|
||||
- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted
|
||||
- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller; the sidebar, top bar, panel tabs, menus and dialogs stay on the fixed 13 px UI scale); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted
|
||||
- **Follows Magpie live** (1.2): light/dark, Magpie's neutral colours and its language follow Magpie while the page is open (and after a reconnect); the accent stays neutral grey
|
||||
- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 9 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve`) so UI work does not burn tokens
|
||||
- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 11 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve` / `tools` / `bashhint`) so UI work does not burn tokens
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -66,7 +67,8 @@ Magpie window
|
||||
▼
|
||||
Magpie plugin host (Bun) ── index.mjs + lib/gate.mjs "gate" on 127.0.0.1:<port> (default 3488)
|
||||
│ first /open: spawns the daemon as a child process (node, --port 0, stdin lifeline, --parent-pid)
|
||||
│ 302 → http://127.0.0.1:<daemonPort>/?theme=…#t=<token>
|
||||
│ 302 → http://127.0.0.1:<port>/app?theme=…#t=<token>&p=<daemonPort> (1.3: the gate's wrapper page, lib/wrapper.mjs)
|
||||
│ └─ <iframe src="http://127.0.0.1:<daemonPort>/?theme=…#t=<token>&w=1">
|
||||
▼
|
||||
daemon (Node, daemon/dist/main.js) ── HTTP + WebSocket on an ephemeral 127.0.0.1 port
|
||||
└─ React app (app/) reads the token from location.hash, sends it as the x-agent-console header
|
||||
@@ -85,8 +87,9 @@ The daemon can run Agents with full access to your machine, so the token that un
|
||||
- token routes (`/api/*`, `/attachments/*`, WebSocket hello) accept `Origin: null` only as a way to *present* the token (the Magpie iframe has an opaque origin); `access-control-allow-origin: null` is emitted only on responses to requests that carried a valid token, plus the preflight for `/api/upload`; credentials are never allowed;
|
||||
- any other origin gets 403 even with a valid token.
|
||||
- **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`.
|
||||
- The gate answers only `GET /open?k=<gate key>` (the daemon token is not accepted there) and `GET /app` (1.3, below), 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 sleep / a daemon restart (1.3).** Before 1.3 the plugin frame sat on the daemon's random port; when the daemon was gone after sleep and the WebView reloaded the frame, it showed "127.0.0.1 拒绝连接" with none of our script left to recover. Now `/open` redirects to the gate's own `GET /app`, a static page that frames the daemon page, so a reload lands on the stable gate port. The daemon page (told by `w=1`) posts `{ac_console:"alive"}` to it every 2 s while its WebSocket is open and `{ac_console:"lost"}` after 5 s without it; no alive within 12 s (6 s after the child frame loaded), a lost, or 15 s of silence while visible (time the wrapper's own timers were suspended doesn't count) sends the frame back through the Magpie page (`b`, as below), which restarts the daemon. At most 3 automatic tries in 2 minutes (`ac_try`), then a button. The wrapper holds no secret of its own: the token arrives only in its fragment and goes on only in the child's fragment, the gate key never reaches it, the child is always `http://127.0.0.1:<integer port>/`, `b` passes the same loopback Magpie-page check, only the Magpie theme protocol is relayed (theme events and hello answers down, the hello call up, messages checked by `event.source`), and it is served with a per-response nonce CSP (`default-src 'none'`, `frame-src http://127.0.0.1:*`, and `frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:`, so only a loopback page or Magpie's own desktop window can frame it). Host and Origin checks apply to `/app` like to `/open`.
|
||||
- **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.
|
||||
|
||||
### Preview proxy (1.2)
|
||||
@@ -120,9 +123,10 @@ The plugin runs wherever Magpie runs (Windows, macOS, Linux). It needs **Node.js
|
||||
- **Terminal.** `node-pty` prebuilds cover win32/darwin/linux × x64/arm64 (Linux prebuilds are glibc only). Default shell: Windows `pwsh` → `powershell` → `cmd`; macOS/Linux `$SHELL` if it exists, else `zsh` (macOS) / `bash` / `sh`. If `node-pty` cannot load, a simple non-PTY terminal is used ([details](#when-node-pty-cant-be-loaded)). On macOS the exec bit of `node-pty`'s `spawn-helper` is restored if the package extraction dropped it.
|
||||
- **Folder picker.** Windows: PowerShell `FolderBrowserDialog`; macOS: `osascript` "choose folder"; Linux: `zenity` or `kdialog` when a graphical session exists; otherwise type the path.
|
||||
- **Paths.** Project paths are compared case-insensitively on Windows and macOS (and NFC-normalized on macOS); `realpath.native` resolves 8.3 short names and `subst` drives; UNC paths work. Discarding an untracked file moves it to the trash with a copy fallback when the project and data dir are on different drives.
|
||||
- **Encoding.** Agent output is decoded as UTF-8; the folder picker falls back to GBK (CP936); the file preview tries UTF-8, then GBK. Git runs with `core.quotepath=false` so Chinese file names show as-is.
|
||||
- **Git Bash for the agents (1.3).** On Windows `bash` on `PATH` is often `C:\Windows\System32\bash.exe`, the WSL launcher. The daemon looks for Git Bash next to `git.exe` on `PATH`, then in Program Files / Program Files (x86) / `%LOCALAPPDATA%\Programs\Git` / scoop, then `X:\Git` and `X:\Program Files\Git` on the other drives (probed in a short-lived child process with a 1.5 s limit, so a dead network drive can't stall it), never taking System32 / SysWOW64 / WindowsApps bash; 设置 → Bash 路径 / Settings → Bash path overrides it (validated). Each Agent spawn gets `CLAUDE_CODE_GIT_BASH_PATH` (Claude Code), `OPENCODE_GIT_BASH_PATH` (OpenCode) and Git's `bin` first on `PATH` (Pi's `where bash.exe`, dsh's `bash`) — per spawn only, no user config file is written and the terminal keeps your own environment. When none is found, Claude Code / Pi / dsh conversations show a hint with a Git for Windows link. Nothing changes on macOS / Linux.
|
||||
- **Encoding.** Agent protocol output is UTF-8. Raw process output (Agent stderr, version / model probes, git errors, the no-PTY terminal) is decoded per chunk: valid UTF-8 stays UTF-8, anything else on Windows is read in the system ANSI code page (GBK on Chinese Windows) with Node's built-in `TextDecoder`, keeping at most 3 bytes of a character split across chunks; the PTY terminal already gets UTF-8 from ConPTY. The folder picker falls back to GBK (CP936); the file preview tries UTF-8, then GBK. Git runs with `core.quotepath=false` so Chinese file names show as-is.
|
||||
- **Magpie desktop window → `http://127.0.0.1`.** Magpie's window origin is `wails://` on macOS/Linux and `http://wails.localhost` on Windows. The plugin frame navigates itself to the gate on `http://127.0.0.1`, as Magpie's plugin-runtime docs describe for page plugins. On macOS, Magpie's `Info.plist` has no ATS keys and ATS exempts IP-address hosts by default, and the main window has no CSP that could block the frame, so the navigation is allowed. This is the one item that still needs a run on a real Mac.
|
||||
- **Clickjacking / `frame-ancestors`.** Not set on purpose. The UI must load inside Magpie's frame on every mode: `wails://` (a non-special scheme whose origin WebKit may treat as opaque), `http://wails.localhost`, and `magpie web` on any address, LAN IP or reverse proxy. No `frame-ancestors` list covers all of them without breaking one. Framing the console also requires the gate key, which only Magpie's per-run page path hands out.
|
||||
- **Clickjacking / `frame-ancestors`.** The gate's `/app` wrapper (1.3) allows only loopback pages (`'self'`, `http://127.0.0.1:*`, `http://localhost:*`, `http://[::1]:*`) and Magpie's desktop window (`wails:` on macOS / Linux, `http://wails.localhost:*` on Windows) as its ancestors. `magpie web` opened through a non-loopback address (a LAN IP or a reverse proxy) is not in that list, so open it as `http://127.0.0.1:<port>` / `http://localhost:<port>` on the same computer to use the console there. The daemon page sets no `frame-ancestors` of its own: the wrapper is its only parent. Getting a working console into any frame still requires the gate key, which only Magpie's per-run page path hands out, and the token, which only travels in the gate's redirect fragment.
|
||||
|
||||
## Reproducible build
|
||||
|
||||
@@ -202,12 +206,14 @@ npm run shot:v1 # screenshot set (light/dark × scenes → _tmp/shots-v1/)
|
||||
# Mock (no real tokens)
|
||||
AGENT_CONSOLE_MOCK=1 npm run dev
|
||||
# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit /serve (local links, 1.2)
|
||||
# /tools (8 tool calls → folded summary) /winrun (long Windows commands + an approval) /tasks (checklist + code block) /bashhint (1.3)
|
||||
```
|
||||
|
||||
| Env | Purpose |
|
||||
|---|---|
|
||||
| `AGENT_CONSOLE_PORT` | gate port in the plugin / daemon port in standalone mode (3488; plugin `options.port` wins) |
|
||||
| `AGENT_CONSOLE_MOCK=1` | register the mock provider |
|
||||
| `AGENT_CONSOLE_MOCK_START_MS` / `AGENT_CONSOLE_MOCK_DETECT_MS` | mock only: delay the Agent start / detection (a slow start like real Agents on Windows; e2e uses `E2E_MOCK_START_MS`, default 1200) |
|
||||
| `AGENT_CONSOLE_TOKEN` | fixed page token (tests/screenshots only; do not set in production) |
|
||||
| `AGENT_CONSOLE_IDLE_EXIT_MIN` | idle auto-exit minutes (default 60) |
|
||||
| `XDG_CONFIG_HOME` | data root (`_tmp/xdg-dev` in development) |
|
||||
@@ -218,4 +224,4 @@ Daemon CLI: `node daemon/dist/main.js [--port N|0] [--data DIR] [--token T] [--p
|
||||
|
||||
MIT (see LICENSE). Third-party licenses are in THIRD-PARTY-NOTICES.md: the 5 installed packages and the 11 bundled into `app/app.js` (mostly MIT; DOMPurify MPL-2.0/Apache-2.0, highlight.js BSD-3-Clause, lucide-react ISC). Build/test: esbuild, vitest, TypeScript, playwright-core.
|
||||
|
||||
Architecture takes cues from Paseo (persistent daemon + provider abstraction) and T3 Code (timeline shape and three-column layout) — ideas only, no copied code.
|
||||
Architecture takes cues from Paseo (persistent daemon + provider abstraction) and T3 Code (timeline shape and three-column layout), and the 1.3 timeline look from Better Paseo (MIT) — ideas only, no copied code.
|
||||
|
||||
@@ -135,9 +135,19 @@ test("the gate: Host checked, any Origin refused, the token only in the # fragme
|
||||
expect(opened).toBe(0)
|
||||
const ok = await get(port, `/open?k=${key}&theme=dark`)
|
||||
expect(ok.status).toBe(302)
|
||||
expect(ok.headers.location).toBe(`http://127.0.0.1:45678/?theme=dark#t=${token}`)
|
||||
// 1.3: the gate sends the frame to its own wrapper page on the stable port; the daemon port rides in the fragment too
|
||||
expect(ok.headers.location).toBe(`http://127.0.0.1:${port}/app?theme=dark#t=${token}&p=45678`)
|
||||
expect(ok.headers["access-control-allow-origin"]).toBeUndefined()
|
||||
expect(ok.body).not.toContain(token)
|
||||
const app = await get(port, "/app?theme=dark")
|
||||
expect(app.status).toBe(200)
|
||||
expect(app.headers["content-security-policy"]).toBeTruthy()
|
||||
// only loopback pages and Magpie's own window may frame the wrapper
|
||||
expect(app.headers["content-security-policy"]).toContain("frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:")
|
||||
expect(app.body).not.toContain(token)
|
||||
expect(app.body).not.toContain(key)
|
||||
expect((await get(port, "/app", { host: `evil.example:${port}` })).status).toBe(421)
|
||||
expect((await get(port, "/app", { origin: "https://evil.example" })).status).toBe(403)
|
||||
} finally {
|
||||
await gate.close()
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+785
-150
File diff suppressed because it is too large
Load Diff
+1
-1
File diff suppressed because one or more lines are too long
@@ -17,17 +17,27 @@ import { Coalescer } from "../timeline/coalescer.js";
|
||||
import { ApiError } from "../ws/methods.js";
|
||||
import { log } from "../log.js";
|
||||
import { tr } from "../util/i18n.js";
|
||||
import { agentShellReady, bashMissingFor } from "../util/agentShell.js";
|
||||
import { resolveMentions, withMentions, type Mention, type MentionRef } from "../util/mentions.js";
|
||||
import {
|
||||
codexSlashCommandsFromEntries,
|
||||
loadCodexSlashEntries,
|
||||
} from "../providers/codex/commands.js";
|
||||
|
||||
/** A message's own words for its conversation title: leading "> " quote blocks dropped (kept when that is all there is) */
|
||||
export function titleText(text: string): string {
|
||||
const blocks = text.trim().split(/\n{2,}/);
|
||||
let i = 0;
|
||||
while (i < blocks.length && blocks[i]!.split("\n").every((l) => l === ">" || l.startsWith("> "))) i++;
|
||||
const rest = blocks.slice(i).join(" ").trim();
|
||||
return (rest || text.trim().replace(/^>\s?/gm, "")).replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
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 }[]; mentions?: Mention[] };
|
||||
type QueuedMessage = { id: string; text: string; attachments: { path: string; mime: string; name?: string }[]; mentions?: Mention[]; clientId?: string };
|
||||
type PendingRequest = {
|
||||
kind: "permission" | "question";
|
||||
requestId: string;
|
||||
@@ -54,6 +64,8 @@ type Runtime = {
|
||||
/** 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;
|
||||
/** 1.3: the "Git Bash not found" hint was already shown in this conversation during this daemon run */
|
||||
bashHinted?: boolean;
|
||||
};
|
||||
|
||||
type DeltaType = "assistant_delta" | "reasoning_delta" | "tool_output_delta";
|
||||
@@ -167,11 +179,13 @@ export class AgentManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
runtimeInfo(threadId: string): { status: string; queue: unknown[]; pending: unknown[] } | null {
|
||||
runtimeInfo(threadId: string): { status: string; starting: boolean; queue: unknown[]; pending: unknown[] } | null {
|
||||
const rt = this.runtimes.get(threadId);
|
||||
if (!rt) return null;
|
||||
return {
|
||||
status: rt.status,
|
||||
// true while startTurn runs (until session.send has returned): a "steer" sent then is queued instead
|
||||
starting: rt.starting,
|
||||
queue: rt.queue,
|
||||
pending: [...rt.pending.values()].map((p) => ({
|
||||
requestId: p.requestId,
|
||||
@@ -220,7 +234,9 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
// ---- send ----
|
||||
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[]; mentions?: MentionRef[] }, behavior: SendBehavior = "queue"): Promise<"started" | "steered" | "queued"> {
|
||||
/** clientId: the page's id for its optimistic bubble; it rides on the user_message event so the page can swap the
|
||||
* bubble for the real one without a duplicate or a jump */
|
||||
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[]; mentions?: MentionRef[]; clientId?: string }, behavior: SendBehavior = "queue"): Promise<"started" | "steered" | "queued"> {
|
||||
const meta = await this.mustThread(threadId);
|
||||
const mentions = await this.resolveMentionRefs(threadId, meta.projectId, input.mentions);
|
||||
if (meta.archived) {
|
||||
@@ -253,6 +269,7 @@ export class AgentManager {
|
||||
steered: true,
|
||||
attachments: this.attachmentLabels(attachmentRefs),
|
||||
...(mentions.length ? { mentions } : {}),
|
||||
...(input.clientId ? { clientId: input.clientId } : {}),
|
||||
});
|
||||
return "steered";
|
||||
} catch (e) {
|
||||
@@ -260,56 +277,71 @@ export class AgentManager {
|
||||
log("info", `thread ${threadId} 插话失败,改为排队:${String(e)}`);
|
||||
}
|
||||
}
|
||||
const q: QueuedMessage = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs, ...(mentions.length ? { mentions } : {}) };
|
||||
const q: QueuedMessage = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs, ...(mentions.length ? { mentions } : {}), ...(input.clientId ? { clientId: input.clientId } : {}) };
|
||||
rt.queue.push(q);
|
||||
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
|
||||
return "queued";
|
||||
}
|
||||
|
||||
await this.startTurn(threadId, input.text, attachmentRefs, mentions);
|
||||
await this.startTurn(threadId, input.text, attachmentRefs, mentions, input.clientId);
|
||||
return "started";
|
||||
}
|
||||
|
||||
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[] = []): Promise<void> {
|
||||
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[] = [], clientId?: string): Promise<void> {
|
||||
const rt = this.rt(threadId);
|
||||
rt.starting = true;
|
||||
try {
|
||||
await this.startTurnInner(threadId, text, attachmentRefs, mentions);
|
||||
await this.startTurnInner(threadId, text, attachmentRefs, mentions, clientId);
|
||||
} finally {
|
||||
rt.starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async startTurnInner(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[]): Promise<void> {
|
||||
private async startTurnInner(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[], clientId?: string): Promise<void> {
|
||||
const meta = await this.mustThread(threadId);
|
||||
const rt = this.rt(threadId);
|
||||
// Conversations that already ran (have a providerSessionId) ignore "disabled": disabling only blocks new conversations
|
||||
const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId });
|
||||
const allowDisabled = !!meta.providerSessionId;
|
||||
// Cheap checks only (no CLI started) before the message is accepted: a bad Agent id or a disabled one is refused outright
|
||||
this.assertProviderAllowed(meta.provider, await this.settings.get(), { allowDisabled });
|
||||
|
||||
if (!rt.session) {
|
||||
await this.setStatus(threadId, "initializing");
|
||||
try {
|
||||
await this.createSessionIfNeeded(threadId, { updateStatus: true });
|
||||
} catch (e) {
|
||||
await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sessionStartFailed", { detail: String((e as Error)?.message ?? e) }) });
|
||||
await this.appendRaw(threadId, { type: "turn_ended", status: "failed", error: String((e as Error)?.message ?? e) } as Partial<TimelineEvent> & { type: "turn_ended" });
|
||||
await this.setStatus(threadId, "error");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto title
|
||||
const trimmed = text.trim();
|
||||
if (meta.titleAuto && trimmed) {
|
||||
await this.threads.patch(threadId, { title: trimmed.slice(0, 40), titleAuto: true });
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
// 1.3: the user's message is persisted and pushed FIRST. It used to wait for detection (a CLI "--version" on a cold
|
||||
// cache) and the Agent start (spawn + ACP initialize/session/new), which on Windows takes seconds, so the bubble came late.
|
||||
await this.appendRaw(threadId, {
|
||||
type: "user_message",
|
||||
text,
|
||||
attachments: this.attachmentLabels(attachmentRefs),
|
||||
...(mentions.length ? { mentions } : {}),
|
||||
...(clientId ? { clientId } : {}),
|
||||
});
|
||||
// Auto title (1.3: without the leading "> " quote blocks that "添加到对话" puts in front of the message)
|
||||
const trimmed = titleText(text);
|
||||
if (meta.titleAuto && trimmed) {
|
||||
await this.threads.patch(threadId, { title: trimmed.slice(0, 40), titleAuto: true });
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
|
||||
if (!rt.session) {
|
||||
await this.setStatus(threadId, "initializing");
|
||||
try {
|
||||
await this.assertProviderUsable(meta.provider, { allowDisabled });
|
||||
await this.createSessionIfNeeded(threadId, { updateStatus: true });
|
||||
} catch (e) {
|
||||
await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sessionStartFailed", { detail: String((e as Error)?.message ?? e) }) });
|
||||
await this.appendRaw(threadId, { type: "turn_ended", status: "failed", error: String((e as Error)?.message ?? e) } as Partial<TimelineEvent> & { type: "turn_ended" });
|
||||
await this.threads.patch(threadId, { lastTurnStatus: "failed" });
|
||||
await this.setStatus(threadId, "error");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
// A live session needs no detection: the Agent is running (the 60 s detect cache used to re-run "--version" on later sends)
|
||||
|
||||
// Windows without Git Bash: say so before the agent's first command fails on the WSL launcher
|
||||
await agentShellReady();
|
||||
if (!rt.bashHinted && bashMissingFor(meta.provider)) {
|
||||
rt.bashHinted = true;
|
||||
await this.appendRaw(threadId, { type: "notice", level: "warn", code: "bash_missing", message: tr("notice.bashMissing") });
|
||||
}
|
||||
await this.setStatus(threadId, "running");
|
||||
try {
|
||||
const images = await this.resolveAttachments(attachmentRefs);
|
||||
@@ -456,7 +488,7 @@ export class AgentManager {
|
||||
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)
|
||||
await this.startTurn(threadId, next.text, next.attachments, next.mentions ?? []).catch((e) => {
|
||||
await this.startTurn(threadId, next.text, next.attachments, next.mentions ?? [], next.clientId).catch((e) => {
|
||||
log("warn", `thread ${threadId} 排队消息启动失败:${String(e)}`);
|
||||
});
|
||||
}
|
||||
@@ -605,7 +637,10 @@ export class AgentManager {
|
||||
throw new ApiError("busy", tr("err.busySwitch"));
|
||||
}
|
||||
const events = await this.threads.readEvents(threadId, 0, 5000);
|
||||
if (events.some((e) => e.type === "user_message")) {
|
||||
// 1.3: the user's message is now saved before the Agent starts, so a first message whose Agent never started
|
||||
// (no session id, no turn, no reply) does not lock the conversation to that Agent
|
||||
const neverRan = !meta.providerSessionId && !events.some((e) => e.type === "turn_started" || e.type === "assistant_message" || e.type === "tool_call");
|
||||
if (events.some((e) => e.type === "user_message") && !neverRan) {
|
||||
throw new ApiError("bad_params", tr("err.hasMessages"));
|
||||
}
|
||||
const p = await this.assertProviderUsable(providerId);
|
||||
@@ -765,6 +800,8 @@ export class AgentManager {
|
||||
const settings = await this.settings.get();
|
||||
const launch = launchFromSettings(settings, meta.provider);
|
||||
rt.deltasOnly = !!provider.capabilities.deltasOnly;
|
||||
// The agent's environment gets the Git Bash found at start / after a settings change (Windows)
|
||||
await agentShellReady();
|
||||
rt.session = await provider.createSession({
|
||||
threadId,
|
||||
cwd: proj.path,
|
||||
@@ -797,10 +834,10 @@ export class AgentManager {
|
||||
return getProvider(meta.provider);
|
||||
}
|
||||
|
||||
private async assertProviderUsable(providerId: string, opts: { allowDisabled?: boolean } = {}): Promise<Provider> {
|
||||
/** The checks that start nothing: a known Agent, enabled (unless allowDisabled), not a planned one */
|
||||
private assertProviderAllowed(providerId: string, s: Awaited<ReturnType<SettingsStore["get"]>>, opts: { allowDisabled?: boolean } = {}): Provider {
|
||||
const p = getProvider(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", tr("provider.disabledNamed", { name: p.name }));
|
||||
}
|
||||
@@ -808,6 +845,12 @@ export class AgentManager {
|
||||
if (entry && !providerCreatable(entry.status)) {
|
||||
throw new ApiError("bad_params", tr("provider.plannedNamed", { name: p.name }));
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
private async assertProviderUsable(providerId: string, opts: { allowDisabled?: boolean } = {}): Promise<Provider> {
|
||||
const s = await this.settings.get();
|
||||
const p = this.assertProviderAllowed(providerId, s, opts);
|
||||
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;
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
import { decodeOutput } from "../util/decode.js";
|
||||
|
||||
export type GitFileEntry = {
|
||||
path: string;
|
||||
@@ -19,10 +20,12 @@ const DIFF_LIMIT = 1024 * 1024;
|
||||
function runGit(cwd: string, args: string[]): Promise<{ code: number; out: string; err: string }> {
|
||||
return new Promise((res) => {
|
||||
// core.quotepath=false: non-ASCII paths (e.g. Chinese file names) are no longer turned into "\346\226\207" octal escapes in diff headers
|
||||
execFile("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (e, stdout, stderr) => {
|
||||
// stdout (paths, diffs) is UTF-8; stderr may carry hook / credential-helper messages in the Windows code page (1.3)
|
||||
execFile("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT, maxBuffer: 8 * 1024 * 1024, windowsHide: true, encoding: "buffer" }, (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 ? tr("git.missing") : String(stderr || (e?.message ?? "")) });
|
||||
const errText = stderr?.length ? decodeOutput(stderr) : "";
|
||||
res({ code, out: stdout ? stdout.toString("utf8") : "", err: missing ? tr("git.missing") : errText || (e?.message ?? "") });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { initLog, log } from "./log.js";
|
||||
import { createHttpServer } from "./http.js";
|
||||
import { AttachmentStore } from "./store/attachments.js";
|
||||
import { SettingsStore } from "./store/settings.js";
|
||||
import { refreshAgentShell } from "./util/agentShell.js";
|
||||
import { ProjectsStore } from "./store/projects.js";
|
||||
import { ThreadsStore } from "./store/threads.js";
|
||||
import { Gateway } from "./ws/gateway.js";
|
||||
@@ -122,6 +123,8 @@ async function main(): Promise<void> {
|
||||
if (bound && typeof bound === "object") cfg.port = bound.port;
|
||||
// Ready line: the plugin host reads this line from stdout to learn the actual port (port and pid only, no token)
|
||||
process.stdout.write(JSON.stringify({ agentConsoleReady: true, port: cfg.port, pid: process.pid }) + "\n");
|
||||
// Windows: find Git Bash for the agents (manual Settings → Bash path first); a no-op elsewhere
|
||||
void settings.get().then((s) => refreshAgentShell(typeof s.bashPath === "string" ? s.bashPath : ""));
|
||||
// Background warm-up: after start, pull detection/models for enabled providers into the cache so the first page open doesn't wait
|
||||
void (async () => {
|
||||
const { warmProviderCache } = await import("./providers/warm.js");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ModelInfo } from "../types.js";
|
||||
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
|
||||
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
export function runCli(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 25000): Promise<string> {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
@@ -12,8 +13,10 @@ export function runCli(r: ResolveResult & { ok: true }, args: string[], timeoutM
|
||||
} catch {}
|
||||
reject(new Error("timeout"));
|
||||
}, timeoutMs);
|
||||
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
// 1.3: --version / model lists may come back in the Windows code page (GBK) when something fails
|
||||
const od = new OutputDecoder(), ed = new OutputDecoder();
|
||||
p.stdout?.on("data", (c: Buffer) => (out += od.write(c)));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += ed.write(c)));
|
||||
p.on("error", reject);
|
||||
p.on("close", () => {
|
||||
clearTimeout(t);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ModelInfo } from "../types.js";
|
||||
import { killTree, spawnBin, type ResolveResult } from "../../util/bin.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
function runCmd(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 20000): Promise<string> {
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
@@ -11,8 +12,10 @@ function runCmd(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 200
|
||||
} catch {}
|
||||
reject(new Error("timeout"));
|
||||
}, timeoutMs);
|
||||
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
// 1.3: --version / model lists may come back in the Windows code page (GBK) when something fails
|
||||
const od = new OutputDecoder(), ed = new OutputDecoder();
|
||||
p.stdout?.on("data", (c: Buffer) => (out += od.write(c)));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += ed.write(c)));
|
||||
p.on("error", reject);
|
||||
p.on("close", () => {
|
||||
clearTimeout(t);
|
||||
|
||||
@@ -88,8 +88,9 @@ export function probeAcpRaw(
|
||||
child.on("error", (e) => finish(e));
|
||||
child.on("close", () => finish(new Error("ACP 进程提前退出")));
|
||||
child.stderr?.on("data", () => {});
|
||||
child.stdout?.on("data", (d: Buffer) => {
|
||||
buf += d.toString();
|
||||
child.stdout?.setEncoding("utf8"); // protocol stdout is UTF-8; setEncoding keeps a character split across chunks intact
|
||||
child.stdout?.on("data", (d: string) => {
|
||||
buf += d;
|
||||
let n: number;
|
||||
while ((n = buf.indexOf("\n")) >= 0) {
|
||||
const line = buf.slice(0, n).trim();
|
||||
|
||||
@@ -5,6 +5,7 @@ import { resolveLaunch } from "../launch.js";
|
||||
import { PLACEHOLDER_MODEL_NAME } from "../types.js";
|
||||
import { AcpSession } from "./session.js";
|
||||
import { knownPromptCaps } from "./promptCaps.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
export type AcpProviderConfig = {
|
||||
id: string;
|
||||
@@ -57,8 +58,10 @@ function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs =
|
||||
} catch {}
|
||||
reject(new Error("timeout"));
|
||||
}, timeoutMs);
|
||||
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
// 1.3: --version / model lists may come back in the Windows code page (GBK) when something fails
|
||||
const od = new OutputDecoder(), ed = new OutputDecoder();
|
||||
p.stdout?.on("data", (c: Buffer) => (out += od.write(c)));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += ed.write(c)));
|
||||
p.on("error", reject);
|
||||
p.on("close", (code) => {
|
||||
clearTimeout(t);
|
||||
|
||||
@@ -19,6 +19,7 @@ import { tr } from "../../util/i18n.js";
|
||||
type AcpSelectValue = { value?: string; name?: string; options?: AcpSelectValue[] };
|
||||
type AcpConfigOption = { id: string; category?: string | null; type?: string; currentValue?: unknown; options?: AcpSelectValue[] };
|
||||
import { log } from "../../log.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
const rid = () => Math.random().toString(36).slice(2, 10);
|
||||
|
||||
@@ -97,8 +98,9 @@ export class AcpSession implements ProviderSession {
|
||||
if (!bin.ok) throw new Error(bin.reason);
|
||||
try {
|
||||
this.child = spawnResolved(bin, launchArgv(this.o.acpArgs, this.o.launch), { cwd: this.o.cwd });
|
||||
const errDec = new OutputDecoder(); // 1.3: stderr may be in the Windows code page (GBK)
|
||||
this.child.stderr?.on("data", (d: Buffer) => {
|
||||
const t = d.toString().trim();
|
||||
const t = errDec.write(d).trim();
|
||||
if (t) log("info", `[${this.o.binName} acp] ${t.slice(0, 500)}`);
|
||||
});
|
||||
this.child.on("error", (e) => this.failInit(e));
|
||||
|
||||
@@ -13,6 +13,7 @@ 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";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
export type ClaudeBin = ResolveResult & { ok: true };
|
||||
export type Json = Record<string, unknown>;
|
||||
@@ -91,8 +92,9 @@ export class ClaudeCli {
|
||||
});
|
||||
this.child.stdout?.setEncoding("utf8");
|
||||
this.child.stdout?.on("data", (d: string) => this.onData(d));
|
||||
const errDec = new OutputDecoder(); // 1.3: stderr may be in the Windows code page (GBK)
|
||||
this.child.stderr?.on("data", (d: Buffer) => {
|
||||
this.stderrTail = (this.stderrTail + d.toString()).slice(-4096);
|
||||
this.stderrTail = (this.stderrTail + errDec.write(d)).slice(-4096);
|
||||
});
|
||||
this.child.stdin?.on("error", () => {}); // EPIPE after the CLI exits: reported through exited
|
||||
this.exited = new Promise((resolve) => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import { mapSdkMessage, newMapState } from "./map.js";
|
||||
import type { ProviderEvent } from "../../timeline/types.js";
|
||||
import { tr } from "../../util/i18n.js";
|
||||
import { resolveLaunch } from "../launch.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
const INSTALL_HINT = "npm i -g @anthropic-ai/claude-code";
|
||||
|
||||
@@ -33,8 +34,10 @@ function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs =
|
||||
} catch {}
|
||||
reject(new Error("timeout"));
|
||||
}, timeoutMs);
|
||||
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
// 1.3: --version / model lists may come back in the Windows code page (GBK) when something fails
|
||||
const od = new OutputDecoder(), ed = new OutputDecoder();
|
||||
p.stdout?.on("data", (c: Buffer) => (out += od.write(c)));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += ed.write(c)));
|
||||
p.on("error", reject);
|
||||
p.on("close", (code) => {
|
||||
clearTimeout(t);
|
||||
|
||||
@@ -12,6 +12,7 @@ import { PLACEHOLDER_MODEL_NAME } from "../types.js";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
|
||||
const INSTALL_HINT = "npm i -g @openai/codex";
|
||||
|
||||
@@ -42,8 +43,10 @@ function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs =
|
||||
} catch {}
|
||||
reject(new Error("timeout"));
|
||||
}, timeoutMs);
|
||||
p.stdout?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += c.toString()));
|
||||
// 1.3: --version / model lists may come back in the Windows code page (GBK) when something fails
|
||||
const od = new OutputDecoder(), ed = new OutputDecoder();
|
||||
p.stdout?.on("data", (c: Buffer) => (out += od.write(c)));
|
||||
p.stderr?.on("data", (c: Buffer) => (out += ed.write(c)));
|
||||
p.on("error", reject);
|
||||
p.on("close", (code) => {
|
||||
clearTimeout(t);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { log } from "../../log.js";
|
||||
import { killTree, trackTree, type Argv } from "../../util/bin.js";
|
||||
import { OutputDecoder } from "../../util/decode.js";
|
||||
import { withAgentShell } from "../../util/agentShell.js";
|
||||
|
||||
export class CodexRpcError extends Error {
|
||||
code?: number;
|
||||
@@ -37,7 +39,7 @@ export class CodexRpc {
|
||||
) {
|
||||
this.proc = spawn(argv.cmd, argv.args, {
|
||||
cwd: opts.cwd,
|
||||
env: opts.env ?? process.env,
|
||||
env: withAgentShell(opts.env ?? process.env),
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
...(argv.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
@@ -47,9 +49,9 @@ export class CodexRpc {
|
||||
trackTree(this.proc);
|
||||
this.proc.stdout!.setEncoding("utf8");
|
||||
this.proc.stdout!.on("data", (chunk: string) => this.onData(chunk));
|
||||
this.proc.stderr!.setEncoding("utf8");
|
||||
this.proc.stderr!.on("data", (chunk: string) => {
|
||||
this.stderrTail = (this.stderrTail + chunk).slice(-4096);
|
||||
const errDec = new OutputDecoder(); // 1.3: stderr may be in the Windows code page (GBK)
|
||||
this.proc.stderr!.on("data", (chunk: Buffer) => {
|
||||
this.stderrTail = (this.stderrTail + errDec.write(chunk)).slice(-4096);
|
||||
});
|
||||
this.proc.on("error", () => this.failAll());
|
||||
this.proc.on("close", (code) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 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.
|
||||
// Scripts by message prefix: default /perm /plan /ask /slow /error /long /exit /tools /winrun /tasks; supports steer/interrupt/resume.
|
||||
import { tr } from "../util/i18n.js";
|
||||
import type { Provider, ProviderSession, DetectResult, ModelInfo,
|
||||
Mode, SendInput, RespondAnswer, SlashCommand,
|
||||
@@ -283,11 +283,6 @@ async function scriptPlan(ctx: Ctx): Promise<void> {
|
||||
type: "plan",
|
||||
itemId: "plan1",
|
||||
markdown: "## 实施计划\n\n1. 改 `src/index.ts` 入口\n2. 更新测试\n3. 跑一遍 e2e",
|
||||
entries: [
|
||||
{ step: "改 src/index.ts 入口", status: "pending" },
|
||||
{ step: "更新测试", status: "pending" },
|
||||
{ step: "跑一遍 e2e", status: "pending" },
|
||||
],
|
||||
});
|
||||
const requestId = "perm-" + rid();
|
||||
emit({
|
||||
@@ -385,6 +380,10 @@ function pickScript(text: string): (ctx: Ctx) => Promise<void> {
|
||||
if (t.startsWith("/long")) return scriptLong;
|
||||
if (t.startsWith("/exit")) return scriptExit;
|
||||
if (t.startsWith("/serve")) return scriptServe;
|
||||
if (t.startsWith("/tools")) return scriptTools;
|
||||
if (t.startsWith("/bashhint")) return scriptBashHint;
|
||||
if (t.startsWith("/winrun")) return scriptWinRun;
|
||||
if (t.startsWith("/tasks")) return scriptTasks;
|
||||
return scriptDefault;
|
||||
}
|
||||
|
||||
@@ -403,6 +402,157 @@ function chunkText(s: string, n: number): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
// "/tools" (1.3): thinking between eight tool calls (more than the six shown flat), one failure and a slow last command,
|
||||
// for the folded tool summary
|
||||
async function scriptTools(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
const sleepA = (ms: number) => sleepAbortable(ms, ctx);
|
||||
const tool = async (id: string, kind: string, title: string, input: Record<string, unknown>, end: Record<string, unknown>, ms = 150) => {
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "running", input } as Parameters<Ctx["emit"]>[0]);
|
||||
if (await sleepA(ms)) return true;
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "ok", durationMs: ms, ...end } as Parameters<Ctx["emit"]>[0]);
|
||||
return false;
|
||||
};
|
||||
emit({ type: "reasoning", itemId: "tr1", text: "先看一下测试和配置。" });
|
||||
if (await tool("x1", "read", "读取 package.json", { file_path: "package.json" }, { output: "{…}" })) return;
|
||||
if (await tool("x2", "search", '搜索 "describe("', { pattern: "describe(" }, { output: "12 处匹配" })) return;
|
||||
emit({ type: "reasoning", itemId: "tr2", text: "" });
|
||||
if (await tool("x3", "read", "读取 test/app.test.ts", { file_path: "test/app.test.ts" }, { output: "…" })) return;
|
||||
if (await tool("x3b", "read", "读取 test/server.test.ts", { file_path: "test/server.test.ts" }, { output: "…" })) return;
|
||||
if (await tool("x3c", "search", '搜索 "createServer"', { pattern: "createServer" }, { output: "3 处匹配" })) return;
|
||||
emit({ type: "tool_call", itemId: "x4", kind: "bash", title: "运行 npm run lint", status: "running", input: { command: "npm run lint" } });
|
||||
if (await sleepA(200)) return;
|
||||
emit({
|
||||
type: "tool_call", itemId: "x4", kind: "bash", title: "运行 npm run lint", status: "failed", exitCode: 1, durationMs: 200,
|
||||
output: "src/app.ts:12:7 error 'unused' is assigned a value but never used no-unused-vars\n\n✖ 1 problem (1 error, 0 warnings)",
|
||||
});
|
||||
const oldStr = "const unused = 1;\nexport const app = 2;";
|
||||
const newStr = "export const app = 2;";
|
||||
if (await tool("x5", "edit", "编辑 src/app.ts", { file_path: "src/app.ts", old_string: oldStr, new_string: newStr },
|
||||
{ detail: editDetail({ path: "src/app.ts", old: oldStr, new: newStr }) })) return;
|
||||
emit({ type: "reasoning", itemId: "tr3", text: "lint 修好了,再跑一遍完整测试。" });
|
||||
const cmd = "npm test -- --reporter=verbose --coverage --run test/app.test.ts test/server.test.ts test/client.test.ts";
|
||||
emit({ type: "tool_call", itemId: "x6", kind: "bash", title: `运行 ${cmd}`, status: "running", input: { command: cmd } });
|
||||
// Slow on purpose: the one-line "正在运行:…" row stays up for screenshots (QA: AGENT_CONSOLE_MOCK_TOOLS_MS)
|
||||
const slow = Number(process.env.AGENT_CONSOLE_MOCK_TOOLS_MS) || 2500;
|
||||
if (await sleepA(slow)) return;
|
||||
emit({ type: "tool_call", itemId: "x6", kind: "bash", title: `运行 ${cmd}`, status: "ok", output: "✓ 3 个测试文件通过", exitCode: 0, durationMs: slow });
|
||||
const reply = ctx.replyPrefix() + "lint 报错已修复,测试全部通过。";
|
||||
emit({ type: "assistant_message", itemId: "tm1", text: reply });
|
||||
}
|
||||
|
||||
// "/winrun" (1.3): Nolan's Windows Cursor turn: short thinking between tool runs, long PowerShell commands (CJK paths),
|
||||
// an approval for one of them, then more groups while the turn is live. The e2e overlap check drives it at ~600 px.
|
||||
async function scriptWinRun(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
const sleepA = (ms: number) => sleepAbortable(ms, ctx);
|
||||
const step = Number(process.env.AGENT_CONSOLE_MOCK_STEP_MS) || 250;
|
||||
const think = async (id: string, text: string) => {
|
||||
for (const ch of chunkText(text, 6)) {
|
||||
emit({ type: "reasoning_delta", itemId: id, text: ch });
|
||||
if (await sleepA(40)) return true;
|
||||
}
|
||||
emit({ type: "reasoning", itemId: id, text });
|
||||
return false;
|
||||
};
|
||||
const tool = async (id: string, kind: string, title: string, input: Record<string, unknown>, ms = step) => {
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "running", input } as Parameters<Ctx["emit"]>[0]);
|
||||
if (await sleepA(ms)) return true;
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "ok", durationMs: ms, output: "ok" } as Parameters<Ctx["emit"]>[0]);
|
||||
return false;
|
||||
};
|
||||
const dir = "D:\\workwork\\抖音快手自动上传";
|
||||
const start = `Set-Location "${dir}"; if (Test-Path ".venv\\Scripts\\pythonw.exe") { Start-Process -FilePath ".venv\\Scripts\\pythonw.exe" -ArgumentList "-m","app.main" -WorkingDirectory "${dir}"; Write-Host "已启动(源码模式)" } else { Write-Host "venv 不存在,尝试 exe"; Start-Process -FilePath "风景视频工具.exe" -WorkingDirectory "${dir}"; Write-Host "已启动(exe)" }`;
|
||||
const ps = `Get-Process pythonw -ErrorAction SilentlyContinue | Where-Object { $_.Path -like "*抖音快手自动上传*" } | Select-Object Id, Path, StartTime | Format-Table -AutoSize`;
|
||||
if (await think("w1", "先检查是否已有实例在跑。")) return;
|
||||
emit({ type: "assistant_message", itemId: "wm1", text: "先检查是否已有实例在跑,再启动应用。" });
|
||||
if (await tool("s1", "search", "搜索 pythonw", { pattern: "pythonw" })) return;
|
||||
if (await tool("s2", "search", "搜索 app.main", { pattern: "app.main" })) return;
|
||||
if (await think("w2", "看下启动脚本。")) return;
|
||||
if (await tool("s3", "search", "搜索 启动.bat", { pattern: "启动.bat" })) return;
|
||||
if (await tool("r1", "read", "读取 启动.bat", { file_path: `${dir}\\启动.bat` })) return;
|
||||
if (await think("w3", "")) return;
|
||||
if (await tool("b0", "bash", `运行 ${ps}`, { command: ps }, step * 2)) return;
|
||||
if (await think("w4", "没有实例在跑,直接启动。")) return;
|
||||
emit({ type: "tool_call", itemId: "b1", kind: "bash", title: `运行 ${start}`, status: "running", input: { command: start } });
|
||||
if (await sleepA(step)) return;
|
||||
const requestId = "perm-" + rid();
|
||||
emit({
|
||||
type: "permission_request", requestId, title: start, kind: "tool",
|
||||
detail: { command: start, cwd: dir },
|
||||
options: [
|
||||
{ id: "allow-once", label: "Allow once", kind: "allow_once" },
|
||||
{ id: "allow-always", label: "Allow always", kind: "allow_always" },
|
||||
{ id: "reject-once", label: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
const ans = await ctx.waitFor(requestId);
|
||||
if (ans.cancelled || ans.optionId === "reject-once") {
|
||||
emit({ type: "tool_call", itemId: "b1", kind: "bash", title: `运行 ${start}`, status: "failed", output: "Rejected", exitCode: 1 });
|
||||
return;
|
||||
}
|
||||
emit({ type: "tool_call", itemId: "b1", kind: "bash", title: `运行 ${start}`, status: "ok", output: "已启动(源码模式)", exitCode: 0, durationMs: step });
|
||||
if (await think("w5", "改三个配置。")) return;
|
||||
for (const n of [1, 2, 3]) if (await tool(`e${n}`, "edit", `编辑 config/${n}.json`, { file_path: `${dir}\\config\\${n}.json` })) return;
|
||||
if (await think("w6", "确认进程起来了。")) return;
|
||||
if (await tool("r2", "read", "读取 logs/selftest.txt", { file_path: `${dir}\\logs\\selftest.txt` })) return;
|
||||
if (await tool("b2", "bash", `运行 ${ps}`, { command: ps }, Number(process.env.AGENT_CONSOLE_MOCK_TOOLS_MS) || step * 6)) return;
|
||||
emit({ type: "assistant_message", itemId: "wm2", text: ctx.replyPrefix() + "已启动,进程在跑。" });
|
||||
}
|
||||
|
||||
// "/tasks" (1.3 timeline polish): an ACP-style step list (plan entries) that the Agent ticks off between tool calls,
|
||||
// a code block in the reply. AGENT_CONSOLE_MOCK_TASKS_HOLD_MS keeps the turn open on the last step (screenshots).
|
||||
async function scriptTasks(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
const sleepA = (ms: number) => sleepAbortable(ms, ctx);
|
||||
const steps = ["复现偶发失败", "找到竞态", "修复并加固测试"];
|
||||
const plan = (done: number, running: boolean) => emit({
|
||||
type: "plan", itemId: "tk-plan", markdown: steps.map((s) => `- ${s}`).join("\n"),
|
||||
entries: steps.map((step, i) => ({ step, status: i < done ? "completed" : i === done && running ? "in_progress" : "pending" })),
|
||||
});
|
||||
const tool = async (id: string, kind: string, title: string, input: Record<string, unknown>, end: Record<string, unknown> = {}, ms = 120) => {
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "running", input } as Parameters<Ctx["emit"]>[0]);
|
||||
if (await sleepA(ms)) return true;
|
||||
emit({ type: "tool_call", itemId: id, kind, title, status: "ok", durationMs: ms, output: "ok", ...end } as Parameters<Ctx["emit"]>[0]);
|
||||
return false;
|
||||
};
|
||||
plan(0, true);
|
||||
if (await tool("k1", "bash", "运行 npx vitest run src/checkout --repeat 50", { command: "npx vitest run src/checkout --repeat 50" })) return;
|
||||
if (await tool("k2", "read", "读取 src/checkout/useCheckout.ts", { file_path: "src/checkout/useCheckout.ts" })) return;
|
||||
plan(1, true);
|
||||
emit({ type: "reasoning", itemId: "k-th", text: "submit() 没有等 confirmOrder。" });
|
||||
const oldStr = " setStatus(\"pending\");\n void confirmOrder(order.id).then(setStatus);";
|
||||
const newStr = " setStatus(\"pending\");\n try {\n setStatus(await confirmOrder(order.id));\n } catch (error) {\n setStatus(\"failed\");\n throw error;\n }";
|
||||
if (await tool("k3", "edit", "编辑 src/checkout/useCheckout.ts", { file_path: "src/checkout/useCheckout.ts", old_string: oldStr, new_string: newStr },
|
||||
{ detail: editDetail({ path: "src/checkout/useCheckout.ts", old: oldStr, new: newStr }) })) return;
|
||||
plan(2, true);
|
||||
if (await tool("k4", "search", '搜索 "confirmOrder"', { pattern: "confirmOrder" })) return;
|
||||
const hold = Number(process.env.AGENT_CONSOLE_MOCK_TASKS_HOLD_MS) || 0;
|
||||
if (await tool("k5", "bash", "运行 npx tsc --noEmit", { command: "npx tsc --noEmit" }, {}, Math.max(120, hold))) return;
|
||||
plan(3, false);
|
||||
const reply = ctx.replyPrefix() + [
|
||||
"**根因:** `submit()` 丢掉了确认请求的 Promise,订单确认前就返回了。",
|
||||
"",
|
||||
"```ts",
|
||||
"async function submit() {",
|
||||
" setStatus(\"pending\");",
|
||||
" const order = await createOrder(cart);",
|
||||
" setStatus(await confirmOrder(order.id));",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"重复跑 50 次都通过了。",
|
||||
].join("\n");
|
||||
emit({ type: "assistant_message", itemId: "k-msg", text: reply });
|
||||
}
|
||||
|
||||
// "/bashhint" (1.3): the Windows "no Git Bash" hint, for screenshots and e2e on any OS
|
||||
async function scriptBashHint(ctx: Ctx): Promise<void> {
|
||||
ctx.emit({ type: "notice", level: "warn", code: "bash_missing", message: tr("notice.bashMissing") });
|
||||
await sleepAbortable(100, ctx);
|
||||
ctx.emit({ type: "assistant_message", itemId: "bh1", text: ctx.replyPrefix() + "(模拟)" });
|
||||
}
|
||||
|
||||
// "/serve": a reply with local dev-server addresses (1.2 preview links) and one external link
|
||||
async function scriptServe(ctx: Ctx): Promise<void> {
|
||||
const emit = (e: Parameters<Ctx["emit"]>[0]) => ctx.emit(e);
|
||||
@@ -457,6 +607,9 @@ export function createMockProvider(): Provider {
|
||||
name: "Mock(演示)",
|
||||
capabilities: mockCapabilities,
|
||||
async detect(): Promise<DetectResult> {
|
||||
// AGENT_CONSOLE_MOCK_DETECT_MS: a slow "--version" probe (a cold CLI on Windows takes seconds)
|
||||
const d = Number(process.env.AGENT_CONSOLE_MOCK_DETECT_MS) || 0;
|
||||
if (d > 0) await sleep(d);
|
||||
return { available: true, bin: "mock", version: "demo" };
|
||||
},
|
||||
async listModels(): Promise<ModelInfo[]> {
|
||||
@@ -467,6 +620,9 @@ export function createMockProvider(): Provider {
|
||||
},
|
||||
async createSession(o) {
|
||||
mockProviderMetrics.createSessionCalls++;
|
||||
// AGENT_CONSOLE_MOCK_START_MS: a slow agent start (spawn + ACP initialize/session/new on Windows takes seconds)
|
||||
const d = Number(process.env.AGENT_CONSOLE_MOCK_START_MS) || 0;
|
||||
if (d > 0) await sleep(d);
|
||||
return new MockSession(o);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -29,6 +29,8 @@ export type Settings = {
|
||||
providerEnabled?: Record<string, boolean>;
|
||||
/** Advanced: override how a Provider is launched (executable + args array, no shell) */
|
||||
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
|
||||
/** 1.3 (Windows): bash.exe the agents use; empty = detect Git Bash */
|
||||
bashPath?: string;
|
||||
[k: string]: unknown;
|
||||
};
|
||||
|
||||
@@ -87,6 +89,7 @@ export const settingsPatchSchema = z
|
||||
z.object({ executable: z.string().max(4096).optional(), args: z.array(z.string().max(4096)).max(64).optional() }).strict(),
|
||||
),
|
||||
v1Migrated: z.boolean(),
|
||||
bashPath: z.string().max(1024),
|
||||
})
|
||||
.partial()
|
||||
.strict();
|
||||
|
||||
@@ -56,6 +56,15 @@ export class ThreadsStore {
|
||||
this.writeQ = p.catch(() => {});
|
||||
return p;
|
||||
}
|
||||
/** Resolves once no meta / timeline write is queued or in flight (tests remove the data dir only after this) */
|
||||
async idle(): Promise<void> {
|
||||
for (;;) {
|
||||
const q = this.writeQ;
|
||||
await q;
|
||||
await new Promise((r) => setTimeout(r, 0)); // writes queued by the settling ones join the chain first
|
||||
if (q === this.writeQ) return;
|
||||
}
|
||||
}
|
||||
constructor(dataDir: string) {
|
||||
this.dir = join(dataDir, "threads");
|
||||
this.trashDir = join(dataDir, "trash", "threads");
|
||||
|
||||
@@ -6,11 +6,11 @@ import { accessSync, chmodSync, constants as fsc, existsSync, statSync } from "n
|
||||
import { createRequire as moduleRequire } from "node:module";
|
||||
import { release } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
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";
|
||||
import { OutputDecoder } from "../util/decode.js";
|
||||
|
||||
type Pty = {
|
||||
write(data: string): void;
|
||||
@@ -174,9 +174,10 @@ export class TerminalService {
|
||||
detached: process.platform !== "win32",
|
||||
});
|
||||
term.proc = proc;
|
||||
// StringDecoder: no garbling when a multibyte character (e.g. Chinese) is split across two chunks
|
||||
const outDec = new StringDecoder("utf8");
|
||||
const errDec = new StringDecoder("utf8");
|
||||
// 1.3 OutputDecoder: UTF-8, or the Windows code page (cmd.exe / PowerShell 5 print GBK on Chinese Windows);
|
||||
// a multibyte character split across two chunks is kept whole
|
||||
const outDec = new OutputDecoder();
|
||||
const errDec = new OutputDecoder();
|
||||
proc.stdout.on("data", (d: Buffer) => this.onData(term, outDec.write(d)));
|
||||
proc.stderr.on("data", (d: Buffer) => this.onData(term, errDec.write(d)));
|
||||
proc.on("exit", () => this.onExit(term));
|
||||
|
||||
@@ -10,7 +10,7 @@ export type AttachmentRef = { id: string; name: string; mime: string };
|
||||
export type PermissionOption = { id: string; label: string; kind: "allow_once" | "allow_always" | "reject_once" };
|
||||
|
||||
export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[]; clientId?: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_started"; model: string | null; mode: string; effort: string | null }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_delta" | "reasoning_delta" | "tool_output_delta"; itemId: string; text: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_message" | "reasoning"; itemId: string; text: string }
|
||||
@@ -22,7 +22,7 @@ export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question"; requestId: string; questions: unknown[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "notice"; level: "info" | "warn" | "error"; message: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "notice"; level: "info" | "warn" | "error"; message: string; code?: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_ended"; status: "completed" | "interrupted" | "failed"; durationMs?: number; error?: string; filesChanged?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "status"; status: string };
|
||||
|
||||
@@ -42,6 +42,6 @@ export type ProviderEvent =
|
||||
| { type: "question"; requestId: string; questions: unknown[] }
|
||||
| { type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
| { type: "notice"; level: "info" | "warn" | "error"; message: string }
|
||||
| { type: "notice"; level: "info" | "warn" | "error"; message: string; code?: string }
|
||||
| { type: "turn_ended"; turnId: string; status: "completed" | "interrupted" | "failed"; durationMs?: number; error?: string; filesChanged?: number }
|
||||
| { type: "slash_commands"; commands: { name: string; description: string; argumentHint?: string; kind: "command" | "skill" }[] };
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Per-spawn shell environment for the Agent CLIs (1.3, Windows only). See gitBash.ts for why.
|
||||
// refreshAgentShell() runs at daemon start and whenever Settings → Bash path changes; spawnBin / CodexRpc merge withAgentShell()
|
||||
// into the child's environment. The integrated terminal is left with the user's own environment.
|
||||
import { homedir } from "node:os";
|
||||
import { bashEnv, findGitBash, type BashCheck, type BashDeps, type BashFound } from "./gitBash.js";
|
||||
import { log } from "../log.js";
|
||||
|
||||
export type AgentShellStatus = {
|
||||
/** Only Windows needs any of this */
|
||||
needed: boolean;
|
||||
found: BashFound | null;
|
||||
/** The manual setting was set but unusable (then detection ran anyway) */
|
||||
manualError?: Exclude<BashCheck, { ok: true }>["reason"];
|
||||
manual: string;
|
||||
};
|
||||
|
||||
let status: AgentShellStatus = { needed: process.platform === "win32", found: null, manual: "" };
|
||||
let isFileDep: ((p: string) => boolean) | undefined;
|
||||
let ready: Promise<void> = Promise.resolve();
|
||||
let generation = 0;
|
||||
|
||||
/** Agents that run their shell tool through bash on Windows (Codex, Cursor, Copilot, Devin and OpenCode default to PowerShell) */
|
||||
export const BASH_AGENTS = new Set(["claude", "pi", "dsh"]);
|
||||
|
||||
export function refreshAgentShell(
|
||||
manual: string | undefined,
|
||||
o: { platform?: NodeJS.Platform; deps?: BashDeps } = {},
|
||||
): Promise<void> {
|
||||
const platform = o.platform ?? process.platform;
|
||||
const my = ++generation;
|
||||
const m = typeof manual === "string" ? manual : "";
|
||||
if (platform !== "win32") {
|
||||
status = { needed: false, found: null, manual: m };
|
||||
ready = Promise.resolve();
|
||||
return ready;
|
||||
}
|
||||
const env = o.deps?.env ?? process.env;
|
||||
ready = findGitBash(m, { home: homedir(), ...o.deps, env })
|
||||
.then(({ found, manualError }) => {
|
||||
if (my !== generation) return;
|
||||
status = { needed: true, found, manual: m, ...(manualError && !manualError.ok ? { manualError: manualError.reason } : {}) };
|
||||
isFileDep = o.deps?.isFile;
|
||||
if (found) log("info", `Git Bash: ${found.path} (${found.source})`);
|
||||
else log("warn", "Git Bash not found; agents that need bash (Claude Code, Pi, dsh) will show a hint");
|
||||
})
|
||||
.catch((e) => {
|
||||
log("warn", "Git Bash detection failed", { err: String(e) });
|
||||
});
|
||||
return ready;
|
||||
}
|
||||
|
||||
/** Wait (bounded) for the current detection; the first spawn after start or a settings change uses its result. */
|
||||
export function agentShellReady(ms = 3000): Promise<void> {
|
||||
return Promise.race([ready, new Promise<void>((r) => setTimeout(r, ms).unref?.())]);
|
||||
}
|
||||
|
||||
export function agentShellStatus(): AgentShellStatus {
|
||||
return status;
|
||||
}
|
||||
|
||||
/** True when this agent needs bash on this machine and none was found */
|
||||
export function bashMissingFor(providerId: string): boolean {
|
||||
return status.needed && !status.found && BASH_AGENTS.has(providerId);
|
||||
}
|
||||
|
||||
/** The child's environment with the shell overrides merged in (unchanged off Windows or when nothing was found). */
|
||||
export function withAgentShell<T extends Record<string, string | undefined>>(env: T): T {
|
||||
if (!status.needed || !status.found) return env;
|
||||
const overrides = bashEnv(status.found, env, isFileDep);
|
||||
const out: Record<string, string | undefined> = { ...env };
|
||||
for (const [k, v] of Object.entries(overrides)) {
|
||||
// PATH may be spelled Path on Windows: replace whichever key the base uses
|
||||
const same = Object.keys(out).find((x) => x.toUpperCase() === k.toUpperCase() && x !== k);
|
||||
if (same && k.toUpperCase() === "PATH") delete out[same];
|
||||
out[k] = v;
|
||||
}
|
||||
return out as T;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { readFile } from "node:fs/promises";
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { tr } from "./i18n.js";
|
||||
import { withAgentShell } from "./agentShell.js";
|
||||
|
||||
const IS_WIN = process.platform === "win32";
|
||||
const cache = new Map<string, { out: ResolveResult; at: number }>();
|
||||
@@ -96,6 +97,8 @@ export function spawnBin(
|
||||
const child = spawn(a.cmd, a.args, {
|
||||
windowsHide: true,
|
||||
...rest,
|
||||
// Windows: Git Bash for the agent (CLAUDE_CODE_GIT_BASH_PATH, OPENCODE_GIT_BASH_PATH, PATH); unchanged elsewhere
|
||||
env: withAgentShell(rest.env ?? process.env),
|
||||
...(a.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
||||
...(group && !IS_WIN ? { detached: true } : {}),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// 1.3: decoding raw process output (stderr tails, probe output, the no-PTY terminal) that may be UTF-8 or, on Windows,
|
||||
// the system code page (GBK on Chinese Windows: cmd.exe, PowerShell 5 errors, older tools, Python with a legacy locale…).
|
||||
// Per chunk: valid UTF-8 stays UTF-8; otherwise it is decoded with the code page. Streaming-safe: at most 3 trailing bytes
|
||||
// of a multibyte character split across chunks are held back for the next chunk (bounded, never more).
|
||||
// Protocol stdout (JSON-RPC / stream-json) is always strict UTF-8 and doesn't go through here. node-pty / ConPTY already
|
||||
// hands out UTF-8, so the PTY terminal doesn't either.
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
/** Windows code page → WHATWG encoding label (Node's TextDecoder with full ICU, the default build since Node 13) */
|
||||
const CP: Record<number, string> = {
|
||||
936: "gbk", 54936: "gb18030", 950: "big5", 932: "shift_jis", 949: "euc-kr", 866: "ibm866", 874: "windows-874",
|
||||
1250: "windows-1250", 1251: "windows-1251", 1252: "windows-1252", 1253: "windows-1253", 1254: "windows-1254",
|
||||
1255: "windows-1255", 1256: "windows-1256", 1257: "windows-1257", 1258: "windows-1258",
|
||||
// 437/850 (OEM, Western) have no WHATWG decoder; output there is almost always ASCII or already UTF-8
|
||||
};
|
||||
|
||||
export function codePageLabel(cp: number): string | null {
|
||||
const label = CP[cp];
|
||||
if (!label) return null;
|
||||
try { new TextDecoder(label); return label; } catch { return null; } // small-icu builds: no legacy decoders
|
||||
}
|
||||
|
||||
/** Fallback when the code page can't be read: guess from the locale */
|
||||
export function labelForLocale(locale: string): string | null {
|
||||
const l = locale.toLowerCase();
|
||||
if (/^zh[-_](tw|hk|mo|hant)/.test(l)) return codePageLabel(950);
|
||||
if (l.startsWith("zh")) return codePageLabel(936);
|
||||
if (l.startsWith("ja")) return codePageLabel(932);
|
||||
if (l.startsWith("ko")) return codePageLabel(949);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Parse `reg query …\Nls\CodePage /v ACP` or `chcp` output ("Active code page: 936", "活动代码页: 936") */
|
||||
export function parseCodePage(out: string): number | null {
|
||||
const m = /ACP\s+REG_SZ\s+(\d{3,5})/i.exec(out) ?? /:\s*(\d{3,5})\s*$/m.exec(out.trim());
|
||||
return m ? Number(m[1]) : null;
|
||||
}
|
||||
|
||||
let systemLabel: string | null | undefined;
|
||||
|
||||
/** The legacy encoding to try for non-UTF-8 output: Windows only (ANSI code page, what programs use for pipes); null elsewhere */
|
||||
export function systemLegacyEncoding(platform: NodeJS.Platform = process.platform): string | null {
|
||||
if (systemLabel !== undefined) return systemLabel; // cached (or set by a test)
|
||||
if (platform !== "win32") return null;
|
||||
let cp: number | null = null;
|
||||
try {
|
||||
const r = spawnSync("reg", ["query", "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage", "/v", "ACP"], { encoding: "latin1", timeout: 2000, windowsHide: true });
|
||||
cp = parseCodePage(String(r.stdout ?? ""));
|
||||
} catch {}
|
||||
if (cp === 65001) return (systemLabel = null); // "Beta: use UTF-8 worldwide": everything is UTF-8 already
|
||||
systemLabel = (cp && codePageLabel(cp)) || labelForLocale(Intl.DateTimeFormat().resolvedOptions().locale);
|
||||
return systemLabel;
|
||||
}
|
||||
|
||||
/** Test hook */
|
||||
export function _setSystemLegacyEncoding(label: string | null | undefined): void { systemLabel = label; }
|
||||
|
||||
/** Length of an incomplete UTF-8 sequence at the end of b (0–3) */
|
||||
function utf8Tail(b: Uint8Array): number {
|
||||
for (let k = 1; k <= Math.min(3, b.length); k++) {
|
||||
const c = b[b.length - k]!;
|
||||
if ((c & 0xc0) === 0x80) continue; // continuation byte: keep looking for the lead
|
||||
const need = c >= 0xf0 ? 4 : c >= 0xe0 ? 3 : c >= 0xc0 ? 2 : 1;
|
||||
return need > k ? k : 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Length of an incomplete double-byte (or GB18030 four-byte) character at the end of b (0–3) */
|
||||
function legacyTail(b: Uint8Array, label: string): number {
|
||||
const dbcs = label === "gbk" || label === "gb18030" || label === "big5" || label === "euc-kr" || label === "shift_jis";
|
||||
if (!dbcs) return 0;
|
||||
const gb = label === "gbk" || label === "gb18030";
|
||||
let i = 0;
|
||||
while (i < b.length) {
|
||||
const c = b[i]!;
|
||||
let n = 1;
|
||||
if (label === "shift_jis") n = (c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc) ? 2 : 1;
|
||||
else if (c >= 0x81 && c <= 0xfe) n = gb && i + 1 < b.length && b[i + 1]! >= 0x30 && b[i + 1]! <= 0x39 ? 4 : 2;
|
||||
if (i + n > b.length) return b.length - i;
|
||||
i += n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Does b (valid UTF-8) contain any 3- or 4-byte sequence? (Strong UTF-8 evidence: CJK text in UTF-8 is 3 bytes.) */
|
||||
function hasLongUtf8(b: Uint8Array): boolean {
|
||||
for (const c of b) if (c >= 0xe0) return true;
|
||||
return false;
|
||||
}
|
||||
function isAscii(b: Uint8Array): boolean {
|
||||
for (const c of b) if (c >= 0x80) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export class OutputDecoder {
|
||||
private pending: Uint8Array = new Uint8Array(0);
|
||||
private legacyLast = false;
|
||||
private readonly utf8 = new TextDecoder("utf-8", { fatal: true });
|
||||
private readonly lenient = new TextDecoder("utf-8");
|
||||
private readonly legacy: TextDecoder | null;
|
||||
|
||||
/** legacy: encoding label for non-UTF-8 chunks; default = the system code page on Windows, none elsewhere */
|
||||
constructor(legacy: string | null = systemLegacyEncoding()) {
|
||||
let d: TextDecoder | null = null;
|
||||
if (legacy) try { d = new TextDecoder(legacy); } catch {}
|
||||
this.legacy = d;
|
||||
}
|
||||
|
||||
write(chunk: Uint8Array | string): string {
|
||||
if (typeof chunk === "string") return chunk;
|
||||
let b: Uint8Array = chunk;
|
||||
if (this.pending.length) {
|
||||
const m = new Uint8Array(this.pending.length + chunk.length);
|
||||
m.set(this.pending); m.set(chunk, this.pending.length);
|
||||
b = m;
|
||||
this.pending = new Uint8Array(0);
|
||||
}
|
||||
if (!b.length) return "";
|
||||
const ut = utf8Tail(b);
|
||||
const head = b.subarray(0, b.length - ut);
|
||||
let text: string | null = null;
|
||||
try { text = this.utf8.decode(head); } catch {}
|
||||
if (text !== null) {
|
||||
// Valid UTF-8. Right after a code-page chunk, a chunk whose only non-ASCII bytes are 2-byte pairs is far more likely
|
||||
// the same program's GBK (e.g. "C4 A1") than Latin/Cyrillic UTF-8, so it sticks with the code page.
|
||||
const ascii = isAscii(head);
|
||||
if (!(this.legacy && this.legacyLast && !ascii && !hasLongUtf8(head))) {
|
||||
if (!ascii) this.legacyLast = false;
|
||||
this.pending = b.slice(b.length - ut);
|
||||
return text;
|
||||
}
|
||||
}
|
||||
if (!this.legacy) {
|
||||
// Not Windows (or no legacy decoder): lenient UTF-8, keeping a split character for the next chunk
|
||||
this.pending = b.slice(b.length - ut);
|
||||
return this.lenient.decode(head);
|
||||
}
|
||||
this.legacyLast = true;
|
||||
const lt = legacyTail(b, this.legacy.encoding);
|
||||
this.pending = b.slice(b.length - lt);
|
||||
return this.legacy.decode(b.subarray(0, b.length - lt));
|
||||
}
|
||||
|
||||
/** Flush whatever is held back (a truncated character at the very end becomes U+FFFD) */
|
||||
end(): string {
|
||||
const b = this.pending;
|
||||
this.pending = new Uint8Array(0);
|
||||
if (!b.length) return "";
|
||||
return (this.legacyLast && this.legacy ? this.legacy : this.lenient).decode(b);
|
||||
}
|
||||
}
|
||||
|
||||
/** One-shot decode of a whole buffer (probe output, a collected stderr) */
|
||||
export function decodeOutput(buf: Uint8Array, legacy?: string | null): string {
|
||||
const d = new OutputDecoder(legacy === undefined ? systemLegacyEncoding() : legacy);
|
||||
return d.write(buf) + d.end();
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Windows: find a usable Git Bash for the Agent CLIs (1.3).
|
||||
//
|
||||
// On Windows `bash` on PATH is often C:\Windows\System32\bash.exe, the WSL launcher. With no Linux distro that has /bin/bash
|
||||
// (Docker Desktop only installs "docker-desktop") every agent that runs `bash -c …` fails. Each agent looks for bash its own way
|
||||
// (see docs in the 1.3 plan): Claude Code reads CLAUDE_CODE_GIT_BASH_PATH, OpenCode OPENCODE_GIT_BASH_PATH, Pi runs
|
||||
// `where bash.exe`, dsh spawns `bash` through PATH. So one detection here feeds three per-spawn environment changes; no user config
|
||||
// file is written. Everything is a no-op off Windows.
|
||||
//
|
||||
// Pure functions with injected fs/env so the Windows logic is tested on Linux.
|
||||
import path from "node:path";
|
||||
import { statSync } from "node:fs";
|
||||
import { spawn } from "node:child_process";
|
||||
import { findOnPath } from "../../../lib/pathscan.mjs";
|
||||
|
||||
const W = path.win32;
|
||||
|
||||
export type Env = Record<string, string | undefined>;
|
||||
export type BashSource = "manual" | "env" | "git" | "known" | "drive" | "path";
|
||||
export type BashFound = { path: string; source: BashSource };
|
||||
export type BashDeps = {
|
||||
env?: Env;
|
||||
home?: string;
|
||||
/** sync existence check for local, well-known paths */
|
||||
isFile?: (p: string) => boolean;
|
||||
/** async check for other drives (tests); by default they are probed in a separate process, see probeInChild */
|
||||
isFileAsync?: (p: string) => Promise<boolean>;
|
||||
/** drive letters to try for X:\Git; default C–Z */
|
||||
drives?: string[];
|
||||
probeTimeoutMs?: number;
|
||||
};
|
||||
|
||||
export const GIT_FOR_WINDOWS_URL = "https://git-scm.com/download/win";
|
||||
|
||||
function envGet(env: Env, name: string): string | undefined {
|
||||
if (env[name] !== undefined) return env[name];
|
||||
const lower = name.toLowerCase();
|
||||
for (const k of Object.keys(env)) if (k.toLowerCase() === lower) return env[k];
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function syncIsFile(p: string): boolean {
|
||||
try {
|
||||
return statSync(p).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function withTimeout(p: Promise<boolean>, ms: number): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
const t = setTimeout(() => resolve(false), ms);
|
||||
t.unref?.();
|
||||
p.then((v) => { clearTimeout(t); resolve(v); }, () => { clearTimeout(t); resolve(false); });
|
||||
});
|
||||
}
|
||||
|
||||
const norm = (p: string) => W.normalize(p).replace(/[\\/]+$/, "").toLowerCase();
|
||||
|
||||
/** The WSL launcher (System32 / SysWOW64 / Sysnative bash.exe) or the WindowsApps alias: never a usable bash. */
|
||||
export function isWslBash(p: string, env: Env = {}): boolean {
|
||||
const n = norm(p);
|
||||
if (/\\windowsapps\\/.test(n + "\\")) return true;
|
||||
if (/^[a-z]:\\windows\\(system32|syswow64|sysnative)\\/.test(n)) return true;
|
||||
const root = envGet(env, "SystemRoot") || envGet(env, "windir");
|
||||
if (root) {
|
||||
const r = norm(root);
|
||||
for (const sub of ["system32", "syswow64", "sysnative"]) if (n.startsWith(`${r}\\${sub}\\`)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Strip quotes/whitespace a user may paste around a path */
|
||||
export function cleanPath(raw: string): string {
|
||||
return raw.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1").trim();
|
||||
}
|
||||
|
||||
export type BashCheck = { ok: true; path: string } | { ok: false; reason: "empty" | "relative" | "notBash" | "wsl" | "missing" };
|
||||
|
||||
/** Validate a bash path typed by the user (or found in the environment). */
|
||||
export function checkBashPath(raw: string | undefined | null, deps: BashDeps = {}): BashCheck {
|
||||
const p = cleanPath(String(raw ?? ""));
|
||||
if (!p) return { ok: false, reason: "empty" };
|
||||
// A drive-letter path only: a UNC path (\\server\share) is checked synchronously and could stall on a dead share
|
||||
if (!/^[A-Za-z]:[\\/]/.test(p)) return { ok: false, reason: "relative" };
|
||||
const base = W.basename(p).toLowerCase();
|
||||
if (base !== "bash.exe" && base !== "sh.exe") return { ok: false, reason: "notBash" };
|
||||
const env = deps.env ?? process.env;
|
||||
if (isWslBash(p, env)) return { ok: false, reason: "wsl" };
|
||||
const full = W.normalize(p);
|
||||
if (!(deps.isFile ?? syncIsFile)(full)) return { ok: false, reason: "missing" };
|
||||
return { ok: true, path: full };
|
||||
}
|
||||
|
||||
/** Where bash.exe sits for a git.exe directory: …\Git\cmd, …\Git\bin, …\Git\mingw64\bin → …\Git\bin\bash.exe */
|
||||
export function bashForGitDir(dir: string): string[] {
|
||||
const d = W.normalize(dir).replace(/[\\/]+$/, "");
|
||||
const base = W.basename(d).toLowerCase();
|
||||
const parent = W.dirname(d);
|
||||
const out: string[] = [];
|
||||
if (base === "bin" || base === "cmd") {
|
||||
const pb = W.basename(parent).toLowerCase();
|
||||
// …\Git\mingw64\bin, …\Git\usr\bin, …\Git\clangarm64\bin
|
||||
if (["mingw64", "mingw32", "clangarm64", "ucrt64", "usr"].includes(pb)) out.push(W.join(W.dirname(parent), "bin", "bash.exe"));
|
||||
out.push(W.join(parent, "bin", "bash.exe"));
|
||||
}
|
||||
out.push(W.join(d, "bash.exe"));
|
||||
return [...new Set(out)];
|
||||
}
|
||||
|
||||
/** Well-known install directories, in order */
|
||||
export function knownBashCandidates(env: Env, home?: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const v of ["ProgramFiles", "ProgramW6432", "ProgramFiles(x86)"]) {
|
||||
const d = envGet(env, v);
|
||||
if (d) out.push(W.join(d, "Git", "bin", "bash.exe"));
|
||||
}
|
||||
out.push("C:\\Program Files\\Git\\bin\\bash.exe", "C:\\Program Files (x86)\\Git\\bin\\bash.exe");
|
||||
const local = envGet(env, "LOCALAPPDATA");
|
||||
if (local) out.push(W.join(local, "Programs", "Git", "bin", "bash.exe"));
|
||||
const scoop = envGet(env, "SCOOP") || (home ? W.join(home, "scoop") : "");
|
||||
if (scoop) out.push(W.join(scoop, "apps", "git", "current", "bin", "bash.exe"));
|
||||
const seen = new Set<string>();
|
||||
return out.filter((p) => (seen.has(norm(p)) ? false : (seen.add(norm(p)), true)));
|
||||
}
|
||||
|
||||
export function driveBashCandidates(drives: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
for (const raw of drives) {
|
||||
const L = raw.replace(/[:\\/]/g, "").toUpperCase();
|
||||
if (!/^[A-Z]$/.test(L)) continue;
|
||||
out.push(`${L}:\\Git\\bin\\bash.exe`, `${L}:\\Program Files\\Git\\bin\\bash.exe`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const ALL_DRIVES = "CDEFGHIJKLMNOPQRSTUVWXYZ".split("");
|
||||
|
||||
/**
|
||||
* Find Git Bash (Windows). Order: manual setting → an existing CLAUDE_CODE_GIT_BASH_PATH / OPENCODE_GIT_BASH_PATH that is valid →
|
||||
* next to git.exe on PATH → Program Files / Program Files (x86) / LocalAppData\Programs / scoop → X:\Git on other drives → a
|
||||
* bash.exe on PATH that is not the WSL launcher. System32 / WindowsApps bash is always skipped.
|
||||
*/
|
||||
export async function findGitBash(manual: string | undefined, deps: BashDeps = {}): Promise<{ found: BashFound | null; manualError?: BashCheck }> {
|
||||
const env = deps.env ?? process.env;
|
||||
const isFile = deps.isFile ?? syncIsFile;
|
||||
const ok = (p: string) => !isWslBash(p, env) && isFile(p);
|
||||
let manualError: BashCheck | undefined;
|
||||
if (manual && cleanPath(manual)) {
|
||||
const c = checkBashPath(manual, { ...deps, env });
|
||||
if (c.ok) return { found: { path: c.path, source: "manual" } };
|
||||
manualError = c;
|
||||
}
|
||||
for (const v of ["CLAUDE_CODE_GIT_BASH_PATH", "OPENCODE_GIT_BASH_PATH"]) {
|
||||
const c = checkBashPath(envGet(env, v), { ...deps, env });
|
||||
if (c.ok) return { found: { path: c.path, source: "env" }, manualError };
|
||||
}
|
||||
for (const git of findOnPath("git.exe", { platform: "win32", env, extra: false, exists: isFile })) {
|
||||
for (const b of bashForGitDir(W.dirname(git))) if (ok(b)) return { found: { path: b, source: "git" }, manualError };
|
||||
}
|
||||
for (const b of knownBashCandidates(env, deps.home)) if (ok(b)) return { found: { path: b, source: "known" }, manualError };
|
||||
const drives = driveBashCandidates(deps.drives ?? ALL_DRIVES);
|
||||
const ms = deps.probeTimeoutMs ?? 1500;
|
||||
const list = drives.filter((p) => !isWslBash(p, env));
|
||||
const hit = deps.isFileAsync
|
||||
? await Promise.all(list.map((p) => withTimeout(deps.isFileAsync!(p), ms))).then((h) => list[h.indexOf(true)] ?? null)
|
||||
: await probeInChild(list, ms);
|
||||
if (hit) return { found: { path: hit, source: "drive" }, manualError };
|
||||
for (const b of findOnPath("bash.exe", { platform: "win32", env, extra: false, exists: isFile })) {
|
||||
if (!isWslBash(b, env)) return { found: { path: b, source: "path" }, manualError };
|
||||
}
|
||||
return { found: null, manualError };
|
||||
}
|
||||
|
||||
/**
|
||||
* Stat the drive candidates in a short-lived child Node process, killed after `ms`. A stat on a disconnected network drive can
|
||||
* block for tens of seconds, and in-process it would hold the daemon's libuv threadpool (every other fs call) that long.
|
||||
* Resolves to the first candidate (in list order) that is a file, or null.
|
||||
*/
|
||||
export function probeInChild(paths: string[], ms: number): Promise<string | null> {
|
||||
if (!paths.length) return Promise.resolve(null);
|
||||
const script =
|
||||
"const fs=require('fs');const p=JSON.parse(process.argv[1]);" +
|
||||
"p.forEach((x,i)=>fs.stat(x,(e,s)=>{if(!e&&s.isFile())process.stdout.write(i+'\\n')}));";
|
||||
return new Promise((resolve) => {
|
||||
const hits = new Set<number>();
|
||||
let out = "";
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
try { child.kill(); } catch {}
|
||||
const first = [...hits].sort((a, b) => a - b)[0];
|
||||
resolve(first === undefined ? null : paths[first] ?? null);
|
||||
};
|
||||
const child = spawn(process.execPath, ["-e", script, JSON.stringify(paths)], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
||||
const timer = setTimeout(finish, ms);
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (d: string) => {
|
||||
out += d;
|
||||
for (const line of out.split("\n").slice(0, -1)) if (/^\d+$/.test(line)) hits.add(Number(line));
|
||||
out = out.slice(out.lastIndexOf("\n") + 1);
|
||||
// the first candidate is a hit: nothing earlier can win, stop waiting
|
||||
if (hits.has(0)) finish();
|
||||
});
|
||||
child.on("error", finish);
|
||||
child.on("close", finish);
|
||||
});
|
||||
}
|
||||
|
||||
/** The directory to put first on PATH so a PATH lookup of `bash` returns this one (…\Git\usr\bin → …\Git\bin when it exists). */
|
||||
export function bashPathDir(bash: string, isFile: (p: string) => boolean = syncIsFile): string {
|
||||
const dir = W.dirname(W.normalize(bash));
|
||||
if (/\\usr\\bin$/i.test(dir)) {
|
||||
const top = W.join(W.dirname(W.dirname(dir)), "bin");
|
||||
if (isFile(W.join(top, "bash.exe"))) return top;
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment changes for an Agent spawn: CLAUDE_CODE_GIT_BASH_PATH and OPENCODE_GIT_BASH_PATH, and the bash directory first on PATH
|
||||
* when a PATH lookup would otherwise return something else (System32\bash.exe → WSL). Nothing when no bash was found.
|
||||
*/
|
||||
export function bashEnv(found: BashFound | null, env: Env, isFile: (p: string) => boolean = syncIsFile): Record<string, string> {
|
||||
if (!found) return {};
|
||||
const out: Record<string, string> = {
|
||||
CLAUDE_CODE_GIT_BASH_PATH: found.path,
|
||||
OPENCODE_GIT_BASH_PATH: found.path,
|
||||
};
|
||||
const dir = bashPathDir(found.path, isFile);
|
||||
const first = findOnPath("bash.exe", { platform: "win32", env, extra: false, exists: isFile })[0];
|
||||
if (!first || norm(first) !== norm(W.join(dir, "bash.exe"))) {
|
||||
const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
|
||||
const rest = String(env[key] ?? "").split(";").filter((d) => d && norm(d.replace(/^"(.*)"$/, "$1")) !== norm(dir));
|
||||
out[key] = [dir, ...rest].join(";");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -28,6 +28,7 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.daemonRestart": "后台已重启,本轮已中断",
|
||||
"notice.sessionStartFailed": "会话启动失败:{detail}",
|
||||
"notice.sendFailed": "发送失败:{detail}",
|
||||
"notice.bashMissing": "没有找到 Git Bash。这个 Agent 在 Windows 上要用 Git Bash 运行命令(C:\\Windows\\System32\\bash.exe 是 WSL 启动器,不能用)。请安装 Git for Windows:https://git-scm.com/download/win ,或在「设置 → Bash 路径」里手动指定 bash.exe。",
|
||||
"notice.effortNextTurn": "思考强度已保存,将在下一轮生效",
|
||||
"notice.effortResetOnModel": "当前模型不支持该思考强度,已恢复为 Default",
|
||||
"turn.agentExit": "Agent 进程意外退出",
|
||||
@@ -138,6 +139,7 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.daemonRestart": "Daemon restarted — this turn was interrupted",
|
||||
"notice.sessionStartFailed": "Session start failed: {detail}",
|
||||
"notice.sendFailed": "Send failed: {detail}",
|
||||
"notice.bashMissing": "Git Bash was not found. On Windows this agent runs its commands with Git Bash (C:\\Windows\\System32\\bash.exe is the WSL launcher and won't work). Install Git for Windows: https://git-scm.com/download/win , or set bash.exe under Settings → Bash path.",
|
||||
"notice.effortNextTurn": "Reasoning effort saved — takes effect on the next turn",
|
||||
"notice.effortResetOnModel": "This model does not support that effort level; reset to Default",
|
||||
"turn.agentExit": "Agent process exited unexpectedly",
|
||||
|
||||
@@ -26,6 +26,8 @@ import { clampMode } from "../providers/modes.js";
|
||||
import { setAppLocale, tr, intlLocale } from "../util/i18n.js";
|
||||
import { MAX_MENTIONS } from "../util/mentions.js";
|
||||
import { openExternal } from "../util/openExternal.js";
|
||||
import { agentShellStatus, refreshAgentShell } from "../util/agentShell.js";
|
||||
import { checkBashPath, GIT_FOR_WINDOWS_URL } from "../util/gitBash.js";
|
||||
import { PreviewError, type PreviewProxy } from "../preview/proxy.js";
|
||||
import { checkPreviewUrl, MAX_PREVIEW_URL } from "../preview/url.js";
|
||||
import { previewHost } from "../preview/host.js";
|
||||
@@ -46,7 +48,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 }[]; mentions?: { rel: string; isDir?: boolean }[] }, behavior?: "queue" | "steer"): Promise<"started" | "steered" | "queued" | void>;
|
||||
send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[]; mentions?: { rel: string; isDir?: boolean }[]; clientId?: 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>;
|
||||
@@ -95,6 +97,16 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
port: svc.cfg.port,
|
||||
})));
|
||||
|
||||
// 1.3: Git Bash for the agents (Windows). status: what the agents get now; check: validate a path typed in Settings
|
||||
gw.method("shell.status", wrap(zEmpty, async () => {
|
||||
const st = agentShellStatus();
|
||||
return { ...st, platform: process.platform, downloadUrl: GIT_FOR_WINDOWS_URL };
|
||||
}));
|
||||
gw.method("shell.check", wrap(z.object({ path: z.string().max(1024) }), (p) => {
|
||||
if (process.platform !== "win32") return { ok: false, reason: "notWindows" };
|
||||
return checkBashPath(p.path);
|
||||
}));
|
||||
|
||||
gw.method("app.shutdown", wrap(zEmpty, () => {
|
||||
setTimeout(() => process.exit(0), 100);
|
||||
return { ok: true };
|
||||
@@ -141,6 +153,10 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
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>);
|
||||
// 1.3: Settings → Bash path (Windows) re-runs Git Bash detection for the next agent start
|
||||
if ("bashPath" in checked.patch && (before.bashPath ?? "") !== (next.bashPath ?? "")) {
|
||||
await refreshAgentShell(typeof next.bashPath === "string" ? next.bashPath : "");
|
||||
}
|
||||
// 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)) {
|
||||
@@ -505,10 +521,12 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
// 1.2: paths dragged from the Files panel, relative to the project (the daemon resolves and checks them)
|
||||
mentions: z.array(z.object({ rel: z.string().min(1).max(4096), isDir: z.boolean().optional() })).max(MAX_MENTIONS).optional(),
|
||||
behavior: z.enum(["queue", "steer"]).optional(),
|
||||
// 1.3: the page's id for its optimistic bubble, echoed on the user_message event (dedupe, no jump)
|
||||
clientId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),
|
||||
}),
|
||||
async (p) => {
|
||||
// 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, mentions: p.mentions }, p.behavior ?? "queue");
|
||||
const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments, mentions: p.mentions, clientId: p.clientId }, p.behavior ?? "queue");
|
||||
return { ok: true, delivered: delivered ?? "started" };
|
||||
}
|
||||
));
|
||||
|
||||
@@ -15,14 +15,20 @@
|
||||
// 1. The plugin host's server() creates the key and token; once the gate binds its port it writes page/session.js (port and key only).
|
||||
// 2. The plugin page (sandbox iframe) reads session.js and navigates itself to http://127.0.0.1:<port>/open?k=<key>.
|
||||
// This is an ordinary navigation: no Origin header, and the gate returns no CORS headers, so other pages can't read the response.
|
||||
// 3. The gate checks the key, starts (or reuses) the daemon and 302s to http://127.0.0.1:<daemonPort>/?<theme params>#t=<token>.
|
||||
// 3. The gate checks the key, starts (or reuses) the daemon and 302s to its own wrapper page
|
||||
// http://127.0.0.1:<port>/app?<theme params>#t=<token>&p=<daemonPort>, which frames http://127.0.0.1:<daemonPort>/#t=<token> (1.3).
|
||||
// The token lives only in the # fragment: fragments aren't sent to servers and don't appear in Referer or daemon logs;
|
||||
// after the navigation the window belongs to the daemon's origin (opaque inside the plugin iframe), and the initiating page can't read its URL.
|
||||
//
|
||||
// The gate itself: every request checks Host (blocks DNS rebinding); any request with an Origin header is refused (navigations only);
|
||||
// everything except GET /open is 404.
|
||||
// everything except GET /open and GET /app is 404.
|
||||
//
|
||||
// 1.3: /open no longer sends the frame to the daemon's random port directly but to the gate's own /app page (lib/wrapper.mjs),
|
||||
// which shows the daemon page in a child iframe. After sleep/wake or a daemon restart, a reload of the frame lands on this
|
||||
// stable port instead of a dead one, and the wrapper sends it back through the Magpie page to a fresh daemon.
|
||||
import http from "node:http";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { parseTry, wrapperCsp, wrapperHtml } from "./wrapper.mjs";
|
||||
|
||||
// Constant-time compare against timing attacks; hash to the same length first.
|
||||
function tokenEqual(a, b) {
|
||||
@@ -106,6 +112,17 @@ export function createGate({ port, key, token, ensureDaemon, host = "127.0.0.1"
|
||||
return;
|
||||
}
|
||||
const url = new URL(req.url ?? "/", `http://${host}:${port}`);
|
||||
if (url.pathname === "/app" && req.method === "GET") {
|
||||
// Static: no secret in it; the token reaches it only in the # fragment
|
||||
const nonce = randomBytes(16).toString("base64");
|
||||
res.writeHead(200, {
|
||||
...SAFE_HEADERS,
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"content-security-policy": wrapperCsp(nonce),
|
||||
});
|
||||
res.end(wrapperHtml(nonce));
|
||||
return;
|
||||
}
|
||||
if (url.pathname !== "/open" || req.method !== "GET") {
|
||||
respond(res, 404, "Not found");
|
||||
return;
|
||||
@@ -135,9 +152,12 @@ 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));
|
||||
}
|
||||
// The wrapper's retry counter (see lib/wrapper.mjs), only in its exact shape
|
||||
const tries = url.searchParams.get("ac_try");
|
||||
if (parseTry(tries)) query.set("ac_try", tries);
|
||||
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}`;
|
||||
const fragment = `t=${encodeURIComponent(token)}&p=${daemon.port}` + (back ? `&b=${encodeURIComponent(back)}` : "");
|
||||
const location = `http://127.0.0.1:${port}/app?${query}#${fragment}`;
|
||||
res.writeHead(302, { ...SAFE_HEADERS, location });
|
||||
res.end();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// 1.3 sleep/wake self-heal: a tiny page the gate serves at http://127.0.0.1:<gate port>/app#t=<token>&p=<daemon port>&b=<back>.
|
||||
//
|
||||
// Before 1.3 the plugin frame was navigated straight to the daemon's random port. When the computer slept and the daemon was
|
||||
// gone afterwards (or the WebView reloaded the frame), the frame reloaded that dead address: "127.0.0.1 拒绝连接", and no
|
||||
// script of ours was left to recover. Now the frame stays on the gate's stable port and shows the daemon page in a child
|
||||
// iframe. A reload lands on the gate (alive as long as the plugin host is), and this page notices the child is not there:
|
||||
// - the child posts {ac_console:"alive"} every 2 s while its WebSocket is open and {ac_console:"lost",at} after 5 s without it;
|
||||
// - no "alive" within 12 s of loading (6 s after the child frame loaded), a "lost", or 15 s of silence (only while visible, and not counting time this page's
|
||||
// own timers were suspended by sleep) → go back through the Magpie plugin page (b), like 1.1's self-heal: boot.js reads the
|
||||
// fresh session.js and opens the gate, which restarts the daemon and sends the frame here again with the new port.
|
||||
// - at most 3 automatic tries in 2 minutes (counted in ?ac_try=<start>.<n>, carried through b → boot.js → gate → here);
|
||||
// then a button, so a daemon that can't start doesn't loop forever.
|
||||
//
|
||||
// Security: this page holds no secret of its own. The daemon token arrives only in its # fragment (as before, never sent to a
|
||||
// server, not in Referer) and is handed to the child in the child's fragment; the gate key is never here. The child is always
|
||||
// http://127.0.0.1:<integer port>/, b must pass the same loopback Magpie-page check as everywhere else (no open redirect),
|
||||
// and only the Magpie theme protocol is relayed (theme events / hello answers down, the hello call up). The page runs inside
|
||||
// Magpie's sandboxed plugin frame (opaque origin) and is served with a nonce-only CSP.
|
||||
|
||||
/** Same check as safeBackUrl in gate.mjs / web/src/api/backToMagpie.ts, as source for the page */
|
||||
const SAFE_BACK_SRC = String.raw`function safeBack(raw) {
|
||||
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
|
||||
var u; try { u = new URL(raw); } catch (e) { return null; }
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (u.username || u.password) return null;
|
||||
var h = u.hostname.toLowerCase();
|
||||
if (h !== "127.0.0.1" && h !== "localhost" && h !== "[::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;
|
||||
}`;
|
||||
|
||||
/** ?ac_try=<start ms>.<n>: valid shape only */
|
||||
export function parseTry(raw) {
|
||||
const m = /^(\d{10,15})\.([0-9])$/.exec(typeof raw === "string" ? raw : "");
|
||||
return m ? { start: Number(m[1]), n: Number(m[2]) } : null;
|
||||
}
|
||||
|
||||
export const WRAP_TIMING = { bootMs: 12000, afterLoadMs: 6000, silentMs: 15000, maxTries: 3, triesWindowMs: 120000 };
|
||||
|
||||
const SCRIPT = String.raw`(function () {
|
||||
"use strict";
|
||||
var T = __TIMING__;
|
||||
${SAFE_BACK_SRC}
|
||||
var frag = new URLSearchParams(location.hash.slice(1));
|
||||
var token = frag.get("t") || "";
|
||||
var port = Number(frag.get("p"));
|
||||
var back = safeBack(frag.get("b"));
|
||||
var q = new URLSearchParams(location.search);
|
||||
var lang = (q.get("lang") || "").toLowerCase();
|
||||
var zh = !lang || lang.indexOf("zh") === 0;
|
||||
if (q.get("theme") === "dark") document.documentElement.className = "dark";
|
||||
var f = document.getElementById("f");
|
||||
var box = document.getElementById("m");
|
||||
var said = document.getElementById("s");
|
||||
var btn = document.getElementById("r");
|
||||
function msg(zhText, enText, button) {
|
||||
said.textContent = zh ? zhText : enText;
|
||||
box.hidden = false;
|
||||
if (button) { btn.textContent = zh ? button[0] : button[1]; btn.hidden = false; }
|
||||
}
|
||||
if (!/^[0-9a-f]{32,128}$/i.test(token) || !(port > 0 && port < 65536 && Math.floor(port) === port)) {
|
||||
msg("链接已失效,请在 Magpie 里重新打开插件页。", "The link is no longer valid. Please reopen the Agent Console page in Magpie.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Child: the daemon page. Theme / language / colour tokens go along in its query, the token in its fragment; w=1 tells it
|
||||
// to report to this page instead of navigating itself.
|
||||
var cq = new URLSearchParams();
|
||||
["theme", "lang", "tokens"].forEach(function (k) { if (q.has(k)) cq.set(k, q.get(k)); });
|
||||
f.src = "http://127.0.0.1:" + port + "/?" + cq.toString() + "#t=" + encodeURIComponent(token) + "&w=1";
|
||||
|
||||
var everAlive = false, lastAlive = 0, recovering = false;
|
||||
var loadedAt = Date.now(), lastTick = Date.now();
|
||||
msg("正在连接本地服务…", "Connecting to the local service…");
|
||||
// A dead port shows the browser's error page, which also fires load: once loaded, the child gets T.afterLoadMs to say alive
|
||||
f.addEventListener("load", function () {
|
||||
if (!everAlive) loadedAt = Math.min(loadedAt, Date.now() - (T.bootMs - T.afterLoadMs));
|
||||
});
|
||||
|
||||
function recover(at) {
|
||||
if (recovering) return;
|
||||
recovering = true;
|
||||
f.classList.remove("on");
|
||||
var now = Date.now();
|
||||
var t = (function (raw) { var m = /^(\d{10,15})\.([0-9])$/.exec(raw || ""); return m ? { start: +m[1], n: +m[2] } : null; })(q.get("ac_try"));
|
||||
if (!t || now - t.start > T.triesWindowMs || t.start > now) t = { start: now, n: 0 };
|
||||
if (!back) {
|
||||
msg("本地服务已断开。请在 Magpie 里重新打开插件页。", "The local service disconnected. Please reopen the Agent Console page in Magpie.");
|
||||
return;
|
||||
}
|
||||
var go = function (auto) {
|
||||
var u = new URL(back);
|
||||
if (at > 0) u.searchParams.set("ac_lost", String(Math.floor(at)));
|
||||
if (auto) u.searchParams.set("ac_try", t.start + "." + (t.n + 1));
|
||||
location.replace(u.toString());
|
||||
};
|
||||
if (t.n >= T.maxTries) {
|
||||
msg("本地服务多次重连失败。", "Reconnecting to the local service failed several times.", ["重新连接", "Reconnect"]);
|
||||
btn.onclick = function () { btn.disabled = true; go(false); };
|
||||
return;
|
||||
}
|
||||
msg("本地服务已断开,正在重新连接…", "The local service disconnected. Reconnecting…");
|
||||
go(true);
|
||||
}
|
||||
|
||||
window.addEventListener("message", function (e) {
|
||||
var d = e.data;
|
||||
if (!d || typeof d !== "object") return;
|
||||
if (e.source === f.contentWindow) {
|
||||
if (d.ac_console === "alive") {
|
||||
lastAlive = Date.now();
|
||||
if (!everAlive) { everAlive = true; box.hidden = true; f.classList.add("on"); }
|
||||
return;
|
||||
}
|
||||
if (d.ac_console === "lost") { recover(Number(d.at) || Date.now()); return; }
|
||||
// The child's Magpie bridge "hello" (asks for the current theme) goes up as a fresh object, nothing else
|
||||
if (d.magpie === 1 && d.method === "hello" && typeof d.id === "number" && window.parent !== window) {
|
||||
window.parent.postMessage({ magpie: 1, id: d.id, method: "hello" }, "*");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.source === window.parent && d.magpie === 1 && f.contentWindow) {
|
||||
// Theme events and hello answers go down (rebuilt: only the fields the child reads)
|
||||
if (d.event === "theme") f.contentWindow.postMessage({ magpie: 1, event: "theme", data: d.data }, "*");
|
||||
else if (typeof d.id === "number" && "result" in d) f.contentWindow.postMessage({ magpie: 1, id: d.id, result: d.result }, "*");
|
||||
}
|
||||
});
|
||||
|
||||
setInterval(function () {
|
||||
var now = Date.now();
|
||||
var gap = now - lastTick;
|
||||
lastTick = now;
|
||||
// This page's own timers were held (sleep, a frozen or heavily throttled frame): give the child a fresh window
|
||||
if (gap > 5000 || document.visibilityState === "hidden") {
|
||||
if (everAlive) lastAlive = Math.max(lastAlive, now);
|
||||
else loadedAt = Math.max(loadedAt, now);
|
||||
return;
|
||||
}
|
||||
if (!everAlive) { if (now - loadedAt > T.bootMs) recover(0); return; }
|
||||
if (now - lastAlive > T.silentMs) recover(lastAlive);
|
||||
}, 1000);
|
||||
})();`;
|
||||
|
||||
/** The wrapper page; nonce must be fresh per response (it is the only thing the CSP allows to run) */
|
||||
export function wrapperHtml(nonce, timing = WRAP_TIMING) {
|
||||
const script = SCRIPT.replace("__TIMING__", JSON.stringify(timing));
|
||||
return (
|
||||
"<!doctype html><html><head><meta charset=utf-8><meta name=referrer content=no-referrer>" +
|
||||
"<meta name=viewport content=\"width=device-width,initial-scale=1\"><title>Agent Console</title>" +
|
||||
`<style nonce="${nonce}">` +
|
||||
"html,body{margin:0;height:100%;overflow:hidden;background:#fff;color:#525252;font:13px/1.6 system-ui,-apple-system,'Segoe UI',sans-serif}" +
|
||||
"html.dark,html.dark body{background:#1a1a1a;color:#a3a3a3}" +
|
||||
"iframe{position:fixed;inset:0;width:100%;height:100%;border:0;display:block;visibility:hidden}" +
|
||||
"iframe.on{visibility:visible}" +
|
||||
"#m{position:fixed;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;text-align:center}" +
|
||||
"#m[hidden]{display:none}" +
|
||||
"button{font:inherit;padding:5px 14px;border-radius:6px;border:1px solid currentColor;background:none;color:inherit;cursor:pointer}" +
|
||||
"</style></head><body>" +
|
||||
"<iframe id=f allow=\"clipboard-read; clipboard-write\" referrerpolicy=no-referrer title=\"Agent Console\"></iframe>" +
|
||||
"<div id=m hidden><p id=s></p><button id=r type=button hidden></button></div>" +
|
||||
`<script nonce="${nonce}">${script}</script>` +
|
||||
"</body></html>"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Who may frame /app: the gate itself, a loopback page (Magpie's plugin page and `magpie web` on this computer) and
|
||||
* Magpie's desktop window, which is wails://localhost on macOS / Linux and http://wails.localhost on Windows (WebView2).
|
||||
* Any other site gets a blank frame. Keep in sync with the README's security section.
|
||||
*/
|
||||
export const WRAPPER_FRAME_ANCESTORS =
|
||||
"frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:";
|
||||
|
||||
export function wrapperCsp(nonce) {
|
||||
return [
|
||||
"default-src 'none'",
|
||||
`script-src 'nonce-${nonce}'`,
|
||||
`style-src 'nonce-${nonce}'`,
|
||||
"frame-src http://127.0.0.1:*",
|
||||
WRAPPER_FRAME_ANCESTORS,
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
].join("; ");
|
||||
}
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.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/qingnian108/magpie-agent-console",
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
const here = new URL(location.href);
|
||||
const lostAt = Number(here.searchParams.get("ac_lost")) || 0;
|
||||
here.searchParams.delete("ac_lost");
|
||||
// ac_try: the gate wrapper's count of automatic reconnects (1.3), handed on to it through the gate
|
||||
const tries = here.searchParams.get("ac_try") || "";
|
||||
here.searchParams.delete("ac_try");
|
||||
here.hash = "";
|
||||
function validSession(s) {
|
||||
return (
|
||||
@@ -103,6 +106,7 @@
|
||||
const q = new URLSearchParams();
|
||||
q.set("k", session.key);
|
||||
if (theme) q.set("theme", theme);
|
||||
if (/^\d{10,15}\.[0-9]$/.test(tries)) q.set("ac_try", tries);
|
||||
if (lang) q.set("lang", lang);
|
||||
const slim = {};
|
||||
for (const [k, v] of Object.entries(tokens || {})) {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
// e2e (§11.2): playwright-core + Edge, isolated data directory _tmp/e2e-xdg, port 3497, AGENT_CONSOLE_MOCK=1.
|
||||
// Scenarios 1–12, 16–19; each prints ✓/✗, and any ✗ exits with code 1.
|
||||
// Scenarios 1–12, 16–26 (20, 22–26: 1.3 overlap at 600 px, message actions, quotes, instant send, tool rows / summary,
|
||||
// checklist + pill + reply footer + code block); each prints ✓/✗, and any ✗ exits with code 1.
|
||||
// The mock Agent starts slowly (E2E_MOCK_START_MS, default 1200 ms) like a real one on Windows, so every scenario runs
|
||||
// with the user's message arriving before the Agent is up.
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { findBrowser } from "./browser-path.mjs";
|
||||
import { mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
||||
@@ -78,7 +81,7 @@ async function setup() {
|
||||
} catch (e) { log("[e2e] git init 失败(场景13 会失败):", String(e).slice(0, 120)); }
|
||||
|
||||
daemon = spawn("node", [join(root, "daemon/dist/main.js"), "--port", String(PORT), "--data", XDG], {
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1", AGENT_CONSOLE_MOCK_START_MS: process.env.E2E_MOCK_START_MS ?? "1200" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
windowsHide: true,
|
||||
});
|
||||
@@ -160,14 +163,34 @@ async function waitEnd(seq = 0) {
|
||||
async function scenario2() {
|
||||
await send("看下这个项目");
|
||||
await waitEnd();
|
||||
const checks = await page.evaluate(() => ({
|
||||
// 1.3 timeline polish: a short run (≤6 tool calls) stays flat, one compact row per step; the edit row shows +N -M
|
||||
// and opens its diff on click; the step list is a checklist with N/M
|
||||
const rows = await page.evaluate(() => {
|
||||
const g = [...document.querySelectorAll(".tg")].pop();
|
||||
const ts = g ? [...g.querySelectorAll(".ts:not(.ts-think)")] : [];
|
||||
const edit = ts.find((x) => x.dataset.kind === "edit");
|
||||
const r = {
|
||||
flat: !!g?.classList.contains("flat") && !g.querySelector(".tg-head"),
|
||||
steps: ts.length,
|
||||
oneLine: ts.every((x) => x.querySelector(".ts-head").getBoundingClientRect().height <= 30),
|
||||
diffStat: edit?.querySelector(".ts-diff")?.textContent?.replace(/\s+/g, " ").trim() ?? "",
|
||||
closed: !g?.querySelector(".diff"),
|
||||
ok: ts.filter((x) => x.querySelector(".ts-st.ok")).length,
|
||||
};
|
||||
edit?.querySelector(".ts-head")?.click();
|
||||
return r;
|
||||
});
|
||||
await sleep(200);
|
||||
const checks = await page.evaluate((rows) => ({
|
||||
...rows,
|
||||
md: !!document.querySelector(".md"),
|
||||
tg: !!document.querySelector(".tg"),
|
||||
diff: !!document.querySelector(".diff"),
|
||||
todo: !!document.querySelector(".rs-item"),
|
||||
diff: !!document.querySelector(".tg .ts .diff"),
|
||||
checklist: document.querySelector(".ck .ck-n")?.textContent ?? "",
|
||||
te: !!document.querySelector(".te"),
|
||||
}));
|
||||
record("场景2 默认剧本(正文/工具组/diff/待办/结束行)", checks.md && checks.tg && checks.diff && checks.todo && checks.te, JSON.stringify(checks));
|
||||
}), rows);
|
||||
const ok = checks.flat && checks.steps === 5 && checks.oneLine && /\+2\s*[-−]1/.test(checks.diffStat) && checks.closed && checks.ok === 5
|
||||
&& checks.md && checks.diff && checks.checklist === "3/4" && checks.te;
|
||||
record("场景2 默认剧本(正文/工具行/+N -M/diff/清单/结束行)", ok, JSON.stringify(checks));
|
||||
}
|
||||
|
||||
async function scenario3() {
|
||||
@@ -391,6 +414,242 @@ async function scenario18() {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
}
|
||||
|
||||
// ---- 1.3 (Nolan's Windows report) ----
|
||||
async function newThread() {
|
||||
// Over the API (scenario 18 may leave the sidebar as a drawer); close the right panel earlier scenarios opened
|
||||
// (below ~900 px it is a sheet over the chat)
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await page.evaluate(() => window.__stores.useUi.getState().closePanel?.());
|
||||
// A dialog left open (e.g. scenario 16's palette when nothing matched): close it by pressing on its scrim
|
||||
for (let i = 0; i < 3 && await page.$(".dlg-scrim"); i++) { await page.mouse.click(4, 4); await sleep(200); }
|
||||
const projects = await wsCall("projects.list", {});
|
||||
const proj = projects.find((p) => p.path === PROJ) ?? projects[0];
|
||||
const th = await wsCall("threads.create", { projectId: proj.id, provider: "mock", mode: "default" });
|
||||
await page.waitForFunction((id) => window.__stores.useData.getState().threads.some((t) => t.id === id), th.id, { timeout: 8000 });
|
||||
await page.evaluate(([p, t]) => window.__stores.useUi.getState().select(p, t), [proj.id, th.id]);
|
||||
await page.waitForFunction((id) => window.__stores.useUi.getState().currentThreadId === id, th.id, { timeout: 5000 });
|
||||
_tid = th.id;
|
||||
await page.waitForSelector(sel.ta, { timeout: 5000 });
|
||||
await sleep(300);
|
||||
}
|
||||
async function waitIdle(ms = 45000) {
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < ms) {
|
||||
const st = await wsCall("threads.get", { id: await curThread() }).then((g) => g.runtimeStatus).catch(() => "?");
|
||||
if (st !== "running" && st !== "initializing") return;
|
||||
await sleep(250);
|
||||
}
|
||||
throw new Error("等待空闲超时");
|
||||
}
|
||||
/** Timeline rows never overlap: each row paints inside its virtual slot, one-line rows stay one line */
|
||||
async function overlapProblems() {
|
||||
return page.evaluate(() => {
|
||||
const bad = [];
|
||||
const inked = (el) => { const rg = document.createRange(); rg.selectNodeContents(el); const rs = [...rg.getClientRects()].filter((x) => x.height > 0);
|
||||
return rs.length ? { top: Math.min(...rs.map((x) => x.top)), bottom: Math.max(...rs.map((x) => x.bottom)) } : null; };
|
||||
const rows = [...document.querySelectorAll(".tl-wrap [data-index]")].map((el) => ({ el, i: +el.dataset.index, r: el.getBoundingClientRect() })).sort((a, b) => a.i - b.i);
|
||||
for (const row of rows) { const k = inked(row.el); if (k && (k.bottom > row.r.bottom + 1 || k.top < row.r.top - 1)) bad.push(`row ${row.i} paints outside its slot`); }
|
||||
for (let k = 0; k + 1 < rows.length; k++) if (rows[k + 1].i === rows[k].i + 1 && rows[k].r.bottom > rows[k + 1].r.top + 0.5) bad.push(`row ${rows[k].i} overlaps ${rows[k + 1].i}`);
|
||||
for (const el of document.querySelectorAll(".tl-wrap .tg-head, .tl-wrap .tg-run, .tl-wrap .rs-head, .tl-wrap .ts-head")) {
|
||||
const r = el.getBoundingClientRect(); const k = inked(el);
|
||||
if (r.height > 30 || (k && (k.bottom > r.bottom + 1 || k.top < r.top - 1))) bad.push(`${el.className} wraps/spills`);
|
||||
}
|
||||
return bad;
|
||||
});
|
||||
}
|
||||
|
||||
async function scenario20() {
|
||||
// Folded tool groups + running row + long PowerShell commands + a pending approval, at Nolan's ~600 px window
|
||||
await newThread();
|
||||
await page.setViewportSize({ width: 600, height: 860 });
|
||||
// E2E_NEG_OVERLAP=1: put back 1.2's squeeze to prove this check catches it (must fail)
|
||||
const neg = process.env.E2E_NEG_OVERLAP ? await page.addStyleTag({ content: ".tg-head{height:24px!important;min-height:0!important;overflow:visible!important;white-space:normal!important}.tg-sum{white-space:normal!important;overflow:visible!important;max-width:42px}.ts-head{height:24px!important;min-height:0!important;overflow:visible!important;white-space:normal!important}.ts-title{white-space:normal!important;overflow:visible!important;max-width:42px}" }) : null;
|
||||
await send("/winrun 帮我启动一下");
|
||||
const seen = new Set();
|
||||
let approved = false;
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < 30000) {
|
||||
for (const b of await overlapProblems()) seen.add(b);
|
||||
if (!approved && await page.$(".card.perm:not(.done)")) {
|
||||
await sleep(400);
|
||||
for (const b of await overlapProblems()) seen.add(b);
|
||||
await page.click(".card.perm:not(.done) .btn.primary");
|
||||
approved = true;
|
||||
}
|
||||
const st = await wsCall("threads.get", { id: await curThread() }).then((g) => g.runtimeStatus).catch(() => "?");
|
||||
if (approved && st !== "running" && st !== "initializing") break;
|
||||
await sleep(40);
|
||||
}
|
||||
for (const b of await overlapProblems()) seen.add(b);
|
||||
await neg?.evaluate((el) => el.remove());
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
record("场景20 600px 运行中折叠行/运行行不重叠", approved && seen.size === 0, [...seen].slice(0, 3).join(" | "));
|
||||
}
|
||||
|
||||
async function scenario22() {
|
||||
// User-message actions: under the bubble, reachable without a hover gap, copy feedback, edit fills the input
|
||||
await newThread();
|
||||
await send("帮我启动一下");
|
||||
await page.waitForSelector(".um", { timeout: 8000 });
|
||||
await waitIdle();
|
||||
const bb = await (await page.$(".um")).boundingBox();
|
||||
await page.mouse.move(bb.x + bb.width / 2, bb.y + bb.height / 2);
|
||||
await sleep(200);
|
||||
const ab = await (await page.$(".um-act")).boundingBox();
|
||||
let hidden = 0;
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
await page.mouse.move(bb.x + bb.width / 2 + (ab.x + 8 - bb.x - bb.width / 2) * i / 10, bb.y + bb.height / 2 + (ab.y + 12 - bb.y - bb.height / 2) * i / 10);
|
||||
const vis = await page.$eval(".um-act", (a) => Number(getComputedStyle(a).opacity) > 0.5);
|
||||
if (!vis) hidden++;
|
||||
}
|
||||
const below = ab.y >= bb.y + bb.height - 1 && ab.x + ab.width <= bb.x + bb.width + 1;
|
||||
await page.click('.um-act button[aria-label="编辑(填回输入框,不会马上发送)"]');
|
||||
await sleep(200);
|
||||
const filled = await page.$eval(sel.ta, (t) => t.value);
|
||||
await page.fill(sel.ta, "");
|
||||
record("场景22 用户消息操作:气泡下方、无悬停缺口、编辑回填", below && hidden === 0 && filled === "帮我启动一下", `below=${below} hidden=${hidden} filled=${filled}`);
|
||||
}
|
||||
|
||||
async function scenario23() {
|
||||
// Select text in a reply → 添加到对话 → quote chip → sent in front of the message as "> "
|
||||
await newThread();
|
||||
await send("看下这个项目");
|
||||
await page.waitForSelector(".tl-wrap .md p", { timeout: 15000 });
|
||||
await waitIdle();
|
||||
// A real mouse drag across the first reply paragraph
|
||||
await page.evaluate(() => document.querySelector(".tl-wrap .md p")?.scrollIntoView({ block: "center" }));
|
||||
await sleep(300);
|
||||
const pb = await (await page.$(".tl-wrap .md p")).boundingBox();
|
||||
await page.mouse.move(pb.x + 2, pb.y + 8);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(pb.x + Math.min(pb.width - 4, 200), pb.y + 8, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
const r = await page.evaluate(() => window.getSelection()?.toString());
|
||||
await page.waitForSelector(".qs-pop", { timeout: 3000 });
|
||||
await page.click(".qs-pop");
|
||||
await page.waitForSelector(".qchip", { timeout: 3000 });
|
||||
await send("这句什么意思?");
|
||||
await waitIdle();
|
||||
const g = await wsCall("threads.get", { id: await curThread() });
|
||||
const last = g.events.filter((e) => e.type === "user_message").pop();
|
||||
const ok = !!r && typeof last?.text === "string" && last.text.startsWith("> ") && last.text.endsWith("这句什么意思?") && !!(await page.$(".um-quote"));
|
||||
record("场景23 选中添加到对话 → 引用随消息发送", ok, JSON.stringify(last?.text ?? "").slice(0, 120));
|
||||
}
|
||||
|
||||
async function scenario24() {
|
||||
// 1.3 (Nolan): the bubble shows the moment 发送 is clicked, while the (slow) mock Agent is still starting; the
|
||||
// daemon's echo takes over the same DOM node (no duplicate, no jump); a failed send stays with 重试
|
||||
await newThread();
|
||||
await page.setViewportSize({ width: 600, height: 860 });
|
||||
await sleep(200);
|
||||
const text = "马上显示这条消息";
|
||||
await page.fill(sel.ta, text);
|
||||
const t = await page.evaluate((text) => new Promise((resolve) => {
|
||||
const t0 = performance.now();
|
||||
const r = { bubble: null, working: null };
|
||||
const tick = () => {
|
||||
const now = Math.round(performance.now() - t0);
|
||||
const row = [...document.querySelectorAll(".tl-wrap .um-row")].find((e) => e.textContent?.includes(text));
|
||||
if (r.bubble == null && row) { r.bubble = now; row.__mark = 1; r.cid = row.dataset.clientId; }
|
||||
if (r.working == null && document.querySelector(".cp-stop")) r.working = now;
|
||||
if ((r.bubble == null || r.working == null) && now < 5000) requestAnimationFrame(tick); else resolve(r);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
document.querySelector(".cp-send").click();
|
||||
}), text);
|
||||
// the echo (the daemon's user_message) replaces it in place
|
||||
await waitFor(() => page.evaluate((text) => (window.__tl.getState().items ?? []).some((i) => i.kind === "user" && i.text === text && !i.sendState), text), 8000, "回显");
|
||||
const same = await page.evaluate((cid) => !!document.querySelector(`.um-row[data-client-id="${cid}"]`)?.__mark, t.cid);
|
||||
await waitIdle();
|
||||
const count = await page.evaluate((text) => (window.__tl.getState().items ?? []).filter((i) => i.kind === "user" && i.text === text).length, text);
|
||||
const scrolled = await page.evaluate(() => { const el = document.querySelector(".scroll"); return el ? el.scrollHeight - el.scrollTop - el.clientHeight < 80 : false; });
|
||||
// Failure: thread.send rejects → the bubble stays, marked failed; 重试 sends it once
|
||||
await page.evaluate(() => { const ws = window.__ws; window.__origCall = ws.call.bind(ws);
|
||||
ws.call = (m, p, tm) => m === "thread.send" ? new Promise((_, rej) => setTimeout(() => rej(new Error("连接已断开")), 200)) : window.__origCall(m, p, tm); });
|
||||
await page.fill(sel.ta, "这条会发送失败");
|
||||
await page.click(sel.send);
|
||||
const failed = await page.waitForSelector(".um-row.failed .um-fail", { timeout: 5000 }).then(() => true).catch(() => false);
|
||||
await page.evaluate(() => { window.__ws.call = window.__origCall; });
|
||||
await page.click('.um-row.failed .um-fail-b[title="重新发送"]').catch(() => {});
|
||||
await waitFor(() => page.evaluate(() => !document.querySelector(".um-row.failed") && (window.__tl.getState().items ?? []).some((i) => i.kind === "user" && i.text === "这条会发送失败" && !i.sendState)), 8000, "重试后回显");
|
||||
await waitIdle();
|
||||
const retried = await page.evaluate(() => (window.__tl.getState().items ?? []).filter((i) => i.kind === "user" && i.text === "这条会发送失败").length);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const ok = t.bubble != null && t.bubble < 300 && t.working != null && t.working < 300 && same && count === 1 && scrolled && failed && retried === 1;
|
||||
record("场景24 点发送气泡立即出现(Agent 慢启动)、回显不重复不跳、失败可重试", ok,
|
||||
`bubble=${t.bubble}ms working=${t.working}ms sameNode=${same} count=${count} bottom=${scrolled} failed=${failed} retried=${retried}`);
|
||||
}
|
||||
|
||||
async function scenario25() {
|
||||
// 1.3 timeline polish: a long run (/tools, 8 tool calls) folds into one summary row with counts and a failure count;
|
||||
// it expands to the same one-line rows, and the failed step shows its output
|
||||
await newThread();
|
||||
await send("/tools 跑一下 lint 和测试");
|
||||
await page.waitForSelector(".tg:not(.flat) .tg-head", { timeout: 15000 });
|
||||
const running = await page.waitForSelector(".tg-run", { timeout: 15000 }).then(() => true).catch(() => false);
|
||||
await waitIdle();
|
||||
const head = await page.evaluate(() => {
|
||||
const g = [...document.querySelectorAll(".tg:not(.flat)")].pop();
|
||||
const r = { sum: g?.querySelector(".tg-sum")?.textContent ?? "", fail: g?.querySelector(".tg-fail")?.textContent ?? "",
|
||||
closed: !g?.querySelector(".tg-list"), h: g?.querySelector(".tg-head")?.getBoundingClientRect().height ?? 99 };
|
||||
g?.querySelector(".tg-head")?.click();
|
||||
return r;
|
||||
});
|
||||
await sleep(200);
|
||||
const open = await page.evaluate(() => {
|
||||
const g = [...document.querySelectorAll(".tg.open")].pop();
|
||||
const ts = g ? [...g.querySelectorAll(".ts:not(.ts-think)")] : [];
|
||||
const failed = ts.find((x) => x.querySelector(".ts-st.fail"));
|
||||
return { steps: ts.length, failedOpen: !!failed?.querySelector(".ts-out"), failedOut: /no-unused-vars/.test(failed?.textContent ?? ""),
|
||||
edit: ts.find((x) => x.dataset.kind === "edit")?.querySelector(".ts-diff")?.textContent?.replace(/\s+/g, " ").trim() ?? "" };
|
||||
});
|
||||
const ok = running && /读取 3/.test(head.sum) && /搜索 2/.test(head.sum) && /运行 2/.test(head.sum) && /改动 1/.test(head.sum) && /1/.test(head.fail)
|
||||
&& head.closed && head.h <= 30 && open.steps === 8 && open.failedOpen && open.failedOut && /[-−]1/.test(open.edit);
|
||||
record("场景25 长运行折叠成摘要(计数/失败数),展开为单行步骤", ok, JSON.stringify({ running, ...head, ...open }));
|
||||
}
|
||||
|
||||
async function scenario26() {
|
||||
// 1.3 timeline polish: /tasks — an ACP plan (entries) as an N/M checklist, the "N/M 个任务" pill above the composer
|
||||
// (click scrolls the list into view), the reply footer (copy · model · time · duration) and the code block
|
||||
// (language, line numbers, wrap toggle, copy of the raw code)
|
||||
await newThread();
|
||||
await send("/tasks 修一下 checkout 偶发失败的测试");
|
||||
const pill = await waitFor(() => page.evaluate(() => {
|
||||
const t = document.querySelector(".tasks-pill")?.textContent ?? "";
|
||||
return /\d\/3/.test(t) ? t : null;
|
||||
}), 15000, "任务胶囊").catch(() => null);
|
||||
await waitIdle();
|
||||
await sleep(300);
|
||||
const done = await page.evaluate(() => {
|
||||
const ck = [...document.querySelectorAll(".ck")].pop();
|
||||
return { n: ck?.querySelector(".ck-n")?.textContent ?? "", rows: ck?.querySelectorAll(".ck-i.done").length ?? 0, lists: document.querySelectorAll(".ck").length,
|
||||
pillGone: !document.querySelector(".tasks-pill") };
|
||||
});
|
||||
const te = await page.evaluate(() => {
|
||||
const t = [...document.querySelectorAll(".te")].pop();
|
||||
const metas = t ? [...t.querySelectorAll(".te-m")].map((m) => m.textContent.trim()) : [];
|
||||
return { copy: !!t?.querySelector(".te-copy"), model: metas.some((m) => /演示/.test(m)), time: metas.some((m) => /^\d{1,2}\/\d{1,2} \d{2}:\d{2}$|^\d{2}:\d{2}$/.test(m)),
|
||||
dur: metas.some((m) => /^\d+(\.\d+)?\s*(ms|s|分|m)/.test(m)) };
|
||||
});
|
||||
await page.evaluate(() => { window.__copied = null; navigator.clipboard.writeText = (s) => { window.__copied = s; return Promise.resolve(); }; });
|
||||
const cb = await page.evaluate(() => {
|
||||
const b = [...document.querySelectorAll(".md .cb")].pop();
|
||||
if (!b) return null;
|
||||
const r = { lang: b.querySelector(".cb-lang")?.textContent ?? "", lines: b.querySelectorAll(".cb-l").length, numbered: b.querySelector("pre, code")?.closest(".numbered") != null || b.querySelector(".numbered") != null };
|
||||
b.querySelector(".cb-wrap").click();
|
||||
r.wrap = b.classList.contains("wrap") || b.querySelector(".cb-wrap").getAttribute("aria-pressed") === "true";
|
||||
b.querySelector(".cb-copy").click();
|
||||
return r;
|
||||
});
|
||||
await sleep(200);
|
||||
const copied = await page.evaluate(() => window.__copied);
|
||||
const okCopy = typeof copied === "string" && copied.startsWith("async function submit() {") && copied.trim().endsWith("}") && !/^\s*\d/.test(copied.split("\n")[1] ?? "");
|
||||
const ok = !!pill && done.n === "3/3" && done.rows === 3 && done.lists === 1 && done.pillGone && te.copy && te.model && te.time && te.dur
|
||||
&& cb && cb.lang === "ts" && cb.lines === 5 && cb.numbered && cb.wrap && okCopy;
|
||||
record("场景26 任务清单 N/M + 胶囊、回复页脚(复制·模型·时间·用时)、代码块(语言/行号/换行/复制)", ok,
|
||||
JSON.stringify({ pill, ...done, ...te, cb, copied: copied?.slice(0, 30) }));
|
||||
}
|
||||
|
||||
async function scenario19() {
|
||||
// Filter benign console errors (e.g. favicon 404)
|
||||
const bad = pageErrors.filter((e) => !/favicon|404|net::/i.test(e) && !e.startsWith("dbg:"));
|
||||
@@ -510,24 +769,11 @@ async function main() {
|
||||
await setup();
|
||||
try {
|
||||
await newProjectFlow();
|
||||
await scenario2();
|
||||
await scenario3();
|
||||
await scenario4();
|
||||
await scenario5();
|
||||
await scenario6();
|
||||
await scenario7();
|
||||
await scenario8();
|
||||
await scenario9();
|
||||
await scenario10();
|
||||
await scenario11();
|
||||
await scenario12();
|
||||
await scenario13();
|
||||
await scenario14();
|
||||
await scenario15();
|
||||
await scenario16();
|
||||
await scenario17();
|
||||
await scenario18();
|
||||
await scenario19();
|
||||
// E2E_ONLY_13=1 runs just the 1.3 scenarios (20–23) and the console-error check
|
||||
const all = [scenario2, scenario3, scenario4, scenario5, scenario6, scenario7, scenario8, scenario9, scenario10, scenario11,
|
||||
scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19];
|
||||
const only13 = new Set([scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19]);
|
||||
for (const f of all) if (!process.env.E2E_ONLY_13 || only13.has(f)) await f();
|
||||
} catch (e) {
|
||||
record("中途异常", false, String(e?.message ?? e).slice(0, 600) + " ||daemon:" + daemonErr.slice(-4).join("|").slice(0, 400));
|
||||
}
|
||||
|
||||
@@ -186,9 +186,9 @@ describe("self-heal back URL (host restart)", () => {
|
||||
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)}`);
|
||||
expect(ok.headers.location).toBe(`http://127.0.0.1:${port}/app?theme=dark#t=${token}&p=${daemonPort}&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}`);
|
||||
expect(bad.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`);
|
||||
// without the key there's still nothing
|
||||
expect((await request(port, `/open?back=${encodeURIComponent(good)}`)).status).toBe(403);
|
||||
} finally {
|
||||
|
||||
@@ -471,14 +471,14 @@ describe("1.2 QA fixes", () => {
|
||||
expect(i18n.t("sidebar.newProject")).toBe("New project");
|
||||
expect(i18n.setLocale("en-US")).toBe(false);
|
||||
expect(i18n.setLocale("zh-TW")).toBe(true);
|
||||
expect(i18n.tf("timeline.toolSummaryOne", { n: 1, parts: "读取 1" })).toBe("已执行 1 步 · 读取 1");
|
||||
expect(i18n.tf("timeline.cat.read", { n: 1 })).toBe("读取 1");
|
||||
});
|
||||
it("every new 1.2 key exists in both languages", async () => {
|
||||
const { messages } = await import("../../web/src/i18n/messages.js");
|
||||
const keys = (o: Record<string, unknown>, p = ""): string[] => Object.entries(o).flatMap(([k, v]) => (typeof v === "object" && v ? keys(v as Record<string, unknown>, p + k + ".") : [p + k]));
|
||||
const zh = new Set(keys(messages.zh as unknown as Record<string, unknown>));
|
||||
const en = new Set(keys(messages.en as unknown as Record<string, unknown>));
|
||||
for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.toolSummaryOne"]) {
|
||||
for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.cat.read"]) {
|
||||
expect(zh.has(k), "zh " + k).toBe(true);
|
||||
expect(en.has(k), "en " + k).toBe(true);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// 1.3 item 3: UTF-8 vs GBK (system code page) decoding of raw process output
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { OutputDecoder, decodeOutput, parseCodePage, codePageLabel, labelForLocale, systemLegacyEncoding, _setSystemLegacyEncoding } from "../../daemon/src/util/decode.js";
|
||||
|
||||
const hex = (h: string) => Buffer.from(h.replace(/\s+/g, ""), "hex");
|
||||
// GBK fixtures (encoded with Python's gbk codec)
|
||||
const GBK_HELLO = hex("c4e3bac3a3accac0bde7"); // 你好,世界
|
||||
const GBK_NOPATH = hex("cfb5cdb3d5d2b2bbb5bdd6b8b6a8b5c4c2b7beb6a1a3"); // 系统找不到指定的路径。
|
||||
const GBK_ERR = hex("b4edcef33a20d5d2b2bbb5bdcec4bcfe20612e7478740d0a"); // 错误: 找不到文件 a.txt\r\n
|
||||
const GBK_YI = hex("d2bb"); // 一 — also valid UTF-8 (U+04BB "һ")
|
||||
|
||||
/** Feed buf in pieces of the given sizes (the rest as one piece) */
|
||||
function feed(d: OutputDecoder, buf: Buffer, sizes: number[]): string {
|
||||
let out = "", i = 0;
|
||||
for (const n of sizes) { out += d.write(buf.subarray(i, i + n)); i += n; }
|
||||
return out + d.write(buf.subarray(i)) + d.end();
|
||||
}
|
||||
|
||||
afterEach(() => _setSystemLegacyEncoding(undefined));
|
||||
|
||||
describe("OutputDecoder (Windows, code page 936)", () => {
|
||||
it("TextDecoder has gbk/gb18030/big5/shift_jis (full ICU, also Node 20)", () => {
|
||||
expect(new TextDecoder("gbk").decode(GBK_HELLO)).toBe("你好,世界");
|
||||
for (const l of ["gbk", "gb18030", "big5", "shift_jis", "euc-kr"]) expect(codePageLabel({ gbk: 936, gb18030: 54936, big5: 950, shift_jis: 932, "euc-kr": 949 }[l]!)).toBe(l);
|
||||
});
|
||||
|
||||
it("valid UTF-8 stays UTF-8, GBK chunks are decoded as GBK", () => {
|
||||
const d = new OutputDecoder("gbk");
|
||||
expect(d.write(Buffer.from("构建成功 ✓\n"))).toBe("构建成功 ✓\n");
|
||||
expect(d.write(GBK_NOPATH)).toBe("系统找不到指定的路径。");
|
||||
expect(d.write(Buffer.from("ok\n"))).toBe("ok\n");
|
||||
expect(d.write(Buffer.from("又是 UTF-8"))).toBe("又是 UTF-8");
|
||||
expect(d.end()).toBe("");
|
||||
});
|
||||
|
||||
it("streaming-safe: GBK and UTF-8 characters split at every byte boundary", () => {
|
||||
for (let cut = 1; cut < GBK_ERR.length; cut++) {
|
||||
expect(feed(new OutputDecoder("gbk"), GBK_ERR, [cut]), `gbk cut ${cut}`).toBe("错误: 找不到文件 a.txt\r\n");
|
||||
}
|
||||
const u = Buffer.from("中文输出 → 完成😀");
|
||||
for (let cut = 1; cut < u.length; cut++) expect(feed(new OutputDecoder("gbk"), u, [cut]), `utf8 cut ${cut}`).toBe("中文输出 → 完成😀");
|
||||
// one byte at a time
|
||||
expect(feed(new OutputDecoder("gbk"), GBK_HELLO, Array(GBK_HELLO.length).fill(1))).toBe("你好,世界");
|
||||
});
|
||||
|
||||
it("bounded: never holds more than 3 bytes", () => {
|
||||
const d = new OutputDecoder("gb18030");
|
||||
expect(d.write(hex("9439fc"))).toBe(""); // 3 of the 4 bytes of 😀 in GB18030
|
||||
expect(d.write(hex("36"))).toBe("😀");
|
||||
const big = Buffer.concat(Array(2000).fill(GBK_HELLO));
|
||||
expect(d.write(big).length).toBe(5 * 2000);
|
||||
expect((d as unknown as { pending: Uint8Array }).pending.length).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("after GBK output, an ambiguous 2-byte chunk (一 = D2 BB) sticks with GBK; a fresh decoder reads it as UTF-8", () => {
|
||||
const d = new OutputDecoder("gbk");
|
||||
d.write(GBK_HELLO);
|
||||
expect(d.write(GBK_YI)).toBe("一");
|
||||
expect(new OutputDecoder("gbk").write(GBK_YI)).toBe("һ");
|
||||
// 3-byte UTF-8 (CJK) is strong evidence and switches back
|
||||
expect(d.write(Buffer.from("好"))).toBe("好");
|
||||
expect(d.write(GBK_YI)).toBe("һ");
|
||||
});
|
||||
|
||||
it("end() flushes a truncated character instead of dropping it", () => {
|
||||
const d = new OutputDecoder("gbk");
|
||||
expect(d.write(hex("c4e3ba"))).toBe("你");
|
||||
expect(d.end()).toBe("\ufffd");
|
||||
});
|
||||
|
||||
it("strings pass through (streams already set to utf8)", () => {
|
||||
expect(new OutputDecoder("gbk").write("abc")).toBe("abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("OutputDecoder off Windows / no legacy decoder", () => {
|
||||
it("lenient UTF-8 with split characters kept", () => {
|
||||
const d = new OutputDecoder(null);
|
||||
const u = Buffer.from("你好");
|
||||
expect(d.write(u.subarray(0, 4)) + d.write(u.subarray(4)) + d.end()).toBe("你好");
|
||||
expect(decodeOutput(GBK_HELLO, null)).toContain("\ufffd");
|
||||
});
|
||||
it("systemLegacyEncoding is null on macOS and Linux", () => {
|
||||
expect(systemLegacyEncoding("darwin")).toBeNull();
|
||||
expect(systemLegacyEncoding("linux")).toBeNull();
|
||||
});
|
||||
it("an unknown label falls back to UTF-8", () => {
|
||||
expect(new OutputDecoder("no-such-enc").write(Buffer.from("ok"))).toBe("ok");
|
||||
});
|
||||
});
|
||||
|
||||
describe("code page detection", () => {
|
||||
it("parses reg query and chcp output", () => {
|
||||
expect(parseCodePage("\r\nHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage\r\n ACP REG_SZ 936\r\n\r\n")).toBe(936);
|
||||
expect(parseCodePage("Active code page: 65001\r\n")).toBe(65001);
|
||||
expect(parseCodePage("活动代码页: 936")).toBe(936);
|
||||
expect(parseCodePage("garbage")).toBeNull();
|
||||
});
|
||||
it("maps code pages and locales", () => {
|
||||
expect(codePageLabel(936)).toBe("gbk");
|
||||
expect(codePageLabel(437)).toBeNull();
|
||||
expect(codePageLabel(1252)).toBe("windows-1252");
|
||||
expect(labelForLocale("zh-CN")).toBe("gbk");
|
||||
expect(labelForLocale("zh-TW")).toBe("big5");
|
||||
expect(labelForLocale("zh-Hant-HK")).toBe("big5");
|
||||
expect(labelForLocale("ja-JP")).toBe("shift_jis");
|
||||
expect(labelForLocale("en-US")).toBeNull();
|
||||
});
|
||||
it("decodeOutput uses the cached system encoding by default", () => {
|
||||
_setSystemLegacyEncoding("gbk");
|
||||
expect(decodeOutput(GBK_NOPATH)).toBe("系统找不到指定的路径。");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
// 1.3 item 2: Claude-desktop-style folding of tool calls and short thinking
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { foldTimeline, summarize, stepTarget, activeStep, SHORT_THINK_CHARS } from "../../web/src/timeline/fold.js";
|
||||
import { reduceTimeline, type DisplayItem, type ToolStep } from "../../web/src/timeline/reducer.js";
|
||||
import { mapSdkMessage, newMapState } from "../../daemon/src/providers/claude/map.js";
|
||||
|
||||
type Ev = Record<string, unknown>;
|
||||
let seq = 0;
|
||||
const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: 0, threadId: "t", turnId: "u1", ...e })) as never[];
|
||||
const tool = (itemId: string, kind: string, status: string, extra: Ev = {}): Ev => ({ type: "tool_call", itemId, kind, title: `${kind} ${itemId}`, status, ...extra });
|
||||
const kinds = (items: DisplayItem[]) => items.map((i) => i.kind);
|
||||
const group = (items: DisplayItem[], n = 0) => items.filter((i) => i.kind === "toolgroup")[n] as Extract<DisplayItem, { kind: "toolgroup" }>;
|
||||
|
||||
describe("foldTimeline", () => {
|
||||
it("merges tool runs split by short thinking into one group; long thinking and text still break it", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "user_message", text: "hi" },
|
||||
{ type: "reasoning", itemId: "r0", text: "先看看" },
|
||||
tool("a", "read", "ok"),
|
||||
{ type: "reasoning", itemId: "r1", text: "" },
|
||||
tool("b", "bash", "ok"),
|
||||
{ type: "reasoning", itemId: "r2", text: "嗯".repeat(20) },
|
||||
tool("c", "edit", "ok"),
|
||||
{ type: "reasoning", itemId: "r3", text: "长".repeat(SHORT_THINK_CHARS + 1) },
|
||||
tool("d", "search", "ok"),
|
||||
{ type: "assistant_message", itemId: "m", text: "完成" },
|
||||
tool("e", "read", "ok"),
|
||||
]), { runtimeStatus: "idle" });
|
||||
// the reducer alone makes 5 groups; folded: [user, group(r0,a,r1,b,r2,c), long reasoning, group(d), assistant, group(e)]
|
||||
expect(items.filter((i) => i.kind === "toolgroup")).toHaveLength(5);
|
||||
const f = foldTimeline(items);
|
||||
expect(kinds(f)).toEqual(["user", "toolgroup", "reasoning", "toolgroup", "assistant", "toolgroup"]);
|
||||
// the empty finished thinking (r1) is dropped, the short ones become steps
|
||||
expect(group(f).steps.map((s) => s.kind)).toEqual(["think", "read", "bash", "think", "edit"]);
|
||||
expect(summarize(group(f).steps).counts).toEqual([["edit", 1], ["run", 1], ["read", 1]]);
|
||||
});
|
||||
|
||||
it("does not mutate the reducer's items", () => {
|
||||
const { items } = reduceTimeline(tl([tool("a", "read", "ok"), { type: "reasoning", itemId: "r", text: "x" }, tool("b", "read", "ok")]), {});
|
||||
const before = JSON.stringify(items);
|
||||
foldTimeline(items);
|
||||
foldTimeline(items);
|
||||
expect(JSON.stringify(items)).toBe(before);
|
||||
});
|
||||
|
||||
it("drops a lone finished empty thinking row, keeps short thinking that has no tools next to it", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "reasoning", itemId: "r0", text: "" },
|
||||
{ type: "assistant_message", itemId: "m", text: "a" },
|
||||
{ type: "reasoning", itemId: "r1", text: "短" },
|
||||
{ type: "assistant_message", itemId: "m2", text: "b" },
|
||||
]), { runtimeStatus: "idle" });
|
||||
expect(kinds(foldTimeline(items))).toEqual(["assistant", "reasoning", "assistant"]);
|
||||
});
|
||||
|
||||
it("showThinking off hides thinking everywhere, also inside groups", () => {
|
||||
const { items } = reduceTimeline(tl([{ type: "reasoning", itemId: "r0", text: "x" }, tool("a", "read", "ok"), { type: "reasoning", itemId: "r1", text: "y".repeat(500) }]), {});
|
||||
const f = foldTimeline(items, { showThinking: false });
|
||||
expect(kinds(f)).toEqual(["toolgroup"]);
|
||||
expect(group(f).steps.map((s) => s.kind)).toEqual(["read"]);
|
||||
});
|
||||
|
||||
it("gone items are transparent (a hidden row doesn't split a run)", () => {
|
||||
const items = [
|
||||
{ kind: "toolgroup", key: "g1", steps: [{ itemId: "a", kind: "read", title: "", status: "ok" }] },
|
||||
{ kind: "gone", key: "x" },
|
||||
{ kind: "toolgroup", key: "g2", steps: [{ itemId: "b", kind: "glob", title: "", status: "ok" }] },
|
||||
] as DisplayItem[];
|
||||
const f = foldTimeline(items);
|
||||
expect(f).toHaveLength(1);
|
||||
expect(f[0]!.key).toBe("g1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("summary, failures and the running row", () => {
|
||||
it("counts by category in a fixed order and counts failures", () => {
|
||||
const steps = [
|
||||
{ itemId: "1", kind: "glob", title: "", status: "ok" }, { itemId: "2", kind: "web", title: "", status: "ok" },
|
||||
{ itemId: "3", kind: "bash", title: "", status: "failed" }, { itemId: "4", kind: "write", title: "", status: "ok" },
|
||||
{ itemId: "5", kind: "edit", title: "", status: "failed" }, { itemId: "6", kind: "mcp", title: "", status: "ok" },
|
||||
{ itemId: "7", kind: "think", title: "", status: "ok", think: { text: "x".repeat(80), streaming: false } },
|
||||
] as ToolStep[];
|
||||
expect(summarize(steps)).toEqual({ counts: [["edit", 2], ["run", 1], ["search", 2], ["other", 1]], failed: 2, thinkSecs: 2 });
|
||||
});
|
||||
|
||||
it("running row: the last running tool's command / file, else streaming thinking at the end", () => {
|
||||
const run = { itemId: "1", kind: "bash", title: "运行 npm test", status: "running", input: { command: "npm\n test --run" } } as ToolStep;
|
||||
expect(stepTarget(run)).toBe("npm test --run");
|
||||
expect(stepTarget({ itemId: "2", kind: "read", title: "读取 a", status: "running", input: { file_path: "src/a.ts" } })).toBe("src/a.ts");
|
||||
expect(stepTarget({ itemId: "3", kind: "other", title: "Some tool", status: "running" })).toBe("Some tool");
|
||||
expect(activeStep([run, { itemId: "x", kind: "read", title: "", status: "ok" }])).toBe(run);
|
||||
const think = { itemId: "t", kind: "think", title: "", status: "running", think: { text: "", streaming: true } } as ToolStep;
|
||||
expect(activeStep([{ itemId: "x", kind: "read", title: "", status: "ok" }, think])).toBe(think);
|
||||
expect(activeStep([{ itemId: "x", kind: "read", title: "", status: "ok" }])).toBeNull();
|
||||
});
|
||||
|
||||
it("an interrupted turn: leftover running steps become failures once idle", () => {
|
||||
const { items } = reduceTimeline(tl([tool("a", "bash", "running", { input: { command: "sleep 99" } })]), { runtimeStatus: "idle" });
|
||||
const f = foldTimeline(items);
|
||||
expect(summarize(group(f).steps).failed).toBe(1);
|
||||
expect(activeStep(group(f).steps)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("real adapter shapes: claude stream-json", () => {
|
||||
it("thinking + Read + Bash(error) in one assistant message fold into one summary with 1 failure", () => {
|
||||
const st = newMapState();
|
||||
const raw: Ev[] = [
|
||||
...mapSdkMessage({ type: "assistant", message: { id: "m1", content: [
|
||||
{ type: "thinking", thinking: "先读文件再跑测试" },
|
||||
{ type: "tool_use", id: "tu1", name: "Read", input: { file_path: "src/a.ts" } },
|
||||
{ type: "tool_use", id: "tu2", name: "Bash", input: { command: "npm test" } },
|
||||
] } }, st, "/p") as Ev[],
|
||||
...mapSdkMessage({ type: "user", message: { role: "user", content: [
|
||||
{ type: "tool_result", tool_use_id: "tu1", content: [{ type: "text", text: "export {}" }] },
|
||||
{ type: "tool_result", tool_use_id: "tu2", content: "Error: 1 test failed", is_error: true },
|
||||
] } }, st, "/p") as Ev[],
|
||||
];
|
||||
const { items } = reduceTimeline(tl(raw), { runtimeStatus: "idle" });
|
||||
const f = foldTimeline(items);
|
||||
expect(kinds(f)).toEqual(["toolgroup"]);
|
||||
const sum = summarize(group(f).steps);
|
||||
expect(sum.counts).toEqual([["run", 1], ["read", 1]]);
|
||||
expect(sum.failed).toBe(1);
|
||||
const failed = group(f).steps.find((s) => s.status === "failed")!;
|
||||
expect(failed.output).toContain("1 test failed");
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,8 @@ describe("gate (lib/gate.mjs)", () => {
|
||||
expect(calls).toBe(1);
|
||||
for (const result of results) {
|
||||
expect(result.status).toBe(302);
|
||||
expect(result.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?theme=dark#t=${token}`);
|
||||
// 1.3: to the gate's own wrapper page, the daemon port next to the token in the fragment
|
||||
expect(result.headers.location).toBe(`http://127.0.0.1:${port}/app?theme=dark#t=${token}&p=${daemonPort}`);
|
||||
expect(result.headers["cache-control"]).toBe("no-store");
|
||||
expect(result.headers["x-content-type-options"]).toBe("nosniff");
|
||||
expect(result.headers["referrer-policy"]).toBe("no-referrer");
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// 1.3: Git Bash detection for the agents on Windows, with a mocked file system (no Windows here).
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import {
|
||||
bashEnv, bashForGitDir, checkBashPath, driveBashCandidates, findGitBash, isWslBash, knownBashCandidates, bashPathDir,
|
||||
} from "../../daemon/src/util/gitBash.js";
|
||||
import { agentShellStatus, bashMissingFor, refreshAgentShell, withAgentShell } from "../../daemon/src/util/agentShell.js";
|
||||
|
||||
const lc = (s: string) => s.toLowerCase();
|
||||
/** A fake Windows disk: the given files exist (case-insensitive), nothing else does */
|
||||
function disk(files: string[]) {
|
||||
const set = new Set(files.map(lc));
|
||||
const isFile = (p: string) => set.has(lc(p));
|
||||
return { isFile, isFileAsync: async (p: string) => isFile(p) };
|
||||
}
|
||||
const WIN_ENV = {
|
||||
SystemRoot: "C:\\WINDOWS",
|
||||
ProgramFiles: "C:\\Program Files",
|
||||
"ProgramFiles(x86)": "C:\\Program Files (x86)",
|
||||
LOCALAPPDATA: "C:\\Users\\nolan\\AppData\\Local",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
};
|
||||
const WSL = "C:\\WINDOWS\\system32\\bash.exe";
|
||||
const APPS = "C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe";
|
||||
|
||||
describe("isWslBash", () => {
|
||||
it("System32 / SysWOW64 / Sysnative / WindowsApps bash are the WSL launcher", () => {
|
||||
expect(isWslBash(WSL, WIN_ENV)).toBe(true);
|
||||
expect(isWslBash("c:/windows/System32/bash.exe")).toBe(true);
|
||||
expect(isWslBash("C:\\Windows\\SysWOW64\\bash.exe")).toBe(true);
|
||||
expect(isWslBash("C:\\Windows\\Sysnative\\bash.exe")).toBe(true);
|
||||
expect(isWslBash(APPS)).toBe(true);
|
||||
expect(isWslBash("D:\\Win\\System32\\bash.exe", { SystemRoot: "D:\\Win" })).toBe(true);
|
||||
expect(isWslBash("E:\\Git\\bin\\bash.exe", WIN_ENV)).toBe(false);
|
||||
expect(isWslBash("C:\\Program Files\\Git\\usr\\bin\\bash.exe", WIN_ENV)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkBashPath (Settings → Bash path)", () => {
|
||||
const d = disk(["E:\\Git\\bin\\bash.exe", WSL, "E:\\Git\\bin\\git.exe"]);
|
||||
it("accepts an existing bash.exe, with quotes and spaces trimmed", () => {
|
||||
expect(checkBashPath(' "E:\\Git\\bin\\bash.exe" ', { ...d, env: WIN_ENV })).toEqual({ ok: true, path: "E:\\Git\\bin\\bash.exe" });
|
||||
expect(checkBashPath("e:/Git/bin/bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: true, path: "e:\\Git\\bin\\bash.exe" });
|
||||
});
|
||||
it("refuses empty, relative, non-bash, WSL and missing paths", () => {
|
||||
expect(checkBashPath("", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "empty" });
|
||||
expect(checkBashPath("bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "relative" });
|
||||
// UNC paths are refused: the check is synchronous and a dead share could stall the daemon
|
||||
expect(checkBashPath("\\\\srv\\share\\Git\\bin\\bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "relative" });
|
||||
expect(checkBashPath("E:\\Git\\bin\\git.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "notBash" });
|
||||
expect(checkBashPath(WSL, { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "wsl" });
|
||||
expect(checkBashPath("F:\\Git\\bin\\bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "missing" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("candidates", () => {
|
||||
it("bash next to git.exe: cmd, bin, mingw64\\bin, usr\\bin", () => {
|
||||
expect(bashForGitDir("E:\\Git\\cmd")[0]).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(bashForGitDir("E:\\Git\\bin")).toContain("E:\\Git\\bin\\bash.exe");
|
||||
expect(bashForGitDir("E:\\Git\\mingw64\\bin")[0]).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(bashForGitDir("D:\\Tools\\Git\\usr\\bin")[0]).toBe("D:\\Tools\\Git\\bin\\bash.exe");
|
||||
});
|
||||
it("known install dirs in order, deduped", () => {
|
||||
const k = knownBashCandidates(WIN_ENV, "C:\\Users\\nolan");
|
||||
expect(k[0]).toBe("C:\\Program Files\\Git\\bin\\bash.exe");
|
||||
expect(k).toContain("C:\\Program Files (x86)\\Git\\bin\\bash.exe");
|
||||
expect(k).toContain("C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe");
|
||||
expect(k).toContain("C:\\Users\\nolan\\scoop\\apps\\git\\current\\bin\\bash.exe");
|
||||
expect(new Set(k.map(lc)).size).toBe(k.length);
|
||||
});
|
||||
it("other drives", () => {
|
||||
expect(driveBashCandidates(["e", "F:", "1"])).toEqual([
|
||||
"E:\\Git\\bin\\bash.exe", "E:\\Program Files\\Git\\bin\\bash.exe",
|
||||
"F:\\Git\\bin\\bash.exe", "F:\\Program Files\\Git\\bin\\bash.exe",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findGitBash", () => {
|
||||
it("Nolan's machine: Git on E:\\Git with git on PATH, WSL bash in System32 first → E:\\Git\\bin\\bash.exe", async () => {
|
||||
const d = disk([WSL, APPS, "E:\\Git\\cmd\\git.exe", "E:\\Git\\bin\\bash.exe"]);
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\WINDOWS;E:\\Git\\cmd;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" };
|
||||
const r = await findGitBash("", { ...d, env, drives: [] });
|
||||
expect(r.found).toEqual({ path: "E:\\Git\\bin\\bash.exe", source: "git" });
|
||||
});
|
||||
it("git not on PATH: finds X:\\Git on another drive, and never System32 or WindowsApps", async () => {
|
||||
const d = disk([WSL, APPS, "E:\\Git\\bin\\bash.exe"]);
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" };
|
||||
const r = await findGitBash("", { ...d, env });
|
||||
expect(r.found).toEqual({ path: "E:\\Git\\bin\\bash.exe", source: "drive" });
|
||||
});
|
||||
it("Program Files before other drives; LocalAppData\\Programs for per-user installs", async () => {
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" };
|
||||
expect((await findGitBash("", { ...disk(["C:\\Program Files\\Git\\bin\\bash.exe", "E:\\Git\\bin\\bash.exe"]), env })).found)
|
||||
.toEqual({ path: "C:\\Program Files\\Git\\bin\\bash.exe", source: "known" });
|
||||
expect((await findGitBash("", { ...disk(["C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe"]), env, drives: [] })).found)
|
||||
.toEqual({ path: "C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe", source: "known" });
|
||||
});
|
||||
it("only the WSL launcher → nothing found", async () => {
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" };
|
||||
expect((await findGitBash("", { ...disk([WSL, APPS]), env })).found).toBeNull();
|
||||
});
|
||||
it("a non-WSL bash.exe on PATH (MSYS2) is the last resort", async () => {
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\msys64\\usr\\bin" };
|
||||
expect((await findGitBash("", { ...disk([WSL, "C:\\msys64\\usr\\bin\\bash.exe"]), env, drives: [] })).found)
|
||||
.toEqual({ path: "C:\\msys64\\usr\\bin\\bash.exe", source: "path" });
|
||||
});
|
||||
it("the manual setting wins; an unusable one is reported and detection still runs", async () => {
|
||||
const d = disk(["D:\\PortableGit\\bin\\bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", WSL]);
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" };
|
||||
expect((await findGitBash("D:\\PortableGit\\bin\\bash.exe", { ...d, env })).found).toEqual({ path: "D:\\PortableGit\\bin\\bash.exe", source: "manual" });
|
||||
const bad = await findGitBash(WSL, { ...d, env });
|
||||
expect(bad.manualError).toEqual({ ok: false, reason: "wsl" });
|
||||
expect(bad.found?.source).toBe("known");
|
||||
});
|
||||
it("a valid CLAUDE_CODE_GIT_BASH_PATH is kept; one pointing at WSL is ignored", async () => {
|
||||
const d = disk(["F:\\g\\bin\\bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", WSL]);
|
||||
const env = { ...WIN_ENV, Path: "", CLAUDE_CODE_GIT_BASH_PATH: "F:\\g\\bin\\bash.exe" };
|
||||
expect((await findGitBash("", { ...d, env })).found).toEqual({ path: "F:\\g\\bin\\bash.exe", source: "env" });
|
||||
expect((await findGitBash("", { ...d, env: { ...env, CLAUDE_CODE_GIT_BASH_PATH: WSL } })).found?.source).toBe("known");
|
||||
});
|
||||
it("a drive probe that hangs (dead network drive) times out instead of blocking", async () => {
|
||||
const env = { ...WIN_ENV, Path: "" };
|
||||
const t0 = Date.now();
|
||||
const r = await findGitBash("", {
|
||||
isFile: () => false,
|
||||
isFileAsync: (p) => (p.startsWith("Z:") ? new Promise(() => {}) : Promise.resolve(p === "E:\\Git\\bin\\bash.exe")),
|
||||
env, probeTimeoutMs: 200,
|
||||
});
|
||||
expect(r.found?.path).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(Date.now() - t0).toBeLessThan(2000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bashEnv (per-spawn environment)", () => {
|
||||
const d = disk([WSL, "E:\\Git\\bin\\bash.exe", "E:\\Git\\cmd\\git.exe"]);
|
||||
it("sets both agent variables and puts Git\\bin before System32 so `where bash.exe` (Pi) and PATH lookups (dsh) find it", () => {
|
||||
const env = { Path: "C:\\WINDOWS\\system32;E:\\Git\\cmd", PATHEXT: ".EXE" };
|
||||
const out = bashEnv({ path: "E:\\Git\\bin\\bash.exe", source: "git" }, env, d.isFile);
|
||||
expect(out.CLAUDE_CODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(out.OPENCODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(out.Path).toBe("E:\\Git\\bin;C:\\WINDOWS\\system32;E:\\Git\\cmd");
|
||||
expect(out.PATH).toBeUndefined();
|
||||
});
|
||||
it("PATH is left alone when the first bash.exe on it is already the chosen one", () => {
|
||||
const env = { PATH: "E:\\Git\\bin;C:\\WINDOWS\\system32", PATHEXT: ".EXE" };
|
||||
const out = bashEnv({ path: "E:\\Git\\bin\\bash.exe", source: "git" }, env, d.isFile);
|
||||
expect(out.PATH).toBeUndefined();
|
||||
});
|
||||
it("usr\\bin picks the Git\\bin directory for PATH (only bash/sh/git there, no coreutils shadowing)", () => {
|
||||
const dd = disk(["E:\\Git\\bin\\bash.exe", "E:\\Git\\usr\\bin\\bash.exe"]);
|
||||
expect(bashPathDir("E:\\Git\\usr\\bin\\bash.exe", dd.isFile)).toBe("E:\\Git\\bin");
|
||||
expect(bashPathDir("C:\\msys64\\usr\\bin\\bash.exe", dd.isFile)).toBe("C:\\msys64\\usr\\bin");
|
||||
});
|
||||
it("nothing found → no changes", () => {
|
||||
expect(bashEnv(null, { PATH: "x" })).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("agentShell state", () => {
|
||||
afterEach(async () => { await refreshAgentShell("", { platform: "linux" }); });
|
||||
it("is a no-op on macOS / Linux", async () => {
|
||||
await refreshAgentShell("C:\\x\\bash.exe", { platform: "darwin" });
|
||||
expect(agentShellStatus().needed).toBe(false);
|
||||
const env = { PATH: "/usr/bin" };
|
||||
expect(withAgentShell(env)).toBe(env);
|
||||
expect(bashMissingFor("claude")).toBe(false);
|
||||
});
|
||||
it("Windows: merges the variables into a spawn env; hint only for agents that need bash", async () => {
|
||||
const d = disk([WSL, "E:\\Git\\bin\\bash.exe"]);
|
||||
const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" };
|
||||
await refreshAgentShell("", { platform: "win32", deps: { ...d, env } });
|
||||
expect(agentShellStatus().found?.path).toBe("E:\\Git\\bin\\bash.exe");
|
||||
const out: Record<string, string | undefined> = withAgentShell({ Path: "C:\\WINDOWS\\system32", FOO: "1" });
|
||||
expect(out.CLAUDE_CODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe");
|
||||
expect(out.Path).toBe("E:\\Git\\bin;C:\\WINDOWS\\system32");
|
||||
expect(out.FOO).toBe("1");
|
||||
expect(bashMissingFor("claude")).toBe(false);
|
||||
|
||||
await refreshAgentShell("", { platform: "win32", deps: { ...disk([WSL]), env, drives: [] } });
|
||||
expect(agentShellStatus().found).toBeNull();
|
||||
expect(bashMissingFor("claude")).toBe(true);
|
||||
expect(bashMissingFor("pi")).toBe(true);
|
||||
expect(bashMissingFor("codex")).toBe(false);
|
||||
expect(withAgentShell({ Path: "x" })).toEqual({ Path: "x" });
|
||||
});
|
||||
it("an unusable manual path is reported in the status", async () => {
|
||||
const env = { ...WIN_ENV, Path: "" };
|
||||
await refreshAgentShell(WSL, { platform: "win32", deps: { ...disk([WSL]), env, drives: [] } });
|
||||
expect(agentShellStatus().manualError).toBe("wsl");
|
||||
});
|
||||
});
|
||||
|
||||
describe("probeInChild (other drives, out of process)", () => {
|
||||
it("returns the first existing candidate in list order, null when none", async () => {
|
||||
const { mkdtempSync, writeFileSync } = await import("node:fs");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const { probeInChild } = await import("../../daemon/src/util/gitBash.js");
|
||||
const dir = mkdtempSync(join(tmpdir(), "ac-probe-"));
|
||||
const a = join(dir, "a"), b = join(dir, "b");
|
||||
writeFileSync(a, ""); writeFileSync(b, "");
|
||||
expect(await probeInChild([join(dir, "nope"), b, a], 5000)).toBe(b);
|
||||
expect(await probeInChild([join(dir, "nope"), dir], 5000)).toBeNull(); // a directory is not a file
|
||||
expect(await probeInChild([], 5000)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -201,11 +201,13 @@ describe("AgentManager", () => {
|
||||
it("idle recycling: idle timeout → closed", async () => {
|
||||
await settings.set({ idleCloseMinutes: 0.0001 }); // ~6ms
|
||||
await manager.send(threadId, { text: "你好" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
|
||||
// The turn's end already runs recycleIdle() itself; with a ~6ms timeout that one may close the thread before a
|
||||
// poll sees "idle" (and while it is still closing, the manual call below returns at once), so accept both here
|
||||
await waitFor(async () => ["idle", "closed"].includes((await threads.get(threadId))?.status ?? ""));
|
||||
// lastActivity is in milliseconds; wait more than 6ms, then trigger recycling by hand
|
||||
await sleep(50);
|
||||
await (manager as unknown as { recycleIdle(): Promise<void> }).recycleIdle();
|
||||
expect((await threads.get(threadId))?.status).toBe("closed");
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "closed", 5000);
|
||||
}, 15000);
|
||||
|
||||
it("B17: at most MAX_WARM_IDLE idle agent processes stay warm", async () => {
|
||||
|
||||
@@ -123,7 +123,10 @@ describe("plugin entry (index.mjs)", () => {
|
||||
expect(open.status).toBe(302);
|
||||
const location = new URL(String(open.headers.location));
|
||||
expect(location.hostname).toBe("127.0.0.1");
|
||||
const daemonPort = Number(location.port);
|
||||
// 1.3: the gate's own wrapper page; the daemon's port is in the fragment next to the token
|
||||
expect(Number(location.port)).toBe(port);
|
||||
expect(location.pathname).toBe("/app");
|
||||
const daemonPort = Number(new URLSearchParams(location.hash.slice(1)).get("p"));
|
||||
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
|
||||
@@ -137,7 +140,7 @@ describe("plugin entry (index.mjs)", () => {
|
||||
expect(token).not.toBe(key);
|
||||
expect(location.search).not.toContain(token);
|
||||
expect(location.search).not.toContain(key);
|
||||
expect(location.hash).toBe(`#t=${token}`);
|
||||
expect(location.hash).toBe(`#t=${token}&p=${daemonPort}`);
|
||||
expect(readFileSync(sessionPath, "utf8")).not.toContain(token);
|
||||
|
||||
// The daemon token can't be used as the gate key (nor the key as the daemon token, see the ping below)
|
||||
@@ -161,7 +164,7 @@ describe("plugin entry (index.mjs)", () => {
|
||||
// Opening a second time reuses the same daemon
|
||||
const again = await request(port, `/open?k=${key}&theme=dark`);
|
||||
expect(again.status).toBe(302);
|
||||
expect(Number(new URL(String(again.headers.location)).port)).toBe(daemonPort);
|
||||
expect(new URLSearchParams(new URL(String(again.headers.location)).hash.slice(1)).get("p")).toBe(String(daemonPort));
|
||||
|
||||
// Origin: null reading a static page → 403
|
||||
const opaque = await request(daemonPort, "/", { origin: "null" });
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
// 1.3 (Nolan, Windows): the user's message must not wait for the Agent to start. The daemon persists and pushes the
|
||||
// user_message (with the page's clientId) before detection / spawn / ACP initialize, and a start that fails afterwards
|
||||
// leaves the message with an error card instead of dropping it.
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AgentManager } from "../../daemon/src/agents/manager.js";
|
||||
import { ThreadsStore } from "../../daemon/src/store/threads.js";
|
||||
import { ProjectsStore } from "../../daemon/src/store/projects.js";
|
||||
import { SettingsStore } from "../../daemon/src/store/settings.js";
|
||||
import { AttachmentStore } from "../../daemon/src/store/attachments.js";
|
||||
import { Gateway } from "../../daemon/src/ws/gateway.js";
|
||||
import { initProviders, getProvider } from "../../daemon/src/providers/registry.js";
|
||||
import { clearProviderCache } from "../../daemon/src/providers/infoCache.js";
|
||||
import type { Config } from "../../daemon/src/config.js";
|
||||
|
||||
process.env.AGENT_CONSOLE_MOCK = "1";
|
||||
const cfg: Config = { port: 0, dataDir: "", token: "t", version: "0.0.0", idleExitMinutes: 60, buildStamp: "0" };
|
||||
|
||||
let dir: string;
|
||||
let threads: ThreadsStore;
|
||||
let projects: ProjectsStore;
|
||||
let gw: Gateway;
|
||||
let manager: AgentManager;
|
||||
let threadId: string;
|
||||
let projectId: string;
|
||||
let pushed: { at: number; ch: string; data: { type?: string; status?: string; event?: { type: string; clientId?: string; text?: string } } }[];
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-lat-"));
|
||||
threads = new ThreadsStore(dir);
|
||||
projects = new ProjectsStore(dir);
|
||||
gw = new Gateway(cfg);
|
||||
pushed = [];
|
||||
const orig = gw.publish.bind(gw);
|
||||
vi.spyOn(gw, "publish").mockImplementation((ch, data) => { pushed.push({ at: Date.now(), ch, data: data as never }); orig(ch, data); });
|
||||
initProviders();
|
||||
manager = new AgentManager(gw, threads, projects, new SettingsStore(dir), new AttachmentStore(join(dir, "attachments")));
|
||||
const proj = await projects.create(dir);
|
||||
projectId = proj.id;
|
||||
threadId = (await threads.create({ projectId, provider: "mock" })).id;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
delete process.env.AGENT_CONSOLE_MOCK_START_MS;
|
||||
delete process.env.AGENT_CONSOLE_MOCK_DETECT_MS;
|
||||
vi.restoreAllMocks();
|
||||
await manager.shutdown();
|
||||
// a status / title patch may still be renaming meta.json.tmp-*: wait for it before the directory goes (Windows ENOENT)
|
||||
await threads.idle();
|
||||
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
});
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 15000) => {
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < ms) { if (await fn()) return; await sleep(20); }
|
||||
throw new Error("waitFor 超时");
|
||||
};
|
||||
const userPush = (clientId?: string) => pushed.find((p) => p.ch === `thread:${threadId}` && p.data.type === "event" && p.data.event?.type === "user_message" && (!clientId || p.data.event.clientId === clientId));
|
||||
const statusPush = (s: string) => pushed.find((p) => p.ch === `thread:${threadId}` && p.data.type === "status" && p.data.status === s);
|
||||
|
||||
describe("send latency (1.3)", () => {
|
||||
it("user_message (with clientId) is pushed before a slow Agent start finishes", async () => {
|
||||
process.env.AGENT_CONSOLE_MOCK_START_MS = "1500";
|
||||
const t0 = Date.now();
|
||||
const sending = manager.send(threadId, { text: "你好", clientId: "c-test-1" });
|
||||
await waitFor(() => !!userPush("c-test-1"), 3000);
|
||||
const echo = userPush("c-test-1")!;
|
||||
expect(echo.at - t0).toBeLessThan(300);
|
||||
// the working state follows right after (pushed once the title patch is on disk), the Agent is still starting
|
||||
await waitFor(() => !!statusPush("initializing"), 1000);
|
||||
expect(statusPush("running")).toBeFalsy();
|
||||
await sending;
|
||||
expect(statusPush("running")!.at - t0).toBeGreaterThanOrEqual(1400);
|
||||
// persisted with the clientId, ahead of turn_started (snapshot reconcile works after a reload)
|
||||
const evs = await threads.readEvents(threadId, 0, 1000);
|
||||
const iu = evs.findIndex((e) => e.type === "user_message");
|
||||
expect((evs[iu] as { clientId?: string }).clientId).toBe("c-test-1");
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle", 20000);
|
||||
const ev2 = await threads.readEvents(threadId, 0, 1000);
|
||||
expect(ev2.findIndex((e) => e.type === "turn_started")).toBeGreaterThan(iu);
|
||||
expect(ev2.filter((e) => e.type === "user_message").length).toBe(1);
|
||||
}, 30000);
|
||||
|
||||
it("a slow detection (cold CLI probe) does not hold the message back either", async () => {
|
||||
process.env.AGENT_CONSOLE_MOCK_DETECT_MS = "1200";
|
||||
clearProviderCache("mock"); // a cold (or >60 s old) detection cache
|
||||
const t0 = Date.now();
|
||||
const sending = manager.send(threadId, { text: "检测慢", clientId: "c-test-2" });
|
||||
await waitFor(() => !!userPush("c-test-2"), 3000);
|
||||
expect(userPush("c-test-2")!.at - t0).toBeLessThan(300);
|
||||
await sending;
|
||||
expect(statusPush("running")!.at - t0).toBeGreaterThanOrEqual(1100); // detection did run, after the message
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle", 20000);
|
||||
}, 30000);
|
||||
|
||||
it("a failed Agent start keeps the message, adds the error card, and doesn't lock the Agent", async () => {
|
||||
const mock = getProvider("mock")!;
|
||||
const spy = vi.spyOn(mock, "createSession").mockRejectedValue(new Error("spawn EPERM"));
|
||||
await expect(manager.send(threadId, { text: "启动失败", clientId: "c-test-3" })).rejects.toThrow(/EPERM/);
|
||||
const evs = await threads.readEvents(threadId, 0, 1000);
|
||||
expect(evs.map((e) => e.type)).toEqual(["user_message", "notice", "turn_ended"]);
|
||||
expect((evs[2] as { status?: string }).status).toBe("failed");
|
||||
spy.mockRestore();
|
||||
// the Agent never ran: switching it is still allowed (mock is the only one here, so switch to itself)
|
||||
await expect(manager.setProvider(threadId, "mock")).resolves.toBeUndefined();
|
||||
}, 20000);
|
||||
|
||||
it("an unknown Agent is refused before anything is saved", async () => {
|
||||
const t = await threads.create({ projectId, provider: "nope-agent" });
|
||||
await expect(manager.send(t.id, { text: "x", clientId: "c-test-4" })).rejects.toThrow();
|
||||
expect((await threads.readEvents(t.id, 0, 100)).length).toBe(0);
|
||||
});
|
||||
|
||||
it("a queued message keeps its clientId until its turn starts; steer carries it too", async () => {
|
||||
await manager.send(threadId, { text: "/slow", clientId: "c-a" });
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "running");
|
||||
expect(await manager.send(threadId, { text: "排队的", clientId: "c-q" })).toBe("queued");
|
||||
expect(userPush("c-q")).toBeFalsy();
|
||||
await waitFor(() => !!userPush("c-q"), 25000);
|
||||
// "running" is stored before session.send returns, and until then (rt.starting) a steer is queued by design:
|
||||
// wait for the turn to have really started, not just for the status (under load the poll lands in that window)
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "running" && manager.runtimeInfo(threadId)?.starting === false);
|
||||
expect(await manager.send(threadId, { text: "插话", clientId: "c-s" }, "steer")).toBe("steered");
|
||||
expect(userPush("c-s")).toBeTruthy();
|
||||
await waitFor(async () => (await threads.get(threadId))?.status === "idle", 25000);
|
||||
}, 60000);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
// 1.3 timeline polish: compact tool rows (+N -M), checklists from every provider's step list, the tasks pill,
|
||||
// and the reply footer's model / time
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { foldTimeline, toolStepCount, stepDiffStat, todoProgress, currentChecklist, TOOL_COLLAPSE_AT } from "../../web/src/timeline/fold.js";
|
||||
import { reduceTimeline, type DisplayItem, type ToolStep } from "../../web/src/timeline/reducer.js";
|
||||
import { editDetail } from "../../daemon/src/agents/diff.js";
|
||||
|
||||
type Ev = Record<string, unknown>;
|
||||
let seq = 0;
|
||||
const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: 1000 + seq, threadId: "t", turnId: "u1", ...e })) as never[];
|
||||
const tool = (itemId: string, kind: string, status: string, extra: Ev = {}): Ev => ({ type: "tool_call", itemId, kind, title: `${kind} ${itemId}`, status, ...extra });
|
||||
const step = (kind: string, detail?: unknown): ToolStep => ({ itemId: kind, kind, title: kind, status: "ok", detail } as ToolStep);
|
||||
const todos = (items: DisplayItem[]) => items.filter((i): i is Extract<DisplayItem, { kind: "todo" }> => i.kind === "todo");
|
||||
|
||||
describe("checklists", () => {
|
||||
it("an ACP plan with entries is a checklist (completed → done); a plan without entries stays a plan card", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "plan", itemId: "p", markdown: "- a\n- b", entries: [{ step: "a", status: "completed" }, { step: "b", status: "in_progress" }, { step: "c", status: "pending" }] },
|
||||
{ type: "plan", itemId: "q", markdown: "## 计划\n1. x" },
|
||||
]), {});
|
||||
expect(todos(items)[0]!.items).toEqual([{ text: "a", status: "done" }, { text: "b", status: "in_progress" }, { text: "c", status: "pending" }]);
|
||||
expect(items.some((i) => i.kind === "plan")).toBe(true);
|
||||
});
|
||||
|
||||
it("only the latest list of a user turn is shown; Claude's TodoWrite tool row is not repeated as a step", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "user_message", text: "1" },
|
||||
{ type: "todo", items: [{ text: "a", status: "pending" }] },
|
||||
tool("w", "todo", "ok"),
|
||||
tool("r", "read", "ok"),
|
||||
{ type: "todo", items: [{ text: "a", status: "done" }] },
|
||||
{ type: "user_message", text: "2" },
|
||||
{ type: "todo", items: [{ text: "b", status: "pending" }] },
|
||||
]), {});
|
||||
const f = foldTimeline(items);
|
||||
expect(todos(f).map((t) => t.items[0]!.text + t.items[0]!.status)).toEqual(["adone", "bpending"]);
|
||||
const g = f.find((i) => i.kind === "toolgroup") as Extract<DisplayItem, { kind: "toolgroup" }>;
|
||||
expect(g.steps.map((s) => s.kind)).toEqual(["read"]);
|
||||
});
|
||||
|
||||
it("the pill shows the latest turn's list while something is open, not a finished one or an older turn's", () => {
|
||||
const run = (evs: Ev[]) => currentChecklist(foldTimeline(reduceTimeline(tl(evs), {}).items));
|
||||
expect(run([{ type: "user_message", text: "1" }, { type: "todo", items: [{ text: "a", status: "done" }, { text: "b", status: "pending" }] }])?.items).toHaveLength(2);
|
||||
expect(run([{ type: "user_message", text: "1" }, { type: "todo", items: [{ text: "a", status: "done" }] }])).toBeNull();
|
||||
expect(run([{ type: "todo", items: [{ text: "a", status: "pending" }] }, { type: "user_message", text: "2" }])).toBeNull();
|
||||
expect(todoProgress([{ status: "done" }, { status: "completed" }, { status: "in_progress" }])).toEqual({ done: 2, total: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("tool rows", () => {
|
||||
it("counts tool calls (not thinking) against the collapse threshold", () => {
|
||||
expect(TOOL_COLLAPSE_AT).toBe(6);
|
||||
expect(toolStepCount([step("think"), step("read"), step("bash"), step("think")])).toBe(2);
|
||||
});
|
||||
|
||||
it("+N -M from the daemon's counts, else from the hunks; null without a diff", () => {
|
||||
const d = editDetail({ path: "a.ts", old: "x\ny\n", new: "x\nz\nw\n" });
|
||||
expect(stepDiffStat(step("edit", d))).toEqual({ added: 2, removed: 1 });
|
||||
expect(stepDiffStat(step("edit", { hunks: d.hunks }))).toEqual({ added: 2, removed: 1 });
|
||||
expect(stepDiffStat(step("edit"))).toBeNull();
|
||||
expect(stepDiffStat(step("bash", "text"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("reply footer", () => {
|
||||
it("the turn end carries the turn's model and end time", () => {
|
||||
const { items } = reduceTimeline(tl([
|
||||
{ type: "turn_started", model: "gpt-5.5" },
|
||||
{ type: "assistant_message", itemId: "m", text: "ok" },
|
||||
{ type: "turn_ended", status: "completed" },
|
||||
]), {});
|
||||
const te = items.find((i) => i.kind === "turnend") as Extract<DisplayItem, { kind: "turnend" }>;
|
||||
expect(te.model).toBe("gpt-5.5");
|
||||
expect(typeof te.ts).toBe("number");
|
||||
expect(te.durationMs).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// 1.3: auto titles of a message sent with "添加到对话" quotes use the user's own words.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { titleText } from "../../daemon/src/agents/manager.js";
|
||||
|
||||
describe("titleText (1.3 quotes)", () => {
|
||||
it("auto titles skip the leading quote blocks", () => {
|
||||
expect(titleText("> [src/a.ts]\n> const x = 1;\n\n> second\n\n这句什么意思?")).toBe("这句什么意思?");
|
||||
expect(titleText("帮我 启动\n一下")).toBe("帮我 启动 一下");
|
||||
expect(titleText("> only a quote")).toBe("only a quote");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
// 1.3 item 5: the gate's wrapper page (lib/wrapper.mjs) that keeps the plugin frame on the stable gate port
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { join, resolve } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { freePort, request } from "./helpers-net.js";
|
||||
|
||||
const root = resolve(__dirname, "..", "..");
|
||||
const gateUrl = pathToFileURL(join(root, "lib", "gate.mjs")).href;
|
||||
const wrapperUrl = pathToFileURL(join(root, "lib", "wrapper.mjs")).href;
|
||||
|
||||
type Msg = { source: unknown; data: unknown };
|
||||
|
||||
/** Runs the wrapper's script against a tiny fake DOM with a controllable clock */
|
||||
async function runWrapper(hash: string, search = "", opts: { visible?: boolean } = {}) {
|
||||
const { wrapperHtml, WRAP_TIMING } = await import(/* @vite-ignore */ wrapperUrl);
|
||||
const html: string = wrapperHtml("n0nce", WRAP_TIMING);
|
||||
const script = html.split('<script nonce="n0nce">')[1]!.split("</script>")[0]!;
|
||||
let now = 1_800_000_000_000;
|
||||
const intervals: (() => void)[] = [];
|
||||
const childWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } };
|
||||
const parentWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } };
|
||||
const el = (id: string) => ({ id, hidden: id !== "f", textContent: "", src: "", disabled: false, onclick: null as null | (() => void),
|
||||
classList: { set: new Set<string>(), add(c: string) { this.set.add(c); }, remove(c: string) { this.set.delete(c); } },
|
||||
on: {} as Record<string, () => void>, addEventListener(t: string, fn: () => void) { this.on[t] = fn; } });
|
||||
const els: Record<string, ReturnType<typeof el>> = { f: el("f"), m: el("m"), s: el("s"), r: el("r") };
|
||||
(els.f as unknown as { contentWindow: unknown }).contentWindow = childWin;
|
||||
let onMessage: (e: Msg) => void = () => {};
|
||||
const loc = { hash, search, replaced: null as string | null, replace(u: string) { this.replaced = u; } };
|
||||
const win: Record<string, unknown> = {
|
||||
parent: parentWin,
|
||||
addEventListener: (t: string, fn: (e: Msg) => void) => { if (t === "message") onMessage = fn; },
|
||||
};
|
||||
const doc = { getElementById: (id: string) => els[id], documentElement: { className: "" }, visibilityState: opts.visible === false ? "hidden" : "visible" };
|
||||
const DateFake = { now: () => now };
|
||||
const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", script);
|
||||
fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams);
|
||||
const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); } };
|
||||
return {
|
||||
els, loc, childWin, parentWin, tick, doc,
|
||||
fromChild: (data: unknown) => onMessage({ source: childWin, data }),
|
||||
fromParent: (data: unknown) => onMessage({ source: parentWin, data }),
|
||||
fromOther: (data: unknown) => onMessage({ source: {}, data }),
|
||||
jump: (ms: number) => { now += ms; },
|
||||
now: () => now,
|
||||
};
|
||||
}
|
||||
|
||||
const TOKEN = "a".repeat(64);
|
||||
const BACK = "http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html?x=1";
|
||||
const hash = (o: Record<string, string>) => "#" + new URLSearchParams(o).toString();
|
||||
|
||||
describe("gate /app", () => {
|
||||
it("serves the wrapper with a fresh nonce CSP; Host and Origin checks still apply; no secrets in it", async () => {
|
||||
const { createGate } = await import(/* @vite-ignore */ gateUrl);
|
||||
const port = await freePort();
|
||||
const key = "c".repeat(64);
|
||||
const gate = createGate({ port, key, token: TOKEN, ensureDaemon: async () => ({ port: 4999 }) });
|
||||
await gate.listen();
|
||||
try {
|
||||
const a = await request(port, "/app");
|
||||
const b = await request(port, "/app?theme=dark");
|
||||
expect(a.status).toBe(200);
|
||||
expect(a.headers["content-type"]).toContain("text/html");
|
||||
const csp = String(a.headers["content-security-policy"]);
|
||||
expect(csp).toMatch(/script-src 'nonce-[A-Za-z0-9+/=]+'/);
|
||||
expect(csp).toContain("default-src 'none'");
|
||||
expect(csp).toContain("frame-src http://127.0.0.1:*");
|
||||
// only loopback pages and Magpie's own window (wails://localhost, http://wails.localhost) may frame /app
|
||||
expect(csp).toContain("frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:");
|
||||
expect(csp).not.toMatch(/frame-ancestors[^;]*\s(\*|https:|http:)(\s|;|$)/); // never "any site"
|
||||
expect(csp).not.toBe(String(b.headers["content-security-policy"]));
|
||||
expect(a.headers["cache-control"]).toBe("no-store");
|
||||
expect(a.body).not.toContain(TOKEN);
|
||||
expect(a.body).not.toContain(key);
|
||||
expect((await request(port, "/app", { host: `evil.example:${port}` })).status).toBe(421);
|
||||
expect((await request(port, "/app", { origin: "null" })).status).toBe(403);
|
||||
// ac_try is forwarded to the wrapper only in its exact shape
|
||||
const ok = await request(port, `/open?k=${key}&ac_try=1800000000000.2`);
|
||||
expect(new URL(String(ok.headers.location)).searchParams.get("ac_try")).toBe("1800000000000.2");
|
||||
const bad = await request(port, `/open?k=${key}&ac_try=${encodeURIComponent("1.2<script>")}`);
|
||||
expect(new URL(String(bad.headers.location)).searchParams.has("ac_try")).toBe(false);
|
||||
} finally {
|
||||
await gate.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("wrapper page", () => {
|
||||
it("frames the daemon on 127.0.0.1:<p> with the token in the fragment and w=1; shows it on the first alive", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "?theme=dark&lang=en&ac_try=1.1");
|
||||
expect(w.els.f!.src).toBe(`http://127.0.0.1:4321/?theme=dark&lang=en#t=${TOKEN}&w=1`);
|
||||
expect(w.doc.documentElement.className).toBe("dark");
|
||||
expect(w.els.f!.classList.set.has("on")).toBe(false);
|
||||
w.fromOther({ ac_console: "alive" }); // not from the child: ignored
|
||||
expect(w.els.f!.classList.set.has("on")).toBe(false);
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
expect(w.els.f!.classList.set.has("on")).toBe(true);
|
||||
expect(w.els.m!.hidden).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses a bad token or port, and never follows a non-Magpie back URL", async () => {
|
||||
const w1 = await runWrapper(hash({ t: "x", p: "4321", b: BACK }));
|
||||
expect(w1.els.f!.src).toBe("");
|
||||
const w2 = await runWrapper(hash({ t: TOKEN, p: "99999", b: BACK }));
|
||||
expect(w2.els.f!.src).toBe("");
|
||||
const w3 = await runWrapper(hash({ t: TOKEN, p: "4321", b: "https://evil.example/_magpie/plugin/a/index.html" }));
|
||||
w3.fromChild({ ac_console: "lost", at: 5 });
|
||||
expect(w3.loc.replaced).toBeNull();
|
||||
expect(w3.els.m!.hidden).toBe(false);
|
||||
});
|
||||
|
||||
it("a reload onto a dead daemon (no alive within 12 s) goes back through the Magpie page", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.tick(11000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.tick(2000);
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.origin + u.pathname).toBe("http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html");
|
||||
expect(u.searchParams.get("x")).toBe("1");
|
||||
expect(u.searchParams.has("ac_lost")).toBe(false);
|
||||
expect(u.searchParams.get("ac_try")).toMatch(/^\d+\.1$/);
|
||||
expect(w.loc.replaced).not.toContain(TOKEN);
|
||||
});
|
||||
|
||||
it("once the child frame has loaded (e.g. the browser's error page), it gets 6 s", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.tick(1000);
|
||||
w.els.f!.on.load!();
|
||||
w.tick(5000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.tick(2000);
|
||||
expect(w.loc.replaced).not.toBeNull();
|
||||
});
|
||||
|
||||
it("'lost' from the child goes back with ac_lost; 15 s of silence too", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.fromChild({ ac_console: "lost", at: 1234567890123 });
|
||||
expect(new URL(w.loc.replaced!).searchParams.get("ac_lost")).toBe("1234567890123");
|
||||
|
||||
const s = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
s.fromChild({ ac_console: "alive" });
|
||||
for (let i = 0; i < 10; i++) { s.tick(2000); s.fromChild({ ac_console: "alive" }); }
|
||||
expect(s.loc.replaced).toBeNull();
|
||||
s.tick(17000);
|
||||
expect(s.loc.replaced).not.toBeNull();
|
||||
});
|
||||
|
||||
it("time this page was suspended (sleep) or hidden does not count as silence", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ ac_console: "alive" });
|
||||
w.jump(3_600_000); // an hour asleep: the next tick sees a big gap
|
||||
w.tick(1000);
|
||||
w.tick(10000);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
const h = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "", { visible: false });
|
||||
h.tick(60000);
|
||||
expect(h.loc.replaced).toBeNull();
|
||||
});
|
||||
|
||||
it("at most 3 automatic tries in 2 minutes, then a button", async () => {
|
||||
const start = 1_800_000_000_000 - 30_000;
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), `?ac_try=${start}.3`);
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.els.r!.hidden).toBe(false);
|
||||
w.els.r!.onclick!();
|
||||
expect(new URL(w.loc.replaced!).searchParams.has("ac_try")).toBe(false);
|
||||
// an old counter (more than 2 minutes ago) starts over
|
||||
const old = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), `?ac_try=${start - 200_000}.3`);
|
||||
old.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(new URL(old.loc.replaced!).searchParams.get("ac_try")).toBe(`${old.now()}.1`);
|
||||
});
|
||||
|
||||
it("relays only the Magpie theme protocol", async () => {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }));
|
||||
w.fromChild({ magpie: 1, id: 7, method: "hello", extra: "x" });
|
||||
w.fromChild({ magpie: 1, id: 8, method: "openExternal", params: { url: "https://evil" } });
|
||||
expect(w.parentWin.posted).toEqual([{ magpie: 1, id: 7, method: "hello" }]);
|
||||
w.fromParent({ magpie: 1, event: "theme", data: { dark: true }, other: 1 });
|
||||
w.fromParent({ magpie: 1, id: 7, result: { dark: false } });
|
||||
w.fromParent({ magpie: 1, method: "something" });
|
||||
w.fromParent({ ac_console: "lost" }); // only the child can report
|
||||
expect(w.childWin.posted).toEqual([{ magpie: 1, event: "theme", data: { dark: true } }, { magpie: 1, id: 7, result: { dark: false } }]);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("daemon page side", () => {
|
||||
it("isWrapped needs w=1 and a parent; heartbeat only while connected", async () => {
|
||||
const m = await import("../../web/src/api/backToMagpie.js");
|
||||
const posted: unknown[] = [];
|
||||
const g = globalThis as unknown as { window?: unknown };
|
||||
const prev = g.window;
|
||||
const parent = { postMessage: (d: unknown) => posted.push(d) };
|
||||
g.window = { parent };
|
||||
try {
|
||||
expect(m.isWrapped("#t=x&w=1")).toBe(true);
|
||||
expect(m.isWrapped("#t=x")).toBe(false);
|
||||
let state = "connecting";
|
||||
const stop = m.startWrapperHeartbeat({ getState: () => state }, 5);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(posted).toEqual([]);
|
||||
state = "open";
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
stop();
|
||||
expect(posted.length).toBeGreaterThan(0);
|
||||
expect(posted[0]).toEqual({ ac_console: "alive" });
|
||||
m.reportLostToWrapper();
|
||||
expect((posted.at(-1) as { ac_console: string }).ac_console).toBe("lost");
|
||||
} finally {
|
||||
g.window = prev;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -12,7 +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";
|
||||
import { goBackToMagpie, isWrapped, reportLostToWrapper } from "./api/backToMagpie.js";
|
||||
|
||||
export function App() {
|
||||
const { state, version } = useConnection();
|
||||
@@ -43,7 +43,7 @@ export function App() {
|
||||
<div className="boot-screen">
|
||||
<div className="boot-wrap">
|
||||
<span>{t("boot.serviceDown")}</span>
|
||||
<button className="btn primary" onClick={() => { if (!goBackToMagpie()) location.reload(); }}>{t("boot.retry")}</button>
|
||||
<button className="btn primary" onClick={() => { if (isWrapped()) reportLostToWrapper(); else if (!goBackToMagpie()) location.reload(); }}>{t("boot.retry")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -60,3 +60,28 @@ export function watchReconnect(
|
||||
});
|
||||
return () => { off(); if (timer) clearTimeout(timer); };
|
||||
}
|
||||
|
||||
// ---- 1.3: inside the gate's wrapper page (lib/wrapper.mjs) ----
|
||||
// The gate frames this page with #…&w=1. Then the wrapper owns recovery: this page tells it it is alive (while connected)
|
||||
// and when the connection has been lost, and never navigates itself (that would load the Magpie page inside the child frame).
|
||||
|
||||
export function isWrapped(hash: string = location.hash): boolean {
|
||||
const fragment = hash.startsWith("#") ? hash.slice(1) : hash;
|
||||
return new URLSearchParams(fragment).get("w") === "1" && typeof window !== "undefined" && window.parent !== window;
|
||||
}
|
||||
|
||||
/** Heartbeat to the wrapper every 2 s while the WebSocket is open; "lost" once it has been down for a while */
|
||||
export function startWrapperHeartbeat(ws: { getState(): string }, everyMs = 2000): () => void {
|
||||
const beat = () => {
|
||||
if (ws.getState() === "open") {
|
||||
try { window.parent.postMessage({ ac_console: "alive" }, "*"); } catch {}
|
||||
}
|
||||
};
|
||||
beat();
|
||||
const t = setInterval(beat, everyMs);
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
|
||||
export function reportLostToWrapper(): void {
|
||||
try { window.parent.postMessage({ ac_console: "lost", at: lostAt || Date.now() }, "*"); } catch {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// 1.3 Settings → Bash path (Windows): shows what Git Bash detection found and takes a manual bash.exe that overrides it.
|
||||
// The path is checked by the daemon (shell.check) before it is saved; an invalid one is never stored.
|
||||
import { useEffect, useState } from "react";
|
||||
import { ws } from "../main";
|
||||
import { errMsg, t, tf } from "../i18n/index.js";
|
||||
import { openExternal } from "../preview/open";
|
||||
import { GIT_FOR_WINDOWS_URL } from "./Timeline";
|
||||
|
||||
export type ShellStatus = {
|
||||
platform: string;
|
||||
needed: boolean;
|
||||
manual: string;
|
||||
found: { path: string; source: string } | null;
|
||||
manualError?: string;
|
||||
};
|
||||
type Check = { ok: true; path: string } | { ok: false; reason: string };
|
||||
|
||||
const reasonText = (r: string) => {
|
||||
const k = `settings.bashBad.${r}`;
|
||||
const v = t(k);
|
||||
return v === k ? r : v;
|
||||
};
|
||||
|
||||
export function BashPathSetting({ value, save }: { value: string; save: (path: string) => Promise<boolean> }) {
|
||||
const [st, setSt] = useState<ShellStatus | null>(null);
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const load = () => ws.call("shell.status").then((v) => setSt(v as ShellStatus)).catch(() => {});
|
||||
useEffect(() => { void load(); }, []);
|
||||
|
||||
if (!st) return null;
|
||||
if (st.platform !== "win32") return <div className="dlg-hint">{t("settings.bashNotWindows")}</div>;
|
||||
|
||||
const text = draft ?? value;
|
||||
const check = async (): Promise<Check | null> => {
|
||||
try { return (await ws.call("shell.check", { path: text.trim() })) as Check; }
|
||||
catch (e) { setMsg({ ok: false, text: errMsg(e) }); return null; }
|
||||
};
|
||||
const onCheck = async () => {
|
||||
if (!text.trim()) { setMsg(null); return; }
|
||||
setBusy(true);
|
||||
const c = await check();
|
||||
setBusy(false);
|
||||
if (c) setMsg(c.ok ? { ok: true, text: tf("settings.bashOk", { path: c.path }) } : { ok: false, text: reasonText(c.reason) });
|
||||
};
|
||||
const commit = async () => {
|
||||
if (draft === null || draft.trim() === value) { setDraft(null); return; }
|
||||
let next = "";
|
||||
if (draft.trim()) {
|
||||
const c = await check();
|
||||
if (!c) return;
|
||||
if (!c.ok) { setMsg({ ok: false, text: reasonText(c.reason) }); return; } // keep the draft so it can be fixed
|
||||
next = c.path;
|
||||
}
|
||||
setBusy(true);
|
||||
const saved = await save(next);
|
||||
setBusy(false);
|
||||
if (saved) { setDraft(null); setMsg(null); await load(); }
|
||||
};
|
||||
|
||||
const src = st.found ? t(`settings.bashSrc.${st.found.source}`) : "";
|
||||
return (
|
||||
<div className="bash-set">
|
||||
<div className="bash-row">
|
||||
<input className={`tinput${msg && !msg.ok ? " err" : ""}`} spellCheck={false}
|
||||
aria-label={t("settings.bashPath")} placeholder="E:\Git\bin\bash.exe"
|
||||
value={text} onChange={(e) => { setDraft(e.target.value); setMsg(null); }}
|
||||
onBlur={() => void commit()} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void commit(); } }} />
|
||||
<button type="button" className="btn" disabled={busy || !text.trim()} onMouseDown={(e) => e.preventDefault()} onClick={() => void onCheck()}>{t("settings.bashCheck")}</button>
|
||||
</div>
|
||||
{msg && <div className={`dlg-hint${msg.ok ? "" : " err"}`}>{msg.text}</div>}
|
||||
{!msg && st.manualError && <div className="dlg-hint err">{tf("settings.bashManualBad", { why: reasonText(st.manualError) })}</div>}
|
||||
<div className="dlg-hint">
|
||||
{st.found ? tf("settings.bashUsing", { path: st.found.path, src }) : (
|
||||
<>
|
||||
{t("settings.bashNone")}{" "}
|
||||
<button type="button" className="te-files" onClick={() => void openExternal(GIT_FOR_WINDOWS_URL)}>{t("timeline.bashDownload")}</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="dlg-hint">{t("settings.bashHint")}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
// Conversation area (§8.6): virtual list, stick-to-bottom, empty state, queue list, Composer.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { useData, pickDefaultProvider } from "../stores/data";
|
||||
import { useTimeline } from "../stores/timeline";
|
||||
import { TimelineRow } from "./Timeline";
|
||||
import { foldTimeline, TOOL_COLLAPSE_AT } from "../timeline/fold";
|
||||
import { Composer } from "./Composer";
|
||||
import { QuoteSelect } from "./QuoteSelect";
|
||||
import { Icon } from "./Icons";
|
||||
import { ws } from "../main";
|
||||
import { toast } from "./Toast";
|
||||
@@ -19,7 +21,9 @@ export function Chat() {
|
||||
const { projects, threads } = useData();
|
||||
const tl = useTimeline();
|
||||
const prefs = useLiveSettings();
|
||||
const items = prefs.showThinking ? tl.items : tl.items.filter((it) => it.kind !== "reasoning");
|
||||
// 1.3: runs of tool calls (and short thinking between them) fold into one summary row
|
||||
// (tl.items is a fresh array after every timeline change, so the memo follows the stream)
|
||||
const items = useMemo(() => foldTimeline(tl.items, { showThinking: prefs.showThinking }), [tl.items, prefs.showThinking]);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [stick, setStick] = useState(true);
|
||||
const [hasNew, setHasNew] = useState(false);
|
||||
@@ -43,10 +47,11 @@ export function Chat() {
|
||||
switch (it.kind) {
|
||||
case "user": return 60;
|
||||
case "assistant": case "reasoning": return 120;
|
||||
case "toolgroup": return 30 + it.steps.length * 26;
|
||||
// 1.3: short runs are flat rows (26px each), long ones one summary row
|
||||
case "toolgroup": return it.steps.length > TOOL_COLLAPSE_AT ? 34 : 8 + 26 * it.steps.length;
|
||||
case "plan": return 200;
|
||||
case "permission": case "question": return 120;
|
||||
case "todo": return 30;
|
||||
case "todo": return 34 + 24 * it.items.length;
|
||||
case "turnend": case "notice": return 30;
|
||||
default: return 60;
|
||||
}
|
||||
@@ -61,6 +66,24 @@ export function Chat() {
|
||||
measureElement: (el) => el.getBoundingClientRect().height,
|
||||
});
|
||||
|
||||
// 1.3: the composer's "N/M tasks" pill brings its checklist into view
|
||||
useEffect(() => {
|
||||
const on = (e: Event) => {
|
||||
const key = (e as CustomEvent).detail?.key as string | undefined;
|
||||
const idx = key ? items.findIndex((x) => x.key === key) : -1;
|
||||
if (idx < 0) return;
|
||||
virt.scrollToIndex(idx, { align: "center" });
|
||||
requestAnimationFrame(() => {
|
||||
const el = scrollRef.current?.querySelector(`[data-todo-key="${CSS.escape(key!)}"]`);
|
||||
el?.classList.remove("flash");
|
||||
void (el as HTMLElement | null)?.offsetWidth;
|
||||
el?.classList.add("flash");
|
||||
});
|
||||
};
|
||||
window.addEventListener("ac-show-item", on);
|
||||
return () => window.removeEventListener("ac-show-item", on);
|
||||
}, [items, virt]);
|
||||
|
||||
const count = items.length;
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
@@ -69,6 +92,18 @@ export function Chat() {
|
||||
else setHasNew(true);
|
||||
}, [count, stick]);
|
||||
|
||||
// 1.3: a send always lands at the bottom, at once (and again after the new row is measured)
|
||||
useEffect(() => {
|
||||
if (!tl.sentAt) return;
|
||||
setStick(true);
|
||||
setHasNew(false);
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
const raf = requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [tl.sentAt]);
|
||||
|
||||
const onScroll = () => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
@@ -90,7 +125,10 @@ export function Chat() {
|
||||
const rels = root && mentions?.length
|
||||
? mentions.map((m) => ({ rel: relFromAbs(root, m.path), isDir: m.isDir })).filter((m): m is { rel: string; isDir: boolean } => !!m.rel)
|
||||
: [];
|
||||
void ws.call("thread.send", { id: activeThreadId, text, ...(rels.length ? { mentions: rels } : {}) });
|
||||
const busy = tl.status === "running" || tl.status === "initializing";
|
||||
// 1.3: optimistic like the composer (shows now, failure keeps a 重试 bubble); behind a running turn it queues
|
||||
void tl.send(activeThreadId, { text, ...(rels.length ? { mentions: rels } : {}) }, mentions?.length ? { mentions } : {}, { optimistic: !busy })
|
||||
.catch((e) => toast(tr("composer.failSend") + errMsg(e), true));
|
||||
};
|
||||
const retryLast = () => {
|
||||
if (tl.lastUserText) resend(tl.lastUserText);
|
||||
@@ -137,7 +175,7 @@ export function Chat() {
|
||||
return (
|
||||
<>
|
||||
<div className="scroll" ref={scrollRef} onScroll={onScroll}>
|
||||
<div className="tl-wrap">
|
||||
<div className="tl-wrap" data-quote-root="chat">
|
||||
<div style={{ height: virt.getTotalSize(), position: "relative" }}>
|
||||
{virt.getVirtualItems().map((v) => {
|
||||
const it = items[v.index];
|
||||
@@ -169,6 +207,7 @@ export function Chat() {
|
||||
</button>
|
||||
)}
|
||||
<Composer />
|
||||
<QuoteSelect />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -206,7 +245,8 @@ function EmptyComposer({ projectId }: { projectId: string }) {
|
||||
mode: s.defaultMode ?? "default",
|
||||
})) as { id: string };
|
||||
ui.select(projectId, created.id);
|
||||
await ws.call("thread.send", { id: created.id, text: text.trim() });
|
||||
// 1.3: the new conversation opens with the bubble already in it (a failure stays there with 重试)
|
||||
await useTimeline.getState().send(created.id, { text: text.trim() });
|
||||
} catch (e) {
|
||||
toast(tr("chat.failSend") + errMsg(e), true);
|
||||
setBusy(false);
|
||||
|
||||
@@ -9,13 +9,15 @@ import { ws } from "../main";
|
||||
import { getToken } from "../api/token";
|
||||
import { Icon } from "./Icons";
|
||||
import { attachmentUrl, MentionChip } from "./Timeline";
|
||||
import { MENTION_MIME, addMention, joinProjectPath, mentionsForSend, parseMentionDrag, type MentionDraft } from "../composer/mentions";
|
||||
import { addQuote, MAX_QUOTES, quoteLabel, quotesToText, quotesFromText, type Quote } from "../composer/quotes";
|
||||
import { MENTION_MIME, addMention, joinProjectPath, mentionsForSend, parseMentionDrag, relFromAbs, type MentionDraft } from "../composer/mentions";
|
||||
import type { Mode, ModelInfo } from "../types/models";
|
||||
import type { SlashCommand } from "../composer/slashMenu";
|
||||
import { toast } from "./Toast";
|
||||
import { useLiveSettings } from "./Settings";
|
||||
import { composerModeOptions, effortLabel } from "../i18n/modes.js";
|
||||
import { Logo } from "./Logo";
|
||||
import { currentChecklist, todoProgress } from "../timeline/fold";
|
||||
import { SelectMenu } from "./SelectMenu";
|
||||
import { errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
import {
|
||||
@@ -40,6 +42,7 @@ export function Composer() {
|
||||
const [text, setText] = useState("");
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [mentions, setMentions] = useState<MentionDraft[]>([]);
|
||||
const [quotes, setQuotes] = useState<Quote[]>([]);
|
||||
const [dropHint, setDropHint] = useState(false);
|
||||
const [agentPop, setAgentPop] = useState(false);
|
||||
const [pickerProviderId, setPickerProviderId] = useState<string | null>(null);
|
||||
@@ -65,7 +68,10 @@ export function Composer() {
|
||||
const mode = thread?.mode ?? "default";
|
||||
const modes = composerModeOptions(thread?.provider, provider?.capabilities.modes ?? [], provider?.capabilities.modeLabels);
|
||||
const modeMeta = modes.find((m) => m.id === mode);
|
||||
const started = tl.items.some((it) => it.kind === "user");
|
||||
// The Agent is locked once the conversation has run. 1.3: the user's message is saved before the Agent starts, so a
|
||||
// first message whose Agent never started (no session id, no reply) leaves the picker open (the daemon agrees)
|
||||
const started = tl.items.some((it) => it.kind === "user") && (running || !!thread?.providerSessionId
|
||||
|| tl.items.some((it) => it.kind === "assistant" || it.kind === "reasoning" || it.kind === "toolgroup" || it.kind === "permission"));
|
||||
|
||||
const slashMenu = useMemo(() => slashMenuState(text, slashSuppress.current), [text]);
|
||||
const slashFiltered = useMemo(
|
||||
@@ -183,28 +189,46 @@ export function Composer() {
|
||||
|
||||
const send = useCallback(async (behavior: "queue" | "steer" = "queue") => {
|
||||
const id = ui.currentThreadId;
|
||||
const msg = text.trim();
|
||||
if (!id || (!msg && attachments.length === 0 && mentions.length === 0)) return;
|
||||
const typed = text.trim();
|
||||
if (!id || (!typed && attachments.length === 0 && mentions.length === 0 && quotes.length === 0)) return;
|
||||
// 1.3: quotes go in front of the message as "> " blocks
|
||||
const msg = quotesToText(quotes, typed);
|
||||
const steer = running && behavior === "steer" && steerOk;
|
||||
// 1.3: a message that starts a turn (or steers one) shows in the timeline at once; one queued behind a running
|
||||
// turn goes to the queue list instead (it joins the timeline when its turn starts)
|
||||
const optimistic = !running || steer;
|
||||
const sent = { attachments, mentions, quotes };
|
||||
if (running && behavior === "queue") setLastSent((s) => [...s, msg]);
|
||||
setText("");
|
||||
setAttachments([]);
|
||||
setMentions([]);
|
||||
setQuotes([]);
|
||||
const root = projects.find((p) => p.id === thread?.projectId)?.path;
|
||||
try {
|
||||
const r = (await ws.call("thread.send", {
|
||||
id, text: msg,
|
||||
attachments: attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })),
|
||||
...(mentions.length ? { mentions: mentionsForSend(mentions) } : {}),
|
||||
behavior: running && behavior === "steer" && steerOk ? "steer" : "queue",
|
||||
})) as { delivered?: "started" | "steered" | "queued" } | undefined;
|
||||
setAttachments([]);
|
||||
setMentions([]);
|
||||
const r = await useTimeline.getState().send(id, {
|
||||
text: msg,
|
||||
attachments: sent.attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })),
|
||||
...(sent.mentions.length ? { mentions: mentionsForSend(sent.mentions) } : {}),
|
||||
behavior: steer ? "steer" : "queue",
|
||||
}, {
|
||||
attachments: sent.attachments.map((a) => ({ id: a.path, name: a.name.trim() || a.path, mime: a.mime })),
|
||||
...(root && sent.mentions.length ? { mentions: sent.mentions.map((m) => ({ path: joinProjectPath(root, m.rel), isDir: m.isDir })) } : {}),
|
||||
}, { optimistic });
|
||||
// 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);
|
||||
// An optimistic bubble stays in the timeline marked failed, with 重试; a queued one goes back into the input
|
||||
if (!optimistic) {
|
||||
setText(typed); // the quotes are still in their chips
|
||||
setAttachments(sent.attachments);
|
||||
setMentions(sent.mentions);
|
||||
setQuotes(sent.quotes);
|
||||
}
|
||||
toast(tr("composer.failSend") + errMsg(e), true);
|
||||
}
|
||||
}, [text, attachments, mentions, ui.currentThreadId, running, steerOk]);
|
||||
}, [text, attachments, mentions, quotes, ui.currentThreadId, running, steerOk, projects, thread?.projectId]);
|
||||
|
||||
const onKey = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isImeComposing(e.nativeEvent)) return;
|
||||
@@ -314,8 +338,50 @@ export function Composer() {
|
||||
window.addEventListener("ac-insert-mention", on);
|
||||
return () => window.removeEventListener("ac-insert-mention", on);
|
||||
});
|
||||
// 1.3: "编辑" on a user message: its text (and its path chips) back in the input, nothing sent
|
||||
useEffect(() => {
|
||||
const on = (e: Event) => {
|
||||
const d = (e as CustomEvent).detail as { text?: string; mentions?: { path: string; isDir: boolean }[] } | undefined;
|
||||
if (!d || typeof d.text !== "string") return;
|
||||
// Never overwrite a draft (or chips) the user has not sent yet
|
||||
if (text.trim() || quotes.length > 0 || mentions.length > 0 || attachments.length > 0) { toast(tr("timeline.editBusy"), true); return; }
|
||||
// Quotes the message was sent with come back as quote chips, the rest as text
|
||||
const back = quotesFromText(d.text);
|
||||
setQuotes(back.quotes);
|
||||
setText(back.rest);
|
||||
const root = project?.path;
|
||||
if (thread && root && d.mentions?.length) {
|
||||
let list: MentionDraft[] = [];
|
||||
for (const m of d.mentions) {
|
||||
const rel = relFromAbs(root, m.path);
|
||||
if (rel) list = addMention(list, { projectId: thread.projectId, rel, isDir: m.isDir });
|
||||
}
|
||||
setMentions(list);
|
||||
}
|
||||
requestAnimationFrame(() => {
|
||||
const ta = taRef.current;
|
||||
if (!ta) return;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(ta.value.length, ta.value.length);
|
||||
});
|
||||
};
|
||||
window.addEventListener("ac-composer-fill", on);
|
||||
return () => window.removeEventListener("ac-composer-fill", on);
|
||||
});
|
||||
// 1.3: "添加到对话" from a text selection
|
||||
useEffect(() => {
|
||||
const on = (e: Event) => {
|
||||
const d = (e as CustomEvent).detail as { text?: string; src?: string } | undefined;
|
||||
if (!d?.text) return;
|
||||
if (quotes.length >= MAX_QUOTES) { toast(tf("quote.full", { n: MAX_QUOTES }), true); return; }
|
||||
setQuotes((list) => addQuote(list, d.text!, d.src));
|
||||
taRef.current?.focus();
|
||||
};
|
||||
window.addEventListener("ac-add-quote", on);
|
||||
return () => window.removeEventListener("ac-add-quote", on);
|
||||
});
|
||||
// A new conversation starts with no chips
|
||||
useEffect(() => { setMentions([]); }, [ui.currentThreadId]);
|
||||
useEffect(() => { setMentions([]); setQuotes([]); }, [ui.currentThreadId]);
|
||||
|
||||
const onDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -369,6 +435,7 @@ export function Composer() {
|
||||
})();
|
||||
|
||||
if (!ui.currentThreadId) return null;
|
||||
const checklist = currentChecklist(tl.items);
|
||||
|
||||
return (
|
||||
<div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop}
|
||||
@@ -379,6 +446,16 @@ export function Composer() {
|
||||
if (ours !== dropHint) setDropHint(ours);
|
||||
}}
|
||||
onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropHint(false); }}>
|
||||
{/* 1.3: the latest turn's step list as a small "N/M tasks" pill; click shows the list in the timeline */}
|
||||
{checklist && (
|
||||
<div className="cp-tasks">
|
||||
<button type="button" className="tasks-pill" title={tr("timeline.tasksPillTitle")}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent("ac-show-item", { detail: { key: checklist.key } }))}>
|
||||
<Icon name="listChecks" size={12} />
|
||||
<span>{tf("timeline.tasksPill", todoProgress(checklist.items))}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{/* queue list */}
|
||||
{tl.queue.length > 0 && (
|
||||
<div className="q-list">
|
||||
@@ -400,6 +477,19 @@ export function Composer() {
|
||||
{imagesByPath && attachments.some((a) => a.mime.startsWith("image/")) && (
|
||||
<div className="att-note">{tf("composer.imagesByPath", { agent: provider?.name ?? "" })}</div>
|
||||
)}
|
||||
{quotes.length > 0 && (
|
||||
<div className="att-bar q-bar">
|
||||
{quotes.map((q) => (
|
||||
<span key={q.id} className="qchip" title={`${tr("quote.chipTitle")}\n\n${q.src ? `[${q.src}]\n` : ""}${q.text.slice(0, 600)}`}>
|
||||
<Icon name="quote" size={12} />
|
||||
<span className="qchip-t">{quoteLabel(q)}</span>
|
||||
{q.text.includes("\n") && <span className="qchip-n">{tf("quote.lines", { n: q.text.split("\n").length })}</span>}
|
||||
<button type="button" className="att-x" aria-label={tr("quote.remove")} title={tr("quote.remove")}
|
||||
onClick={() => setQuotes((list) => list.filter((x) => x.id !== q.id))}>×</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{(attachments.length > 0 || mentions.length > 0) && (
|
||||
<div className="att-bar">
|
||||
{mentions.map((m) => (
|
||||
@@ -481,10 +571,10 @@ export function Composer() {
|
||||
{/* Agent·model pill */}
|
||||
<div className="pill-wrap" ref={pickerRef}>
|
||||
<button className="pill chip" onClick={() => openPicker(!agentPop)} title={tr("composer.agentModel")}>
|
||||
<Logo size={18} className="chip-logo" />
|
||||
<Logo size={16} 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>
|
||||
<ChipCaret />
|
||||
</button>
|
||||
{agentPop && (
|
||||
<div className="pop agent-pop agent-picker">
|
||||
@@ -635,6 +725,7 @@ export function Composer() {
|
||||
if (!cur) return tr("composer.defaultEffort");
|
||||
return effortLabel(cur, thinkingOpts.find((o) => o.id === cur)?.label);
|
||||
})()}</span>
|
||||
<ChipCaret />
|
||||
</SelectMenu>
|
||||
)}
|
||||
{/* permission mode: list only the modes this Agent really has; hidden when there is only one (e.g. Pi has no modes) */}
|
||||
@@ -655,6 +746,7 @@ export function Composer() {
|
||||
>
|
||||
<Icon name="shield" size={14} />
|
||||
<span className="ip-l">{shown.label}</span>
|
||||
<ChipCaret />
|
||||
</SelectMenu>
|
||||
);
|
||||
})()}
|
||||
@@ -670,7 +762,9 @@ export function Composer() {
|
||||
onChange={(v) => setCursorOpts({ cursorFast: v === "fast" })}
|
||||
options={[{ value: "off", label: "Fast: Off" }, { value: "fast", label: "Fast: On" }]}
|
||||
>
|
||||
<Icon name="zap" size={13} />
|
||||
<span className="ip-l">{thread.cursorFast ? "Fast: On" : "Fast: Off"}</span>
|
||||
<ChipCaret />
|
||||
</SelectMenu>
|
||||
)}
|
||||
<span className="cp-div" aria-hidden="true" />
|
||||
@@ -684,7 +778,7 @@ export function Composer() {
|
||||
{running ? (
|
||||
<>
|
||||
<span className="cp-clock">{elapsed}s</span>
|
||||
{(text.trim() || attachments.length > 0 || mentions.length > 0) && (
|
||||
{(text.trim() || attachments.length > 0 || mentions.length > 0 || quotes.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")}>
|
||||
@@ -696,7 +790,7 @@ export function Composer() {
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0 && mentions.length === 0) || attachments.some((a) => a.uploading)}
|
||||
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0 && mentions.length === 0 && quotes.length === 0) || attachments.some((a) => a.uploading)}
|
||||
onClick={() => void send("queue")}>
|
||||
<Icon name="arrowUp" />
|
||||
</button>
|
||||
@@ -710,3 +804,12 @@ export function Composer() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The small ⌄ every composer chip ends with (1.3: one chip style for agent·model, effort, permission, Fast) */
|
||||
function ChipCaret() {
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,21 @@ const PATHS: Record<string, string> = {
|
||||
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",
|
||||
quote: "M5 7h5v5H7c0 2 1 3 3 4M14 7h5v5h-3c0 2 1 3 3 4",
|
||||
pencil: "M4 20h4L19 9a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",
|
||||
zap: "M13 2L4 14h7l-1 8 9-12h-7l1-8z",
|
||||
// 1.3 timeline rows / footer / code blocks
|
||||
prompt: "M5 7l5 5-5 5M12 17h7",
|
||||
fileText: "M6 3h8l4 4v14H6zM14 3v4h4M9 12h6M9 16h6",
|
||||
layers: "M12 3l9 5-9 5-9-5 9-5zM3 13l9 5 9-5",
|
||||
wrench: "M14.7 6.3a4 4 0 0 0-5.4 5.4L4 17l3 3 5.3-5.3a4 4 0 0 0 5.4-5.4l-2.5 2.5-2.4-.6-.6-2.4z",
|
||||
spark: "M12 4v4M12 16v4M4 12h4M16 12h4M6.6 6.6l2.2 2.2M15.2 15.2l2.2 2.2M6.6 17.4l2.2-2.2M15.2 8.8l2.2-2.2",
|
||||
clock: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l3 2",
|
||||
hourglass: "M7 3h10M7 21h10M8 3c0 4.5 8 4.5 8 9s-8 4.5-8 9M16 3c0 4.5-8 4.5-8 9s8 4.5 8 9",
|
||||
cpu: "M6 6h12v12H6zM10 10h4v4h-4zM9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3",
|
||||
wrap: "M4 6h16M4 12h13a3 3 0 0 1 0 6h-4m2-2-2 2 2 2M4 18h5",
|
||||
listChecks: "M4 7l2 2 3-3M4 15l2 2 3-3M12 8h8M12 16h8",
|
||||
circle: "M12 4.5a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15z",
|
||||
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",
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Markdown rendering: marked + DOMPurify + highlight.js (languages on demand, code blocks with a copy button).
|
||||
// Markdown rendering: marked + DOMPurify + highlight.js (languages on demand). 1.3: code blocks get a header with the
|
||||
// language, copy and wrap buttons, and line numbers (a CSS counter on one block per line, so wrapped lines keep a gutter).
|
||||
import { useMemo, useRef, useEffect } from "react";
|
||||
import { marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
@@ -28,21 +29,13 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea
|
||||
if (!el) return;
|
||||
for (const pre of el.querySelectorAll("pre")) {
|
||||
const code = pre.querySelector("code");
|
||||
if (code && !code.dataset.hl) {
|
||||
code.dataset.hl = "1";
|
||||
try { hljs.highlightElement(code as HTMLElement); } catch {}
|
||||
}
|
||||
if (!pre.querySelector(".cb-copy")) {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "cb-copy";
|
||||
btn.type = "button";
|
||||
btn.textContent = t("common.copy");
|
||||
btn.onclick = () => {
|
||||
const txt = code?.textContent ?? "";
|
||||
void copyText(txt).then(() => { btn.textContent = t("common.copied"); setTimeout(() => (btn.textContent = t("common.copy")), 1200); });
|
||||
};
|
||||
pre.appendChild(btn);
|
||||
}
|
||||
if (!code || code.dataset.hl) continue;
|
||||
code.dataset.hl = "1";
|
||||
const raw = (code.textContent ?? "").replace(/\n$/, "");
|
||||
const fence = /(?:^|\s)language-([\w+#.-]+)/.exec(code.className)?.[1];
|
||||
try { hljs.highlightElement(code as HTMLElement); } catch {}
|
||||
const lang = fence ?? /(?:^|\s)language-([\w+#.-]+)/.exec(code.className)?.[1] ?? "";
|
||||
decorateCodeBlock(pre, code as HTMLElement, raw, lang);
|
||||
}
|
||||
// While streaming the text changes many times a second: link once it settles (and on every final render)
|
||||
if (!streaming) linkifyLocal(el, t("links.openPreviewTitle"));
|
||||
@@ -58,6 +51,94 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea
|
||||
);
|
||||
}
|
||||
|
||||
const SVG_NS = "http://www.w3.org/2000/svg";
|
||||
function svgIcon(d: string): SVGSVGElement {
|
||||
const svg = document.createElementNS(SVG_NS, "svg");
|
||||
for (const [k, v] of Object.entries({ width: "13", height: "13", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "1.6", "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": "true" })) svg.setAttribute(k, v);
|
||||
const path = document.createElementNS(SVG_NS, "path");
|
||||
path.setAttribute("d", d);
|
||||
svg.appendChild(path);
|
||||
return svg;
|
||||
}
|
||||
const ICON_COPY = "M8 8h11v12H8zM5 16V4h11";
|
||||
const ICON_CHECK = "M5 13l4 4L19 7";
|
||||
const ICON_WRAP = "M4 6h16M4 12h13a3 3 0 0 1 0 6h-4m2-2-2 2 2 2M4 18h5";
|
||||
|
||||
/** Highlighted code → one block per line (hljs spans that cross a line break are re-opened on the next line) */
|
||||
export function splitCodeLines(code: HTMLElement): HTMLElement[] {
|
||||
const lines: HTMLElement[] = [];
|
||||
const newLine = () => { const l = document.createElement("span"); l.className = "cb-l"; lines.push(l); return l; };
|
||||
let cur = newLine();
|
||||
const walk = (node: Node, classes: string[]) => {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
const parts = (node.textContent ?? "").split("\n");
|
||||
parts.forEach((part, i) => {
|
||||
if (i > 0) cur = newLine();
|
||||
if (!part) return;
|
||||
let host: HTMLElement = cur;
|
||||
for (const c of classes) { const sp = document.createElement("span"); sp.className = c; host.appendChild(sp); host = sp; }
|
||||
host.appendChild(document.createTextNode(part));
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const cls = (node as Element).getAttribute("class");
|
||||
for (const ch of [...node.childNodes]) walk(ch, cls ? [...classes, cls] : classes);
|
||||
}
|
||||
};
|
||||
for (const ch of [...code.childNodes]) walk(ch, []);
|
||||
// the trailing newline of a fenced block is not a line of its own
|
||||
while (lines.length > 1 && !lines[lines.length - 1]!.textContent) lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** Wrap a rendered <pre><code> in a code block: header (language · wrap · copy), numbered lines */
|
||||
function decorateCodeBlock(pre: HTMLPreElement, code: HTMLElement, raw: string, lang: string): void {
|
||||
if (pre.parentElement?.classList.contains("cb")) return;
|
||||
const box = document.createElement("div");
|
||||
box.className = "cb";
|
||||
const head = document.createElement("div");
|
||||
head.className = "cb-head";
|
||||
const label = document.createElement("span");
|
||||
label.className = "cb-lang";
|
||||
label.textContent = lang || "text";
|
||||
const acts = document.createElement("span");
|
||||
acts.className = "cb-acts";
|
||||
const btn = (title: string, d: string, cls: string) => {
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.className = `cb-btn ${cls}`;
|
||||
b.title = title;
|
||||
b.setAttribute("aria-label", title);
|
||||
b.appendChild(svgIcon(d));
|
||||
return b;
|
||||
};
|
||||
const wrap = btn(t("timeline.codeWrap"), ICON_WRAP, "cb-wrap");
|
||||
wrap.setAttribute("aria-pressed", "false");
|
||||
wrap.onclick = () => {
|
||||
const on = !box.classList.contains("wrap");
|
||||
box.classList.toggle("wrap", on);
|
||||
wrap.setAttribute("aria-pressed", String(on));
|
||||
};
|
||||
const copy = btn(t("common.copy"), ICON_COPY, "cb-copy");
|
||||
copy.onclick = () => {
|
||||
void copyText(raw).then(() => {
|
||||
copy.replaceChildren(svgIcon(ICON_CHECK));
|
||||
copy.classList.add("done");
|
||||
setTimeout(() => { copy.replaceChildren(svgIcon(ICON_COPY)); copy.classList.remove("done"); }, 1200);
|
||||
});
|
||||
};
|
||||
acts.append(wrap, copy);
|
||||
head.append(label, acts);
|
||||
const lines = splitCodeLines(code);
|
||||
if (lines.length > 1) {
|
||||
code.replaceChildren(...lines);
|
||||
box.classList.add("numbered");
|
||||
}
|
||||
pre.replaceWith(box);
|
||||
box.append(head, pre);
|
||||
}
|
||||
|
||||
// Clipboard: writeText → on failure fall back to a hidden textarea + execCommand (§8.2)
|
||||
export async function copyText(t: string): Promise<void> {
|
||||
try {
|
||||
|
||||
@@ -210,7 +210,7 @@ function ChangesPanel() {
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="chg-diff">
|
||||
<div className="chg-diff" data-quote-root="panel" data-quote-src={selPath ?? undefined}>
|
||||
{diff?.loading && <div className="pn-empty">{t("panel.loadingDiff")}</div>}
|
||||
{diff?.tooLarge && <div className="pn-empty">{t("panel.diffTooLarge")}</div>}
|
||||
{diff?.error && <div className="pn-empty">{diff.error}</div>}
|
||||
@@ -381,7 +381,7 @@ function FilesPanel() {
|
||||
</div>
|
||||
<div className="ft-tree">{renderDir(".", 0)}</div>
|
||||
{sel && (
|
||||
<div className="ft-view">
|
||||
<div className="ft-view" data-quote-root="panel" data-quote-src={sel}>
|
||||
{file?.loading && <div className="pn-empty">{t("panel.reading")}</div>}
|
||||
{file?.binary && <div className="pn-empty">{t("panel.binary")}</div>}
|
||||
{file?.tooLarge && <div className="pn-empty">{t("panel.tooLarge")}</div>}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// 1.3 "添加到对话": select text in the conversation (replies, your own messages, code, tool output) or in the right
|
||||
// panel (file preview, diff) and a small button offers to add it to the composer as a quote.
|
||||
// - Only inside [data-quote-root] areas; never for selections in inputs, the composer, buttons or across two areas.
|
||||
// - Hidden while the mouse is still dragging (no flicker), shown on release; it never takes the selection away
|
||||
// (mousedown on it is cancelled), so Ctrl+C keeps working and the button stays while the pointer travels to it.
|
||||
// - Placed above the selection, or below it when there is no room, inside the visible part of the scroller
|
||||
// (above the composer), never off-screen at narrow widths. Follows scrolling; Esc or an empty selection hides it.
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Icon } from "./Icons";
|
||||
import { t } from "../i18n/index.js";
|
||||
import { placeQuotePop, type Box } from "../composer/quotes";
|
||||
|
||||
type Pick = { text: string; src?: string; left: number; top: number };
|
||||
|
||||
const POP_W_FALLBACK = 118, POP_H = 30;
|
||||
const EDITABLE = "input, textarea, select, [contenteditable=''], [contenteditable='true'], button, .cp-card, .qs-pop, [data-quote-off]";
|
||||
|
||||
function elOf(n: Node | null): Element | null {
|
||||
return !n ? null : n.nodeType === 1 ? (n as Element) : n.parentElement;
|
||||
}
|
||||
|
||||
/** The selection to quote, or null (outside a quote area, inside an input, spanning two areas, blank) */
|
||||
export function quotableSelection(sel: Selection | null): { range: Range; text: string; root: Element; src?: string } | null {
|
||||
if (!sel || sel.isCollapsed || sel.rangeCount === 0) return null;
|
||||
const text = sel.toString();
|
||||
if (!text.trim()) return null;
|
||||
const a = elOf(sel.anchorNode), f = elOf(sel.focusNode);
|
||||
if (!a || !f) return null;
|
||||
const root = a.closest("[data-quote-root]");
|
||||
if (!root || root !== f.closest("[data-quote-root]")) return null;
|
||||
if (a.closest(EDITABLE) || f.closest(EDITABLE)) return null;
|
||||
const range = sel.getRangeAt(0);
|
||||
const srcEl = elOf(range.commonAncestorContainer)?.closest("[data-quote-src]");
|
||||
const src = srcEl?.getAttribute("data-quote-src") || undefined;
|
||||
return { range, text, root, src };
|
||||
}
|
||||
|
||||
function visibleArea(root: Element): Box {
|
||||
// The scroller the area lives in; for the chat, stop above the composer
|
||||
let sc: Element | null = root;
|
||||
while (sc && sc !== document.body) {
|
||||
const o = getComputedStyle(sc).overflowY;
|
||||
if (o === "auto" || o === "scroll") break;
|
||||
sc = sc.parentElement;
|
||||
}
|
||||
const r = (sc && sc !== document.body ? sc : document.documentElement).getBoundingClientRect();
|
||||
let bottom = Math.min(r.bottom, window.innerHeight);
|
||||
const cp = document.querySelector(".composer");
|
||||
if (root.getAttribute("data-quote-root") === "chat" && cp) bottom = Math.min(bottom, cp.getBoundingClientRect().top);
|
||||
return { left: r.left, right: r.right, top: Math.max(r.top, 0) + 4, bottom: bottom - 4 };
|
||||
}
|
||||
|
||||
export function QuoteSelect() {
|
||||
const [pick, setPick] = useState<Pick | null>(null);
|
||||
const dragging = useRef(false);
|
||||
const popRef = useRef<HTMLButtonElement>(null);
|
||||
const raf = useRef(0);
|
||||
|
||||
const update = useCallback(() => {
|
||||
cancelAnimationFrame(raf.current);
|
||||
raf.current = requestAnimationFrame(() => {
|
||||
if (dragging.current) return;
|
||||
const q = quotableSelection(window.getSelection());
|
||||
if (!q) { setPick(null); return; }
|
||||
const w = popRef.current?.offsetWidth || POP_W_FALLBACK;
|
||||
const boxes = [...q.range.getClientRects()].map((r) => ({ left: r.left, top: r.top, right: r.right, bottom: r.bottom }));
|
||||
const at = placeQuotePop(boxes, visibleArea(q.root), { w, h: POP_H }, window.innerWidth);
|
||||
if (!at) { setPick(null); return; }
|
||||
setPick({ text: q.text, src: q.src, left: at.left, top: at.top });
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const down = (e: PointerEvent) => {
|
||||
if ((e.target as Element | null)?.closest?.(".qs-pop")) return;
|
||||
if (e.button !== 0) return;
|
||||
dragging.current = true;
|
||||
setPick(null);
|
||||
};
|
||||
const up = () => {
|
||||
if (!dragging.current) return;
|
||||
dragging.current = false;
|
||||
update();
|
||||
};
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { setPick(null); return; }
|
||||
update();
|
||||
};
|
||||
const onSel = () => update();
|
||||
const onScroll = () => update();
|
||||
document.addEventListener("pointerdown", down, true);
|
||||
document.addEventListener("pointerup", up, true);
|
||||
document.addEventListener("keyup", key, true);
|
||||
document.addEventListener("selectionchange", onSel);
|
||||
window.addEventListener("scroll", onScroll, true);
|
||||
window.addEventListener("resize", onScroll);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", down, true);
|
||||
document.removeEventListener("pointerup", up, true);
|
||||
document.removeEventListener("keyup", key, true);
|
||||
document.removeEventListener("selectionchange", onSel);
|
||||
window.removeEventListener("scroll", onScroll, true);
|
||||
window.removeEventListener("resize", onScroll);
|
||||
cancelAnimationFrame(raf.current);
|
||||
};
|
||||
}, [update]);
|
||||
|
||||
if (!pick) return null;
|
||||
const add = () => {
|
||||
window.dispatchEvent(new CustomEvent("ac-add-quote", { detail: { text: pick.text, src: pick.src } }));
|
||||
window.getSelection()?.removeAllRanges();
|
||||
setPick(null);
|
||||
};
|
||||
return createPortal(
|
||||
<button
|
||||
ref={popRef}
|
||||
type="button"
|
||||
className="qs-pop"
|
||||
style={{ left: pick.left, top: pick.top }}
|
||||
title={t("quote.addHint")}
|
||||
// Keep the selection (and so Ctrl+C) while clicking
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onPointerDown={(e) => e.preventDefault()}
|
||||
onClick={add}
|
||||
>
|
||||
<Icon name="quote" size={13} />
|
||||
<span>{t("quote.add")}</span>
|
||||
</button>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ 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 { BashPathSetting } from "./BashPathSetting";
|
||||
import { useData } from "../stores/data.js";
|
||||
import { IDLE_MAX, IDLE_MIN, parseArgsDraft, parseIdleDraft } from "./settingsFields.js";
|
||||
import { applyTheme, embeddedInMagpie, normalizeThemeSetting } from "../layout/theme.js";
|
||||
@@ -16,7 +17,7 @@ type Settings = {
|
||||
defaultProvider?: string; defaultMode?: string;
|
||||
sendKey?: string; runningSend?: string; showThinking?: boolean;
|
||||
theme?: string; idleCloseMinutes?: number;
|
||||
contentWidth?: string; chatFontSize?: number;
|
||||
contentWidth?: string; chatFontSize?: number; bashPath?: string;
|
||||
providerEnabled?: Record<string, boolean>;
|
||||
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
|
||||
[k: string]: unknown;
|
||||
@@ -281,6 +282,7 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
|
||||
<span className="dlg-hint">{t("settings.idleMinutes")}</span>
|
||||
</div>
|
||||
), idleBad ? t("settings.idleInvalid") : undefined)}
|
||||
{row(t("settings.bashPath"), <BashPathSetting value={s.bashPath ?? ""} save={(bashPath) => set({ bashPath })} />)}
|
||||
<div className="msep" />
|
||||
<div className="dlg-hint">
|
||||
{tf("settings.versionLine", { ver: info.version ?? "?", pid: info.pid ?? "?" })}<br />
|
||||
|
||||
@@ -7,12 +7,18 @@ import { Icon } from "./Icons";
|
||||
import { ws } from "../main";
|
||||
import { getToken } from "../api/token";
|
||||
import { normalizeHunks } from "../timeline/diffHunks";
|
||||
import { activeStep, stepCategory, stepDiffStat, stepTarget, summarize, todoProgress, toolStepCount, TOOL_COLLAPSE_AT } from "../timeline/fold";
|
||||
import { useData } from "../stores/data";
|
||||
import { fmtDur, fmtTokens, fmtCost } from "../util/format";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { localizeDaemonMessage, t, tf } from "../i18n/index.js";
|
||||
import { toast } from "./Toast";
|
||||
import { splitLocalLinks } from "../util/localLinks";
|
||||
import { onChatLinkClick } from "../preview/open";
|
||||
import { onChatLinkClick, openExternal } from "../preview/open";
|
||||
import { splitQuotes } from "../composer/quotes";
|
||||
import { localClientIds, useTimeline } from "../stores/timeline";
|
||||
|
||||
export const GIT_FOR_WINDOWS_URL = "https://git-scm.com/download/win";
|
||||
|
||||
const token = () => getToken();
|
||||
|
||||
@@ -51,9 +57,29 @@ export function MentionChip({ path, isDir, onRemove }: { path: string; isDir: bo
|
||||
}
|
||||
|
||||
// ---------- user message ----------
|
||||
/** A copy button's "copied" check for 1.5 s */
|
||||
function useCopied(): [boolean, (text: string) => void] {
|
||||
const [copied, setCopied] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!copied) return;
|
||||
const id = setTimeout(() => setCopied(false), 1500);
|
||||
return () => clearTimeout(id);
|
||||
}, [copied]);
|
||||
return [copied, (text: string) => void copyText(text).then(() => setCopied(true))];
|
||||
}
|
||||
|
||||
export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string, mentions?: { path: string; isDir: boolean }[]) => void }) {
|
||||
// 1.3: the actions sit right under the bubble, inside the row that is the hover target (1.2 floated them 12px to the
|
||||
// bubble's left, outside it, so they vanished on the way there), and stay reachable from the keyboard
|
||||
const [copied, copy] = useCopied();
|
||||
// 1.3: quotes added with "添加到对话" were sent as leading "> " blocks: show them as quotes
|
||||
const parsed = useMemo(() => splitQuotes(it.text), [it.text]);
|
||||
const edit = () => window.dispatchEvent(new CustomEvent("ac-composer-fill", { detail: { text: it.text, mentions: it.mentions ?? [] } }));
|
||||
// 1.3: a bubble sent from this page fades in once; the echo keeps the same key and class, so nothing replays or jumps
|
||||
const fresh = !!it.clientId && localClientIds.has(it.clientId);
|
||||
const failed = it.sendState === "failed";
|
||||
return (
|
||||
<div className="um-row">
|
||||
<div className={`um-row${fresh ? " fresh" : ""}${it.sendState ? ` ${it.sendState}` : ""}`} data-client-id={it.clientId}>
|
||||
<div className="um">
|
||||
{it.attachments?.filter((a) => isImageMime(a.mime)).map((a) => (
|
||||
<img key={a.id} className="um-img" src={`/attachments/${a.id}?t=${token()}`} alt={a.name} />
|
||||
@@ -69,13 +95,37 @@ export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "us
|
||||
{it.mentions && it.mentions.length > 0 && (
|
||||
<span className="um-mentions">{it.mentions.map((m) => <MentionChip key={m.path} path={m.path} isDir={m.isDir} />)}</span>
|
||||
)}
|
||||
<span className="um-text">{it.text}</span>
|
||||
<div className="um-act">
|
||||
<button className="ibtn" title={t("common.copy")} onClick={() => void copyText(it.text)}><Icon name="copy" size={13} /></button>
|
||||
{onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text, it.mentions)}><Icon name="send" size={13} /></button>}
|
||||
</div>
|
||||
{parsed.quotes.map((q, i) => <span key={i} className="um-quote">{q}</span>)}
|
||||
<span className="um-text">{parsed.rest}</span>
|
||||
</div>
|
||||
{it.steered && <div className="um-tag">{t("timeline.steer")}</div>}
|
||||
{failed && it.clientId && (
|
||||
<div className="um-fail" role="alert">
|
||||
<span className="um-fail-t" title={it.sendError ? localizeDaemonMessage(it.sendError) : undefined}>
|
||||
<Icon name="x" size={12} />{t("timeline.sendFailed")}
|
||||
</span>
|
||||
<button type="button" className="um-fail-b" title={t("timeline.sendRetry")} onClick={() => useTimeline.getState().retry(it.clientId!)}>
|
||||
<Icon name="refresh" size={12} /><span>{t("common.retry")}</span>
|
||||
</button>
|
||||
<button type="button" className="um-fail-b" title={t("timeline.sendDismiss")} aria-label={t("timeline.sendDismiss")} onClick={() => useTimeline.getState().dismiss(it.clientId!)}>
|
||||
<span>{t("common.remove")}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="um-act" role="toolbar" aria-label={t("timeline.msgActions")}>
|
||||
<button type="button" className={`ibtn${copied ? " done" : ""}`} title={copied ? t("common.copied") : t("common.copy")}
|
||||
aria-label={copied ? t("common.copied") : t("common.copy")} onClick={() => copy(it.text)}>
|
||||
<Icon name={copied ? "check" : "copy"} size={13} />
|
||||
</button>
|
||||
<button type="button" className="ibtn" title={t("timeline.editMsg")} aria-label={t("timeline.editMsg")} onClick={edit}>
|
||||
<Icon name="pencil" size={13} />
|
||||
</button>
|
||||
{onRetry && !it.sendState && (
|
||||
<button type="button" className="ibtn" title={t("timeline.resend")} aria-label={t("timeline.resend")} onClick={() => onRetry(it.text, it.mentions)}>
|
||||
<Icon name="refresh" size={13} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -100,13 +150,26 @@ export function ReasoningItem({ it }: { it: Extract<DisplayItem, { kind: "reason
|
||||
return (
|
||||
<div className="rs-item">
|
||||
<button className="rs-head" onClick={() => setOpen(!open)}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span> {tf("timeline.thinking", { s: secs })}
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span> {it.streaming ? t("timeline.nowThinking") : tf("timeline.thinking", { s: secs })}
|
||||
</button>
|
||||
{open && <div className="rs-body">{it.text}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 1.3: Windows without Git Bash (Claude Code / Pi / dsh need it): link to Git for Windows and to the manual setting */
|
||||
function BashMissingNotice({ it }: { it: Extract<DisplayItem, { kind: "notice" }> }) {
|
||||
return (
|
||||
<div className={`nt ${it.level} nt-bash`}>
|
||||
<div>{t("timeline.bashMissing")}</div>
|
||||
<div className="nt-actions">
|
||||
<button type="button" className="btn" onClick={() => void openExternal(GIT_FOR_WINDOWS_URL)}>{t("timeline.bashDownload")}</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event("open-settings"))}>{t("timeline.bashSetting")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- tool group ----------
|
||||
function toolKind(k: string): string {
|
||||
const key = `timeline.tool.${k}` as const;
|
||||
@@ -114,58 +177,130 @@ function toolKind(k: string): string {
|
||||
return v.startsWith("timeline.tool.") ? t("timeline.tool.other") : v;
|
||||
}
|
||||
|
||||
/** 1.3 rows: a small line icon per tool type (grayscale) */
|
||||
const KIND_ICON: Record<string, string> = {
|
||||
edit: "pencil", write: "pencil", bash: "prompt", read: "fileText", search: "search", glob: "search",
|
||||
web: "globe", task: "layers", mcp: "wrench", todo: "listChecks",
|
||||
};
|
||||
/** Rows whose target is a command, a path or a pattern: drawn in the code font */
|
||||
const MONO_KINDS = new Set(["edit", "write", "bash", "read", "search", "glob"]);
|
||||
|
||||
/** The current project's folder, to show tool paths relative to it */
|
||||
function useProjectRoot(): string | null {
|
||||
const pid = useUi((s) => s.currentProjectId);
|
||||
const projects = useData((s) => s.projects);
|
||||
return projects.find((p) => p.id === pid)?.path ?? null;
|
||||
}
|
||||
|
||||
/** "D:\\proj\\src\\a.ts" under "D:\\proj" → "src\\a.ts" (case-insensitive, either slash); anything else unchanged */
|
||||
export function relToRoot(target: string, root: string | null): string {
|
||||
if (!root) return target;
|
||||
const norm = (x: string) => x.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
||||
const r = norm(root);
|
||||
const tl = target.replace(/\\/g, "/").toLowerCase();
|
||||
if (r && tl.startsWith(r + "/")) return target.slice(r.length + 1);
|
||||
// a command that cds into the project first keeps its text; only whole paths are shortened
|
||||
return target;
|
||||
}
|
||||
|
||||
export function ToolGroupItem({ it }: { it: Extract<DisplayItem, { kind: "toolgroup" }> }) {
|
||||
// Failed steps or steps with a diff are worth seeing directly → auto-expand (never reopened after the user collapses them)
|
||||
const hasFail = it.steps.some((s) => s.status === "failed");
|
||||
const hasDiff = it.steps.some((s) => {
|
||||
const d = s.detail as { hunks?: unknown[]; diff?: { hunks?: unknown[] } } | undefined;
|
||||
const h = d?.hunks ?? d?.diff?.hunks;
|
||||
return Array.isArray(h) && h.length > 0;
|
||||
});
|
||||
const [open, setOpen] = useState(hasFail || hasDiff);
|
||||
const userToggled = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!userToggled.current && (hasFail || hasDiff)) setOpen(true);
|
||||
}, [hasFail, hasDiff]);
|
||||
// Not memoized on it.steps: the reducer appends steps to the same array while a turn streams,
|
||||
// so a memo keyed on the array kept the first count ("1 step · Read 1" next to five steps).
|
||||
const summary = (() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const s of it.steps) counts.set(s.kind, (counts.get(s.kind) ?? 0) + 1);
|
||||
const parts = [...counts.entries()].map(([k, n]) => `${toolKind(k)} ${n}`);
|
||||
return tf(it.steps.length === 1 ? "timeline.toolSummaryOne" : "timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") });
|
||||
})();
|
||||
const runningStep = it.steps.find((s) => s.status === "running");
|
||||
// 1.3 timeline polish (Better Paseo style): every step is one compact row (icon · command or path · +N -M · status).
|
||||
// Only a long run (more than TOOL_COLLAPSE_AT tool calls) folds into one summary row with counts, which expands.
|
||||
const [open, setOpen] = useState(false);
|
||||
// Not memoized on it.steps: the reducer appends steps to the same array while a turn streams
|
||||
const long = toolStepCount(it.steps) > TOOL_COLLAPSE_AT;
|
||||
if (!long) {
|
||||
return (
|
||||
<div className="tg flat">
|
||||
<div className="tg-list">
|
||||
{it.steps.map((s) => (s.kind === "think" ? <ThinkStepRow key={s.itemId} s={s} /> : <ToolStepRow key={s.itemId} s={s} />))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const sum = summarize(it.steps);
|
||||
const parts = sum.counts.map(([c, n]) => tf(`timeline.cat.${c}`, { n }));
|
||||
if (!parts.length && sum.thinkSecs) parts.push(tf("timeline.thinking", { s: sum.thinkSecs }));
|
||||
const active = activeStep(it.steps);
|
||||
return (
|
||||
<div className="tg">
|
||||
<button className="tg-head" onClick={() => { userToggled.current = true; setOpen(!open); }}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span>
|
||||
<span>{summary}</span>
|
||||
{runningStep && <span className="tg-live">{tf("timeline.toolRunning", { kind: toolKind(runningStep.kind), title: runningStep.title })}</span>}
|
||||
<div className={`tg${open ? " open" : ""}`}>
|
||||
<button className="tg-head" aria-expanded={open} onClick={() => setOpen(!open)}>
|
||||
<span className="tg-ic" aria-hidden><Icon name="layers" size={13} /></span>
|
||||
<span className="tg-sum">{parts.join(" · ")}</span>
|
||||
{sum.failed > 0 && <span className="tg-fail">{tf("timeline.failedCount", { n: sum.failed })}</span>}
|
||||
<span className={`caret${open ? " open" : ""}`} aria-hidden>›</span>
|
||||
</button>
|
||||
{!open && active && <RunningRow s={active} />}
|
||||
{open && (
|
||||
<div className="tg-list">
|
||||
{it.steps.map((s) => <ToolStepRow key={s.itemId} s={s} />)}
|
||||
{it.steps.map((s) => (s.kind === "think" ? <ThinkStepRow key={s.itemId} s={s} /> : <ToolStepRow key={s.itemId} s={s} />))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolStepRow({ s }: { s: ToolStep }) {
|
||||
// Failed steps and steps with a diff expand their details by default (the diff is what the user wants to see)
|
||||
const detail = s.detail as { hunks?: unknown[] } | undefined;
|
||||
const [open, setOpen] = useState(s.status === "failed" || (Array.isArray(detail?.hunks) && detail.hunks.length > 0));
|
||||
const icon = s.status === "running" ? "…" : s.status === "ok" ? "✓" : "✗";
|
||||
const cls = s.status === "running" ? "run" : s.status === "ok" ? "ok" : "fail";
|
||||
const hasDetail = s.output || s.detail;
|
||||
/** One line, never wrapping: "正在运行:npm test…" (the ellipsis is the CSS one when it doesn't fit) */
|
||||
function RunningRow({ s }: { s: ToolStep }) {
|
||||
const cat = stepCategory(s.kind);
|
||||
const text = cat === "think" ? t("timeline.nowThinking") : tf(`timeline.now.${cat}`, { x: stepTarget(s) });
|
||||
return (
|
||||
<div className="ts">
|
||||
<button className="ts-head" onClick={() => hasDetail && setOpen(!open)}>
|
||||
<span className={`ts-ic ${cls}`}>{icon}</span>
|
||||
<span className="ts-title">{s.title || toolKind(s.kind)}</span>
|
||||
{s.durationMs != null && <span className="ts-meta">{fmtDur(s.durationMs)}</span>}
|
||||
<div className="tg-run" title={text}>
|
||||
<span className="spin" aria-hidden />
|
||||
<span className="tg-run-text">{text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Short thinking between tool calls: a quiet "思考 Xs" row that opens to its text */
|
||||
function ThinkStepRow({ s }: { s: ToolStep }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const text = s.think?.text ?? "";
|
||||
const secs = Math.max(1, Math.round(text.length / 40));
|
||||
const live = !!s.think?.streaming;
|
||||
return (
|
||||
<div className="ts ts-think">
|
||||
<button className="ts-head" aria-expanded={open} onClick={() => text.trim() && setOpen(!open)}>
|
||||
<span className="ts-ic" aria-hidden><Icon name="spark" size={13} /></span>
|
||||
<span className="ts-title">{live ? t("timeline.nowThinking") : tf("timeline.thinking", { s: secs })}</span>
|
||||
{live && <span className="ts-st" aria-hidden><span className="spin" /></span>}
|
||||
</button>
|
||||
{open && <div className="rs-body">{text}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusMark({ status }: { status: ToolStep["status"] }) {
|
||||
if (status === "running") return <span className="ts-st run" aria-label="running"><span className="spin" /></span>;
|
||||
if (status === "failed") return <span className="ts-st fail" aria-label="failed"><Icon name="x" size={12} /></span>;
|
||||
return <span className="ts-st ok" aria-label="ok"><Icon name="check" size={12} /></span>;
|
||||
}
|
||||
|
||||
function ToolStepRow({ s }: { s: ToolStep }) {
|
||||
// A failed step opens its error output (the error is the point); everything else opens on click
|
||||
const [open, setOpen] = useState(s.status === "failed");
|
||||
const failed = s.status === "failed";
|
||||
const wasFailed = useRef(failed);
|
||||
useEffect(() => {
|
||||
if (failed && !wasFailed.current) setOpen(true);
|
||||
wasFailed.current = failed;
|
||||
}, [failed]);
|
||||
const root = useProjectRoot();
|
||||
const hasDetail = !!(s.output || s.detail || s.input != null || failed);
|
||||
const target = relToRoot(stepTarget(s), root) || toolKind(s.kind);
|
||||
const diff = s.kind === "edit" || s.kind === "write" ? stepDiffStat(s) : null;
|
||||
const mono = MONO_KINDS.has(s.kind) && target !== s.title;
|
||||
const tip = `${toolKind(s.kind)} · ${s.title || target}${s.durationMs != null ? ` · ${fmtDur(s.durationMs)}` : ""}`;
|
||||
return (
|
||||
<div className={`ts${failed ? " failed" : ""}${open ? " open" : ""}`} data-kind={s.kind}>
|
||||
<button className="ts-head" title={tip} aria-expanded={hasDetail ? open : undefined} onClick={() => hasDetail && setOpen(!open)}>
|
||||
<span className="ts-ic" aria-hidden><Icon name={KIND_ICON[s.kind] ?? "wrench"} size={13} /></span>
|
||||
<span className={`ts-title${mono ? " mono" : ""}`}>{target}</span>
|
||||
{diff && (diff.added > 0 || diff.removed > 0) && (
|
||||
<span className="ts-diff"><span className="add">+{diff.added}</span><span className="del">-{diff.removed}</span></span>
|
||||
)}
|
||||
{s.exitCode != null && s.exitCode !== 0 && <span className="ts-meta err">exit {s.exitCode}</span>}
|
||||
<StatusMark status={s.status} />
|
||||
</button>
|
||||
{open && <ToolDetail s={s} />}
|
||||
</div>
|
||||
@@ -180,6 +315,14 @@ function ToolDetail({ s }: { s: ToolStep }) {
|
||||
if (rawHunks) {
|
||||
return <DiffView hunks={normalizeHunks(rawHunks)} path={detail?.diff?.path ?? detail?.path} />;
|
||||
}
|
||||
if (s.status === "failed" && !s.output?.trim()) {
|
||||
return (
|
||||
<div className="ts-out">
|
||||
<div className="ts-noerr">{t("timeline.noErrorOutput")}</div>
|
||||
{s.input != null && <pre>{JSON.stringify(s.input, null, 2).slice(0, 4000)}</pre>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (s.output != null) {
|
||||
const lines = s.output.split("\n");
|
||||
const tail = lines.length > 50 && !full;
|
||||
@@ -232,24 +375,26 @@ export function PlanItem({ it }: { it: Extract<DisplayItem, { kind: "plan" }> })
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- todo ----------
|
||||
// ---------- checklist (todo / plan entries) ----------
|
||||
export function TodoItem({ it }: { it: Extract<DisplayItem, { kind: "todo" }> }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const done = it.items.filter((i) => i.status === "done" || i.status === "completed").length;
|
||||
// 1.3: the Agent's step list inline, like Better Paseo: "2/3" and one check row per step (the newest list of a turn only)
|
||||
const { done, total } = todoProgress(it.items);
|
||||
return (
|
||||
<div className="rs-item">
|
||||
<button className="rs-head" onClick={() => setOpen(!open)}>
|
||||
<span className={`caret${open ? " open" : ""}`}>›</span> {tf("timeline.todo", { done, total: it.items.length })}
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="todo-list">
|
||||
{it.items.map((i, n) => (
|
||||
<li key={n} className={`todo ${i.status}`}>
|
||||
{i.status === "done" || i.status === "completed" ? "☑" : i.status === "in_progress" ? "◐" : "☐"} {i.text}
|
||||
<div className="ck" data-todo-key={it.key}>
|
||||
<div className="ck-head"><Icon name="listChecks" size={13} /><span className="ck-n">{done}/{total}</span><span className="ck-l">{t("timeline.tasks")}</span></div>
|
||||
<ul className="ck-list">
|
||||
{it.items.map((i, n) => {
|
||||
const st = i.status === "done" || i.status === "completed" ? "done" : i.status === "in_progress" ? "doing" : "todo";
|
||||
return (
|
||||
<li key={n} className={`ck-i ${st}`}>
|
||||
<span className="ck-box" aria-hidden>
|
||||
{st === "done" ? <Icon name="check" size={12} /> : st === "doing" ? <span className="spin" /> : <Icon name="circle" size={12} />}
|
||||
</span>
|
||||
<span className="ck-t">{i.text}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -338,6 +483,8 @@ export function QuestionItem({ it, threadId }: { it: Extract<DisplayItem, { kind
|
||||
export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayItem, { kind: "turnend" }>; onRetry?: () => void; replyText?: string }) {
|
||||
const ui = useUi();
|
||||
const [showErr, setShowErr] = useState(false);
|
||||
const [copied, copy] = useCopied();
|
||||
const model = useModelName(it.model, it.model !== undefined);
|
||||
if (it.status === "failed") {
|
||||
return (
|
||||
<div className="card err-card">
|
||||
@@ -352,25 +499,29 @@ export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayIte
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (it.durationMs != null) parts.push(fmtDur(it.durationMs));
|
||||
const usage: string[] = [];
|
||||
if (it.usage) {
|
||||
const tk = it.usage.inputTokens + it.usage.outputTokens;
|
||||
if (tk) parts.push(`${fmtTokens(tk)} tokens`);
|
||||
if (it.usage.costUsd) parts.push(fmtCost(it.usage.costUsd));
|
||||
if (tk) usage.push(`${fmtTokens(tk)} tokens`);
|
||||
if (it.usage.costUsd) usage.push(fmtCost(it.usage.costUsd));
|
||||
}
|
||||
if (it.status === "interrupted") parts.push(t("timeline.interrupted"));
|
||||
return (
|
||||
<div className="te">
|
||||
{parts.length > 0 && <span className="te-meta">{parts.join(" · ")}</span>}
|
||||
{/* 1.3 reply footer: Copy · model · time · duration (· tokens · cost), only what the turn reported */}
|
||||
{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 type="button" className={`te-act te-copy${copied ? " done" : ""}`} title={copied ? t("common.copied") : t("common.copy")}
|
||||
aria-label={copied ? t("common.copied") : t("common.copy")} onClick={() => copy(replyText)}>
|
||||
<Icon name={copied ? "check" : "copy"} size={13} /><span>{copied ? t("common.copied") : t("common.copy")}</span>
|
||||
</button>
|
||||
)}
|
||||
{model && <span className="te-m" title={model}><Icon name="cpu" size={12} /><span>{model}</span></span>}
|
||||
{it.ts != null && <span className="te-m" title={new Date(it.ts).toLocaleString()}><Icon name="clock" size={12} /><span>{fmtClock(it.ts)}</span></span>}
|
||||
{it.durationMs != null && <span className="te-m"><Icon name="hourglass" size={12} /><span>{fmtDur(it.durationMs)}</span></span>}
|
||||
{usage.length > 0 && <span className="te-m te-u">{usage.join(" · ")}</span>}
|
||||
{it.status === "interrupted" && <span className="te-m">{t("timeline.interrupted")}</span>}
|
||||
{onRetry && (
|
||||
<button className="te-act" title={t("common.retry")} onClick={onRetry}>
|
||||
<Icon name="refresh" size={13} /><span>{t("common.retry")}</span>
|
||||
<button type="button" className="te-act" title={t("timeline.retryHint")} aria-label={t("timeline.retryHint")} onClick={onRetry}>
|
||||
<Icon name="refresh" size={13} />
|
||||
</button>
|
||||
)}
|
||||
{it.filesChanged != null && it.filesChanged > 0 && (
|
||||
@@ -382,6 +533,26 @@ export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayIte
|
||||
);
|
||||
}
|
||||
|
||||
/** 19:13 today, "11/3 19:13" on another day (the user's locale) */
|
||||
function fmtClock(ts: number): string {
|
||||
const d = new Date(ts);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
return d.toDateString() === new Date().toDateString() ? hm : `${d.getMonth() + 1}/${d.getDate()} ${hm}`;
|
||||
}
|
||||
|
||||
/** The model a turn ran on, by its display name; a turn on the Agent's default shows the default's name when known */
|
||||
function useModelName(id: string | null | undefined, known: boolean): string | null {
|
||||
const threadId = useUi((s) => s.currentThreadId);
|
||||
const threads = useData((s) => s.threads);
|
||||
const providers = useData((s) => s.providers);
|
||||
if (!known) return null;
|
||||
const th = threads.find((x) => x.id === threadId);
|
||||
const models = providers.find((p) => p.id === th?.provider)?.models ?? [];
|
||||
if (id) return models.find((m) => m.id === id)?.name ?? id;
|
||||
return models.find((m) => m.isDefault)?.name ?? null;
|
||||
}
|
||||
|
||||
// ---------- dispatch ----------
|
||||
export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText }: {
|
||||
it: DisplayItem; threadId: string; replyText?: string;
|
||||
@@ -397,7 +568,9 @@ export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText
|
||||
case "todo": return <TodoItem it={it} />;
|
||||
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 "notice":
|
||||
if (it.code === "bash_missing") return <BashMissingNotice it={it} />;
|
||||
return <div className={`nt ${it.level}`}>{localizeDaemonMessage(it.message)}</div>;
|
||||
case "turnend": return <TurnEndItem it={it} onRetry={onRetryLast} replyText={replyText} />;
|
||||
case "gone": return null;
|
||||
default: return null;
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// 1.3 "添加到对话": quote normalising, the chip list, the text sent to the Agent, the bubble split and the popup position.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { quotesFromText, addQuote, normalizeQuote, quotesToText, splitQuotes, quoteLabel, placeQuotePop, MAX_QUOTES, MAX_QUOTE_CHARS, type Quote } from "./quotes.js";
|
||||
|
||||
describe("normalizeQuote", () => {
|
||||
it("drops CR, nbsp, trailing blanks and runs of empty lines", () => {
|
||||
expect(normalizeQuote("\n\na \r\n\r\n\r\n\r\nb\u00a0c\t\n\n")).toBe("a\n\nb c");
|
||||
});
|
||||
it("keeps leading indentation (code)", () => {
|
||||
expect(normalizeQuote(" if (x) {\n y();\n }")).toBe(" if (x) {\n y();\n }");
|
||||
});
|
||||
it("caps very long selections", () => {
|
||||
const s = normalizeQuote("x".repeat(MAX_QUOTE_CHARS + 50));
|
||||
expect(s.length).toBe(MAX_QUOTE_CHARS + 1);
|
||||
expect(s.endsWith("…")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addQuote", () => {
|
||||
it("adds, dedupes by text and source, ignores blanks, caps the list", () => {
|
||||
let l: Quote[] = [];
|
||||
l = addQuote(l, "hello");
|
||||
l = addQuote(l, "hello ");
|
||||
expect(l).toHaveLength(1);
|
||||
l = addQuote(l, "hello", "src/a.ts");
|
||||
expect(l).toHaveLength(2);
|
||||
const same = addQuote(l, " \n ");
|
||||
expect(same).toBe(l);
|
||||
for (let i = 0; i < 20; i++) l = addQuote(l, `q${i}`);
|
||||
expect(l).toHaveLength(MAX_QUOTES);
|
||||
expect(new Set(l.map((q) => q.id)).size).toBe(MAX_QUOTES);
|
||||
});
|
||||
});
|
||||
|
||||
describe("quotesToText / splitQuotes", () => {
|
||||
const qs: Quote[] = [
|
||||
{ id: "1", text: "第一段\n\n第二段" },
|
||||
{ id: "2", text: "const x = 1;", src: "src/index.ts" },
|
||||
];
|
||||
it("sends each quote as a > block, the source first, then the message", () => {
|
||||
expect(quotesToText(qs, "这是什么?")).toBe("> 第一段\n>\n> 第二段\n\n> [src/index.ts]\n> const x = 1;\n\n这是什么?");
|
||||
});
|
||||
it("quotes only (no typed text) and no quotes", () => {
|
||||
expect(quotesToText(qs.slice(0, 1), " ")).toBe("> 第一段\n>\n> 第二段");
|
||||
expect(quotesToText([], "hi")).toBe("hi");
|
||||
});
|
||||
it("round-trips for the bubble", () => {
|
||||
const sp = splitQuotes(quotesToText(qs, "这是什么?\n\n第二行"));
|
||||
expect(sp.quotes).toEqual(["第一段\n\n第二段", "[src/index.ts]\nconst x = 1;"]);
|
||||
expect(sp.rest).toBe("这是什么?\n\n第二行");
|
||||
});
|
||||
it("a message that is only a quote, or a > later on, stays plain text", () => {
|
||||
expect(splitQuotes("> just a quote")).toEqual({ quotes: [], rest: "> just a quote" });
|
||||
expect(splitQuotes("hi\n\n> not leading")).toEqual({ quotes: [], rest: "hi\n\n> not leading" });
|
||||
expect(splitQuotes(">no space\n\nhi").quotes).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteLabel", () => {
|
||||
it("first non-empty line, shortened", () => {
|
||||
expect(quoteLabel({ id: "a", text: "\n hello world \nnext" })).toBe("hello world");
|
||||
expect(quoteLabel({ id: "a", text: "x".repeat(40) }, 10)).toBe("xxxxxxxxx…");
|
||||
});
|
||||
});
|
||||
|
||||
describe("placeQuotePop", () => {
|
||||
const area = { left: 0, right: 600, top: 50, bottom: 700 };
|
||||
const pop = { w: 110, h: 30 };
|
||||
it("above the selection, at its first line", () => {
|
||||
const p = placeQuotePop([{ left: 100, right: 400, top: 300, bottom: 320 }, { left: 20, right: 200, top: 320, bottom: 340 }], area, pop, 600);
|
||||
expect(p).toEqual({ left: 100, top: 300 - 6 - 30, side: "above" });
|
||||
});
|
||||
it("below when there is no room above; never over the selection", () => {
|
||||
const p = placeQuotePop([{ left: 100, right: 400, top: 60, bottom: 80 }], area, pop, 600)!;
|
||||
expect(p.side).toBe("below");
|
||||
expect(p.top).toBeGreaterThanOrEqual(80);
|
||||
});
|
||||
it("inside the visible area (above the composer) when the selection fills it", () => {
|
||||
const p = placeQuotePop([{ left: 10, right: 590, top: 40, bottom: 710 }], area, pop, 600)!;
|
||||
expect(p.side).toBe("inside");
|
||||
expect(p.top + pop.h).toBeLessThanOrEqual(area.bottom);
|
||||
});
|
||||
it("clamped inside a narrow window", () => {
|
||||
const p = placeQuotePop([{ left: 560, right: 598, top: 300, bottom: 320 }], area, pop, 600)!;
|
||||
expect(p.left + pop.w).toBeLessThanOrEqual(600 - 8);
|
||||
const q = placeQuotePop([{ left: -20, right: 50, top: 300, bottom: 320 }], area, pop, 600)!;
|
||||
expect(q.left).toBeGreaterThanOrEqual(8);
|
||||
});
|
||||
it("nothing when the selection is scrolled out of view", () => {
|
||||
expect(placeQuotePop([{ left: 10, right: 50, top: 0, bottom: 20 }], area, pop, 600)).toBeNull();
|
||||
expect(placeQuotePop([], area, pop, 600)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("quotesFromText (编辑 on a sent message)", () => {
|
||||
it("gives the chips back, with their source", () => {
|
||||
const qs: Quote[] = [{ id: "1", text: "a\n\nb" }, { id: "2", text: "x = 1", src: "src/a.ts" }];
|
||||
const back = quotesFromText(quotesToText(qs, "问题"));
|
||||
expect(back.rest).toBe("问题");
|
||||
expect(back.quotes.map((q) => [q.text, q.src])).toEqual([["a\n\nb", undefined], ["x = 1", "src/a.ts"]]);
|
||||
});
|
||||
it("plain messages come back unchanged", () => {
|
||||
expect(quotesFromText("> hi")).toEqual({ quotes: [], rest: "> hi" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
// 1.3 "添加到对话": text selected in the conversation or the right panel becomes a quote chip in the composer.
|
||||
// The quotes go out in front of the message as Markdown block quotes (what every Agent reads as "the user is
|
||||
// pointing at this"); the composer's own text stays plain and editable.
|
||||
export type Quote = { id: string; text: string; src?: string };
|
||||
|
||||
export const MAX_QUOTES = 10;
|
||||
export const MAX_QUOTE_CHARS = 4000;
|
||||
|
||||
/** Selected text as it should be quoted: no trailing blanks per line, at most one empty line in a row, capped */
|
||||
export function normalizeQuote(raw: string): string {
|
||||
let s = raw.replace(/\r\n?/g, "\n").replace(/\u00a0/g, " ");
|
||||
s = s.split("\n").map((l) => l.replace(/\s+$/u, "")).join("\n");
|
||||
s = s.replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "");
|
||||
if (s.length > MAX_QUOTE_CHARS) s = s.slice(0, MAX_QUOTE_CHARS).replace(/\s+$/u, "") + "…";
|
||||
return s;
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
/** Adds a quote; the same text from the same place is not added twice; the list is capped. Returns the same list when nothing changed. */
|
||||
export function addQuote(list: Quote[], text: string, src?: string): Quote[] {
|
||||
const t = normalizeQuote(text);
|
||||
if (!t.trim()) return list;
|
||||
if (list.some((q) => q.text === t && q.src === src)) return list;
|
||||
if (list.length >= MAX_QUOTES) return list;
|
||||
return [...list, { id: `q${Date.now().toString(36)}${(seq++).toString(36)}`, text: t, src }];
|
||||
}
|
||||
|
||||
/** The text sent to the Agent: each quote as a "> " block (its source path first when it has one), then the message */
|
||||
export function quotesToText(quotes: Quote[], msg: string): string {
|
||||
if (!quotes.length) return msg;
|
||||
const blocks = quotes.map((q) => {
|
||||
const lines = q.text.split("\n").map((l) => (l ? `> ${l}` : ">"));
|
||||
return (q.src ? [`> [${q.src}]`, ...lines] : lines).join("\n");
|
||||
});
|
||||
return [...blocks, msg].filter((x) => x.trim()).join("\n\n");
|
||||
}
|
||||
|
||||
/** Chip text: the first line, shortened */
|
||||
export function quoteLabel(q: Quote, max = 28): string {
|
||||
const first = q.text.split("\n").find((l) => l.trim()) ?? "";
|
||||
const one = first.trim().replace(/\s+/g, " ");
|
||||
return one.length > max ? one.slice(0, max - 1) + "…" : one;
|
||||
}
|
||||
|
||||
export type Box = { left: number; top: number; right: number; bottom: number };
|
||||
|
||||
/**
|
||||
* Where the "添加到对话" button goes: above the selection when there is room in the visible area, else below it,
|
||||
* else (the selection fills the view) at the bottom of the visible area; never outside the window horizontally.
|
||||
* sel = the selection's line boxes (client coordinates), area = the part of the scroller that is visible
|
||||
* (for the chat: above the composer), pop = the button's size.
|
||||
*/
|
||||
export function placeQuotePop(sel: Box[], area: Box, pop: { w: number; h: number }, vw: number, gap = 6): { left: number; top: number; side: "above" | "below" | "inside" } | null {
|
||||
const lines = sel.filter((r) => r.bottom > area.top && r.top < area.bottom && r.right > r.left);
|
||||
if (!lines.length) return null;
|
||||
const top = Math.min(...lines.map((r) => r.top));
|
||||
const bottom = Math.max(...lines.map((r) => r.bottom));
|
||||
const first = lines.reduce((a, b) => (b.top < a.top ? b : a));
|
||||
const last = lines.reduce((a, b) => (b.bottom > a.bottom || (b.bottom === a.bottom && b.right > a.right) ? b : a));
|
||||
const clampX = (x: number) => Math.max(8, Math.min(x, vw - pop.w - 8));
|
||||
if (top - gap - pop.h >= area.top) return { left: clampX(first.left), top: top - gap - pop.h, side: "above" };
|
||||
if (bottom + gap + pop.h <= area.bottom) return { left: clampX(last.right - pop.w), top: bottom + gap, side: "below" };
|
||||
return { left: clampX(last.right - pop.w), top: Math.max(area.top, area.bottom - pop.h - gap), side: "inside" };
|
||||
}
|
||||
|
||||
/** The reverse for display: leading "> " blocks of a sent message (the quotes) and the rest */
|
||||
export function splitQuotes(text: string): { quotes: string[]; rest: string } {
|
||||
const blocks = text.split(/\n{2,}/);
|
||||
const quotes: string[] = [];
|
||||
let i = 0;
|
||||
for (; i < blocks.length; i++) {
|
||||
const lines = blocks[i]!.split("\n");
|
||||
if (!lines.every((l) => l === ">" || l.startsWith("> "))) break;
|
||||
quotes.push(lines.map((l) => (l === ">" ? "" : l.slice(2))).join("\n"));
|
||||
}
|
||||
// A message that is nothing but a quote keeps it as text (the user typed "> …" on purpose)
|
||||
if (i === blocks.length) return { quotes: [], rest: text };
|
||||
return { quotes, rest: blocks.slice(i).join("\n\n") };
|
||||
}
|
||||
|
||||
/** "编辑" on a sent message: its leading quotes back as chips (the "[path]" line back as the source), the rest as text */
|
||||
export function quotesFromText(text: string): { quotes: Quote[]; rest: string } {
|
||||
const sp = splitQuotes(text);
|
||||
let quotes: Quote[] = [];
|
||||
for (const q of sp.quotes) {
|
||||
const m = /^\[([^\]\n]+)\]\n([\s\S]*)$/.exec(q);
|
||||
quotes = m ? addQuote(quotes, m[2]!, m[1]) : addQuote(quotes, q);
|
||||
}
|
||||
return { quotes, rest: sp.rest };
|
||||
}
|
||||
@@ -61,7 +61,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
queuePlaceholderNoSteer: "继续补充要求,回车排队发送…",
|
||||
steerUnsupported: "{agent} 不支持插话:运行中发的消息会排队,本回合结束后再发送。",
|
||||
queuedToast: "已排队:本回合结束后发送", steeredToast: "已插话",
|
||||
inputPlaceholder: "输入消息…", bypassWarn: "Bypass:Agent 的所有操作不会再问你。",
|
||||
inputPlaceholder: "输入消息,/ 使用命令…", bypassWarn: "Bypass:Agent 的所有操作不会再问你。",
|
||||
imagesByPath: "{agent} 不能直接看图片:会把图片的文件路径发给它(它能用文件工具打开)。",
|
||||
agentModel: "Agent & model", agentLocked: "Agent (locked)", agent: "Agent",
|
||||
model: "Model", searchModel: "Search", searchAllModels: "Search models…", providers: "Agent",
|
||||
@@ -96,6 +96,13 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
settings: {
|
||||
contentWidth: "内容宽度", widthNarrow: "窄(640)", widthDefault: "默认(720)", widthWide: "宽(880)", widthFull: "铺满",
|
||||
bashPath: "Bash 路径(Windows)", bashCheck: "检测", bashOk: "可用:{path}",
|
||||
bashUsing: "当前使用:{path}({src})", bashNone: "没有找到 Git Bash。",
|
||||
bashManualBad: "手动路径不可用({why}),已改用自动检测",
|
||||
bashHint: "Claude Code、Pi、dsh 在 Windows 上用 Git Bash 执行命令。留空就自动检测(git.exe 旁边、Program Files、各盘的 \\Git);装在别处时填 bash.exe 的完整路径。",
|
||||
bashNotWindows: "只在 Windows 上需要。macOS 和 Linux 直接用系统自带的 bash。",
|
||||
bashSrc: { manual: "手动设置", env: "环境变量", git: "git.exe 旁边", known: "默认安装位置", drive: "其他盘", path: "PATH" },
|
||||
bashBad: { empty: "路径为空", relative: "要填完整路径,比如 E:\\Git\\bin\\bash.exe", notBash: "要指向 bash.exe(或 sh.exe)", wsl: "这是 WSL 的 bash,不能用", missing: "文件不存在" },
|
||||
chatFont: "聊天字号", chatFontDefault: "(默认)", chatFontHint: "对话正文、输入框、工具输出和代码一起缩放(代码小 1px)",
|
||||
title: "设置", defaultAgent: "默认 Agent", defaultMode: "默认权限模式", theme: "主题",
|
||||
themeAuto: "跟随系统", themeMagpie: "跟随 Magpie", themeLight: "浅色", themeDark: "深色",
|
||||
@@ -146,15 +153,20 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
sessionNone: "(未建立)", tokensFmt: "{in} 入 / {out} 出 / {cache} 缓存",
|
||||
},
|
||||
timeline: {
|
||||
thinking: "思考 {s}s", todo: "待办 {done}/{total}", steer: "插话",
|
||||
thinking: "思考 {s}s", todo: "待办 {done}/{total}", steer: "插话", tasks: "任务", tasksPill: "{done}/{total} 个任务", tasksPillTitle: "查看任务清单",
|
||||
codeWrap: "自动换行",
|
||||
permAllowSession: "本对话都允许", permDenied: "已拒绝", permAllowed: "已允许", permCancelled: "已取消",
|
||||
submitted: "已提交:{ans}", turnError: "出错:{err}", unknownError: "未知错误",
|
||||
interrupted: "已打断", filesChanged: "改动 {n} 个文件 ›", editResend: "编辑后重发",
|
||||
interrupted: "已打断", filesChanged: "改动 {n} 个文件 ›", editMsg: "编辑(填回输入框,不会马上发送)", sendFailed: "发送失败", sendRetry: "重新发送", sendDismiss: "移除这条没发出的消息", resend: "重新发送这条消息", retryHint: "重试:重新发送上一条消息", msgActions: "消息操作", editBusy: "输入框里还有没发送的内容:先发送或清空,再点编辑",
|
||||
tool: {
|
||||
read: "读取", edit: "修改", write: "写入", bash: "运行", search: "搜索", glob: "搜索",
|
||||
web: "联网", task: "子任务", mcp: "工具", todo: "待办", other: "工具", processing: "处理",
|
||||
},
|
||||
toolSummary: "已执行 {n} 步 · {parts}", toolSummaryOne: "已执行 1 步 · {parts}", toolRunning: "正在{kind}:{title}",
|
||||
cat: { edit: "改动 {n}", run: "运行 {n}", read: "读取 {n}", search: "搜索 {n}", other: "其他 {n}" },
|
||||
failedCount: "{n} 失败", noErrorOutput: "没有错误输出", nowThinking: "正在思考…",
|
||||
now: { edit: "正在改动:{x}…", run: "正在运行:{x}…", read: "正在读取:{x}…", search: "正在搜索:{x}…", other: "正在执行:{x}…" },
|
||||
bashMissing: "没有找到 Git Bash。Claude Code、Pi 等 Agent 在 Windows 上要用它执行命令。(C:\\Windows\\System32\\bash.exe 是 WSL 启动器,不能用。)装好 Git for Windows 后重新发送;装在别处可以在「设置 → Bash 路径」里指定 bash.exe。",
|
||||
bashDownload: "下载 Git for Windows", bashSetting: "打开设置",
|
||||
showAllLines: "显示全部 {n} 行", diffClip: "(只显示前 {n} 行)",
|
||||
},
|
||||
api: {
|
||||
@@ -174,6 +186,10 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
openPreviewTitle: "在预览中打开(Ctrl/⌘+点击用浏览器打开)",
|
||||
externalFailed: "打不开系统浏览器,已复制链接",
|
||||
},
|
||||
quote: {
|
||||
add: "添加到对话", addHint: "把选中的文字作为引用放进输入框(不会马上发送)",
|
||||
chipTitle: "引用的文字(发送时以引用的形式放在你的消息前面)", remove: "移除引用", full: "最多 {n} 条引用", lines: "{n} 行",
|
||||
},
|
||||
mention: {
|
||||
drop: "松开以插入到聊天", add: "插入到聊天", copyRel: "复制相对路径", remove: "移除",
|
||||
otherProject: "只能插入当前对话所在项目里的文件",
|
||||
@@ -240,7 +256,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
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.",
|
||||
inputPlaceholder: "Message the agent, / for commands…", 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",
|
||||
model: "Model", searchModel: "Search", searchAllModels: "Search all models…", providers: "Providers",
|
||||
@@ -270,6 +286,13 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
},
|
||||
settings: {
|
||||
contentWidth: "Content width", widthNarrow: "Narrow (640)", widthDefault: "Default (720)", widthWide: "Wide (880)", widthFull: "Full",
|
||||
bashPath: "Bash path (Windows)", bashCheck: "Check", bashOk: "Works: {path}",
|
||||
bashUsing: "In use: {path} ({src})", bashNone: "Git Bash was not found.",
|
||||
bashManualBad: "The manual path can't be used ({why}); using auto-detection",
|
||||
bashHint: "Claude Code, Pi and dsh run commands with Git Bash on Windows. Leave empty to auto-detect (next to git.exe, Program Files, \\Git on each drive); fill in the full bash.exe path if it lives elsewhere.",
|
||||
bashNotWindows: "Only needed on Windows. macOS and Linux use the system bash.",
|
||||
bashSrc: { manual: "set manually", env: "environment variable", git: "next to git.exe", known: "default install folder", drive: "another drive", path: "PATH" },
|
||||
bashBad: { empty: "The path is empty", relative: "Use a full path, e.g. E:\\Git\\bin\\bash.exe", notBash: "It must point to bash.exe (or sh.exe)", wsl: "That is the WSL bash, which won't work", missing: "File not found" },
|
||||
chatFont: "Chat font size", chatFontDefault: " (default)", chatFontHint: "Scales the conversation, the input, tool output and code (code 1px smaller)",
|
||||
title: "Settings", defaultAgent: "Default agent", defaultMode: "Default permission mode", theme: "Theme",
|
||||
themeAuto: "System", themeMagpie: "Follow Magpie", themeLight: "Light", themeDark: "Dark",
|
||||
@@ -321,15 +344,20 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
sessionNone: "(none)", tokensFmt: "{in} in / {out} out / {cache} cache",
|
||||
},
|
||||
timeline: {
|
||||
thinking: "Thinking {s}s", todo: "Todos {done}/{total}", steer: "Steer",
|
||||
thinking: "Thinking {s}s", todo: "Todos {done}/{total}", steer: "Steer", tasks: "tasks", tasksPill: "{done}/{total} tasks", tasksPillTitle: "Show the task list",
|
||||
codeWrap: "Wrap lines",
|
||||
permAllowSession: "Allowed for this chat", permDenied: "Denied", permAllowed: "Allowed", permCancelled: "Cancelled",
|
||||
submitted: "Submitted: {ans}", turnError: "Error: {err}", unknownError: "Unknown error",
|
||||
interrupted: "Interrupted", filesChanged: "{n} file(s) changed ›", editResend: "Edit and resend",
|
||||
interrupted: "Interrupted", filesChanged: "{n} file(s) changed ›", editMsg: "Edit (puts it back in the input; nothing is sent yet)", sendFailed: "Not sent", sendRetry: "Send again", sendDismiss: "Remove this unsent message", resend: "Send this message again", retryHint: "Retry: send the last message again", msgActions: "Message actions", editBusy: "The input still has unsent text: send or clear it first, then click Edit",
|
||||
tool: {
|
||||
read: "Read", edit: "Edit", write: "Write", bash: "Run", search: "Search", glob: "Search",
|
||||
web: "Web", task: "Subtask", mcp: "Tool", todo: "Todo", other: "Tool", processing: "Working",
|
||||
},
|
||||
toolSummary: "{n} steps · {parts}", toolSummaryOne: "1 step · {parts}", toolRunning: "{kind}: {title}",
|
||||
cat: { edit: "Edited {n}", run: "Ran {n}", read: "Read {n}", search: "Searched {n}", other: "Other {n}" },
|
||||
failedCount: "{n} failed", noErrorOutput: "No error output", nowThinking: "Thinking…",
|
||||
now: { edit: "Editing: {x}…", run: "Running: {x}…", read: "Reading: {x}…", search: "Searching: {x}…", other: "Working: {x}…" },
|
||||
bashMissing: "Git Bash was not found. Claude Code, Pi and similar agents need it to run commands on Windows. (C:\\Windows\\System32\\bash.exe is the WSL launcher and won't work.) Install Git for Windows and send again; if it is installed elsewhere, set bash.exe under Settings → Bash path.",
|
||||
bashDownload: "Download Git for Windows", bashSetting: "Open Settings",
|
||||
showAllLines: "Show all {n} lines", diffClip: "(first {n} lines only)",
|
||||
},
|
||||
api: {
|
||||
@@ -349,6 +377,10 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
openPreviewTitle: "Open in Preview (Ctrl/⌘+click opens the browser)",
|
||||
externalFailed: "Couldn't open the browser; the link was copied",
|
||||
},
|
||||
quote: {
|
||||
add: "Add to chat", addHint: "Quote the selected text in the input (nothing is sent yet)",
|
||||
chipTitle: "Quoted text (sent in front of your message as a quote)", remove: "Remove quote", full: "{n} quotes at most", lines: "{n} lines",
|
||||
},
|
||||
mention: {
|
||||
drop: "Drop to add to the chat", add: "Add to chat", copyRel: "Copy relative path", remove: "Remove",
|
||||
otherProject: "Only files of this conversation's project can be added",
|
||||
|
||||
@@ -10,7 +10,7 @@ import { applyMagpieTokensFromSearch } from "./layout/applyMagpieTokens.js";
|
||||
import { applyTheme, initTheme } from "./layout/theme.js";
|
||||
import { startMagpieThemeBridge } from "./layout/magpieBridge.js";
|
||||
import { applyChatLayout } from "./layout/chatLayout.js";
|
||||
import { goBackToMagpie, watchReconnect } from "./api/backToMagpie.js";
|
||||
import { goBackToMagpie, isWrapped, reportLostToWrapper, startWrapperHeartbeat, watchReconnect } from "./api/backToMagpie.js";
|
||||
import { initLocale, getLocale, setLocale } from "./i18n/index.js";
|
||||
import { WsClient } from "./api/ws";
|
||||
import { useConnection } from "./stores/connection";
|
||||
@@ -43,8 +43,15 @@ 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(); });
|
||||
// Daemon gone for 5s (Magpie restarted the plugin host, or the daemon after sleep) → back through the Magpie page to the gate.
|
||||
// 1.3: inside the gate's wrapper page the wrapper does that (it survives a reload; this page on its random port doesn't).
|
||||
const wrapped = isWrapped();
|
||||
watchReconnect(ws, () => { if (wrapped) reportLostToWrapper(); else goBackToMagpie(); });
|
||||
if (wrapped) {
|
||||
startWrapperHeartbeat(ws);
|
||||
// the first beat as soon as the connection opens, so the wrapper shows this page without waiting for the next tick
|
||||
ws.onState((s) => { if (s === "open") { try { window.parent.postMessage({ ac_console: "alive" }, "*"); } catch {} } });
|
||||
}
|
||||
ws.connect();
|
||||
ws.waitHello().then(async (h) => {
|
||||
useConnection.getState().set({ version: (h as { version?: string }).version ?? null });
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { TimelineEvent } from "../timeline/types";
|
||||
import { applyEvent, newTimelineState, reduceTimeline, type DisplayItem } from "../timeline/reducer";
|
||||
import { ws } from "../main";
|
||||
import type { SlashCommand } from "../composer/slashMenu";
|
||||
import { Outbox, newClientId, withOutbox, type SendDisplay, type SendPayload } from "../timeline/outbox";
|
||||
|
||||
export type QueueItem = { id: string; text: string; attachments?: { path: string; mime: string }[] };
|
||||
export type PendingReq = { requestId: string; kind: "permission" | "question" };
|
||||
@@ -18,10 +19,26 @@ type TlStore = {
|
||||
error: string | null;
|
||||
slashCommands: SlashCommand[];
|
||||
|
||||
/** 1.3: bumped on every optimistic send (the chat jumps to the bottom) */
|
||||
sentAt: number;
|
||||
|
||||
open(threadId: string): void;
|
||||
close(): void;
|
||||
/** 1.3 optimistic send: the bubble shows now, the echo replaces it, a failure marks it (see timeline/outbox.ts).
|
||||
* optimistic=false (queued behind a running turn): nothing is drawn, the queue list shows it. Throws on failure. */
|
||||
send(threadId: string, payload: SendPayload, display?: SendDisplay, opts?: { optimistic?: boolean }): Promise<{ delivered?: "started" | "steered" | "queued" } | undefined>;
|
||||
/** Send a failed bubble again (same text, attachments and chips) */
|
||||
retry(clientId: string): void;
|
||||
/** Drop a failed bubble */
|
||||
dismiss(clientId: string): void;
|
||||
};
|
||||
|
||||
/** Sends waiting for their echo, per thread (kept across thread switches so a failed bubble isn't lost) */
|
||||
const outbox = new Outbox();
|
||||
/** clientIds sent from this page: their bubbles fade in once (history and other tabs' messages don't) */
|
||||
export const localClientIds = new Set<string>();
|
||||
const busyStatus = (s: string) => s === "running" || s === "initializing";
|
||||
|
||||
// Internal: incremental events go through the same reducer state (no full recompute)
|
||||
let st = newTimelineState();
|
||||
let stSeqMax = 0;
|
||||
@@ -39,6 +56,15 @@ function syncRuntimeFlags() {
|
||||
}
|
||||
|
||||
export const useTimeline = create<TlStore>((set, get) => {
|
||||
/** Timeline items + optimistic bubbles, and the status the composer sees ("initializing" right after a send) */
|
||||
const view = (threadId: string) => ({
|
||||
items: withOutbox(st.items.slice(), outbox.items(threadId)),
|
||||
status: !busyStatus(runtimeStatus) && outbox.starting(threadId) ? "initializing" : runtimeStatus,
|
||||
});
|
||||
const refresh = (threadId: string) => {
|
||||
if (get().threadId === threadId) set(view(threadId));
|
||||
};
|
||||
|
||||
// Subscribe to thread:<id>: the server replays missed persisted events by afterSeq (subscribing before the snapshot would lose
|
||||
// the part replayed into the old st and discarded when the snapshot rebuilds, so the order must be: snapshot → subscribe).
|
||||
const subscribeChannel = (threadId: string) => {
|
||||
@@ -60,19 +86,23 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
if (ev.seq <= stSeqMax) return; // Dedupe reconnects/replays
|
||||
stSeqMax = Math.max(stSeqMax, ev.seq);
|
||||
}
|
||||
if (ev.type === "user_message") set({ lastUserText: ev.text });
|
||||
if (ev.type === "user_message") {
|
||||
set({ lastUserText: ev.text });
|
||||
outbox.echo(ev.clientId);
|
||||
}
|
||||
applyEvent(st, ev);
|
||||
// pending is derived from timeline items (pending permission/question → composer waiting state)
|
||||
const pending = st.items
|
||||
.filter((i) => (i.kind === "permission" || i.kind === "question") && i.status === "pending")
|
||||
.map((i) => ({ requestId: (i as { requestId: string }).requestId, kind: i.kind as "permission" | "question" }));
|
||||
set({ items: st.items.slice(), pending });
|
||||
set({ ...view(threadId), pending });
|
||||
return;
|
||||
}
|
||||
if (data.type === "status" && data.status) {
|
||||
runtimeStatus = data.status;
|
||||
if (busyStatus(runtimeStatus) || runtimeStatus === "error" || runtimeStatus === "closed") outbox.busy(threadId);
|
||||
syncRuntimeFlags();
|
||||
set({ status: runtimeStatus, items: st.items.slice() });
|
||||
set(view(threadId));
|
||||
return;
|
||||
}
|
||||
if (data.type === "queue" && data.queue) {
|
||||
@@ -101,11 +131,12 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
lastUserText: null,
|
||||
error: null,
|
||||
slashCommands: [],
|
||||
sentAt: 0,
|
||||
|
||||
open: (threadId) => {
|
||||
if (get().threadId === threadId) return;
|
||||
get().close();
|
||||
set({ threadId, status: "initializing", items: [], queue: [], pending: [], lastUserText: null, error: null, slashCommands: [] });
|
||||
set({ threadId, status: "initializing", items: outbox.items(threadId), queue: [], pending: [], lastUserText: null, error: null, slashCommands: [] });
|
||||
st = newTimelineState();
|
||||
stSeqMax = 0;
|
||||
runtimeStatus = "initializing";
|
||||
@@ -123,9 +154,10 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
st = newTimelineState();
|
||||
for (const ev of g.events) applyEvent(st, ev);
|
||||
stSeqMax = Math.max(0, ...g.events.map((e) => e.seq ?? 0));
|
||||
outbox.reconcile(threadId, g.events.flatMap((e) => (e.type === "user_message" && e.clientId ? [e.clientId] : [])));
|
||||
syncRuntimeFlags();
|
||||
set({
|
||||
items: st.items.slice(), status: runtimeStatus,
|
||||
...view(threadId),
|
||||
queue: g.queue ?? [], pending: g.pending ?? [], lastUserText: r.lastUserText,
|
||||
});
|
||||
// Subscribe only once the snapshot is ready: the server replays events after afterSeq=stSeqMax, joining the snapshot seamlessly
|
||||
@@ -143,5 +175,46 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
stSeqMax = 0;
|
||||
set({ threadId: null, items: [], queue: [], pending: [], lastUserText: null, error: null, status: "idle", slashCommands: [] });
|
||||
},
|
||||
|
||||
send: async (threadId, payload, display = {}, opts = {}) => {
|
||||
const clientId = newClientId();
|
||||
const optimistic = opts.optimistic !== false;
|
||||
if (optimistic) {
|
||||
const cur = get().threadId === threadId ? get().status : "idle";
|
||||
outbox.add({ clientId, threadId, payload, display, startsTurn: !busyStatus(cur) && payload.behavior !== "steer" });
|
||||
localClientIds.add(clientId);
|
||||
if (get().threadId === threadId) set({ ...view(threadId), sentAt: Date.now() });
|
||||
}
|
||||
try {
|
||||
const r = (await ws.call("thread.send", {
|
||||
id: threadId, text: payload.text,
|
||||
...(payload.attachments?.length ? { attachments: payload.attachments } : {}),
|
||||
...(payload.mentions?.length ? { mentions: payload.mentions } : {}),
|
||||
...(payload.behavior ? { behavior: payload.behavior } : {}),
|
||||
clientId,
|
||||
})) as { delivered?: "started" | "steered" | "queued" } | undefined;
|
||||
outbox.ok(clientId, r?.delivered);
|
||||
refresh(threadId);
|
||||
return r;
|
||||
} catch (e) {
|
||||
outbox.fail(clientId, String((e as Error)?.message ?? e));
|
||||
refresh(threadId);
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
retry: (clientId) => {
|
||||
const e = outbox.get(clientId);
|
||||
if (!e || e.state !== "failed") return;
|
||||
outbox.remove(clientId);
|
||||
void get().send(e.threadId, e.payload, e.display).catch(() => {});
|
||||
},
|
||||
|
||||
dismiss: (clientId) => {
|
||||
const e = outbox.get(clientId);
|
||||
if (!e || e.state !== "failed") return;
|
||||
outbox.remove(clientId);
|
||||
refresh(e.threadId);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -106,6 +106,9 @@ textarea.tinput { height: auto; min-height: 60px; padding: 6px 10px; resize: ver
|
||||
.provider-switch input { width: 16px; height: 16px; cursor: pointer; }
|
||||
.dlg-hint { font-size: var(--fs-s); color: var(--muted); }
|
||||
.dlg-hint.err { color: var(--danger); }
|
||||
.bash-set { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.bash-row { display: flex; gap: 8px; align-items: center; }
|
||||
.bash-row .tinput { flex: 1; min-width: 0; font-family: var(--font-mono); }
|
||||
|
||||
/* Toast */
|
||||
.toasts { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); z-index: 80; display: flex; flex-direction: column; gap: 8px; align-items: center; }
|
||||
|
||||
@@ -1,18 +1,34 @@
|
||||
/* 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: 4px 0 16px; }
|
||||
.um-row { display: flex; flex-direction: column; align-items: flex-end; margin: 4px 0 8px; }
|
||||
.um {
|
||||
position: relative; max-width: 78%;
|
||||
background: var(--accent-soft); border-radius: 14px 14px 4px 14px; color: var(--fg);
|
||||
padding: 6px 12px; font-size: var(--chat-fs); 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; }
|
||||
.um-act .ibtn { width: 24px; height: 24px; }
|
||||
/* Actions under the bubble, right-aligned. The whole row is the hover target (no gap to cross); hidden with opacity
|
||||
so the buttons stay in the tab order, and shown while one has focus or on touch screens. */
|
||||
.um-act { display: flex; gap: 2px; margin-top: 2px; height: 24px; opacity: 0; transition: opacity var(--dur-1); }
|
||||
.um-row:hover .um-act, .um-act:focus-within { opacity: 1; }
|
||||
@media (hover: none) { .um-act { opacity: 1; } }
|
||||
.um-act .ibtn { width: 24px; height: 24px; color: var(--meta); }
|
||||
.um-act .ibtn:hover, .um-act .ibtn:focus-visible { color: var(--fg); }
|
||||
.um-act .ibtn.done, .te-act.done { color: var(--fg); }
|
||||
.um-img { display: block; max-width: 200px; max-height: 140px; border-radius: var(--r-s); margin-bottom: 6px; cursor: zoom-in; }
|
||||
.um-tag { font-size: var(--chat-fs-s); color: var(--muted); margin-top: 2px; }
|
||||
/* 1.3 optimistic send: a bubble sent from this page fades in (opacity only: the row's box never moves, so the
|
||||
virtual list's measurements and the overlap checks are unaffected); a failed one keeps its place, with 重试 */
|
||||
.um-row.fresh .um { animation: um-in 140ms var(--ease, ease-out) both; }
|
||||
@keyframes um-in { from { opacity: 0; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) { .um-row.fresh .um { animation: none; } }
|
||||
.um-row.failed .um { box-shadow: inset 0 0 0 1px var(--danger); }
|
||||
.um-fail { display: flex; align-items: center; gap: 8px; margin-top: 4px; font-size: var(--chat-fs-s); color: var(--danger); }
|
||||
.um-fail-t { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.um-fail-b { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 6px; border: 1px solid var(--line);
|
||||
background: transparent; color: var(--fg); font: inherit; cursor: pointer; }
|
||||
.um-fail-b:hover, .um-fail-b:focus-visible { background: var(--surface-hover); }
|
||||
|
||||
/* Streaming cursor for the body */
|
||||
.as { margin: 4px 0; }
|
||||
@@ -41,51 +57,110 @@
|
||||
.md blockquote { margin: 6px 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); }
|
||||
.md table { border-collapse: collapse; margin: 8px 0; }
|
||||
.md th, .md td { border: 1px solid var(--line); padding: 4px 10px; font-size: var(--chat-fs-s); }
|
||||
.cb-copy {
|
||||
position: absolute; top: 6px; right: 6px; font-size: var(--fs-s); color: var(--muted);
|
||||
padding: 2px 8px; border-radius: var(--r-s); background: var(--bg); opacity: 0; transition: opacity var(--dur-1);
|
||||
/* 1.3 code blocks: header (language · wrap · copy), numbered lines (a CSS counter per line block, so wrapped lines keep
|
||||
the gutter), horizontal scroll unless wrapped */
|
||||
.md .cb { margin: 0.5em 0 0.7em; border: 1px solid var(--code-line); border-radius: var(--r-m); background: var(--code-bg); overflow: hidden; }
|
||||
.md .cb pre { margin: 0; border: 0; border-radius: 0; background: none; padding: 2px 12px 10px; }
|
||||
.cb-head { display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 6px 0 12px; font-size: var(--fs-xs); color: var(--meta); user-select: none; -webkit-user-select: none; }
|
||||
.cb-lang { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--font-mono); }
|
||||
.cb-acts { flex: none; display: inline-flex; gap: 2px; }
|
||||
.cb-btn { width: 24px; height: 22px; display: inline-flex; align-items: center; justify-content: center; border-radius: var(--r-s); color: var(--meta); }
|
||||
.cb-btn:hover, .cb-btn:focus-visible { background: var(--surface-hover); color: var(--fg); }
|
||||
.cb-btn[aria-pressed="true"], .cb-btn.done { color: var(--fg); }
|
||||
.md .cb pre code { display: block; min-width: max-content; }
|
||||
.md .cb.wrap pre code { min-width: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.md .cb.numbered pre code { counter-reset: cb-line; }
|
||||
.cb-l { display: block; min-height: 1.55em; }
|
||||
.cb.numbered .cb-l { position: relative; padding-left: 3em; }
|
||||
.cb.numbered .cb-l::before {
|
||||
counter-increment: cb-line; content: counter(cb-line); position: absolute; left: 0; width: 2em; text-align: right;
|
||||
color: var(--meta); opacity: .8; user-select: none; -webkit-user-select: none; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.md pre:hover .cb-copy { opacity: 1; }
|
||||
.cb-copy:hover { color: var(--fg); }
|
||||
/* Syntax colours stay quiet and grayscale-leaning (the chrome has no hue): weight and tone, not a rainbow */
|
||||
.md .hljs-keyword, .md .hljs-built_in, .md .hljs-selector-tag, .md .hljs-type { color: var(--fg); font-weight: 600; }
|
||||
.md .hljs-string, .md .hljs-regexp, .md .hljs-attr, .md .hljs-symbol { color: color-mix(in oklab, var(--fg) 62%, var(--bg)); }
|
||||
.md .hljs-comment, .md .hljs-quote { color: var(--meta); font-style: italic; }
|
||||
.md .hljs-number, .md .hljs-literal { color: color-mix(in oklab, var(--fg) 75%, var(--bg)); }
|
||||
.md .hljs-title, .md .hljs-title.function_, .md .hljs-section { color: var(--fg); }
|
||||
.md .hljs-meta, .md .hljs-variable.language_ { color: var(--muted); }
|
||||
|
||||
/* Thinking (collapsed gray text) / todo */
|
||||
.rs-item { margin: 4px 0 6px; }
|
||||
.rs-head {
|
||||
display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0;
|
||||
color: var(--meta); font-size: var(--chat-fs-s);
|
||||
display: inline-flex; align-items: center; gap: 4px; min-height: 22px; max-width: 100%; padding: 0;
|
||||
color: var(--meta); font-size: var(--chat-fs-s); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.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: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--chat-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(--chat-fs-s); }
|
||||
.todo { color: var(--muted); }
|
||||
.todo.in_progress { color: var(--fg); }
|
||||
/* 1.3 checklist (TodoWrite / turn/plan/updated / ACP plan entries): "2/3 任务" and one check row per step */
|
||||
.ck { margin: 4px 0 8px; font-size: var(--chat-fs-s); border-radius: var(--r-m); transition: background var(--dur-2); }
|
||||
.ck.flash { animation: ck-flash 1.2s var(--ease); }
|
||||
@keyframes ck-flash { 0%, 40% { background: var(--surface-hover); } 100% { background: transparent; } }
|
||||
.ck-head { display: flex; align-items: center; gap: 6px; min-height: 24px; padding: 0 6px; color: var(--muted); white-space: nowrap; overflow: hidden; }
|
||||
.ck-head svg { flex: none; color: var(--meta); }
|
||||
.ck-n { font-variant-numeric: tabular-nums; color: var(--fg); font-weight: 500; }
|
||||
.ck-list { list-style: none; margin: 0; padding: 0; }
|
||||
.ck-i { display: flex; align-items: flex-start; gap: 8px; padding: 2px 6px; line-height: 1.55; color: var(--muted); }
|
||||
.ck-box { flex: none; width: 14px; height: calc(var(--chat-fs-s) * 1.55); display: inline-flex; align-items: center; justify-content: center; color: var(--meta); }
|
||||
.ck-i.done .ck-box { color: var(--muted); }
|
||||
.ck-i.done .ck-t { color: var(--meta); }
|
||||
.ck-i.doing .ck-t { color: var(--fg); }
|
||||
.ck-t { min-width: 0; overflow-wrap: anywhere; }
|
||||
|
||||
/* Tool group */
|
||||
.tg { margin: 4px 0 10px; }
|
||||
/* Tool group. Every line here is one line that can only clip, never wrap: 1.2 gave the summary a fixed 24px height
|
||||
while a long "running" label squeezed it to a few characters, so the wrapped text spilled over the rows around it
|
||||
(Nolan's Windows screenshot). min-height + nowrap + overflow hidden keep each line inside its own box at any width
|
||||
and font size; the virtual list then measures the real height.
|
||||
1.3 timeline polish (after Better Paseo): steps are flat one-line rows — type icon, command / path in the code font,
|
||||
+N -M for edits, status at the right edge; only long runs fold into the summary row. Grayscale; red only for failures. */
|
||||
.tg { margin: 2px 0 8px; min-width: 0; }
|
||||
.tg-head {
|
||||
display: flex; align-items: center; gap: 6px; width: 100%; height: 24px; padding: 0;
|
||||
color: var(--meta); font-size: var(--chat-fs-s); text-align: left;
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-height: 26px; padding: 0 6px; overflow: hidden; border-radius: var(--r-s);
|
||||
color: var(--muted); font-size: var(--chat-fs-s); text-align: left; white-space: nowrap;
|
||||
}
|
||||
.tg-head:hover { color: var(--fg); }
|
||||
.tg-head .caret { transition: transform var(--dur-1); }
|
||||
.tg-head:hover { color: var(--fg); background: var(--surface-hover); }
|
||||
.tg-ic { width: 14px; flex: none; display: inline-flex; justify-content: center; color: var(--meta); }
|
||||
.tg-head .caret { flex: none; color: var(--meta); transition: transform var(--dur-1); }
|
||||
.tg-head .caret.open { transform: rotate(90deg); }
|
||||
.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; }
|
||||
.tg-sum { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tg-fail { flex: none; color: var(--danger); }
|
||||
.tg-fail::before { content: "·"; margin-right: 6px; color: var(--meta); }
|
||||
/* One line while a step runs: "正在运行:npm test…", cut with an ellipsis rather than wrapping */
|
||||
.tg-run { display: flex; align-items: center; gap: 8px; min-height: 22px; padding-left: 6px; color: var(--muted); font-size: var(--chat-fs-s); min-width: 0; overflow: hidden; white-space: nowrap; }
|
||||
.tg-run-text { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ts-noerr { color: var(--meta); font-size: var(--chat-fs-s); margin-bottom: 4px; }
|
||||
.tg-list { margin: 0; padding: 0; }
|
||||
.tg.open > .tg-list { margin: 2px 0 0 13px; padding-left: 6px; border-left: 1px solid var(--line); }
|
||||
.ts-head {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; height: 26px; padding: 0 6px;
|
||||
border-radius: var(--r-s); font-size: calc(var(--chat-fs) - 0.5px); text-align: left; color: var(--text);
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-height: 26px; padding: 0 6px; overflow: hidden;
|
||||
border-radius: var(--r-s); font-size: var(--chat-fs-s); text-align: left; color: var(--muted); white-space: nowrap;
|
||||
}
|
||||
.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-2); animation: breathe 1.2s infinite; }
|
||||
.ts-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ts-head:hover, .ts.open > .ts-head { background: var(--surface-hover); color: var(--fg); }
|
||||
.ts-ic { width: 14px; flex: none; display: inline-flex; justify-content: center; color: var(--meta); }
|
||||
.ts-head:hover .ts-ic { color: var(--muted); }
|
||||
.ts-title { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ts-title.mono { font-family: var(--font-mono); font-size: var(--chat-code-fs); }
|
||||
.ts-think .ts-head { color: var(--meta); }
|
||||
.ts-think .rs-body { margin-left: 28px; }
|
||||
.ts-diff { flex: none; display: inline-flex; gap: 5px; font-family: var(--font-mono); font-size: var(--chat-code-fs); font-variant-numeric: tabular-nums; color: var(--meta); }
|
||||
.ts-diff .add { 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-st { flex: none; width: 14px; display: inline-flex; align-items: center; justify-content: center; margin-left: auto; color: var(--meta); }
|
||||
.ts-st.ok { color: var(--muted); }
|
||||
.ts-st.fail { color: var(--danger); }
|
||||
.ts.failed > .ts-head .ts-title { color: var(--fg); }
|
||||
/* A small grey ring that turns (running step, in-progress checklist row) */
|
||||
.spin {
|
||||
display: inline-block; width: 10px; height: 10px; flex: none; border-radius: 50%;
|
||||
border: 1.5px solid color-mix(in oklab, var(--fg) 18%, transparent); border-top-color: var(--accent-2);
|
||||
animation: ac-spin .8s linear infinite;
|
||||
}
|
||||
@keyframes ac-spin { to { transform: rotate(360deg); } }
|
||||
@media (prefers-reduced-motion: reduce) { .spin { animation-duration: 2.4s; } }
|
||||
.ts-out { margin: 2px 6px 6px 28px; }
|
||||
.ts-out pre {
|
||||
background: var(--code-bg); border-radius: var(--r-s); padding: 8px 10px;
|
||||
font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.5;
|
||||
@@ -94,7 +169,7 @@
|
||||
.ts-more { font-size: var(--chat-fs-s); color: var(--accent); margin-bottom: 4px; }
|
||||
|
||||
/* diff (unified view, red/green backgrounds) */
|
||||
.diff { margin: 2px 6px 6px 22px; border: 1px solid var(--line); border-radius: var(--r-m); overflow: hidden; }
|
||||
.diff { margin: 2px 6px 6px 28px; border: 1px solid var(--line); border-radius: var(--r-m); overflow: hidden; }
|
||||
.diff-path { padding: 4px 10px; font-size: var(--chat-code-fs); 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(--chat-code-fs); line-height: 1.5; overflow-x: auto; }
|
||||
.dh-head { display: block; color: var(--muted); padding: 0 10px; }
|
||||
@@ -129,18 +204,20 @@
|
||||
.nt { margin: 8px 0; text-align: center; font-size: var(--chat-fs-s); color: var(--muted); }
|
||||
.nt.warn { color: var(--warn); }
|
||||
.nt.error { color: var(--danger); }
|
||||
.nt-bash { text-align: left; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r-m); line-height: 1.6; }
|
||||
.nt-actions { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
|
||||
|
||||
/* Turn end: small right-aligned text */
|
||||
/* 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(--chat-fs-s); color: var(--meta); }
|
||||
.te-meta { padding: 0 6px; font-variant-numeric: tabular-nums; }
|
||||
/* Turn end / reply footer (1.3): "Copy · model · 19:13 · 2m 59s" in one quiet line under the reply */
|
||||
.te { display: flex; flex-wrap: wrap; justify-content: flex-start; align-items: center; gap: 2px 4px; margin: 6px 0 18px -6px; font-size: var(--chat-fs-s); color: var(--meta); min-width: 0; }
|
||||
.te-m { display: inline-flex; align-items: center; gap: 4px; padding: 0 4px; height: 24px; font-variant-numeric: tabular-nums; white-space: nowrap; min-width: 0; max-width: 100%; }
|
||||
.te-m > span { overflow: hidden; text-overflow: ellipsis; }
|
||||
.te-m svg { flex: none; }
|
||||
.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);
|
||||
padding: 0 6px; border-radius: var(--r-s); color: var(--meta); white-space: nowrap;
|
||||
}
|
||||
.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 { color: var(--accent); font-size: inherit; margin-left: 6px; } /* chat-sized in a turn-end row, chrome-sized in dialogs */
|
||||
.te-files:hover { text-decoration: underline; }
|
||||
|
||||
/* Empty state */
|
||||
@@ -177,3 +254,17 @@ a.ac-local { cursor: pointer; }
|
||||
.mention-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.um-mentions { display: flex; flex-wrap: wrap; gap: 4px; margin: 2px 0 4px; white-space: normal; }
|
||||
.um .mention { background: color-mix(in oklab, var(--fg) 5%, var(--accent-soft)); }
|
||||
|
||||
/* 1.3 "添加到对话" button over a text selection (portaled, fixed). Grayscale, like the rest of the chrome. */
|
||||
.qs-pop {
|
||||
position: fixed; z-index: 60; display: inline-flex; align-items: center; gap: 5px; height: 30px; padding: 0 10px;
|
||||
border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); font-size: var(--fs-s);
|
||||
box-shadow: 0 4px 14px rgb(0 0 0 / .12), 0 1px 2px rgb(0 0 0 / .08); white-space: nowrap; cursor: pointer;
|
||||
user-select: none; -webkit-user-select: none;
|
||||
}
|
||||
.qs-pop:hover { background: var(--surface-hover); }
|
||||
.qs-pop svg { flex: none; color: var(--muted); }
|
||||
.um-quote {
|
||||
display: block; margin: 2px 0 6px; padding-left: 8px; border-left: 2px solid color-mix(in oklab, var(--fg) 30%, transparent);
|
||||
color: var(--muted); font-size: var(--chat-fs-s); max-height: 7.5em; overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
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; }
|
||||
.cp-hint { max-width: var(--col); margin: 6px auto 0; font-size: var(--fs-xs); 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 {
|
||||
@@ -31,8 +31,8 @@
|
||||
gap: 0;
|
||||
}
|
||||
.slash-pop .slash-name { font-weight: 500; }
|
||||
.slash-pop .slash-desc { font-size: var(--fs-xs); color: var(--muted); line-height: 1.3; }
|
||||
.slash-pop .slash-hint { font-size: var(--fs-xs); color: var(--muted); font-family: var(--mono, monospace); }
|
||||
.slash-pop .slash-desc { font-size: var(--fs-s); color: var(--muted); line-height: 1.3; }
|
||||
.slash-pop .slash-hint { font-size: var(--fs-s); color: var(--muted); font-family: var(--font-mono); }
|
||||
.slash-pop .mi.slash-item.sel { background: var(--surface-hover); }
|
||||
|
||||
.cp-ta {
|
||||
@@ -46,7 +46,8 @@
|
||||
margin: 4px 0 0 -6px; min-width: 0;
|
||||
}
|
||||
|
||||
/* Pill controls: 26px, 7px radius, 12px text; the agent·model chip is filled, the others are icon + label */
|
||||
/* Pill controls: 26px, 7px radius, 12px text. 1.3: every composer chip (agent·model, effort, permission, Fast) shares one
|
||||
style: a filled 24px chip with an icon, a label and a ⌄ */
|
||||
.pill-wrap { position: relative; flex: 0 1 auto; min-width: 0; max-width: 100%; }
|
||||
.pill {
|
||||
position: relative; display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 8px;
|
||||
@@ -67,6 +68,20 @@
|
||||
.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); }
|
||||
.cp-bar .pill { height: 24px; border-radius: 6px; background: var(--chip-bg); border-color: var(--chip-line); padding: 0 6px 0 7px; gap: 5px; }
|
||||
.cp-bar .pill:hover, .cp-bar .pill[aria-expanded="true"] { background: var(--surface-hover); }
|
||||
.cp-bar .pill.chip { padding: 0 6px 0 3px; }
|
||||
.cp-bar .pill.chip .chip-logo { width: 16px; height: 16px; }
|
||||
.cp-bar .ipill.danger { border-color: color-mix(in oklab, var(--danger) 35%, var(--chip-line)); }
|
||||
.cp-bar { gap: 4px; }
|
||||
/* 1.3: "2/3 tasks" above the composer while the latest turn has a step list */
|
||||
.cp-tasks { max-width: var(--col); margin: 0 auto 6px; display: flex; }
|
||||
.tasks-pill {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 8px; border-radius: var(--r-full);
|
||||
border: 1px solid var(--chip-line); background: var(--bg); color: var(--muted); font-size: var(--fs-xs); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.tasks-pill:hover { color: var(--fg); background: var(--surface-hover); }
|
||||
.tasks-pill svg { flex: none; color: var(--meta); }
|
||||
.mode-menu { max-width: 300px; }
|
||||
.cp-div { width: 1px; height: 14px; background: var(--line); margin: 0 4px; flex: none; }
|
||||
.cp-bar > .ibtn { flex: none; }
|
||||
@@ -155,7 +170,7 @@
|
||||
flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.agent-picker .mi-row .mi-sub {
|
||||
flex: none; max-width: 38%; font-size: 11px; color: var(--muted);
|
||||
flex: none; max-width: 38%; font-size: var(--fs-xs); color: var(--muted);
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.agent-picker .model-pick-row {
|
||||
@@ -167,7 +182,7 @@
|
||||
.agent-picker .model-pick-default {
|
||||
flex: 0 1 58%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.agent-picker .mi-meta { flex: none; font-size: 11px; color: var(--muted); white-space: nowrap; }
|
||||
.agent-picker .mi-meta { flex: none; font-size: var(--fs-xs); color: var(--muted); white-space: nowrap; }
|
||||
.agent-picker .mi-tag { flex: none; font-size: 10px; color: var(--accent); }
|
||||
.agent-picker .mi-caret { flex: none; color: var(--muted); display: inline-flex; }
|
||||
.agent-picker .mi-check { flex: none; margin-left: auto; color: var(--accent); }
|
||||
@@ -209,3 +224,15 @@
|
||||
.cp-card.drop-on { outline: 1.5px dashed var(--cp-focus); outline-offset: 2px; }
|
||||
.cp-drop-hint { padding: 4px 10px 0; font-size: var(--fs-s); color: var(--muted); }
|
||||
.att-bar .mention { height: 24px; }
|
||||
|
||||
/* 1.3 quotes from a text selection ("添加到对话") */
|
||||
.qchip {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 24px; max-width: 260px; padding: 0 4px 0 8px;
|
||||
border-radius: 6px; background: var(--surface-hover); color: var(--fg); font-size: var(--fs-s); min-width: 0;
|
||||
border-left: 2px solid color-mix(in oklab, var(--fg) 35%, transparent);
|
||||
}
|
||||
.qchip svg { flex: none; color: var(--muted); }
|
||||
.qchip-t { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.qchip-n { flex: none; color: var(--meta); }
|
||||
.qchip .att-x { flex: none; width: 18px; height: 18px; border-radius: 4px; }
|
||||
.qchip .att-x:hover { background: color-mix(in oklab, var(--fg) 10%, transparent); }
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
.pj-badge {
|
||||
width: 18px; height: 18px; flex: none; border-radius: 5px;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: var(--badge-bg); color: var(--badge-fg); font-size: 11px; font-weight: 600; line-height: 1;
|
||||
background: var(--badge-bg); color: var(--badge-fg); font-size: var(--fs-xs); font-weight: 600; line-height: 1;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.pj-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -70,7 +70,7 @@
|
||||
.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: 11.5px; color: var(--meta); font-weight: 400; }
|
||||
.t-time { flex: none; font-size: var(--fs-xs); 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;
|
||||
@@ -214,7 +214,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
}
|
||||
.ft-row:hover { background: var(--surface-hover); }
|
||||
.ft-row.on { background: var(--surface-hover); }
|
||||
.ft-row .caret { font-size: 11px; color: var(--muted); display: inline-block; transition: transform var(--dur-1) var(--ease); }
|
||||
.ft-row .caret { font-size: var(--fs-xs); color: var(--muted); display: inline-block; transition: transform var(--dur-1) var(--ease); }
|
||||
.ft-row .caret.open { transform: rotate(90deg); }
|
||||
.ft-dot { width: 13px; flex: none; }
|
||||
.ft-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -34,7 +34,9 @@
|
||||
--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: var(--magpie-code, "Cascadia Code", "Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace);
|
||||
--fs-s: 12px; --fs-m: 13px; --fs-l: 14px;
|
||||
/* UI chrome (sidebar, top bar, right panel, menus, dialogs) stays on this fixed scale; only the conversation follows
|
||||
Settings → Chat font size (1.3 review). --fs-xs: badges, timestamps and tiny meta. */
|
||||
--fs-xs: 11px; --fs-s: 12px; --fs-m: 13px; --fs-l: 14px;
|
||||
--fs-hero: 18px;
|
||||
--lh: 1.6;
|
||||
--col: 720px;
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// 1.3 display pass over the reduced timeline, like the Claude Code desktop app:
|
||||
// - consecutive tool groups merge into one foldable summary ("改动 1 · 运行 3 · 读取 2 · 1 失败");
|
||||
// - short or empty thinking next to tool calls folds into that summary as a step instead of its own "思考 Xs" row;
|
||||
// - a lone, finished, empty thinking row is dropped (nothing to open).
|
||||
// Long thinking, text, plans, permissions, notices and turn ends still break a run. Pure: the reducer's items are not changed.
|
||||
// 1.3 timeline polish: a run shows its steps as flat one-line rows; only a run of more than TOOL_COLLAPSE_AT tool calls folds
|
||||
// into the summary. Within one user turn only the newest checklist (todo) is kept, where it was last updated, and Claude's
|
||||
// TodoWrite step is dropped from the rows (the checklist shows it).
|
||||
import type { DisplayItem, ToolStep } from "./reducer.js";
|
||||
|
||||
/** Thinking up to this many characters (≈5 s at the "思考 Xs" rate) counts as short */
|
||||
export const SHORT_THINK_CHARS = 200;
|
||||
|
||||
type Reasoning = Extract<DisplayItem, { kind: "reasoning" }>;
|
||||
type Group = Extract<DisplayItem, { kind: "toolgroup" }>;
|
||||
|
||||
export function isShortThinking(it: DisplayItem): it is Reasoning {
|
||||
return it.kind === "reasoning" && it.text.trim().length <= SHORT_THINK_CHARS;
|
||||
}
|
||||
|
||||
function thinkStep(r: Reasoning): ToolStep {
|
||||
return {
|
||||
itemId: `think:${r.itemId}`, kind: "think", title: "",
|
||||
status: r.streaming ? "running" : "ok",
|
||||
think: { text: r.text, streaming: r.streaming },
|
||||
};
|
||||
}
|
||||
|
||||
/** A run of more tool calls than this folds into one summary row (expandable); shorter runs show every row */
|
||||
export const TOOL_COLLAPSE_AT = 6;
|
||||
|
||||
type Todo = Extract<DisplayItem, { kind: "todo" }>;
|
||||
|
||||
/** Checklists replaced by a newer one in the same user turn */
|
||||
function supersededTodos(items: DisplayItem[]): Set<DisplayItem> {
|
||||
const out = new Set<DisplayItem>();
|
||||
let last: DisplayItem | null = null;
|
||||
for (const it of items) {
|
||||
if (it.kind === "user") last = null;
|
||||
else if (it.kind === "todo") {
|
||||
if (last) out.add(last);
|
||||
last = it;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function foldTimeline(items: DisplayItem[], opts: { showThinking?: boolean } = {}): DisplayItem[] {
|
||||
const showThinking = opts.showThinking !== false;
|
||||
const stale = supersededTodos(items);
|
||||
const out: DisplayItem[] = [];
|
||||
let group: Group | null = null;
|
||||
let held: Reasoning[] = [];
|
||||
const flushHeld = () => {
|
||||
for (const r of held) if (r.streaming || r.text.trim()) out.push(r);
|
||||
held = [];
|
||||
};
|
||||
for (const it of items) {
|
||||
if (it.kind === "gone" || stale.has(it)) continue;
|
||||
if (it.kind === "toolgroup") {
|
||||
const steps = it.steps.filter((s) => s.kind !== "todo");
|
||||
if (!steps.length) continue;
|
||||
if (group) {
|
||||
group.steps.push(...steps);
|
||||
} else {
|
||||
group = { kind: "toolgroup", key: it.key, steps: [...(showThinking ? held.map(thinkStep) : []), ...steps] };
|
||||
held = [];
|
||||
out.push(group);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (it.kind === "reasoning") {
|
||||
if (!showThinking) continue;
|
||||
if (isShortThinking(it)) {
|
||||
if (!it.streaming && !it.text.trim()) continue; // finished and empty: nothing to show, and it doesn't split a run
|
||||
if (group) group.steps.push(thinkStep(it));
|
||||
else held.push(it);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
flushHeld();
|
||||
group = null;
|
||||
out.push(it);
|
||||
}
|
||||
flushHeld();
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- summary helpers (shared by the component and tests) ----
|
||||
export type StepCategory = "edit" | "run" | "read" | "search" | "other";
|
||||
export const CATEGORY_ORDER: StepCategory[] = ["edit", "run", "read", "search", "other"];
|
||||
|
||||
export function stepCategory(kind: string): StepCategory | "think" {
|
||||
switch (kind) {
|
||||
case "think": return "think";
|
||||
case "edit": case "write": return "edit";
|
||||
case "bash": return "run";
|
||||
case "read": return "read";
|
||||
case "search": case "glob": case "web": return "search";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
export type GroupSummary = { counts: [StepCategory, number][]; failed: number; thinkSecs: number };
|
||||
|
||||
export function summarize(steps: ToolStep[]): GroupSummary {
|
||||
const m = new Map<StepCategory, number>();
|
||||
let failed = 0;
|
||||
let thinkChars = 0;
|
||||
for (const s of steps) {
|
||||
const c = stepCategory(s.kind);
|
||||
if (c === "think") { thinkChars += s.think?.text.length ?? 0; continue; }
|
||||
m.set(c, (m.get(c) ?? 0) + 1);
|
||||
if (s.status === "failed") failed++;
|
||||
}
|
||||
return {
|
||||
counts: CATEGORY_ORDER.filter((c) => m.has(c)).map((c) => [c, m.get(c)!]),
|
||||
failed,
|
||||
thinkSecs: thinkChars ? Math.max(1, Math.round(thinkChars / 40)) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim() : "");
|
||||
|
||||
/** What a running step works on: the command, the file, the pattern… (falls back to its title) */
|
||||
export function stepTarget(s: ToolStep): string {
|
||||
const i = (s.input ?? {}) as Record<string, unknown>;
|
||||
const d = (s.detail ?? {}) as Record<string, unknown>;
|
||||
const v =
|
||||
str(d.command) || str(i.command) || str(i.cmd) ||
|
||||
str(i.file_path) || str(i.path) || str(d.path) || str(i.filePath) ||
|
||||
str(i.pattern) || str(i.query) || str(i.url) ||
|
||||
str(s.title);
|
||||
return v.replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
/** The step to show in the one-line "正在…" row: the last running tool, else a thinking step still streaming at the end */
|
||||
export function activeStep(steps: ToolStep[]): ToolStep | null {
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
const s = steps[i];
|
||||
if (s.status === "running" && s.kind !== "think") return s;
|
||||
}
|
||||
const last = steps[steps.length - 1];
|
||||
return last && last.kind === "think" && last.think?.streaming ? last : null;
|
||||
}
|
||||
|
||||
/** Tool calls in a run (short thinking folded into it doesn't count) */
|
||||
export function toolStepCount(steps: ToolStep[]): number {
|
||||
let n = 0;
|
||||
for (const s of steps) if (s.kind !== "think") n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Lines added / removed by an edit step: the daemon's counts, else counted from its hunks; null when it has no diff */
|
||||
export function stepDiffStat(s: ToolStep): { added: number; removed: number } | null {
|
||||
const d = (s.detail ?? null) as { added?: unknown; removed?: unknown; hunks?: unknown; diff?: { hunks?: unknown } } | null;
|
||||
if (!d || typeof d !== "object") return null;
|
||||
if (typeof d.added === "number" && typeof d.removed === "number") return { added: d.added, removed: d.removed };
|
||||
const hunks = Array.isArray(d.hunks) ? d.hunks : Array.isArray(d.diff?.hunks) ? d.diff!.hunks as unknown[] : null;
|
||||
if (!hunks) return null;
|
||||
let added = 0, removed = 0;
|
||||
for (const h of hunks) {
|
||||
for (const l of ((h as { lines?: unknown }).lines ?? []) as { t?: unknown }[]) {
|
||||
if (l?.t === "+") added++;
|
||||
else if (l?.t === "-") removed++;
|
||||
}
|
||||
}
|
||||
return { added, removed };
|
||||
}
|
||||
|
||||
/** A checklist's progress */
|
||||
export function todoProgress(items: { status: string }[]): { done: number; total: number } {
|
||||
return { done: items.filter((i) => i.status === "done" || i.status === "completed").length, total: items.length };
|
||||
}
|
||||
|
||||
/** The unfinished checklist of the latest user turn (for the "N/M tasks" pill above the composer), or null */
|
||||
export function currentChecklist(items: DisplayItem[]): Todo | null {
|
||||
for (let i = items.length - 1; i >= 0; i--) {
|
||||
const it = items[i]!;
|
||||
// A finished list needs no reminder: the pill shows while something is still open
|
||||
if (it.kind === "todo") return it.items.some((x) => x.status !== "done") ? it : null;
|
||||
if (it.kind === "user") return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { Outbox, newClientId, userKey, withOutbox } from "./outbox";
|
||||
import { applyEvent, newTimelineState } from "./reducer";
|
||||
import type { TimelineEvent } from "./types";
|
||||
|
||||
const um = (seq: number, text: string, clientId?: string): TimelineEvent =>
|
||||
({ seq, ts: 1000 + seq, threadId: "t1", type: "user_message", text, ...(clientId ? { clientId } : {}) }) as TimelineEvent;
|
||||
|
||||
describe("optimistic send outbox (1.3)", () => {
|
||||
it("shows the bubble at once, and the echo replaces it under the same key (no duplicate, no jump)", () => {
|
||||
const ob = new Outbox();
|
||||
const st = newTimelineState();
|
||||
const id = newClientId();
|
||||
ob.add({ clientId: id, threadId: "t1", payload: { text: "> 引用\n\n你好" }, display: {}, startsTurn: true });
|
||||
let view = withOutbox(st.items, ob.items("t1"));
|
||||
expect(view).toHaveLength(1);
|
||||
expect(view[0]).toMatchObject({ kind: "user", key: userKey(0, id), sendState: "sending", text: "> 引用\n\n你好" });
|
||||
expect(ob.starting("t1")).toBe(true);
|
||||
// echo arrives (before thread.send answers: the daemon pushes it before the Agent starts)
|
||||
expect(ob.echo(id)).toBe(true);
|
||||
applyEvent(st, um(5, "> 引用\n\n你好", id));
|
||||
view = withOutbox(st.items, ob.items("t1"));
|
||||
expect(view).toHaveLength(1);
|
||||
expect(view[0].key).toBe(userKey(5, id));
|
||||
expect((view[0] as { sendState?: string }).sendState).toBeUndefined();
|
||||
// a late failure (e.g. timeout while the Agent was starting) doesn't turn the real message into a failed one
|
||||
expect(ob.fail(id, "timeout")).toBe(false);
|
||||
expect(ob.items("t1")).toHaveLength(0);
|
||||
expect(ob.get(id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("messages without a clientId (history, other tabs) keep the seq key", () => {
|
||||
const st = newTimelineState();
|
||||
applyEvent(st, um(3, "旧消息"));
|
||||
expect(st.items[0].key).toBe("u:3");
|
||||
});
|
||||
|
||||
it("a failed send keeps its bubble, marked failed; status falls back", () => {
|
||||
const ob = new Outbox();
|
||||
ob.add({ clientId: "c1", threadId: "t1", payload: { text: "hi", mentions: [{ rel: "a.txt", isDir: false }] }, display: { mentions: [{ path: "/p/a.txt", isDir: false }] }, startsTurn: true });
|
||||
expect(ob.fail("c1", "连接已断开")).toBe(true);
|
||||
const [b] = ob.items("t1");
|
||||
expect(b).toMatchObject({ sendState: "failed", sendError: "连接已断开", mentions: [{ path: "/p/a.txt", isDir: false }] });
|
||||
expect(ob.starting("t1")).toBe(false);
|
||||
// retry has everything it needs
|
||||
expect(ob.get("c1")!.payload.mentions).toEqual([{ rel: "a.txt", isDir: false }]);
|
||||
ob.remove("c1");
|
||||
expect(ob.items("t1")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("delivered=queued drops the bubble (the queue list shows it); a busy status ends the optimistic working state", () => {
|
||||
const ob = new Outbox();
|
||||
ob.add({ clientId: "c2", threadId: "t1", payload: { text: "x" }, display: {}, startsTurn: true });
|
||||
ob.ok("c2", "queued");
|
||||
expect(ob.items("t1")).toHaveLength(0);
|
||||
ob.add({ clientId: "c3", threadId: "t1", payload: { text: "y" }, display: {}, startsTurn: true });
|
||||
ob.busy("t1");
|
||||
expect(ob.starting("t1")).toBe(false);
|
||||
expect(ob.items("t1")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("snapshot reconcile (reopened conversation) and per-thread isolation", () => {
|
||||
const ob = new Outbox();
|
||||
ob.add({ clientId: "c4", threadId: "t1", payload: { text: "a" }, display: {}, startsTurn: true });
|
||||
ob.add({ clientId: "c5", threadId: "t2", payload: { text: "b" }, display: {}, startsTurn: true });
|
||||
ob.reconcile("t1", ["c4", "c5"]);
|
||||
expect(ob.items("t1")).toHaveLength(0);
|
||||
expect(ob.items("t2")).toHaveLength(1);
|
||||
ob.ok("c4");
|
||||
expect(ob.get("c4")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("steer bubbles are tagged; client ids are unique and accepted by the daemon's schema", () => {
|
||||
const ob = new Outbox();
|
||||
ob.add({ clientId: "c6", threadId: "t1", payload: { text: "插话", behavior: "steer" }, display: {}, startsTurn: false });
|
||||
expect(ob.items("t1")[0]).toMatchObject({ steered: true });
|
||||
expect(ob.starting("t1")).toBe(false);
|
||||
const ids = new Set(Array.from({ length: 500 }, () => newClientId()));
|
||||
expect(ids.size).toBe(500);
|
||||
for (const id of ids) expect(id).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
// 1.3 optimistic send: the user's bubble shows the moment 发送 is clicked, before the daemon echoes the
|
||||
// user_message (which used to wait for the Agent to start: seconds on Windows). Each send gets a clientId that the
|
||||
// daemon puts on its user_message; the echo replaces the optimistic bubble under the same React key (no duplicate,
|
||||
// no jump). A send that fails before any echo keeps its bubble, marked failed, with 重试. Pure, unit tested.
|
||||
import type { DisplayItem } from "./reducer.js";
|
||||
|
||||
export type SendPayload = {
|
||||
text: string;
|
||||
attachments?: { path: string; mime: string; name?: string }[];
|
||||
mentions?: { rel: string; isDir: boolean }[];
|
||||
behavior?: "queue" | "steer";
|
||||
};
|
||||
export type SendDisplay = {
|
||||
attachments?: { id: string; name: string; mime: string }[];
|
||||
mentions?: { path: string; isDir: boolean }[];
|
||||
};
|
||||
export type OutboxEntry = {
|
||||
clientId: string;
|
||||
threadId: string;
|
||||
payload: SendPayload;
|
||||
display: SendDisplay;
|
||||
ts: number;
|
||||
state: "sending" | "failed";
|
||||
error?: string;
|
||||
/** the daemon's user_message with this clientId arrived: the real bubble is in the timeline */
|
||||
echoed: boolean;
|
||||
/** thread.send answered (ok or error) */
|
||||
settled: boolean;
|
||||
/** this send starts a turn (the conversation was idle): the composer shows "working" straight away */
|
||||
startsTurn: boolean;
|
||||
/** a running/initializing status arrived after this send: the real status takes over */
|
||||
busySeen: boolean;
|
||||
};
|
||||
|
||||
let counter = 0;
|
||||
export function newClientId(now = Date.now()): string {
|
||||
counter = (counter + 1) % 1_000_000;
|
||||
return `c${now.toString(36)}${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
/** Display key of a user bubble: the clientId when there is one, so optimistic and echoed share it */
|
||||
export function userKey(seq: number, clientId?: string): string {
|
||||
return clientId ? `u:c:${clientId}` : `u:${seq}`;
|
||||
}
|
||||
|
||||
export class Outbox {
|
||||
private list: OutboxEntry[] = [];
|
||||
|
||||
add(e: Omit<OutboxEntry, "state" | "echoed" | "settled" | "busySeen" | "ts"> & { ts?: number }): OutboxEntry {
|
||||
const entry: OutboxEntry = { ts: Date.now(), ...e, state: "sending", echoed: false, settled: false, busySeen: false };
|
||||
this.list.push(entry);
|
||||
return entry;
|
||||
}
|
||||
get(clientId: string): OutboxEntry | undefined {
|
||||
return this.list.find((e) => e.clientId === clientId);
|
||||
}
|
||||
entries(threadId: string): OutboxEntry[] {
|
||||
return this.list.filter((e) => e.threadId === threadId);
|
||||
}
|
||||
remove(clientId: string): void {
|
||||
this.list = this.list.filter((e) => e.clientId !== clientId);
|
||||
}
|
||||
private gc(e: OutboxEntry): void {
|
||||
if (e.echoed && e.settled) this.remove(e.clientId);
|
||||
}
|
||||
/** The daemon echoed it (live event or snapshot). Returns whether it was ours. */
|
||||
echo(clientId: string | undefined): boolean {
|
||||
if (!clientId) return false;
|
||||
const e = this.get(clientId);
|
||||
if (!e) return false;
|
||||
e.echoed = true;
|
||||
// an echo after a failure (a slow daemon answered after a timeout): the message did go, so it isn't failed
|
||||
e.state = "sending";
|
||||
e.error = undefined;
|
||||
this.gc(e);
|
||||
return true;
|
||||
}
|
||||
/** thread.send answered ok. "queued" means it sits in the composer's queue list, not in the timeline yet. */
|
||||
ok(clientId: string, delivered?: string): void {
|
||||
const e = this.get(clientId);
|
||||
if (!e) return;
|
||||
if (delivered === "queued" && !e.echoed) { this.remove(clientId); return; }
|
||||
e.settled = true;
|
||||
this.gc(e);
|
||||
}
|
||||
/** thread.send failed. Echoed already → the daemon wrote its own error card; otherwise the bubble turns failed. */
|
||||
fail(clientId: string, error: string): boolean {
|
||||
const e = this.get(clientId);
|
||||
if (!e) return false;
|
||||
e.settled = true;
|
||||
if (e.echoed) { this.gc(e); return false; }
|
||||
e.state = "failed";
|
||||
e.error = error;
|
||||
return true;
|
||||
}
|
||||
/** A running/initializing status for the thread */
|
||||
busy(threadId: string): void {
|
||||
for (const e of this.list) if (e.threadId === threadId) e.busySeen = true;
|
||||
}
|
||||
/** Snapshot reconcile: drop the entries whose user_message is already in the events */
|
||||
reconcile(threadId: string, echoedIds: Iterable<string>): void {
|
||||
for (const id of echoedIds) {
|
||||
const e = this.get(id);
|
||||
if (e && e.threadId === threadId) this.echo(id);
|
||||
}
|
||||
}
|
||||
/** Bubbles still waiting for their echo (or failed), as timeline items */
|
||||
items(threadId: string): DisplayItem[] {
|
||||
return this.entries(threadId)
|
||||
.filter((e) => !e.echoed)
|
||||
.map((e) => ({
|
||||
kind: "user" as const,
|
||||
key: userKey(0, e.clientId),
|
||||
text: e.payload.text,
|
||||
...(e.display.attachments?.length ? { attachments: e.display.attachments } : {}),
|
||||
...(e.display.mentions?.length ? { mentions: e.display.mentions } : {}),
|
||||
...(e.payload.behavior === "steer" ? { steered: true } : {}),
|
||||
ts: e.ts,
|
||||
clientId: e.clientId,
|
||||
sendState: e.state,
|
||||
...(e.error ? { sendError: e.error } : {}),
|
||||
}));
|
||||
}
|
||||
/** A turn-starting send is on its way and no busy status has come yet */
|
||||
starting(threadId: string): boolean {
|
||||
return this.entries(threadId).some((e) => e.startsTurn && e.state === "sending" && !e.settled && !e.busySeen);
|
||||
}
|
||||
}
|
||||
|
||||
/** The timeline with the optimistic bubbles at the end */
|
||||
export function withOutbox(items: DisplayItem[], pending: DisplayItem[]): DisplayItem[] {
|
||||
return pending.length ? [...items, ...pending] : items;
|
||||
}
|
||||
@@ -3,16 +3,23 @@
|
||||
// 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.js";
|
||||
import { userKey } from "./outbox.js";
|
||||
|
||||
export type ToolStep = {
|
||||
itemId: string; kind: string; title: string;
|
||||
status: "running" | "ok" | "failed";
|
||||
input?: unknown; detail?: unknown; output?: string;
|
||||
exitCode?: number; durationMs?: number;
|
||||
/** 1.3: a short "thinking" folded into the tool summary (display only, see fold.ts) */
|
||||
think?: { text: string; streaming: boolean };
|
||||
};
|
||||
|
||||
export type DisplayItem =
|
||||
| { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; mentions?: { path: string; isDir: boolean }[]; steered?: boolean; ts: number }
|
||||
| { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; mentions?: { path: string; isDir: boolean }[]; steered?: boolean; ts: number;
|
||||
/** 1.3: the page's id for the send (optimistic bubble ↔ echoed user_message) */
|
||||
clientId?: string;
|
||||
/** 1.3: only on optimistic bubbles: still on its way, or the send failed */
|
||||
sendState?: "sending" | "failed"; sendError?: string }
|
||||
| { kind: "assistant"; key: string; itemId: string; text: string; streaming: boolean }
|
||||
| { kind: "reasoning"; key: string; itemId: string; text: string; streaming: boolean }
|
||||
| { kind: "toolgroup"; key: string; steps: ToolStep[] }
|
||||
@@ -20,9 +27,11 @@ export type DisplayItem =
|
||||
| { kind: "todo"; key: string; items: { text: string; status: string }[] }
|
||||
| { kind: "permission"; key: string; requestId: string; title: string; kindStr: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; status: "pending" | "resolved" | "cancelled"; choice?: string }
|
||||
| { kind: "question"; key: string; requestId: string; questions: unknown[]; answers?: Record<string, string>; status: "pending" | "answered" | "cancelled" }
|
||||
| { kind: "notice"; key: string; level: string; message: string }
|
||||
| { kind: "notice"; key: string; level: string; message: string; code?: string }
|
||||
| { kind: "gone"; key: string } // placeholder: duplicate delta items cleared by sweepSiblings; skipped when rendering
|
||||
| { kind: "turnend"; key: string; status: string; durationMs?: number; error?: string; filesChanged?: number; usage?: TurnUsage };
|
||||
| { kind: "turnend"; key: string; status: string; durationMs?: number; error?: string; filesChanged?: number; usage?: TurnUsage;
|
||||
/** 1.3: the model the turn ran on (turn_started; null = the Agent's default) and when it ended, for the reply footer */
|
||||
model?: string | null; ts?: number };
|
||||
|
||||
export type TurnUsage = { inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number };
|
||||
|
||||
@@ -43,6 +52,8 @@ type State = {
|
||||
lastUserIdx: Map<string, number>;
|
||||
// turnId -> turn_started ts (fallback duration for agents that don't report one, e.g. ACP)
|
||||
turnStart: Map<string, number>;
|
||||
// turnId -> the model turn_started reported (1.3 reply footer)
|
||||
turnModel: Map<string, string | null>;
|
||||
};
|
||||
|
||||
export function newTimelineState(): State {
|
||||
@@ -56,6 +67,7 @@ export function newTimelineState(): State {
|
||||
turnUsage: new Map(),
|
||||
lastUserIdx: new Map(),
|
||||
turnStart: new Map(),
|
||||
turnModel: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -164,7 +176,7 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
case "user_message":
|
||||
breakGroup(st);
|
||||
st.lastUserIdx.set(ev.turnId ?? "", st.items.length);
|
||||
st.items.push({ kind: "user", key: `u:${ev.seq}`, text: ev.text, attachments: ev.attachments, ...(ev.mentions?.length ? { mentions: ev.mentions } : {}), steered: ev.steered, ts: ev.ts });
|
||||
st.items.push({ kind: "user", key: userKey(ev.seq, ev.clientId), text: ev.text, attachments: ev.attachments, ...(ev.mentions?.length ? { mentions: ev.mentions } : {}), steered: ev.steered, ts: ev.ts, ...(ev.clientId ? { clientId: ev.clientId } : {}) });
|
||||
return;
|
||||
case "assistant_delta":
|
||||
applyDelta(st, ev.itemId, "assistant", ev.text);
|
||||
@@ -194,6 +206,12 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
return;
|
||||
case "plan":
|
||||
breakGroup(st);
|
||||
// 1.3: an ACP plan is the Agent's step list (entries with pending / in_progress / completed): a checklist like
|
||||
// Claude's TodoWrite and Codex's turn/plan/updated. A plan without entries (Claude / Codex plan text) stays a card.
|
||||
if (ev.entries?.length) {
|
||||
st.items.push({ kind: "todo", key: `todo:${ev.seq}`, items: ev.entries.map((e) => ({ text: e.step, status: e.status === "completed" ? "done" : e.status || "pending" })) });
|
||||
return;
|
||||
}
|
||||
st.items.push({ kind: "plan", key: `plan:${ev.itemId}`, itemId: ev.itemId, markdown: ev.markdown });
|
||||
return;
|
||||
case "todo":
|
||||
@@ -243,7 +261,7 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
}
|
||||
case "notice":
|
||||
breakGroup(st);
|
||||
st.items.push({ kind: "notice", key: `n:${ev.seq}`, level: ev.level, message: ev.message });
|
||||
st.items.push({ kind: "notice", key: `n:${ev.seq}`, level: ev.level, message: ev.message, ...(ev.code ? { code: ev.code } : {}) });
|
||||
return;
|
||||
case "turn_ended":
|
||||
breakGroup(st);
|
||||
@@ -252,11 +270,14 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
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),
|
||||
...(st.turnModel.has(ev.turnId) ? { model: st.turnModel.get(ev.turnId) } : {}),
|
||||
ts: ev.ts,
|
||||
});
|
||||
return;
|
||||
case "turn_started":
|
||||
// not shown as an item; the status pill uses status events / runtime
|
||||
st.turnStart.set(ev.turnId, ev.ts);
|
||||
st.turnModel.set(ev.turnId, ev.model ?? null);
|
||||
return;
|
||||
case "status":
|
||||
return;
|
||||
|
||||
@@ -9,7 +9,7 @@ export type AttachmentRef = { id: string; name: string; mime: string };
|
||||
export type PermissionOption = { id: string; label: string; kind: "allow_once" | "allow_always" | "reject_once" };
|
||||
|
||||
export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[]; clientId?: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_started"; model: string | null; mode: string; effort: string | null }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_delta" | "reasoning_delta" | "tool_output_delta"; itemId: string; text: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_message" | "reasoning"; itemId: string; text: string }
|
||||
@@ -21,6 +21,6 @@ export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question"; requestId: string; questions: unknown[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "notice"; level: "info" | "warn" | "error"; message: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "notice"; level: "info" | "warn" | "error"; message: string; code?: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_ended"; status: "completed" | "interrupted" | "failed"; durationMs?: number; error?: string; filesChanged?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "status"; status: string };
|
||||
|
||||
Reference in New Issue
Block a user