Files
plugins/packages/agent-console/web/src/main.tsx
T
qingnian108 5703c9f18a agent-console 1.3: reviewed features from #727 and timeline polish (#733)
This carries #727's reviewed part forward, without auto-approve (that comes as its own PR). Permission behaviour is the same as 1.2.

- Windows Git Bash detection, never the WSL System32 bash. It can be overridden in Settings and is passed per spawn only.
- GBK / system code page decoding of raw process output.
- Folded tool steps that don't wrap at ~600px.
- Select-to-quote, and copy/edit under the user bubble.
- Instant send with the echo replacing the bubble in place, and retry when a send fails.
- `/app` heals itself after sleep/wake. `frame-ancestors` is limited to loopback and Magpie's window.
- Grayscale timeline polish: one-line tool rows, a task-list pill, a reply footer and code blocks.
- Test fixes:
  - The `initializing` push is awaited.
  - `afterEach` waits for the thread store's writes.
  - `runtimeInfo().starting` is exposed, and the steer test waits on it.
  - "idle recycling" waits for closed.

Run on mote (macOS) at 65ab7c94:
- `npm ci`, `npm run check` and `build` are ok; `verify:build` gives 5/5 OK.
- Full `vitest run` x5: 4 green (427 passed). One red, "send while running → queued", is a race that is on main too.
  - Cause: `setStatus(idle)` runs before `queue.shift()`.
  - A 300ms pause injected there makes it red 3/3 on main and on this head.
  - Filed on #585 with the cause and the repro.
- Focused send-latency + manager runs: 12/12. `e2e:v1`: 25/25, with no pageerror or console error.
- Broken by hand:
  - With the old steer wait and the mock send held 400ms, the test is red 3/3; the new wait passes 3/3.
  - With `recycleIdle` made a no-op, "idle recycling" goes red.
- Playwright render:
  - Chromium and WebKit × zh/en × light/dark × 1280/420.
  - No gradients, no coloured left borders, no `<select>`, no page errors.
  - At 420 the page scrolls sideways (scrollWidth 480), the same as main.

Not tried: Windows (Git Bash detection, GBK decoding) and a real agent, rather than the mock.
2026-11-05 11:08:38 +08:00

128 lines
5.8 KiB
TypeScript

// 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";
import "./styles/chat.css";
import "./styles/composer.css";
import { createRoot } from "react-dom/client";
import { applyMagpieTokensFromSearch } from "./layout/applyMagpieTokens.js";
import { applyTheme, initTheme } from "./layout/theme.js";
import { startMagpieThemeBridge } from "./layout/magpieBridge.js";
import { applyChatLayout } from "./layout/chatLayout.js";
import { goBackToMagpie, isWrapped, reportLostToWrapper, startWrapperHeartbeat, watchReconnect } from "./api/backToMagpie.js";
import { initLocale, getLocale, setLocale } from "./i18n/index.js";
import { WsClient } from "./api/ws";
import { useConnection } from "./stores/connection";
import { useUi } from "./stores/ui";
import { useData } from "./stores/data";
import { App } from "./App";
import { DebugApp } from "./Debug";
import { getToken } from "./api/token";
const token = getToken();
// Theme: Magpie's ?theme= (or the OS) until the saved setting arrives; an explicit Light/Dark setting then wins (B4)
const params = new URLSearchParams(location.search);
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, usePreview };
void import("./stores/timeline").then((m) => {
(window as unknown as { __tl?: unknown }).__tl = m.useTimeline;
});
ws.onState((s) => useConnection.getState().set({ state: s }));
// Daemon gone for 5s (Magpie restarted the plugin host, or the daemon after sleep) → back through the Magpie page to the gate.
// 1.3: inside the gate's wrapper page the wrapper does that (it survives a reload; this page on its random port doesn't).
const wrapped = isWrapped();
watchReconnect(ws, () => { if (wrapped) reportLostToWrapper(); else goBackToMagpie(); });
if (wrapped) {
startWrapperHeartbeat(ws);
// the first beat as soon as the connection opens, so the wrapper shows this page without waiting for the next tick
ws.onState((s) => { if (s === "open") { try { window.parent.postMessage({ ac_console: "alive" }, "*"); } catch {} } });
}
ws.connect();
ws.waitHello().then(async (h) => {
useConnection.getState().set({ version: (h as { version?: string }).version ?? null });
// Fetch UI preferences (sidebar width / panel / collapsed projects / last opened conversation)
useUi.getState().bind(ws);
try {
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);
});
setInterval(() => ws.ping(), 10000);
const isDebug = params.get("debug") === "1";
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).
if (params.get("audit") === "1") {
setTimeout(() => {
try {
const vw = window.innerWidth;
const docW = document.documentElement.scrollWidth;
const fontSizes = new Set<string>();
const accentEls: string[] = [];
let borders = 0;
const accent = getComputedStyle(document.documentElement).getPropertyValue("--accent").trim();
const inFirstScreen = (r: DOMRect) => r.top < window.innerHeight && r.bottom > 0 && r.width > 0;
document.querySelectorAll("*").forEach((el) => {
const e = el as HTMLElement;
const cs = getComputedStyle(e);
const r = e.getBoundingClientRect();
if (!inFirstScreen(r) || cs.display === "none" || cs.visibility === "hidden") return;
if (r.width < 3 || r.height < 3) return;
fontSizes.add(cs.fontSize);
if (cs.borderTopWidth !== "0px" && cs.borderTopStyle !== "none") borders++;
if (cs.borderBottomWidth !== "0px" && cs.borderBottomStyle !== "none") borders++;
// Accent-colored elements (background or text color equals the resolved --accent)
const bg = cs.backgroundColor, fg = cs.color;
if (accent && (bg === accent || fg === accent)) {
const cls = (e.getAttribute("class") ?? "").split(" ")[0];
if (!accentEls.includes(cls)) accentEls.push(cls);
}
});
const out = {
vw, docW,
noHScroll: docW <= vw + 1,
fontSizes: [...fontSizes].sort(),
bordersFirstScreen: borders,
accentEls,
};
const pre = document.createElement("pre");
pre.id = "audit";
pre.style.display = "none";
pre.textContent = JSON.stringify(out);
document.body.appendChild(pre);
} catch (e) {
const pre = document.createElement("pre");
pre.id = "audit";
pre.textContent = JSON.stringify({ error: String(e) });
document.body.appendChild(pre);
}
}, 1500);
}