agent-console 1.3.7: auto-detect unlabelled code blocks, html-only sanitize, Windows desktop reconnect through Magpie's Try again (#792)
Code blocks are drawn in the same pass as the Markdown, so a streaming reply no longer flickers. Two fixes from the review on 40eb3027:
- An unlabelled fence is detected by highlight.js again (`highlightAuto`, behind a 128-entry LRU). Only a fence that is still open at the end of a streaming message stays plain "text" (`isClosedFence`, which follows marked's fence rule).
- DOMPurify is back to the html profile only. The code-block icons are per-load random placeholders until after sanitize, and `codeBlockKey` is gone.
The Windows desktop reconnect is also fixed. `safeBackUrl` (gate, wrapper and web) takes loopback Magpie pages only, never `http://wails.localhost`. WebView2 can't route a 127.0.0.1 frame's request there, so it showed its gray error page. In the desktop window the wrapper, or an unwrapped daemon page, posts `{magpie:1, method:"error"}` instead, and Magpie's pluginpages.js answers with its Try again card. A stale stored wails back URL is dropped.
Reviewed at c520fa46 (merge base 1eb9473f = main) on mote (mote-run, HOME=$(mktemp -d), package copied out of the workspace):
- npm ci; `npm run check` clean; `npm run verify:build` OK for all 5 files.
- `npx vitest run` with CHROME_PATH set to Playwright's Chromium 1248: 77 files, 567 passed, 17 skipped, 0 failed. markdown-render-browser ran (it went red under the hand-breaks).
- `bun scripts/check.mjs agent-console` ok. Repo `bun test`: 6449 pass, 0 fail.
- Broken by hand, each red:
- autoDetect forced on while streaming: markdown-render-browser red.
- `svg: true` put back in the profile: markdown-render-browser red.
- Auto-detection removed: codeBlock and markdown-render-browser red.
- LRU eviction removed: codeBlock red.
- `isClosedFence` accepting any backtick run: codeBlock red.
- wails.localhost accepted again in gate.mjs, then in backToMagpie.ts: ac11 red (3 and 2 tests).
- The same in wrapper.mjs: wrapper red (4 tests).
- The stale stored back kept: wrapper red.
- Read magpie's pluginpages.js on main: `method:"error"` from the page's own frame calls `broke(key, why)`.
Not tried: a real WebView2 on Windows (the reconnect path), or a real streaming reply in the desktop app.
This commit is contained in:
@@ -55,7 +55,7 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
The daemon only ever answers with the option for that one request (allow once / accept), never allow-always, so no lasting rule is written into the Agent's own config; when a request offers nothing narrower, the card stays for you. Plan approvals and questions are never answered for you. Every approval it gives is saved in the conversation (`permission_request` + `permission_resolved`, both `auto: true`) and shown as a quiet row after its tool calls, 已自动同意 3 项 · npm test · git status, that opens to each request's title, command or file and the answer. Turning the mode on also approves a card that is already waiting. Only the page (with its token) can switch it on.
|
||||
|
||||
**Upgrading from 1.2.** 1.2's 全部放行 (`bypassPermissions`) did nothing for Cursor and OpenCode (they had no such mode, so it fell back to 每次询问) and dsh still asked; from 1.3 the same setting would really auto-approve for them. It is not escalated silently: on the first 1.3 start, Cursor / OpenCode / dsh conversations saved in that mode go back to 每次询问 with a notice in the conversation, and if your default permission mode was 全部放行, new Cursor / OpenCode / dsh conversations keep starting in 每次询问; the first one shows a notice that the new mode exists, with a button to turn it on there. Claude Code, Codex, Copilot and Devin keep the mode, which already meant the same in 1.2. Choosing the default permission mode again in Settings ends this.
|
||||
- **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
|
||||
- **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). A block written without a language is detected by highlight.js (`highlightAuto`), coloured and labelled with what it found; while a reply streams, that happens as soon as the block's closing fence arrives (an open block stays plain "text" so its colours and label don't flip with every token), and results are cached so a closed block isn't detected again on every frame (1.3.7). Since 1.3.7 code blocks are drawn in the same pass as the Markdown, so a streaming reply no longer flickers; the Agent's Markdown is sanitized by DOMPurify with the HTML profile only (an `<svg>` the Agent writes is dropped), and the code block icons are added after sanitizing. 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
|
||||
@@ -104,7 +104,7 @@ The daemon can run Agents with full access to your machine, so the token that un
|
||||
- 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. Coming back to the page (`visibilitychange` → visible, or window focus) checks at once instead of waiting out the timers pushed back while hidden: if the child never said alive within 12 s of loading or its last real alive is older than 15 s, it gets 4 s (two heartbeats) to speak up before the same recovery runs; a child that answers is left alone. If a disconnect end state is showing, coming back counts as clicking Reconnect, also when the automatic tries are used up. 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.
|
||||
- **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. In Magpie's desktop window (`wails://localhost` on macOS / Linux, `http://wails.localhost` on Windows) there is no loopback `back`, and none is ever taken: the wrapper posts `{magpie: 1, method: "error"}` to the window instead, Magpie swaps the frame for its "This page stopped working" card at once, and its Try again builds a new frame on the Magpie page (fresh `session.js` → new gate → new daemon). 1.3.5 / 1.3.6 also took `http://wails.localhost` as `back` on Windows, but WebView2 doesn't route that request from a frame that is on `127.0.0.1` (Wails intercepts `wails.localhost` with the filter that skips out-of-process iframes), so the frame ended on WebView2's gray error page with nothing of ours left to recover. 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)
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+21
@@ -834,6 +834,26 @@ async function scriptBigReply(ctx) {
|
||||
}
|
||||
emit({ type: "assistant_message", itemId: "B1", text: acc });
|
||||
}
|
||||
async function scriptCodeStream(ctx) {
|
||||
const { emit } = ctx;
|
||||
let acc = "";
|
||||
const put = (p) => {
|
||||
acc += p;
|
||||
emit({ type: "assistant_delta", itemId: "C1", text: p });
|
||||
};
|
||||
put("\u5148\u770B\u7B2C\u4E00\u6BB5\u4EE3\u7801\uFF1A\n\n```ts\n");
|
||||
for (let b = 1; b <= 2; b++) {
|
||||
if (b === 2) put("```\n\n\u7136\u540E\u662F\u7B2C\u4E8C\u6BB5\uFF1A\n\n```ts\n");
|
||||
for (let k = 0; k < 22; k++) {
|
||||
if (ctx.interrupted()) return;
|
||||
put(`const block${b}_line${k} = computeSomethingRatherLong(${b}, ${k}, "a fairly long string literal so wrapping matters ${"x".repeat(60)}");
|
||||
`);
|
||||
await sleep(120);
|
||||
}
|
||||
}
|
||||
put("```\n\n\u5B8C\u6BD5\u3002");
|
||||
emit({ type: "assistant_message", itemId: "C1", text: acc });
|
||||
}
|
||||
async function scriptExit(_ctx) {
|
||||
await sleep(300);
|
||||
throw new MockCrash();
|
||||
@@ -849,6 +869,7 @@ function pickScript(text) {
|
||||
if (t.startsWith("/long")) return scriptLong;
|
||||
if (t.startsWith("/exit")) return scriptExit;
|
||||
if (t.startsWith("/bigreply")) return scriptBigReply;
|
||||
if (t.startsWith("/codestream")) return scriptCodeStream;
|
||||
if (t.startsWith("/serve")) return scriptServe;
|
||||
if (t.startsWith("/tools")) return scriptTools;
|
||||
if (t.startsWith("/bashhint")) return scriptBashHint;
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -405,6 +405,25 @@ async function scriptBigReply(ctx: Ctx): Promise<void> {
|
||||
emit({ type: "assistant_message", itemId: "B1", text: acc });
|
||||
}
|
||||
|
||||
// "/codestream" (1.3.7 flicker e2e): a reply whose fenced code blocks grow one line per delta, the way a real
|
||||
// Agent streams code (so a block is still open while the user clicks its wrap toggle), then a second block
|
||||
async function scriptCodeStream(ctx: Ctx): Promise<void> {
|
||||
const { emit } = ctx;
|
||||
let acc = "";
|
||||
const put = (p: string) => { acc += p; emit({ type: "assistant_delta", itemId: "C1", text: p }); };
|
||||
put("先看第一段代码:\n\n```ts\n");
|
||||
for (let b = 1; b <= 2; b++) {
|
||||
if (b === 2) put("```\n\n然后是第二段:\n\n```ts\n");
|
||||
for (let k = 0; k < 22; k++) {
|
||||
if (ctx.interrupted()) return;
|
||||
put(`const block${b}_line${k} = computeSomethingRatherLong(${b}, ${k}, "a fairly long string literal so wrapping matters ${"x".repeat(60)}");\n`);
|
||||
await sleep(120);
|
||||
}
|
||||
}
|
||||
put("```\n\n完毕。");
|
||||
emit({ type: "assistant_message", itemId: "C1", text: acc });
|
||||
}
|
||||
|
||||
async function scriptExit(_ctx: Ctx): Promise<void> {
|
||||
await sleep(300);
|
||||
throw new MockCrash();
|
||||
@@ -421,6 +440,7 @@ function pickScript(text: string): (ctx: Ctx) => Promise<void> {
|
||||
if (t.startsWith("/long")) return scriptLong;
|
||||
if (t.startsWith("/exit")) return scriptExit;
|
||||
if (t.startsWith("/bigreply")) return scriptBigReply;
|
||||
if (t.startsWith("/codestream")) return scriptCodeStream;
|
||||
if (t.startsWith("/serve")) return scriptServe;
|
||||
if (t.startsWith("/tools")) return scriptTools;
|
||||
if (t.startsWith("/bashhint")) return scriptBashHint;
|
||||
|
||||
@@ -64,22 +64,27 @@ export function failureHtml(error) {
|
||||
|
||||
/**
|
||||
* The Magpie plugin page boot.js came from (?back=), so the daemon page can go back through it after the plugin host restarts
|
||||
* (fresh session.js → new gate → new daemon). Only a Magpie plugin page on loopback (magpie web) or the Windows desktop
|
||||
* host (exact hostname wails.localhost) is accepted, so the daemon page can't be turned into an open redirect; it travels
|
||||
* in the 302's # fragment next to the token and never reaches a server.
|
||||
* (fresh session.js → new gate → new daemon). Only a Magpie plugin page on loopback (`magpie web`: 127.0.0.1, localhost,
|
||||
* [::1]) is accepted, so the daemon page can't be turned into an open redirect; it travels in the 302's # fragment next to
|
||||
* the token and never reaches a server.
|
||||
* Magpie's desktop window is never a back target, on any OS: wails://localhost (macOS / Linux) can't be navigated to from
|
||||
* this http page at all, and http://wails.localhost (Windows) only exists inside WebView2's request interception, which
|
||||
* Wails sets up with the plain AddWebResourceRequestedFilter (no request source kinds): it doesn't see requests from the
|
||||
* sandboxed plugin frame once that frame is on 127.0.0.1 (an out-of-process iframe), so the navigation goes to the real
|
||||
* network, fails, and leaves WebView2's own gray error page in the frame with none of our script to recover (1.3.5/1.3.6).
|
||||
* Without a back URL the wrapper asks Magpie to show its Try again card instead, which rebuilds the frame from the window.
|
||||
* Keep in sync with web/src/api/backToMagpie.ts and lib/wrapper.mjs SAFE_BACK_SRC.
|
||||
*/
|
||||
export function safeBackUrl(raw, platform = process.platform) {
|
||||
export function safeBackUrl(raw) {
|
||||
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
|
||||
let u;
|
||||
try { u = new URL(raw); } catch { return null; }
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (u.username || u.password) return null;
|
||||
const hostname = u.hostname.toLowerCase();
|
||||
// Exact hosts only: never evil-wails.localhost / wails.localhost.evil.com / 127.0.0.1.evil…
|
||||
// Exact loopback hosts only: never 127.0.0.1.evil… / wails.localhost (see above)
|
||||
const loopback = hostname === "127.0.0.1" || hostname === "localhost" || hostname === "[::1]";
|
||||
const magpieWin = platform === "win32" && hostname === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!loopback) 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}`;
|
||||
}
|
||||
|
||||
@@ -25,12 +25,14 @@
|
||||
//
|
||||
// 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 Magpie-page check as everywhere else (http(s) on loopback or exact
|
||||
// Windows desktop host wails.localhost, path /_magpie/plugin/<id>/(page/)?index.html, no credentials — no open redirect),
|
||||
// http://127.0.0.1:<integer port>/, b must pass the same Magpie-page check as everywhere else (http(s) on loopback only,
|
||||
// path /_magpie/plugin/<id>/(page/)?index.html, no credentials — no open redirect; never the desktop window's
|
||||
// wails://localhost or http://wails.localhost, which this frame can't navigate to: see gate.mjs safeBackUrl),
|
||||
// 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 */
|
||||
/** Same check as safeBackUrl in gate.mjs / web/src/api/backToMagpie.ts, as source for the page: loopback Magpie pages only
|
||||
* (magpie web). Never Magpie's desktop window (wails://localhost, http://wails.localhost): see gate.mjs safeBackUrl. */
|
||||
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; }
|
||||
@@ -38,9 +40,7 @@ const SAFE_BACK_SRC = String.raw`function safeBack(raw) {
|
||||
if (u.username || u.password) return null;
|
||||
var h = u.hostname.toLowerCase();
|
||||
var loopback = h === "127.0.0.1" || h === "localhost" || h === "[::1]";
|
||||
var magpieWin = /Windows/.test(typeof navigator !== "undefined" ? navigator.userAgent : "") &&
|
||||
h === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!loopback) 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;
|
||||
}`;
|
||||
@@ -61,8 +61,15 @@ const SCRIPT = String.raw`(function () {
|
||||
var token = frag.get("t") || "";
|
||||
var port = Number(frag.get("p"));
|
||||
var BACK_KEY = "ac_wrap_back";
|
||||
// A stored value that no longer passes safeBack (e.g. http://wails.localhost/… kept by 1.3.5 / 1.3.6) is never followed
|
||||
// and is dropped. (Inside Magpie's sandboxed frame this page has an opaque origin and sessionStorage throws: null.)
|
||||
function readStoredBack() {
|
||||
try { return safeBack(sessionStorage.getItem(BACK_KEY)); } catch (e) { return null; }
|
||||
try {
|
||||
var raw = sessionStorage.getItem(BACK_KEY);
|
||||
var v = safeBack(raw);
|
||||
if (raw && !v) sessionStorage.removeItem(BACK_KEY);
|
||||
return v;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
function writeStoredBack(v) {
|
||||
if (!v) return;
|
||||
@@ -88,8 +95,11 @@ const SCRIPT = String.raw`(function () {
|
||||
box.hidden = false;
|
||||
if (button) { btn.textContent = zh ? button[0] : button[1]; btn.hidden = false; }
|
||||
}
|
||||
// Ask Magpie's parent frame to show its native "Try again" card (pluginpages.js → broke → rebuild iframe).
|
||||
// Used when #b= is missing (e.g. macOS/Linux wails:// origin cannot navigate from this http gate page).
|
||||
// Ask Magpie's parent frame to show its native "Try again" card: pluginpages.js broke(key) → kernel.js fail() replaces
|
||||
// #view-<key>'s children (this frame included) with the card at once, and Try again runs open(key) again, a fresh
|
||||
// <iframe sandbox=allow-scripts> on the Magpie page URL → boot.js → fresh session.js → new gate /open → new daemon.
|
||||
// Used whenever there is no loopback #b=: always in Magpie's desktop window (wails://localhost on macOS / Linux,
|
||||
// http://wails.localhost on Windows, neither reachable from this http page).
|
||||
function askMagpieRetry(why) {
|
||||
if (window.parent === window) return false;
|
||||
try {
|
||||
@@ -104,7 +114,8 @@ const SCRIPT = String.raw`(function () {
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
if (targetBack) { location.replace(targetBack); return; }
|
||||
// Framed in Magpie: ask the host to rebuild the plugin iframe; if it does not unload us, fall back to reload.
|
||||
// Framed in Magpie: ask the host to rebuild the plugin iframe (Magpie removes this frame right away). The reload is
|
||||
// only a fallback for a parent that ignores the message; it reloads this same #t=/p= and doesn't get a new session.
|
||||
if (askMagpieRetry()) {
|
||||
setTimeout(function () { location.reload(); }, 300);
|
||||
} else {
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.7",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.6",
|
||||
"version": "1.3.7",
|
||||
"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",
|
||||
|
||||
@@ -13,7 +13,7 @@ import { parseCodexConfig } from "../../daemon/src/providers/codex/provider.js";
|
||||
import { mapNotification, newCodexMapState } from "../../daemon/src/providers/codex/map.js";
|
||||
import { costIsReal } from "../../daemon/src/providers/claude/map.js";
|
||||
import { setAppLocale as setLocale, tr } from "../../daemon/src/util/i18n.js";
|
||||
import { safeBackUrl as webSafeBackUrl, backUrlFromHash, backTarget, watchReconnect } from "../../web/src/api/backToMagpie.js";
|
||||
import { safeBackUrl as webSafeBackUrl, backUrlFromHash, backTarget, watchReconnect, askMagpieRetry } from "../../web/src/api/backToMagpie.js";
|
||||
import { resolveTheme, normalizeThemeSetting } from "../../web/src/layout/theme.js";
|
||||
import { parseArgsDraft, parseIdleDraft } from "../../web/src/components/settingsFields.js";
|
||||
|
||||
@@ -148,8 +148,9 @@ describe("self-heal back URL (host restart)", () => {
|
||||
[good + "#frag", good],
|
||||
["http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1", "http://localhost:3425/_magpie/plugin/abc/page/index.html?x=1"],
|
||||
["http://[::1]:3430/_magpie/plugin/abc/index.html", "http://[::1]:3430/_magpie/plugin/abc/index.html"],
|
||||
// Windows Magpie desktop (exact host only)
|
||||
["http://wails.localhost/_magpie/plugin/abc/index.html", "http://wails.localhost/_magpie/plugin/abc/index.html"],
|
||||
// Magpie's desktop window is never a back target (Windows WebView2 can't navigate a 127.0.0.1 frame there: gray error page)
|
||||
["http://wails.localhost/_magpie/plugin/abc/index.html", null],
|
||||
["http://wails.localhost/_magpie/plugin/abc/page/index.html", null],
|
||||
["https://wails.localhost/_magpie/plugin/abc/page/index.html?x=1", null],
|
||||
["http://wails.localhost:8080/_magpie/plugin/a/index.html", null],
|
||||
["https://localhost:4430/_magpie/plugin/a/index.html", "https://localhost:4430/_magpie/plugin/a/index.html"],
|
||||
@@ -169,21 +170,44 @@ describe("self-heal back URL (host restart)", () => {
|
||||
["http://127.0.0.1:3430/_magpie/plugin/abc/evil.html", null],
|
||||
["", null],
|
||||
];
|
||||
it("web and gate accept only Magpie plugin pages on loopback or exact wails.localhost", async () => {
|
||||
it("web and gate accept only Magpie plugin pages on loopback", async () => {
|
||||
const { safeBackUrl } = await import(/* @vite-ignore */ gateUrl);
|
||||
for (const [input, want] of cases) {
|
||||
expect(webSafeBackUrl(input, "Windows NT 10.0"), input).toBe(want);
|
||||
expect(safeBackUrl(input, "win32"), input).toBe(want);
|
||||
expect(webSafeBackUrl(input), input).toBe(want);
|
||||
expect(safeBackUrl(input), input).toBe(want);
|
||||
}
|
||||
});
|
||||
it("rejects Windows virtual host on non-Windows, including the default platform / UA", async () => {
|
||||
it("rejects the Windows desktop host wails.localhost on every platform (1.3.5 / 1.3.6 took it on Windows)", async () => {
|
||||
const { safeBackUrl } = await import(/* @vite-ignore */ gateUrl);
|
||||
const win = "http://wails.localhost/_magpie/plugin/a/page/index.html";
|
||||
for (const os of ["linux", "darwin"]) expect(safeBackUrl(win, os)).toBeNull();
|
||||
for (const ua of ["Macintosh", "X11; Linux x86_64", ""]) expect(webSafeBackUrl(win, ua)).toBeNull();
|
||||
expect(safeBackUrl(win)).toBe(process.platform === "win32" ? win : null);
|
||||
const isWindows = /Windows/.test(typeof navigator !== "undefined" ? navigator.userAgent : "");
|
||||
expect(webSafeBackUrl(win)).toBe(isWindows ? win : null);
|
||||
// an extra platform / UA argument (the 1.3.5 signature) changes nothing
|
||||
for (const os of ["win32", "linux", "darwin"]) expect((safeBackUrl as (r: string, p: string) => unknown)(win, os)).toBeNull();
|
||||
for (const ua of ["Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Macintosh", "X11; Linux x86_64", ""]) {
|
||||
expect((webSafeBackUrl as (r: string, u: string) => unknown)(win, ua)).toBeNull();
|
||||
}
|
||||
expect(safeBackUrl(win)).toBeNull();
|
||||
expect(webSafeBackUrl(win)).toBeNull();
|
||||
expect(backUrlFromHash(`#t=abc&b=${encodeURIComponent(win)}`)).toBeNull();
|
||||
expect(backTarget(`#t=x&b=${encodeURIComponent(win)}`, 1234)).toBeNull();
|
||||
});
|
||||
it("unwrapped daemon page without a back URL asks a framing Magpie for Try again, and does nothing top-level", () => {
|
||||
const g = globalThis as unknown as { window?: unknown };
|
||||
const had = "window" in g, prev = g.window;
|
||||
try {
|
||||
const posted: unknown[] = [];
|
||||
const parent = { postMessage: (d: unknown) => posted.push(d) };
|
||||
g.window = { parent };
|
||||
expect(askMagpieRetry("本地服务已断开")).toBe(true);
|
||||
expect(posted).toEqual([{ magpie: 1, method: "error", params: { message: "本地服务已断开" } }]);
|
||||
const top: Record<string, unknown> = {};
|
||||
top.parent = top;
|
||||
g.window = top;
|
||||
expect(askMagpieRetry("x")).toBe(false);
|
||||
delete g.window;
|
||||
expect(askMagpieRetry("x")).toBe(false);
|
||||
} finally {
|
||||
if (had) g.window = prev; else delete g.window;
|
||||
}
|
||||
});
|
||||
it("reads b= from the fragment next to the token", () => {
|
||||
expect(backUrlFromHash(`#t=abc&b=${encodeURIComponent(good)}`)).toBe(good);
|
||||
@@ -214,8 +238,8 @@ describe("self-heal back URL (host restart)", () => {
|
||||
const wails = "http://wails.localhost/_magpie/plugin/tok123/index.html";
|
||||
const win = await request(port, `/open?k=${key}&back=${encodeURIComponent(wails)}`);
|
||||
expect(win.status).toBe(302);
|
||||
expect(win.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}` +
|
||||
(process.platform === "win32" ? `&b=${encodeURIComponent(wails)}` : ""));
|
||||
// never forwarded, on any OS: the wrapper asks Magpie for its Try again card instead
|
||||
expect(win.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`);
|
||||
const lookalike = await request(port, `/open?k=${key}&back=${encodeURIComponent("http://evil-wails.localhost/_magpie/plugin/tok/index.html")}`);
|
||||
expect(lookalike.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`);
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn } from "node:child_process";
|
||||
import { chromium } from "playwright-core";
|
||||
// @ts-expect-error mjs helper
|
||||
import { findBrowser } from "../../scripts/browser-path.mjs";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const browserPath: string | null = findBrowser();
|
||||
|
||||
describe.skipIf(!browserPath)("Chat streaming markdown flicker in real Chromium (1.3.7)", () => {
|
||||
it("streams multi-code-block replies with no bare <pre> frames, no height collapse, sticky bottom, wrap persist, XSS safe", async () => {
|
||||
const xdg = mkdtempSync(join(tmpdir(), "ac-flicker-xdg-"));
|
||||
const projDir = mkdtempSync(join(tmpdir(), "ac-flicker-proj-"));
|
||||
const dataDir = join(xdg, "magpie", "agent-console");
|
||||
const projectId = "p_flicker1";
|
||||
const threadId = "t_flicker1";
|
||||
mkdirSync(join(dataDir, "threads", threadId), { recursive: true });
|
||||
const now = Date.now();
|
||||
writeFileSync(join(dataDir, "settings.json"), JSON.stringify({
|
||||
v1Migrated: true, theme: "dark", lastProjectId: projectId, lastThreadId: threadId,
|
||||
}));
|
||||
writeFileSync(join(dataDir, "projects.json"), JSON.stringify([
|
||||
{ id: projectId, name: "flicker", path: projDir, createdAt: now },
|
||||
]));
|
||||
writeFileSync(join(dataDir, "threads", threadId, "meta.json"), JSON.stringify({
|
||||
id: threadId, projectId, title: "stream flicker", titleAuto: false, provider: "mock", model: null,
|
||||
mode: "bypassPermissions", effort: "high", providerSessionId: null, status: "idle", pinned: false,
|
||||
archived: false, createdAt: now - 1000, updatedAt: now, lastTurnStatus: "completed",
|
||||
usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, costUsd: 0 }, seq: 0,
|
||||
}));
|
||||
writeFileSync(join(dataDir, "threads", threadId, "timeline.jsonl"), "");
|
||||
|
||||
const port = 35700 + Math.floor(Math.random() * 400);
|
||||
const daemon = spawn(process.execPath, [join(root, "daemon/dist/main.js"), "--port", String(port), "--data", xdg], {
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const launchArgs = process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [];
|
||||
const browser = await chromium.launch({ executablePath: browserPath!, headless: true, args: launchArgs });
|
||||
try {
|
||||
let token = "";
|
||||
const readyDeadline = Date.now() + 12000;
|
||||
while (Date.now() < readyDeadline) {
|
||||
try {
|
||||
const dj = JSON.parse(readFileSync(join(dataDir, "daemon.json"), "utf8"));
|
||||
if (dj.token) { token = dj.token; break; }
|
||||
} catch {}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
expect(token.length).toBeGreaterThan(0);
|
||||
|
||||
const page = await browser.newPage({ viewport: { width: 920, height: 860 } });
|
||||
await page.goto(`http://127.0.0.1:${port}/?lang=zh#t=${encodeURIComponent(token)}`, { waitUntil: "domcontentloaded" });
|
||||
await page.waitForSelector(".cp-ta", { timeout: 10000 });
|
||||
await page.waitForTimeout(250);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as { __flicker: Record<string, unknown> };
|
||||
w.__flicker = {
|
||||
barePreFrames: 0,
|
||||
heightDrops: 0,
|
||||
maxDrop: 0,
|
||||
lastH: 0,
|
||||
gapMax: 0,
|
||||
samples: 0,
|
||||
stop: false,
|
||||
};
|
||||
const f = w.__flicker as {
|
||||
barePreFrames: number; heightDrops: number; maxDrop: number; lastH: number;
|
||||
gapMax: number; samples: number; stop: boolean;
|
||||
};
|
||||
const sample = () => {
|
||||
if (f.stop) return;
|
||||
f.samples++;
|
||||
const md = document.querySelector(".md.streaming") || document.querySelector(".as .md");
|
||||
const scroll = document.querySelector(".scroll") as HTMLElement | null;
|
||||
if (md) {
|
||||
let bare = 0;
|
||||
for (const pre of md.querySelectorAll("pre")) if (!pre.closest(".cb")) bare++;
|
||||
if (bare > 0) f.barePreFrames++;
|
||||
const h = (md as HTMLElement).scrollHeight;
|
||||
if (f.lastH > 0 && h < f.lastH - 2) {
|
||||
f.heightDrops++;
|
||||
f.maxDrop = Math.max(f.maxDrop, f.lastH - h);
|
||||
}
|
||||
f.lastH = h;
|
||||
}
|
||||
if (scroll) {
|
||||
const gap = scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight;
|
||||
if (gap > f.gapMax) f.gapMax = gap;
|
||||
}
|
||||
requestAnimationFrame(sample);
|
||||
};
|
||||
// Also catch bare <pre> between React commit and paint via MutationObserver
|
||||
const mo = new MutationObserver(() => {
|
||||
const md = document.querySelector(".md.streaming") || document.querySelector(".as .md");
|
||||
if (!md) return;
|
||||
for (const pre of md.querySelectorAll("pre")) {
|
||||
if (!pre.closest(".cb")) f.barePreFrames++;
|
||||
}
|
||||
});
|
||||
mo.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
|
||||
(w.__flicker as { mo: MutationObserver }).mo = mo;
|
||||
requestAnimationFrame(sample);
|
||||
});
|
||||
|
||||
await page.locator(".cp-ta").fill("/bigreply slow");
|
||||
await page.keyboard.press("Enter");
|
||||
// Wait until a few code blocks exist, then toggle wrap on the first one mid-stream
|
||||
await page.waitForFunction(() => document.querySelectorAll(".as .md .cb").length >= 3, null, { timeout: 15000 });
|
||||
await page.locator(".as .md .cb").first().locator(".cb-wrap").click();
|
||||
expect(await page.locator(".as .md .cb").first().evaluate((el) => el.classList.contains("wrap"))).toBe(true);
|
||||
|
||||
await page.getByText("第 14 部分", { exact: false }).waitFor({ timeout: 20000 });
|
||||
await page.waitForTimeout(600);
|
||||
|
||||
const result = await page.evaluate(() => {
|
||||
const w = window as unknown as { __flicker: {
|
||||
barePreFrames: number; heightDrops: number; maxDrop: number; gapMax: number;
|
||||
samples: number; stop: boolean; mo?: MutationObserver;
|
||||
} };
|
||||
w.__flicker.stop = true;
|
||||
w.__flicker.mo?.disconnect();
|
||||
const md = document.querySelector(".as .md");
|
||||
const scroll = document.querySelector(".scroll") as HTMLElement | null;
|
||||
const first = md?.querySelector(".cb");
|
||||
return {
|
||||
barePreFrames: w.__flicker.barePreFrames,
|
||||
heightDrops: w.__flicker.heightDrops,
|
||||
maxDrop: w.__flicker.maxDrop,
|
||||
gapMax: w.__flicker.gapMax,
|
||||
samples: w.__flicker.samples,
|
||||
finalCbs: md ? md.querySelectorAll(".cb").length : 0,
|
||||
finalBare: md ? [...md.querySelectorAll("pre")].filter((p) => !p.closest(".cb")).length : -1,
|
||||
finalGap: scroll ? scroll.scrollHeight - scroll.scrollTop - scroll.clientHeight : -1,
|
||||
wrapStillOn: first ? first.classList.contains("wrap") : false,
|
||||
hasCbHead: md ? md.querySelectorAll(".cb-head").length : 0,
|
||||
};
|
||||
});
|
||||
|
||||
expect(result.samples).toBeGreaterThan(50);
|
||||
expect(result.finalCbs).toBeGreaterThanOrEqual(14);
|
||||
expect(result.hasCbHead).toBe(result.finalCbs);
|
||||
expect(result.finalBare).toBe(0);
|
||||
// Primary flicker: React used to paint bare <pre> then decorate to .cb after paint
|
||||
expect(result.barePreFrames).toBe(0);
|
||||
// Large collapses were the decorate flash (baseline ~169px); tiny markdown-structure
|
||||
// reflows at the streaming tip (~one line) are unrelated and still allowed
|
||||
expect(result.maxDrop).toBeLessThan(40);
|
||||
expect(result.finalGap).toBeLessThanOrEqual(2);
|
||||
// Stick may lag a frame while the virtualizer remeasures; never leave the bottom for long
|
||||
expect(result.gapMax).toBeLessThanOrEqual(120);
|
||||
expect(result.wrapStillOn).toBe(true);
|
||||
|
||||
// Copy button present and wired (clipboard may be denied in headless — just ensure click doesn't throw)
|
||||
await page.locator(".as .md .cb").first().locator(".cb-copy").click();
|
||||
|
||||
// XSS: finished assistant markdown must not execute markup (DOMPurify + escaped fences)
|
||||
// Finished assistant markdown via the timeline store (window.__tl from main.tsx)
|
||||
const liveXss = await page.evaluate(async () => {
|
||||
type R = { ok: boolean; xss: boolean; bareImg: boolean; script: boolean; cb: number };
|
||||
const useTl = (window as unknown as { __tl?: { setState: (p: unknown) => void } }).__tl;
|
||||
if (!useTl) return { ok: false, xss: true, bareImg: true, script: true, cb: 0 } satisfies R;
|
||||
const evil = "hello\n\n```html\n<img src=x onerror=window.__xssLive=1>\n<script>window.__xssLive=1</script>\n```\n\n<img src=x onerror=window.__xssLive=1>\n<script>window.__xssLive=1</script>";
|
||||
useTl.setState({
|
||||
items: [{ kind: "assistant", key: "xss1", itemId: "xss1", text: evil, streaming: false }],
|
||||
status: "idle",
|
||||
pending: [],
|
||||
queue: [],
|
||||
error: null,
|
||||
});
|
||||
await new Promise((r) => requestAnimationFrame(() => setTimeout(r, 120)));
|
||||
const md = document.querySelector(".as .md") || document.querySelector(".md");
|
||||
return {
|
||||
ok: true,
|
||||
xss: Boolean((window as unknown as { __xssLive?: boolean }).__xssLive),
|
||||
bareImg: md ? md.querySelectorAll("img").length > 0 : false,
|
||||
script: md ? md.querySelectorAll("script").length > 0 : false,
|
||||
cb: md ? md.querySelectorAll(".cb").length : 0,
|
||||
} satisfies R;
|
||||
});
|
||||
expect(liveXss.ok).toBe(true);
|
||||
expect(liveXss.xss).toBe(false);
|
||||
expect(liveXss.bareImg).toBe(false);
|
||||
expect(liveXss.script).toBe(false);
|
||||
expect(liveXss.cb).toBeGreaterThanOrEqual(1);
|
||||
} finally {
|
||||
await browser.close();
|
||||
daemon.kill("SIGTERM");
|
||||
rmSync(xdg, { recursive: true, force: true });
|
||||
rmSync(projDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
it("a growing code block keeps its wrap toggle, the stuck bottom never bounces 16px, and the shell doesn't re-render per token", async () => {
|
||||
const xdg = mkdtempSync(join(tmpdir(), "ac-flicker2-xdg-"));
|
||||
const projDir = mkdtempSync(join(tmpdir(), "ac-flicker2-proj-"));
|
||||
const dataDir = join(xdg, "magpie", "agent-console");
|
||||
const projectId = "p_flicker2";
|
||||
const threadId = "t_flicker2";
|
||||
mkdirSync(join(dataDir, "threads", threadId), { recursive: true });
|
||||
const now = Date.now();
|
||||
writeFileSync(join(dataDir, "settings.json"), JSON.stringify({
|
||||
v1Migrated: true, theme: "dark", lastProjectId: projectId, lastThreadId: threadId,
|
||||
}));
|
||||
writeFileSync(join(dataDir, "projects.json"), JSON.stringify([
|
||||
{ id: projectId, name: "flicker2", path: projDir, createdAt: now },
|
||||
]));
|
||||
writeFileSync(join(dataDir, "threads", threadId, "meta.json"), JSON.stringify({
|
||||
id: threadId, projectId, title: "stream flicker 2", titleAuto: false, provider: "mock", model: null,
|
||||
mode: "bypassPermissions", effort: "high", providerSessionId: null, status: "idle", pinned: false,
|
||||
archived: false, createdAt: now - 1000, updatedAt: now, lastTurnStatus: "completed",
|
||||
usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, costUsd: 0 }, seq: 0,
|
||||
}));
|
||||
writeFileSync(join(dataDir, "threads", threadId, "timeline.jsonl"), "");
|
||||
|
||||
const port = 36100 + Math.floor(Math.random() * 400);
|
||||
const daemon = spawn(process.execPath, [join(root, "daemon/dist/main.js"), "--port", String(port), "--data", xdg], {
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const launchArgs = process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [];
|
||||
const browser = await chromium.launch({ executablePath: browserPath!, headless: true, args: launchArgs });
|
||||
try {
|
||||
let token = "";
|
||||
const readyDeadline = Date.now() + 12000;
|
||||
while (Date.now() < readyDeadline) {
|
||||
try {
|
||||
const dj = JSON.parse(readFileSync(join(dataDir, "daemon.json"), "utf8"));
|
||||
if (dj.token) { token = dj.token; break; }
|
||||
} catch {}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
expect(token.length).toBeGreaterThan(0);
|
||||
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 860 } });
|
||||
// A minimal DevTools hook: React reports every commit, which lets the page count component renders
|
||||
await page.addInitScript(() => {
|
||||
const w = window as unknown as Record<string, unknown>;
|
||||
w.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
|
||||
supportsFiber: true, isDisabled: false, renderers: new Map(), inject: () => 1, checkDCE() {},
|
||||
onCommitFiberRoot: () => { w.__lastCommit = performance.now(); (w.__onCommit as (() => void) | undefined)?.(); },
|
||||
onCommitFiberUnmount() {}, onPostCommitFiberRoot() {},
|
||||
};
|
||||
// Requests still waiting for their response (boot calls like providers.list land late and re-render App)
|
||||
const open = new Set<unknown>();
|
||||
w.__openReqs = open;
|
||||
const OW = window.WebSocket;
|
||||
window.WebSocket = class extends OW {
|
||||
constructor(...a: ConstructorParameters<typeof WebSocket>) {
|
||||
super(...a);
|
||||
this.addEventListener("message", (e) => {
|
||||
try { const m = JSON.parse(String(e.data)); if (m.t === "res") open.delete(m.id); } catch {}
|
||||
});
|
||||
}
|
||||
send(data: Parameters<WebSocket["send"]>[0]) {
|
||||
try { const m = JSON.parse(String(data)); if (m.t === "req") open.add(m.id); } catch {}
|
||||
super.send(data);
|
||||
}
|
||||
};
|
||||
});
|
||||
await page.goto(`http://127.0.0.1:${port}/?lang=zh#t=${encodeURIComponent(token)}`, { waitUntil: "domcontentloaded" });
|
||||
await page.waitForSelector(".composer .cp-ta", { timeout: 10000 });
|
||||
|
||||
await page.evaluate(() => {
|
||||
type Fiber = { tag: number; return: Fiber | null; alternate: Fiber | null; memoizedState: unknown };
|
||||
const w = window as unknown as Record<string, unknown>;
|
||||
const fiberOf = (el: Element | null): Fiber | null => {
|
||||
if (!el) return null;
|
||||
const k = Object.keys(el).find((x) => x.startsWith("__reactFiber$"));
|
||||
return k ? (el as unknown as Record<string, Fiber>)[k]! : null;
|
||||
};
|
||||
// nearest function / memo / forwardRef component above a host fiber
|
||||
const fnAbove = (f: Fiber | null): Fiber | null => {
|
||||
while (f && ![0, 11, 14, 15].includes(f.tag)) f = f.return;
|
||||
return f;
|
||||
};
|
||||
// A render gives a function component a fresh hook list (memoizedState); a skipped one keeps it
|
||||
const T: Record<string, { f: Fiber; seen: Set<unknown>; n: number; at: number[] }> = {};
|
||||
const track = (name: string, f: Fiber | null) => {
|
||||
if (f) T[name] = { f, seen: new Set([f.memoizedState, f.alternate?.memoizedState]), n: 0, at: [] };
|
||||
};
|
||||
const layout = fnAbove(fiberOf(document.querySelector(".app")));
|
||||
track("Layout", layout);
|
||||
track("App", fnAbove(layout?.return ?? null));
|
||||
track("Sidebar", fnAbove(fiberOf(document.querySelector(".sidebar > *"))));
|
||||
track("Topbar", fnAbove(fiberOf(document.querySelector(".topbar"))));
|
||||
track("Panel", fnAbove(fiberOf(document.querySelector(".panel > *"))));
|
||||
track("Composer", fnAbove(fiberOf(document.querySelector(".composer"))));
|
||||
w.__renders = T;
|
||||
w.__onCommit = () => {
|
||||
for (const t of Object.values(T)) {
|
||||
for (const st of [t.f.memoizedState, t.f.alternate?.memoizedState]) {
|
||||
if (st && !t.seen.has(st)) { t.seen.add(st); t.n++; t.at.push(performance.now()); }
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
// Let the late boot responses (providers.list, settings) land before measuring
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as unknown as { __openReqs: Set<unknown>; __lastCommit?: number };
|
||||
return w.__openReqs.size === 0 && performance.now() - (w.__lastCommit ?? 0) > 600;
|
||||
}, null, { timeout: 15000, polling: 100 });
|
||||
const tracked = await page.evaluate(() => Object.keys((window as unknown as { __renders: object }).__renders).sort());
|
||||
expect(tracked).toEqual(["App", "Composer", "Layout", "Panel", "Sidebar", "Topbar"]);
|
||||
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as { __f2: Record<string, unknown> };
|
||||
const f = {
|
||||
stop: false, barePreFrames: 0, endD: [] as number[], wrapLost: 0, clicked: false, frames: 0,
|
||||
sbMut: 0, tbMut: 0,
|
||||
};
|
||||
w.__f2 = f as unknown as Record<string, unknown>;
|
||||
new MutationObserver((m) => { f.sbMut += m.filter((x) => x.type === "childList").length; })
|
||||
.observe(document.querySelector(".sidebar")!, { subtree: true, childList: true });
|
||||
new MutationObserver((m) => { f.tbMut += m.filter((x) => x.type === "childList").length; })
|
||||
.observe(document.querySelector(".topbar")!, { subtree: true, childList: true });
|
||||
// Distance from the streaming row's content to the scroller's bottom edge, while stuck and overflowing
|
||||
const measure = () => {
|
||||
const s = document.querySelector(".scroll") as HTMLElement | null;
|
||||
const md = document.querySelector(".md.streaming");
|
||||
if (!s || !md || s.scrollTop <= 0) return;
|
||||
const rows = [...s.querySelectorAll<HTMLElement>("[data-index]")];
|
||||
const last = rows.reduce<HTMLElement | null>((a, b) => (!a || +b.dataset.index! > +a.dataset.index! ? b : a), null);
|
||||
if (!last || !last.contains(md)) return;
|
||||
const inner = (last.firstElementChild as HTMLElement | null) ?? last;
|
||||
f.endD.push(Math.round(s.getBoundingClientRect().bottom - inner.getBoundingClientRect().bottom));
|
||||
for (const pre of md.querySelectorAll("pre")) if (!pre.closest(".cb")) f.barePreFrames++;
|
||||
if (f.clicked && !md.querySelector(".cb")?.classList.contains("wrap")) f.wrapLost++;
|
||||
};
|
||||
const loop = () => {
|
||||
if (f.stop) return;
|
||||
f.frames++;
|
||||
// Frame end: a ResizeObserver created now delivers its first callback in this frame's RO step, after the
|
||||
// app's own observers (virtualizer remeasure, stick-to-bottom) — the layout that is about to be painted
|
||||
const ro = new ResizeObserver(() => { ro.disconnect(); measure(); });
|
||||
ro.observe(document.body);
|
||||
requestAnimationFrame(loop);
|
||||
};
|
||||
requestAnimationFrame(loop);
|
||||
});
|
||||
|
||||
await page.locator(".cp-ta").fill("/codestream");
|
||||
await page.keyboard.press("Enter");
|
||||
// First block still open and growing: toggle its wrap mid-stream (in-page: Playwright's click waits for a
|
||||
// stable element, which a growing block never is)
|
||||
await page.waitForFunction(() => (document.querySelector(".md.streaming .cb")?.querySelectorAll(".cb-l").length ?? 0) >= 4, null, { timeout: 15000 });
|
||||
const atClick = await page.evaluate(() => {
|
||||
const cb = document.querySelector(".md.streaming .cb")!;
|
||||
cb.querySelector(".cb-wrap")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
(window as unknown as { __f2: { clicked: boolean } }).__f2.clicked = true;
|
||||
return { lines: cb.querySelectorAll(".cb-l").length, blocks: document.querySelectorAll(".md.streaming .cb").length };
|
||||
});
|
||||
expect(atClick.blocks).toBe(1);
|
||||
|
||||
// Mid-stream window: the shell's nodes and render counts
|
||||
const base = await page.evaluate(() => {
|
||||
const w = window as unknown as { __renders: Record<string, { n: number }>; __f2: Record<string, unknown>; __shell: Element[] };
|
||||
w.__shell = [document.querySelector(".sidebar")!, ...document.querySelector(".sidebar")!.children,
|
||||
document.querySelector(".topbar")!, ...document.querySelector(".topbar")!.children];
|
||||
w.__f2.sbMut = 0; w.__f2.tbMut = 0;
|
||||
return { t: performance.now(), lines: document.querySelector(".md.streaming .cb")!.querySelectorAll(".cb-l").length,
|
||||
n: Object.fromEntries(Object.entries(w.__renders).map(([k, v]) => [k, v.n])) };
|
||||
});
|
||||
await page.waitForFunction(() => (document.querySelectorAll(".md.streaming .cb")[1]?.querySelectorAll(".cb-l").length ?? 0) >= 10, null, { timeout: 20000 });
|
||||
const mid = await page.evaluate((b) => {
|
||||
const w = window as unknown as { __renders: Record<string, { n: number }>; __f2: { sbMut: number; tbMut: number }; __shell: Element[] };
|
||||
const cbs = document.querySelectorAll(".md.streaming .cb");
|
||||
return {
|
||||
seconds: (performance.now() - b.t) / 1000,
|
||||
linesAdded: cbs[0]!.querySelectorAll(".cb-l").length - b.lines + cbs[1]!.querySelectorAll(".cb-l").length,
|
||||
renders: Object.fromEntries(Object.entries(w.__renders).map(([k, v]) => [k, v.n - b.n[k]!])),
|
||||
shellKept: w.__shell.every((el) => el.isConnected),
|
||||
sbMut: w.__f2.sbMut,
|
||||
tbMut: w.__f2.tbMut,
|
||||
};
|
||||
}, base);
|
||||
expect(mid.linesAdded).toBeGreaterThanOrEqual(20);
|
||||
// Streamed tokens never reach the three-column shell (1.3.6: App re-rendered Layout/Sidebar/Topbar/Panel per delta)
|
||||
expect(mid.renders.App).toBe(0);
|
||||
expect(mid.renders.Layout).toBe(0);
|
||||
expect(mid.renders.Sidebar).toBe(0);
|
||||
expect(mid.renders.Panel).toBe(0);
|
||||
// Topbar and Composer only tick their 1 Hz running clocks (1.3.6: every delta re-rendered both)
|
||||
expect(mid.renders.Topbar).toBeLessThanOrEqual(Math.ceil(mid.seconds) + 1);
|
||||
expect(mid.renders.Composer).toBeLessThanOrEqual(Math.ceil(mid.seconds) + 1);
|
||||
expect(mid.renders.Composer).toBeLessThan(mid.linesAdded / 2);
|
||||
expect(mid.shellKept).toBe(true);
|
||||
expect(mid.sbMut).toBe(0);
|
||||
expect(mid.tbMut).toBe(0);
|
||||
|
||||
await page.waitForFunction(() => !document.querySelector(".md.streaming"), null, { timeout: 20000 });
|
||||
await page.waitForTimeout(300);
|
||||
const result = await page.evaluate(() => {
|
||||
const w = window as unknown as { __f2: { stop: boolean; barePreFrames: number; endD: number[]; wrapLost: number; frames: number } };
|
||||
w.__f2.stop = true;
|
||||
const cbs = [...document.querySelectorAll(".as .md .cb")];
|
||||
let bounces = 0;
|
||||
const d = w.__f2.endD;
|
||||
for (let i = 1; i < d.length; i++) if (Math.abs(d[i]! - d[i - 1]!) >= 8) bounces++;
|
||||
return {
|
||||
frames: w.__f2.frames, samples: d.length, min: Math.min(...d), max: Math.max(...d), bounces,
|
||||
barePreFrames: w.__f2.barePreFrames, wrapLost: w.__f2.wrapLost,
|
||||
blocks: cbs.length,
|
||||
firstWrap: cbs[0]?.classList.contains("wrap"), firstPressed: cbs[0]?.querySelector(".cb-wrap")?.getAttribute("aria-pressed"),
|
||||
firstLines: cbs[0]?.querySelectorAll(".cb-l").length ?? 0,
|
||||
secondWrap: cbs[1]?.classList.contains("wrap"),
|
||||
};
|
||||
});
|
||||
expect(result.blocks).toBe(2);
|
||||
// The toggled block kept growing after the click and stayed wrapped on every frame to the end
|
||||
expect(result.firstLines).toBeGreaterThan(atClick.lines);
|
||||
expect(result.firstLines).toBe(22);
|
||||
expect(result.firstWrap).toBe(true);
|
||||
expect(result.firstPressed).toBe("true");
|
||||
expect(result.wrapLost).toBe(0);
|
||||
expect(result.secondWrap).toBe(false);
|
||||
expect(result.barePreFrames).toBe(0);
|
||||
// Stuck to the bottom with the list's 16px gap on every painted frame (1.3.6 alternated 4px ↔ 20px per line)
|
||||
expect(result.samples).toBeGreaterThan(60);
|
||||
expect(result.max - result.min).toBeLessThanOrEqual(2);
|
||||
expect(result.bounces).toBe(0);
|
||||
} finally {
|
||||
await browser.close();
|
||||
daemon.kill("SIGTERM");
|
||||
rmSync(xdg, { recursive: true, force: true });
|
||||
rmSync(projDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 60000);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
// renderMarkdown (web/src/util/renderMarkdown.ts) in real Chromium: DOMPurify needs a DOM, so the module is bundled
|
||||
// with esbuild and run in a page. Pins the 1.3.7 review points: unlabelled fences are auto-detected again once
|
||||
// closed / settled (an open fence of a streaming message stays "text"), the model's <svg> is dropped (html profile
|
||||
// only), and the code block buttons still get their icons in the same pass.
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as esbuild from "esbuild";
|
||||
import { chromium } from "playwright-core";
|
||||
// @ts-expect-error mjs helper
|
||||
import { findBrowser } from "../../scripts/browser-path.mjs";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "../..");
|
||||
const browserPath: string | null = findBrowser();
|
||||
|
||||
type Block = { lang: string; codeClass: string; hl: number; btnSvgs: number[]; dataI: string | null; pressed: string | null };
|
||||
type Out = { blocks: Block[]; svgOutsideButtons: number; circles: number; onload: number; html: string; pwned: unknown };
|
||||
|
||||
describe.skipIf(!browserPath)("renderMarkdown in real Chromium (1.3.7 review)", () => {
|
||||
it("auto-detects closed / settled unlabelled fences, keeps an open streaming fence plain, strips model <svg>", async () => {
|
||||
const bundle = await esbuild.build({
|
||||
entryPoints: [join(root, "web/src/util/renderMarkdown.ts")],
|
||||
absWorkingDir: root,
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "iife",
|
||||
globalName: "AC_MD",
|
||||
platform: "browser",
|
||||
target: "es2020",
|
||||
define: { "process.env.NODE_ENV": '"production"' },
|
||||
logLevel: "silent",
|
||||
});
|
||||
const code = bundle.outputFiles[0]!.text;
|
||||
const launchArgs = process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [];
|
||||
const browser = await chromium.launch({ executablePath: browserPath!, headless: true, args: launchArgs });
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.setContent("<!doctype html><html><body><div id=root></div></body></html>");
|
||||
await page.addScriptTag({ content: code });
|
||||
const render = (md: string, streaming: boolean, wrapped: number[] = []) =>
|
||||
page.evaluate(({ md, streaming, wrapped }) => {
|
||||
const w = window as unknown as { AC_MD: { renderMarkdown: (t: string, o: object) => { html: string } }; __pwned?: unknown };
|
||||
const { html } = w.AC_MD.renderMarkdown(md, { streaming, wrapped: new Set(wrapped) });
|
||||
const el = document.getElementById("root")!;
|
||||
el.innerHTML = html;
|
||||
const blocks = [...el.querySelectorAll(".cb")].map((cb) => ({
|
||||
lang: cb.querySelector(".cb-lang")?.textContent ?? "",
|
||||
codeClass: cb.querySelector("pre > code")?.className ?? "",
|
||||
hl: cb.querySelectorAll("pre [class^='hljs-']").length,
|
||||
btnSvgs: [...cb.querySelectorAll(".cb-btn")].map((b) => b.querySelectorAll(":scope > svg > path[d]").length),
|
||||
dataI: cb.querySelector(".cb-copy")?.getAttribute("data-i") ?? null,
|
||||
pressed: cb.querySelector(".cb-wrap")?.getAttribute("aria-pressed") ?? null,
|
||||
}));
|
||||
const svgOutsideButtons = [...el.querySelectorAll("svg")].filter((s) => !s.closest(".cb-btn")).length;
|
||||
return {
|
||||
blocks,
|
||||
svgOutsideButtons,
|
||||
circles: el.querySelectorAll("circle").length,
|
||||
onload: el.querySelectorAll("[onload]").length,
|
||||
html,
|
||||
pwned: w.__pwned,
|
||||
};
|
||||
}, { md, streaming, wrapped }) as Promise<Out>;
|
||||
|
||||
const py = "def greet(name):\n return f\"hi {name}\"\n\nclass A:\n pass";
|
||||
const closed = "```\n" + py + "\n```\n";
|
||||
const open = "```\n" + py + "\n";
|
||||
|
||||
// settled message: unlabelled fence → highlightAuto + detected label (as 1.3.6)
|
||||
let r = await render("intro\n\n" + closed + "\ndone", false);
|
||||
expect(r.blocks).toHaveLength(1);
|
||||
expect(r.blocks[0]!.lang).toBe("python");
|
||||
expect(r.blocks[0]!.codeClass).toBe("hljs language-python");
|
||||
expect(r.blocks[0]!.hl).toBeGreaterThan(0);
|
||||
|
||||
// streaming, the fence is still open at the end: plain "text", no colours (no flip-flop while it grows)
|
||||
r = await render("intro\n\n" + open, true);
|
||||
expect(r.blocks[0]!.lang).toBe("text");
|
||||
expect(r.blocks[0]!.codeClass).toBe("hljs");
|
||||
expect(r.blocks[0]!.hl).toBe(0);
|
||||
// ...also every prefix of it while tokens arrive
|
||||
for (let n = 4; n <= open.length; n += 7) {
|
||||
const p = await render(open.slice(0, n), true);
|
||||
expect(p.blocks.length <= 1 && (p.blocks[0]?.lang ?? "text")).toBe("text");
|
||||
}
|
||||
|
||||
// streaming, a closed fence followed by an open one: the closed one is detected, the open one waits
|
||||
r = await render(closed + "\nnext:\n\n" + open, true);
|
||||
expect(r.blocks.map((b) => b.lang)).toEqual(["python", "text"]);
|
||||
// the same text once it settles: both detected
|
||||
r = await render(closed + "\nnext:\n\n" + open, false);
|
||||
expect(r.blocks.map((b) => b.lang)).toEqual(["python", "python"]);
|
||||
// tildes close too
|
||||
r = await render("~~~~\n" + py + "\n~~~~\n", true);
|
||||
expect(r.blocks[0]!.lang).toBe("python");
|
||||
|
||||
// an explicit language is used as written, streaming or not
|
||||
for (const streaming of [true, false]) {
|
||||
r = await render("```ts\nconst x: number = 1;\n", streaming);
|
||||
expect(r.blocks[0]!.lang).toBe("ts");
|
||||
expect(r.blocks[0]!.codeClass).toBe("hljs language-ts");
|
||||
expect(r.blocks[0]!.hl).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
// the model's own <svg> is dropped; the code block buttons keep their icons; chrome attributes survive
|
||||
const evil =
|
||||
"look <svg><circle cx=\"5\" cy=\"5\" r=\"4\"/></svg> here\n\n" +
|
||||
"<svg onload=\"window.__pwned=1\"><circle cx=\"1\" cy=\"1\" r=\"1\"/></svg>\n\n" +
|
||||
"<img src=x onerror=\"window.__pwned=2\">\n\n" +
|
||||
"```ts\nlet a = 1;\nlet b = 2;\n```\n\n```\necho hi\n```\n";
|
||||
for (const streaming of [true, false]) {
|
||||
r = await render(evil, streaming, [1]);
|
||||
expect(r.svgOutsideButtons).toBe(0);
|
||||
expect(r.circles).toBe(0);
|
||||
expect(r.onload).toBe(0);
|
||||
expect(r.html).not.toMatch(/onerror|onload|__AC_CB_/);
|
||||
expect(r.blocks).toHaveLength(2);
|
||||
for (const b of r.blocks) expect(b.btnSvgs).toEqual([1, 1]);
|
||||
expect(r.blocks.map((b) => b.dataI)).toEqual(["0", "1"]);
|
||||
expect(r.blocks.map((b) => b.pressed)).toEqual(["false", "true"]);
|
||||
}
|
||||
await page.waitForTimeout(50);
|
||||
expect(await page.evaluate(() => (window as unknown as { __pwned?: unknown }).__pwned)).toBeUndefined();
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -291,29 +291,63 @@ describe("wrapper page", () => {
|
||||
expect(w.loc.reloaded).toBe(1);
|
||||
});
|
||||
|
||||
it("Windows wails.localhost #b= is kept and recover navigates back through it", async () => {
|
||||
// 1.3.5 / 1.3.6 followed http://wails.localhost/… on Windows: WebView2 can't load it from this frame (on 127.0.0.1, an
|
||||
// out-of-process iframe Wails' request filter doesn't see), which left its gray error page. Now it is never a target.
|
||||
it("Windows wails.localhost #b= is not taken: on loss it asks Magpie for Try again and never navigates", async () => {
|
||||
const WAILS = "http://wails.localhost/_magpie/plugin/abc123/index.html";
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), "", { ua: "Windows NT 10.0" });
|
||||
expect(w.store.get("ac_wrap_back")).toBe(WAILS);
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), "", { ua: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Edg/146.0" });
|
||||
expect(w.store.has("ac_wrap_back")).toBe(false);
|
||||
w.fromChild({ ac_console: "lost", at: 42 });
|
||||
const u = new URL(w.loc.replaced!);
|
||||
expect(u.origin + u.pathname).toBe("http://wails.localhost/_magpie/plugin/abc123/index.html");
|
||||
expect(u.searchParams.get("ac_lost")).toBe("42");
|
||||
expect(u.searchParams.get("ac_try")).toMatch(/^\d+\.1$/);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.parentWin.posted).toEqual([{ magpie: 1, method: "error", params: { message: "本地服务已断开" } }]);
|
||||
// the 12 s boot timeout / 15 s silence path is the same
|
||||
const w2 = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), "?lang=en", { ua: "Windows NT 10.0" });
|
||||
w2.tick(20_000);
|
||||
expect(w2.loc.replaced).toBeNull();
|
||||
expect(w2.parentWin.posted).toEqual([{ magpie: 1, method: "error", params: { message: "Local service disconnected" } }]);
|
||||
});
|
||||
|
||||
it("Windows wails.localhost: after max auto tries, Reconnect still replaces to #b=", async () => {
|
||||
it("Windows wails.localhost: Reconnect, also after max auto tries, asks Magpie and never replaces to it", async () => {
|
||||
const WAILS = "http://wails.localhost/_magpie/plugin/tok/page/index.html";
|
||||
const start = 1_800_000_000_000 - 30_000;
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321", b: WAILS }), `?ac_try=${start}.3`, { ua: "Windows NT 10.0" });
|
||||
w.fromChild({ ac_console: "lost", at: 1 });
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
w.parentWin.posted.length = 0;
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced!.startsWith("http://wails.localhost/_magpie/plugin/tok/page/index.html")).toBe(true);
|
||||
expect(new URL(w.loc.replaced!).searchParams.has("ac_try")).toBe(false);
|
||||
expect(w.loc.replaced).toBeNull();
|
||||
expect(w.parentWin.posted).toEqual([{ magpie: 1, method: "error", params: { message: "本地服务已断开" } }]);
|
||||
});
|
||||
|
||||
it("a stale http://wails.localhost back in sessionStorage (left by 1.3.5 / 1.3.6) is dropped and never followed", async () => {
|
||||
const STALE = "http://wails.localhost/_magpie/plugin/oldtok/page/index.html";
|
||||
for (const ua of ["Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Macintosh", "X11; Linux x86_64"]) {
|
||||
const w = await runWrapper(hash({ t: TOKEN, p: "4321" }), "", { ua, sessionStorage: { ac_wrap_back: STALE } });
|
||||
w.fromChild({ ac_console: "lost", at: 7 });
|
||||
expect(w.loc.replaced, ua).toBeNull();
|
||||
expect(w.store.has("ac_wrap_back"), ua).toBe(false);
|
||||
expect(w.parentWin.posted, ua).toEqual([{ magpie: 1, method: "error", params: { message: "本地服务已断开" } }]);
|
||||
w.parentWin.posted.length = 0;
|
||||
w.els.r!.onclick!();
|
||||
expect(w.loc.replaced, ua).toBeNull();
|
||||
expect(w.parentWin.posted, ua).toEqual([{ magpie: 1, method: "error", params: { message: "本地服务已断开" } }]);
|
||||
}
|
||||
// invalid link + stale stored back: same, Magpie's card right away
|
||||
const bad = await runWrapper(hash({ t: "nope", p: "1" }), "", { ua: "Windows NT 10.0", sessionStorage: { ac_wrap_back: STALE } });
|
||||
expect(bad.loc.replaced).toBeNull();
|
||||
expect(bad.store.has("ac_wrap_back")).toBe(false);
|
||||
expect(bad.parentWin.posted).toEqual([{ magpie: 1, method: "error", params: { message: "链接已失效" } }]);
|
||||
// a stale wails back never shadows a fresh loopback #b= (magpie web)
|
||||
const web = await runWrapper(hash({ t: TOKEN, p: "4321", b: BACK }), "", { ua: "Windows NT 10.0", sessionStorage: { ac_wrap_back: STALE } });
|
||||
expect(web.store.get("ac_wrap_back")).toBe(BACK);
|
||||
web.fromChild({ ac_console: "lost", at: 7 });
|
||||
expect(new URL(web.loc.replaced!).origin).toBe("http://127.0.0.1:5000");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["http://wails.localhost/_magpie/plugin/a/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost/_magpie/plugin/a/page/index.html", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"],
|
||||
["wails://localhost/_magpie/plugin/a/page/index.html", "Macintosh"],
|
||||
["https://wails.localhost/_magpie/plugin/a/page/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost:8080/_magpie/plugin/a/index.html", "Windows NT 10.0"],
|
||||
["http://wails.localhost/_magpie/plugin/a/index.html", "Macintosh"],
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Topbar } from "./components/Topbar";
|
||||
import { Chat } from "./components/Chat";
|
||||
import { useTimeline } from "./stores/timeline";
|
||||
import { useData } from "./stores/data";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { CommandPalette } from "./components/CommandPalette";
|
||||
import { Panel } from "./components/Panel";
|
||||
import { SettingsDialog } from "./components/Settings";
|
||||
@@ -14,9 +14,20 @@ import { Toasts } from "./components/Toast";
|
||||
import { t } from "./i18n/index.js";
|
||||
import { goBackToMagpie, isWrapped, reportLostToWrapper } from "./api/backToMagpie.js";
|
||||
|
||||
/** No thread waiting: one shared Set, so Sidebar's prop stays the same reference */
|
||||
const NO_PENDING_THREADS: Set<string> = new Set<string>();
|
||||
|
||||
export function App() {
|
||||
const { state, version } = useConnection();
|
||||
const pending = useTimeline((s) => s.pending);
|
||||
// Field-level selectors: a token delta (assistant/reasoning/tool output) changes none of these, so the shell
|
||||
// (Layout, Sidebar, Topbar, Panel) doesn't re-render while a reply streams
|
||||
const pendingCount = useTimeline((s) => s.pending.length);
|
||||
const pendingKey = useTimeline((s) => s.pending[0]?.key);
|
||||
const pendingThreadId = useTimeline((s) => (s.pending.length > 0 ? s.threadId : null));
|
||||
const pendingByThread = useMemo<Set<string>>(
|
||||
() => (pendingThreadId ? new Set([pendingThreadId]) : NO_PENDING_THREADS),
|
||||
[pendingThreadId],
|
||||
);
|
||||
const providers = useData((s) => s.providers);
|
||||
const [palette, setPalette] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
@@ -59,8 +70,8 @@ export function App() {
|
||||
|
||||
return (
|
||||
<Layout
|
||||
sidebar={<Sidebar pendingByThread={new Set(pending.map((p) => useTimeline.getState().threadId!).filter(Boolean))} />}
|
||||
topbar={<Topbar pendingCount={pending.length} pendingKey={pending[0]?.key} />}
|
||||
sidebar={<Sidebar pendingByThread={pendingByThread} />}
|
||||
topbar={<Topbar pendingCount={pendingCount} pendingKey={pendingKey} />}
|
||||
panel={<Panel />}
|
||||
>
|
||||
{state === "reconnecting" && <div className="connbar">{t("boot.reconnecting")}</div>}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
// Self-heal after the plugin host restarts (Magpie restarts its Bun plugin host from time to time; the old host's daemon exits with it
|
||||
// and the gate key / port change). This page was opened by the gate with the Magpie plugin page URL in the fragment (#t=…&b=…).
|
||||
// When the daemon can't be reached for a few seconds, the page goes back to that Magpie page: boot.js reads the fresh session.js and
|
||||
// opens the new gate, which starts a new daemon. Only a Magpie plugin page URL on loopback or exact wails.localhost is ever followed (no open redirect),
|
||||
// and the token is never put anywhere but this page's own fragment.
|
||||
// opens the new gate, which starts a new daemon. Only a Magpie plugin page URL on loopback (magpie web) is ever followed (no open
|
||||
// redirect), and the token is never put anywhere but this page's own fragment. Magpie's desktop window (wails://localhost,
|
||||
// http://wails.localhost on Windows) is never a back target: a frame on 127.0.0.1 can't navigate there (see lib/gate.mjs
|
||||
// safeBackUrl); framed by Magpie without a back URL, this page asks Magpie for its Try again card instead.
|
||||
|
||||
/** Same check as lib/gate.mjs safeBackUrl: http(s), loopback or exact wails.localhost, no credentials, /_magpie/plugin/<id>/[page/]index.html */
|
||||
export function safeBackUrl(raw: string | null | undefined, ua = typeof navigator !== "undefined" ? navigator.userAgent : ""): string | null {
|
||||
/** Same check as lib/gate.mjs safeBackUrl: http(s), loopback only, no credentials, /_magpie/plugin/<id>/[page/]index.html */
|
||||
export function safeBackUrl(raw: string | null | undefined): string | null {
|
||||
if (typeof raw !== "string" || !raw || raw.length > 2048) return null;
|
||||
let u: URL;
|
||||
try { u = new URL(raw); } catch { return null; }
|
||||
@@ -13,8 +15,7 @@ export function safeBackUrl(raw: string | null | undefined, ua = typeof navigato
|
||||
if (u.username || u.password) return null;
|
||||
const host = u.hostname.toLowerCase();
|
||||
const loopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]";
|
||||
const magpieWin = /Windows/.test(ua) && host === "wails.localhost" && u.protocol === "http:" && u.port === "";
|
||||
if (!loopback && !magpieWin) return null;
|
||||
if (!loopback) 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}`;
|
||||
}
|
||||
@@ -44,6 +45,18 @@ export function goBackToMagpie(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Framed by Magpie with no back URL: ask the window for its Try again card ({magpie:1, method:"error"}), which replaces this
|
||||
* frame and rebuilds it from the Magpie page. False when not framed (nothing to ask). */
|
||||
export function askMagpieRetry(message: string): boolean {
|
||||
if (typeof window === "undefined" || window.parent === window) return false;
|
||||
try {
|
||||
window.parent.postMessage({ magpie: 1, method: "error", params: { message } }, "*");
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls onStuck once the connection has been down for `ms` without coming back */
|
||||
export function watchReconnect(
|
||||
ws: { onState(fn: (s: string) => void): () => void; getState(): string },
|
||||
|
||||
@@ -265,7 +265,11 @@ export function Chat() {
|
||||
key={v.key}
|
||||
data-index={v.index}
|
||||
ref={rowRef}
|
||||
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)` }}
|
||||
style={{
|
||||
position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${v.start}px)`,
|
||||
// 1.3.7: the list's bottom gap lives inside the last row's measured height (see .tl-wrap in layout.css)
|
||||
...(!tl.error && v.index === items.length - 1 ? { paddingBottom: "var(--tl-pad-b)" } : {}),
|
||||
}}
|
||||
>
|
||||
<TimelineRow it={it} threadId={activeThreadId} onEditResend={resend}
|
||||
onRetryLast={v.index === lastTurnEnd ? retryLast : undefined}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Input area (§8.6 Composer): auto-grow, IME, queue/steer, waiting for permission, attachments,
|
||||
// Agent·model popover, thinking level, permission mode, ↑ to recall.
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isImeComposing } from "../composer/ime";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { useData } from "../stores/data";
|
||||
@@ -36,10 +36,19 @@ type Attachment = { path: string; name: string; mime: string; uploading?: boolea
|
||||
/** Maximum rows drawn in the model list at once (hundreds of buttons make the popover noticeably sluggish) */
|
||||
const MODEL_LIST_CAP = 150;
|
||||
|
||||
export function Composer() {
|
||||
/** memo: no props, so Chat re-rendering on every streamed token (items, virtual height) leaves the composer alone */
|
||||
export const Composer = memo(function Composer() {
|
||||
const ui = useUi();
|
||||
const { threads, providers, projects } = useData();
|
||||
const tl = useTimeline();
|
||||
// 1.3.7: subscribe field-by-field so assistant_delta tokens don't re-render the whole composer
|
||||
const status = useTimeline((s) => s.status);
|
||||
const pending = useTimeline((s) => s.pending);
|
||||
const slashCommands = useTimeline((s) => s.slashCommands);
|
||||
const queue = useTimeline((s) => s.queue);
|
||||
const hasUserItem = useTimeline((s) => s.items.some((it) => it.kind === "user"));
|
||||
const hasAgentItem = useTimeline((s) => s.items.some((it) =>
|
||||
it.kind === "assistant" || it.kind === "reasoning" || it.kind === "toolgroup" || it.kind === "permission"));
|
||||
const checklist = useTimeline((s) => currentChecklist(s.items));
|
||||
const [text, setText] = useState("");
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [mentions, setMentions] = useState<MentionDraft[]>([]);
|
||||
@@ -64,8 +73,8 @@ export function Composer() {
|
||||
|
||||
const thread = threads.find((t) => t.id === ui.currentThreadId);
|
||||
const provider = providers.find((p) => p.id === thread?.provider);
|
||||
const running = tl.status === "running" || tl.status === "initializing";
|
||||
const waiting = tl.pending.length > 0;
|
||||
const running = status === "running" || status === "initializing";
|
||||
const waiting = pending.length > 0;
|
||||
const steerOk = provider?.capabilities.steer ?? false;
|
||||
// Known not to take images (an ACP Agent whose initialize doesn't advertise them): images still go, as file paths
|
||||
const imagesByPath = !!provider && !provider.capabilities.images && provider.capabilities.imagesKnown !== false;
|
||||
@@ -74,13 +83,12 @@ export function Composer() {
|
||||
const modeMeta = modes.find((m) => m.id === mode);
|
||||
// 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 started = hasUserItem && (running || !!thread?.providerSessionId || hasAgentItem);
|
||||
|
||||
const slashMenu = useMemo(() => slashMenuState(text, slashSuppress.current), [text]);
|
||||
const slashFiltered = useMemo(
|
||||
() => filterSlashCommands(tl.slashCommands, slashMenu.query),
|
||||
[tl.slashCommands, slashMenu.query],
|
||||
() => filterSlashCommands(slashCommands, slashMenu.query),
|
||||
[slashCommands, slashMenu.query],
|
||||
);
|
||||
const slashRows = useMemo(() => slashMenuRows(slashFiltered), [slashFiltered]);
|
||||
const slashPickable = useMemo(() => selectableSlashRows(slashRows), [slashRows]);
|
||||
@@ -472,8 +480,6 @@ export function Composer() {
|
||||
})();
|
||||
|
||||
if (!ui.currentThreadId) return null;
|
||||
const checklist = currentChecklist(tl.items);
|
||||
|
||||
return (
|
||||
<div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop}
|
||||
onDragOver={(e) => {
|
||||
@@ -494,9 +500,9 @@ export function Composer() {
|
||||
</div>
|
||||
)}
|
||||
{/* queue list */}
|
||||
{tl.queue.length > 0 && (
|
||||
{queue.length > 0 && (
|
||||
<div className="q-list">
|
||||
{tl.queue.map((q) => (
|
||||
{queue.map((q) => (
|
||||
<div key={q.id} className="q-item">
|
||||
<span className="q-text">{q.text}</span>
|
||||
<button className="ibtn" title={tr("common.remove")} onClick={() => void ws.call("thread.queueRemove", { id: thread?.id, queueId: q.id }).catch(() => {})}>
|
||||
@@ -861,7 +867,7 @@ export function Composer() {
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
/** The small ⌄ every composer chip ends with (1.3: one chip style for agent·model, effort, permission, Fast) */
|
||||
function ChipCaret() {
|
||||
|
||||
@@ -1,144 +1,90 @@
|
||||
// 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";
|
||||
import hljs from "highlight.js/lib/common";
|
||||
// Markdown rendering (marked + DOMPurify + highlight.js live in util/renderMarkdown.ts).
|
||||
// 1.3.7: fenced code is built as the final .cb / header / numbered / highlighted HTML inside renderMarkdown,
|
||||
// so React's commit paints the stable height in one shot (the old useEffect decorate ran after paint and
|
||||
// flashed bare <pre> ↔ .cb on every streaming token). Copy / wrap use container event delegation; wrap
|
||||
// state is keyed by the block's index in its message (a streaming block keeps its index while it grows; a
|
||||
// source fingerprint changed with every token and dropped the toggle) and is baked into the HTML string.
|
||||
import { useLayoutEffect, useMemo, useRef, type MouseEvent } from "react";
|
||||
import { linkifyLocal } from "../util/localLinks";
|
||||
import { onChatLinkClick } from "../preview/open";
|
||||
import { t } from "../i18n/index.js";
|
||||
import { ICON_CHECK, ICON_COPY, svgIconHtml } from "../util/codeBlock";
|
||||
import { renderMarkdown } from "../util/renderMarkdown";
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
const purify = (html: string) =>
|
||||
DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
return purify(marked.parse(text, { async: false }));
|
||||
}
|
||||
export { renderMarkdown, type RenderedMarkdown } from "../util/renderMarkdown";
|
||||
|
||||
export function Markdown({ text, streaming }: { text: string; streaming?: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const html = useMemo(() => renderMarkdown(text), [text]);
|
||||
const rawsRef = useRef<string[]>([]);
|
||||
// One <Markdown> is one message: while it streams its code blocks only ever get appended, so block i stays block i
|
||||
const wrapIdx = useRef(new Set<number>());
|
||||
// wrapIdx is read at render time (a toggle mutates the DOM directly; the next text change bakes it into the HTML)
|
||||
// streaming: an unlabelled fence still open at the end stays "text" until it closes or the message settles
|
||||
const rendered = useMemo(() => renderMarkdown(text, { wrapped: wrapIdx.current, streaming }), [text, streaming]);
|
||||
rawsRef.current = rendered.raws;
|
||||
|
||||
// After rendering: highlight code blocks + copy button, then local addresses become Preview links (1.2).
|
||||
// Link clicks are handled by onChatLinkClick (system browser / Preview tab): target=_blank can't open anything in
|
||||
// Magpie's sandboxed frame, and a plain click would navigate the whole page away.
|
||||
useEffect(() => {
|
||||
// Restore .wrap before paint so a streaming re-render never flashes the unwrapped width
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
for (const pre of el.querySelectorAll("pre")) {
|
||||
const code = pre.querySelector("code");
|
||||
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);
|
||||
}
|
||||
// No code block left in the text (reset / replaced): start from a clean wrap state
|
||||
if (rendered.raws.length === 0) wrapIdx.current.clear();
|
||||
// Safety net: the HTML already carries .wrap / aria-pressed for toggled blocks
|
||||
const boxes = el.querySelectorAll(".cb");
|
||||
boxes.forEach((box, i) => {
|
||||
const on = wrapIdx.current.has(i);
|
||||
if (box.classList.contains("wrap") !== on) box.classList.toggle("wrap", on);
|
||||
box.querySelector(".cb-wrap")?.setAttribute("aria-pressed", String(on));
|
||||
});
|
||||
// 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"));
|
||||
}, [html, streaming]);
|
||||
}, [rendered.html, streaming]);
|
||||
|
||||
const onClick = (e: MouseEvent<HTMLDivElement>) => {
|
||||
onChatLinkClick(e);
|
||||
const btn = (e.target as HTMLElement | null)?.closest?.(".cb-btn") as HTMLElement | null;
|
||||
const root = ref.current;
|
||||
if (!btn || !root || !root.contains(btn)) return;
|
||||
e.preventDefault();
|
||||
const box = btn.closest(".cb");
|
||||
if (!box) return;
|
||||
if (btn.classList.contains("cb-wrap")) {
|
||||
const on = !box.classList.contains("wrap");
|
||||
box.classList.toggle("wrap", on);
|
||||
btn.setAttribute("aria-pressed", String(on));
|
||||
const idx = [...root.querySelectorAll(".cb")].indexOf(box);
|
||||
if (idx < 0) return;
|
||||
if (on) wrapIdx.current.add(idx);
|
||||
else wrapIdx.current.delete(idx);
|
||||
return;
|
||||
}
|
||||
if (btn.classList.contains("cb-copy")) {
|
||||
const idx = Number(btn.getAttribute("data-i") ?? "-1");
|
||||
const raw = rawsRef.current[idx] ?? "";
|
||||
void copyText(raw).then(() => {
|
||||
// Ignore if this button was replaced by a later stream frame
|
||||
if (!btn.isConnected) return;
|
||||
btn.innerHTML = svgIconHtml(ICON_CHECK);
|
||||
btn.classList.add("done");
|
||||
setTimeout(() => {
|
||||
if (!btn.isConnected) return;
|
||||
btn.innerHTML = svgIconHtml(ICON_COPY);
|
||||
btn.classList.remove("done");
|
||||
}, 1200);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`md${streaming ? " streaming" : ""}`}
|
||||
onClick={onChatLinkClick}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
onClick={onClick}
|
||||
dangerouslySetInnerHTML={{ __html: rendered.html }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// (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 { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Icon } from "./Icons";
|
||||
import { t } from "../i18n/index.js";
|
||||
@@ -51,7 +51,8 @@ function visibleArea(root: Element): Box {
|
||||
return { left: r.left, right: r.right, top: Math.max(r.top, 0) + 4, bottom: bottom - 4 };
|
||||
}
|
||||
|
||||
export function QuoteSelect() {
|
||||
/** memo: no props, Chat's streaming re-renders don't reach it */
|
||||
export const QuoteSelect = memo(function QuoteSelect() {
|
||||
const [pick, setPick] = useState<Pick | null>(null);
|
||||
const dragging = useRef(false);
|
||||
const popRef = useRef<HTMLButtonElement>(null);
|
||||
@@ -129,4 +130,4 @@ export function QuoteSelect() {
|
||||
</button>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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, isWrapped, reportLostToWrapper, startWrapperHeartbeat, watchReconnect } from "./api/backToMagpie.js";
|
||||
import { askMagpieRetry, 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";
|
||||
@@ -46,7 +46,11 @@ ws.onState((s) => useConnection.getState().set({ state: s }));
|
||||
// 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(); });
|
||||
// Unwrapped with no loopback back URL (Magpie's desktop window never is one): framed by Magpie, ask for its Try again card.
|
||||
watchReconnect(ws, () => {
|
||||
if (wrapped) reportLostToWrapper();
|
||||
else if (!goBackToMagpie()) askMagpieRetry(getLocale().startsWith("zh") ? "本地服务已断开" : "Local service disconnected");
|
||||
});
|
||||
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
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// 1.3.7: `pending` keeps its reference across token deltas, so App's selectors don't re-render the shell per token
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
type Handler = (ch: string, d: unknown) => void;
|
||||
const fake = vi.hoisted(() => ({ handlers: new Map<string, (ch: string, d: unknown) => void>() }));
|
||||
vi.mock("../main", () => ({
|
||||
ws: {
|
||||
call: async (method: string) => {
|
||||
if (method === "threads.get") return { meta: { status: "running" }, events: [], queue: [], pending: [], runtimeStatus: "running" };
|
||||
return {};
|
||||
},
|
||||
subscribe: (ch: string, cb: Handler) => {
|
||||
fake.handlers.set(ch, cb);
|
||||
return () => fake.handlers.delete(ch);
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { useTimeline, EMPTY_PENDING, samePending, stablePending, type PendingReq } from "./timeline";
|
||||
|
||||
const TID = "t_pending";
|
||||
let seq = 0;
|
||||
const push = (d: unknown) => fake.handlers.get(`thread:${TID}`)!(`thread:${TID}`, d);
|
||||
const ev = (e: Record<string, unknown>) => push({ type: "event", event: { ts: Date.now(), threadId: TID, turnId: "u1", ...e } });
|
||||
const delta = (text: string) => ev({ seq: -1, type: "assistant_delta", itemId: "a1", text });
|
||||
|
||||
async function openThread() {
|
||||
useTimeline.getState().close();
|
||||
useTimeline.getState().open(TID);
|
||||
for (let i = 0; i < 50 && !fake.handlers.has(`thread:${TID}`); i++) await new Promise((r) => setTimeout(r, 0));
|
||||
expect(fake.handlers.has(`thread:${TID}`)).toBe(true);
|
||||
}
|
||||
|
||||
describe("useTimeline pending reference", () => {
|
||||
beforeEach(() => { seq = 0; fake.handlers.clear(); });
|
||||
|
||||
it("samePending / stablePending compare id, kind and key", () => {
|
||||
const a: PendingReq[] = [{ requestId: "r1", kind: "permission", key: "k1" }];
|
||||
expect(samePending(a, [{ requestId: "r1", kind: "permission", key: "k1" }])).toBe(true);
|
||||
expect(samePending(a, [{ requestId: "r2", kind: "permission", key: "k1" }])).toBe(false);
|
||||
expect(samePending(a, [{ requestId: "r1", kind: "question", key: "k1" }])).toBe(false);
|
||||
expect(samePending(a, [{ requestId: "r1", kind: "permission", key: "k2" }])).toBe(false);
|
||||
expect(samePending(a, [])).toBe(false);
|
||||
expect(stablePending(a, [{ requestId: "r1", kind: "permission", key: "k1" }])).toBe(a);
|
||||
expect(stablePending(a, [])).toBe(EMPTY_PENDING);
|
||||
});
|
||||
|
||||
it("streamed deltas keep s.pending === across updates; a permission request and its resolution change it", async () => {
|
||||
await openThread();
|
||||
const p0 = useTimeline.getState().pending;
|
||||
expect(p0).toBe(EMPTY_PENDING);
|
||||
let changes = 0;
|
||||
const unsub = useTimeline.subscribe((s, prev) => { if (s.pending !== prev.pending) changes++; });
|
||||
|
||||
ev({ seq: ++seq, type: "turn_started" });
|
||||
for (let i = 0; i < 20; i++) delta(`token ${i} `);
|
||||
ev({ seq: -1, type: "reasoning_delta", itemId: "r1", text: "thinking" });
|
||||
push({ type: "status", status: "running" });
|
||||
expect(useTimeline.getState().items.length).toBeGreaterThan(0);
|
||||
expect(useTimeline.getState().pending).toBe(p0);
|
||||
expect(changes).toBe(0);
|
||||
|
||||
ev({ seq: ++seq, type: "permission_request", requestId: "req1", title: "run ls", kind: "execute", options: [{ id: "allow", label: "Allow", kind: "allow_once" }] });
|
||||
const p1 = useTimeline.getState().pending;
|
||||
expect(p1).not.toBe(p0);
|
||||
expect(p1.map((p) => p.requestId)).toEqual(["req1"]);
|
||||
expect(changes).toBe(1);
|
||||
|
||||
// still waiting: more deltas / a status echo / the daemon's pending list keep the same array
|
||||
for (let i = 0; i < 5; i++) delta(`more ${i}`);
|
||||
push({ type: "status", status: "running" });
|
||||
push({ type: "pending", pending: [{ requestId: "req1", kind: "permission" }] });
|
||||
expect(useTimeline.getState().pending).toBe(p1);
|
||||
expect(changes).toBe(1);
|
||||
|
||||
ev({ seq: ++seq, type: "permission_resolved", requestId: "req1", optionId: "allow" });
|
||||
expect(useTimeline.getState().pending).toBe(EMPTY_PENDING);
|
||||
expect(changes).toBe(2);
|
||||
for (let i = 0; i < 5; i++) delta(`after ${i}`);
|
||||
expect(useTimeline.getState().pending).toBe(EMPTY_PENDING);
|
||||
expect(changes).toBe(2);
|
||||
unsub();
|
||||
useTimeline.getState().close();
|
||||
expect(useTimeline.getState().pending).toBe(EMPTY_PENDING);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,27 @@ import { Outbox, newClientId, withOutbox, type SendDisplay, type SendPayload } f
|
||||
export type QueueItem = { id: string; text: string; attachments?: { path: string; mime: string }[] };
|
||||
export type PendingReq = { requestId: string; kind: "permission" | "question"; key?: string };
|
||||
|
||||
/** Shared empty list: "nothing waiting" is always the same reference, so selectors on `pending` don't fire */
|
||||
export const EMPTY_PENDING: PendingReq[] = [];
|
||||
|
||||
/** Same waiting requests (same order, ids, kinds and keys) */
|
||||
export function samePending(a: readonly PendingReq[], b: readonly PendingReq[]): boolean {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const x = a[i]!, y = b[i]!;
|
||||
if (x.requestId !== y.requestId || x.kind !== y.kind || x.key !== y.key) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Keep the previous reference when nothing changed: a token delta must not hand App a new `pending` array
|
||||
* (that re-rendered the whole three-column shell on every delta) */
|
||||
export function stablePending(prev: PendingReq[], next: PendingReq[]): PendingReq[] {
|
||||
if (next.length === 0) return EMPTY_PENDING;
|
||||
return samePending(prev, next) ? prev : next;
|
||||
}
|
||||
|
||||
type TlStore = {
|
||||
threadId: string | null;
|
||||
status: string;
|
||||
@@ -92,7 +113,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
}
|
||||
applyEvent(st, ev);
|
||||
// pending is derived from timeline items (pending permission/question → composer waiting state)
|
||||
set({ ...view(threadId), pending: pendingRequests(st.items) });
|
||||
set({ ...view(threadId), pending: stablePending(get().pending, pendingRequests(st.items)) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "status" && data.status) {
|
||||
@@ -101,7 +122,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
syncRuntimeFlags();
|
||||
// Going idle closes the open cards (syncRuntimeFlags): the waiting state follows them, or the top bar would
|
||||
// keep 等待授权 with no card to click
|
||||
set({ ...view(threadId), pending: pendingRequests(st.items) });
|
||||
set({ ...view(threadId), pending: stablePending(get().pending, pendingRequests(st.items)) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "queue" && data.queue) {
|
||||
@@ -110,7 +131,8 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
}
|
||||
if (data.type === "pending" && data.pending) {
|
||||
// Only requests the timeline shows a live card for
|
||||
set({ pending: pendingRequests(st.items).filter((p) => data.pending!.some((d) => d.requestId === p.requestId)) });
|
||||
const next = pendingRequests(st.items).filter((p) => data.pending!.some((d) => d.requestId === p.requestId));
|
||||
set({ pending: stablePending(get().pending, next) });
|
||||
return;
|
||||
}
|
||||
if (data.type === "commands" && data.commands) {
|
||||
@@ -127,7 +149,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
status: "idle",
|
||||
items: [],
|
||||
queue: [],
|
||||
pending: [],
|
||||
pending: EMPTY_PENDING,
|
||||
lastUserText: null,
|
||||
error: null,
|
||||
slashCommands: [],
|
||||
@@ -136,7 +158,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
open: (threadId) => {
|
||||
if (get().threadId === threadId) return;
|
||||
get().close();
|
||||
set({ threadId, status: "initializing", items: outbox.items(threadId), queue: [], pending: [], lastUserText: null, error: null, slashCommands: [] });
|
||||
set({ threadId, status: "initializing", items: outbox.items(threadId), queue: [], pending: EMPTY_PENDING, lastUserText: null, error: null, slashCommands: [] });
|
||||
st = newTimelineState();
|
||||
stSeqMax = 0;
|
||||
runtimeStatus = "initializing";
|
||||
@@ -160,7 +182,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
...view(threadId),
|
||||
// Not g.pending: the daemon's list could hold a request the timeline already closed (a 1.2 daemon kept
|
||||
// one whose turn had ended). Waiting follows the cards that show buttons.
|
||||
queue: g.queue ?? [], pending: pendingRequests(st.items), lastUserText: r.lastUserText,
|
||||
queue: g.queue ?? [], pending: stablePending(get().pending, pendingRequests(st.items)), lastUserText: r.lastUserText,
|
||||
});
|
||||
// Subscribe only once the snapshot is ready: the server replays events after afterSeq=stSeqMax, joining the snapshot seamlessly
|
||||
if (get().threadId === threadId) subscribeChannel(threadId);
|
||||
@@ -175,7 +197,7 @@ export const useTimeline = create<TlStore>((set, get) => {
|
||||
unsub = null;
|
||||
st = newTimelineState();
|
||||
stSeqMax = 0;
|
||||
set({ threadId: null, items: [], queue: [], pending: [], lastUserText: null, error: null, status: "idle", slashCommands: [] });
|
||||
set({ threadId: null, items: [], queue: [], pending: EMPTY_PENDING, lastUserText: null, error: null, status: "idle", slashCommands: [] });
|
||||
},
|
||||
|
||||
send: async (threadId, payload, display = {}, opts = {}) => {
|
||||
|
||||
@@ -135,9 +135,14 @@ button.tb-pill { border: 0; font-family: inherit; cursor: pointer; }
|
||||
}
|
||||
|
||||
/* Timeline: content max width 760, centered */
|
||||
.scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; position: relative; }
|
||||
.scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; position: relative; scrollbar-gutter: stable; }
|
||||
/* Conversation and composer share one column: --col, 720px by default (Settings → Content width: 640 / 720 / 880 / full) */
|
||||
.tl-wrap { max-width: calc(var(--col) + 40px); min-width: 0; margin: 0 auto; padding: 24px 20px 16px; }
|
||||
/* 1.3.7: no bottom padding here — the virtual rows are position:absolute, and an absolute row overflowing the old
|
||||
totalSize doesn't count the ancestor's padding-bottom in scrollHeight, so the gap vanished for one frame and came
|
||||
back the next (the stuck-to-bottom chat bounced --tl-pad-b px per streamed line). The last row carries the gap instead
|
||||
(Chat.tsx), inside its own measured height, so both frames have the same scrollHeight. */
|
||||
.tl-wrap { --tl-pad-b: 16px; display: flow-root; max-width: calc(var(--col) + 40px); min-width: 0; margin: 0 auto; padding: 24px 20px 0; }
|
||||
.tl-wrap > .nt, .tl-wrap > .sb-empty { margin-bottom: var(--tl-pad-b); }
|
||||
|
||||
/* ↓ jump-to-bottom button */
|
||||
.jump {
|
||||
@@ -304,7 +309,7 @@ button.tb-pill { border: 0; font-family: inherit; cursor: pointer; }
|
||||
.sidebar.open { transform: none; }
|
||||
.sidebar ~ .rs-l { display: none; }
|
||||
.tb-menu-btn { display: inline-flex; }
|
||||
.tl-wrap { padding: 16px 14px 8px; }
|
||||
.tl-wrap { --tl-pad-b: 8px; padding: 16px 14px 0; }
|
||||
.tb-model { display: none; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { marked } from "marked";
|
||||
import {
|
||||
autoCacheSize,
|
||||
buildCodeBlockHtml,
|
||||
COPY_ICON_TOKEN,
|
||||
WRAP_ICON_TOKEN,
|
||||
escapeHtml,
|
||||
highlightAutoCached,
|
||||
isClosedFence,
|
||||
restoreCodeBlockIcons,
|
||||
sanitizeLang,
|
||||
splitHljsHtmlLines,
|
||||
} from "./codeBlock";
|
||||
|
||||
describe("codeBlock helpers (1.3.7 single-pass markdown)", () => {
|
||||
it("escapeHtml encodes markup characters", () => {
|
||||
expect(escapeHtml(`<img onerror="alert(1)"> & "`)).toBe(
|
||||
"<img onerror="alert(1)"> & "",
|
||||
);
|
||||
});
|
||||
|
||||
it("sanitizeLang keeps safe language ids only", () => {
|
||||
expect(sanitizeLang("ts")).toBe("ts");
|
||||
expect(sanitizeLang("c++")).toBe("c++");
|
||||
expect(sanitizeLang("js;alert(1)")).toBe("js");
|
||||
expect(sanitizeLang("")).toBe("");
|
||||
expect(sanitizeLang(undefined)).toBe("");
|
||||
});
|
||||
|
||||
it("splitHljsHtmlLines re-opens spans across newlines", () => {
|
||||
const hl = `<span class="hljs-keyword">const</span> x;\n<span class="hljs-title function_">fn</span>()`;
|
||||
expect(splitHljsHtmlLines(hl)).toEqual([
|
||||
`<span class="hljs-keyword">const</span> x;`,
|
||||
`<span class="hljs-title function_">fn</span>()`,
|
||||
]);
|
||||
// span that wraps a newline
|
||||
const cross = `<span class="hljs-string">"a\nb"</span>`;
|
||||
expect(splitHljsHtmlLines(cross)).toEqual([
|
||||
`<span class="hljs-string">"a</span>`,
|
||||
`<span class="hljs-string">b"</span>`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("buildCodeBlockHtml emits .cb chrome with numbered lines and no bare script", () => {
|
||||
const html = buildCodeBlockHtml("const x = 1;\nconsole.log(x);", "js", 3, {
|
||||
wrap: "Wrap lines",
|
||||
copy: "Copy",
|
||||
});
|
||||
expect(html).toContain('class="cb numbered"');
|
||||
expect(html).toContain('class="cb-lang">js<');
|
||||
expect(html).toContain('data-i="3"');
|
||||
expect(html).toContain('class="cb-l"');
|
||||
expect(html).toContain("hljs-keyword");
|
||||
expect(html).not.toContain("<script");
|
||||
expect(html).toContain("<button type=\"button\" class=\"cb-btn cb-wrap\"");
|
||||
expect(html).toContain("<button type=\"button\" class=\"cb-btn cb-copy\"");
|
||||
});
|
||||
|
||||
it("buildCodeBlockHtml escapes unknown-language body text", () => {
|
||||
const html = buildCodeBlockHtml(`<img onerror=alert(1)>\n<script>x</script>`, "notalang", 0, {
|
||||
wrap: "w",
|
||||
copy: "c",
|
||||
});
|
||||
expect(html).toContain("<img onerror=alert(1)>");
|
||||
expect(html).toContain("<script>x</script>");
|
||||
expect(html).not.toMatch(/<img\s/i);
|
||||
expect(html).not.toMatch(/<script>/i);
|
||||
});
|
||||
|
||||
it("buildCodeBlockHtml bakes a wrapped block's .wrap and aria-pressed into the HTML", () => {
|
||||
const off = buildCodeBlockHtml("a\nb", "ts", 0, { wrap: "w", copy: "c" });
|
||||
expect(off).toMatch(/^<div class="cb numbered">/);
|
||||
expect(off).toContain('aria-pressed="false"');
|
||||
const on = buildCodeBlockHtml("a\nb", "ts", 0, { wrap: "w", copy: "c" }, true);
|
||||
expect(on).toMatch(/^<div class="cb numbered wrap">/);
|
||||
expect(on).toContain('class="cb-btn cb-wrap" title="w" aria-label="w" aria-pressed="true"');
|
||||
});
|
||||
|
||||
it("buildCodeBlockHtml emits icon placeholders that restoreCodeBlockIcons turns into the trusted <svg> icons", () => {
|
||||
const html = buildCodeBlockHtml("x", "ts", 0, { wrap: "w", copy: "c" });
|
||||
expect(html).not.toContain("<svg");
|
||||
expect(html).toContain(WRAP_ICON_TOKEN);
|
||||
expect(html).toContain(COPY_ICON_TOKEN);
|
||||
expect(WRAP_ICON_TOKEN).toMatch(/^__AC_CB_WRAP_[0-9a-f]{24}__$/);
|
||||
expect(COPY_ICON_TOKEN).toMatch(/^__AC_CB_COPY_[0-9a-f]{24}__$/);
|
||||
const out = restoreCodeBlockIcons(html);
|
||||
expect(out).not.toContain(WRAP_ICON_TOKEN);
|
||||
expect(out).not.toContain(COPY_ICON_TOKEN);
|
||||
expect(out.match(/<svg /g)?.length).toBe(2);
|
||||
// a look-alike the model could type is left alone
|
||||
expect(restoreCodeBlockIcons("__AC_CB_WRAP_000000000000000000000000__")).toBe("__AC_CB_WRAP_000000000000000000000000__");
|
||||
});
|
||||
|
||||
// ---- unlabelled fences (yetone review on 1.3.7): 1.3.6 auto-detected them; keep that ----
|
||||
const py = "def greet(name):\n return f\"hi {name}\"\n\nclass A:\n pass\n";
|
||||
|
||||
it("an unlabelled block is auto-highlighted and labelled with the detected language", () => {
|
||||
const html = buildCodeBlockHtml(py, "", 0, { wrap: "w", copy: "c" });
|
||||
expect(html).toContain('class="cb-lang">python<');
|
||||
expect(html).toContain('class="hljs language-python"');
|
||||
expect(html).toMatch(/hljs-(keyword|title|string)/);
|
||||
// same as asking highlight.js directly (1.3.6's highlightElement → highlightAuto)
|
||||
expect(highlightAutoCached(py.replace(/\n$/, "")).language).toBe("python");
|
||||
});
|
||||
|
||||
it("autoDetect=false (an open fence while streaming) stays plain \"text\"", () => {
|
||||
const html = buildCodeBlockHtml(py, "", 0, { wrap: "w", copy: "c" }, false, false);
|
||||
expect(html).toContain('class="cb-lang">text<');
|
||||
expect(html).toContain('<code class="hljs">');
|
||||
expect(html).not.toMatch(/hljs-(keyword|title|string)/);
|
||||
});
|
||||
|
||||
it("an explicit language still uses it (no auto-detection), autoDetect or not", () => {
|
||||
for (const auto of [true, false]) {
|
||||
const html = buildCodeBlockHtml("const x: number = 1;", "ts", 0, { wrap: "w", copy: "c" }, false, auto);
|
||||
expect(html).toContain('class="cb-lang">ts<');
|
||||
expect(html).toContain('class="hljs language-ts"');
|
||||
expect(html).toContain("hljs-keyword");
|
||||
}
|
||||
// an unknown label is kept as the label and not auto-detected
|
||||
const unk = buildCodeBlockHtml(py, "notalang", 0, { wrap: "w", copy: "c" });
|
||||
expect(unk).toContain('class="cb-lang">notalang<');
|
||||
expect(unk).not.toMatch(/hljs-(keyword|title|string)/);
|
||||
});
|
||||
|
||||
it("an empty unlabelled block is \"text\"", () => {
|
||||
expect(buildCodeBlockHtml("", "", 0, { wrap: "w", copy: "c" })).toContain('class="cb-lang">text<');
|
||||
});
|
||||
|
||||
it("highlightAuto results are cached (bounded) so a re-render doesn't run it again", () => {
|
||||
const code = "SELECT id, name FROM users WHERE id = 1;";
|
||||
const a = highlightAutoCached(code);
|
||||
expect(highlightAutoCached(code)).toBe(a);
|
||||
for (let i = 0; i < 300; i++) highlightAutoCached(`x${i}`);
|
||||
expect(autoCacheSize()).toBeLessThanOrEqual(128);
|
||||
expect(highlightAutoCached(code)).not.toBe(a); // evicted, recomputed
|
||||
});
|
||||
|
||||
it("isClosedFence matches marked's fence rule for backticks, tildes, indents, and EOF", () => {
|
||||
const fence = (md: string) => {
|
||||
const out: { raw: string; style?: string }[] = [];
|
||||
marked.walkTokens(marked.lexer(md), (tk) => {
|
||||
if (tk.type === "code") out.push({ raw: tk.raw, style: (tk as { codeBlockStyle?: string }).codeBlockStyle });
|
||||
});
|
||||
expect(out.length).toBe(1);
|
||||
return isClosedFence(out[0]!.raw, out[0]!.style);
|
||||
};
|
||||
// closed
|
||||
expect(fence("```\nfoo\n```")).toBe(true);
|
||||
expect(fence("```\nfoo\n```\nafter")).toBe(true);
|
||||
expect(fence("```\nfoo\n```\n\n")).toBe(true);
|
||||
expect(fence("~~~\nfoo\n~~~")).toBe(true);
|
||||
expect(fence("~~~~\nx\n~~~~~ \n\nz")).toBe(true);
|
||||
expect(fence(" ```\nx\n ```")).toBe(true);
|
||||
expect(fence("````\nx\n`````")).toBe(true);
|
||||
expect(fence("```\n```")).toBe(true);
|
||||
expect(fence("> ```\n> a\n> ```")).toBe(true);
|
||||
expect(fence("- item\n\n ```\n a\n ```")).toBe(true);
|
||||
// open (ran into the end of the text)
|
||||
expect(fence("```")).toBe(false);
|
||||
expect(fence("```\n")).toBe(false);
|
||||
expect(fence("```\nfoo")).toBe(false);
|
||||
expect(fence("```\nfoo\n")).toBe(false);
|
||||
expect(fence("```\nfoo\n``")).toBe(false);
|
||||
expect(fence("````\nfoo\n```")).toBe(false);
|
||||
expect(fence("~~~~\nx\n~~~\n")).toBe(false);
|
||||
expect(fence("~~~\nx\n```")).toBe(false);
|
||||
expect(fence("```\na\n````x")).toBe(false);
|
||||
expect(fence("```\na\n``` x")).toBe(false);
|
||||
// indented code has no fence: never "closed" while streaming
|
||||
expect(fence(" indented\n code")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
// Pure helpers for fenced-code HTML: highlight + line split + .cb chrome in one string,
|
||||
// so React can paint the final height on the first commit (no post-paint decorate flicker).
|
||||
import hljs from "highlight.js/lib/common";
|
||||
|
||||
export function escapeHtml(s: string): string {
|
||||
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
export function sanitizeLang(lang: string | undefined | null): string {
|
||||
if (!lang) return "";
|
||||
const m = /[\w+#.-]+/.exec(lang.trim());
|
||||
return m?.[0] ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a fenced code token from marked ended on its own closing fence (not at the end of the input).
|
||||
* `raw` is the token's raw source (marked has already taken off any blockquote / list indentation).
|
||||
* Mirrors marked's fence rule: opening ` {0,3}(`{3,}|~{3,})`, closing ` {0,3}<same fence>[~`]* *` on its own line.
|
||||
* An indented code block has no fence: it can always grow while the text streams, so it is never "closed".
|
||||
*/
|
||||
export function isClosedFence(raw: string, codeBlockStyle?: string): boolean {
|
||||
if (codeBlockStyle === "indented") return false;
|
||||
const lines = raw.replace(/\n+$/, "").split("\n");
|
||||
if (lines.length < 2) return false;
|
||||
const open = /^ {0,3}(`{3,}|~{3,})/.exec(lines[0]!);
|
||||
if (!open) return false;
|
||||
const fence = open[1]!;
|
||||
const last = lines[lines.length - 1]!;
|
||||
const m = /^ {0,3}([`~]+) *$/.exec(last);
|
||||
if (!m) return false;
|
||||
const run = m[1]!;
|
||||
// same fence (char and at least its length) first; marked lets any mix of ` / ~ follow it
|
||||
return run.startsWith(fence);
|
||||
}
|
||||
|
||||
type AutoResult = { value: string; language: string };
|
||||
const AUTO_CACHE_MAX = 128;
|
||||
const autoCache = new Map<string, AutoResult>();
|
||||
|
||||
/** hljs.highlightAuto with a small LRU: a streaming message re-renders every frame, and a block that is
|
||||
* already closed (or a settled message re-rendered) must not pay highlightAuto again. */
|
||||
export function highlightAutoCached(code: string): AutoResult {
|
||||
const hit = autoCache.get(code);
|
||||
if (hit) {
|
||||
autoCache.delete(code);
|
||||
autoCache.set(code, hit);
|
||||
return hit;
|
||||
}
|
||||
let out: AutoResult;
|
||||
try {
|
||||
const res = hljs.highlightAuto(code);
|
||||
out = { value: res.value, language: res.language ?? "" };
|
||||
} catch {
|
||||
out = { value: escapeHtml(code), language: "" };
|
||||
}
|
||||
autoCache.set(code, out);
|
||||
if (autoCache.size > AUTO_CACHE_MAX) autoCache.delete(autoCache.keys().next().value!);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** test hook */
|
||||
export function autoCacheSize(): number {
|
||||
return autoCache.size;
|
||||
}
|
||||
|
||||
const OPEN_RE = /^<span\s+class="([^"]*)">/i;
|
||||
const CLOSE_RE = /^<\/span>/i;
|
||||
|
||||
/**
|
||||
* Split highlight.js HTML into one HTML fragment per source line.
|
||||
* Spans that cross a newline are closed and re-opened on the next line (matches prior DOM walk).
|
||||
*/
|
||||
export function splitHljsHtmlLines(hl: string): string[] {
|
||||
const lines: string[] = [""];
|
||||
let i = 0;
|
||||
const stack: string[] = [];
|
||||
const openSpan = (cls: string) => `<span class="${cls}">`;
|
||||
|
||||
while (i < hl.length) {
|
||||
if (hl.charCodeAt(i) === 10 /* \n */) {
|
||||
for (let k = stack.length - 1; k >= 0; k--) lines[lines.length - 1] += "</span>";
|
||||
lines.push("");
|
||||
for (const cls of stack) lines[lines.length - 1] += openSpan(cls);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (hl[i] === "<") {
|
||||
const rest = hl.slice(i);
|
||||
const open = OPEN_RE.exec(rest);
|
||||
if (open) {
|
||||
stack.push(open[1]!);
|
||||
lines[lines.length - 1] += open[0];
|
||||
i += open[0].length;
|
||||
continue;
|
||||
}
|
||||
const close = CLOSE_RE.exec(rest);
|
||||
if (close) {
|
||||
stack.pop();
|
||||
lines[lines.length - 1] += close[0];
|
||||
i += close[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// text / entities / any other tag char — copy through until next < or \n
|
||||
let j = i + 1;
|
||||
while (j < hl.length && hl[j] !== "<" && hl.charCodeAt(j) !== 10) j++;
|
||||
lines[lines.length - 1] += hl.slice(i, j);
|
||||
i = j;
|
||||
}
|
||||
|
||||
while (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
const SVG = (d: string) =>
|
||||
`<svg 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"><path d="${d}"></path></svg>`;
|
||||
|
||||
export const ICON_COPY = "M8 8h11v12H8zM5 16V4h11";
|
||||
export const ICON_CHECK = "M5 13l4 4L19 7";
|
||||
export const ICON_WRAP = "M4 6h16M4 12h13a3 3 0 0 1 0 6h-4m2-2-2 2 2 2M4 18h5";
|
||||
|
||||
export function svgIconHtml(d: string): string {
|
||||
return SVG(d);
|
||||
}
|
||||
|
||||
// The model's markdown is sanitized with DOMPurify's html profile only (no <svg>), so the code block chrome can't
|
||||
// carry its icons through sanitize. The renderer writes these per-load random placeholders instead (plain text
|
||||
// to DOMPurify), and restoreCodeBlockIcons swaps them for the static icons right after sanitize — still one pass.
|
||||
function randomHex(): string {
|
||||
const b = new Uint8Array(12);
|
||||
globalThis.crypto.getRandomValues(b);
|
||||
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
const ICON_NONCE = randomHex();
|
||||
export const WRAP_ICON_TOKEN = `__AC_CB_WRAP_${ICON_NONCE}__`;
|
||||
export const COPY_ICON_TOKEN = `__AC_CB_COPY_${ICON_NONCE}__`;
|
||||
|
||||
/** Put the trusted icons into sanitized markdown HTML (replaces only the exact placeholders) */
|
||||
export function restoreCodeBlockIcons(html: string): string {
|
||||
return html.split(WRAP_ICON_TOKEN).join(SVG(ICON_WRAP)).split(COPY_ICON_TOKEN).join(SVG(ICON_COPY));
|
||||
}
|
||||
|
||||
export type CodeBlockLabels = { wrap: string; copy: string };
|
||||
|
||||
/**
|
||||
* Build the final .cb HTML (header + optional numbered lines + highlighted body) in one pass.
|
||||
* The buttons carry WRAP_ICON_TOKEN / COPY_ICON_TOKEN; restoreCodeBlockIcons turns them into icons after sanitize.
|
||||
* autoDetect: a block with no language label gets hljs.highlightAuto and the detected language as its label
|
||||
* (as 1.3.6 did). The renderer turns it off only for a still-open trailing fence of a streaming message, so the
|
||||
* label and colours can't flip while tokens arrive; it is on for closed blocks and settled messages.
|
||||
*/
|
||||
export function buildCodeBlockHtml(
|
||||
raw: string,
|
||||
lang: string | undefined,
|
||||
index: number,
|
||||
labels: CodeBlockLabels,
|
||||
wrapped = false,
|
||||
autoDetect = true,
|
||||
): string {
|
||||
let fence = sanitizeLang(lang);
|
||||
const bodyRaw = raw.replace(/\n$/, "");
|
||||
let hl: string;
|
||||
try {
|
||||
if (fence && hljs.getLanguage(fence)) {
|
||||
hl = hljs.highlight(bodyRaw, { language: fence }).value;
|
||||
} else if (!fence && autoDetect && bodyRaw) {
|
||||
const auto = highlightAutoCached(bodyRaw);
|
||||
hl = auto.value;
|
||||
fence = sanitizeLang(auto.language);
|
||||
} else {
|
||||
hl = escapeHtml(bodyRaw);
|
||||
}
|
||||
} catch {
|
||||
hl = escapeHtml(bodyRaw);
|
||||
}
|
||||
const lines = splitHljsHtmlLines(hl);
|
||||
const numbered = lines.length > 1;
|
||||
const body = numbered
|
||||
? lines.map((l) => `<span class="cb-l">${l}</span>`).join("")
|
||||
: (lines[0] ?? "");
|
||||
const langLabel = escapeHtml(fence || "text");
|
||||
const wrapTitle = escapeHtml(labels.wrap);
|
||||
const copyTitle = escapeHtml(labels.copy);
|
||||
const cls = `cb${numbered ? " numbered" : ""}${wrapped ? " wrap" : ""}`;
|
||||
return (
|
||||
`<div class="${cls}">` +
|
||||
`<div class="cb-head">` +
|
||||
`<span class="cb-lang">${langLabel}</span>` +
|
||||
`<span class="cb-acts">` +
|
||||
`<button type="button" class="cb-btn cb-wrap" title="${wrapTitle}" aria-label="${wrapTitle}" aria-pressed="${wrapped}">${WRAP_ICON_TOKEN}</button>` +
|
||||
`<button type="button" class="cb-btn cb-copy" title="${copyTitle}" aria-label="${copyTitle}" data-i="${index}">${COPY_ICON_TOKEN}</button>` +
|
||||
`</span>` +
|
||||
`</div>` +
|
||||
`<pre><code class="hljs${fence ? ` language-${fence}` : ""}">${body}</code></pre>` +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Markdown → sanitized HTML (marked + DOMPurify + highlight.js), kept apart from the React component so it can be
|
||||
// bundled and tested on its own in a real browser.
|
||||
// Fenced code is built as the final .cb / header / numbered / highlighted HTML inside marked's renderer (1.3.7), so
|
||||
// React paints the stable height in one commit. The model's markdown is sanitized with the html profile only (as in
|
||||
// 1.3.6: an <svg> the model writes is dropped); the code block icons are placeholders until after sanitize.
|
||||
import { marked, Renderer, type Tokens } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { t } from "../i18n/index.js";
|
||||
import { buildCodeBlockHtml, isClosedFence, restoreCodeBlockIcons } from "./codeBlock";
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
const purify = (html: string) =>
|
||||
DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["target", "aria-pressed", "aria-label", "aria-hidden", "data-i"],
|
||||
});
|
||||
|
||||
export type RenderedMarkdown = { html: string; raws: string[] };
|
||||
|
||||
export type RenderMarkdownOptions = {
|
||||
/** indexes of the code blocks (in this text) drawn soft-wrapped */
|
||||
wrapped?: ReadonlySet<number>;
|
||||
/** the message is still streaming: an unlabelled fence that isn't closed yet stays plain "text" (no
|
||||
* highlightAuto flip-flop while it grows); closed unlabelled blocks are auto-detected (cached) */
|
||||
streaming?: boolean;
|
||||
};
|
||||
|
||||
export function renderMarkdown(text: string, opts: RenderMarkdownOptions = {}): RenderedMarkdown {
|
||||
const { wrapped, streaming = false } = opts;
|
||||
const raws: string[] = [];
|
||||
const renderer = new Renderer();
|
||||
renderer.code = ({ text: code, lang, raw, codeBlockStyle }: Tokens.Code) => {
|
||||
const index = raws.length;
|
||||
raws.push(code);
|
||||
const autoDetect = !streaming || isClosedFence(raw, codeBlockStyle);
|
||||
return buildCodeBlockHtml(code, lang, index, {
|
||||
wrap: t("timeline.codeWrap"),
|
||||
copy: t("common.copy"),
|
||||
}, wrapped?.has(index) ?? false, autoDetect);
|
||||
};
|
||||
const dirty = marked.parse(text, { async: false, renderer }) as string;
|
||||
return { html: restoreCodeBlockIcons(purify(dirty)), raws };
|
||||
}
|
||||
Reference in New Issue
Block a user