agent-console 1.2.0: Preview tab, chat links, file chips, font size/width settings, live magpie theme (#582)
agent-console 1.2.0 by qingnian108 (#582): Preview tab, chat links, file chips, font size/width settings, live magpie theme. Reviewed and run at c459773107caa20f7063d12b2133c230f91c066c (mote, macOS, Node 22, sandbox HOME): - npm ci --workspaces=false; npm run check ok; npm test: 48 files, 339 passed, 17 skipped; npm run verify:build 5/5 OK; bun scripts/check.mjs agent-console ok. - Only test/v1/ws.test.ts changed since the last reviewed head 66d1070 (the new "preview.open returns host from previewHost()" test, through registerMethods). - Broke by hand: methods.ts `return { ...r, host: previewHost() }` -> `return r;` turns that test red (1 of 5); restored, green. Changing previewHost's body alone stays green, as the test compares to previewHost(); fix582.test.ts covers its values. - Earlier reviews' findings (per-listener key host, nonce/canary, gateway port + identity check, mentions path, Darwin major from the daemon) were checked in the earlier rounds. The proxy listens on 127.0.0.1 only and answers only the keyed Host. - Not run: preview-attack.mjs browser half at this head, Windows box.
This commit is contained in:
@@ -49,7 +49,12 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
- **Images**: attach or paste images (and text files). Only PNG, JPEG, GIF and WebP are sent as images. Claude Code and Codex take them natively; Claude Code gets a text file (up to 1 MB) as a plain-text document, Codex gets its path; any other file (SVG, binaries, images over Claude's 5 MB limit) goes by path, with a notice. An ACP Agent (Cursor, Copilot, OpenCode, Pi, Devin CLI, dsh) gets image blocks when its ACP `initialize` advertises `promptCapabilities.image`; otherwise it gets each image's file path (as text and a `resource_link`), so it can open it with its file tools, and the timeline says it can't see the image itself. The composer says so before you send once the Agent has been asked. dsh answers `initialize` for the route its ACP starts on (its `acp` config row, which ships as a model dsh's catalog doesn't have) and refuses image blocks otherwise, so Agent Console starts dsh with a `--patch` overlay that puts that row on the conversation's model: on a model that sees images (Magpie writes those as `input: [text, image]`) dsh then takes image blocks; after a switch to another model in the same chat, images go by path and dsh opens them with its `read_image` tool. Checked on 2026-10-31 with the real CLIs, a throwaway HOME, no sign-in and a local stand-in for the model API (`npm run test:real`, see `test/real/`): the image reaches the model request from Claude Code 2.1.316 (stream-json), Codex 0.165.0, Copilot 1.0.105 (BYOK), OpenCode 1.19.5, Pi (pi-acp 0.0.34 + pi 1.4.0) and dsh 0.2.1-rc.5; Devin CLI 3000.11.234 and Cursor 2026.10.22 advertise images and Devin gets the image block, but both need a sign-in to run a model. Inline media is capped at 10 MB per file and 16 MB per message (an ACP SDK peer refuses messages over 32 MB); larger images go by path
|
||||
- **Import history**: import matching sessions from `~/.claude/projects` and `~/.codex/sessions` as new threads (resumable)
|
||||
- **Thread management**: search (Ctrl+K), pin, rename, archive, delete (trash), export Markdown, thread info (usage / cost / session ID)
|
||||
- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 8 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit`) so UI work does not burn tokens
|
||||
- **Preview tab** (1.2): a small browser in the right panel for local dev servers (`localhost`, `127.0.0.1`, `[::1]`, `*.localhost`, `0.0.0.0`): address bar, back / forward, reload, open in the system browser, widen the panel. The address is remembered per conversation. Pages load through the daemon's local preview proxy (see the security model), so module scripts, `fetch` and HMR WebSockets work inside Magpie's sandboxed frame. Limits: popups, `alert` and native form posts don't run in the sandbox; `localStorage` / `sessionStorage` / `document.cookie` are in-memory and reset on reload, and cookies are not passed (use 用浏览器打开 / Open in browser for logins)
|
||||
- **Links in chat** (1.2): local addresses in agent text, rendered Markdown and tool output (`localhost:5173`, `http://127.0.0.1:8080/x`, …) become links that open in the Preview tab; Ctrl/⌘+click, and any other `http(s)` link, opens the system browser through the daemon (`app.openExternal`: http/https only, re-serialized, run with `execFile` and no shell: `rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `xdg-open` on Linux; if that fails the link is copied). The terminal is not linkified
|
||||
- **File chips** (1.2): drag a row from the Files tab into the composer, or right-click → 插入到聊天 / Add to chat, to attach a path chip. Chips are sent as project-relative paths, checked by the daemon (inside the project, no `..`, no symlink escape, must exist, at most 50), and reach the Agent as a "Referenced files" section with absolute paths after your text (plus `resource_link` blocks for ACP Agents). Dropping files from the OS file manager still uploads them as attachments
|
||||
- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted
|
||||
- **Follows Magpie live** (1.2): light/dark, Magpie's neutral colours and its language follow Magpie while the page is open (and after a reconnect); the accent stays neutral grey
|
||||
- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 9 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve`) so UI work does not burn tokens
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -84,6 +89,18 @@ The daemon can run Agents with full access to your machine, so the token that un
|
||||
- WebSocket connections must send `hello` with the token within 5 seconds, otherwise they are closed with code 4401.
|
||||
- **Coming back after a plugin host restart.** Magpie restarts its plugin host from time to time; the old host's daemon exits with it and the new host has a new gate key. `boot.js` passes its own page URL to the gate as `back`; the gate accepts it only if it is a loopback `/_magpie/plugin/<id>/index.html` URL and forwards it **only in the fragment** (`#t=…&b=…`). When the daemon page can't reconnect for 5 seconds (or on 重试 / Retry) it navigates back to that page, which reads the fresh `session.js` and opens the new gate. To tell a live host's `session.js` from one a killed host left behind (a hard kill can't delete it), the file carries `ts` and `beat`: from the first page open on, the host rewrites it every 4 s, and after a lost connection `boot.js` only takes a file written after the loss; a host that was never opened doesn't rewrite it, and a new host deletes a file whose writer (pid in `session-owner.json`, outside the page folder) is gone before Magpie serves the page. The daemon page checks the URL again before following it, so it is never an open redirect, and the token never leaves its own fragment.
|
||||
|
||||
### Preview proxy (1.2)
|
||||
|
||||
The Preview tab can't frame a dev server directly: Magpie's frame is sandboxed without `allow-same-origin`, so the page would run with an opaque origin and module scripts, `fetch` and storage break. The daemon runs a small reverse proxy instead:
|
||||
|
||||
- **Created only over the authenticated WebSocket** (`preview.open`); there is no HTTP route to start one.
|
||||
- **Loopback targets only**: `localhost`, `*.localhost`, `127.0.0.0/8`, `0.0.0.0`, `::1`/`::`, `http:` or `https:`, no user-info, at most 2048 characters. Anything else is refused before a socket is opened.
|
||||
- **Refused ports**: the daemon's own port, the gate (`--gate-port`, 3488), Magpie (3425, 3430, any port in `MAGPIE_ADDR` / `MAGPIE_WEB_ADDR` / `MAGPIE_URL`, and the gateway port saved in Magpie's own `settings.json`, read again on every open: the portable `data` folder beside Magpie, `$XDG_CONFIG_HOME/magpie`, `~/.config/magpie`), the proxy's own ports, plus `AGENT_CONSOLE_PREVIEW_DENY` (comma-separated). Whatever the port, a target whose `GET /` answers like Magpie's gateway (`{"name":"magpie",…}`), or that replies with `X-Magpie-*` headers, is refused; the check is repeated every minute and fails closed (no answer → nothing forwarded).
|
||||
- **A key on every request**: each listener answers only at `http://ac<128-bit random key>.localhost:<port>`. The preview frame is an opaque origin (Magpie's sandbox is inherited), so its requests carry `Origin: null` and no `Referer`, exactly what any other web page can send from a sandboxed iframe of its own, and the port can be found by scanning. The host name is the one thing the browser attaches to every request the frame makes (navigations, module scripts and their imports, `fetch`, CSS `url()`, workers, the HMR WebSocket) that another page can't know. A request with any other `Host` is refused before anything is forwarded and gets no CORS headers: `127.0.0.1:<port>` / `localhost:<port>` → 403, anything else → 421 (DNS rebinding). Responses carry `Referrer-Policy: no-referrer` so the key isn't sent on to other sites. `preview.open` also returns a per-open nonce over the authenticated WebSocket; `GET /__agent_console__/ping` must echo it exactly (a plain 200 `ok` from a hostile DNS answer is refused and the listener is released). Before the keyed name is looked up, the panel probes a keyless canary (`acprobe<random>.localhost` on the same port) the same way. Apple WebKit before macOS 26 (Magpie's Mac app on 12–15, Safari with `magpie web`) asks network DNS for `*.localhost`, so it is refused before any such name is looked up and the listener is released. The macOS version doesn't come from the user agent (Apple froze it at `Mac OS X 10_15_7`, macOS 26+ included): `preview.open` reports the daemon's own `os.platform()` and the Darwin major of `os.release()` (25 = macOS 26), and the panel refuses only Apple WebKit on a Darwin host below 25, or when that answer is missing. The daemon listens on 127.0.0.1 only, so the page and the daemon run on the same machine; the keyless canary stays as the runtime check either way. Chromium / WebView2, WebKitGTK and WebKit on macOS 26+ resolve `*.localhost` to loopback themselves. Where the preview can't run, the panel offers the system browser instead.
|
||||
- **One listener per target origin** on `127.0.0.1` with a random port (at most 8, least recently used closed first). Every request and upgrade checks `Host` (above) and `Origin` (absent, `null` or the proxy's own origin, else 403).
|
||||
- **Headers**: upstream gets the target's `Host` and `Origin`; `Cookie`, `Forwarded` and `X-Forwarded-*` are dropped. Responses lose `X-Frame-Options`, the CSP `frame-ancestors` directive, `Set-Cookie` and upstream CORS headers; same-target redirects are rewritten to the proxy; CORS is answered for the opaque frame only, and only on requests that carry the key (`access-control-allow-origin: null`, no credentials). Cookies are dropped both ways because cookies for `127.0.0.1` are shared across ports. HTML gets one injected script (`/__agent_console__/preview.js`) that reports the address and title to the panel and accepts back / forward / reload from the parent frame only.
|
||||
- **Closed when idle**: after 10 minutes without traffic (an open HMR socket counts as traffic), when the Preview tab closes or changes origin, when the last WebSocket client disconnects, and on daemon exit.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
- Importing `index.mjs` has no side effects (no port, no process, no files).
|
||||
@@ -184,7 +201,7 @@ npm run shot:v1 # screenshot set (light/dark × scenes → _tmp/shots-v1/)
|
||||
|
||||
# Mock (no real tokens)
|
||||
AGENT_CONSOLE_MOCK=1 npm run dev
|
||||
# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit
|
||||
# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit /serve (local links, 1.2)
|
||||
```
|
||||
|
||||
| Env | Purpose |
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1224
-150
File diff suppressed because it is too large
Load Diff
+1
-1
File diff suppressed because one or more lines are too long
@@ -2,6 +2,8 @@
|
||||
// Adapters call callInfo(name, input, cwd) to get {kind, title, detail}; the frontend renders by kind.
|
||||
import type { ToolKind } from "../timeline/types.js";
|
||||
import { tr } from "../util/i18n.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
|
||||
const MAX_CMD = 80;
|
||||
const trunc = (s: string, n = MAX_CMD): string => (s.length > n ? s.slice(0, n - 1) + "…" : s);
|
||||
@@ -18,6 +20,17 @@ export function relPath(p: string, cwd: string): string {
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Whether a Write target already exists (checked when the tool call arrives, i.e. before it runs). */
|
||||
export function targetExists(input: Record<string, unknown>, cwd = ""): boolean {
|
||||
const p = String(input.file_path ?? input.path ?? "");
|
||||
if (!p) return false;
|
||||
try {
|
||||
return existsSync(isAbsolute(p) || !cwd ? p : resolve(cwd, p));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export type CallInfo = { kind: ToolKind; title: string; detail: Record<string, unknown> };
|
||||
|
||||
type ToolInput = Record<string, unknown> & { _exists?: boolean };
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Coalescer } from "../timeline/coalescer.js";
|
||||
import { ApiError } from "../ws/methods.js";
|
||||
import { log } from "../log.js";
|
||||
import { tr } from "../util/i18n.js";
|
||||
import { resolveMentions, withMentions, type Mention, type MentionRef } from "../util/mentions.js";
|
||||
import {
|
||||
codexSlashCommandsFromEntries,
|
||||
loadCodexSlashEntries,
|
||||
@@ -26,7 +27,7 @@ const SLASH_CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
/** Idle Agent processes kept warm at most (one per conversation); older idle ones are closed (resumed on the next message) */
|
||||
export const MAX_WARM_IDLE = 3;
|
||||
|
||||
type QueuedMessage = { id: string; text: string; attachments: { path: string; mime: string; name?: string }[] };
|
||||
type QueuedMessage = { id: string; text: string; attachments: { path: string; mime: string; name?: string }[]; mentions?: Mention[] };
|
||||
type PendingRequest = {
|
||||
kind: "permission" | "question";
|
||||
requestId: string;
|
||||
@@ -80,6 +81,18 @@ export class AgentManager {
|
||||
return resolveAttachmentRefs(this.attachments, refs);
|
||||
}
|
||||
|
||||
/** Mentions from the Files panel → absolute paths inside the project; a path that can't be used gets a notice */
|
||||
private async resolveMentionRefs(threadId: string, projectId: string, refs: MentionRef[] | undefined): Promise<Mention[]> {
|
||||
if (!refs?.length) return [];
|
||||
const proj = await this.projects.get(projectId);
|
||||
if (!proj) return [];
|
||||
const { mentions, warnings } = await resolveMentions(proj.path, refs);
|
||||
if (warnings.length) {
|
||||
await this.appendRaw(threadId, { type: "notice", level: "warn", message: tr("notice.mentionSkipped", { paths: warnings.join(", ") }) });
|
||||
}
|
||||
return mentions;
|
||||
}
|
||||
|
||||
private attachmentLabels(refs: { path: string; mime: string; name?: string }[]) {
|
||||
return refs.map((a) => ({ id: a.path, name: (a.name ?? "").trim() || a.path, mime: a.mime }));
|
||||
}
|
||||
@@ -207,8 +220,9 @@ export class AgentManager {
|
||||
}
|
||||
|
||||
// ---- send ----
|
||||
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior: SendBehavior = "queue"): Promise<"started" | "steered" | "queued"> {
|
||||
async send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[]; mentions?: MentionRef[] }, behavior: SendBehavior = "queue"): Promise<"started" | "steered" | "queued"> {
|
||||
const meta = await this.mustThread(threadId);
|
||||
const mentions = await this.resolveMentionRefs(threadId, meta.projectId, input.mentions);
|
||||
if (meta.archived) {
|
||||
await this.threads.patch(threadId, { archived: false });
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
@@ -232,12 +246,13 @@ export class AgentManager {
|
||||
if (behavior === "steer" && provider?.capabilities.steer && rt.session?.steer && !rt.starting) {
|
||||
try {
|
||||
const images = await this.resolveAttachments(attachmentRefs);
|
||||
await rt.session.steer({ text: input.text, images });
|
||||
await rt.session.steer({ text: withMentions(input.text, mentions), images, mentions });
|
||||
await this.appendRaw(threadId, {
|
||||
type: "user_message",
|
||||
text: input.text,
|
||||
steered: true,
|
||||
attachments: this.attachmentLabels(attachmentRefs),
|
||||
...(mentions.length ? { mentions } : {}),
|
||||
});
|
||||
return "steered";
|
||||
} catch (e) {
|
||||
@@ -245,27 +260,27 @@ export class AgentManager {
|
||||
log("info", `thread ${threadId} 插话失败,改为排队:${String(e)}`);
|
||||
}
|
||||
}
|
||||
const q: QueuedMessage = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs };
|
||||
const q: QueuedMessage = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs, ...(mentions.length ? { mentions } : {}) };
|
||||
rt.queue.push(q);
|
||||
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
|
||||
return "queued";
|
||||
}
|
||||
|
||||
await this.startTurn(threadId, input.text, attachmentRefs);
|
||||
await this.startTurn(threadId, input.text, attachmentRefs, mentions);
|
||||
return "started";
|
||||
}
|
||||
|
||||
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[]): Promise<void> {
|
||||
private async startTurn(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[] = []): Promise<void> {
|
||||
const rt = this.rt(threadId);
|
||||
rt.starting = true;
|
||||
try {
|
||||
await this.startTurnInner(threadId, text, attachmentRefs);
|
||||
await this.startTurnInner(threadId, text, attachmentRefs, mentions);
|
||||
} finally {
|
||||
rt.starting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async startTurnInner(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[]): Promise<void> {
|
||||
private async startTurnInner(threadId: string, text: string, attachmentRefs: { path: string; mime: string; name?: string }[], mentions: Mention[]): Promise<void> {
|
||||
const meta = await this.mustThread(threadId);
|
||||
const rt = this.rt(threadId);
|
||||
// Conversations that already ran (have a providerSessionId) ignore "disabled": disabling only blocks new conversations
|
||||
@@ -293,11 +308,12 @@ export class AgentManager {
|
||||
type: "user_message",
|
||||
text,
|
||||
attachments: this.attachmentLabels(attachmentRefs),
|
||||
...(mentions.length ? { mentions } : {}),
|
||||
});
|
||||
await this.setStatus(threadId, "running");
|
||||
try {
|
||||
const images = await this.resolveAttachments(attachmentRefs);
|
||||
await rt.session!.send({ text, images });
|
||||
await rt.session!.send({ text: withMentions(text, mentions), images, mentions });
|
||||
} catch (e) {
|
||||
// A failed send must not leave the conversation running
|
||||
const msg = String((e as Error)?.message ?? e);
|
||||
@@ -440,7 +456,7 @@ export class AgentManager {
|
||||
if (next) {
|
||||
this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue });
|
||||
// A queued message that fails to start is only logged; it must not break the event pump (startTurn already wrote notice/turn_ended)
|
||||
await this.startTurn(threadId, next.text, next.attachments).catch((e) => {
|
||||
await this.startTurn(threadId, next.text, next.attachments, next.mentions ?? []).catch((e) => {
|
||||
log("warn", `thread ${threadId} 排队消息启动失败:${String(e)}`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ export type Config = {
|
||||
idleExitMinutes: number;
|
||||
buildStamp: string;
|
||||
parentPid?: number;
|
||||
/** The plugin gate's port (index.mjs passes --gate-port); the preview refuses it */
|
||||
gatePort?: number;
|
||||
};
|
||||
|
||||
function pkgVersion(): string {
|
||||
@@ -35,6 +37,7 @@ export function parseConfig(argv: string[]): Config {
|
||||
let data: string | null = null;
|
||||
let token: string | null = null;
|
||||
let parentPid: number | undefined;
|
||||
let gatePort: number | undefined;
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === "--port" && argv[i + 1]) port = Number(argv[++i]);
|
||||
@@ -45,6 +48,8 @@ export function parseConfig(argv: string[]): Config {
|
||||
else if (a.startsWith("--token=")) token = a.slice(8);
|
||||
else if (a === "--parent-pid" && argv[i + 1]) parentPid = Number(argv[++i]);
|
||||
else if (a.startsWith("--parent-pid=")) parentPid = Number(a.slice(13));
|
||||
else if (a === "--gate-port" && argv[i + 1]) gatePort = Number(argv[++i]);
|
||||
else if (a.startsWith("--gate-port=")) gatePort = Number(a.slice(12));
|
||||
}
|
||||
if (port == null || !Number.isInteger(port) || port < 0 || port > 65535) {
|
||||
const envPort = Number(process.env.AGENT_CONSOLE_PORT || "");
|
||||
@@ -61,5 +66,6 @@ export function parseConfig(argv: string[]): Config {
|
||||
idleExitMinutes: Number.isFinite(idleEnv) && idleEnv > 0 ? idleEnv : 60,
|
||||
buildStamp: daemonBuildStamp(),
|
||||
parentPid: Number.isInteger(parentPid) ? parentPid : undefined,
|
||||
gatePort: Number.isInteger(gatePort) && gatePort! > 0 && gatePort! <= 65535 ? gatePort : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import { GitService } from "./git/service.js";
|
||||
import { FileService } from "./files/service.js";
|
||||
import { TerminalService } from "./terminal/service.js";
|
||||
import { augmentPath, pidAlive } from "./util/proc.js";
|
||||
import { PreviewProxy } from "./preview/proxy.js";
|
||||
import { previewDeniedPorts } from "./preview/ports.js";
|
||||
|
||||
// The bundle targets node20: an older Node (or being started by Bun by mistake) gets a clear message instead of crashing on some API
|
||||
const nodeMajor = Number(/^v?(\d+)/.exec(process.versions.node ?? "")?.[1] ?? 0);
|
||||
@@ -68,6 +70,12 @@ async function main(): Promise<void> {
|
||||
const manager = new AgentManager(gateway, threads, projects, settings, attachments);
|
||||
await manager.recoverOnStart();
|
||||
const terminals = new TerminalService(gateway);
|
||||
const preview = new PreviewProxy({
|
||||
deniedPorts: () => previewDeniedPorts(cfg),
|
||||
log: (level, msg) => log(level, msg),
|
||||
});
|
||||
// Last page gone → no preview frame is left to use the proxies
|
||||
gateway.onConnectionClosed = (left) => { if (left === 0) preview.closeAll(); };
|
||||
registerMethods(gateway, {
|
||||
cfg,
|
||||
settings,
|
||||
@@ -78,6 +86,7 @@ async function main(): Promise<void> {
|
||||
git: new GitService(),
|
||||
files: new FileService(),
|
||||
terminals,
|
||||
preview,
|
||||
runtime: (id) => manager.runtimeInfo(id),
|
||||
});
|
||||
|
||||
@@ -155,6 +164,7 @@ async function main(): Promise<void> {
|
||||
shuttingDown = true;
|
||||
log("info", "daemon 关闭中");
|
||||
terminals.killAll();
|
||||
preview.closeAll();
|
||||
gateway.closeAll();
|
||||
try {
|
||||
rmSync(daemonJsonPath, { force: true });
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// What the page needs to know about the daemon's OS to decide whether the in-panel preview can run (#582).
|
||||
// Apple froze the OS version in the WebKit UA at "Mac OS X 10_15_7" (WKWebView and Safari on macOS 26+ still send it),
|
||||
// so the page can't tell macOS 15 from 26 by itself. The daemon runs on the same Mac (it listens on 127.0.0.1 only)
|
||||
// and reads the real version: Darwin kernel 25.x is macOS 26, whose WebKit resolves *.localhost to loopback itself.
|
||||
import os from "node:os";
|
||||
|
||||
export type PreviewHost = {
|
||||
/** os.platform() of the daemon host */
|
||||
platform: string;
|
||||
/** major of os.release() when platform is darwin (25 = macOS 26), else null; null too when it can't be parsed */
|
||||
darwinMajor: number | null;
|
||||
};
|
||||
|
||||
/** Darwin 25 = macOS 26, the first macOS whose WebKit answers *.localhost with loopback without asking DNS */
|
||||
export const DARWIN_LOCALHOST_LOOPBACK = 25;
|
||||
|
||||
export function previewHost(platform: string = os.platform(), release: string = os.release()): PreviewHost {
|
||||
if (platform !== "darwin") return { platform, darwinMajor: null };
|
||||
const m = /^(\d+)\./.exec(String(release ?? "").trim()) ?? /^(\d+)$/.exec(String(release ?? "").trim());
|
||||
const major = m ? Number(m[1]) : NaN;
|
||||
return { platform, darwinMajor: Number.isInteger(major) && major > 0 ? major : null };
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// The small script the preview proxy adds to HTML pages it serves (as /__agent_console__/preview.js, an external script
|
||||
// so a dev app's CSP against inline scripts doesn't block it). Inside Magpie the preview frame is an opaque origin
|
||||
// (sandbox="allow-scripts" is inherited), so:
|
||||
// 1. localStorage / sessionStorage / document.cookie throw SecurityError → replace them with in-memory stand-ins
|
||||
// (lost on reload; the README says so);
|
||||
// 2. navigation bridge: report {ac_preview:1, href, title} to the parent page, and take {ac_preview_cmd} back/forward/reload
|
||||
// from the parent only. Nothing else is accepted.
|
||||
export const PREVIEW_SCRIPT_PATH = "/__agent_console__/preview.js";
|
||||
|
||||
export const PREVIEW_SCRIPT = `(function(){
|
||||
"use strict";
|
||||
if (window.__acPreview) return; window.__acPreview = 1;
|
||||
function mem(){ var m = new Map(); var s = {
|
||||
getItem: function(k){ k = String(k); return m.has(k) ? m.get(k) : null; },
|
||||
setItem: function(k, v){ m.set(String(k), String(v)); },
|
||||
removeItem: function(k){ m.delete(String(k)); },
|
||||
clear: function(){ m.clear(); },
|
||||
key: function(i){ var a = Array.from(m.keys()); return i >= 0 && i < a.length ? a[i] : null; }
|
||||
}; Object.defineProperty(s, "length", { get: function(){ return m.size; } }); return s; }
|
||||
["localStorage", "sessionStorage"].forEach(function(n){
|
||||
var ok = true; try { var st = window[n]; st.getItem("__ac"); } catch (e) { ok = false; }
|
||||
if (!ok) { try { Object.defineProperty(window, n, { value: mem(), configurable: true }); } catch (e) {} }
|
||||
});
|
||||
try { void document.cookie; } catch (e) {
|
||||
var jar = {};
|
||||
try { Object.defineProperty(document, "cookie", { configurable: true,
|
||||
get: function(){ return Object.keys(jar).map(function(k){ return k + "=" + jar[k]; }).join("; "); },
|
||||
set: function(v){ var p = String(v).split(";")[0]; var i = p.indexOf("="); if (i > 0) jar[p.slice(0, i).trim()] = p.slice(i + 1).trim(); }
|
||||
}); } catch (e2) {}
|
||||
}
|
||||
var parentWin = window.parent;
|
||||
if (!parentWin || parentWin === window) return;
|
||||
var last = "";
|
||||
function report(){ try {
|
||||
var msg = { ac_preview: 1, href: String(location.href), title: String(document.title || "") };
|
||||
var key = msg.href + "\\n" + msg.title; if (key === last) return; last = key;
|
||||
parentWin.postMessage(msg, "*");
|
||||
} catch (e) {} }
|
||||
["pushState", "replaceState"].forEach(function(k){
|
||||
var orig = history[k]; if (typeof orig !== "function") return;
|
||||
history[k] = function(){ var r = orig.apply(this, arguments); setTimeout(report, 0); return r; };
|
||||
});
|
||||
window.addEventListener("popstate", report);
|
||||
window.addEventListener("hashchange", report);
|
||||
window.addEventListener("load", report);
|
||||
document.addEventListener("DOMContentLoaded", report);
|
||||
setInterval(report, 1000);
|
||||
window.addEventListener("message", function(e){
|
||||
if (e.source !== parentWin) return;
|
||||
var d = e.data; if (!d || typeof d !== "object") return;
|
||||
var c = d.ac_preview_cmd;
|
||||
if (c === "back") history.back();
|
||||
else if (c === "forward") history.forward();
|
||||
else if (c === "reload") location.reload();
|
||||
else if (c === "ping") { last = ""; report(); }
|
||||
});
|
||||
report();
|
||||
})();
|
||||
`;
|
||||
|
||||
/** Insert the script tag right after <head …> (else after <html …>, else after the doctype, else at the start). */
|
||||
export function injectScriptTag(html: string): string {
|
||||
const tag = `<script src="${PREVIEW_SCRIPT_PATH}"></script>`;
|
||||
const head = /<head(\s[^>]*)?>/i.exec(html);
|
||||
if (head) return html.slice(0, head.index + head[0].length) + tag + html.slice(head.index + head[0].length);
|
||||
const root = /<html(\s[^>]*)?>/i.exec(html);
|
||||
if (root) return html.slice(0, root.index + root[0].length) + tag + html.slice(root.index + root[0].length);
|
||||
const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
|
||||
if (doctype) return html.slice(0, doctype[0].length) + tag + html.slice(doctype[0].length);
|
||||
return tag + html;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Ports the preview proxy never forwards to (1.2): rewriting Origin for them would get around their own checks.
|
||||
// - this daemon's port and the plugin gate's (--gate-port, default 3488)
|
||||
// - Magpie's local API / gateway and magpie web: their defaults 3425 and 3430, MAGPIE_ADDR / MAGPIE_WEB_ADDR / MAGPIE_URL
|
||||
// where set, and (#582) the port saved in Magpie's own settings.json (Settings → gateway port, settings.Port), read
|
||||
// again on every preview.open: older Magpie builds don't tell plugin hosts MAGPIE_ADDR, and the user can move the
|
||||
// gateway while the daemon runs.
|
||||
// Magpie keeps settings.json in its config folder (internal/appdir.Config): the "data" folder beside a portable magpie,
|
||||
// else $XDG_CONFIG_HOME/magpie, else ~/.config/magpie, on Windows, macOS and Linux alike. A portable folder is found
|
||||
// from where this package is installed (<config>/plugins/node_modules/…) and from the daemon's working folder
|
||||
// (<config>/plugin-work). The proxy also refuses a target that answers like a Magpie gateway (proxy.ts), whatever its port.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const MAGPIE_DEFAULT_PORTS = [3425, 3430];
|
||||
export const GATE_DEFAULT_PORT = 3488;
|
||||
|
||||
function portOf(addr: string | undefined): number | null {
|
||||
if (!addr) return null;
|
||||
const m = /:(\d{1,5})\/?$/.exec(addr.trim());
|
||||
const n = m ? Number(m[1]) : NaN;
|
||||
return Number.isInteger(n) && n > 0 && n <= 65535 ? n : null;
|
||||
}
|
||||
|
||||
/** <config> of a Magpie whose plugins folder holds this path (…/<config>/plugins/node_modules/…), or null */
|
||||
export function magpieDirFromInstall(p: string): string | null {
|
||||
const norm = p.replace(/\\/g, "/");
|
||||
const i = norm.lastIndexOf("/plugins/node_modules/");
|
||||
if (i <= 0) return null;
|
||||
return p.slice(0, i);
|
||||
}
|
||||
|
||||
/** Magpie config folders that may hold its settings.json, most specific first (duplicates removed) */
|
||||
export function magpieConfigDirs(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
where: { self?: string; cwd?: string; home?: string; platform?: NodeJS.Platform } = {},
|
||||
): string[] {
|
||||
const out: string[] = [];
|
||||
const add = (d: string | null | undefined) => { if (d && isAbsolute(d) && !out.includes(d)) out.push(d); };
|
||||
let self = where.self;
|
||||
if (self === undefined) { try { self = fileURLToPath(import.meta.url); } catch { self = ""; } }
|
||||
add(magpieDirFromInstall(self));
|
||||
const cwd = where.cwd ?? (env === process.env ? process.cwd() : "");
|
||||
if (cwd && basename(cwd) === "plugin-work") add(dirname(cwd));
|
||||
const x = env.XDG_CONFIG_HOME;
|
||||
if (x && isAbsolute(x)) add(join(x, "magpie"));
|
||||
const platform = where.platform ?? process.platform;
|
||||
const home = where.home ?? (env === process.env ? homedir() : platform === "win32" ? env.USERPROFILE : env.HOME);
|
||||
if (home) add(join(home, ".config", "magpie"));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The gateway port saved in a Magpie settings.json (settings.Port; 0 or out of range = the default 3425), or null */
|
||||
export function savedGatewayPort(file: string, read: (f: string) => string = (f) => readFileSync(f, "utf8")): number | null {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = read(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const s = JSON.parse(raw) as { port?: unknown };
|
||||
const p = typeof s?.port === "number" ? s.port : 0;
|
||||
return Number.isInteger(p) && p >= 1024 && p <= 65535 ? p : MAGPIE_DEFAULT_PORTS[0]!;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function previewDeniedPorts(
|
||||
cfg: { port: number; gatePort?: number },
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
opts: { configDirs?: string[]; read?: (f: string) => string } = {},
|
||||
): number[] {
|
||||
const out = new Set<number>([cfg.port, GATE_DEFAULT_PORT, ...MAGPIE_DEFAULT_PORTS]);
|
||||
if (cfg.gatePort) out.add(cfg.gatePort);
|
||||
for (const k of ["MAGPIE_ADDR", "MAGPIE_WEB_ADDR", "MAGPIE_URL"]) {
|
||||
const p = portOf(env[k]);
|
||||
if (p) out.add(p);
|
||||
}
|
||||
for (const d of opts.configDirs ?? magpieConfigDirs(env)) {
|
||||
const p = savedGatewayPort(join(d, "settings.json"), opts.read);
|
||||
if (p) out.add(p);
|
||||
}
|
||||
const extra = env.AGENT_CONSOLE_PREVIEW_DENY;
|
||||
if (extra) for (const s of extra.split(/[,\s]+/)) { const n = Number(s); if (Number.isInteger(n) && n > 0 && n <= 65535) out.add(n); }
|
||||
out.delete(0);
|
||||
return [...out];
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
// Preview proxy (1.2): a local-only reverse proxy, one 127.0.0.1:<random port> listener per loopback target origin.
|
||||
//
|
||||
// Why: Magpie's page frame is sandbox="allow-scripts" and the sandbox is inherited by every child frame, so a plain
|
||||
// <iframe src="http://localhost:5173"> runs as an opaque origin: module scripts and fetch() fail CORS (Origin: null),
|
||||
// storage throws. The proxy makes a dev app work there: it answers CORS for "null", sends the dev server its own Host/Origin,
|
||||
// drops X-Frame-Options / frame-ancestors, and adds a tiny script with in-memory storage and a navigation bridge.
|
||||
//
|
||||
// Who may use a listener (#582): the preview frame is an opaque origin, so every request it makes carries Origin: null (or
|
||||
// none) and, from an opaque document, no Referer; any other web page can send exactly the same from a sandboxed iframe of
|
||||
// its own. Origin/Referer/Sec-Fetch-* can't tell them apart, and the port is not a secret (a page can scan for it). So each
|
||||
// listener has a 128-bit random key and is only reachable at http://ac<key>.localhost:<port>: the browser puts that host
|
||||
// name in the Host header of every request the frame makes (navigations, module scripts and their imports, fetch/XHR,
|
||||
// CSS url(), workers, the HMR WebSocket), because they are all resolved against the page's own URL; no rewriting needed.
|
||||
// A request whose Host is not exactly that name is refused before anything is forwarded, with no CORS headers:
|
||||
// 127.0.0.1:<port> / localhost:<port> (no key) → 403, any other Host → 421 (DNS rebinding). Only preview.open on an
|
||||
// authenticated WS connection hands out the name. Each open also returns a per-open nonce (separate from the key): the
|
||||
// panel's ping must echo it exactly, or the listener is released at once — a plain 200 "ok" from a hostile DNS answer
|
||||
// is not enough. Before the keyed name is ever looked up, the panel probes a keyless canary host on the same port
|
||||
// (acprobe<random>.localhost) the same way. preview.open also reports the daemon's OS (preview/host.ts: os.platform() and
|
||||
// the Darwin major of os.release(); the WebKit UA is frozen at 10_15_7 and can't say), and the panel refuses Apple WebKit
|
||||
// on a Darwin < 25 host (macOS 12–15) or with no host info before any *.localhost name is looked up, releasing the
|
||||
// listener, so the key never hits network DNS. Chromium/WebView2, WebKitGTK and WebKit on macOS 26+ resolve *.localhost
|
||||
// themselves.
|
||||
// Responses carry Referrer-Policy: no-referrer so the key isn't sent to other sites a previewed page loads from.
|
||||
//
|
||||
// Limits (see README "Preview proxy"):
|
||||
// - created only through preview.open on an authenticated WS connection; targets are loopback only (preview/url.ts);
|
||||
// the daemon's, the gate's and Magpie's ports (ports.ts: defaults, env, Magpie's settings.json) and the proxy's own
|
||||
// are refused, and so is any target that answers like Magpie's gateway (GET / names "magpie", or X-Magpie-* headers);
|
||||
// - each listener serves exactly one target; Host must be ac<key>.localhost:<p> (see above), except a one-shot
|
||||
// keyless canary host that answers only /__agent_console__/ping with a separate nonce;
|
||||
// a request with a foreign Origin is refused (only "null", none, or the proxy's own origin);
|
||||
// - cookies are not forwarded in either direction (127.0.0.1 cookies are shared across ports: Magpie's would leak to the
|
||||
// dev server, and the dev server could set cookies other local apps see);
|
||||
// - a listener closes after 10 idle minutes, on preview.release, when the last page connection goes, and with the daemon;
|
||||
// at most 8 targets at once (the least recently used one is closed).
|
||||
import { createServer, request as httpRequest, type IncomingMessage, type ServerResponse, type Server, type OutgoingHttpHeaders } from "node:http";
|
||||
import { request as httpsRequest } from "node:https";
|
||||
import { connect as netConnect, isIP, type Socket } from "node:net";
|
||||
import { connect as tlsConnect } from "node:tls";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { checkHost, tokenEqual } from "../security.js";
|
||||
import { checkPreviewUrl, deniedPort, displayOrigin, type PreviewTarget } from "./url.js";
|
||||
import { PREVIEW_SCRIPT, PREVIEW_SCRIPT_PATH, injectScriptTag } from "./inject.js";
|
||||
|
||||
export class PreviewError extends Error {
|
||||
code: string;
|
||||
constructor(code: string, message: string) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export type PreviewProxyOptions = {
|
||||
/** Ports never proxied (daemon, gate, Magpie); read on every open */
|
||||
deniedPorts: () => Iterable<number>;
|
||||
idleMs?: number;
|
||||
maxTargets?: number;
|
||||
maxHtmlBytes?: number;
|
||||
now?: () => number;
|
||||
/** how long the "is this Magpie?" check waits for GET / (fails closed: no answer, nothing forwarded) */
|
||||
identityTimeoutMs?: number;
|
||||
/** For tests: a fixed listening port is never used, always 0 (random) */
|
||||
log?: (level: "info" | "warn", msg: string) => void;
|
||||
};
|
||||
|
||||
type Listener = {
|
||||
target: PreviewTarget;
|
||||
server: Server;
|
||||
port: number;
|
||||
/** ac<128-bit hex key>.localhost:<port>: the Host this listener answers for real traffic */
|
||||
authority: string;
|
||||
proxyOrigin: string;
|
||||
/** echoed by GET /__agent_console__/ping on the keyed host; rotated on every preview.open */
|
||||
nonce: string;
|
||||
/** keyless acprobe<random>.localhost:<port>: ping-only canary before the keyed name is looked up */
|
||||
canaryAuthority: string;
|
||||
canaryNonce: string;
|
||||
/** the target answered like Magpie's gateway: nothing is forwarded any more */
|
||||
magpie: boolean;
|
||||
/** when the target's identity was last checked (it is checked again after IDENTITY_TTL) */
|
||||
checkedAt: number;
|
||||
resolving: Promise<string | null> | null;
|
||||
lastUsed: number;
|
||||
sockets: Set<Socket>;
|
||||
/** open WebSocket tunnels (HMR): a listener with one is never idle */
|
||||
tunnels: number;
|
||||
/** address that answered last time (localhost: 127.0.0.1 or ::1) */
|
||||
addr: string | null;
|
||||
};
|
||||
|
||||
export type PreviewOpen = { proxyOrigin: string; target: string; url: string; path: string; proxyHref: string; nonce: string; canaryOrigin: string; canaryNonce: string };
|
||||
|
||||
const HOP = new Set(["connection", "keep-alive", "proxy-connection", "proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade"]);
|
||||
const RETRY_CODES = new Set(["ECONNREFUSED", "EADDRNOTAVAIL", "EAFNOSUPPORT", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT"]);
|
||||
/** a listener's target is asked again whether it is Magpie after this long (the port may have changed hands) */
|
||||
const IDENTITY_TTL = 60 * 1000;
|
||||
export const PREVIEW_PING_PATH = "/__agent_console__/ping";
|
||||
|
||||
export class PreviewProxy {
|
||||
private byOrigin = new Map<string, Listener>();
|
||||
private opening = new Map<string, Promise<Listener>>();
|
||||
private sweepTimer: NodeJS.Timeout | null = null;
|
||||
private idleMs: number;
|
||||
private maxTargets: number;
|
||||
private maxHtml: number;
|
||||
private now: () => number;
|
||||
private identityTimeout: number;
|
||||
|
||||
constructor(private opts: PreviewProxyOptions) {
|
||||
this.idleMs = opts.idleMs ?? 10 * 60 * 1000;
|
||||
this.maxTargets = opts.maxTargets ?? 8;
|
||||
this.maxHtml = opts.maxHtmlBytes ?? 8 * 1024 * 1024;
|
||||
this.now = opts.now ?? Date.now;
|
||||
this.identityTimeout = opts.identityTimeoutMs ?? 30 * 1000;
|
||||
}
|
||||
|
||||
/** Ports of the listeners themselves (a preview of a preview is refused) */
|
||||
ports(): number[] {
|
||||
return [...this.byOrigin.values()].map((l) => l.port);
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.byOrigin.size;
|
||||
}
|
||||
|
||||
async open(raw: string): Promise<PreviewOpen> {
|
||||
const c = checkPreviewUrl(raw);
|
||||
if (!c.ok) throw new PreviewError(c.reason, `preview url refused: ${c.reason}`);
|
||||
const t = c.target;
|
||||
if (deniedPort(t.port, [...this.opts.deniedPorts(), ...this.ports()])) {
|
||||
throw new PreviewError("denied_port", `port ${t.port} can't be previewed`);
|
||||
}
|
||||
let l = this.byOrigin.get(t.origin);
|
||||
if (!l) {
|
||||
// Defense in depth for a gateway on a port we don't know about: ask the target first (short wait; the request
|
||||
// path asks again and fails closed)
|
||||
const who = await identify(t, t.connect, Math.min(3000, this.identityTimeout));
|
||||
if (who === "magpie") {
|
||||
this.opts.log?.("warn", `preview refused: ${t.origin} answers like Magpie's gateway`);
|
||||
throw new PreviewError("denied_port", `${t.origin} is Magpie's gateway`);
|
||||
}
|
||||
let p = this.opening.get(t.origin);
|
||||
if (!p) {
|
||||
p = this.listen(t).finally(() => this.opening.delete(t.origin));
|
||||
this.opening.set(t.origin, p);
|
||||
}
|
||||
l = await p;
|
||||
}
|
||||
l.lastUsed = this.now();
|
||||
// Fresh nonces every open: the panel must prove it reached *this* listener (not a hostile DNS answer)
|
||||
// before the keyed name is used, and again on the keyed ping.
|
||||
l.nonce = randomBytes(16).toString("hex");
|
||||
l.canaryAuthority = `acprobe${randomBytes(16).toString("hex")}.localhost:${l.port}`;
|
||||
l.canaryNonce = randomBytes(16).toString("hex");
|
||||
this.ensureSweep();
|
||||
return {
|
||||
proxyOrigin: l.proxyOrigin,
|
||||
target: t.origin,
|
||||
url: t.href,
|
||||
path: t.path,
|
||||
proxyHref: l.proxyOrigin + t.path,
|
||||
nonce: l.nonce,
|
||||
canaryOrigin: `http://${l.canaryAuthority}`,
|
||||
canaryNonce: l.canaryNonce,
|
||||
};
|
||||
}
|
||||
|
||||
/** Close the listener for this target (any URL on it, or its origin) */
|
||||
release(raw: string): boolean {
|
||||
const c = checkPreviewUrl(raw);
|
||||
if (!c.ok) return false;
|
||||
const l = this.byOrigin.get(c.target.origin);
|
||||
if (!l) return false;
|
||||
this.close(l);
|
||||
return true;
|
||||
}
|
||||
|
||||
closeAll(): void {
|
||||
for (const l of [...this.byOrigin.values()]) this.close(l);
|
||||
if (this.sweepTimer) clearInterval(this.sweepTimer);
|
||||
this.sweepTimer = null;
|
||||
}
|
||||
|
||||
/** Close listeners idle for idleMs (no request and no open WebSocket); exposed for tests with a fake clock */
|
||||
sweep(): void {
|
||||
const now = this.now();
|
||||
for (const l of [...this.byOrigin.values()]) {
|
||||
if (l.tunnels === 0 && now - l.lastUsed > this.idleMs) {
|
||||
this.opts.log?.("info", `preview proxy for ${l.target.origin} idle, closing`);
|
||||
this.close(l);
|
||||
}
|
||||
}
|
||||
if (this.byOrigin.size === 0 && this.sweepTimer) {
|
||||
clearInterval(this.sweepTimer);
|
||||
this.sweepTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private ensureSweep(): void {
|
||||
if (this.sweepTimer) return;
|
||||
this.sweepTimer = setInterval(() => this.sweep(), 60 * 1000);
|
||||
this.sweepTimer.unref();
|
||||
}
|
||||
|
||||
private close(l: Listener): void {
|
||||
if (this.byOrigin.get(l.target.origin) === l) this.byOrigin.delete(l.target.origin);
|
||||
try { l.server.close(); } catch {}
|
||||
for (const s of l.sockets) s.destroy();
|
||||
l.sockets.clear();
|
||||
}
|
||||
|
||||
private async listen(t: PreviewTarget): Promise<Listener> {
|
||||
// Over the limit: close the least recently used target
|
||||
while (this.byOrigin.size >= this.maxTargets) {
|
||||
const oldest = [...this.byOrigin.values()].sort((a, b) => a.lastUsed - b.lastUsed)[0];
|
||||
if (!oldest) break;
|
||||
this.close(oldest);
|
||||
}
|
||||
const server = createServer();
|
||||
const l: Listener = {
|
||||
target: t, server, port: 0, authority: "", proxyOrigin: "", nonce: "", canaryAuthority: "", canaryNonce: "",
|
||||
magpie: false, checkedAt: 0, resolving: null,
|
||||
lastUsed: this.now(), sockets: new Set(), tunnels: 0, addr: null,
|
||||
};
|
||||
server.on("connection", (s) => {
|
||||
l.sockets.add(s);
|
||||
s.on("close", () => l.sockets.delete(s));
|
||||
});
|
||||
server.on("request", (req, res) => this.onRequest(l, req, res));
|
||||
server.on("upgrade", (req, socket, head) => this.onUpgrade(l, req, socket as Socket, head));
|
||||
server.on("clientError", (_e, socket) => { try { socket.destroy(); } catch {} });
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
const a = server.address();
|
||||
l.port = a && typeof a === "object" ? a.port : 0;
|
||||
l.authority = `ac${randomBytes(16).toString("hex")}.localhost:${l.port}`;
|
||||
l.proxyOrigin = `http://${l.authority}`;
|
||||
this.byOrigin.set(t.origin, l);
|
||||
this.opts.log?.("info", `preview proxy 127.0.0.1:${l.port} → ${t.origin}`); // the key is never logged
|
||||
return l;
|
||||
}
|
||||
|
||||
// ---- request gate shared by HTTP and WS ----
|
||||
/** null = refuse; otherwise which name matched (canary is ping-only) */
|
||||
private gate(l: Listener, req: IncomingMessage): { code: number; why: string } | { role: "key" | "canary" } {
|
||||
const host = String(req.headers.host ?? "").toLowerCase();
|
||||
let role: "key" | "canary" | null = null;
|
||||
if (l.authority && tokenEqual(host, l.authority)) role = "key";
|
||||
else if (l.canaryAuthority && tokenEqual(host, l.canaryAuthority)) role = "canary";
|
||||
else {
|
||||
// the bare loopback address carries no key: any page could send that (#582)
|
||||
return checkHost(req.headers.host, l.port).ok ? { code: 403, why: "preview_key" } : { code: 421, why: "bad_host" };
|
||||
}
|
||||
const o = req.headers.origin;
|
||||
if (o !== undefined && o !== "" && o !== "null") {
|
||||
// canary has no stable origin of its own; only null / absent (opaque preview / no-cors probes)
|
||||
if (role === "key" && o.toLowerCase() !== l.proxyOrigin) return { code: 403, why: "bad_origin" };
|
||||
if (role === "canary") return { code: 403, why: "bad_origin" };
|
||||
}
|
||||
return { role };
|
||||
}
|
||||
|
||||
/** A refusal: plain text, no CORS headers (the page that sent it can't read it), nothing forwarded */
|
||||
private refuse(res: ServerResponse, req: IncomingMessage, code: number, why: string): void {
|
||||
res.writeHead(code, {
|
||||
"content-type": "text/plain; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
"x-content-type-options": "nosniff",
|
||||
"content-security-policy": "sandbox; default-src 'none'",
|
||||
"referrer-policy": "no-referrer",
|
||||
});
|
||||
res.end(req.method === "HEAD" ? undefined : why);
|
||||
req.resume();
|
||||
}
|
||||
|
||||
private onRequest(l: Listener, req: IncomingMessage, res: ServerResponse): void {
|
||||
const g = this.gate(l, req);
|
||||
if ("code" in g) {
|
||||
this.refuse(res, req, g.code, g.why); // a refused request doesn't keep the listener alive
|
||||
return;
|
||||
}
|
||||
l.lastUsed = this.now();
|
||||
const path = (req.url ?? "/").split("?")[0];
|
||||
if (path === PREVIEW_PING_PATH) {
|
||||
// panel must see the nonce from preview.open (WS), not a generic 200 "ok" from hostile DNS (#582)
|
||||
const body = g.role === "canary" ? l.canaryNonce : l.nonce;
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null", "referrer-policy": "no-referrer" });
|
||||
res.end(req.method === "HEAD" ? undefined : body);
|
||||
req.resume();
|
||||
return;
|
||||
}
|
||||
// canary name is ping-only: never forward, never serve the inject script
|
||||
if (g.role === "canary") {
|
||||
this.refuse(res, req, 403, "preview_canary");
|
||||
return;
|
||||
}
|
||||
if (l.magpie) {
|
||||
this.refuse(res, req, 403, "magpie");
|
||||
return;
|
||||
}
|
||||
if (path === PREVIEW_SCRIPT_PATH) {
|
||||
res.writeHead(200, {
|
||||
"content-type": "text/javascript; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
"access-control-allow-origin": "null",
|
||||
"x-content-type-options": "nosniff",
|
||||
"referrer-policy": "no-referrer",
|
||||
});
|
||||
res.end(req.method === "HEAD" ? undefined : PREVIEW_SCRIPT);
|
||||
return;
|
||||
}
|
||||
// CORS preflight from the opaque preview frame: answered here (the dev server would not allow "null")
|
||||
if (req.method === "OPTIONS" && req.headers["access-control-request-method"]) {
|
||||
const h: OutgoingHttpHeaders = {
|
||||
"access-control-allow-origin": "null",
|
||||
"access-control-allow-methods": String(req.headers["access-control-request-method"]).slice(0, 200) + ", GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD",
|
||||
"access-control-max-age": "600",
|
||||
vary: "origin",
|
||||
};
|
||||
const rh = req.headers["access-control-request-headers"];
|
||||
if (typeof rh === "string") h["access-control-allow-headers"] = rh.slice(0, 2000);
|
||||
res.writeHead(204, h);
|
||||
res.end();
|
||||
req.resume();
|
||||
return;
|
||||
}
|
||||
void this.forward(l, req, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* The address to forward to, once the target is known not to be Magpie's gateway (asked again after IDENTITY_TTL).
|
||||
* Fails closed: no answer to the identity check → null (error page), Magpie → l.magpie (refused from then on).
|
||||
*/
|
||||
private resolveAddr(l: Listener): Promise<string | null> {
|
||||
if (l.magpie) return Promise.resolve(null);
|
||||
if (l.addr && this.now() - l.checkedAt < IDENTITY_TTL) return Promise.resolve(l.addr);
|
||||
if (!l.resolving) {
|
||||
l.resolving = (async () => {
|
||||
const addr = l.addr ?? (await this.probeAddr(l));
|
||||
if (!addr) return null;
|
||||
const who = await identify(l.target, [addr], this.identityTimeout);
|
||||
if (who === "magpie") {
|
||||
l.magpie = true;
|
||||
l.addr = null;
|
||||
this.opts.log?.("warn", `preview proxy for ${l.target.origin}: the target answers like Magpie's gateway, refusing`);
|
||||
return null;
|
||||
}
|
||||
if (who === "none") {
|
||||
l.addr = null;
|
||||
return null;
|
||||
}
|
||||
l.addr = addr;
|
||||
l.checkedAt = this.now();
|
||||
return addr;
|
||||
})().finally(() => { l.resolving = null; });
|
||||
}
|
||||
return l.resolving;
|
||||
}
|
||||
|
||||
private async probeAddr(l: Listener): Promise<string | null> {
|
||||
for (const host of l.target.connect) {
|
||||
const ok = await new Promise<boolean>((resolve) => {
|
||||
const s = netConnect({ host, port: l.target.port });
|
||||
const done = (v: boolean) => { s.removeAllListeners(); s.destroy(); resolve(v); };
|
||||
s.setTimeout(3000, () => done(false));
|
||||
s.once("connect", () => done(true));
|
||||
s.once("error", () => done(false));
|
||||
});
|
||||
if (ok) return host;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private servername(l: Listener): string | undefined {
|
||||
return isIP(l.target.hostname) ? undefined : l.target.hostname;
|
||||
}
|
||||
|
||||
private async forward(l: Listener, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const addr = await this.resolveAddr(l);
|
||||
if (l.magpie) {
|
||||
this.refuse(res, req, 403, "magpie");
|
||||
return;
|
||||
}
|
||||
if (!addr) {
|
||||
this.errorPage(l, req, res);
|
||||
return;
|
||||
}
|
||||
const headers = rewriteRequestHeaders(req.headers, l.target, l.proxyOrigin, false);
|
||||
const reqFn = l.target.secure ? httpsRequest : httpRequest;
|
||||
const up = reqFn({
|
||||
host: addr,
|
||||
port: l.target.port,
|
||||
method: req.method,
|
||||
path: req.url ?? "/",
|
||||
headers,
|
||||
...(l.target.secure ? { rejectUnauthorized: false, servername: this.servername(l) } : {}),
|
||||
});
|
||||
up.on("response", (ur) => this.respond(l, req, res, ur));
|
||||
up.on("error", (e: NodeJS.ErrnoException) => {
|
||||
if (RETRY_CODES.has(e.code ?? "")) l.addr = null; // re-probe next time (the dev server may have moved between 127.0.0.1 and ::1)
|
||||
if (!res.headersSent) this.errorPage(l, req, res);
|
||||
else res.destroy();
|
||||
});
|
||||
req.on("aborted", () => up.destroy());
|
||||
res.on("close", () => { if (!res.writableFinished) up.destroy(); });
|
||||
req.pipe(up);
|
||||
}
|
||||
|
||||
private respond(l: Listener, req: IncomingMessage, res: ServerResponse, ur: IncomingMessage): void {
|
||||
l.lastUsed = this.now();
|
||||
if (looksLikeMagpie(ur.headers)) {
|
||||
// a gateway reply (X-Magpie-*): the port changed hands since the last check
|
||||
l.magpie = true;
|
||||
l.addr = null;
|
||||
ur.resume();
|
||||
this.refuse(res, req, 403, "magpie");
|
||||
return;
|
||||
}
|
||||
const h = rewriteResponseHeaders(ur.headers, l.target, l.proxyOrigin);
|
||||
const status = ur.statusCode ?? 502;
|
||||
const ctype = String(ur.headers["content-type"] ?? "").toLowerCase();
|
||||
const encoded = !!ur.headers["content-encoding"] && ur.headers["content-encoding"] !== "identity";
|
||||
const html = ctype.includes("text/html") && !encoded && req.method !== "HEAD" && status !== 204 && status !== 304;
|
||||
if (!html) {
|
||||
res.writeHead(status, h);
|
||||
ur.pipe(res);
|
||||
return;
|
||||
}
|
||||
// HTML: buffer (bounded) and add the script tag; a huge page passes through untouched
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
let passthrough = false;
|
||||
ur.on("data", (c: Buffer) => {
|
||||
if (passthrough) return;
|
||||
size += c.length;
|
||||
chunks.push(c);
|
||||
if (size > this.maxHtml) {
|
||||
passthrough = true;
|
||||
res.writeHead(status, h);
|
||||
for (const x of chunks) res.write(x);
|
||||
ur.removeAllListeners("data");
|
||||
ur.removeAllListeners("end");
|
||||
ur.pipe(res);
|
||||
}
|
||||
});
|
||||
ur.on("end", () => {
|
||||
if (passthrough) return;
|
||||
// latin1 keeps every byte as it was, whatever the page's charset
|
||||
const out = Buffer.from(injectScriptTag(Buffer.concat(chunks).toString("latin1")), "latin1");
|
||||
h["content-length"] = String(out.length);
|
||||
res.writeHead(status, h);
|
||||
res.end(out);
|
||||
});
|
||||
ur.on("error", () => res.destroy());
|
||||
}
|
||||
|
||||
private errorPage(l: Listener, req: IncomingMessage, res: ServerResponse): void {
|
||||
const where = displayOrigin(l.target.origin).replace(/^https?:\/\//, "");
|
||||
const body = `<!doctype html><html><head><meta charset="utf-8"><title>${esc(where)}</title>
|
||||
<style>body{font:13px/1.6 system-ui,sans-serif;color:#525252;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#fff}
|
||||
@media (prefers-color-scheme:dark){body{background:#1a1a1a;color:#a3a3a3}button{background:#262626;color:#e5e5e5;border-color:#3a3a3a}}
|
||||
.b{text-align:center;max-width:420px;padding:20px}code{font-family:ui-monospace,monospace}button{margin-top:12px;padding:5px 14px;border:1px solid #d4d4d4;border-radius:6px;background:#fafafa;cursor:pointer;font:inherit}</style></head>
|
||||
<body><div class="b"><div><code>${esc(where)}</code> 没有响应,dev server 启动了吗?</div><div><code>${esc(where)}</code> is not responding. Is the dev server running?</div>
|
||||
<button onclick="location.reload()">重试 / Retry</button></div></body></html>`;
|
||||
res.writeHead(502, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null" });
|
||||
res.end(req.method === "HEAD" ? undefined : body);
|
||||
req.resume();
|
||||
}
|
||||
|
||||
// ---- WebSocket (HMR) ----
|
||||
private onUpgrade(l: Listener, req: IncomingMessage, socket: Socket, head: Buffer): void {
|
||||
const g = this.gate(l, req);
|
||||
if ("code" in g || g.role === "canary" || l.magpie) {
|
||||
const code = "code" in g ? g.code : 403;
|
||||
socket.end(`HTTP/1.1 ${code} ${code === 421 ? "Misdirected Request" : "Forbidden"}\r\nconnection: close\r\n\r\n`);
|
||||
return;
|
||||
}
|
||||
l.lastUsed = this.now();
|
||||
socket.on("error", () => {});
|
||||
void this.resolveAddr(l).then((addr) => {
|
||||
if (!addr || socket.destroyed) {
|
||||
socket.end("HTTP/1.1 502 Bad Gateway\r\nconnection: close\r\n\r\n");
|
||||
return;
|
||||
}
|
||||
const up: Socket = l.target.secure
|
||||
? tlsConnect({ host: addr, port: l.target.port, rejectUnauthorized: false, servername: this.servername(l) })
|
||||
: netConnect({ host: addr, port: l.target.port });
|
||||
const ready = l.target.secure ? "secureConnect" : "connect";
|
||||
l.tunnels++;
|
||||
let counted = true;
|
||||
const done = () => {
|
||||
if (counted) { counted = false; l.tunnels--; l.lastUsed = this.now(); }
|
||||
up.destroy();
|
||||
socket.destroy();
|
||||
};
|
||||
up.once(ready, () => {
|
||||
const lines = [`${req.method ?? "GET"} ${req.url ?? "/"} HTTP/1.1`];
|
||||
const hs = rewriteRequestHeaders(req.headers, l.target, l.proxyOrigin, true);
|
||||
for (const [k, v] of Object.entries(hs)) {
|
||||
if (v === undefined) continue;
|
||||
for (const one of Array.isArray(v) ? v : [v]) lines.push(`${k}: ${String(one).replace(/[\r\n]/g, "")}`);
|
||||
}
|
||||
up.write(lines.join("\r\n") + "\r\n\r\n");
|
||||
if (head?.length) up.write(head);
|
||||
up.pipe(socket);
|
||||
socket.pipe(up);
|
||||
});
|
||||
up.on("data", () => { l.lastUsed = this.now(); });
|
||||
up.on("error", done);
|
||||
up.on("close", done);
|
||||
socket.on("close", done);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function esc(s: string): string {
|
||||
return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
||||
}
|
||||
|
||||
/** Headers sent upstream: the dev server sees its own Host / Origin, no cookies, no compression. */
|
||||
export function rewriteRequestHeaders(
|
||||
inH: IncomingMessage["headers"],
|
||||
t: PreviewTarget,
|
||||
proxyOrigin: string,
|
||||
upgrade: boolean,
|
||||
): OutgoingHttpHeaders {
|
||||
const out: OutgoingHttpHeaders = {};
|
||||
const targetOrigin = displayOrigin(t.origin);
|
||||
for (const [k, v] of Object.entries(inH)) {
|
||||
if (v === undefined) continue;
|
||||
const key = k.toLowerCase();
|
||||
if (!upgrade && HOP.has(key)) continue;
|
||||
if (upgrade && (key === "proxy-connection" || key === "proxy-authorization" || key === "keep-alive" || key === "te" || key === "trailer" || key === "transfer-encoding")) continue;
|
||||
if (key === "cookie" || key === "host" || key === "origin" || key === "referer" || key === "forwarded" || key.startsWith("x-forwarded-")) continue;
|
||||
out[key] = v;
|
||||
}
|
||||
out.host = t.hostHeader.replace(/:(80|443)$/, (m) => ((m === ":80" && !t.secure) || (m === ":443" && t.secure) ? "" : m));
|
||||
if (inH.origin !== undefined) out.origin = targetOrigin;
|
||||
const ref = inH.referer;
|
||||
if (typeof ref === "string" && (ref === proxyOrigin || ref.startsWith(proxyOrigin + "/"))) out.referer = targetOrigin + ref.slice(proxyOrigin.length);
|
||||
if (inH["sec-fetch-site"] !== undefined) out["sec-fetch-site"] = "same-origin";
|
||||
if (!upgrade) out["accept-encoding"] = "identity";
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Headers sent back to the preview frame: readable by an opaque origin, frameable, no cookies, redirects stay on the proxy. */
|
||||
export function rewriteResponseHeaders(inH: IncomingMessage["headers"], t: PreviewTarget, proxyOrigin: string): OutgoingHttpHeaders {
|
||||
const out: OutgoingHttpHeaders = {};
|
||||
for (const [k, v] of Object.entries(inH)) {
|
||||
if (v === undefined) continue;
|
||||
const key = k.toLowerCase();
|
||||
if (HOP.has(key)) continue;
|
||||
if (key === "x-frame-options" || key === "set-cookie" || key === "referrer-policy" || key.startsWith("access-control-allow-")) continue;
|
||||
if (key === "content-security-policy" || key === "content-security-policy-report-only") {
|
||||
const kept = (Array.isArray(v) ? v : [v]).map(stripFrameAncestors).filter(Boolean);
|
||||
if (kept.length) out[key] = kept.join(", ");
|
||||
continue;
|
||||
}
|
||||
if (key === "location" && typeof v === "string") {
|
||||
out[key] = rewriteLocation(v, t, proxyOrigin);
|
||||
continue;
|
||||
}
|
||||
out[key] = v;
|
||||
}
|
||||
out["access-control-allow-origin"] = "null";
|
||||
// the proxy's host name holds the listener key: never send it to another site in a Referer
|
||||
out["referrer-policy"] = "no-referrer";
|
||||
const vary = typeof out.vary === "string" ? out.vary : "";
|
||||
out.vary = vary ? (/\borigin\b/i.test(vary) ? vary : `${vary}, Origin`) : "Origin";
|
||||
return out;
|
||||
}
|
||||
|
||||
export function stripFrameAncestors(csp: string): string {
|
||||
return csp
|
||||
.split(";")
|
||||
.map((d) => d.trim())
|
||||
.filter((d) => d && !/^frame-ancestors(\s|$)/i.test(d))
|
||||
.join("; ");
|
||||
}
|
||||
|
||||
/** A redirect to the target itself goes to the proxy instead; anything else (another site) is left alone */
|
||||
export function rewriteLocation(loc: string, t: PreviewTarget, proxyOrigin: string): string {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(loc, t.href);
|
||||
} catch {
|
||||
return loc;
|
||||
}
|
||||
if (!/^[a-z][a-z0-9+.-]*:/i.test(loc) && !loc.startsWith("//")) return loc; // relative: already right
|
||||
const port = u.port ? Number(u.port) : u.protocol === "https:" ? 443 : 80;
|
||||
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (u.protocol === (t.secure ? "https:" : "http:") && host === t.hostname && port === t.port) {
|
||||
return proxyOrigin + u.pathname + u.search + u.hash;
|
||||
}
|
||||
return loc;
|
||||
}
|
||||
|
||||
/** Reply headers only Magpie's gateway sends */
|
||||
export function looksLikeMagpie(h: IncomingMessage["headers"]): boolean {
|
||||
return Object.keys(h).some((k) => k.toLowerCase().startsWith("x-magpie-"));
|
||||
}
|
||||
|
||||
/** GET / body of Magpie's gateway: {"name":"magpie","apis":[…],"version":…} */
|
||||
export function magpieIndex(body: string): boolean {
|
||||
try {
|
||||
const j = JSON.parse(body) as { name?: unknown; apis?: unknown; version?: unknown };
|
||||
return !!j && typeof j === "object" && j.name === "magpie" && (Array.isArray(j.apis) || typeof j.version === "string");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the target answer like Magpie's gateway? GET / on the first address that answers.
|
||||
* "magpie" / "other" (any other HTTP answer) / "none" (no HTTP answer in time: the caller fails closed).
|
||||
*/
|
||||
export async function identify(t: PreviewTarget, addrs: string[], timeoutMs: number): Promise<"magpie" | "other" | "none"> {
|
||||
for (const addr of addrs) {
|
||||
const r = await new Promise<"magpie" | "other" | "none">((resolve) => {
|
||||
let settled = false;
|
||||
const done = (v: "magpie" | "other" | "none") => { if (!settled) { settled = true; clearTimeout(timer); resolve(v); } };
|
||||
const reqFn = t.secure ? httpsRequest : httpRequest;
|
||||
const q = reqFn({
|
||||
host: addr,
|
||||
port: t.port,
|
||||
method: "GET",
|
||||
path: "/",
|
||||
headers: { host: t.hostHeader, accept: "application/json", "accept-encoding": "identity", "user-agent": "agent-console-preview-check" },
|
||||
agent: false,
|
||||
...(t.secure ? { rejectUnauthorized: false, servername: isIP(t.hostname) ? undefined : t.hostname } : {}),
|
||||
});
|
||||
const timer = setTimeout(() => { q.destroy(); done("none"); }, timeoutMs);
|
||||
q.on("error", () => done("none"));
|
||||
q.on("response", (res) => {
|
||||
if (looksLikeMagpie(res.headers)) { res.destroy(); return done("magpie"); }
|
||||
const ct = String(res.headers["content-type"] ?? "").toLowerCase();
|
||||
if (!ct.includes("json")) { res.destroy(); return done("other"); }
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
res.on("data", (c: Buffer) => {
|
||||
size += c.length;
|
||||
if (size > 256 * 1024) { res.destroy(); done("other"); return; }
|
||||
chunks.push(c);
|
||||
});
|
||||
res.on("end", () => done(magpieIndex(Buffer.concat(chunks).toString("utf8")) ? "magpie" : "other"));
|
||||
res.on("error", () => done("none"));
|
||||
});
|
||||
q.end();
|
||||
});
|
||||
if (r !== "none") return r;
|
||||
}
|
||||
return "none";
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Preview target URLs (1.2): normalize what the user typed or clicked, and decide whether the preview may load it.
|
||||
// Pure (no node: imports) so the page uses the very same rules (web/src/preview imports this file).
|
||||
//
|
||||
// Only loopback targets are allowed: localhost, *.localhost, 127.0.0.0/8, 0.0.0.0, [::1], [::].
|
||||
// http/https only, no user:pass@, port 1–65535, at most 2048 characters.
|
||||
// Ports the daemon refuses (its own, the gate's, Magpie's) are checked by the caller with deniedPort().
|
||||
|
||||
export const MAX_PREVIEW_URL = 2048;
|
||||
|
||||
export type PreviewTarget = {
|
||||
/** Normalized target URL, e.g. http://localhost:5173/app?x=1 */
|
||||
href: string;
|
||||
/** scheme://host:port of the target (what one proxy listener serves) */
|
||||
origin: string;
|
||||
/** Path + query + hash on the target */
|
||||
path: string;
|
||||
secure: boolean;
|
||||
/** Host name as written (lowercase; IPv6 without brackets) */
|
||||
hostname: string;
|
||||
port: number;
|
||||
/** Addresses to connect to, in order (localhost tries IPv4 first, then ::1) */
|
||||
connect: string[];
|
||||
/** Host header to send upstream (host:port as the dev server expects to see it) */
|
||||
hostHeader: string;
|
||||
};
|
||||
|
||||
export type PreviewCheck = { ok: true; target: PreviewTarget } | { ok: false; reason: "empty" | "too_long" | "bad_url" | "scheme" | "userinfo" | "not_local" | "port" };
|
||||
|
||||
/** Is this host name a loopback host the preview may load? (brackets of IPv6 allowed or not) */
|
||||
export function isLoopbackHost(host: string): boolean {
|
||||
const h = host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (h === "localhost" || h.endsWith(".localhost")) return /^[a-z0-9.-]+$/.test(h) && !h.includes("..");
|
||||
if (h === "0.0.0.0" || h === "::1" || h === "::") return true;
|
||||
const m = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
|
||||
return !!m && m.slice(1).every((x) => Number(x) <= 255);
|
||||
}
|
||||
|
||||
function connectHosts(h: string): string[] {
|
||||
if (h === "localhost" || h.endsWith(".localhost")) return ["127.0.0.1", "::1"];
|
||||
if (h === "0.0.0.0") return ["127.0.0.1"];
|
||||
if (h === "::1") return ["::1"];
|
||||
if (h === "::") return ["::1", "127.0.0.1"];
|
||||
return [h];
|
||||
}
|
||||
|
||||
/** "5173", ":5173", "localhost:5173", "127.0.0.1:5173/x", "http://[::1]:4000" → a URL string with a scheme */
|
||||
export function withScheme(raw: string): string {
|
||||
const s = raw.trim();
|
||||
if (/^\d{1,5}$/.test(s)) return `http://localhost:${s}/`;
|
||||
if (/^:\d{1,5}(?:[/?#].*)?$/.test(s)) return `http://localhost${s}`;
|
||||
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) return s;
|
||||
// "mailto:", "javascript:", "file:" etc. stay as they are (and are refused below); "localhost:5173" is host:port, not a scheme
|
||||
if (/^[a-z][a-z0-9+.-]*:(?!\d)/i.test(s)) return s;
|
||||
return `http://${s}`;
|
||||
}
|
||||
|
||||
export function checkPreviewUrl(raw: string): PreviewCheck {
|
||||
if (typeof raw !== "string" || !raw.trim()) return { ok: false, reason: "empty" };
|
||||
if (raw.length > MAX_PREVIEW_URL) return { ok: false, reason: "too_long" };
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(withScheme(raw));
|
||||
} catch {
|
||||
return { ok: false, reason: "bad_url" };
|
||||
}
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, reason: "scheme" };
|
||||
if (u.username || u.password) return { ok: false, reason: "userinfo" };
|
||||
const hostname = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
if (!isLoopbackHost(hostname)) return { ok: false, reason: "not_local" };
|
||||
const secure = u.protocol === "https:";
|
||||
const port = u.port ? Number(u.port) : secure ? 443 : 80;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return { ok: false, reason: "port" };
|
||||
const href = u.href;
|
||||
if (href.length > MAX_PREVIEW_URL) return { ok: false, reason: "too_long" };
|
||||
const hostForUrl = hostname.includes(":") ? `[${hostname}]` : hostname;
|
||||
return {
|
||||
ok: true,
|
||||
target: {
|
||||
href,
|
||||
origin: `${u.protocol}//${hostForUrl}:${port}`,
|
||||
path: `${u.pathname}${u.search}${u.hash}`,
|
||||
secure,
|
||||
hostname,
|
||||
port,
|
||||
connect: connectHosts(hostname),
|
||||
hostHeader: `${hostForUrl}:${port}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The preview never proxies these ports (the daemon, the gate, Magpie): rewriting Origin would bypass their own checks */
|
||||
export function deniedPort(port: number, denied: Iterable<number>): boolean {
|
||||
for (const d of denied) if (d === port) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** URL the user sees in the address bar for a proxied location: proxy origin swapped back to the target origin */
|
||||
export function displayHref(proxiedHref: string, proxyOrigin: string, targetOrigin: string): string {
|
||||
if (proxiedHref.startsWith(proxyOrigin)) return displayOrigin(targetOrigin) + proxiedHref.slice(proxyOrigin.length);
|
||||
return proxiedHref;
|
||||
}
|
||||
|
||||
/** http://localhost:80 → http://localhost (how a browser would print it) */
|
||||
export function displayOrigin(origin: string): string {
|
||||
return origin.replace(/^http:\/\/(.+):80$/, "http://$1").replace(/^https:\/\/(.+):443$/, "https://$1");
|
||||
}
|
||||
|
||||
/** Only http/https may go to the system browser (no file:, javascript:, custom schemes). Returns the re-serialized href. */
|
||||
export function externalHref(raw: string): string | null {
|
||||
if (typeof raw !== "string" || !raw || raw.length > MAX_PREVIEW_URL) return null;
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
||||
if (!u.hostname) return null;
|
||||
const href = u.href;
|
||||
// URL.href percent-encodes spaces/quotes/controls; refuse anything that still looks odd
|
||||
if (/[\s"'<>`\\^{|}]/.test(href) || href.length > MAX_PREVIEW_URL) return null;
|
||||
return href;
|
||||
}
|
||||
@@ -35,6 +35,7 @@ export async function buildAcpPrompt(
|
||||
text: string,
|
||||
attachments: { path: string; mime: string }[],
|
||||
caps: AcpPromptCaps,
|
||||
mentions: { path: string; isDir: boolean }[] = [],
|
||||
): Promise<AcpPromptBuild> {
|
||||
const media: ContentBlock[] = [];
|
||||
const links: ContentBlock[] = [];
|
||||
@@ -103,5 +104,9 @@ export async function buildAcpPrompt(
|
||||
const blocks: ContentBlock[] = [];
|
||||
if (fullText) blocks.push({ type: "text", text: fullText });
|
||||
blocks.push(...media, ...links);
|
||||
// Files / folders referenced from the Files panel: a resource_link each (ACP baseline); the text already names them too
|
||||
for (const m of mentions) {
|
||||
blocks.push({ type: "resource_link", uri: pathToFileURL(m.path).href, name: basename(m.path) || m.path });
|
||||
}
|
||||
return { blocks, imagesByPath, warnings };
|
||||
}
|
||||
|
||||
@@ -396,7 +396,7 @@ export class AcpSession implements ProviderSession {
|
||||
return;
|
||||
}
|
||||
// An image-only message is still a prompt: images go as image blocks when the Agent takes them, else by file path
|
||||
const built = await buildAcpPrompt(text, attachments, this.promptCaps);
|
||||
const built = await buildAcpPrompt(text, attachments, this.promptCaps, input.mentions ?? []);
|
||||
const agent = this.o.providerName ?? this.o.binName;
|
||||
if (built.imagesByPath.length && !this.promptCaps.image) {
|
||||
const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// claude stream-json messages (and ~/.claude/projects jsonl lines) → ProviderEvent (§7.2.3). Ported from normalize in lib/agents/claude.mjs.
|
||||
import type { ProviderEvent } from "../../timeline/types.js";
|
||||
import { callInfo, todoItems } from "../../agents/kinds.js";
|
||||
import { targetExists, callInfo, todoItems } from "../../agents/kinds.js";
|
||||
import { editDetail } from "../../agents/diff.js";
|
||||
import { tr } from "../../util/i18n.js";
|
||||
|
||||
@@ -179,7 +179,7 @@ function mapToolUse(blk: Rec, cwd: string): ProviderEvent[] {
|
||||
const input = rec(blk.input);
|
||||
const name = str(blk.name) ?? "tool";
|
||||
const id = str(blk.id) ?? "";
|
||||
const info = callInfo(name, { ...input, _exists: true }, cwd);
|
||||
const info = callInfo(name, { ...input, _exists: name === "Write" ? targetExists(input, cwd) : true }, cwd);
|
||||
let detail: unknown = info.detail;
|
||||
if (info.kind === "edit" && (input.old_string !== undefined || Array.isArray(input.edits))) {
|
||||
detail = editDetail({ path: (info.detail as Rec).path as string, old: input.old_string, new: input.new_string, edits: input.edits });
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../types.js";
|
||||
import type { ProviderEvent } from "../../timeline/types.js";
|
||||
import { AsyncQueue } from "../../util/queue.js";
|
||||
import { callInfo } from "../../agents/kinds.js";
|
||||
import { targetExists, callInfo } from "../../agents/kinds.js";
|
||||
import { editDetail } from "../../agents/diff.js";
|
||||
import { mapSdkMessage, newMapState, type MapState } from "./map.js";
|
||||
import { log } from "../../log.js";
|
||||
@@ -162,7 +162,7 @@ export class ClaudeSession implements ProviderSession {
|
||||
return this.handleQuestion(requestId, input, signal);
|
||||
}
|
||||
|
||||
const info = callInfo(toolName, { ...input, _exists: true }, this.o.cwd);
|
||||
const info = callInfo(toolName, { ...input, _exists: toolName === "Write" ? targetExists(input, this.o.cwd) : true }, this.o.cwd);
|
||||
let detail: Record<string, unknown> = { ...(info.detail as Record<string, unknown>), toolName };
|
||||
if (info.kind === "edit" && (input.old_string !== undefined || Array.isArray(input.edits))) {
|
||||
detail = { ...editDetail({ path: info.detail.path as string, old: input.old_string, new: input.new_string, edits: input.edits }), toolName };
|
||||
|
||||
@@ -384,6 +384,7 @@ function pickScript(text: string): (ctx: Ctx) => Promise<void> {
|
||||
if (t.startsWith("/error")) return scriptError;
|
||||
if (t.startsWith("/long")) return scriptLong;
|
||||
if (t.startsWith("/exit")) return scriptExit;
|
||||
if (t.startsWith("/serve")) return scriptServe;
|
||||
return scriptDefault;
|
||||
}
|
||||
|
||||
@@ -402,6 +403,27 @@ function chunkText(s: string, n: number): string[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
// "/serve": a reply with local dev-server addresses (1.2 preview links) and one external link
|
||||
async function scriptServe(ctx: Ctx): Promise<void> {
|
||||
const emit = (e: Parameters<Ctx["emit"]>[0]) => ctx.emit(e);
|
||||
const reply = [
|
||||
"开发服务器已经启动:http://localhost:5173/ ,接口在 127.0.0.1:5173/api.json。",
|
||||
"",
|
||||
"- 在预览里打开 [首页](http://localhost:5173/) 或 [about](http://localhost:5173/about.html)",
|
||||
"- 文档:[Vite](https://vite.dev/guide/)",
|
||||
"",
|
||||
"```",
|
||||
" VITE v5.4.21 ready in 139 ms",
|
||||
" ➜ Local: http://localhost:5173/",
|
||||
"```",
|
||||
].join("\n");
|
||||
for (const ch of chunkText(reply, 40)) {
|
||||
if (await sleepAbortable(20, ctx)) return;
|
||||
emit({ type: "assistant_delta", itemId: "sv", text: ch });
|
||||
}
|
||||
emit({ type: "assistant_message", itemId: "sv", text: reply });
|
||||
}
|
||||
|
||||
function mockReply(ctx: Ctx): string {
|
||||
const base = [
|
||||
"好的,我已经按你的要求改好了。",
|
||||
|
||||
@@ -40,7 +40,8 @@ export type DetectResult = { available: boolean; bin?: string; version?: string;
|
||||
/** Custom launch (Settings › Launch command). args are appended after the built-in arguments; prefixArgs (internal) go before them. */
|
||||
export type LaunchCommand = { cmd: string; prefixArgs?: string[]; args?: string[] };
|
||||
export type HistoryItem = { provider: string; sessionId: string; title: string; updatedAt: number; messageCount: number; imported: boolean };
|
||||
export type SendInput = { text: string; images: { path: string; mime: string }[] };
|
||||
/** text already carries the "Referenced files" section for mentions; mentions is there for Agents with a native form (ACP resource_link) */
|
||||
export type SendInput = { text: string; images: { path: string; mime: string }[]; mentions?: { path: string; isDir: boolean }[] };
|
||||
export type RespondAnswer = { optionId?: string; answers?: Record<string, string>; cancelled?: boolean };
|
||||
|
||||
export interface Provider {
|
||||
|
||||
@@ -11,10 +11,16 @@ export type Settings = {
|
||||
runningSend: "queue" | "steer";
|
||||
showThinking: boolean;
|
||||
theme: "auto" | "light" | "dark";
|
||||
/** 1.2: width of the conversation column */
|
||||
contentWidth: ContentWidth;
|
||||
/** 1.2: chat text size in px (timeline, composer; code 1px smaller) */
|
||||
chatFontSize: number;
|
||||
idleCloseMinutes: number;
|
||||
collapsedProjects: string[];
|
||||
panel: { open: boolean; tab: string; width: number };
|
||||
sidebarWidth: number;
|
||||
/** 1.2: the sidebar column is collapsed (wide windows) */
|
||||
sidebarHidden?: boolean;
|
||||
lastProjectId: string | null;
|
||||
lastThreadId: string | null;
|
||||
recentDirs?: string[];
|
||||
@@ -26,6 +32,12 @@ export type Settings = {
|
||||
[k: string]: unknown;
|
||||
};
|
||||
|
||||
export const CONTENT_WIDTHS = ["narrow", "default", "wide", "full"] as const;
|
||||
export type ContentWidth = (typeof CONTENT_WIDTHS)[number];
|
||||
export const CHAT_FONT_MIN = 12;
|
||||
export const CHAT_FONT_MAX = 18;
|
||||
export const CHAT_FONT_DEFAULT = 13;
|
||||
|
||||
export const DEFAULT_SETTINGS: Settings = {
|
||||
defaultProvider: "claude",
|
||||
defaultMode: "default",
|
||||
@@ -33,6 +45,8 @@ export const DEFAULT_SETTINGS: Settings = {
|
||||
runningSend: "queue",
|
||||
showThinking: true,
|
||||
theme: "auto",
|
||||
contentWidth: "default",
|
||||
chatFontSize: CHAT_FONT_DEFAULT,
|
||||
idleCloseMinutes: 30,
|
||||
collapsedProjects: [],
|
||||
panel: { open: false, tab: "changes", width: 440 },
|
||||
@@ -57,10 +71,13 @@ export const settingsPatchSchema = z
|
||||
showThinking: z.boolean(),
|
||||
// auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it
|
||||
theme: z.enum(["auto", "light", "dark"]),
|
||||
contentWidth: z.enum(CONTENT_WIDTHS),
|
||||
chatFontSize: z.number().int().min(CHAT_FONT_MIN).max(CHAT_FONT_MAX),
|
||||
idleCloseMinutes: z.number().int().min(IDLE_CLOSE_MIN).max(IDLE_CLOSE_MAX),
|
||||
collapsedProjects: z.array(id).max(1000),
|
||||
panel: z.object({ open: z.boolean(), tab: z.string().max(40), width: z.number().min(0).max(5000) }).partial(),
|
||||
sidebarWidth: z.number().min(0).max(5000),
|
||||
sidebarHidden: z.boolean(),
|
||||
lastProjectId: id.nullable(),
|
||||
lastThreadId: id.nullable(),
|
||||
recentDirs: z.array(z.string().max(4096)).max(50),
|
||||
|
||||
@@ -34,6 +34,8 @@ export type ThreadMeta = {
|
||||
cursorFast?: boolean;
|
||||
/** Cursor Agent: Auto-review, the client auto-approves safe tool permissions */
|
||||
cursorAutoReview?: boolean;
|
||||
/** 1.2: last URL shown in the Preview tab (the target, not the proxy URL) */
|
||||
previewUrl?: string | null;
|
||||
};
|
||||
|
||||
export type { Mode };
|
||||
|
||||
@@ -10,7 +10,7 @@ export type AttachmentRef = { id: string; name: string; mime: string };
|
||||
export type PermissionOption = { id: string; label: string; kind: "allow_once" | "allow_always" | "reject_once" };
|
||||
|
||||
export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_started"; model: string | null; mode: string; effort: string | null }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_delta" | "reasoning_delta" | "tool_output_delta"; itemId: string; text: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_message" | "reasoning"; itemId: string; text: string }
|
||||
|
||||
@@ -36,6 +36,7 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.acpImageByPathSwitched": "{agent} 是在另一个模型上启动的,只对那个模型接收图片,这次改为发送图片的文件路径(当前模型能看图时它会用 read_image 打开):{paths}",
|
||||
"notice.acpSessionNotRestored": "{agent} 不能恢复上一轮对话(它的 ACP 既不支持 session/load 也不支持 session/resume),已新开一轮;先前的上下文不会带回。",
|
||||
"notice.attachmentIssue": "附件问题:{detail}",
|
||||
"notice.mentionSkipped": "这些路径不在项目里或已不存在,没有发给 Agent:{paths}",
|
||||
"claude.notFound": "找不到 claude({detail})。本插件不附带 Claude Code,请先安装:{hint}",
|
||||
"claude.startFailed": "无法启动 claude:{detail}",
|
||||
"claude.exited": "claude 进程意外退出({code})",
|
||||
@@ -53,6 +54,9 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"provider.unavailable": "{name} 未安装或不可用",
|
||||
"provider.unknown": "未知 Agent:{id}",
|
||||
"provider.timeout": "检测超时",
|
||||
"err.previewUrl": "预览只支持本机地址(localhost、127.0.0.1 等)",
|
||||
"err.previewDenied": "这个端口不能预览(是 Agent 控制台或 Magpie 自己的端口)",
|
||||
"err.previewUnavailable": "预览不可用",
|
||||
"err.projectMissing": "项目不存在",
|
||||
"err.threadMissing": "对话不存在",
|
||||
"err.dirMissing": "目录不存在或不是文件夹",
|
||||
@@ -142,6 +146,7 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.acpImageByPathSwitched": "{agent} was started on another model and takes image blocks only for that one, so the image went as its file path (it opens it with read_image when this model sees images): {paths}",
|
||||
"notice.acpSessionNotRestored": "{agent} can't restore the previous conversation (its ACP advertises neither session/load nor session/resume); started a new one — prior context won't come back.",
|
||||
"notice.attachmentIssue": "Attachment issue: {detail}",
|
||||
"notice.mentionSkipped": "Not sent to the Agent (outside the project or gone): {paths}",
|
||||
"claude.notFound": "claude was not found ({detail}). Claude Code is not bundled with this plugin; install it first: {hint}",
|
||||
"claude.startFailed": "Could not start claude: {detail}",
|
||||
"claude.exited": "claude exited unexpectedly ({code})",
|
||||
@@ -159,6 +164,9 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"provider.unavailable": "{name} is not installed or not available",
|
||||
"provider.unknown": "Unknown agent: {id}",
|
||||
"provider.timeout": "Detection timed out",
|
||||
"err.previewUrl": "Preview only supports local addresses (localhost, 127.0.0.1, …)",
|
||||
"err.previewDenied": "This port can't be previewed (it belongs to Agent Console or Magpie)",
|
||||
"err.previewUnavailable": "Preview is unavailable",
|
||||
"err.projectMissing": "Project not found",
|
||||
"err.threadMissing": "Conversation not found",
|
||||
"err.dirMissing": "The folder does not exist or is not a folder",
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// File / folder references dragged from the Files panel into the composer (1.2).
|
||||
// The page sends {rel, isDir} relative to the conversation's project; the daemon resolves the absolute path itself and
|
||||
// checks (with realpath, so a symlink can't escape) that it is still inside the project. A mention only names a path:
|
||||
// no file content is read, so it never widens what the Agent may read.
|
||||
// The path handed to the Agent is built on the project path as it was opened (macOS /var/… stays /var/…, a symlinked
|
||||
// workspace keeps its own name); realpath is only used for the containment check (#582).
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import { isAbsolute, resolve, sep, win32, posix } from "node:path";
|
||||
|
||||
export type MentionRef = { rel: string; isDir?: boolean };
|
||||
export type Mention = { path: string; isDir: boolean };
|
||||
|
||||
export const MAX_MENTIONS = 50;
|
||||
|
||||
/** Is child inside (or equal to) root? Case-insensitive on Windows. */
|
||||
export function insideRoot(root: string, child: string, platform: NodeJS.Platform = process.platform): boolean {
|
||||
const p = platform === "win32" ? win32 : posix;
|
||||
const norm = (s: string) => (platform === "win32" ? p.resolve(s).toLowerCase() : p.resolve(s));
|
||||
const r = p.relative(norm(root), norm(child));
|
||||
return r === "" || (!r.startsWith("..") && !p.isAbsolute(r));
|
||||
}
|
||||
|
||||
export async function resolveMentions(projectPath: string, refs: MentionRef[]): Promise<{ mentions: Mention[]; warnings: string[] }> {
|
||||
const mentions: Mention[] = [];
|
||||
const warnings: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
// shown: the project path as opened (what the user and the Agent know); realRoot: where it really is (containment only)
|
||||
const shown = resolve(projectPath);
|
||||
let realRoot: string;
|
||||
try {
|
||||
realRoot = await realpath(shown);
|
||||
} catch {
|
||||
return { mentions, warnings: refs.map((r) => r.rel) };
|
||||
}
|
||||
for (const ref of refs.slice(0, MAX_MENTIONS)) {
|
||||
const rel = String(ref.rel ?? "").replace(/\\/g, "/");
|
||||
if (!rel || rel.includes("\0") || isAbsolute(rel) || /^[a-zA-Z]:/.test(rel)) {
|
||||
warnings.push(rel || "(empty)");
|
||||
continue;
|
||||
}
|
||||
const abs = resolve(shown, rel === "." ? "" : rel);
|
||||
if (!insideRoot(shown, abs)) {
|
||||
warnings.push(rel);
|
||||
continue;
|
||||
}
|
||||
let real: string;
|
||||
let isDir: boolean;
|
||||
try {
|
||||
real = await realpath(abs);
|
||||
isDir = (await stat(real)).isDirectory();
|
||||
} catch {
|
||||
warnings.push(rel);
|
||||
continue;
|
||||
}
|
||||
if (!insideRoot(realRoot, real)) {
|
||||
warnings.push(rel);
|
||||
continue;
|
||||
}
|
||||
// Keep the path the user saw (inside the project), not the symlink's target
|
||||
if (seen.has(abs)) continue;
|
||||
seen.add(abs);
|
||||
mentions.push({ path: abs, isDir });
|
||||
}
|
||||
return { mentions, warnings };
|
||||
}
|
||||
|
||||
/** Text appended to the prompt; the same for every Agent (ACP Agents also get resource_link blocks). */
|
||||
export function mentionSection(mentions: Mention[]): string {
|
||||
if (!mentions.length) return "";
|
||||
const lines = mentions.map((m) => {
|
||||
const shown = m.isDir && !m.path.endsWith(sep) && !m.path.endsWith("/") ? m.path + (m.path.includes("\\") && !m.path.includes("/") ? "\\" : "/") : m.path;
|
||||
const quoted = /\s|`/.test(shown) ? "`" + shown.replace(/`/g, "'") + "`" : shown;
|
||||
return `- ${quoted}${m.isDir ? " (folder)" : ""}`;
|
||||
});
|
||||
return `Referenced files (read them as needed):\n${lines.join("\n")}`;
|
||||
}
|
||||
|
||||
/** The prompt text an Agent receives: the user's text, then the referenced paths */
|
||||
export function withMentions(text: string, mentions: Mention[]): string {
|
||||
const sec = mentionSection(mentions);
|
||||
if (!sec) return text;
|
||||
return text.trim() ? `${text}\n\n${sec}` : sec;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Open an http(s) URL in the system browser (1.2). Inside Magpie the page has no allow-popups, so target=_blank and
|
||||
// window.open do nothing; the daemon opens the link instead. execFile only (no shell), the URL is re-serialized by URL
|
||||
// and passed as one argument:
|
||||
// macOS open <href>
|
||||
// Linux xdg-open <href>
|
||||
// Windows rundll32.exe url.dll,FileProtocolHandler <href> (not `cmd /c start`: cmd would parse & | ^ in the URL)
|
||||
import { execFile } from "node:child_process";
|
||||
import { externalHref } from "../preview/url.js";
|
||||
|
||||
export function openerFor(platform: NodeJS.Platform, href: string): { cmd: string; args: string[] } {
|
||||
if (platform === "win32") return { cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", href] };
|
||||
if (platform === "darwin") return { cmd: "open", args: [href] };
|
||||
return { cmd: "xdg-open", args: [href] };
|
||||
}
|
||||
|
||||
type ExecLike = (cmd: string, args: string[], opts: { windowsHide: boolean; timeout: number }, cb: (err: Error | null) => void) => { on(ev: "error", fn: (e: Error) => void): unknown };
|
||||
|
||||
/** ok:false when the URL is refused or no opener could run (e.g. no xdg-open): the page then copies the link instead */
|
||||
export async function openExternal(
|
||||
raw: string,
|
||||
opts: { platform?: NodeJS.Platform; exec?: ExecLike; waitMs?: number } = {},
|
||||
): Promise<{ ok: boolean; href?: string; reason?: string }> {
|
||||
const href = externalHref(raw);
|
||||
if (!href) return { ok: false, reason: "bad_url" };
|
||||
const { cmd, args } = openerFor(opts.platform ?? process.platform, href);
|
||||
const run = opts.exec ?? (execFile as unknown as ExecLike);
|
||||
return await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (v: { ok: boolean; href?: string; reason?: string }) => {
|
||||
if (!settled) { settled = true; resolve(v); }
|
||||
};
|
||||
try {
|
||||
const child = run(cmd, args, { windowsHide: true, timeout: 15000 }, (err) => {
|
||||
// rundll32 / open / xdg-open return quickly; a non-zero exit means nothing was opened
|
||||
done(err ? { ok: false, href, reason: "opener_failed" } : { ok: true, href });
|
||||
});
|
||||
child.on("error", () => done({ ok: false, href, reason: "no_opener" }));
|
||||
} catch {
|
||||
done({ ok: false, href, reason: "no_opener" });
|
||||
}
|
||||
// Some openers stay running (a browser launched in the foreground): treat "still running" as opened
|
||||
setTimeout(() => done({ ok: true, href }), opts.waitMs ?? 4000).unref?.();
|
||||
});
|
||||
}
|
||||
@@ -62,6 +62,8 @@ export class Gateway {
|
||||
private methods = new Map<string, MethodHandler>();
|
||||
private helloTimers = new Map<string, NodeJS.Timeout>();
|
||||
onTerminalInput?: (conn: Conn, index: number, op: number, payload: Buffer) => void;
|
||||
/** Called after a connection closes, with how many are left (the preview proxy closes when none are) */
|
||||
onConnectionClosed?: (left: number) => void;
|
||||
|
||||
constructor(private cfg: Config) {
|
||||
this.wss = new WebSocketServer({ noServer: true });
|
||||
@@ -122,6 +124,7 @@ export class Gateway {
|
||||
});
|
||||
ws.on("close", () => {
|
||||
this.conns.delete(conn.id);
|
||||
try { this.onConnectionClosed?.(this.conns.size); } catch {}
|
||||
const t = this.helloTimers.get(conn.id);
|
||||
if (t) clearTimeout(t);
|
||||
this.helloTimers.delete(conn.id);
|
||||
|
||||
@@ -23,7 +23,12 @@ import { clearBinCache } from "../util/bin.js";
|
||||
import { cachedDetect, cachedModels, clearProviderCache } from "../providers/infoCache.js";
|
||||
import { launchFromSettings } from "../providers/launch.js";
|
||||
import { clampMode } from "../providers/modes.js";
|
||||
import { tr, intlLocale } from "../util/i18n.js";
|
||||
import { setAppLocale, tr, intlLocale } from "../util/i18n.js";
|
||||
import { MAX_MENTIONS } from "../util/mentions.js";
|
||||
import { openExternal } from "../util/openExternal.js";
|
||||
import { PreviewError, type PreviewProxy } from "../preview/proxy.js";
|
||||
import { checkPreviewUrl, MAX_PREVIEW_URL } from "../preview/url.js";
|
||||
import { previewHost } from "../preview/host.js";
|
||||
|
||||
const threadModeSchema = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]);
|
||||
|
||||
@@ -36,10 +41,12 @@ export type Services = {
|
||||
git: GitService;
|
||||
files: FileService;
|
||||
terminals: TerminalService;
|
||||
/** 1.2 preview proxy (absent in some tests) */
|
||||
preview?: PreviewProxy;
|
||||
// AgentManager provides runtime info once wired in at P1-4; may be empty (no session started)
|
||||
runtime?: (threadId: string) => { status: string; queue: unknown[]; pending: unknown[] } | null;
|
||||
manager?: {
|
||||
send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior?: "queue" | "steer"): Promise<"started" | "steered" | "queued" | void>;
|
||||
send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[]; mentions?: { rel: string; isDir?: boolean }[] }, behavior?: "queue" | "steer"): Promise<"started" | "steered" | "queued" | void>;
|
||||
interrupt(threadId: string): Promise<void>;
|
||||
respond(threadId: string, requestId: string, answer: { optionId?: string; answers?: Record<string, string>; cancelled?: boolean }): Promise<void>;
|
||||
setModel(threadId: string, model: string | null): Promise<void>;
|
||||
@@ -75,6 +82,12 @@ function wrap<T extends z.ZodType>(schema: T, fn: (p: z.infer<T>, ctx: ConnCtx)
|
||||
export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
const zEmpty = z.object({}).passthrough().optional();
|
||||
|
||||
// Magpie's language changed while the page is open (1.2): daemon-made text (notices, tool titles) follows it
|
||||
gw.method("app.setLocale", wrap(z.object({ lang: z.string().max(32) }), (p) => {
|
||||
setAppLocale(p.lang);
|
||||
return true;
|
||||
}));
|
||||
|
||||
gw.method("app.info", wrap(zEmpty, () => ({
|
||||
version: svc.cfg.version,
|
||||
dataDir: svc.cfg.dataDir,
|
||||
@@ -87,6 +100,40 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
return { ok: true };
|
||||
}));
|
||||
|
||||
// 1.2: open an http(s) link in the system browser (the sandboxed page can't open popups)
|
||||
gw.method("app.openExternal", wrap(z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL) }), async (p) => openExternal(p.url)));
|
||||
|
||||
// 1.2 preview: a local-only reverse proxy for a loopback dev URL (see preview/proxy.ts for the limits)
|
||||
gw.method("preview.open", wrap(
|
||||
z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL), threadId: z.string().max(200).optional() }),
|
||||
async (p) => {
|
||||
if (!svc.preview) throw new ApiError("unavailable", tr("err.previewUnavailable"));
|
||||
let r;
|
||||
try {
|
||||
r = await svc.preview.open(p.url);
|
||||
} catch (e) {
|
||||
if (e instanceof PreviewError) {
|
||||
throw new ApiError(e.code === "denied_port" ? "preview_denied" : "preview_url", tr(e.code === "denied_port" ? "err.previewDenied" : "err.previewUrl"));
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
if (p.threadId) {
|
||||
const meta = await svc.threads.get(p.threadId);
|
||||
if (meta && meta.previewUrl !== r.url) {
|
||||
const next = await svc.threads.patch(p.threadId, { previewUrl: r.url });
|
||||
gw.publish("sidebar", { type: "thread.upsert", thread: next });
|
||||
}
|
||||
}
|
||||
// The daemon's real OS (the UA can't carry it, #582): the page refuses Apple WebKit on Darwin < 25 before any
|
||||
// *.localhost name is looked up, and releases this listener
|
||||
return { ...r, host: previewHost() };
|
||||
},
|
||||
));
|
||||
|
||||
gw.method("preview.release", wrap(z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL) }), (p) => ({
|
||||
ok: svc.preview?.release(p.url) ?? false,
|
||||
})));
|
||||
|
||||
gw.method("settings.get", wrap(zEmpty, () => svc.settings.get()));
|
||||
|
||||
gw.method("settings.set", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), async (p) => {
|
||||
@@ -296,6 +343,7 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
title: z.string().optional(),
|
||||
pinned: z.boolean().optional(),
|
||||
archived: z.boolean().optional(),
|
||||
previewUrl: z.string().max(MAX_PREVIEW_URL).nullable().optional(),
|
||||
}),
|
||||
async (p) => {
|
||||
const meta = await svc.threads.get(p.id);
|
||||
@@ -307,6 +355,15 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
}
|
||||
if (p.pinned !== undefined) patch.pinned = p.pinned;
|
||||
if (p.archived !== undefined) patch.archived = p.archived;
|
||||
if (p.previewUrl !== undefined) {
|
||||
// Only a loopback URL is remembered (normalized); null clears it
|
||||
if (p.previewUrl === null) patch.previewUrl = null;
|
||||
else {
|
||||
const c = checkPreviewUrl(p.previewUrl);
|
||||
if (!c.ok) throw new ApiError("bad_params", tr("err.previewUrl"));
|
||||
patch.previewUrl = c.target.href;
|
||||
}
|
||||
}
|
||||
const next = await svc.threads.patch(p.id, patch);
|
||||
gw.publish("sidebar", { type: "thread.upsert", thread: next });
|
||||
return next;
|
||||
@@ -445,11 +502,13 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
id: z.string(),
|
||||
text: z.string(),
|
||||
attachments: z.array(z.object({ path: z.string(), mime: z.string(), name: z.string().optional() })).optional(),
|
||||
// 1.2: paths dragged from the Files panel, relative to the project (the daemon resolves and checks them)
|
||||
mentions: z.array(z.object({ rel: z.string().min(1).max(4096), isDir: z.boolean().optional() })).max(MAX_MENTIONS).optional(),
|
||||
behavior: z.enum(["queue", "steer"]).optional(),
|
||||
}),
|
||||
async (p) => {
|
||||
// delivered tells the composer what happened: a steer an Agent can't take is queued (B7)
|
||||
const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue");
|
||||
const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments, mentions: p.mentions }, p.behavior ?? "queue");
|
||||
return { ok: true, delivered: delivered ?? "started" };
|
||||
}
|
||||
));
|
||||
@@ -533,7 +592,11 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
L.push(`> ${meta.provider} · ${meta.model ?? tr("export.defaultModel")} · ${meta.mode} · ${new Date(meta.createdAt).toLocaleString(intlLocale())}`, "");
|
||||
for (const e of events) {
|
||||
switch (e.type) {
|
||||
case "user_message": L.push(`**${tr("export.me")}**${e.steered ? tr("export.steered") : ""}:\n\n${e.text}`, ""); break;
|
||||
case "user_message": {
|
||||
const refs = e.mentions?.length ? "\n\n" + e.mentions.map((m) => `- \`${m.path}${m.isDir ? "/" : ""}\``).join("\n") : "";
|
||||
L.push(`**${tr("export.me")}**${e.steered ? tr("export.steered") : ""}:\n\n${e.text}${refs}`, "");
|
||||
break;
|
||||
}
|
||||
case "assistant_message": L.push(e.text, ""); break;
|
||||
case "reasoning": L.push(`<details><summary>${tr("export.reasoning")}</summary>\n\n${e.text}\n</details>`, ""); break;
|
||||
case "tool_call": {
|
||||
|
||||
@@ -266,6 +266,7 @@ function installExitHook() {
|
||||
}
|
||||
|
||||
function createHost(port) {
|
||||
const gatePort = port;
|
||||
const p = paths();
|
||||
const log = makeLogger(p);
|
||||
// Gate key: written to session.js; even if leaked it only buys one navigation to the daemon
|
||||
@@ -331,6 +332,9 @@ function createHost(port) {
|
||||
p.dataRoot,
|
||||
"--parent-pid",
|
||||
String(process.pid),
|
||||
// the preview proxy refuses the gate's port
|
||||
"--gate-port",
|
||||
String(gatePort),
|
||||
],
|
||||
{
|
||||
// The token goes through an environment variable, not the command line (command lines are visible to other users on the machine)
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
|
||||
"author": "qingnian108 (https://github.com/qingnian108)",
|
||||
"homepage": "https://github.com/qingnian108/magpie-agent-console",
|
||||
@@ -64,7 +64,8 @@
|
||||
"e2e:v1": "node scripts/e2e-v1.mjs",
|
||||
"shot:v1": "node scripts/shot-v1.mjs",
|
||||
"verify:build": "node scripts/verify-build.mjs",
|
||||
"test:real": "vitest run --config vitest.real.config.ts"
|
||||
"test:real": "vitest run --config vitest.real.config.ts",
|
||||
"test:preview-attack": "node scripts/preview-attack.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20",
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// Real-browser regression for #582 (preview proxy): another web page must not be able to read or drive a previewed dev
|
||||
// server through the proxy, while the preview frame itself (sandboxed, opaque, as inside Magpie) still works.
|
||||
//
|
||||
// node scripts/preview-attack.mjs [--daemon daemon/dist/main.js] [--browser chromium|webkit|all]
|
||||
//
|
||||
// What it runs: a dev server that refuses foreign Origins (as Vite does since CVE-2025-24010), the real daemon bundle with a
|
||||
// throwaway data folder, preview.open over the token WebSocket, then in a real browser
|
||||
// - attacker: a page on another origin whose sandbox="allow-scripts" frame (Origin: null) tries the proxy port directly
|
||||
// (127.0.0.1 / localhost / a made-up ac<key>.localhost name), a POST, a no-cors POST and a WebSocket;
|
||||
// - legit: a Magpie-like page → sandbox="allow-scripts" frame → the preview iframe at proxyHref, running an ES module app
|
||||
// that imports a module, fetches /secret, POSTs /admin, loads an absolute-path image and opens a WebSocket.
|
||||
// Exit code 1 if the attacker read or changed anything, or the legit preview broke.
|
||||
import http from "node:http";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { platform as osPlatform, release as osRelease, tmpdir } from "node:os";
|
||||
import { join, dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createRequire } from "node:module";
|
||||
import { findBrowser } from "./browser-path.mjs";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const require = createRequire(join(root, "package.json"));
|
||||
const { chromium, webkit } = require("playwright-core");
|
||||
const WebSocket = require("ws");
|
||||
|
||||
const arg = (k, d) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };
|
||||
const daemonPath = resolve(arg("--daemon", join(root, "daemon/dist/main.js")));
|
||||
const which = arg("--browser", "chromium");
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const listen = (srv) => new Promise((r) => srv.listen(0, "127.0.0.1", () => r(srv.address().port)));
|
||||
|
||||
// ---- dev server: refuses a foreign Origin, never sends CORS headers ----
|
||||
const hits = [];
|
||||
let devPort = 0;
|
||||
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", "base64");
|
||||
const dev = http.createServer((req, res) => {
|
||||
const o = req.headers.origin;
|
||||
if (o && o !== `http://localhost:${devPort}`) { res.writeHead(403); res.end("foreign origin"); return; }
|
||||
const u = new URL(req.url, "http://x");
|
||||
hits.push(`${req.method} ${u.pathname}${u.search}`);
|
||||
if (u.pathname === "/") {
|
||||
res.writeHead(200, { "content-type": "text/html" });
|
||||
res.end(`<!doctype html><html><head><title>dev</title></head><body><img id="logo" src="/logo.png"><script type="module" src="/src/main.js"></script></body></html>`);
|
||||
} else if (u.pathname === "/src/main.js") {
|
||||
res.writeHead(200, { "content-type": "text/javascript" });
|
||||
res.end(`import { dep } from "/src/dep.js";
|
||||
const out = { module: dep };
|
||||
try { out.secret = await (await fetch("/secret")).text(); } catch (e) { out.secret = "ERR " + e; }
|
||||
try { out.admin = await (await fetch("/admin?by=legit", { method: "POST", body: "x" })).text(); } catch (e) { out.admin = "ERR " + e; }
|
||||
const img = document.getElementById("logo");
|
||||
out.image = img.complete ? img.naturalWidth > 0 : await new Promise((r) => { img.onload = () => r(true); img.onerror = () => r(false); });
|
||||
out.ws = await new Promise((r) => { try { const w = new WebSocket("ws://" + location.host + "/hmr"); w.onopen = () => w.send("hi"); w.onmessage = (e) => { r(String(e.data)); w.close(); }; w.onerror = () => r("ERR"); setTimeout(() => r("TIMEOUT"), 4000); } catch (e) { r("ERR " + e); } });
|
||||
out.storage = (() => { try { localStorage.setItem("k", "v"); return localStorage.getItem("k"); } catch (e) { return "ERR"; } })();
|
||||
parent.postMessage({ app: out }, "*");`);
|
||||
} else if (u.pathname === "/src/dep.js") {
|
||||
res.writeHead(200, { "content-type": "text/javascript" });
|
||||
res.end(`export const dep = "MODULE-OK";`);
|
||||
} else if (u.pathname === "/logo.png") {
|
||||
res.writeHead(200, { "content-type": "image/png" });
|
||||
res.end(PNG);
|
||||
} else if (u.pathname === "/secret") {
|
||||
res.writeHead(200, { "content-type": "text/plain" });
|
||||
res.end("DEV-SECRET-4242");
|
||||
} else if (u.pathname === "/admin") {
|
||||
res.writeHead(200, { "content-type": "text/plain" });
|
||||
res.end("ADMIN-ACTION-DONE " + (u.searchParams.get("by") ?? ""));
|
||||
} else { res.writeHead(404); res.end(); }
|
||||
});
|
||||
dev.on("upgrade", (req, socket) => {
|
||||
const o = req.headers.origin;
|
||||
if (o && o !== `http://localhost:${devPort}`) { socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); return; }
|
||||
hits.push(`WS ${req.url}`);
|
||||
// minimal WebSocket: accept, then echo "echo:<text>" for one short text frame
|
||||
const key = req.headers["sec-websocket-key"];
|
||||
const accept = require("node:crypto").createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
|
||||
socket.write(`HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: ${accept}\r\n\r\n`);
|
||||
socket.on("data", (b) => {
|
||||
if (b.length < 6 || (b[0] & 0x0f) !== 1) return;
|
||||
const len = b[1] & 0x7f; const mask = b.subarray(2, 6); const data = Buffer.from(b.subarray(6, 6 + len)).map((x, i) => x ^ mask[i % 4]);
|
||||
const msg = Buffer.from("echo:" + data.toString());
|
||||
socket.write(Buffer.concat([Buffer.from([0x81, msg.length]), msg]));
|
||||
});
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
devPort = await listen(dev);
|
||||
|
||||
// ---- the real daemon, throwaway data folder, preview.open over the token WebSocket ----
|
||||
const data = mkdtempSync(join(tmpdir(), "ac-attack-"));
|
||||
const daemon = spawn(process.execPath, [daemonPath, "--port", "0", "--data", data], {
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1", HOME: data, USERPROFILE: data, XDG_CONFIG_HOME: join(data, "cfg") },
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
let dj = null;
|
||||
for (let i = 0; i < 100 && !dj; i++) { try { dj = JSON.parse(readFileSync(join(data, "magpie/agent-console/daemon.json"), "utf8")); } catch { await sleep(150); } }
|
||||
if (!dj) throw new Error("daemon did not start");
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${dj.port}/ws`, { headers: { origin: "null" } });
|
||||
await new Promise((r, j) => { ws.once("open", r); ws.once("error", j); });
|
||||
const pending = new Map();
|
||||
ws.on("message", (b) => { const m = JSON.parse(String(b)); if (m.t === "res" && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); } });
|
||||
ws.send(JSON.stringify({ t: "hello", token: dj.token, v: 1 }));
|
||||
await sleep(300);
|
||||
let nid = 1;
|
||||
const call = (m, p) => new Promise((r) => { const id = nid++; pending.set(id, r); ws.send(JSON.stringify({ t: "req", id, m, p })); });
|
||||
const opened = await call("preview.open", { url: `http://localhost:${devPort}/` });
|
||||
if (!opened.ok) throw new Error("preview.open failed: " + JSON.stringify(opened.e));
|
||||
const { proxyOrigin, proxyHref, nonce, canaryOrigin, canaryNonce } = opened.r;
|
||||
if (!nonce || !canaryOrigin || !canaryNonce) throw new Error("preview.open missing nonce/canary: " + JSON.stringify(opened.r));
|
||||
// The daemon reports its own OS (the WebKit UA is frozen at 10_15_7): the panel refuses Apple WebKit on Darwin < 25
|
||||
const host = opened.r.host;
|
||||
const wantMajor = osPlatform() === "darwin" ? Number(osRelease().split(".")[0]) : null;
|
||||
if (!host || host.platform !== osPlatform() || host.darwinMajor !== wantMajor) {
|
||||
throw new Error("preview.open host info wrong: " + JSON.stringify(host) + " want " + JSON.stringify({ platform: osPlatform(), darwinMajor: wantMajor }));
|
||||
}
|
||||
const proxyPort = Number(new URL(proxyOrigin).port);
|
||||
|
||||
// ---- attacker: another origin, sandboxed frame, knows the proxy port (worst case) but not the key ----
|
||||
const attackJs = `
|
||||
const P = ${proxyPort}, D = ${devPort};
|
||||
const tryText = async (url, init) => { try { const r = await fetch(url, init); return r.status + " " + (await r.text()).slice(0, 60); } catch (e) { return "blocked (" + e.name + ")"; } };
|
||||
(async () => {
|
||||
const out = {};
|
||||
out.devDirect = await tryText("http://localhost:" + D + "/secret");
|
||||
out.proxy127 = await tryText("http://127.0.0.1:" + P + "/secret");
|
||||
out.proxyLocalhost = await tryText("http://localhost:" + P + "/secret");
|
||||
out.proxyGuessedKey = await tryText("http://ac" + "0123456789abcdef0123456789abcdef" + ".localhost:" + P + "/secret");
|
||||
out.adminPost = await tryText("http://127.0.0.1:" + P + "/admin?by=attacker", { method: "POST", body: "x" });
|
||||
try { await fetch("http://127.0.0.1:" + P + "/admin?by=attacker-nocors", { method: "POST", body: "x", mode: "no-cors" }); out.adminNoCors = "sent"; } catch (e) { out.adminNoCors = "blocked"; }
|
||||
out.ws = await new Promise((r) => { try { const w = new WebSocket("ws://127.0.0.1:" + P + "/hmr"); w.onopen = () => w.send("hi"); w.onmessage = (e) => r("READ " + e.data); w.onerror = () => r("blocked"); setTimeout(() => r("timeout"), 3000); } catch (e) { r("blocked"); } });
|
||||
parent.postMessage({ attack: out }, "*");
|
||||
})();`;
|
||||
const attacker = http.createServer((_q, res) => {
|
||||
res.writeHead(200, { "content-type": "text/html" });
|
||||
res.end(`<!doctype html><script>window.__r=null;addEventListener("message",e=>{if(e.data&&e.data.attack)window.__r=e.data.attack});</script>
|
||||
<iframe sandbox="allow-scripts" srcdoc="${`<script>${attackJs}</script>`.replace(/&/g, "&").replace(/"/g, """)}"></iframe>`);
|
||||
});
|
||||
const attackerPort = await listen(attacker);
|
||||
|
||||
// ---- legit: Magpie-like page → sandboxed console-like frame → the preview iframe ----
|
||||
const PING = "/__agent_console__/ping";
|
||||
const consoleJs = `
|
||||
(async () => {
|
||||
const pingOnce = async (origin, expect) => {
|
||||
try {
|
||||
const r = await fetch(origin + ${JSON.stringify(PING)}, { cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer" });
|
||||
const body = await r.text();
|
||||
return r.status + " " + (body === expect ? "nonce-ok" : ("nonce-bad:" + body.slice(0, 40)));
|
||||
} catch (e) { return "ERR " + e.name; }
|
||||
};
|
||||
let ping = "n/a";
|
||||
let canary = "n/a";
|
||||
if (${JSON.stringify(proxyOrigin)}.indexOf(".localhost:") > 0) {
|
||||
canary = await pingOnce(${JSON.stringify(canaryOrigin)}, ${JSON.stringify(canaryNonce)});
|
||||
ping = await pingOnce(${JSON.stringify(proxyOrigin)}, ${JSON.stringify(nonce)});
|
||||
}
|
||||
addEventListener("message", (e) => { if (e.data && e.data.app) parent.postMessage({ legit: Object.assign({ ping, canary }, e.data.app) }, "*"); });
|
||||
if (!/nonce-ok/.test(canary) || !/nonce-ok/.test(ping)) {
|
||||
parent.postMessage({ legit: { ping, canary, module: "SKIPPED", secret: "SKIPPED", admin: "SKIPPED", image: false, ws: "SKIPPED" } }, "*");
|
||||
return;
|
||||
}
|
||||
const f = document.createElement("iframe"); f.src = ${JSON.stringify(proxyHref)}; f.referrerPolicy = "no-referrer"; document.body.appendChild(f);
|
||||
})();`;
|
||||
const magpieSim = http.createServer((_q, res) => {
|
||||
res.writeHead(200, { "content-type": "text/html" });
|
||||
res.end(`<!doctype html><script>window.__r=null;addEventListener("message",e=>{if(e.data&&e.data.legit)window.__r=e.data.legit});</script>
|
||||
<iframe sandbox="allow-scripts" srcdoc="${`<body><script>${consoleJs}</script></body>`.replace(/&/g, "&").replace(/"/g, """)}"></iframe>`);
|
||||
});
|
||||
const magpiePort = await listen(magpieSim);
|
||||
|
||||
async function run(name, type, opts) {
|
||||
hits.length = 0;
|
||||
const browser = await type.launch({ headless: true, ...opts });
|
||||
const page = await browser.newPage();
|
||||
const get = async (url) => {
|
||||
await page.goto(url);
|
||||
for (let i = 0; i < 80; i++) { const r = await page.evaluate(() => window.__r); if (r) return r; await sleep(150); }
|
||||
return "no result";
|
||||
};
|
||||
const attack = await get(`http://127.0.0.1:${attackerPort}/`);
|
||||
await sleep(500);
|
||||
const attackerHits = hits.filter((h) => h.includes("attacker"));
|
||||
const legit = await get(`http://127.0.0.1:${magpiePort}/`);
|
||||
await browser.close();
|
||||
return { browser: name, attack, attackerHitsOnDevServer: attackerHits, legit };
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const browsers = [];
|
||||
if (which === "chromium" || which === "all") browsers.push(["chromium", chromium, { executablePath: findBrowser(), args: ["--no-sandbox"] }]);
|
||||
if (which === "webkit" || which === "all") browsers.push(["webkit", webkit, {}]);
|
||||
for (const [n, t, o] of browsers) {
|
||||
try { results.push(await run(n, t, o)); } catch (e) { results.push({ browser: n, error: String(e).split("\n")[0] }); }
|
||||
}
|
||||
ws.close();
|
||||
daemon.kill();
|
||||
dev.close(); attacker.close(); magpieSim.close();
|
||||
await sleep(200);
|
||||
rmSync(data, { recursive: true, force: true });
|
||||
|
||||
let bad = false;
|
||||
for (const r of results) {
|
||||
if (r.error) { bad = true; continue; }
|
||||
const leaked = Object.values(r.attack).some((v) => /DEV-SECRET|ADMIN-ACTION|READ /.test(String(v))) || r.attackerHitsOnDevServer.length > 0;
|
||||
const l = r.legit;
|
||||
const works = l && /nonce-ok/.test(l.canary) && /nonce-ok/.test(l.ping) && l.module === "MODULE-OK" && l.secret === "DEV-SECRET-4242" && /ADMIN-ACTION-DONE legit/.test(l.admin) && l.image === true && l.ws === "echo:hi";
|
||||
r.verdict = { attackerGotIn: leaked, legitPreviewWorks: !!works };
|
||||
if (leaked || !works) bad = true;
|
||||
}
|
||||
console.log(JSON.stringify({ daemon: daemonPath.replace(root + "/", ""), proxyOrigin: proxyOrigin.replace(/ac[0-9a-f]{32}/, "ac<key>"), results }, null, 2));
|
||||
process.exit(bad ? 1 : 0);
|
||||
@@ -0,0 +1,488 @@
|
||||
// 1.2: preview proxy security rules, local-link detection, path chips, content width / chat font size, live Magpie theme.
|
||||
import { describe, expect, it, afterEach } from "vitest";
|
||||
import http from "node:http";
|
||||
import net from "node:net";
|
||||
import { existsSync, mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve, sep } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { request as netRequest } from "./helpers-net.js";
|
||||
|
||||
// Preview listeners answer only at ac<key>.localhost:<port> (#582): requests below go there unless a test sets Host itself
|
||||
const proxyHosts = new Map<number, string>();
|
||||
function remember<T extends { proxyOrigin: string }>(r: T): T {
|
||||
const u = new URL(r.proxyOrigin);
|
||||
proxyHosts.set(Number(u.port), u.host);
|
||||
return r;
|
||||
}
|
||||
const request = (port: number, path: string, headers: Record<string, string> = {}, method?: string) =>
|
||||
netRequest(port, path, { host: proxyHosts.get(port) ?? `127.0.0.1:${port}`, ...headers }, method);
|
||||
import { checkPreviewUrl, deniedPort, displayHref, externalHref, withScheme } from "../../daemon/src/preview/url.js";
|
||||
import { PreviewProxy, rewriteLocation, stripFrameAncestors } from "../../daemon/src/preview/proxy.js";
|
||||
import { injectScriptTag, PREVIEW_SCRIPT_PATH } from "../../daemon/src/preview/inject.js";
|
||||
import { previewDeniedPorts } from "../../daemon/src/preview/ports.js";
|
||||
import { openExternal, openerFor } from "../../daemon/src/util/openExternal.js";
|
||||
import { insideRoot, mentionSection, resolveMentions, withMentions } from "../../daemon/src/util/mentions.js";
|
||||
import { buildAcpPrompt } from "../../daemon/src/providers/acp/prompt.js";
|
||||
import { parseSettingsPatch, sanitizeStored, DEFAULT_SETTINGS } from "../../daemon/src/store/settings.js";
|
||||
import { parseConfig } from "../../daemon/src/config.js";
|
||||
import { findLocalLinks, localHref, splitLocalLinks } from "../../web/src/util/localLinks.js";
|
||||
import { addMention, joinProjectPath, mentionsForSend, parseMentionDrag, relFromAbs } from "../../web/src/composer/mentions.js";
|
||||
import { colValue, normalizeChatFont, normalizeContentWidth } from "../../web/src/layout/chatLayout.js";
|
||||
import { parseMagpieTheme, themeFromMessage } from "../../web/src/layout/magpieBridge.js";
|
||||
import { magpieTokenVars } from "../../web/src/layout/applyMagpieTokens.js";
|
||||
|
||||
describe("preview URL rules", () => {
|
||||
it("normalizes what people type", () => {
|
||||
expect(withScheme("5173")).toBe("http://localhost:5173/");
|
||||
expect(withScheme(":5173/x")).toBe("http://localhost:5173/x");
|
||||
expect(withScheme("localhost:5173")).toBe("http://localhost:5173");
|
||||
const ok = (s: string) => { const c = checkPreviewUrl(s); return c.ok ? c.target.href : null; };
|
||||
expect(ok("5173")).toBe("http://localhost:5173/");
|
||||
expect(ok("localhost:3000/a?b=1#c")).toBe("http://localhost:3000/a?b=1#c");
|
||||
expect(ok("http://127.0.0.1:5173/x")).toBe("http://127.0.0.1:5173/x");
|
||||
expect(ok("127.1.2.3:80")).toBe("http://127.1.2.3/");
|
||||
expect(ok("0.0.0.0:8080")).toBe("http://0.0.0.0:8080/");
|
||||
expect(ok("http://[::1]:4000/")).toBe("http://[::1]:4000/");
|
||||
expect(ok("app.localhost:3000")).toBe("http://app.localhost:3000/");
|
||||
expect(ok("https://localhost:8443")).toBe("https://localhost:8443/");
|
||||
});
|
||||
it("refuses anything that isn't a loopback http(s) URL", () => {
|
||||
const why = (s: string) => { const c = checkPreviewUrl(s); return c.ok ? "ok" : c.reason; };
|
||||
expect(why("")).toBe("empty");
|
||||
expect(why("example.com")).toBe("not_local");
|
||||
expect(why("192.168.1.10:3000")).toBe("not_local");
|
||||
expect(why("10.0.0.1:80")).toBe("not_local");
|
||||
expect(why("localhost.evil.com:80")).toBe("not_local");
|
||||
expect(why("127.0.0.1.nip.io:80")).toBe("not_local");
|
||||
expect(why("http://user:pw@localhost:3000")).toBe("userinfo");
|
||||
expect(why("file:///etc/passwd")).toBe("scheme");
|
||||
expect(why("javascript:alert(1)")).toBe("scheme");
|
||||
expect(why("ftp://localhost:21")).toBe("scheme");
|
||||
expect(why("localhost:99999")).toBe("bad_url");
|
||||
expect(why("http://localhost:3000/" + "a".repeat(2100))).toBe("too_long");
|
||||
});
|
||||
it("connects localhost to IPv4 first, then ::1; 0.0.0.0 to 127.0.0.1", () => {
|
||||
const c = checkPreviewUrl("localhost:5173");
|
||||
expect(c.ok && c.target.connect).toEqual(["127.0.0.1", "::1"]);
|
||||
const z = checkPreviewUrl("0.0.0.0:5173");
|
||||
expect(z.ok && z.target.connect).toEqual(["127.0.0.1"]);
|
||||
const v6 = checkPreviewUrl("[::1]:5173");
|
||||
expect(v6.ok && v6.target.connect).toEqual(["::1"]);
|
||||
});
|
||||
it("denies the daemon, gate and Magpie ports", () => {
|
||||
const d = previewDeniedPorts({ port: 41000, gatePort: 3499 }, { MAGPIE_ADDR: "127.0.0.1:3525" });
|
||||
for (const p of [41000, 3499, 3488, 3425, 3430, 3525]) expect(deniedPort(p, d)).toBe(true);
|
||||
expect(deniedPort(5173, d)).toBe(false);
|
||||
expect(previewDeniedPorts({ port: 1 }, { AGENT_CONSOLE_PREVIEW_DENY: "9000, 9001" })).toEqual(expect.arrayContaining([9000, 9001]));
|
||||
expect(parseConfig(["--port", "0", "--gate-port", "3555"]).gatePort).toBe(3555);
|
||||
expect(parseConfig(["--gate-port", "nope"]).gatePort).toBeUndefined();
|
||||
});
|
||||
it("maps a proxied href back to the target for the address bar", () => {
|
||||
expect(displayHref("http://127.0.0.1:4444/a?b#c", "http://127.0.0.1:4444", "http://localhost:5173")).toBe("http://localhost:5173/a?b#c");
|
||||
expect(displayHref("http://127.0.0.1:4444/", "http://127.0.0.1:4444", "http://localhost:80")).toBe("http://localhost/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("app.openExternal", () => {
|
||||
it("only takes http(s), re-serialized", () => {
|
||||
expect(externalHref("https://example.com/a b")).toBe("https://example.com/a%20b");
|
||||
expect(externalHref("javascript:alert(1)")).toBeNull();
|
||||
expect(externalHref("file:///C:/Windows/system32/calc.exe")).toBeNull();
|
||||
expect(externalHref("vscode://open?x")).toBeNull();
|
||||
expect(externalHref("not a url")).toBeNull();
|
||||
expect(externalHref("https://x.com/?q=a&b=|c")).toBeNull(); // odd characters left by URL: refused
|
||||
});
|
||||
it("uses a no-shell opener per OS", () => {
|
||||
const href = "https://example.com/?a=1&b=2";
|
||||
expect(openerFor("win32", href)).toEqual({ cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", href] });
|
||||
expect(openerFor("darwin", href)).toEqual({ cmd: "open", args: [href] });
|
||||
expect(openerFor("linux", href)).toEqual({ cmd: "xdg-open", args: [href] });
|
||||
});
|
||||
it("runs execFile with one argument and reports a missing opener", async () => {
|
||||
const calls: { cmd: string; args: string[] }[] = [];
|
||||
const ok = await openExternal("https://example.com/x?y=1&z=2", {
|
||||
platform: "win32",
|
||||
exec: (cmd, args, _o, cb) => { calls.push({ cmd, args }); setTimeout(() => cb(null), 1); return { on: () => {} }; },
|
||||
});
|
||||
expect(ok.ok).toBe(true);
|
||||
expect(calls).toEqual([{ cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", "https://example.com/x?y=1&z=2"] }]);
|
||||
const missing = await openExternal("https://example.com/", {
|
||||
platform: "linux",
|
||||
exec: () => ({ on: (_e: string, fn: (e: Error) => void) => setTimeout(() => fn(new Error("ENOENT")), 1) }),
|
||||
});
|
||||
expect(missing.ok).toBe(false);
|
||||
expect((await openExternal("file:///etc/passwd", { exec: () => { throw new Error("must not run"); } })).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the proxy against a real upstream ----
|
||||
type Up = { server: http.Server; port: number; seen: http.IncomingHttpHeaders[] };
|
||||
async function upstream(handler: (req: http.IncomingMessage, res: http.ServerResponse) => void): Promise<Up> {
|
||||
const seen: http.IncomingHttpHeaders[] = [];
|
||||
const server = http.createServer((req, res) => { seen.push(req.headers); handler(req, res); });
|
||||
server.on("upgrade", (req, socket) => {
|
||||
seen.push(req.headers);
|
||||
socket.write("HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\n\r\n");
|
||||
socket.on("data", (d) => socket.write(Buffer.concat([Buffer.from("echo:"), d])));
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
|
||||
return { server, port: (server.address() as net.AddressInfo).port, seen };
|
||||
}
|
||||
|
||||
describe("preview proxy", () => {
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => { for (const f of cleanup.splice(0)) f(); });
|
||||
|
||||
async function setup(handler: Parameters<typeof upstream>[0], opts: Partial<ConstructorParameters<typeof PreviewProxy>[0]> = {}) {
|
||||
const up = await upstream(handler);
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [], ...opts });
|
||||
cleanup.push(() => { proxy.closeAll(); up.server.close(); });
|
||||
const r = remember(await proxy.open(`http://localhost:${up.port}/start`));
|
||||
const port = Number(new URL(r.proxyOrigin).port);
|
||||
return { up, proxy, r, port };
|
||||
}
|
||||
|
||||
it("opens one random-port listener per target and refuses denied ports", async () => {
|
||||
const { proxy, r, up, port } = await setup((_q, s) => s.end("ok"));
|
||||
expect(r.proxyOrigin).toMatch(/^http:\/\/ac[0-9a-f]{32}\.localhost:\d+$/);
|
||||
expect(r.proxyHref).toBe(`${r.proxyOrigin}/start`);
|
||||
expect(r.target).toBe(`http://localhost:${up.port}`);
|
||||
const again = await proxy.open(`localhost:${up.port}/other`);
|
||||
expect(again.proxyOrigin).toBe(r.proxyOrigin);
|
||||
await expect(proxy.open(`localhost:${port}`)).rejects.toMatchObject({ code: "denied_port" }); // the proxy itself
|
||||
const p2 = new PreviewProxy({ deniedPorts: () => [up.port] });
|
||||
await expect(p2.open(`localhost:${up.port}`)).rejects.toMatchObject({ code: "denied_port" });
|
||||
await expect(p2.open("example.com:80")).rejects.toMatchObject({ code: "not_local" });
|
||||
p2.closeAll();
|
||||
});
|
||||
|
||||
it("checks Host and Origin; rewrites Host/Origin/Referer upstream; strips cookies", async () => {
|
||||
const { up, port } = await setup((_q, s) => s.end("hi"));
|
||||
expect((await request(port, "/", { host: `evil.test:${port}` })).status).toBe(421);
|
||||
expect((await request(port, "/", { host: `127.0.0.1:${port + 1}` })).status).toBe(421);
|
||||
// the bare loopback address (no key) is refused, with nothing a page could read (#582)
|
||||
for (const host of [`127.0.0.1:${port}`, `localhost:${port}`, `ac${"0".repeat(32)}.localhost:${port}`]) {
|
||||
const no = await request(port, "/", { host, origin: "null" });
|
||||
expect([403, 421]).toContain(no.status);
|
||||
expect(no.headers["access-control-allow-origin"]).toBeUndefined();
|
||||
}
|
||||
expect((await request(port, "/", { origin: "https://evil.test" })).status).toBe(403);
|
||||
expect((await request(port, "/", { origin: "http://localhost:3430" })).status).toBe(403);
|
||||
const ok = await request(port, "/x", { origin: "null", cookie: "magpie=secret", referer: `http://${proxyHosts.get(port)}/a`, "sec-fetch-site": "cross-site" });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.headers["access-control-allow-origin"]).toBe("null");
|
||||
const h = up.seen.at(-1)!;
|
||||
expect(h.host).toBe(`localhost:${up.port}`);
|
||||
expect(h.origin).toBe(`http://localhost:${up.port}`);
|
||||
expect(h.referer).toBe(`http://localhost:${up.port}/a`);
|
||||
expect(h["sec-fetch-site"]).toBe("same-origin");
|
||||
expect(h.cookie).toBeUndefined();
|
||||
expect(h["accept-encoding"]).toBe("identity");
|
||||
// no Origin stays no Origin
|
||||
await request(port, "/y");
|
||||
expect(up.seen.at(-1)!.origin).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops X-Frame-Options, frame-ancestors and Set-Cookie; rewrites a redirect to the target", async () => {
|
||||
const { up, port, r } = await setup((req, s) => {
|
||||
if (req.url === "/go") { s.writeHead(302, { location: `http://localhost:${up.port}/there?q=1` }); s.end(); return; }
|
||||
if (req.url === "/away") { s.writeHead(302, { location: "https://example.com/" }); s.end(); return; }
|
||||
s.writeHead(200, { "x-frame-options": "DENY", "content-security-policy": "default-src 'self'; frame-ancestors 'none'", "set-cookie": "sid=1", "access-control-allow-origin": "*" });
|
||||
s.end("x");
|
||||
});
|
||||
const res = await request(port, "/");
|
||||
expect(res.headers["x-frame-options"]).toBeUndefined();
|
||||
expect(res.headers["content-security-policy"]).toBe("default-src 'self'");
|
||||
expect(res.headers["set-cookie"]).toBeUndefined();
|
||||
expect(res.headers["access-control-allow-origin"]).toBe("null");
|
||||
expect((await request(port, "/go")).headers.location).toBe(`${r.proxyOrigin}/there?q=1`);
|
||||
expect((await request(port, "/away")).headers.location).toBe("https://example.com/");
|
||||
expect(stripFrameAncestors("frame-ancestors 'self'")).toBe("");
|
||||
});
|
||||
|
||||
it("injects the bridge script into HTML (chunked, no <head>) and serves it itself", async () => {
|
||||
const { port } = await setup((req, s) => {
|
||||
s.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
||||
if (req.url === "/nohead") { s.write("<!doctype html><body>"); s.end("hi</body>"); return; }
|
||||
s.write("<!doctype html><html><head><title>t</title></head>");
|
||||
s.end("<body>é</body></html>");
|
||||
});
|
||||
const a = await request(port, "/");
|
||||
expect(a.body).toContain(`<head><script src="${PREVIEW_SCRIPT_PATH}"></script><title>`);
|
||||
expect(a.body).toContain("é");
|
||||
expect(Number(a.headers["content-length"])).toBe(Buffer.byteLength(a.body));
|
||||
const b = await request(port, "/nohead");
|
||||
expect(b.body.startsWith(`<!doctype html><script src="${PREVIEW_SCRIPT_PATH}">`)).toBe(true);
|
||||
const js = await request(port, PREVIEW_SCRIPT_PATH);
|
||||
expect(js.status).toBe(200);
|
||||
expect(js.headers["content-type"]).toContain("javascript");
|
||||
expect(js.body).toContain("ac_preview");
|
||||
expect(injectScriptTag("<p>x</p>")).toBe(`<script src="${PREVIEW_SCRIPT_PATH}"></script><p>x</p>`);
|
||||
expect(injectScriptTag("<header>x</header>")).toBe(`<script src="${PREVIEW_SCRIPT_PATH}"></script><header>x</header>`);
|
||||
});
|
||||
|
||||
it("answers CORS preflight for the opaque frame", async () => {
|
||||
const { port } = await setup((_q, s) => s.end());
|
||||
const r = await request(port, "/api", { origin: "null", "access-control-request-method": "POST", "access-control-request-headers": "content-type" }, "OPTIONS");
|
||||
expect(r.status).toBe(204);
|
||||
expect(r.headers["access-control-allow-origin"]).toBe("null");
|
||||
expect(r.headers["access-control-allow-headers"]).toBe("content-type");
|
||||
});
|
||||
|
||||
it("shows an error page when the dev server isn't running", async () => {
|
||||
const dead = await upstream((_q, s) => s.end());
|
||||
const deadPort = dead.port;
|
||||
await new Promise((r) => dead.server.close(r));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const r = remember(await proxy.open(`localhost:${deadPort}`));
|
||||
const res = await request(Number(new URL(r.proxyOrigin).port), "/");
|
||||
expect(res.status).toBe(502);
|
||||
expect(res.body).toContain(`localhost:${deadPort}`);
|
||||
expect(res.body).toContain("Retry");
|
||||
});
|
||||
|
||||
it("tunnels WebSocket upgrades (HMR) with the Origin rewritten, and refuses a foreign Origin", async () => {
|
||||
const { up, port } = await setup((_q, s) => s.end());
|
||||
const talk = (origin: string, host = proxyHosts.get(port)!) => new Promise<string>((resolve) => {
|
||||
const s = net.connect(port, "127.0.0.1", () => {
|
||||
s.write(`GET /hmr HTTP/1.1\r\nhost: ${host}\r\nupgrade: websocket\r\nconnection: Upgrade\r\norigin: ${origin}\r\nsec-websocket-key: x\r\nsec-websocket-version: 13\r\n\r\n`);
|
||||
});
|
||||
let got = "";
|
||||
s.on("data", (d) => {
|
||||
got += d.toString();
|
||||
if (got.includes("101") && !got.includes("echo:")) s.write("ping");
|
||||
if (got.includes("echo:ping") || got.includes("403") || got.includes("421")) { s.destroy(); resolve(got); }
|
||||
});
|
||||
s.on("close", () => resolve(got));
|
||||
});
|
||||
const ok = await talk("null");
|
||||
expect(ok).toContain("101 Switching Protocols");
|
||||
expect(ok).toContain("echo:ping");
|
||||
expect(up.seen.at(-1)!.origin).toBe(`http://localhost:${up.port}`);
|
||||
expect(up.seen.at(-1)!.host).toBe(`localhost:${up.port}`);
|
||||
expect(await talk("https://evil.test")).toContain("403");
|
||||
expect(await talk("null", `127.0.0.1:${port}`)).toContain("403"); // no key (#582)
|
||||
});
|
||||
|
||||
it("closes idle listeners (fake clock), on release, and keeps at most N targets", async () => {
|
||||
let now = 1000;
|
||||
const a = await upstream((_q, s) => s.end("a"));
|
||||
const b = await upstream((_q, s) => s.end("b"));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [], now: () => now, idleMs: 10_000, maxTargets: 1 });
|
||||
cleanup.push(() => { proxy.closeAll(); a.server.close(); b.server.close(); });
|
||||
const ra = remember(await proxy.open(`localhost:${a.port}`));
|
||||
const rb = remember(await proxy.open(`localhost:${b.port}`));
|
||||
expect(proxy.size).toBe(1); // a was closed for b
|
||||
expect(proxy.ports()).toEqual([Number(new URL(rb.proxyOrigin).port)]);
|
||||
await expect(request(Number(new URL(ra.proxyOrigin).port), "/")).rejects.toThrow();
|
||||
now += 5_000;
|
||||
proxy.sweep();
|
||||
expect(proxy.size).toBe(1);
|
||||
now += 20_000;
|
||||
proxy.sweep();
|
||||
expect(proxy.size).toBe(0);
|
||||
await proxy.open(`localhost:${b.port}`);
|
||||
expect(proxy.release(`http://localhost:${b.port}/anything`)).toBe(true);
|
||||
expect(proxy.size).toBe(0);
|
||||
});
|
||||
|
||||
it("rewriteLocation leaves relative and foreign redirects alone", () => {
|
||||
const c = checkPreviewUrl("localhost:5173");
|
||||
if (!c.ok) throw new Error("x");
|
||||
expect(rewriteLocation("/login", c.target, "http://127.0.0.1:9")).toBe("/login");
|
||||
expect(rewriteLocation("http://localhost:5173/a", c.target, "http://127.0.0.1:9")).toBe("http://127.0.0.1:9/a");
|
||||
expect(rewriteLocation("http://localhost:5174/a", c.target, "http://127.0.0.1:9")).toBe("http://localhost:5174/a");
|
||||
});
|
||||
});
|
||||
|
||||
describe("local links in chat", () => {
|
||||
const urls = (s: string) => findLocalLinks(s).map((l) => l.text);
|
||||
it("finds local addresses, with or without a scheme", () => {
|
||||
expect(urls("open http://localhost:5173/ now")).toEqual(["http://localhost:5173/"]);
|
||||
expect(urls("跑在 localhost:3000 上了")).toEqual(["localhost:3000"]);
|
||||
expect(urls("地址:127.0.0.1:8080/api?x=1,然后")).toEqual(["127.0.0.1:8080/api?x=1"]);
|
||||
expect(urls("bind 0.0.0.0:8000 and [::1]:4000")).toEqual(["0.0.0.0:8000", "[::1]:4000"]);
|
||||
expect(urls("app.localhost:3000.")).toEqual(["app.localhost:3000"]);
|
||||
expect(urls("(see localhost:3000)")).toEqual(["localhost:3000"]);
|
||||
expect(urls("Local: http://localhost:5173/,")).toEqual(["http://localhost:5173/"]);
|
||||
expect(urls("go to localhost:3000/a/(b)")).toEqual(["localhost:3000/a/(b)"]);
|
||||
expect(urls("(见 localhost:3000/a)")).toEqual(["localhost:3000/a"]);
|
||||
});
|
||||
it("leaves other text alone", () => {
|
||||
expect(urls("runs on localhost")).toEqual([]);
|
||||
expect(urls("xlocalhost:3000 foo/localhost:3000 user@localhost:22")).toEqual([]);
|
||||
expect(urls("http://192.168.1.2:3000 and 10.0.0.1:80")).toEqual([]);
|
||||
expect(urls("localhost.evil.com:80")).toEqual([]);
|
||||
});
|
||||
it("normalizes to a URL the preview opens", () => {
|
||||
expect(findLocalLinks("localhost:3000")[0]!.url).toBe("http://localhost:3000/");
|
||||
expect(splitLocalLinks("a localhost:1 b")).toEqual(["a ", expect.objectContaining({ text: "localhost:1" }), " b"]);
|
||||
expect(localHref("http://localhost:3000/x")).toBe("http://localhost:3000/x");
|
||||
expect(localHref("https://example.com")).toBeNull();
|
||||
expect(localHref("localhost:3000")).toBeNull(); // hrefs need a scheme
|
||||
});
|
||||
});
|
||||
|
||||
describe("path chips (mentions)", () => {
|
||||
let dir = "";
|
||||
afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; });
|
||||
it("resolves inside the project only (../, absolute, symlink escape, missing)", async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac12-m-"));
|
||||
const proj = join(dir, "proj");
|
||||
mkdirSync(join(proj, "src"), { recursive: true });
|
||||
writeFileSync(join(proj, "src", "a b.ts"), "x");
|
||||
writeFileSync(join(dir, "secret.txt"), "s");
|
||||
try { symlinkSync(join(dir, "secret.txt"), join(proj, "link.txt")); } catch {}
|
||||
const r = await resolveMentions(proj, [
|
||||
{ rel: "src/a b.ts" }, { rel: "src", isDir: true }, { rel: "src/a b.ts" },
|
||||
{ rel: "../secret.txt" }, { rel: "/etc/passwd" }, { rel: "C:/x" }, { rel: "link.txt" }, { rel: "nope.ts" },
|
||||
]);
|
||||
// the path as the project was opened, with this OS's separators (#582: not the realpath, not always "/")
|
||||
expect(r.mentions.map((m) => [m.path, m.isDir])).toEqual([[join(proj, "src", "a b.ts"), false], [join(proj, "src"), true]]);
|
||||
expect(r.warnings).toEqual(expect.arrayContaining(["../secret.txt", "/etc/passwd", "C:/x", "nope.ts"]));
|
||||
if (process.platform !== "win32") expect(r.warnings).toContain("link.txt");
|
||||
});
|
||||
it("keeps the project path as opened when it goes through a symlink (macOS /var → /private/var, a linked workspace)", async () => {
|
||||
dir = realpathSync(mkdtempSync(join(tmpdir(), "ac12-ml-")));
|
||||
const realProj = join(dir, "real", "proj");
|
||||
mkdirSync(join(realProj, "src"), { recursive: true });
|
||||
writeFileSync(join(realProj, "src", "a.ts"), "x");
|
||||
writeFileSync(join(dir, "outside.txt"), "o");
|
||||
const alias = join(dir, "alias");
|
||||
try { symlinkSync(join(dir, "real"), alias, "junction"); } catch { return; } // no symlinks allowed here: nothing to check
|
||||
const proj = join(alias, "proj");
|
||||
// a link inside the project that points back into it through the real path is fine; one that leaves it is not
|
||||
try { symlinkSync(join(realProj, "src", "a.ts"), join(realProj, "inner.ts")); } catch {}
|
||||
try { symlinkSync(join(dir, "outside.txt"), join(realProj, "out.txt")); } catch {}
|
||||
const r = await resolveMentions(proj, [{ rel: "src/a.ts" }, { rel: "src", isDir: true }, { rel: "." , isDir: true }, { rel: "../../outside.txt" }, { rel: "out.txt" }]);
|
||||
expect(r.mentions.map((m) => m.path)).toEqual([join(proj, "src", "a.ts"), join(proj, "src"), proj]);
|
||||
expect(r.warnings).toEqual(expect.arrayContaining(["../../outside.txt"]));
|
||||
if (existsSync(join(realProj, "out.txt"))) expect(r.warnings).toContain("out.txt");
|
||||
if (existsSync(join(realProj, "inner.ts"))) {
|
||||
const r2 = await resolveMentions(proj, [{ rel: "inner.ts" }]);
|
||||
expect(r2.mentions.map((m) => m.path)).toEqual([join(proj, "inner.ts")]);
|
||||
}
|
||||
// a project opened with a trailing separator or a "." segment is the same project
|
||||
const r3 = await resolveMentions(proj + sep + "." + sep, [{ rel: "src/a.ts" }]);
|
||||
expect(r3.mentions.map((m) => m.path)).toEqual([join(proj, "src", "a.ts")]);
|
||||
});
|
||||
it("serializes for every Agent; ACP also gets resource_link blocks", async () => {
|
||||
const P = resolve(sep, "p");
|
||||
const m = [{ path: join(P, "src", "a b.ts"), isDir: false }, { path: join(P, "src"), isDir: true }];
|
||||
const slash = sep === "\\" ? "\\" : "/";
|
||||
expect(mentionSection(m)).toBe(`Referenced files (read them as needed):\n- \`${m[0]!.path}\`\n- ${m[1]!.path}${slash} (folder)`);
|
||||
expect(mentionSection([{ path: "/p/src/a b.ts", isDir: false }, { path: "/p/src", isDir: true }])).toBe("Referenced files (read them as needed):\n- `/p/src/a b.ts`\n- /p/src/ (folder)");
|
||||
expect(withMentions("fix it", m)).toBe("fix it\n\n" + mentionSection(m));
|
||||
expect(withMentions("", m)).toBe(mentionSection(m));
|
||||
expect(withMentions("x", [])).toBe("x");
|
||||
expect(mentionSection([{ path: "C:\\p\\src", isDir: true }])).toContain("C:\\p\\src\\ (folder)");
|
||||
const built = await buildAcpPrompt(withMentions("fix", m), [], { image: false, audio: false, embeddedContext: false }, m);
|
||||
expect(built.blocks[0]).toMatchObject({ type: "text" });
|
||||
expect(built.blocks.filter((b) => b.type === "resource_link").map((b) => (b as { uri: string }).uri)).toEqual([pathToFileURL(m[0]!.path).href, pathToFileURL(m[1]!.path).href]);
|
||||
if (sep === "/") expect(pathToFileURL(m[0]!.path).href).toBe("file:///p/src/a%20b.ts");
|
||||
});
|
||||
it("insideRoot handles Windows case and prefixes", () => {
|
||||
expect(insideRoot("C:\\Work\\App", "c:\\work\\app\\src", "win32")).toBe(true);
|
||||
expect(insideRoot("C:\\Work\\App", "C:\\Work\\App2\\x", "win32")).toBe(false);
|
||||
expect(insideRoot("/a/b", "/a/bc", "linux")).toBe(false);
|
||||
});
|
||||
it("composer side: drag data, dedupe, send shape, resend paths", () => {
|
||||
expect(parseMentionDrag(JSON.stringify({ projectId: "p1", rel: "src/a.ts", isDir: false }))).toEqual({ projectId: "p1", rel: "src/a.ts", isDir: false });
|
||||
expect(parseMentionDrag("{bad")).toBeNull();
|
||||
expect(parseMentionDrag(JSON.stringify({ projectId: 1, rel: "x" }))).toBeNull();
|
||||
let list = addMention([], { projectId: "p", rel: "a", isDir: false });
|
||||
list = addMention(list, { projectId: "p", rel: "a", isDir: false });
|
||||
list = addMention(list, { projectId: "p", rel: "d", isDir: true });
|
||||
expect(mentionsForSend(list)).toEqual([{ rel: "a", isDir: false }, { rel: "d", isDir: true }]);
|
||||
expect(joinProjectPath("/home/u/p", "src/a.ts")).toBe("/home/u/p/src/a.ts");
|
||||
expect(joinProjectPath("C:\\work\\p\\", "src/a.ts")).toBe("C:\\work\\p\\src\\a.ts");
|
||||
expect(relFromAbs("/home/u/p", "/home/u/p/src/a.ts")).toBe("src/a.ts");
|
||||
expect(relFromAbs("C:\\Work\\P", "c:\\work\\p\\src")).toBe("src");
|
||||
expect(relFromAbs("/home/u/p", "/home/u/p2/x")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("content width and chat font size", () => {
|
||||
it("settings accept the presets and 12–18 px only", () => {
|
||||
expect(DEFAULT_SETTINGS.contentWidth).toBe("default");
|
||||
expect(DEFAULT_SETTINGS.chatFontSize).toBe(13);
|
||||
for (const w of ["narrow", "default", "wide", "full"]) expect(parseSettingsPatch({ contentWidth: w }).ok).toBe(true);
|
||||
expect(parseSettingsPatch({ contentWidth: "huge" }).ok).toBe(false);
|
||||
expect(parseSettingsPatch({ chatFontSize: 12 }).ok).toBe(true);
|
||||
expect(parseSettingsPatch({ chatFontSize: 18 }).ok).toBe(true);
|
||||
expect(parseSettingsPatch({ chatFontSize: 11 }).ok).toBe(false);
|
||||
expect(parseSettingsPatch({ chatFontSize: 19 }).ok).toBe(false);
|
||||
expect(parseSettingsPatch({ chatFontSize: 13.5 }).ok).toBe(false);
|
||||
expect(parseSettingsPatch({ sidebarHidden: true }).ok).toBe(true);
|
||||
expect(sanitizeStored({ contentWidth: "x", chatFontSize: 40, theme: "dark" })).toEqual({ theme: "dark" });
|
||||
});
|
||||
it("maps to CSS values", () => {
|
||||
expect(colValue("narrow")).toBe("640px");
|
||||
expect(colValue("default")).toBe("720px");
|
||||
expect(colValue("wide")).toBe("880px");
|
||||
expect(colValue("full")).toBe("100%");
|
||||
expect(colValue("bogus")).toBe("720px");
|
||||
expect(normalizeContentWidth(undefined)).toBe("default");
|
||||
expect(normalizeChatFont(undefined)).toBe(13);
|
||||
expect(normalizeChatFont(9)).toBe(12);
|
||||
expect(normalizeChatFont(30)).toBe(18);
|
||||
expect(normalizeChatFont("16")).toBe(16);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live Magpie theme (bridge messages after the redirect)", () => {
|
||||
it("reads theme events and our hello answer only", () => {
|
||||
expect(themeFromMessage({ magpie: 1, event: "theme", data: { dark: true, lang: "zh", tokens: { bg: "#111" } } }, 5)).toEqual({ dark: true, lang: "zh", tokens: { bg: "#111" } });
|
||||
expect(themeFromMessage({ magpie: 1, id: 5, result: { dark: false, tokens: {} } }, 5)).toEqual({ dark: false, tokens: {} });
|
||||
expect(themeFromMessage({ magpie: 1, id: 6, result: { dark: false } }, 5)).toBeNull();
|
||||
expect(themeFromMessage({ event: "theme", data: { dark: true } }, 5)).toBeNull();
|
||||
expect(themeFromMessage({ magpie: 1, event: "theme", data: { dark: "yes" } }, 5)).toBeNull();
|
||||
expect(parseMagpieTheme({ dark: true, tokens: [1] })).toEqual({ dark: true, tokens: {} });
|
||||
});
|
||||
it("keeps neutral tokens, drops the accent and odd values", () => {
|
||||
expect(magpieTokenVars({ bg: "#111", "fg-2": "#eee", accent: "#f00", "accent-soft": "#f00", bad: "red;}", "x y": "1", font: "Inter, sans-serif" })).toEqual({
|
||||
"--magpie-bg": "#111", "--magpie-fg-2": "#eee", "--magpie-font": "Inter, sans-serif",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("1.2 QA fixes", () => {
|
||||
it("Claude Write says Create for a new file, Overwrite for an existing one", async () => {
|
||||
const { targetExists, callInfo } = await import("../../daemon/src/agents/kinds.js");
|
||||
const dir = mkdtempSync(join(tmpdir(), "ac12-k-"));
|
||||
writeFileSync(join(dir, "old.txt"), "x");
|
||||
expect(targetExists({ file_path: join(dir, "old.txt") })).toBe(true);
|
||||
expect(targetExists({ file_path: "old.txt" }, dir)).toBe(true);
|
||||
expect(targetExists({ file_path: join(dir, "new.txt") })).toBe(false);
|
||||
expect(targetExists({})).toBe(false);
|
||||
const create = callInfo("Write", { file_path: join(dir, "new.txt"), _exists: targetExists({ file_path: join(dir, "new.txt") }) }, dir);
|
||||
expect(create.title).toMatch(/新建|Create/);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
it("the theme bridge carries Magpie's language, and the UI language can switch at runtime", async () => {
|
||||
expect(parseMagpieTheme({ dark: false, lang: "en", tokens: {} })).toEqual({ dark: false, lang: "en", tokens: {} });
|
||||
expect(parseMagpieTheme({ dark: false, lang: "x".repeat(40) })).toEqual({ dark: false, tokens: {} });
|
||||
const i18n = await import("../../web/src/i18n/index.js");
|
||||
i18n.initLocale("?lang=zh");
|
||||
expect(i18n.t("sidebar.newProject")).toBe("新建项目");
|
||||
expect(i18n.setLocale("en")).toBe(true);
|
||||
expect(i18n.t("sidebar.newProject")).toBe("New project");
|
||||
expect(i18n.setLocale("en-US")).toBe(false);
|
||||
expect(i18n.setLocale("zh-TW")).toBe(true);
|
||||
expect(i18n.tf("timeline.toolSummaryOne", { n: 1, parts: "读取 1" })).toBe("已执行 1 步 · 读取 1");
|
||||
});
|
||||
it("every new 1.2 key exists in both languages", async () => {
|
||||
const { messages } = await import("../../web/src/i18n/messages.js");
|
||||
const keys = (o: Record<string, unknown>, p = ""): string[] => Object.entries(o).flatMap(([k, v]) => (typeof v === "object" && v ? keys(v as Record<string, unknown>, p + k + ".") : [p + k]));
|
||||
const zh = new Set(keys(messages.zh as unknown as Record<string, unknown>));
|
||||
const en = new Set(keys(messages.en as unknown as Record<string, unknown>));
|
||||
for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.toolSummaryOne"]) {
|
||||
expect(zh.has(k), "zh " + k).toBe(true);
|
||||
expect(en.has(k), "en " + k).toBe(true);
|
||||
}
|
||||
expect([...zh].filter((k) => !en.has(k) && !k.startsWith("composer.agentMode."))).toEqual([]);
|
||||
expect([...en].filter((k) => !zh.has(k))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,463 @@
|
||||
// #582 review fixes: the preview proxy's key (Host ac<key>.localhost), Magpie's gateway found by its settings.json port
|
||||
// and by how it answers, the per-open nonce the ping must echo (and the keyless canary before the keyed host is looked
|
||||
// up), and Apple WebKit refused only when the daemon host is before macOS 26 (Darwin < 25 from os.release(); the UA is
|
||||
// frozen at 10_15_7). The real-browser attack check is scripts/preview-attack.mjs (Chromium / WebKit).
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import http from "node:http";
|
||||
import net from "node:net";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { platform as osPlatform, release as osRelease, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { request } from "./helpers-net.js";
|
||||
import { PreviewProxy, PREVIEW_PING_PATH, identify, looksLikeMagpie, magpieIndex } from "../../daemon/src/preview/proxy.js";
|
||||
import { magpieConfigDirs, magpieDirFromInstall, previewDeniedPorts, savedGatewayPort } from "../../daemon/src/preview/ports.js";
|
||||
import { checkPreviewUrl, deniedPort } from "../../daemon/src/preview/url.js";
|
||||
import {
|
||||
PREVIEW_PING_PATH as WEB_PING,
|
||||
canReachProxy,
|
||||
confirmPreviewReachable,
|
||||
DARWIN_LOCALHOST_LOOPBACK as WEB_DARWIN_LOCALHOST_LOOPBACK,
|
||||
isAppleWebKit,
|
||||
isUnsafeLocalhostResolver,
|
||||
usePreview,
|
||||
} from "../../web/src/stores/preview.js";
|
||||
import { DARWIN_LOCALHOST_LOOPBACK, previewHost } from "../../daemon/src/preview/host.js";
|
||||
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => { for (const f of cleanup.splice(0)) f(); });
|
||||
|
||||
async function serve(handler: http.RequestListener): Promise<{ server: http.Server; port: number }> {
|
||||
const server = http.createServer(handler);
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r()));
|
||||
cleanup.push(() => server.close());
|
||||
return { server, port: (server.address() as net.AddressInfo).port };
|
||||
}
|
||||
const MAGPIE_INDEX = JSON.stringify({ apis: ["/v1/chat/completions"], models: 2, name: "magpie", pid: 1, version: "0.1.2391" });
|
||||
const hostOf = (proxyOrigin: string) => new URL(proxyOrigin).host;
|
||||
const portOf = (proxyOrigin: string) => Number(new URL(proxyOrigin).port);
|
||||
|
||||
describe("preview key (#582 finding 1)", () => {
|
||||
it("each listener gets its own unguessable ac<key>.localhost name; only that Host is served", async () => {
|
||||
const up = await serve((_q, s) => { s.setHeader("content-type", "text/plain"); s.end("DEV-SECRET"); });
|
||||
const up2 = await serve((_q, s) => s.end("two"));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const a = await proxy.open(`localhost:${up.port}`);
|
||||
const b = await proxy.open(`localhost:${up2.port}`);
|
||||
expect(a.proxyOrigin).toMatch(/^http:\/\/ac[0-9a-f]{32}\.localhost:\d+$/);
|
||||
expect(hostOf(a.proxyOrigin).split(".")[0]).not.toBe(hostOf(b.proxyOrigin).split(".")[0]);
|
||||
const port = portOf(a.proxyOrigin);
|
||||
// what any page can send: Origin null, the bare loopback port, a guessed name, b's key on a's port
|
||||
for (const host of [`127.0.0.1:${port}`, `localhost:${port}`, `AC${"f".repeat(32)}.localhost:${port}`, `${hostOf(b.proxyOrigin).split(":")[0]}:${port}`]) {
|
||||
for (const method of ["GET", "POST", "OPTIONS"]) {
|
||||
const r = await request(port, "/", { host, origin: "null", "access-control-request-method": "POST" }, method);
|
||||
expect([403, 421], `${method} ${host}`).toContain(r.status);
|
||||
expect(r.headers["access-control-allow-origin"]).toBeUndefined();
|
||||
expect(r.body).not.toContain("DEV-SECRET");
|
||||
}
|
||||
expect([403, 421]).toContain((await request(port, PREVIEW_PING_PATH, { host })).status);
|
||||
}
|
||||
// the right name: served, readable by the opaque frame, the key never sent on as a Referer
|
||||
const ok = await request(port, "/", { host: hostOf(a.proxyOrigin), origin: "null" });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.body).toBe("DEV-SECRET");
|
||||
expect(ok.headers["access-control-allow-origin"]).toBe("null");
|
||||
expect(ok.headers["referrer-policy"]).toBe("no-referrer");
|
||||
const ping = await request(port, PREVIEW_PING_PATH, { host: hostOf(a.proxyOrigin), origin: "null" });
|
||||
expect(ping.status).toBe(200);
|
||||
expect(ping.body).toBe(a.nonce);
|
||||
expect(ping.body).not.toBe("ok");
|
||||
expect(ping.headers["access-control-allow-origin"]).toBe("null");
|
||||
expect(a.nonce).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(a.canaryOrigin).toMatch(/^http:\/\/acprobe[0-9a-f]{32}\.localhost:\d+$/);
|
||||
expect(a.canaryNonce).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(a.canaryNonce).not.toBe(a.nonce);
|
||||
const canary = await request(port, PREVIEW_PING_PATH, { host: hostOf(a.canaryOrigin), origin: "null" });
|
||||
expect([canary.status, canary.body]).toEqual([200, a.canaryNonce]);
|
||||
// canary is ping-only
|
||||
expect((await request(port, "/", { host: hostOf(a.canaryOrigin), origin: "null" })).status).toBe(403);
|
||||
expect(WEB_PING).toBe(PREVIEW_PING_PATH);
|
||||
// the name is case-insensitive like any host name; the proxy's own origin is accepted, another is not
|
||||
expect((await request(port, "/", { host: hostOf(a.proxyOrigin).toUpperCase() })).status).toBe(200);
|
||||
expect((await request(port, "/", { host: hostOf(a.proxyOrigin), origin: a.proxyOrigin })).status).toBe(200);
|
||||
expect((await request(port, "/", { host: hostOf(a.proxyOrigin), origin: `http://127.0.0.1:${port}` })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("a refused WebSocket upgrade never reaches the dev server", async () => {
|
||||
let upgrades = 0;
|
||||
const up = await serve((_q, s) => s.end());
|
||||
up.server.on("upgrade", (_q, sock) => { upgrades++; sock.destroy(); });
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const r = await proxy.open(`localhost:${up.port}`);
|
||||
const port = portOf(r.proxyOrigin);
|
||||
const reply = await new Promise<string>((resolve) => {
|
||||
const s = net.connect(port, "127.0.0.1", () => s.write(`GET /hmr HTTP/1.1\r\nhost: 127.0.0.1:${port}\r\nupgrade: websocket\r\nconnection: Upgrade\r\norigin: null\r\nsec-websocket-key: x\r\nsec-websocket-version: 13\r\n\r\n`));
|
||||
let got = "";
|
||||
s.on("data", (d) => { got += d; });
|
||||
s.on("close", () => resolve(got));
|
||||
});
|
||||
expect(reply).toContain("403");
|
||||
expect(upgrades).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Magpie's gateway is never previewed (#582 finding 2)", () => {
|
||||
let dir = "";
|
||||
afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; });
|
||||
|
||||
it("reads the gateway port from Magpie's settings.json (XDG, ~/.config, portable, plugin-work)", () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac582-"));
|
||||
const home = join(dir, "home");
|
||||
const xdg = join(dir, "xdg");
|
||||
const portable = join(dir, "Magpie", "data");
|
||||
for (const [d, port] of [[join(home, ".config", "magpie"), 3561], [join(xdg, "magpie"), 3562], [portable, 3563]] as const) {
|
||||
mkdirSync(d, { recursive: true });
|
||||
writeFileSync(join(d, "settings.json"), JSON.stringify({ theme: "dark", port }));
|
||||
}
|
||||
const self = join(portable, "plugins", "node_modules", "@magpie-community", "page-agent-console", "daemon", "dist", "main.js");
|
||||
const dirs = magpieConfigDirs({ HOME: home, XDG_CONFIG_HOME: xdg }, { self, cwd: join(portable, "plugin-work"), platform: "linux" });
|
||||
expect(dirs).toEqual([portable, join(xdg, "magpie"), join(home, ".config", "magpie")]);
|
||||
const denied = previewDeniedPorts({ port: 41000 }, {}, { configDirs: dirs });
|
||||
for (const p of [3561, 3562, 3563, 3425, 3430, 3488, 41000]) expect(deniedPort(p, denied), String(p)).toBe(true);
|
||||
expect(deniedPort(5173, denied)).toBe(false);
|
||||
// Windows: the home folder is USERPROFILE; paths with backslashes
|
||||
expect(magpieConfigDirs({ USERPROFILE: "C:\\Users\\me" }, { self: "", cwd: "", platform: "win32" })).toEqual(process.platform === "win32" ? ["C:\\Users\\me\\.config\\magpie"] : []);
|
||||
expect(magpieDirFromInstall("C:\\Magpie\\data\\plugins\\node_modules\\@magpie-community\\page-agent-console\\daemon\\dist\\main.js")).toBe("C:\\Magpie\\data");
|
||||
expect(magpieDirFromInstall("/opt/x/main.js")).toBeNull();
|
||||
});
|
||||
|
||||
it("settings.json without a port (or a bad one) means the default; unreadable means nothing", () => {
|
||||
const read = (body: string) => () => body;
|
||||
expect(savedGatewayPort("x", read("{}"))).toBe(3425);
|
||||
expect(savedGatewayPort("x", read('{"port":0}'))).toBe(3425);
|
||||
expect(savedGatewayPort("x", read('{"port":80}'))).toBe(3425);
|
||||
expect(savedGatewayPort("x", read('{"port":3561}'))).toBe(3561);
|
||||
expect(savedGatewayPort("x", read("garbled"))).toBeNull();
|
||||
expect(savedGatewayPort("x", () => { throw new Error("ENOENT"); })).toBeNull();
|
||||
// read again on every open: a port changed in Settings while the daemon runs is denied at once
|
||||
let body = '{"port":3561}';
|
||||
const opts = { configDirs: ["/m"], read: () => body };
|
||||
expect(previewDeniedPorts({ port: 1 }, {}, opts)).toContain(3561);
|
||||
body = '{"port":3999}';
|
||||
expect(previewDeniedPorts({ port: 1 }, {}, opts)).toContain(3999);
|
||||
});
|
||||
|
||||
it("refuses a target that answers GET / like the gateway, on any port (open and later)", async () => {
|
||||
const gw = await serve((req, s) => {
|
||||
if (req.url === "/") { s.writeHead(200, { "content-type": "application/json" }); s.end(MAGPIE_INDEX); return; }
|
||||
s.writeHead(200, { "content-type": "application/json" }); s.end('{"data":[],"object":"list"}');
|
||||
});
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
await expect(proxy.open(`localhost:${gw.port}/v1/models`)).rejects.toMatchObject({ code: "denied_port" });
|
||||
expect(proxy.size).toBe(0);
|
||||
|
||||
// a dev server that is later replaced by the gateway on the same port: refused once it is asked again
|
||||
let magpie = false;
|
||||
let now = 1_000_000;
|
||||
const dev = await serve((req, s) => {
|
||||
if (magpie && req.url === "/") { s.writeHead(200, { "content-type": "application/json" }); s.end(MAGPIE_INDEX); return; }
|
||||
s.writeHead(200, { "content-type": magpie ? "application/json" : "text/plain" }); s.end(magpie ? '{"data":[]}' : "dev");
|
||||
});
|
||||
const p2 = new PreviewProxy({ deniedPorts: () => [], now: () => now });
|
||||
cleanup.push(() => p2.closeAll());
|
||||
const r = await p2.open(`localhost:${dev.port}`);
|
||||
const port = portOf(r.proxyOrigin);
|
||||
expect((await request(port, "/v1/models", { host: hostOf(r.proxyOrigin) })).body).toBe("dev");
|
||||
magpie = true;
|
||||
now += 61_000;
|
||||
const refused = await request(port, "/v1/models", { host: hostOf(r.proxyOrigin), origin: "null" });
|
||||
expect(refused.status).toBe(403);
|
||||
expect(refused.body).not.toContain("data");
|
||||
expect(refused.headers["access-control-allow-origin"]).toBeUndefined();
|
||||
// and stays refused
|
||||
magpie = false;
|
||||
expect((await request(port, "/", { host: hostOf(r.proxyOrigin) })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("refuses any reply that carries X-Magpie-* headers", async () => {
|
||||
const gw = await serve((req, s) => {
|
||||
if (req.url === "/") { s.end("hello"); return; } // index not recognisable
|
||||
s.writeHead(200, { "content-type": "application/json", "x-magpie-provider": "deepseek" }); s.end('{"secret":1}');
|
||||
});
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const r = await proxy.open(`localhost:${gw.port}`);
|
||||
const port = portOf(r.proxyOrigin);
|
||||
const res = await request(port, "/v1/chat/completions", { host: hostOf(r.proxyOrigin) });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body).not.toContain("secret");
|
||||
expect((await request(port, "/", { host: hostOf(r.proxyOrigin) })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("fails closed when the target doesn't answer the identity check in time", async () => {
|
||||
const hang = net.createServer((s) => { s.on("error", () => {}); /* accepts, never answers */ });
|
||||
await new Promise<void>((r) => hang.listen(0, "127.0.0.1", () => r()));
|
||||
cleanup.push(() => hang.close());
|
||||
const hp = (hang.address() as net.AddressInfo).port;
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [], identityTimeoutMs: 300 });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const r = await proxy.open(`localhost:${hp}`);
|
||||
const res = await request(portOf(r.proxyOrigin), "/", { host: hostOf(r.proxyOrigin) });
|
||||
expect(res.status).toBe(502); // the "not responding" page; nothing was forwarded
|
||||
});
|
||||
|
||||
it("recognises the gateway's index and headers only", async () => {
|
||||
expect(magpieIndex(MAGPIE_INDEX)).toBe(true);
|
||||
expect(magpieIndex('{"name":"magpie"}')).toBe(false);
|
||||
expect(magpieIndex('{"name":"my-app","apis":[]}')).toBe(false);
|
||||
expect(magpieIndex("<html>")).toBe(false);
|
||||
expect(looksLikeMagpie({ "X-Magpie-Provider": "x" } as never)).toBe(true);
|
||||
expect(looksLikeMagpie({ "content-type": "text/html" })).toBe(false);
|
||||
const c = checkPreviewUrl("localhost:1");
|
||||
if (!c.ok) throw new Error("x");
|
||||
expect(await identify(c.target, ["127.0.0.1"], 500)).toBe("none");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("preview ping nonce + canary (#582 WebKit DNS)", () => {
|
||||
it("rotates nonces on every open; ping never answers a generic ok", async () => {
|
||||
const up = await serve((_q, s) => s.end("dev"));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const a = await proxy.open(`localhost:${up.port}`);
|
||||
const b = await proxy.open(`localhost:${up.port}/again`);
|
||||
expect(a.proxyOrigin).toBe(b.proxyOrigin);
|
||||
expect(b.nonce).not.toBe(a.nonce);
|
||||
expect(b.canaryNonce).not.toBe(a.canaryNonce);
|
||||
expect(b.canaryOrigin).not.toBe(a.canaryOrigin);
|
||||
const port = portOf(a.proxyOrigin);
|
||||
// old nonce is gone; retired canary Host is unknown → 421 (not a bare loopback address)
|
||||
expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(a.proxyOrigin) })).body).toBe(b.nonce);
|
||||
expect([403, 421]).toContain((await request(port, PREVIEW_PING_PATH, { host: hostOf(a.canaryOrigin) })).status);
|
||||
expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(b.canaryOrigin) })).body).toBe(b.canaryNonce);
|
||||
});
|
||||
|
||||
it("a non-proxy server that answers 200 ok fails canReachProxy; navigate releases the listener", async () => {
|
||||
const up = await serve((_q, s) => s.end("DEV-SECRET"));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
const opened = await proxy.open(`localhost:${up.port}/`);
|
||||
expect(proxy.size).toBe(1);
|
||||
|
||||
// Real proxy ping body (Host header, connect to 127.0.0.1) — must be the nonce, never "ok"
|
||||
const port = portOf(opened.proxyOrigin);
|
||||
expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(opened.proxyOrigin) })).body).toBe(opened.nonce);
|
||||
expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(opened.canaryOrigin) })).body).toBe(opened.canaryNonce);
|
||||
|
||||
// Attacker DNS: answers with plain 200 "ok" (what canReachProxy used to accept). Fetch via 127.0.0.1
|
||||
// so the test does not depend on this machine's *.localhost resolver.
|
||||
const fake = await serve((_q, s) => {
|
||||
s.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "null" });
|
||||
s.end("ok");
|
||||
});
|
||||
const good = await serve((_q, s) => {
|
||||
s.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "null" });
|
||||
s.end(opened.nonce);
|
||||
});
|
||||
expect(await canReachProxy(`http://127.0.0.1:${fake.port}`, opened.nonce)).toBe(false);
|
||||
expect(await canReachProxy(`http://127.0.0.1:${good.port}`, "ok")).toBe(false);
|
||||
expect(await canReachProxy(`http://127.0.0.1:${good.port}`, opened.nonce)).toBe(true);
|
||||
expect(await confirmPreviewReachable({
|
||||
proxyOrigin: `http://127.0.0.1:${fake.port}`,
|
||||
proxyHref: `http://127.0.0.1:${fake.port}/`,
|
||||
url: opened.url,
|
||||
nonce: opened.nonce,
|
||||
canaryOrigin: `http://127.0.0.1:${fake.port}`,
|
||||
canaryNonce: opened.canaryNonce,
|
||||
})).toBe(false);
|
||||
|
||||
// Panel path: preview.open returns real listener, but fetch is hijacked to the fake server → must release
|
||||
const released: string[] = [];
|
||||
const prevFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
const u = new URL(url);
|
||||
// rewrite any *.localhost lookup → fake server (simulates hostile DNS answering the lookup)
|
||||
return prevFetch(`http://127.0.0.1:${fake.port}${u.pathname}${u.search}`, {
|
||||
cache: "no-store",
|
||||
credentials: "omit",
|
||||
referrerPolicy: "no-referrer",
|
||||
});
|
||||
}) as typeof fetch;
|
||||
cleanup.push(() => { globalThis.fetch = prevFetch; });
|
||||
|
||||
usePreview.setState({ byThread: {} });
|
||||
const call = async (m: string, p?: unknown) => {
|
||||
if (m === "preview.open") {
|
||||
return {
|
||||
proxyOrigin: opened.proxyOrigin,
|
||||
proxyHref: opened.proxyHref,
|
||||
url: opened.url,
|
||||
nonce: opened.nonce,
|
||||
canaryOrigin: opened.canaryOrigin,
|
||||
canaryNonce: opened.canaryNonce,
|
||||
};
|
||||
}
|
||||
if (m === "preview.release") {
|
||||
const url = String((p as { url?: string } | undefined)?.url ?? "");
|
||||
released.push(url);
|
||||
proxy.release(url);
|
||||
return { ok: true };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
const ok = await usePreview.getState().navigate(call, "t1", null, `http://localhost:${up.port}/`, { push: true });
|
||||
expect(ok).toBe(false);
|
||||
expect(released).toEqual([`http://localhost:${up.port}`]);
|
||||
expect(proxy.size).toBe(0);
|
||||
const entry = usePreview.getState().byThread["t1"];
|
||||
expect(entry?.proxyHref).toBeNull();
|
||||
expect(entry?.error).toBeTruthy();
|
||||
// real ping would have worked; the failure was the fake answer
|
||||
expect(entry?.error?.length ?? 0).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
// #582 third review: Apple froze the UA at "Mac OS X 10_15_7", so the macOS version comes from the daemon
|
||||
// (os.platform() + os.release(), Darwin 25 = macOS 26) via preview.open, never from the UA.
|
||||
describe("Apple WebKit + daemon Darwin version (#582 frozen UA)", () => {
|
||||
// Literal UAs Apple WebKit sends on every macOS, 26+ included (a plain WKWebView on macOS 27.2, and Safari)
|
||||
const WKWEBVIEW_FROZEN = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
|
||||
const SAFARI_FROZEN = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15";
|
||||
const IPAD_SAFARI = "Mozilla/5.0 (iPad; CPU OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Mobile/15E148 Safari/604.1";
|
||||
const CHROME_MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
const EDGE_WIN = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0";
|
||||
const WEBKITGTK = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15";
|
||||
|
||||
const macos26 = previewHost("darwin", "25.0.0");
|
||||
const macos27 = previewHost("darwin", "26.2.0");
|
||||
const macos15 = previewHost("darwin", "24.6.0");
|
||||
const macos12 = previewHost("darwin", "21.6.0");
|
||||
const linux = previewHost("linux", "6.8.0-45-generic");
|
||||
const win = previewHost("win32", "10.0.26100");
|
||||
|
||||
it("the daemon reads the Darwin major from os.release()", () => {
|
||||
expect(macos26).toEqual({ platform: "darwin", darwinMajor: 25 });
|
||||
expect(macos27).toEqual({ platform: "darwin", darwinMajor: 26 });
|
||||
expect(macos15).toEqual({ platform: "darwin", darwinMajor: 24 });
|
||||
expect(linux).toEqual({ platform: "linux", darwinMajor: null });
|
||||
expect(win).toEqual({ platform: "win32", darwinMajor: null });
|
||||
expect(previewHost("darwin", "")).toEqual({ platform: "darwin", darwinMajor: null });
|
||||
expect(previewHost("darwin", "garbage")).toEqual({ platform: "darwin", darwinMajor: null });
|
||||
expect(DARWIN_LOCALHOST_LOOPBACK).toBe(WEB_DARWIN_LOCALHOST_LOOPBACK);
|
||||
// default arguments = this host
|
||||
const here = previewHost();
|
||||
expect(here.platform).toBe(osPlatform());
|
||||
if (here.platform === "darwin") expect(here.darwinMajor).toBe(Number(osRelease().split(".")[0]));
|
||||
else expect(here.darwinMajor).toBeNull();
|
||||
});
|
||||
|
||||
it("the frozen 10_15_7 UA on a macOS 26+ host is safe; on Darwin 24 or an unknown host it is refused", () => {
|
||||
for (const ua of [WKWEBVIEW_FROZEN, SAFARI_FROZEN, IPAD_SAFARI]) {
|
||||
expect(isAppleWebKit(ua)).toBe(true);
|
||||
expect(isUnsafeLocalhostResolver(macos26, ua)).toBe(false);
|
||||
expect(isUnsafeLocalhostResolver(macos27, ua)).toBe(false);
|
||||
expect(isUnsafeLocalhostResolver(macos15, ua)).toBe(true);
|
||||
expect(isUnsafeLocalhostResolver(macos12, ua)).toBe(true);
|
||||
// missing / unparseable daemon info fails closed
|
||||
expect(isUnsafeLocalhostResolver(undefined, ua)).toBe(true);
|
||||
expect(isUnsafeLocalhostResolver(null, ua)).toBe(true);
|
||||
expect(isUnsafeLocalhostResolver({ platform: "darwin", darwinMajor: null }, ua)).toBe(true);
|
||||
expect(isUnsafeLocalhostResolver({ platform: "", darwinMajor: null }, ua)).toBe(true);
|
||||
// non-darwin daemon hosts are left to the canary + nonce probe
|
||||
expect(isUnsafeLocalhostResolver(linux, ua)).toBe(false);
|
||||
expect(isUnsafeLocalhostResolver(win, ua)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("Chromium / Edge / WebKitGTK are never refused, whatever the host", () => {
|
||||
for (const ua of [CHROME_MAC, EDGE_WIN, WEBKITGTK]) {
|
||||
expect(isAppleWebKit(ua)).toBe(false);
|
||||
for (const h of [macos12, macos15, macos26, linux, win, null]) expect(isUnsafeLocalhostResolver(h, ua)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Panel path against a real listener. fetch is routed to 127.0.0.1:<port> with the name's Host header, so the test
|
||||
// doesn't depend on this machine's *.localhost resolver.
|
||||
async function panel(ua: string, host: unknown) {
|
||||
const up = await serve((_q, s) => s.end("DEV"));
|
||||
const proxy = new PreviewProxy({ deniedPorts: () => [] });
|
||||
cleanup.push(() => proxy.closeAll());
|
||||
vi.stubGlobal("navigator", { userAgent: ua });
|
||||
cleanup.push(() => vi.unstubAllGlobals());
|
||||
const pinged: string[] = [];
|
||||
const prevFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
||||
const u = new URL(String(input));
|
||||
pinged.push(u.hostname);
|
||||
const r = await request(Number(u.port), u.pathname + u.search, { host: u.host });
|
||||
return new Response(r.body, { status: r.status });
|
||||
}) as typeof fetch;
|
||||
cleanup.push(() => { globalThis.fetch = prevFetch; });
|
||||
const calls: string[] = [];
|
||||
const released: string[] = [];
|
||||
const call = async (m: string, p?: unknown) => {
|
||||
calls.push(m);
|
||||
if (m === "preview.open") {
|
||||
const opened = await proxy.open(String((p as { url: string }).url));
|
||||
return host === undefined ? opened : { ...opened, host };
|
||||
}
|
||||
if (m === "preview.release") {
|
||||
const url = String((p as { url?: string } | undefined)?.url ?? "");
|
||||
released.push(url);
|
||||
proxy.release(url);
|
||||
return { ok: true };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
usePreview.setState({ byThread: {} });
|
||||
const ok = await usePreview.getState().navigate(call, "mac", null, `http://localhost:${up.port}/`, { push: true });
|
||||
return { ok, calls, released, pinged, proxy, up, entry: usePreview.getState().byThread["mac"] };
|
||||
}
|
||||
|
||||
it("Magpie's Mac app (frozen WKWebView UA) on a macOS 26 host (Darwin 25.x) opens the preview", async () => {
|
||||
const r = await panel(WKWEBVIEW_FROZEN, previewHost("darwin", "25.0.0"));
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.calls).toEqual(["preview.open"]);
|
||||
expect(r.released).toEqual([]);
|
||||
expect(r.proxy.size).toBe(1);
|
||||
expect(r.entry?.error).toBeNull();
|
||||
expect(r.entry?.proxyHref).toMatch(/^http:\/\/ac[0-9a-f]+\.localhost:\d+\/$/);
|
||||
// canary first, then the keyed name
|
||||
expect(r.pinged).toHaveLength(2);
|
||||
expect(r.pinged[0]).toMatch(/^acprobe[0-9a-f]+\.localhost$/);
|
||||
expect(r.pinged[1]).toBe(new URL(r.entry!.proxyHref!).hostname);
|
||||
});
|
||||
|
||||
it("Safari (frozen UA) with magpie web on a macOS 27 host opens the preview", async () => {
|
||||
const r = await panel(SAFARI_FROZEN, previewHost("darwin", "26.2.0"));
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.entry?.proxyHref).toBeTruthy();
|
||||
expect(r.released).toEqual([]);
|
||||
});
|
||||
|
||||
it("Apple WebKit on a Darwin 24.x host (macOS 15) is refused: no *.localhost lookup, listener released", async () => {
|
||||
const r = await panel(WKWEBVIEW_FROZEN, previewHost("darwin", "24.6.0"));
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.pinged).toEqual([]);
|
||||
expect(r.released).toEqual([`http://localhost:${r.up.port}`]);
|
||||
expect(r.proxy.size).toBe(0);
|
||||
expect(r.entry?.proxyHref).toBeNull();
|
||||
expect(r.entry?.error).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Apple WebKit with no host info from the daemon fails closed the same way", async () => {
|
||||
const r = await panel(SAFARI_FROZEN, undefined);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.pinged).toEqual([]);
|
||||
expect(r.proxy.size).toBe(0);
|
||||
});
|
||||
|
||||
it("a non-darwin daemon host is unaffected (frozen Safari UA and Chromium both open)", async () => {
|
||||
const a = await panel(SAFARI_FROZEN, previewHost("linux", "6.8.0"));
|
||||
expect(a.ok).toBe(true);
|
||||
expect(a.released).toEqual([]);
|
||||
const b = await panel(EDGE_WIN, previewHost("win32", "10.0.26100"));
|
||||
expect(b.ok).toBe(true);
|
||||
expect(b.released).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
// WS gateway tests: hello authentication, app.info, wrong token 4401, subscription push
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
||||
import http from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { Server } from "node:http";
|
||||
@@ -16,6 +17,8 @@ import { registerMethods } from "../../daemon/src/ws/methods.js";
|
||||
import { GitService } from "../../daemon/src/git/service.js";
|
||||
import { FileService } from "../../daemon/src/files/service.js";
|
||||
import { TerminalService } from "../../daemon/src/terminal/service.js";
|
||||
import { PreviewProxy } from "../../daemon/src/preview/proxy.js";
|
||||
import { previewHost } from "../../daemon/src/preview/host.js";
|
||||
import type { Config } from "../../daemon/src/config.js";
|
||||
|
||||
const TOKEN = "testtoken123";
|
||||
@@ -23,6 +26,7 @@ let dir = "";
|
||||
let server: Server;
|
||||
let port = 0;
|
||||
let gateway: Gateway;
|
||||
let preview: PreviewProxy;
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-ws-"));
|
||||
@@ -32,7 +36,8 @@ beforeAll(async () => {
|
||||
const cfg: Config = { port: 0, dataDir: dir, token: TOKEN, version: "9.9.9", idleExitMinutes: 60, buildStamp: "0" };
|
||||
gateway = new Gateway(cfg);
|
||||
const settings = new SettingsStore(dir);
|
||||
registerMethods(gateway, { cfg, settings, gateway, projects: new ProjectsStore(dir), threads: new ThreadsStore(dir), git: new GitService(), files: new FileService(), terminals: new TerminalService(gateway) });
|
||||
preview = new PreviewProxy({ deniedPorts: () => [] });
|
||||
registerMethods(gateway, { cfg, settings, gateway, projects: new ProjectsStore(dir), threads: new ThreadsStore(dir), git: new GitService(), files: new FileService(), terminals: new TerminalService(gateway), preview });
|
||||
server = createHttpServer(cfg, appDir, new AttachmentStore(join(dir, "attachments")), {
|
||||
onUpgrade: (req, socket, head) => gateway.handleUpgrade(req, socket, head),
|
||||
});
|
||||
@@ -42,6 +47,7 @@ beforeAll(async () => {
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
preview.closeAll();
|
||||
gateway.closeAll();
|
||||
server.close();
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
@@ -124,4 +130,31 @@ describe("ws gateway", () => {
|
||||
expect(e.ch).toBe("sidebar");
|
||||
ws.close();
|
||||
});
|
||||
|
||||
// #582 review: methods.ts rewrites host via previewHost(); bare `return r;` must make this red
|
||||
it("preview.open returns host from previewHost()", async () => {
|
||||
const up = http.createServer((_q, s) => { s.end("dev"); });
|
||||
await new Promise<void>((r) => up.listen(0, "127.0.0.1", () => r()));
|
||||
const upPort = (up.address() as AddressInfo).port;
|
||||
try {
|
||||
const ws = await connect();
|
||||
const hello = nextMsg(ws, (o) => o.t === "hello.ok");
|
||||
ws.send(JSON.stringify({ t: "hello", token: TOKEN }));
|
||||
await hello;
|
||||
const res = nextMsg(ws, (o) => o.t === "res" && o.id === 30);
|
||||
ws.send(JSON.stringify({ t: "req", id: 30, m: "preview.open", p: { url: `http://localhost:${upPort}/` } }));
|
||||
const r = await res;
|
||||
expect(r.ok).toBe(true);
|
||||
const body = r.r as { host?: unknown; proxyOrigin?: string };
|
||||
expect(body.host).toEqual(previewHost());
|
||||
if (body.proxyOrigin) {
|
||||
const rel = nextMsg(ws, (o) => o.t === "res" && o.id === 31);
|
||||
ws.send(JSON.stringify({ t: "req", id: 31, m: "preview.release", p: { url: `http://localhost:${upPort}/` } }));
|
||||
await rel;
|
||||
}
|
||||
ws.close();
|
||||
} finally {
|
||||
up.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,6 +21,11 @@ export class WsClient {
|
||||
|
||||
constructor(private token: string, private lang = "zh") {}
|
||||
|
||||
/** Language sent in the next hello (reconnects) */
|
||||
setLang(lang: string): void {
|
||||
this.lang = lang;
|
||||
}
|
||||
|
||||
onState(fn: (s: ConnState) => void): () => void {
|
||||
this.stateListeners.add(fn);
|
||||
fn(this.state);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Composer } from "./Composer";
|
||||
import { Icon } from "./Icons";
|
||||
import { ws } from "../main";
|
||||
import { toast } from "./Toast";
|
||||
import { relFromAbs } from "../composer/mentions";
|
||||
import { useLiveSettings } from "./Settings";
|
||||
import { errMsg, localizeDaemonMessage, t as tr, tf } from "../i18n/index.js";
|
||||
|
||||
@@ -82,9 +83,14 @@ export function Chat() {
|
||||
setHasNew(false);
|
||||
};
|
||||
|
||||
const resend = (text: string) => {
|
||||
const resend = (text: string, mentions?: { path: string; isDir: boolean }[]) => {
|
||||
if (!activeThreadId) return;
|
||||
void ws.call("thread.send", { id: activeThreadId, text });
|
||||
// chips go along again (as project-relative paths; the daemon re-checks them)
|
||||
const root = project?.path;
|
||||
const rels = root && mentions?.length
|
||||
? mentions.map((m) => ({ rel: relFromAbs(root, m.path), isDir: m.isDir })).filter((m): m is { rel: string; isDir: boolean } => !!m.rel)
|
||||
: [];
|
||||
void ws.call("thread.send", { id: activeThreadId, text, ...(rels.length ? { mentions: rels } : {}) });
|
||||
};
|
||||
const retryLast = () => {
|
||||
if (tl.lastUserText) resend(tl.lastUserText);
|
||||
|
||||
@@ -8,7 +8,8 @@ import { useTimeline } from "../stores/timeline";
|
||||
import { ws } from "../main";
|
||||
import { getToken } from "../api/token";
|
||||
import { Icon } from "./Icons";
|
||||
import { attachmentUrl } from "./Timeline";
|
||||
import { attachmentUrl, MentionChip } from "./Timeline";
|
||||
import { MENTION_MIME, addMention, joinProjectPath, mentionsForSend, parseMentionDrag, type MentionDraft } from "../composer/mentions";
|
||||
import type { Mode, ModelInfo } from "../types/models";
|
||||
import type { SlashCommand } from "../composer/slashMenu";
|
||||
import { toast } from "./Toast";
|
||||
@@ -34,10 +35,12 @@ const MODEL_LIST_CAP = 150;
|
||||
|
||||
export function Composer() {
|
||||
const ui = useUi();
|
||||
const { threads, providers } = useData();
|
||||
const { threads, providers, projects } = useData();
|
||||
const tl = useTimeline();
|
||||
const [text, setText] = useState("");
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [mentions, setMentions] = useState<MentionDraft[]>([]);
|
||||
const [dropHint, setDropHint] = useState(false);
|
||||
const [agentPop, setAgentPop] = useState(false);
|
||||
const [pickerProviderId, setPickerProviderId] = useState<string | null>(null);
|
||||
const [modelQ, setModelQ] = useState("");
|
||||
@@ -173,22 +176,26 @@ export function Composer() {
|
||||
const ta = taRef.current;
|
||||
if (!ta) return;
|
||||
ta.style.height = "auto";
|
||||
ta.style.height = Math.min(ta.scrollHeight, 12 * 22) + "px";
|
||||
// 12 lines at the current chat font size (line-height follows --chat-fs)
|
||||
const lh = parseFloat(getComputedStyle(ta).lineHeight) || 22;
|
||||
ta.style.height = Math.min(ta.scrollHeight, Math.round(12 * lh)) + "px";
|
||||
}, [text]);
|
||||
|
||||
const send = useCallback(async (behavior: "queue" | "steer" = "queue") => {
|
||||
const id = ui.currentThreadId;
|
||||
const msg = text.trim();
|
||||
if (!id || (!msg && attachments.length === 0)) return;
|
||||
if (!id || (!msg && attachments.length === 0 && mentions.length === 0)) return;
|
||||
if (running && behavior === "queue") setLastSent((s) => [...s, msg]);
|
||||
setText("");
|
||||
try {
|
||||
const r = (await ws.call("thread.send", {
|
||||
id, text: msg,
|
||||
attachments: attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })),
|
||||
...(mentions.length ? { mentions: mentionsForSend(mentions) } : {}),
|
||||
behavior: running && behavior === "steer" && steerOk ? "steer" : "queue",
|
||||
})) as { delivered?: "started" | "steered" | "queued" } | undefined;
|
||||
setAttachments([]);
|
||||
setMentions([]);
|
||||
// Say what really happened to a message sent mid-turn (B7: agents without steer queue it)
|
||||
if (r?.delivered === "queued" && running) toast(tr("composer.queuedToast"));
|
||||
else if (r?.delivered === "steered") toast(tr("composer.steeredToast"));
|
||||
@@ -197,7 +204,7 @@ export function Composer() {
|
||||
setText(msg);
|
||||
toast(tr("composer.failSend") + errMsg(e), true);
|
||||
}
|
||||
}, [text, attachments, ui.currentThreadId, running, steerOk]);
|
||||
}, [text, attachments, mentions, ui.currentThreadId, running, steerOk]);
|
||||
|
||||
const onKey = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isImeComposing(e.nativeEvent)) return;
|
||||
@@ -291,8 +298,33 @@ export function Composer() {
|
||||
}
|
||||
};
|
||||
|
||||
const project = projects.find((p) => p.id === thread?.projectId) ?? null;
|
||||
const takeMention = (m: MentionDraft | null) => {
|
||||
if (!m) return;
|
||||
if (!thread || m.projectId !== thread.projectId) {
|
||||
toast(tr("mention.otherProject"), true);
|
||||
return;
|
||||
}
|
||||
setMentions((list) => addMention(list, m));
|
||||
taRef.current?.focus();
|
||||
};
|
||||
// Files panel → context menu "Add to chat"
|
||||
useEffect(() => {
|
||||
const on = (e: Event) => takeMention((e as CustomEvent).detail as MentionDraft);
|
||||
window.addEventListener("ac-insert-mention", on);
|
||||
return () => window.removeEventListener("ac-insert-mention", on);
|
||||
});
|
||||
// A new conversation starts with no chips
|
||||
useEffect(() => { setMentions([]); }, [ui.currentThreadId]);
|
||||
|
||||
const onDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setDropHint(false);
|
||||
// A row from our Files panel: a path chip, not an upload. Files from the OS file manager keep the old behaviour.
|
||||
if (e.dataTransfer.types.includes(MENTION_MIME)) {
|
||||
takeMention(parseMentionDrag(e.dataTransfer.getData(MENTION_MIME)));
|
||||
return;
|
||||
}
|
||||
for (const f of e.dataTransfer.files) {
|
||||
if (f.type.startsWith("image/") || f.type.startsWith("text/")) await upload(f);
|
||||
}
|
||||
@@ -339,7 +371,14 @@ export function Composer() {
|
||||
if (!ui.currentThreadId) return null;
|
||||
|
||||
return (
|
||||
<div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop} onDragOver={(e) => e.preventDefault()}>
|
||||
<div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
const ours = e.dataTransfer.types.includes(MENTION_MIME);
|
||||
if (ours) e.dataTransfer.dropEffect = "copy";
|
||||
if (ours !== dropHint) setDropHint(ours);
|
||||
}}
|
||||
onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropHint(false); }}>
|
||||
{/* queue list */}
|
||||
{tl.queue.length > 0 && (
|
||||
<div className="q-list">
|
||||
@@ -356,12 +395,17 @@ export function Composer() {
|
||||
{mode === "bypassPermissions" && (
|
||||
<div className="cp-danger">{tr("composer.bypassWarn")}</div>
|
||||
)}
|
||||
<div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}`}>
|
||||
<div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}${dropHint ? " drop-on" : ""}`}>
|
||||
{dropHint && <div className="cp-drop-hint">{tr("mention.drop")}</div>}
|
||||
{imagesByPath && attachments.some((a) => a.mime.startsWith("image/")) && (
|
||||
<div className="att-note">{tf("composer.imagesByPath", { agent: provider?.name ?? "" })}</div>
|
||||
)}
|
||||
{attachments.length > 0 && (
|
||||
{(attachments.length > 0 || mentions.length > 0) && (
|
||||
<div className="att-bar">
|
||||
{mentions.map((m) => (
|
||||
<MentionChip key={m.rel} path={project ? joinProjectPath(project.path, m.rel) : m.rel} isDir={m.isDir}
|
||||
onRemove={() => setMentions((list) => list.filter((x) => x !== m))} />
|
||||
))}
|
||||
{attachments.map((a, i) => (
|
||||
<span key={i} className={`att${a.uploading ? " up" : ""}`}>
|
||||
{a.mime.startsWith("image/") && a.path
|
||||
@@ -640,7 +684,7 @@ export function Composer() {
|
||||
{running ? (
|
||||
<>
|
||||
<span className="cp-clock">{elapsed}s</span>
|
||||
{(text.trim() || attachments.length > 0) && (
|
||||
{(text.trim() || attachments.length > 0 || mentions.length > 0) && (
|
||||
<button className="cp-send" title={tr(steerOk && prefs.runningSend === "steer" ? "settings.steer" : "settings.queue")}
|
||||
disabled={waiting || attachments.some((a) => a.uploading)}
|
||||
onClick={() => void send(prefs.runningSend === "steer" && steerOk ? "steer" : "queue")}>
|
||||
@@ -652,7 +696,7 @@ export function Composer() {
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0) || attachments.some((a) => a.uploading)}
|
||||
<button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0 && mentions.length === 0) || attachments.some((a) => a.uploading)}
|
||||
onClick={() => void send("queue")}>
|
||||
<Icon name="arrowUp" />
|
||||
</button>
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
// Small line icons (stroke=currentColor, 1.6px); no third-party icon pack, keeps the bundle small.
|
||||
const PATHS: Record<string, string> = {
|
||||
plus: "M12 5v14M5 12h14",
|
||||
file: "M6 3h8l4 4v14H6zM14 3v4h4",
|
||||
arrowLeft: "M19 12H5m6-6-6 6 6 6",
|
||||
arrowRight: "M5 12h14m-6-6 6 6-6 6",
|
||||
external: "M14 4h6v6M20 4l-9 9M18 14v6H4V6h6",
|
||||
globe: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.6 3.8 5.6 3.8 9s-1.3 6.4-3.8 9c-2.5-2.6-3.8-5.6-3.8-9S9.5 5.6 12 3Z",
|
||||
panelLeft: "M4 5h16v14H4zM9.5 5v14",
|
||||
widen: "M4 12h16M8 8l-4 4 4 4M16 8l4 4-4 4",
|
||||
search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm10 17-4.5-4.5",
|
||||
caret: "M9 6l6 6-6 6",
|
||||
dots: "M5 12h.01M12 12h.01M19 12h.01",
|
||||
|
||||
@@ -104,9 +104,7 @@ export function Layout({
|
||||
const k = e.key.toLowerCase();
|
||||
if (k === "b") {
|
||||
e.preventDefault();
|
||||
const s = useUi.getState();
|
||||
if (window.matchMedia("(max-width: 759px)").matches) s.setSbOpen(!s.sbOpen);
|
||||
else s.toggleSidebarHidden();
|
||||
useUi.getState().toggleSidebar();
|
||||
} else if (k === "j") {
|
||||
e.preventDefault();
|
||||
const s = useUi.getState();
|
||||
|
||||
@@ -3,11 +3,14 @@ import { useMemo, useRef, useEffect } from "react";
|
||||
import { marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import hljs from "highlight.js/lib/common";
|
||||
import { linkifyLocal } from "../util/localLinks";
|
||||
import { onChatLinkClick } from "../preview/open";
|
||||
import { t } from "../i18n/index.js";
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
const purify = (html: string) =>
|
||||
DOMPurify.sanitize(html, { USE_PROFILES: { html: true }, ADD_ATTR: ["target", "rel"] });
|
||||
DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
return purify(marked.parse(text, { async: false }));
|
||||
@@ -17,14 +20,12 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const html = useMemo(() => renderMarkdown(text), [text]);
|
||||
|
||||
// After rendering: highlight code blocks + copy button; external links target=_blank
|
||||
// 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(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
for (const a of el.querySelectorAll("a[href^='http']")) {
|
||||
(a as HTMLAnchorElement).target = "_blank";
|
||||
(a as HTMLAnchorElement).rel = "noopener";
|
||||
}
|
||||
for (const pre of el.querySelectorAll("pre")) {
|
||||
const code = pre.querySelector("code");
|
||||
if (code && !code.dataset.hl) {
|
||||
@@ -34,20 +35,24 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea
|
||||
if (!pre.querySelector(".cb-copy")) {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "cb-copy";
|
||||
btn.textContent = "复制";
|
||||
btn.type = "button";
|
||||
btn.textContent = t("common.copy");
|
||||
btn.onclick = () => {
|
||||
const t = code?.textContent ?? "";
|
||||
void copyText(t).then(() => { btn.textContent = "已复制"; setTimeout(() => (btn.textContent = "复制"), 1200); });
|
||||
const txt = code?.textContent ?? "";
|
||||
void copyText(txt).then(() => { btn.textContent = t("common.copied"); setTimeout(() => (btn.textContent = t("common.copy")), 1200); });
|
||||
};
|
||||
pre.appendChild(btn);
|
||||
}
|
||||
}
|
||||
}, [html]);
|
||||
// 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]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`md${streaming ? " streaming" : ""}`}
|
||||
onClick={onChatLinkClick}
|
||||
dangerouslySetInnerHTML={{ __html: html }}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -10,6 +10,9 @@ import { ConfirmDialog } from "./Dialog";
|
||||
import { toast } from "./Toast";
|
||||
import { errMsg, t, tf } from "../i18n/index.js";
|
||||
import { TerminalPanel } from "./TerminalPanel";
|
||||
import { PreviewPanel } from "./PreviewPanel";
|
||||
import { Menu, type MenuItem } from "./Menu";
|
||||
import { MENTION_MIME, joinProjectPath, type MentionDraft } from "../composer/mentions";
|
||||
import { copyText } from "./Markdown";
|
||||
import hljs from "highlight.js/lib/common";
|
||||
|
||||
@@ -19,6 +22,7 @@ export function Panel() {
|
||||
{ tab: "changes", label: t("panel.changes") },
|
||||
{ tab: "files", label: t("panel.files") },
|
||||
{ tab: "terminal", label: t("panel.terminal") },
|
||||
{ tab: "preview", label: t("preview.tab") },
|
||||
];
|
||||
return (
|
||||
<>
|
||||
@@ -42,6 +46,7 @@ export function Panel() {
|
||||
{ui.panelTab === "changes" && <ChangesPanel />}
|
||||
{ui.panelTab === "files" && <FilesPanel />}
|
||||
{ui.panelTab === "terminal" && <TerminalPanel />}
|
||||
{ui.panelTab === "preview" && ui.panelOpen && <PreviewPanel />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
@@ -230,6 +235,10 @@ function ChangesPanel() {
|
||||
}
|
||||
|
||||
// ---------- files panel ----------
|
||||
/** Context menu "Add to chat": the composer listens for this */
|
||||
export function insertMention(m: MentionDraft): void {
|
||||
window.dispatchEvent(new CustomEvent("ac-insert-mention", { detail: m }));
|
||||
}
|
||||
type TreeEntry = { name: string; path: string; isDir: boolean };
|
||||
|
||||
function FilesPanel() {
|
||||
@@ -245,6 +254,7 @@ function FilesPanel() {
|
||||
const [dirs, setDirs] = useState<Record<string, TreeEntry[] | "loading" | string>>({});
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [file, setFile] = useState<{ text?: string; language?: string; binary?: boolean; tooLarge?: boolean; error?: string; loading?: boolean } | null>(null);
|
||||
const [ctx, setCtx] = useState<{ x: number; y: number; entry: TreeEntry } | null>(null);
|
||||
|
||||
const loadDir = useCallback(async (dir: string) => {
|
||||
if (!projectId) return;
|
||||
@@ -314,6 +324,17 @@ function FilesPanel() {
|
||||
style={{ paddingLeft: 8 + depth * 14 }}
|
||||
onClick={() => toggle(e)}
|
||||
title={e.path}
|
||||
draggable
|
||||
onDragStart={(ev) => {
|
||||
// 1.2: drag into the composer → a path chip; other drop targets get the absolute path as text
|
||||
ev.dataTransfer.effectAllowed = "copy";
|
||||
ev.dataTransfer.setData(MENTION_MIME, JSON.stringify({ projectId: project.id, rel: e.path, isDir: e.isDir }));
|
||||
ev.dataTransfer.setData("text/plain", joinProjectPath(project.path, e.path));
|
||||
}}
|
||||
onContextMenu={(ev) => {
|
||||
ev.preventDefault();
|
||||
setCtx({ x: ev.clientX, y: ev.clientY, entry: e });
|
||||
}}
|
||||
>
|
||||
{e.isDir ? (
|
||||
<>
|
||||
@@ -333,8 +354,18 @@ function FilesPanel() {
|
||||
));
|
||||
};
|
||||
|
||||
const ctxItems: MenuItem[] = ctx
|
||||
? [
|
||||
{ kind: "item", label: t("mention.add"), onClick: () => insertMention({ projectId: project.id, rel: ctx.entry.path, isDir: ctx.entry.isDir }) },
|
||||
{ kind: "sep" },
|
||||
{ kind: "item", label: t("common.copyPath"), onClick: () => { void copyText(joinProjectPath(project.path, ctx.entry.path)); toast(t("common.copiedPath")); } },
|
||||
{ kind: "item", label: t("mention.copyRel"), onClick: () => { void copyText(ctx.entry.path); toast(t("common.copiedPath")); } },
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<>
|
||||
{ctx && <Menu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
|
||||
<div className="ft-crumbs">
|
||||
{sel ? (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// Preview tab (1.2): a light browser for local dev URLs. The page loads through the daemon's preview proxy
|
||||
// (preview/proxy.ts): inside Magpie the frame is sandboxed and opaque, and a direct iframe of localhost breaks module scripts,
|
||||
// fetch and storage. Back/forward/reload go through the injected bridge when the page has it, else through our own URL stack.
|
||||
// Messages from the frame are only read when they come from this iframe and carry {ac_preview:1, href, title}; they only
|
||||
// update the address bar and title. The parent page's history is never touched (it is Magpie's whole window).
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { ws } from "../main";
|
||||
import { useUi, PN_MAX } from "../stores/ui";
|
||||
import { useData } from "../stores/data";
|
||||
import { usePreview, threadKey, addressText } from "../stores/preview";
|
||||
import { checkPreviewUrl, displayHref, externalHref } from "../../../daemon/src/preview/url.js";
|
||||
import { openExternal } from "../preview/open";
|
||||
import { localizeDaemonMessage, t } from "../i18n/index.js";
|
||||
import { Icon } from "./Icons";
|
||||
import { maxPanelWidth } from "../layout/bounds";
|
||||
|
||||
const call = (m: string, p?: unknown) => ws.call(m, p);
|
||||
|
||||
export function PreviewPanel() {
|
||||
const ui = useUi();
|
||||
const threads = useData((s) => s.threads);
|
||||
const threadId = ui.currentThreadId;
|
||||
const key = threadKey(threadId);
|
||||
const entry = usePreview((s) => s.byThread[key]);
|
||||
const thread = threads.find((x) => x.id === threadId) ?? null;
|
||||
const frameRef = useRef<HTMLIFrameElement>(null);
|
||||
const [addr, setAddr] = useState("");
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [bad, setBad] = useState<string | null>(null);
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Restore this conversation's last URL (or re-open the proxy after a release)
|
||||
useEffect(() => {
|
||||
const st = usePreview.getState();
|
||||
const cur = st.byThread[key];
|
||||
if (cur && cur.proxyHref) return;
|
||||
const url = cur?.url ?? thread?.previewUrl ?? null;
|
||||
if (url) void st.navigate(call, key, threadId, url, { push: false });
|
||||
}, [key, threadId, thread?.previewUrl]);
|
||||
|
||||
// Leaving the tab / the conversation: let the proxy go (it is re-opened when the tab shows this URL again)
|
||||
const origin = entry?.origin;
|
||||
const proxied = !!entry?.proxyOrigin;
|
||||
useEffect(() => {
|
||||
if (!origin || !proxied) return;
|
||||
return () => {
|
||||
// another conversation may show the same target right now: only release when none does
|
||||
const st = usePreview.getState();
|
||||
const nowKey = threadKey(useUi.getState().currentThreadId);
|
||||
const stillShown = useUi.getState().panelOpen && useUi.getState().panelTab === "preview" && st.byThread[nowKey]?.origin === origin && nowKey !== key;
|
||||
st.detach(key);
|
||||
if (!stillShown) void ws.call("preview.release", { url: origin }).catch(() => {});
|
||||
};
|
||||
}, [origin, proxied, key]);
|
||||
|
||||
// Address bar follows the page unless the user is typing
|
||||
useEffect(() => {
|
||||
if (!editing) setAddr(entry ? addressText(entry.url) : "");
|
||||
}, [entry?.url, editing]);
|
||||
|
||||
// Navigation bridge messages from our iframe only
|
||||
useEffect(() => {
|
||||
const onMsg = (e: MessageEvent) => {
|
||||
const win = frameRef.current?.contentWindow;
|
||||
if (!win || e.source !== win) return;
|
||||
const d = e.data as { ac_preview?: unknown; href?: unknown; title?: unknown };
|
||||
if (!d || typeof d !== "object" || d.ac_preview !== 1 || typeof d.href !== "string") return;
|
||||
const cur = usePreview.getState().byThread[key];
|
||||
if (!cur?.proxyOrigin) return;
|
||||
const shown = displayHref(d.href.slice(0, 2048), cur.proxyOrigin, cur.origin);
|
||||
const c = checkPreviewUrl(shown);
|
||||
if (!c.ok || c.target.origin !== cur.origin) return;
|
||||
const title = typeof d.title === "string" ? d.title.slice(0, 200) : "";
|
||||
usePreview.getState().reported(key, c.target.href, title);
|
||||
// remember in-page navigation on the conversation (debounced)
|
||||
if (threadId && c.target.href !== cur.url) {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current);
|
||||
saveTimer.current = setTimeout(() => void ws.call("threads.update", { id: threadId, previewUrl: c.target.href }).catch(() => {}), 800);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", onMsg);
|
||||
return () => window.removeEventListener("message", onMsg);
|
||||
}, [key, threadId]);
|
||||
|
||||
const go = (raw: string) => {
|
||||
const v = raw.trim();
|
||||
if (!v) return;
|
||||
const c = checkPreviewUrl(v);
|
||||
if (!c.ok) {
|
||||
setBad(v);
|
||||
return;
|
||||
}
|
||||
setBad(null);
|
||||
setEditing(false);
|
||||
void usePreview.getState().navigate(call, key, threadId, c.target.href, { push: true });
|
||||
};
|
||||
|
||||
const post = (cmd: "back" | "forward" | "reload") => {
|
||||
try { frameRef.current?.contentWindow?.postMessage({ ac_preview_cmd: cmd }, "*"); } catch {}
|
||||
};
|
||||
const back = () => {
|
||||
if (entry?.bridged) return post("back");
|
||||
const u = usePreview.getState().step(key, -1);
|
||||
if (u) void usePreview.getState().navigate(call, key, threadId, u, { push: false });
|
||||
};
|
||||
const forward = () => {
|
||||
if (entry?.bridged) return post("forward");
|
||||
const u = usePreview.getState().step(key, 1);
|
||||
if (u) void usePreview.getState().navigate(call, key, threadId, u, { push: false });
|
||||
};
|
||||
const reload = () => {
|
||||
if (!entry) return;
|
||||
if (entry.error || !entry.proxyHref) {
|
||||
void usePreview.getState().navigate(call, key, threadId, entry.url, { push: false });
|
||||
return;
|
||||
}
|
||||
if (entry.bridged) post("reload");
|
||||
else usePreview.getState().reload(key);
|
||||
};
|
||||
|
||||
const canBack = !!entry && (entry.bridged || entry.idx > 0);
|
||||
const canFwd = !!entry && (entry.bridged || entry.idx < entry.stack.length - 1);
|
||||
const external = entry ? externalHref(entry.url) : null;
|
||||
const badExternal = bad ? externalHref(/^[a-z][a-z0-9+.-]*:\/\//i.test(bad) ? bad : `https://${bad}`) : null;
|
||||
const widen = () => ui.setPanelWidth(Math.min(PN_MAX, maxPanelWidth({ ...useUi.getState(), panelOpen: true })));
|
||||
|
||||
return (
|
||||
<div className="pv">
|
||||
<div className="pv-bar">
|
||||
<button type="button" className="ibtn" title={t("preview.back")} aria-label={t("preview.back")} disabled={!canBack} onClick={back}><Icon name="arrowLeft" size={15} /></button>
|
||||
<button type="button" className="ibtn" title={t("preview.forward")} aria-label={t("preview.forward")} disabled={!canFwd} onClick={forward}><Icon name="arrowRight" size={15} /></button>
|
||||
<button type="button" className="ibtn" title={t("preview.reload")} aria-label={t("preview.reload")} disabled={!entry} onClick={reload}><Icon name="refresh" size={14} /></button>
|
||||
<input
|
||||
className={`pv-addr${bad ? " err" : ""}`}
|
||||
value={addr}
|
||||
spellCheck={false}
|
||||
placeholder={t("preview.placeholder")}
|
||||
aria-label={t("preview.address")}
|
||||
onFocus={(e) => { setEditing(true); e.currentTarget.select(); }}
|
||||
onBlur={() => { setEditing(false); }}
|
||||
onChange={(e) => { setAddr(e.target.value); if (bad) setBad(null); }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.nativeEvent.isComposing) return;
|
||||
if (e.key === "Enter") { e.preventDefault(); go(addr); }
|
||||
else if (e.key === "Escape") { setEditing(false); setBad(null); setAddr(entry ? addressText(entry.url) : ""); (e.target as HTMLInputElement).blur(); }
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="ibtn" title={t("preview.openExternal")} aria-label={t("preview.openExternal")} disabled={!external} onClick={() => external && void openExternal(external)}><Icon name="external" size={14} /></button>
|
||||
<button type="button" className="ibtn" title={t("preview.widen")} aria-label={t("preview.widen")} onClick={widen}><Icon name="widen" size={15} /></button>
|
||||
</div>
|
||||
{bad && (
|
||||
<div className="pv-note err">
|
||||
<span>{t("preview.onlyLocal")}</span>
|
||||
{badExternal && <button type="button" className="btn" onClick={() => { void openExternal(badExternal); setBad(null); }}>{t("preview.openExternal")}</button>}
|
||||
</div>
|
||||
)}
|
||||
{entry?.error && (
|
||||
<div className="pv-note err">
|
||||
<span>{t("preview.failed")}{localizeDaemonMessage(entry.error)}</span>
|
||||
{external && <button type="button" className="btn" onClick={() => void openExternal(external)}>{t("preview.openExternal")}</button>}
|
||||
<button type="button" className="btn" onClick={reload}>{t("common.retry")}</button>
|
||||
</div>
|
||||
)}
|
||||
{!entry ? (
|
||||
<div className="pv-empty">
|
||||
<div>{t("preview.empty")}</div>
|
||||
<div className="pv-hint">{t("preview.limits")}</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pv-frame-wrap">
|
||||
{entry.loading && <div className="pv-loading" />}
|
||||
{entry.proxyHref && (
|
||||
<iframe
|
||||
key={`${entry.proxyOrigin}|${entry.nonce}`}
|
||||
ref={frameRef}
|
||||
className="pv-frame"
|
||||
title={entry.title || addressText(entry.url)}
|
||||
src={entry.proxyHref}
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,11 +10,13 @@ import type { ProviderInfo } from "../types/models.js";
|
||||
import { useData } from "../stores/data.js";
|
||||
import { IDLE_MAX, IDLE_MIN, parseArgsDraft, parseIdleDraft } from "./settingsFields.js";
|
||||
import { applyTheme, embeddedInMagpie, normalizeThemeSetting } from "../layout/theme.js";
|
||||
import { applyChatLayout, normalizeChatFont, normalizeContentWidth, CHAT_FONT_MIN, CHAT_FONT_MAX, CHAT_FONT_DEFAULT } from "../layout/chatLayout.js";
|
||||
|
||||
type Settings = {
|
||||
defaultProvider?: string; defaultMode?: string;
|
||||
sendKey?: string; runningSend?: string; showThinking?: boolean;
|
||||
theme?: string; idleCloseMinutes?: number;
|
||||
contentWidth?: string; chatFontSize?: number;
|
||||
providerEnabled?: Record<string, boolean>;
|
||||
providerCommand?: Record<string, { executable?: string; args?: string[] }>;
|
||||
[k: string]: unknown;
|
||||
@@ -63,6 +65,8 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
|
||||
const next = { ...s, ...patch } as Settings;
|
||||
setS(next);
|
||||
if (patch.theme) applyTheme(patch.theme);
|
||||
const layout = patch.contentWidth !== undefined || patch.chatFontSize !== undefined;
|
||||
if (layout) applyChatLayout(next);
|
||||
try {
|
||||
await ws.call("settings.set", { patch });
|
||||
window.dispatchEvent(new CustomEvent("settings-changed", { detail: next }));
|
||||
@@ -70,6 +74,7 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
|
||||
} catch (e) {
|
||||
setS(prev);
|
||||
if (patch.theme) applyTheme(prev?.theme);
|
||||
if (layout) applyChatLayout(prev ?? {});
|
||||
toast(t("settings.failSave") + errMsg(e), true);
|
||||
return false;
|
||||
}
|
||||
@@ -232,6 +237,24 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
|
||||
{ value: "dark", label: t("settings.themeDark") },
|
||||
]} />
|
||||
))}
|
||||
{row(t("settings.contentWidth"), (
|
||||
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.contentWidth")}
|
||||
value={normalizeContentWidth(s.contentWidth)} onChange={(v) => void set({ contentWidth: v })}
|
||||
options={[
|
||||
{ value: "narrow", label: t("settings.widthNarrow") },
|
||||
{ value: "default", label: t("settings.widthDefault") },
|
||||
{ value: "wide", label: t("settings.widthWide") },
|
||||
{ value: "full", label: t("settings.widthFull") },
|
||||
]} />
|
||||
))}
|
||||
{row(t("settings.chatFont"), (
|
||||
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.chatFont")}
|
||||
value={String(normalizeChatFont(s.chatFontSize))} onChange={(v) => void set({ chatFontSize: Number(v) })}
|
||||
options={Array.from({ length: CHAT_FONT_MAX - CHAT_FONT_MIN + 1 }, (_, i) => CHAT_FONT_MIN + i).map((n) => ({
|
||||
value: String(n),
|
||||
label: `${n} px${n === CHAT_FONT_DEFAULT ? t("settings.chatFontDefault") : ""}`,
|
||||
}))} />
|
||||
), t("settings.chatFontHint"))}
|
||||
{row(t("settings.sendKey"), (
|
||||
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.sendKey")}
|
||||
value={s.sendKey ?? "enter"} onChange={(v) => void set({ sendKey: v })}
|
||||
|
||||
@@ -153,6 +153,7 @@ export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) {
|
||||
return (
|
||||
<>
|
||||
<div className="sb-row">
|
||||
<SidebarToggle />
|
||||
<button className="sb-new" onClick={() => setNewProjOpen(true)}>
|
||||
<span className="sb-new-tile"><Icon name="plus" size={12} /></span>{tr("sidebar.newProject")}
|
||||
</button>
|
||||
@@ -512,3 +513,16 @@ async function exportThread(t: ThreadMeta) {
|
||||
toast(tr("sidebar.failExport") + errMsg(e), true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Collapse / expand the sidebar (the same button sits in the top bar while the sidebar is collapsed); Ctrl/⌘+B */
|
||||
export function SidebarToggle({ className = "" }: { className?: string }) {
|
||||
const hidden = useUi((s) => s.sbHidden);
|
||||
const open = useUi((s) => s.sbOpen);
|
||||
const label = tr(hidden && !open ? "sidebar.expand" : "sidebar.collapse");
|
||||
return (
|
||||
<button type="button" className={`ibtn sb-toggle ${className}`} title={`${label} (Ctrl+B)`} aria-label={label}
|
||||
aria-expanded={!hidden || open} onClick={() => useUi.getState().toggleSidebar()}>
|
||||
<Icon name="panelLeft" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import { fmtDur, fmtTokens, fmtCost } from "../util/format";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { localizeDaemonMessage, t, tf } from "../i18n/index.js";
|
||||
import { toast } from "./Toast";
|
||||
import { splitLocalLinks } from "../util/localLinks";
|
||||
import { onChatLinkClick } from "../preview/open";
|
||||
|
||||
const token = () => getToken();
|
||||
|
||||
@@ -18,18 +20,59 @@ export function attachmentUrl(id: string): string {
|
||||
return `/attachments/${id}?t=${token()}`;
|
||||
}
|
||||
|
||||
/** Plain text with local addresses as Preview links (tool output; React nodes, no innerHTML) */
|
||||
export function LinkifiedText({ text }: { text: string }) {
|
||||
const parts = useMemo(() => splitLocalLinks(text), [text]);
|
||||
if (parts.length === 1 && typeof parts[0] === "string") return <>{text}</>;
|
||||
return (
|
||||
<>
|
||||
{parts.map((p, i) =>
|
||||
typeof p === "string" ? p : (
|
||||
<a key={i} href={p.url} data-ac-local={p.url} className="ac-local" title={t("links.openPreviewTitle")}>{p.text}</a>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const baseName = (p: string) => p.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || p;
|
||||
|
||||
/** A path chip (composer, user bubble): icon + name (folders end with /), full path on hover */
|
||||
const isImageMime = (m: string | undefined): boolean => !m || m.startsWith("image/");
|
||||
|
||||
export function MentionChip({ path, isDir, onRemove }: { path: string; isDir: boolean; onRemove?: () => void }) {
|
||||
return (
|
||||
<span className="mention" title={path}>
|
||||
<Icon name={isDir ? "files" : "file"} size={12} />
|
||||
<span className="mention-name">{baseName(path)}{isDir ? "/" : ""}</span>
|
||||
{onRemove && <button type="button" className="att-x" aria-label={t("mention.remove")} onClick={onRemove}>×</button>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- user message ----------
|
||||
export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string) => void }) {
|
||||
export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string, mentions?: { path: string; isDir: boolean }[]) => void }) {
|
||||
return (
|
||||
<div className="um-row">
|
||||
<div className="um">
|
||||
{it.attachments?.map((a) => (
|
||||
{it.attachments?.filter((a) => isImageMime(a.mime)).map((a) => (
|
||||
<img key={a.id} className="um-img" src={`/attachments/${a.id}?t=${token()}`} alt={a.name} />
|
||||
))}
|
||||
{/* text / PDF / other files: a name chip (they used to render as a broken <img>) */}
|
||||
{it.attachments?.some((a) => !isImageMime(a.mime)) && (
|
||||
<span className="um-mentions">
|
||||
{it.attachments.filter((a) => !isImageMime(a.mime)).map((a) => (
|
||||
<span key={a.id} className="mention" title={a.name}><Icon name="file" size={12} /><span className="mention-name">{a.name}</span></span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
{it.mentions && it.mentions.length > 0 && (
|
||||
<span className="um-mentions">{it.mentions.map((m) => <MentionChip key={m.path} path={m.path} isDir={m.isDir} />)}</span>
|
||||
)}
|
||||
<span className="um-text">{it.text}</span>
|
||||
<div className="um-act">
|
||||
<button className="ibtn" title={t("common.copy")} onClick={() => void copyText(it.text)}><Icon name="copy" size={13} /></button>
|
||||
{onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text)}><Icon name="send" size={13} /></button>}
|
||||
{onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text, it.mentions)}><Icon name="send" size={13} /></button>}
|
||||
</div>
|
||||
</div>
|
||||
{it.steered && <div className="um-tag">{t("timeline.steer")}</div>}
|
||||
@@ -84,12 +127,14 @@ export function ToolGroupItem({ it }: { it: Extract<DisplayItem, { kind: "toolgr
|
||||
useEffect(() => {
|
||||
if (!userToggled.current && (hasFail || hasDiff)) setOpen(true);
|
||||
}, [hasFail, hasDiff]);
|
||||
const summary = useMemo(() => {
|
||||
// Not memoized on it.steps: the reducer appends steps to the same array while a turn streams,
|
||||
// so a memo keyed on the array kept the first count ("1 step · Read 1" next to five steps).
|
||||
const summary = (() => {
|
||||
const counts = new Map<string, number>();
|
||||
for (const s of it.steps) counts.set(s.kind, (counts.get(s.kind) ?? 0) + 1);
|
||||
const parts = [...counts.entries()].map(([k, n]) => `${toolKind(k)} ${n}`);
|
||||
return tf("timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") });
|
||||
}, [it.steps]);
|
||||
return tf(it.steps.length === 1 ? "timeline.toolSummaryOne" : "timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") });
|
||||
})();
|
||||
const runningStep = it.steps.find((s) => s.status === "running");
|
||||
return (
|
||||
<div className="tg">
|
||||
@@ -142,7 +187,7 @@ function ToolDetail({ s }: { s: ToolStep }) {
|
||||
return (
|
||||
<div className="ts-out">
|
||||
{tail && <button className="ts-more" onClick={() => setFull(true)}>{tf("timeline.showAllLines", { n: lines.length })}</button>}
|
||||
<pre>{text}</pre>
|
||||
<pre onClick={onChatLinkClick}><LinkifiedText text={text} /></pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -340,7 +385,7 @@ export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayIte
|
||||
// ---------- dispatch ----------
|
||||
export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText }: {
|
||||
it: DisplayItem; threadId: string; replyText?: string;
|
||||
onEditResend?: (text: string) => void;
|
||||
onEditResend?: (text: string, mentions?: { path: string; isDir: boolean }[]) => void;
|
||||
onRetryLast?: () => void;
|
||||
}) {
|
||||
switch (it.kind) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useUi, type PanelTab } from "../stores/ui";
|
||||
import { useConnection } from "../stores/connection";
|
||||
import { ws } from "../main";
|
||||
import { Icon } from "./Icons";
|
||||
import { SidebarToggle } from "./Sidebar";
|
||||
import { Menu, useMenu, type MenuItem } from "./Menu";
|
||||
import { Dialog } from "./Dialog";
|
||||
import { copyText } from "./Markdown";
|
||||
@@ -55,6 +56,7 @@ export function Topbar({ pendingCount }: { pendingCount: number }) {
|
||||
{ tab: "changes", icon: "changes", title: t("topbar.panelChanges") },
|
||||
{ tab: "files", icon: "files", title: t("topbar.panelFiles") },
|
||||
{ tab: "terminal", icon: "term", title: t("topbar.panelTerminal") },
|
||||
{ tab: "preview", icon: "globe", title: t("preview.tab") },
|
||||
];
|
||||
|
||||
const moreItems: MenuItem[] = thread
|
||||
@@ -72,13 +74,8 @@ export function Topbar({ pendingCount }: { pendingCount: number }) {
|
||||
|
||||
return (
|
||||
<header className="topbar">
|
||||
<button
|
||||
className="ibtn tb-menu-btn"
|
||||
title={t("topbar.sidebar")}
|
||||
onClick={() => ui.setSbOpen(!ui.sbOpen)}
|
||||
>
|
||||
<Icon name="menu" />
|
||||
</button>
|
||||
{/* sidebar collapsed (or a narrow window's drawer): the toggle lives here, before the breadcrumb */}
|
||||
<SidebarToggle className={`tb-menu-btn${ui.sbHidden ? " tb-sb-collapsed" : ""}`} />
|
||||
{project && <span className="tb-crumb">{project.name}</span>}
|
||||
{project && thread && <span className="tb-sep">/</span>}
|
||||
{thread ? (
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Path chips from the Files panel (1.2): drag data, de-duplication, what thread.send gets. Pure, unit tested.
|
||||
|
||||
/** dataTransfer type of a Files-panel row dragged into the composer */
|
||||
export const MENTION_MIME = "application/x-agent-console-path";
|
||||
export const MAX_MENTIONS = 50;
|
||||
export type MentionDraft = { projectId: string; rel: string; isDir: boolean };
|
||||
|
||||
/** Absolute path of a project-relative path, with the project's own separator (Windows paths keep backslashes) */
|
||||
export function joinProjectPath(root: string, rel: string): string {
|
||||
const win = /^[a-zA-Z]:[\\/]/.test(root) || root.startsWith("\\\\");
|
||||
const sep = win ? "\\" : "/";
|
||||
const r = rel === "." ? "" : win ? rel.replace(/\//g, "\\") : rel;
|
||||
return r ? root.replace(/[\\/]+$/, "") + sep + r : root;
|
||||
}
|
||||
|
||||
/** The drag payload (any page could forge one: the daemon checks the path again) */
|
||||
export function parseMentionDrag(raw: string | null | undefined): MentionDraft | null {
|
||||
if (!raw || raw.length > 10000) return null;
|
||||
try {
|
||||
const o = JSON.parse(raw) as Partial<MentionDraft>;
|
||||
if (typeof o.projectId !== "string" || typeof o.rel !== "string" || !o.rel || o.rel.length > 4096) return null;
|
||||
return { projectId: o.projectId, rel: o.rel, isDir: o.isDir === true };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function addMention(list: MentionDraft[], m: MentionDraft): MentionDraft[] {
|
||||
if (list.some((x) => x.projectId === m.projectId && x.rel === m.rel)) return list;
|
||||
if (list.length >= MAX_MENTIONS) return list;
|
||||
return [...list, m];
|
||||
}
|
||||
|
||||
/** thread.send's mentions field */
|
||||
export function mentionsForSend(list: MentionDraft[]): { rel: string; isDir: boolean }[] {
|
||||
return list.map((m) => ({ rel: m.rel, isDir: m.isDir }));
|
||||
}
|
||||
|
||||
/** A sent message's absolute paths → project-relative again (edit & resend); paths outside the project are dropped */
|
||||
export function relFromAbs(root: string, abs: string): string | null {
|
||||
const norm = (s: string) => s.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const r = norm(root);
|
||||
const a = norm(abs);
|
||||
const win = /^[a-zA-Z]:\//.test(r);
|
||||
const eq = (x: string, y: string) => (win ? x.toLowerCase() === y.toLowerCase() : x === y);
|
||||
if (eq(a, r)) return ".";
|
||||
if (a.length > r.length && eq(a.slice(0, r.length), r) && a[r.length] === "/") return a.slice(r.length + 1);
|
||||
return null;
|
||||
}
|
||||
@@ -24,6 +24,15 @@ export function initLocale(search: string): LocaleId {
|
||||
return locale;
|
||||
}
|
||||
|
||||
/** Switch the UI language at runtime (Magpie's language changed); returns whether it changed */
|
||||
export function setLocale(raw: string | null | undefined): boolean {
|
||||
const next = normalizeLang(raw);
|
||||
if (next === locale) return false;
|
||||
locale = next;
|
||||
if (typeof document !== "undefined") document.documentElement.lang = locale === "zh" ? "zh-CN" : "en";
|
||||
return true;
|
||||
}
|
||||
|
||||
export function getLocale(): LocaleId {
|
||||
return locale;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
panelChanges: "改动(Ctrl+J)", panelFiles: "文件", panelTerminal: "终端",
|
||||
},
|
||||
sidebar: {
|
||||
newProject: "新建项目", filterPlaceholder: "过滤对话标题", searchTitle: "搜索(Ctrl+K)",
|
||||
newProject: "新建项目", collapse: "收起侧栏", expand: "展开侧栏", filterPlaceholder: "过滤对话标题", searchTitle: "搜索(Ctrl+K)",
|
||||
noProjectsTitle: "还没有项目", noProjectsSub: "项目对应一个本机目录,对话都在目录里干活。",
|
||||
newThread: "新建对话", projectMenu: "项目菜单", showAll: "显示全部 {n} 条", noThreads: "还没有对话",
|
||||
rename: "重命名", pin: "置顶", unpin: "取消置顶", archive: "归档", unarchive: "取消归档",
|
||||
@@ -95,6 +95,8 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
effort: { low: "低", medium: "中", high: "高", xhigh: "超高", max: "最高", minimal: "最低", none: "关闭" },
|
||||
},
|
||||
settings: {
|
||||
contentWidth: "内容宽度", widthNarrow: "窄(640)", widthDefault: "默认(720)", widthWide: "宽(880)", widthFull: "铺满",
|
||||
chatFont: "聊天字号", chatFontDefault: "(默认)", chatFontHint: "对话正文、输入框、工具输出和代码一起缩放(代码小 1px)",
|
||||
title: "设置", defaultAgent: "默认 Agent", defaultMode: "默认权限模式", theme: "主题",
|
||||
themeAuto: "跟随系统", themeMagpie: "跟随 Magpie", themeLight: "浅色", themeDark: "深色",
|
||||
sendKey: "发送键", sendEnter: "Enter 发送 / Shift+Enter 换行", sendCtrl: "Ctrl+Enter 发送 / Enter 换行",
|
||||
@@ -152,7 +154,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
read: "读取", edit: "修改", write: "写入", bash: "运行", search: "搜索", glob: "搜索",
|
||||
web: "联网", task: "子任务", mcp: "工具", todo: "待办", other: "工具", processing: "处理",
|
||||
},
|
||||
toolSummary: "已执行 {n} 步 · {parts}", toolRunning: "正在{kind}:{title}",
|
||||
toolSummary: "已执行 {n} 步 · {parts}", toolSummaryOne: "已执行 1 步 · {parts}", toolRunning: "正在{kind}:{title}",
|
||||
showAllLines: "显示全部 {n} 行", diffClip: "(只显示前 {n} 行)",
|
||||
},
|
||||
api: {
|
||||
@@ -160,6 +162,22 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
busy: "正忙,请稍后再试", bad_path: "路径无效",
|
||||
connClosed: "连接中断", notConnected: "连接未建立", timeout: "请求超时",
|
||||
},
|
||||
preview: {
|
||||
tab: "预览", address: "预览地址", placeholder: "localhost:5173", back: "后退", forward: "前进", reload: "刷新",
|
||||
openExternal: "用系统浏览器打开", widen: "加宽面板", onlyLocal: "预览只支持本机地址(localhost、127.0.0.1 等)",
|
||||
failed: "打不开预览:",
|
||||
empty: "还没有预览地址。在对话里点 localhost 链接,或在上方输入,例如 localhost:5173",
|
||||
limits: "预览在沙箱里运行:弹窗、alert 和原生表单提交不可用;localStorage 和登录 cookie 刷新后会丢失,需要时请用系统浏览器打开。",
|
||||
noLocalhost: "这台电脑的网页内核打不开 *.localhost 地址(macOS 26 以前的系统会这样)。预览靠这个地址挡住别的网页读取你的 dev server,所以这里不能预览,请用系统浏览器打开。",
|
||||
},
|
||||
links: {
|
||||
openPreviewTitle: "在预览中打开(Ctrl/⌘+点击用浏览器打开)",
|
||||
externalFailed: "打不开系统浏览器,已复制链接",
|
||||
},
|
||||
mention: {
|
||||
drop: "松开以插入到聊天", add: "插入到聊天", copyRel: "复制相对路径", remove: "移除",
|
||||
otherProject: "只能插入当前对话所在项目里的文件",
|
||||
},
|
||||
},
|
||||
en: {
|
||||
app: { title: "Agent Console", subtitle: "Create or select a project in the sidebar" },
|
||||
@@ -185,7 +203,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
panelChanges: "Changes (Ctrl+J)", panelFiles: "Files", panelTerminal: "Terminal",
|
||||
},
|
||||
sidebar: {
|
||||
newProject: "New project", filterPlaceholder: "Filter conversations", searchTitle: "Search (Ctrl+K)",
|
||||
newProject: "New project", collapse: "Collapse sidebar", expand: "Expand sidebar", filterPlaceholder: "Filter conversations", searchTitle: "Search (Ctrl+K)",
|
||||
noProjectsTitle: "No projects yet", noProjectsSub: "A project maps to a folder on this machine.",
|
||||
newThread: "New conversation", projectMenu: "Project menu", showAll: "Show all {n}",
|
||||
noThreads: "No conversations yet",
|
||||
@@ -251,6 +269,8 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
effort: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max", minimal: "Minimal", none: "Off" },
|
||||
},
|
||||
settings: {
|
||||
contentWidth: "Content width", widthNarrow: "Narrow (640)", widthDefault: "Default (720)", widthWide: "Wide (880)", widthFull: "Full",
|
||||
chatFont: "Chat font size", chatFontDefault: " (default)", chatFontHint: "Scales the conversation, the input, tool output and code (code 1px smaller)",
|
||||
title: "Settings", defaultAgent: "Default agent", defaultMode: "Default permission mode", theme: "Theme",
|
||||
themeAuto: "System", themeMagpie: "Follow Magpie", themeLight: "Light", themeDark: "Dark",
|
||||
sendKey: "Send shortcut", sendEnter: "Enter sends / Shift+Enter newline",
|
||||
@@ -309,7 +329,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
read: "Read", edit: "Edit", write: "Write", bash: "Run", search: "Search", glob: "Search",
|
||||
web: "Web", task: "Subtask", mcp: "Tool", todo: "Todo", other: "Tool", processing: "Working",
|
||||
},
|
||||
toolSummary: "{n} step(s) · {parts}", toolRunning: "{kind}: {title}",
|
||||
toolSummary: "{n} steps · {parts}", toolSummaryOne: "1 step · {parts}", toolRunning: "{kind}: {title}",
|
||||
showAllLines: "Show all {n} lines", diffClip: "(first {n} lines only)",
|
||||
},
|
||||
api: {
|
||||
@@ -317,5 +337,21 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
busy: "Busy — try again later", bad_path: "Invalid path",
|
||||
connClosed: "Connection lost", notConnected: "Not connected", timeout: "Request timed out",
|
||||
},
|
||||
preview: {
|
||||
tab: "Preview", address: "Preview address", placeholder: "localhost:5173", back: "Back", forward: "Forward", reload: "Reload",
|
||||
openExternal: "Open in browser", widen: "Widen panel", onlyLocal: "Preview only supports local addresses (localhost, 127.0.0.1, …)",
|
||||
failed: "Can't open the preview: ",
|
||||
empty: "Nothing to preview yet. Click a localhost link in the chat, or type an address above, e.g. localhost:5173",
|
||||
limits: "The preview runs sandboxed: popups, alert and native form posts don't work; localStorage and login cookies are lost on reload. Open it in your browser when you need them.",
|
||||
noLocalhost: "This system's web view can't open *.localhost addresses (macOS before 26 can't). The preview needs one to keep other web pages out of your dev server, so it can't run here: open it in your browser instead.",
|
||||
},
|
||||
links: {
|
||||
openPreviewTitle: "Open in Preview (Ctrl/⌘+click opens the browser)",
|
||||
externalFailed: "Couldn't open the browser; the link was copied",
|
||||
},
|
||||
mention: {
|
||||
drop: "Drop to add to the chat", add: "Add to chat", copyRel: "Copy relative path", remove: "Remove",
|
||||
otherProject: "Only files of this conversation's project can be added",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -13,11 +13,26 @@ export function applyMagpieTokensFromSearch(search: string): void {
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const root = document.documentElement;
|
||||
applyMagpieTokens(obj);
|
||||
}
|
||||
|
||||
/** Magpie token map → CSS variables name → value (accent dropped; odd names / values skipped). Pure, for tests. */
|
||||
export function magpieTokenVars(obj: Record<string, unknown> | null | undefined): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
if (!obj || typeof obj !== "object") return out;
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
const s = String(v ?? "").trim();
|
||||
if (!s || isAccentToken(k)) continue;
|
||||
const varName = k.startsWith("--") ? k : k.startsWith("magpie-") ? `--${k}` : `--magpie-${k}`;
|
||||
root.style.setProperty(varName, s);
|
||||
if (typeof v !== "string" && typeof v !== "number") continue;
|
||||
const s = String(v).trim();
|
||||
if (!s || s.length > 300 || /[;{}<>]/.test(s) || isAccentToken(k)) continue;
|
||||
const name = k.replace(/^--/, "").replace(/^magpie-/i, "");
|
||||
if (!/^[a-zA-Z0-9-]{1,48}$/.test(name)) continue;
|
||||
out[`--magpie-${name}`] = s;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Write Magpie's tokens as --magpie-* variables (at load from ?tokens=, and live from the bridge's theme events) */
|
||||
export function applyMagpieTokens(obj: Record<string, unknown> | null | undefined): void {
|
||||
const root = document.documentElement;
|
||||
for (const [k, v] of Object.entries(magpieTokenVars(obj))) root.style.setProperty(k, v);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Conversation column width and chat text size (1.2 settings). Both are CSS variables on <html>:
|
||||
// --col the column the timeline and the composer share (720px by default)
|
||||
// --chat-fs chat text size; tokens.css derives code (1px smaller), headings and line heights from it
|
||||
export type ContentWidth = "narrow" | "default" | "wide" | "full";
|
||||
export const CONTENT_WIDTHS: ContentWidth[] = ["narrow", "default", "wide", "full"];
|
||||
export const WIDTH_PX: Record<Exclude<ContentWidth, "full">, number> = { narrow: 640, default: 720, wide: 880 };
|
||||
export const CHAT_FONT_MIN = 12;
|
||||
export const CHAT_FONT_MAX = 18;
|
||||
export const CHAT_FONT_DEFAULT = 13;
|
||||
|
||||
export function normalizeContentWidth(v: unknown): ContentWidth {
|
||||
return v === "narrow" || v === "wide" || v === "full" ? v : "default";
|
||||
}
|
||||
|
||||
/** CSS value of --col for a width setting */
|
||||
export function colValue(v: unknown): string {
|
||||
const w = normalizeContentWidth(v);
|
||||
return w === "full" ? "100%" : `${WIDTH_PX[w]}px`;
|
||||
}
|
||||
|
||||
export function normalizeChatFont(v: unknown): number {
|
||||
const n = typeof v === "number" ? v : Number(v);
|
||||
if (!Number.isFinite(n)) return CHAT_FONT_DEFAULT;
|
||||
return Math.min(CHAT_FONT_MAX, Math.max(CHAT_FONT_MIN, Math.round(n)));
|
||||
}
|
||||
|
||||
export function applyChatLayout(s: { contentWidth?: unknown; chatFontSize?: unknown }): void {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty("--col", colValue(s.contentWidth));
|
||||
root.style.setProperty("--chat-fs", `${normalizeChatFont(s.chatFontSize)}px`);
|
||||
root.dataset.contentWidth = normalizeContentWidth(s.contentWidth);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Live theme from Magpie (1.2 fix). The plugin page (page/boot.js) navigates its frame to the daemon page, so Magpie's
|
||||
// bridge.js is gone from the frame; but Magpie's window keeps posting {magpie:1, event:"theme", data:{dark, lang, tokens}}
|
||||
// to the frame's window, and answers a {magpie:1, method:"hello"} call with the current theme. This page speaks that small
|
||||
// part of the bridge protocol itself: at load (the theme may have changed during the redirect, or after a self-heal) and on
|
||||
// every switch, so the page follows Magpie's light/dark and neutral colours without a reload.
|
||||
// Only messages from window.parent with magpie:1 are read, and only the theme fields (and the language) are used; no commands are taken.
|
||||
import { applyMagpieTokens } from "./applyMagpieTokens.js";
|
||||
import { setHostTheme } from "./theme.js";
|
||||
|
||||
export type MagpieTheme = { dark: boolean; tokens: Record<string, unknown>; lang?: string };
|
||||
|
||||
/** A theme payload from Magpie (event data, or a hello answer) → {dark, tokens}, or null if it isn't one */
|
||||
export function parseMagpieTheme(d: unknown): MagpieTheme | null {
|
||||
if (!d || typeof d !== "object") return null;
|
||||
const o = d as { dark?: unknown; tokens?: unknown; lang?: unknown };
|
||||
if (typeof o.dark !== "boolean") return null;
|
||||
const tokens = o.tokens && typeof o.tokens === "object" && !Array.isArray(o.tokens) ? (o.tokens as Record<string, unknown>) : {};
|
||||
const out: MagpieTheme = { dark: o.dark, tokens };
|
||||
if (typeof o.lang === "string" && o.lang.length <= 32) out.lang = o.lang;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Which theme a bridge message carries, given the id of our own hello call */
|
||||
export function themeFromMessage(m: unknown, helloId: number): MagpieTheme | null {
|
||||
if (!m || typeof m !== "object") return null;
|
||||
const msg = m as { magpie?: unknown; event?: unknown; data?: unknown; id?: unknown; result?: unknown };
|
||||
if (msg.magpie !== 1) return null;
|
||||
if (msg.event === "theme") return parseMagpieTheme(msg.data);
|
||||
if (msg.id === helloId && msg.result) return parseMagpieTheme(msg.result);
|
||||
return null;
|
||||
}
|
||||
|
||||
let started = false;
|
||||
|
||||
export function startMagpieThemeBridge(onTheme?: (t: MagpieTheme) => void): void {
|
||||
if (started || typeof window === "undefined") return;
|
||||
const parentWin = window.parent;
|
||||
if (!parentWin || parentWin === window) return;
|
||||
started = true;
|
||||
// a large id of our own, far from what bridge.js used before the navigation
|
||||
const helloId = 1_000_000 + Math.floor(Math.random() * 1_000_000);
|
||||
window.addEventListener("message", (e) => {
|
||||
if (e.source !== parentWin) return;
|
||||
const t = themeFromMessage(e.data, helloId);
|
||||
if (!t) return;
|
||||
applyMagpieTokens(t.tokens);
|
||||
setHostTheme(t.dark ? "dark" : "light");
|
||||
onTheme?.(t);
|
||||
});
|
||||
try {
|
||||
parentWin.postMessage({ magpie: 1, id: helloId, method: "hello" }, "*");
|
||||
} catch {}
|
||||
}
|
||||
@@ -38,6 +38,16 @@ export function embeddedInMagpie(): boolean {
|
||||
return hostTheme !== null;
|
||||
}
|
||||
|
||||
/** Magpie switched light/dark while the page is open (bridge theme event, see magpieBridge.ts) */
|
||||
export function setHostTheme(t: Theme): void {
|
||||
hostTheme = t;
|
||||
applyTheme(current);
|
||||
}
|
||||
|
||||
export function currentSetting(): ThemeSetting {
|
||||
return current;
|
||||
}
|
||||
|
||||
export function applyTheme(setting: unknown): void {
|
||||
current = normalizeThemeSetting(setting);
|
||||
const { theme, hostColors } = resolveTheme(current, hostTheme, osTheme());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Entry: read the hash token and theme params, mount <App/>.
|
||||
import { usePreview } from "./stores/preview";
|
||||
import "./styles/tokens.css";
|
||||
import "./styles/base.css";
|
||||
import "./styles/layout.css";
|
||||
@@ -7,8 +8,10 @@ import "./styles/composer.css";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { applyMagpieTokensFromSearch } from "./layout/applyMagpieTokens.js";
|
||||
import { applyTheme, initTheme } from "./layout/theme.js";
|
||||
import { startMagpieThemeBridge } from "./layout/magpieBridge.js";
|
||||
import { applyChatLayout } from "./layout/chatLayout.js";
|
||||
import { goBackToMagpie, watchReconnect } from "./api/backToMagpie.js";
|
||||
import { initLocale, getLocale } from "./i18n/index.js";
|
||||
import { initLocale, getLocale, setLocale } from "./i18n/index.js";
|
||||
import { WsClient } from "./api/ws";
|
||||
import { useConnection } from "./stores/connection";
|
||||
import { useUi } from "./stores/ui";
|
||||
@@ -24,11 +27,18 @@ const params = new URLSearchParams(location.search);
|
||||
initLocale(location.search);
|
||||
applyMagpieTokensFromSearch(location.search);
|
||||
initTheme(location.search);
|
||||
|
||||
// Follow Magpie's light/dark live (the frame no longer has bridge.js after boot.js navigated it here)
|
||||
export const ws = new WsClient(token, getLocale());
|
||||
// ...and its language: re-render the tree in the new language (t() isn't reactive), tell the daemon for its own text
|
||||
startMagpieThemeBridge((th) => {
|
||||
if (!th.lang || !setLocale(th.lang)) return;
|
||||
ws.setLang(getLocale());
|
||||
void ws.call("app.setLocale", { lang: getLocale() }).catch(() => {});
|
||||
renderApp();
|
||||
});
|
||||
// For the debug page (P1-8) and e2e driving: expose the authenticated client and internal stores.
|
||||
(window as unknown as { __ws?: WsClient; __stores?: unknown }).__ws = ws;
|
||||
(window as unknown as { __stores?: unknown }).__stores = { useData, useUi, useConnection };
|
||||
(window as unknown as { __stores?: unknown }).__stores = { useData, useUi, useConnection, usePreview };
|
||||
void import("./stores/timeline").then((m) => {
|
||||
(window as unknown as { __tl?: unknown }).__tl = m.useTimeline;
|
||||
});
|
||||
@@ -44,6 +54,7 @@ ws.waitHello().then(async (h) => {
|
||||
const s = (await ws.call("settings.get")) as Record<string, unknown>;
|
||||
useUi.getState().hydrate(s);
|
||||
applyTheme(s.theme);
|
||||
applyChatLayout(s);
|
||||
} catch {}
|
||||
// Fetch the project/conversation/provider lists and subscribe to the sidebar channel
|
||||
await useData.getState().bind(ws);
|
||||
@@ -51,7 +62,13 @@ ws.waitHello().then(async (h) => {
|
||||
setInterval(() => ws.ping(), 10000);
|
||||
|
||||
const isDebug = params.get("debug") === "1";
|
||||
createRoot(document.getElementById("root")!).render(isDebug ? <DebugApp /> : <App />);
|
||||
const root = createRoot(document.getElementById("root")!);
|
||||
let renders = 0;
|
||||
function renderApp(): void {
|
||||
renders++;
|
||||
root.render(isDebug ? <DebugApp /> : <App key={`${getLocale()}-${renders}`} />);
|
||||
}
|
||||
renderApp();
|
||||
|
||||
// ?audit=1 (§11.3 screenshot self-check metrics): count visible borders on the first screen, font-size set, accent-colored elements, horizontal scroll,
|
||||
// written to <pre id="audit"> (after 1.5s so the first screen settles).
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Opening links from chat (1.2): local addresses go to the Preview tab, everything http(s) else to the system browser
|
||||
// (the sandboxed page can't open popups, so target=_blank did nothing). Only a user's click gets here.
|
||||
import { ws } from "../main";
|
||||
import { useUi } from "../stores/ui";
|
||||
import { usePreview, threadKey } from "../stores/preview";
|
||||
import { localHref } from "../util/localLinks";
|
||||
import { copyText } from "../components/Markdown";
|
||||
import { toast } from "../components/Toast";
|
||||
import { t } from "../i18n/index.js";
|
||||
|
||||
export function openPreview(url: string): void {
|
||||
const ui = useUi.getState();
|
||||
const threadId = ui.currentThreadId;
|
||||
ui.openPanel("preview");
|
||||
void usePreview.getState().navigate((m, p) => ws.call(m, p), threadKey(threadId), threadId, url, { push: true });
|
||||
}
|
||||
|
||||
export async function openExternal(url: string): Promise<void> {
|
||||
try {
|
||||
const r = (await ws.call("app.openExternal", { url })) as { ok?: boolean };
|
||||
if (r?.ok) return;
|
||||
} catch {}
|
||||
await copyText(url);
|
||||
toast(t("links.externalFailed"));
|
||||
}
|
||||
|
||||
/** Delegated click handler for chat content: handles <a> clicks, never lets the frame navigate away */
|
||||
export function onChatLinkClick(e: React.MouseEvent | MouseEvent): void {
|
||||
const target = e.target as HTMLElement | null;
|
||||
const a = target?.closest?.("a");
|
||||
if (!a) return;
|
||||
const href = a.getAttribute("href") ?? "";
|
||||
e.preventDefault();
|
||||
const local = (a as HTMLElement).dataset.acLocal || localHref(href);
|
||||
const modified = e.ctrlKey || e.metaKey;
|
||||
if (local && !modified) {
|
||||
openPreview(local);
|
||||
return;
|
||||
}
|
||||
if (/^https?:\/\//i.test(local || href)) void openExternal(local || href);
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// Preview tab state per conversation (1.2): target URL, the proxy serving it, title, and a URL stack for back/forward
|
||||
// when the page has no navigation bridge (the bridge, when present, drives back/forward inside the frame instead).
|
||||
import { create } from "zustand";
|
||||
import { checkPreviewUrl, displayOrigin } from "../../../daemon/src/preview/url.js";
|
||||
import { t as tr } from "../i18n/index.js";
|
||||
|
||||
const t_noLocalhost = () => tr("preview.noLocalhost");
|
||||
|
||||
export type PreviewEntry = {
|
||||
/** normalized target URL currently shown */
|
||||
url: string;
|
||||
/** scheme://host:port of the target */
|
||||
origin: string;
|
||||
proxyOrigin: string | null;
|
||||
/** what the iframe loads (proxy origin + path); null until the proxy is up */
|
||||
proxyHref: string | null;
|
||||
title: string;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** bumped to force the iframe to reload */
|
||||
nonce: number;
|
||||
/** the injected bridge has reported at least once */
|
||||
bridged: boolean;
|
||||
stack: string[];
|
||||
idx: number;
|
||||
};
|
||||
|
||||
type Caller = (method: string, params?: unknown) => Promise<unknown>;
|
||||
|
||||
type PreviewStore = {
|
||||
byThread: Record<string, PreviewEntry>;
|
||||
/** Load a URL in this conversation's preview (push = a new history entry) */
|
||||
navigate(call: Caller, key: string, threadId: string | null, raw: string, opts?: { push?: boolean }): Promise<boolean>;
|
||||
/** The frame reported where it is now (bridge) */
|
||||
reported(key: string, url: string, title: string): void;
|
||||
/** The proxy for this entry was released: re-open it next time */
|
||||
detach(key: string): void;
|
||||
reload(key: string): void;
|
||||
step(key: string, delta: -1 | 1): string | null;
|
||||
};
|
||||
|
||||
export const threadKey = (threadId: string | null | undefined) => threadId ?? "_";
|
||||
|
||||
const inflight = new Map<string, Promise<boolean>>();
|
||||
|
||||
// The proxy answers only at http://ac<key>.localhost:<port> (#582, daemon/src/preview/proxy.ts). Before showing the frame,
|
||||
// check that this web view resolves that name (Chromium/WebView2, WebKitGTK and WebKit on macOS 26+ do, WebKit on macOS
|
||||
// before 26 doesn't): otherwise say why instead of a blank "can't find server" frame. Checked with a per-open nonce so a
|
||||
// hostile DNS answer that returns a plain 200 "ok" can't pass.
|
||||
export const PREVIEW_PING_PATH = "/__agent_console__/ping";
|
||||
|
||||
/** The daemon's OS as preview.open reports it (daemon/src/preview/host.ts) */
|
||||
export type PreviewHost = { platform: string; darwinMajor: number | null };
|
||||
|
||||
/** Darwin 25 = macOS 26 (same constant as daemon/src/preview/host.ts) */
|
||||
export const DARWIN_LOCALHOST_LOOPBACK = 25;
|
||||
|
||||
/**
|
||||
* Apple WebKit (Magpie's Mac app = WKWebView, Safari with magpie web): no Chrome / Chromium / Edge / Opera / iOS
|
||||
* Chrome or Firefox token, and a Mac or iOS device. Linux WebKitGTK / WPE carry AppleWebKit but no Macintosh → not it.
|
||||
*/
|
||||
export function isAppleWebKit(ua = typeof navigator !== "undefined" ? navigator.userAgent : ""): boolean {
|
||||
return /AppleWebKit\//i.test(ua)
|
||||
&& /Macintosh|iPhone|iPad|iPod/i.test(ua)
|
||||
&& !/Chrome\//i.test(ua)
|
||||
&& !/Chromium\//i.test(ua)
|
||||
&& !/Edg(?:e|A|iOS)?\//i.test(ua)
|
||||
&& !/OPR\//i.test(ua)
|
||||
&& !/CriOS\//i.test(ua)
|
||||
&& !/FxiOS\//i.test(ua);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apple WebKit before macOS 26 asks the system DNS for *.localhost (Magpie's Mac app on 12–15, Safari with magpie web).
|
||||
* The UA can't tell: Apple froze it at "Mac OS X 10_15_7" on every macOS, 26+ included. So the version comes from the
|
||||
* daemon (os.platform() + os.release() on the same Mac, it listens on 127.0.0.1 only). Refused: Apple WebKit on a
|
||||
* Darwin < 25 host, or when the daemon's answer is missing / unparseable (fail closed). Non-darwin hosts and every
|
||||
* other engine are left to the canary + nonce probe.
|
||||
*/
|
||||
export function isUnsafeLocalhostResolver(
|
||||
host: PreviewHost | null | undefined,
|
||||
ua = typeof navigator !== "undefined" ? navigator.userAgent : "",
|
||||
): boolean {
|
||||
if (!isAppleWebKit(ua)) return false;
|
||||
if (!host || typeof host.platform !== "string" || !host.platform) return true;
|
||||
if (host.platform !== "darwin") return false;
|
||||
const major = host.darwinMajor;
|
||||
if (typeof major !== "number" || !Number.isInteger(major)) return true;
|
||||
return major < DARWIN_LOCALHOST_LOOPBACK;
|
||||
}
|
||||
|
||||
/** GET origin+/__agent_console__/ping must return exactly expectedNonce (from preview.open over the authenticated WS). */
|
||||
export async function canReachProxy(origin: string, expectedNonce: string, timeoutMs = 5000): Promise<boolean> {
|
||||
if (!expectedNonce) return false;
|
||||
const ac = new AbortController();
|
||||
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
||||
try {
|
||||
const r = await fetch(origin + PREVIEW_PING_PATH, {
|
||||
cache: "no-store",
|
||||
credentials: "omit",
|
||||
referrerPolicy: "no-referrer",
|
||||
signal: ac.signal,
|
||||
});
|
||||
if (!r.ok) return false;
|
||||
const text = await r.text();
|
||||
return text === expectedNonce;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
type PreviewOpenResult = {
|
||||
proxyOrigin: string;
|
||||
proxyHref: string;
|
||||
url: string;
|
||||
nonce: string;
|
||||
canaryOrigin: string;
|
||||
canaryNonce: string;
|
||||
host?: PreviewHost;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prove loopback resolution (keyless canary) then that the keyed host is our listener (nonce echo).
|
||||
* On any failure the caller must preview.release so a leaked key dies with the listener.
|
||||
*/
|
||||
export async function confirmPreviewReachable(r: PreviewOpenResult, timeoutMs = 5000): Promise<boolean> {
|
||||
// Canary first: the keyed name is never looked up if *.localhost goes to hostile DNS
|
||||
if (!(await canReachProxy(r.canaryOrigin, r.canaryNonce, timeoutMs))) return false;
|
||||
return canReachProxy(r.proxyOrigin, r.nonce, timeoutMs);
|
||||
}
|
||||
|
||||
export const usePreview = create<PreviewStore>((set, get) => ({
|
||||
byThread: {},
|
||||
navigate: async (call, key, threadId, raw, opts) => {
|
||||
const c = checkPreviewUrl(raw);
|
||||
if (!c.ok) return false;
|
||||
const t = c.target;
|
||||
const prev = get().byThread[key];
|
||||
const sameProxy = prev && prev.origin === t.origin && prev.proxyOrigin;
|
||||
let stack = prev?.stack ?? [];
|
||||
let idx = prev?.idx ?? -1;
|
||||
if (opts?.push !== false) {
|
||||
if (stack[idx] !== t.href) {
|
||||
stack = [...stack.slice(0, idx + 1), t.href].slice(-50);
|
||||
idx = stack.length - 1;
|
||||
}
|
||||
} else if (!stack.length) {
|
||||
stack = [t.href];
|
||||
idx = 0;
|
||||
}
|
||||
if (sameProxy) {
|
||||
set((s) => ({ byThread: { ...s.byThread, [key]: { ...prev!, url: t.href, proxyHref: prev!.proxyOrigin + t.path, error: null, nonce: prev!.nonce + 1, stack, idx } } }));
|
||||
// remember it on the conversation
|
||||
if (threadId) void call("threads.update", { id: threadId, previewUrl: t.href }).catch(() => {});
|
||||
return true;
|
||||
}
|
||||
set((s) => ({
|
||||
byThread: {
|
||||
...s.byThread,
|
||||
[key]: {
|
||||
url: t.href, origin: t.origin, proxyOrigin: null, proxyHref: null, title: prev?.origin === t.origin ? prev.title : "",
|
||||
loading: true, error: null, nonce: (prev?.nonce ?? 0) + 1, bridged: false, stack, idx,
|
||||
},
|
||||
},
|
||||
}));
|
||||
const flightKey = `${key}\n${t.href}`;
|
||||
let p = inflight.get(flightKey);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
try {
|
||||
const r = (await call("preview.open", { url: t.href, ...(threadId ? { threadId } : {}) })) as PreviewOpenResult;
|
||||
// Fail closed before any *.localhost name is looked up on an engine that sends it to network DNS (#582): the
|
||||
// key only travelled over the authenticated WS, and the listener is released right away
|
||||
if (isUnsafeLocalhostResolver(r?.host)) {
|
||||
void call("preview.release", { url: t.origin }).catch(() => {});
|
||||
throw new Error(t_noLocalhost());
|
||||
}
|
||||
if (!(await confirmPreviewReachable(r))) {
|
||||
void call("preview.release", { url: t.origin }).catch(() => {});
|
||||
throw new Error(t_noLocalhost());
|
||||
}
|
||||
set((s) => {
|
||||
const cur = s.byThread[key];
|
||||
if (!cur || cur.url !== t.href) return s;
|
||||
return { byThread: { ...s.byThread, [key]: { ...cur, proxyOrigin: r.proxyOrigin, proxyHref: r.proxyHref, loading: false, error: null } } };
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
const msg = String((e as Error)?.message ?? e);
|
||||
set((s) => {
|
||||
const cur = s.byThread[key];
|
||||
if (!cur || cur.url !== t.href) return s;
|
||||
return { byThread: { ...s.byThread, [key]: { ...cur, loading: false, error: msg } } };
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
inflight.delete(flightKey);
|
||||
}
|
||||
})();
|
||||
inflight.set(flightKey, p);
|
||||
}
|
||||
return p;
|
||||
},
|
||||
reported: (key, url, title) => {
|
||||
set((s) => {
|
||||
const cur = s.byThread[key];
|
||||
if (!cur) return s;
|
||||
let { stack, idx } = cur;
|
||||
if (stack[idx] !== url) {
|
||||
// in-page navigation: keep our fallback stack in step
|
||||
if (stack[idx - 1] === url) idx -= 1;
|
||||
else if (stack[idx + 1] === url) idx += 1;
|
||||
else { stack = [...stack.slice(0, idx + 1), url].slice(-50); idx = stack.length - 1; }
|
||||
}
|
||||
return { byThread: { ...s.byThread, [key]: { ...cur, url, title, bridged: true, stack, idx } } };
|
||||
});
|
||||
},
|
||||
detach: (key) => {
|
||||
set((s) => {
|
||||
const cur = s.byThread[key];
|
||||
if (!cur) return s;
|
||||
return { byThread: { ...s.byThread, [key]: { ...cur, proxyOrigin: null, proxyHref: null, bridged: false } } };
|
||||
});
|
||||
},
|
||||
reload: (key) => {
|
||||
set((s) => {
|
||||
const cur = s.byThread[key];
|
||||
if (!cur) return s;
|
||||
return { byThread: { ...s.byThread, [key]: { ...cur, nonce: cur.nonce + 1, error: null } } };
|
||||
});
|
||||
},
|
||||
step: (key, delta) => {
|
||||
const cur = get().byThread[key];
|
||||
if (!cur) return null;
|
||||
const idx = cur.idx + delta;
|
||||
if (idx < 0 || idx >= cur.stack.length) return null;
|
||||
set((s) => ({ byThread: { ...s.byThread, [key]: { ...cur, idx } } }));
|
||||
return cur.stack[idx]!;
|
||||
},
|
||||
}));
|
||||
|
||||
/** Address-bar text for a target URL (default ports hidden, like a browser) */
|
||||
export function addressText(url: string): string {
|
||||
const c = checkPreviewUrl(url);
|
||||
if (!c.ok) return url;
|
||||
return displayOrigin(c.target.origin) + c.target.path;
|
||||
}
|
||||
@@ -4,10 +4,12 @@ import { create } from "zustand";
|
||||
import type { WsClient } from "../api/ws.js";
|
||||
import { clampLayoutWidths, maxPanelWidth, maxSidebarWidth } from "../layout/bounds.js";
|
||||
|
||||
export type PanelTab = "changes" | "files" | "terminal";
|
||||
export type PanelTab = "changes" | "files" | "terminal" | "preview";
|
||||
export const PANEL_TABS: PanelTab[] = ["changes", "files", "terminal", "preview"];
|
||||
|
||||
export type UiSettings = {
|
||||
sidebarWidth?: number;
|
||||
sidebarHidden?: boolean;
|
||||
panel?: { open?: boolean; tab?: PanelTab; width?: number };
|
||||
collapsedProjects?: string[];
|
||||
lastProjectId?: string | null;
|
||||
@@ -35,6 +37,8 @@ type UiStore = {
|
||||
closePanel(): void;
|
||||
setPanelTab(tab: PanelTab): void;
|
||||
toggleSidebarHidden(): void;
|
||||
/** The sidebar toggle button / Ctrl+B: the drawer on narrow windows, else collapse the column (persisted) */
|
||||
toggleSidebar(): void;
|
||||
setSbOpen(open: boolean): void;
|
||||
toggleCollapsed(projectId: string): void;
|
||||
select(projectId: string | null, threadId: string | null): void;
|
||||
@@ -71,13 +75,14 @@ export const useUi = create<UiStore>((set, get) => ({
|
||||
sidebarWidth: s.sidebarWidth ?? 248,
|
||||
panelWidth: s.panel?.width ?? 440,
|
||||
panelOpen: s.panel?.open ?? false,
|
||||
sbHidden: false,
|
||||
sbHidden: s.sidebarHidden === true,
|
||||
};
|
||||
const sized = clampLayoutWidths(draft);
|
||||
set({
|
||||
sidebarWidth: sized.sidebarWidth,
|
||||
sbHidden: draft.sbHidden,
|
||||
panelOpen: draft.panelOpen,
|
||||
panelTab: s.panel?.tab ?? "changes",
|
||||
panelTab: PANEL_TABS.includes(s.panel?.tab as PanelTab) ? (s.panel!.tab as PanelTab) : "changes",
|
||||
panelWidth: sized.panelWidth,
|
||||
collapsed,
|
||||
currentProjectId: s.lastProjectId ?? null,
|
||||
@@ -113,7 +118,15 @@ export const useUi = create<UiStore>((set, get) => ({
|
||||
set({ panelTab: tab });
|
||||
persist(get, { panel: { open: get().panelOpen, tab, width: get().panelWidth } });
|
||||
},
|
||||
toggleSidebarHidden: () => set((s) => ({ sbHidden: !s.sbHidden })),
|
||||
toggleSidebarHidden: () => {
|
||||
const next = !get().sbHidden;
|
||||
set({ sbHidden: next });
|
||||
persist(get, { sidebarHidden: next });
|
||||
},
|
||||
toggleSidebar: () => {
|
||||
if (typeof window !== "undefined" && window.matchMedia?.("(max-width: 759px)").matches) get().setSbOpen(!get().sbOpen);
|
||||
else get().toggleSidebarHidden();
|
||||
},
|
||||
setSbOpen: (open) => set({ sbOpen: open }),
|
||||
toggleCollapsed: (projectId) => {
|
||||
const collapsed = { ...get().collapsed };
|
||||
|
||||
@@ -5,36 +5,42 @@
|
||||
.um {
|
||||
position: relative; max-width: 78%;
|
||||
background: var(--accent-soft); border-radius: 14px 14px 4px 14px; color: var(--fg);
|
||||
padding: 6px 12px; font-size: var(--fs-l); line-height: 1.6;
|
||||
padding: 6px 12px; font-size: var(--chat-fs); line-height: 1.6;
|
||||
white-space: pre-wrap; word-break: normal; overflow-wrap: break-word;
|
||||
}
|
||||
.um:hover .um-act { display: flex; }
|
||||
.um-act { position: absolute; left: -62px; top: 4px; display: none; gap: 2px; }
|
||||
.um-act .ibtn { width: 24px; height: 24px; }
|
||||
.um-img { display: block; max-width: 200px; max-height: 140px; border-radius: var(--r-s); margin-bottom: 6px; cursor: zoom-in; }
|
||||
.um-tag { font-size: var(--fs-s); color: var(--muted); margin-top: 2px; }
|
||||
.um-tag { font-size: var(--chat-fs-s); color: var(--muted); margin-top: 2px; }
|
||||
|
||||
/* Streaming cursor for the body */
|
||||
.as { margin: 4px 0; }
|
||||
.md.streaming::after { content: "▍"; color: var(--accent); animation: breathe 1s infinite; }
|
||||
|
||||
/* Markdown */
|
||||
.md { font-size: var(--fs-l); line-height: 1.75; color: var(--text); word-break: normal; overflow-wrap: break-word; }
|
||||
.md p { margin: 0 0 8px; }
|
||||
.md { font-size: var(--chat-fs); line-height: var(--chat-lh); color: var(--text); word-break: normal; overflow-wrap: break-word; }
|
||||
.md p { margin: 0 0 0.6em; }
|
||||
.md > :last-child { margin-bottom: 0; }
|
||||
.md a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; text-decoration-color: color-mix(in oklab, var(--accent) 40%, transparent); }
|
||||
.md a:hover { text-decoration: underline; }
|
||||
.md pre {
|
||||
position: relative; background: var(--code-bg); border: 1px solid var(--code-line); border-radius: var(--r-m);
|
||||
padding: 10px 12px; overflow-x: auto; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.55;
|
||||
padding: 10px 12px; overflow-x: auto; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.55;
|
||||
}
|
||||
.md code { font-family: var(--font-mono); font-size: 12.5px; background: var(--code-bg); color: var(--code-fg); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--code-line); }
|
||||
.md pre code { background: none; padding: 0; border: 0; color: inherit; }
|
||||
.md ul, .md ol { margin: 6px 0; padding-left: 22px; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 12px 0 6px; font-size: var(--fs-l); font-weight: 600; }
|
||||
.md code { font-family: var(--font-mono); font-size: var(--chat-code-fs); background: var(--code-bg); color: var(--code-fg); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--code-line); }
|
||||
.md pre code { background: none; padding: 0; border: 0; color: inherit; font-size: inherit; }
|
||||
.md ul, .md ol { margin: 0.45em 0; padding-left: 1.7em; }
|
||||
.md li + li { margin-top: 0.15em; }
|
||||
.md h1, .md h2, .md h3, .md h4 { margin: 0.95em 0 0.4em; font-weight: 600; line-height: 1.4; }
|
||||
.md h1 { font-size: calc(var(--chat-fs) + 4px); }
|
||||
.md h2 { font-size: calc(var(--chat-fs) + 2px); }
|
||||
.md h3 { font-size: calc(var(--chat-fs) + 1px); }
|
||||
.md h4 { font-size: var(--chat-fs); }
|
||||
.md > h1:first-child, .md > h2:first-child, .md > h3:first-child, .md > h4:first-child { margin-top: 0.2em; }
|
||||
.md blockquote { margin: 6px 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); }
|
||||
.md table { border-collapse: collapse; margin: 8px 0; }
|
||||
.md th, .md td { border: 1px solid var(--line); padding: 4px 10px; font-size: var(--fs-s); }
|
||||
.md th, .md td { border: 1px solid var(--line); padding: 4px 10px; font-size: var(--chat-fs-s); }
|
||||
.cb-copy {
|
||||
position: absolute; top: 6px; right: 6px; font-size: var(--fs-s); color: var(--muted);
|
||||
padding: 2px 8px; border-radius: var(--r-s); background: var(--bg); opacity: 0; transition: opacity var(--dur-1);
|
||||
@@ -46,13 +52,13 @@
|
||||
.rs-item { margin: 4px 0 6px; }
|
||||
.rs-head {
|
||||
display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0;
|
||||
color: var(--meta); font-size: var(--fs-s);
|
||||
color: var(--meta); font-size: var(--chat-fs-s);
|
||||
}
|
||||
.rs-head:hover { color: var(--fg); }
|
||||
.rs-head .caret { display: inline-block; transition: transform var(--dur-1); }
|
||||
.rs-head .caret.open { transform: rotate(90deg); }
|
||||
.rs-body { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--fs-s); line-height: 1.65; white-space: pre-wrap; }
|
||||
.todo-list { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); list-style: none; font-size: var(--fs-s); }
|
||||
.rs-body { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--chat-fs-s); line-height: 1.65; white-space: pre-wrap; }
|
||||
.todo-list { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); list-style: none; font-size: var(--chat-fs-s); }
|
||||
.todo { color: var(--muted); }
|
||||
.todo.in_progress { color: var(--fg); }
|
||||
|
||||
@@ -60,7 +66,7 @@
|
||||
.tg { margin: 4px 0 10px; }
|
||||
.tg-head {
|
||||
display: flex; align-items: center; gap: 6px; width: 100%; height: 24px; padding: 0;
|
||||
color: var(--meta); font-size: var(--fs-s); text-align: left;
|
||||
color: var(--meta); font-size: var(--chat-fs-s); text-align: left;
|
||||
}
|
||||
.tg-head:hover { color: var(--fg); }
|
||||
.tg-head .caret { transition: transform var(--dur-1); }
|
||||
@@ -69,7 +75,7 @@
|
||||
.tg-list { margin: 2px 0 0 5px; border-left: 1px solid var(--line); padding-left: 6px; }
|
||||
.ts-head {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; height: 26px; padding: 0 6px;
|
||||
border-radius: var(--r-s); font-size: 12.5px; text-align: left; color: var(--text);
|
||||
border-radius: var(--r-s); font-size: calc(var(--chat-fs) - 0.5px); text-align: left; color: var(--text);
|
||||
}
|
||||
.ts-head:hover { background: var(--surface-hover); }
|
||||
.ts-ic { width: 14px; flex: none; text-align: center; }
|
||||
@@ -82,15 +88,15 @@
|
||||
.ts-out { margin: 2px 8px 6px 30px; }
|
||||
.ts-out pre {
|
||||
background: var(--code-bg); border-radius: var(--r-s); padding: 8px 10px;
|
||||
font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.5;
|
||||
font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.5;
|
||||
overflow-x: auto; white-space: pre-wrap; word-break: break-all; margin: 0;
|
||||
}
|
||||
.ts-more { font-size: var(--fs-s); color: var(--accent); margin-bottom: 4px; }
|
||||
.ts-more { font-size: var(--chat-fs-s); color: var(--accent); margin-bottom: 4px; }
|
||||
|
||||
/* diff (unified view, red/green backgrounds) */
|
||||
.diff { margin: 2px 6px 6px 22px; border: 1px solid var(--line); border-radius: var(--r-m); overflow: hidden; }
|
||||
.diff-path { padding: 4px 10px; font-size: var(--fs-s); color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--line); font-family: var(--font-mono); }
|
||||
.diff-pre { margin: 0; padding: 6px 0; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.5; overflow-x: auto; }
|
||||
.diff-path { padding: 4px 10px; font-size: var(--chat-code-fs); color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--line); font-family: var(--font-mono); }
|
||||
.diff-pre { margin: 0; padding: 6px 0; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.5; overflow-x: auto; }
|
||||
.dh-head { display: block; color: var(--muted); padding: 0 10px; }
|
||||
.dl { display: block; padding: 0 10px; white-space: pre-wrap; word-break: break-all; }
|
||||
.dl.add { background: var(--add-bg); }
|
||||
@@ -104,29 +110,29 @@
|
||||
.card.ask { border: 1px solid color-mix(in oklab, var(--info) 45%, var(--bg)); }
|
||||
.card.ask.done { border-color: var(--line); opacity: .75; }
|
||||
.err-card { border: 1px solid color-mix(in oklab, var(--danger) 45%, var(--bg)); }
|
||||
.err-line { color: var(--danger); font-size: var(--fs-m); }
|
||||
.perm-title { font-size: var(--fs-m); font-weight: 500; }
|
||||
.err-line { color: var(--danger); font-size: var(--chat-fs); }
|
||||
.perm-title { font-size: var(--chat-fs); font-weight: 500; }
|
||||
.perm-cmd {
|
||||
margin: 8px 0 0; background: var(--code-bg); border-radius: var(--r-s); padding: 8px 10px;
|
||||
font-family: var(--font-mono); font-size: var(--fs-s); white-space: pre-wrap; word-break: break-all;
|
||||
font-family: var(--font-mono); font-size: var(--chat-code-fs); white-space: pre-wrap; word-break: break-all;
|
||||
}
|
||||
.perm-path { margin-top: 6px; font-family: var(--font-mono); font-size: var(--fs-s); color: var(--muted); }
|
||||
.perm-path { margin-top: 6px; font-family: var(--font-mono); font-size: var(--chat-code-fs); color: var(--muted); }
|
||||
.perm-btns { display: flex; gap: 8px; margin-top: 10px; }
|
||||
.perm-done { margin-top: 8px; font-size: var(--fs-s); color: var(--muted); }
|
||||
.perm-done { margin-top: 8px; font-size: var(--chat-fs-s); color: var(--muted); }
|
||||
.ask-q { margin-bottom: 10px; }
|
||||
.ask-t { font-size: var(--fs-m); font-weight: 500; margin-bottom: 6px; }
|
||||
.ask-t { font-size: var(--chat-fs); font-weight: 500; margin-bottom: 6px; }
|
||||
.ask-opts { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 6px; }
|
||||
.ask-free { margin-top: 4px; }
|
||||
.ask .btn.primary { margin-top: 4px; }
|
||||
|
||||
/* Notices */
|
||||
.nt { margin: 8px 0; text-align: center; font-size: var(--fs-s); color: var(--muted); }
|
||||
.nt { margin: 8px 0; text-align: center; font-size: var(--chat-fs-s); color: var(--muted); }
|
||||
.nt.warn { color: var(--warn); }
|
||||
.nt.error { color: var(--danger); }
|
||||
|
||||
/* Turn end: small right-aligned text */
|
||||
/* Turn end: "3s · copy · retry" left-aligned under the reply */
|
||||
.te { display: flex; justify-content: flex-start; align-items: center; gap: 2px; margin: 4px 0 18px -6px; font-size: var(--fs-s); color: var(--meta); }
|
||||
.te { display: flex; justify-content: flex-start; align-items: center; gap: 2px; margin: 4px 0 18px -6px; font-size: var(--chat-fs-s); color: var(--meta); }
|
||||
.te-meta { padding: 0 6px; font-variant-numeric: tabular-nums; }
|
||||
.te-act {
|
||||
height: 24px; min-width: 24px; display: inline-flex; align-items: center; justify-content: center; gap: 4px;
|
||||
@@ -155,3 +161,19 @@
|
||||
}
|
||||
.q-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.q-item .ibtn { width: 20px; height: 20px; }
|
||||
|
||||
/* 1.2: local addresses in chat open in the Preview tab (same look as other links, monochrome) */
|
||||
a.ac-local { cursor: pointer; }
|
||||
.ts-out pre a.ac-local, .md pre a.ac-local { color: inherit; text-decoration: underline; text-decoration-color: color-mix(in oklab, currentColor 45%, transparent); text-underline-offset: 2px; }
|
||||
.md code a.ac-local { color: inherit; }
|
||||
|
||||
/* Path chips (Files panel → composer), also in the sent bubble */
|
||||
.mention {
|
||||
display: inline-flex; align-items: center; gap: 4px; max-width: 260px; height: 22px; padding: 0 6px;
|
||||
border-radius: var(--r-s); background: var(--chip-bg); border: 1px solid var(--chip-line); color: var(--pill-fg);
|
||||
font-size: var(--fs-s); font-family: var(--font-mono); white-space: nowrap; vertical-align: middle;
|
||||
}
|
||||
.mention svg { flex: none; }
|
||||
.mention-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.um-mentions { display: flex; flex-wrap: wrap; gap: 4px; margin: 2px 0 4px; white-space: normal; }
|
||||
.um .mention { background: color-mix(in oklab, var(--fg) 5%, var(--accent-soft)); }
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
.cp-ta {
|
||||
width: 100%; border: 0; resize: none; background: none; outline: none; color: var(--text);
|
||||
font-size: var(--fs-l); line-height: 22px; min-height: 34px; max-height: calc(22px * 12); overflow-y: auto;
|
||||
font-size: var(--chat-fs); line-height: calc(var(--chat-fs) * 1.62); min-height: 34px; max-height: calc(var(--chat-fs) * 1.62 * 12); overflow-y: auto;
|
||||
display: block; padding: 0;
|
||||
}
|
||||
.cp-ta::placeholder { color: var(--meta); }
|
||||
@@ -204,3 +204,8 @@
|
||||
@media (max-width: 560px) {
|
||||
.composer { padding: 0 10px 10px; }
|
||||
}
|
||||
|
||||
/* 1.2: drop target while a Files-panel row is dragged over the composer */
|
||||
.cp-card.drop-on { outline: 1.5px dashed var(--cp-focus); outline-offset: 2px; }
|
||||
.cp-drop-hint { padding: 4px 10px 0; font-size: var(--fs-s); color: var(--muted); }
|
||||
.att-bar .mention { height: 24px; }
|
||||
|
||||
@@ -105,6 +105,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
padding: 0 10px; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.tb-menu-btn { display: none; }
|
||||
.tb-menu-btn.tb-sb-collapsed { display: inline-flex; margin-right: 2px; }
|
||||
.tb-crumb { flex: none; max-width: 26%; font-size: var(--fs-m); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tb-sep { flex: none; color: var(--muted); }
|
||||
.tb-title {
|
||||
@@ -134,7 +135,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
|
||||
/* Timeline: content max width 760, centered */
|
||||
.scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; position: relative; }
|
||||
/* Conversation and composer share one 720px column */
|
||||
/* 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; }
|
||||
|
||||
/* ↓ jump-to-bottom button */
|
||||
@@ -144,6 +145,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
display: flex; align-items: center; justify-content: center; color: var(--muted); z-index: 5;
|
||||
}
|
||||
.jump:hover { color: var(--fg); }
|
||||
.jump svg { transform: rotate(90deg); }
|
||||
.jump .jd { position: absolute; top: 4px; right: 4px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); }
|
||||
|
||||
/* ---- right panel ---- */
|
||||
@@ -218,7 +220,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
.ft-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ft-err { color: var(--danger); font-size: var(--fs-s); padding: 2px 0; }
|
||||
.ft-view { flex: 1; min-height: 0; overflow: auto; border-top: 1px solid var(--line); }
|
||||
.ft-pre { margin: 0; padding: 10px 12px; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.55; }
|
||||
.ft-pre { margin: 0; padding: 10px 12px; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.55; }
|
||||
.ft-pre code { background: none; padding: 0; display: block; white-space: pre; }
|
||||
|
||||
/* Terminal panel */
|
||||
@@ -263,9 +265,17 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
|
||||
/* Wide screens: Ctrl+B hides the whole column / Ctrl+J hides the panel */
|
||||
@media (min-width: 760px) {
|
||||
.sidebar.w-hide { display: none; }
|
||||
/* collapse slides the column out (quick, and none with reduced motion); hidden afterwards so it can't take focus */
|
||||
.sidebar { transition: margin-left var(--dur-2) var(--ease), visibility 0s linear 0s; }
|
||||
.sidebar.w-hide {
|
||||
margin-left: calc(-1 * var(--sb-w, 248px)); visibility: hidden;
|
||||
transition: margin-left var(--dur-2) var(--ease), visibility 0s linear var(--dur-2);
|
||||
}
|
||||
.sidebar.w-hide + .rs-l { display: none; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .sidebar, .sidebar.w-hide { transition: none; } }
|
||||
.sb-row .sb-toggle { flex: none; color: var(--muted); }
|
||||
.sb-toggle:hover { color: var(--fg); }
|
||||
@media (min-width: 900px) {
|
||||
.panel.w-hide { display: none; }
|
||||
}
|
||||
@@ -311,3 +321,30 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; }
|
||||
.cpal-item.on { background: var(--surface-hover); }
|
||||
.cpal-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cpal-hint { flex: none; font-size: var(--fs-s); color: var(--muted); }
|
||||
|
||||
/* ---- 1.2 Preview tab ---- */
|
||||
.pv { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.pv-bar { flex: none; display: flex; align-items: center; gap: 2px; height: 38px; padding: 0 6px; border-bottom: 1px solid var(--line); }
|
||||
.pv-bar .ibtn { width: 26px; height: 26px; flex: none; color: var(--muted); }
|
||||
.pv-bar .ibtn:hover:not(:disabled) { color: var(--fg); }
|
||||
.pv-bar .ibtn:disabled { opacity: .35; cursor: default; }
|
||||
.pv-addr {
|
||||
flex: 1; min-width: 0; height: 26px; padding: 0 8px; margin: 0 2px; border-radius: var(--r-s);
|
||||
background: var(--search-bg); border: 1px solid transparent; color: var(--fg);
|
||||
font-family: var(--font-mono); font-size: var(--fs-s); outline: none;
|
||||
}
|
||||
.pv-addr:focus { border-color: var(--cp-focus); background: var(--bg); }
|
||||
.pv-addr.err { border-color: color-mix(in oklab, var(--danger) 60%, var(--bg)); }
|
||||
.pv-note { flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 10px; font-size: var(--fs-s); color: var(--muted); border-bottom: 1px solid var(--line); }
|
||||
.pv-note.err { color: var(--danger); }
|
||||
.pv-note .btn { height: 24px; font-size: var(--fs-s); }
|
||||
.pv-frame-wrap { flex: 1; min-height: 0; position: relative; background: var(--bg); }
|
||||
.pv-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #fff; }
|
||||
.pv-loading { position: absolute; top: 0; left: 0; right: 0; height: 2px; background: var(--accent-2); opacity: .5; animation: breathe 1s infinite; }
|
||||
.pv-empty { padding: 28px 22px; color: var(--muted); font-size: var(--fs-m); text-align: center; line-height: 1.7; }
|
||||
.pv-empty code { font-family: var(--font-mono); font-size: var(--fs-s); background: var(--code-bg); border: 1px solid var(--code-line); border-radius: 4px; padding: 0 4px; color: var(--code-fg); }
|
||||
.pv-hint { margin-top: 10px; font-size: var(--fs-s); color: var(--meta); }
|
||||
|
||||
/* Files panel rows can be dragged into the composer */
|
||||
.ft-row[draggable="true"] { cursor: default; }
|
||||
.ft-row.dragging { opacity: .5; }
|
||||
|
||||
@@ -38,6 +38,12 @@
|
||||
--fs-hero: 18px;
|
||||
--lh: 1.6;
|
||||
--col: 720px;
|
||||
/* Chat text size (Settings → Chat font size, 12–18, default 13): timeline, composer, tool output, diffs.
|
||||
Code is 1px smaller, secondary rows (tool steps, thinking, notices) 1px smaller but never under 12px. */
|
||||
--chat-fs: 13px;
|
||||
--chat-fs-s: max(12px, calc(var(--chat-fs) - 1px));
|
||||
--chat-code-fs: max(11.5px, calc(var(--chat-fs) - 1px));
|
||||
--chat-lh: 1.7;
|
||||
--row: 26px;
|
||||
--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .16), 0 0 0 1px var(--line);
|
||||
--term-bg: #ffffff;
|
||||
|
||||
@@ -12,7 +12,7 @@ export type ToolStep = {
|
||||
};
|
||||
|
||||
export type DisplayItem =
|
||||
| { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; steered?: boolean; ts: number }
|
||||
| { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; mentions?: { path: string; isDir: boolean }[]; steered?: boolean; ts: number }
|
||||
| { kind: "assistant"; key: string; itemId: string; text: string; streaming: boolean }
|
||||
| { kind: "reasoning"; key: string; itemId: string; text: string; streaming: boolean }
|
||||
| { kind: "toolgroup"; key: string; steps: ToolStep[] }
|
||||
@@ -164,7 +164,7 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
case "user_message":
|
||||
breakGroup(st);
|
||||
st.lastUserIdx.set(ev.turnId ?? "", st.items.length);
|
||||
st.items.push({ kind: "user", key: `u:${ev.seq}`, text: ev.text, attachments: ev.attachments, steered: ev.steered, ts: ev.ts });
|
||||
st.items.push({ kind: "user", key: `u:${ev.seq}`, text: ev.text, attachments: ev.attachments, ...(ev.mentions?.length ? { mentions: ev.mentions } : {}), steered: ev.steered, ts: ev.ts });
|
||||
return;
|
||||
case "assistant_delta":
|
||||
applyDelta(st, ev.itemId, "assistant", ev.text);
|
||||
|
||||
@@ -9,7 +9,7 @@ export type AttachmentRef = { id: string; name: string; mime: string };
|
||||
export type PermissionOption = { id: string; label: string; kind: "allow_once" | "allow_always" | "reject_once" };
|
||||
|
||||
export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId: string; type: "turn_started"; model: string | null; mode: string; effort: string | null }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_delta" | "reasoning_delta" | "tool_output_delta"; itemId: string; text: string }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_message" | "reasoning"; itemId: string; text: string }
|
||||
|
||||
@@ -16,6 +16,8 @@ export type ThreadMeta = {
|
||||
seq: number;
|
||||
cursorFast?: boolean;
|
||||
cursorAutoReview?: boolean;
|
||||
/** 1.2: last Preview tab URL (target, not proxy) */
|
||||
previewUrl?: string | null;
|
||||
};
|
||||
|
||||
export type Capabilities = {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Local addresses in chat text (1.2): localhost:3000, http://127.0.0.1:5173/x, 0.0.0.0:8080, [::1]:4000, app.localhost:3000.
|
||||
// Pure functions (unit tested) plus a DOM pass for rendered Markdown. A bare host needs a port to count
|
||||
// ("runs on localhost" stays text); trailing punctuation (English and Chinese) is left out; LAN addresses (192.168.x, 10.x)
|
||||
// are not local and stay ordinary external links.
|
||||
import { checkPreviewUrl } from "../../../daemon/src/preview/url.js";
|
||||
|
||||
export type LocalLink = { start: number; end: number; text: string; url: string };
|
||||
|
||||
const HOST = String.raw`(?:localhost|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1?\])`;
|
||||
const RE = new RegExp(String.raw`(https?:\/\/)?${HOST}(:\d{1,5})?((?:[/?#][^\s<>"'\`)】」』,。;!?、]*)?)`, "gi");
|
||||
const TRAIL = /[.,;:!?。,;:!?…'"’”]+$/;
|
||||
|
||||
export function findLocalLinks(text: string): LocalLink[] {
|
||||
const out: LocalLink[] = [];
|
||||
if (!text) return out;
|
||||
RE.lastIndex = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = RE.exec(text))) {
|
||||
let start = m.index;
|
||||
let raw = m[0];
|
||||
const scheme = m[1];
|
||||
const port = m[2];
|
||||
// Must not be part of a longer word / host / path (xlocalhost:1, foo/localhost:1, user@localhost:1)
|
||||
const before = start > 0 ? text[start - 1]! : "";
|
||||
if (before && /[\w.@/\\:-]/.test(before)) continue;
|
||||
if (!scheme && !port) continue;
|
||||
// Drop trailing punctuation, and a closing bracket that has no opening one inside the match
|
||||
let trimmed = raw.replace(TRAIL, "");
|
||||
while (/[)\]]$/.test(trimmed)) {
|
||||
const close = trimmed.endsWith(")") ? ")" : "]";
|
||||
const open = close === ")" ? "(" : "[";
|
||||
const opens = trimmed.split(open).length - 1;
|
||||
const closes = trimmed.split(close).length - 1;
|
||||
if (closes > opens) trimmed = trimmed.slice(0, -1).replace(TRAIL, "");
|
||||
else break;
|
||||
}
|
||||
raw = trimmed;
|
||||
const c = checkPreviewUrl(raw);
|
||||
if (!c.ok) continue;
|
||||
out.push({ start, end: start + raw.length, text: raw, url: c.target.href });
|
||||
RE.lastIndex = start + Math.max(1, raw.length);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Text → alternating plain strings and links (for React rendering without innerHTML) */
|
||||
export function splitLocalLinks(text: string): (string | LocalLink)[] {
|
||||
const links = findLocalLinks(text);
|
||||
if (!links.length) return [text];
|
||||
const parts: (string | LocalLink)[] = [];
|
||||
let at = 0;
|
||||
for (const l of links) {
|
||||
if (l.start > at) parts.push(text.slice(at, l.start));
|
||||
parts.push(l);
|
||||
at = l.end;
|
||||
}
|
||||
if (at < text.length) parts.push(text.slice(at));
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** Is this href a local address the preview can open? → its normalized URL */
|
||||
export function localHref(href: string | null | undefined): string | null {
|
||||
if (!href || !/^https?:\/\//i.test(href)) return null;
|
||||
const c = checkPreviewUrl(href);
|
||||
return c.ok ? c.target.href : null;
|
||||
}
|
||||
|
||||
const SKIP = new Set(["A", "BUTTON", "SCRIPT", "STYLE", "TEXTAREA"]);
|
||||
|
||||
function textNodesUnder(root: Node): Text[] {
|
||||
const out: Text[] = [];
|
||||
const walk = (n: Node) => {
|
||||
if (n.nodeType === 3) { out.push(n as Text); return; }
|
||||
if (n.nodeType !== 1) return;
|
||||
if (SKIP.has((n as Element).tagName)) return;
|
||||
for (let c = n.firstChild; c; c = c.nextSibling) walk(c);
|
||||
};
|
||||
walk(root);
|
||||
return out;
|
||||
}
|
||||
|
||||
function wrapLinks(root: Node, nodes: Text[]): void {
|
||||
const full = nodes.map((n) => n.data).join("");
|
||||
const links = findLocalLinks(full);
|
||||
if (!links.length) return;
|
||||
// offsets → (node, offset)
|
||||
const starts: number[] = [];
|
||||
let acc = 0;
|
||||
for (const n of nodes) { starts.push(acc); acc += n.data.length; }
|
||||
const locate = (pos: number, end: boolean): [Text, number] => {
|
||||
for (let i = nodes.length - 1; i >= 0; i--) {
|
||||
const s = starts[i]!;
|
||||
if (end ? pos > s : pos >= s) return [nodes[i]!, pos - s];
|
||||
}
|
||||
return [nodes[0]!, 0];
|
||||
};
|
||||
const doc = root.ownerDocument ?? document;
|
||||
// Back to front so earlier offsets stay valid
|
||||
for (const l of [...links].reverse()) {
|
||||
const [sn, so] = locate(l.start, false);
|
||||
const [en, eo] = locate(l.end, true);
|
||||
const range = doc.createRange();
|
||||
range.setStart(sn, so);
|
||||
range.setEnd(en, eo);
|
||||
const a = doc.createElement("a");
|
||||
a.href = l.url;
|
||||
a.dataset.acLocal = l.url;
|
||||
a.className = "ac-local";
|
||||
a.appendChild(range.extractContents());
|
||||
range.insertNode(a);
|
||||
}
|
||||
}
|
||||
|
||||
/** Rendered Markdown: mark local <a href> links, and turn bare local addresses into links (code blocks too, across hljs spans) */
|
||||
export function linkifyLocal(root: HTMLElement, title?: string): void {
|
||||
for (const a of Array.from(root.querySelectorAll("a[href]"))) {
|
||||
const u = localHref(a.getAttribute("href"));
|
||||
if (u) { (a as HTMLElement).dataset.acLocal = u; a.classList.add("ac-local"); }
|
||||
}
|
||||
// Code blocks: one pass over the whole block (a URL may be split across highlight spans)
|
||||
for (const pre of Array.from(root.querySelectorAll("pre"))) {
|
||||
if ((pre as HTMLElement).dataset.acLinked) continue;
|
||||
(pre as HTMLElement).dataset.acLinked = "1";
|
||||
wrapLinks(pre, textNodesUnder(pre));
|
||||
}
|
||||
// Everything else: per text node
|
||||
for (const n of textNodesUnder(root)) {
|
||||
if (n.parentElement?.closest("pre")) continue;
|
||||
if (!n.parentNode) continue;
|
||||
wrapLinks(n.parentNode, [n]);
|
||||
}
|
||||
if (title) for (const a of Array.from(root.querySelectorAll("a.ac-local"))) (a as HTMLElement).title = title;
|
||||
}
|
||||
Reference in New Issue
Block a user