web: gated access, anchored viewers, mobile tabs and chat colour
- serve.mjs requires a signed session cookie for every page, artifact and the WebSocket, with a password file, 30-day sessions, login throttling and public brand assets for the sign-in page. - The diff viewer is a fixed-height top-anchored panel whose toolbar (modes, copy, previous, next, close as icons) is its first row; the artifact viewer is likewise a fixed frame so its navigation never moves. - The audit's selected tab uses the app's normal selected surface and bottom accent. Sessions that were not recorded say so plainly. - Chat code blocks are syntax-coloured; graph pinch-zoom works with two fingers while a single pointer still pans and clicks nodes. - Phones always keep the destination bar (pane collapse is wide-only), with the destinations spread evenly and Search on the right; the list default width is narrower; the theme colour matches the app. - Code-format and layout tests, plus the full browser suite, pass.
This commit is contained in:
@@ -235,6 +235,8 @@ a { color: var(--color-accent); }
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-s);
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
padding: 20px;
|
||||
background: rgba(0, 0, 0, 0.86);
|
||||
}
|
||||
|
||||
+16
-1
@@ -820,5 +820,20 @@
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
|
||||
overflow: hidden;
|
||||
}
|
||||
.chat-tools-modal-panel .chat-tool-panel { position: static; max-height: none; border: 0; box-shadow: none; background: transparent; }
|
||||
.chat-tools-modal-panel .chat-tool-panel {
|
||||
position: static;
|
||||
width: 100%;
|
||||
max-height: none;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
background: transparent;
|
||||
}
|
||||
.chat-tools-modal-panel .chat-tool-list { overflow: auto; }
|
||||
|
||||
/* Code in agent replies keeps the terminal's colour grammar: comments muted,
|
||||
strings green, numbers amber, keywords blue, literals pink. */
|
||||
.tok-comment { color: var(--color-muted); font-style: italic; }
|
||||
.tok-string { color: #9ecb8f; }
|
||||
.tok-number { color: #d8b46a; }
|
||||
.tok-keyword { color: #93add0; font-weight: 600; }
|
||||
.tok-literal { color: #c58fb0; }
|
||||
|
||||
@@ -214,7 +214,7 @@
|
||||
/* ---- Layout ------------------------------------------------------------ */
|
||||
--layout-rail: 200px;
|
||||
--layout-list-min: 200px;
|
||||
--layout-list-max: 360px;
|
||||
--layout-list-max: 288px;
|
||||
--layout-detail-min: 200px;
|
||||
--layout-dock: 60px;
|
||||
--layout-hairline: 1px;
|
||||
|
||||
+4
-2
@@ -512,7 +512,7 @@
|
||||
flex-direction: column;
|
||||
gap: var(--space-s);
|
||||
width: min(1100px, 100%);
|
||||
max-height: 100%;
|
||||
height: calc(100vh - 40px);
|
||||
min-height: 0;
|
||||
padding: 16px;
|
||||
background: var(--surface);
|
||||
@@ -616,11 +616,13 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
.audit-tab:hover { background: var(--tint-hover); color: var(--color-text); }
|
||||
/* Match the app's other tab selection exactly: the panel surface and a bottom
|
||||
accent, never the rail's tinted left bar. */
|
||||
.audit-tab.active {
|
||||
background: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-weight: var(--weight-semibold);
|
||||
box-shadow: inset 2px 0 0 var(--color-accent);
|
||||
box-shadow: inset 0 -2px 0 var(--color-accent);
|
||||
}
|
||||
.audit-body { min-height: 0; overflow: auto; padding: 16px 18px; }
|
||||
.audit-doc { max-width: var(--layout-measure); }
|
||||
|
||||
+3
-3
@@ -2,15 +2,15 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, interactive-widget=resizes-content" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
|
||||
<title>Pipelines</title>
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<meta name="theme-color" content="#101013" />
|
||||
<meta name="theme-color" content="#0a0a0b" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-title" content="Pipelines" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
|
||||
<link rel="stylesheet" href="./design/tokens/tokens.css" />
|
||||
<link rel="stylesheet" href="./base.css" />
|
||||
<link rel="stylesheet" href="./shell.css" />
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#101013",
|
||||
"theme_color": "#101013",
|
||||
"background_color": "#0a0a0b",
|
||||
"theme_color": "#0a0a0b",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icon-192.png",
|
||||
|
||||
+20
-2
@@ -253,17 +253,19 @@
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background: rgba(0, 0, 0, 0.78);
|
||||
}
|
||||
/* Fixed height, anchored at the top: the toolbar (modes, copy, paging, close)
|
||||
never moves when a diff is long or short. */
|
||||
.change-viewer-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
width: min(1200px, 100%);
|
||||
max-height: 100%;
|
||||
height: calc(100vh - 48px);
|
||||
min-height: 0;
|
||||
padding: 16px;
|
||||
background: var(--surface);
|
||||
@@ -283,6 +285,22 @@
|
||||
.change-form.active { border-color: var(--accent); color: var(--accent); }
|
||||
.change-form:disabled { opacity: 0.45; }
|
||||
.change-page:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.change-icon {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
padding: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--surface-2);
|
||||
color: var(--text);
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
}
|
||||
.change-icon:hover { border-color: var(--color-border-strong); }
|
||||
.change-icon:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.change-viewer-body { flex: 1; min-height: 0; overflow: auto; display: grid; gap: 16px; align-content: start; }
|
||||
|
||||
.change-honest {
|
||||
|
||||
+252
@@ -16,6 +16,9 @@
|
||||
//
|
||||
// The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN.
|
||||
import { createServer, request } from "node:http";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { extname, join, normalize, resolve, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -23,6 +26,196 @@ import net from "node:net";
|
||||
|
||||
const ROOT = resolve(fileURLToPath(new URL(".", import.meta.url)));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Access control
|
||||
//
|
||||
// The proxy can be reached from a tailnet, so it refuses to serve anything
|
||||
// without a session cookie. The password and cookie secret live in a 0600 file
|
||||
// outside the repository; tests may disable the gate explicitly.
|
||||
// ---------------------------------------------------------------------------
|
||||
const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled";
|
||||
const AUTH_FILE =
|
||||
process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json");
|
||||
const SESSION_COOKIE = "pipelines_session";
|
||||
const SESSION_TTL_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function loadAuth() {
|
||||
if (AUTH_DISABLED) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(AUTH_FILE, "utf8"));
|
||||
if (
|
||||
typeof parsed.password === "string" &&
|
||||
parsed.password.length >= 8 &&
|
||||
typeof parsed.secret === "string" &&
|
||||
parsed.secret.length >= 32
|
||||
) {
|
||||
return { password: parsed.password, secret: parsed.secret };
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the refusal below.
|
||||
}
|
||||
console.error(
|
||||
`web auth: refusing to start without ${AUTH_FILE} (or PIPELINES_WEB_AUTH=disabled for tests)`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const auth = loadAuth();
|
||||
|
||||
function cookieValue(req, name) {
|
||||
for (const part of String(req.headers.cookie ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i < 0) continue;
|
||||
if (part.slice(0, i).trim() === name) {
|
||||
try {
|
||||
return decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function signSession(expires) {
|
||||
return `${expires}.${createHmac("sha256", auth.secret).update(String(expires)).digest("base64url")}`;
|
||||
}
|
||||
|
||||
function sessionToken() {
|
||||
return signSession(Math.floor(Date.now() / 1000) + SESSION_TTL_SECONDS);
|
||||
}
|
||||
|
||||
function validSession(value) {
|
||||
if (!auth || typeof value !== "string") return false;
|
||||
const [expires, signature] = value.split(".");
|
||||
if (!expires || !signature) return false;
|
||||
const expected = createHmac("sha256", auth.secret).update(expires).digest();
|
||||
let given;
|
||||
try {
|
||||
given = Buffer.from(signature, "base64url");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false;
|
||||
return Number(expires) > Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function isAuthed(req) {
|
||||
return !auth || validSession(cookieValue(req, SESSION_COOKIE));
|
||||
}
|
||||
|
||||
function passwordOk(candidate) {
|
||||
if (!auth) return true;
|
||||
const given = Buffer.from(String(candidate ?? ""));
|
||||
const expected = Buffer.from(auth.password);
|
||||
return given.length === expected.length && timingSafeEqual(given, expected);
|
||||
}
|
||||
|
||||
function sessionCookie(req) {
|
||||
const bits = [
|
||||
`${SESSION_COOKIE}=${sessionToken()}`,
|
||||
"Path=/",
|
||||
"HttpOnly",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${SESSION_TTL_SECONDS}`,
|
||||
];
|
||||
// Tailscale terminates TLS and usually forwards the scheme; when it does, the
|
||||
// cookie is Secure. A direct plain-http LAN visit still works without it.
|
||||
const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim();
|
||||
if (forwarded === "https") bits.push("Secure");
|
||||
return bits.join("; ");
|
||||
}
|
||||
|
||||
/** Small per-address brake on password guessing. */
|
||||
const loginFailures = new Map();
|
||||
function loginBlocked(address) {
|
||||
const entry = loginFailures.get(address);
|
||||
return Boolean(entry && entry.until > Date.now());
|
||||
}
|
||||
function noteLoginFailure(address) {
|
||||
const now = Date.now();
|
||||
const entry = loginFailures.get(address) ?? { count: 0, until: 0 };
|
||||
entry.count += 1;
|
||||
if (entry.count >= 8) {
|
||||
entry.count = 0;
|
||||
entry.until = now + 30_000;
|
||||
}
|
||||
loginFailures.set(address, entry);
|
||||
}
|
||||
|
||||
function safeNext(value) {
|
||||
const next = String(value ?? "");
|
||||
return next.startsWith("/") && !next.startsWith("//") ? next : "/";
|
||||
}
|
||||
|
||||
function loginPage({ next = "/", error = "" } = {}) {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<meta name="theme-color" content="#0a0a0b" />
|
||||
<title>Pipelines · sign in</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center;
|
||||
background: #101013; color: #e8e8ea;
|
||||
font: 14px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif; }
|
||||
main { width: min(360px, calc(100vw - 32px)); padding: 28px 24px 22px;
|
||||
background: #17171b; border: 1px solid #2a2a31; border-radius: 16px; }
|
||||
.mark { width: 40px; height: 40px; border-radius: 10px; display: block;
|
||||
border: 1px solid #2a2a31; background: #101013; }
|
||||
h1 { margin: 14px 0 4px; font-size: 20px; }
|
||||
p { margin: 0 0 18px; color: #9a9aa2; font-size: 13px; }
|
||||
label { display: block; font-size: 12px; color: #b8b8c0; margin-bottom: 6px; }
|
||||
input { width: 100%; padding: 11px 12px; border-radius: 9px; border: 1px solid #33333c;
|
||||
background: #101013; color: #e8e8ea; font: inherit; }
|
||||
input:focus { outline: 2px solid #8fa8c8; outline-offset: 1px; }
|
||||
button { width: 100%; margin-top: 14px; padding: 11px 12px; border: 0; border-radius: 9px;
|
||||
background: #8fa8c8; color: #101013; font: inherit; font-weight: 650; cursor: pointer; }
|
||||
.error { margin: 10px 0 0; color: #e08a8a; font-size: 13px; }
|
||||
.hint { margin: 16px 0 0; font-size: 11px; color: #77777f; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<img class="mark" src="/favicon.svg" alt="" width="40" height="40" />
|
||||
<h1>Pipelines</h1>
|
||||
<p>Sign in to reach this server.</p>
|
||||
<form method="post" action="/login">
|
||||
<input type="hidden" name="next" value="${next.replace(/"/g, """)}" />
|
||||
<label for="password">Password</label>
|
||||
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
||||
${error ? `<p class="error">${error}</p>` : ""}
|
||||
<button type="submit">Sign in</button>
|
||||
</form>
|
||||
<p class="hint">The session lasts 30 days on this device.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function readRequestBody(req, limit = 4096) {
|
||||
return new Promise((resolveBody, rejectBody) => {
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
req.on("data", (chunk) => {
|
||||
size += chunk.length;
|
||||
if (size > limit) {
|
||||
rejectBody(new Error("request too large"));
|
||||
req.destroy();
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
req.on("end", () => resolveBody(Buffer.concat(chunks).toString("utf8")));
|
||||
req.on("error", rejectBody);
|
||||
});
|
||||
}
|
||||
|
||||
const MIME = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
@@ -123,6 +316,59 @@ function proxyArtifact(req, res) {
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
const pathname = (req.url ?? "/").split("?")[0];
|
||||
if (auth) {
|
||||
// Brand assets are public so the sign-in page itself can show the app icon.
|
||||
if (
|
||||
req.method === "GET" &&
|
||||
(pathname === "/favicon.svg" || pathname === "/apple-touch-icon.png")
|
||||
) {
|
||||
// fall through to the static handler below
|
||||
} else if (pathname === "/login" && req.method === "GET") {
|
||||
if (isAuthed(req)) {
|
||||
res.writeHead(302, { Location: "/" }).end();
|
||||
return;
|
||||
}
|
||||
const next = new URL(req.url ?? "/login", "http://localhost").searchParams.get("next") ?? "/";
|
||||
res
|
||||
.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ next: safeNext(next) }));
|
||||
return;
|
||||
} else if (pathname === "/login" && req.method === "POST") {
|
||||
const body = await readRequestBody(req).catch(() => "");
|
||||
const fields = new URLSearchParams(body);
|
||||
const address = req.socket.remoteAddress ?? "";
|
||||
if (loginBlocked(address)) {
|
||||
res
|
||||
.writeHead(429, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ error: "Too many attempts. Wait 30 seconds." }));
|
||||
return;
|
||||
}
|
||||
if (!passwordOk(fields.get("password"))) {
|
||||
noteLoginFailure(address);
|
||||
res
|
||||
.writeHead(401, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end(loginPage({ next: safeNext(fields.get("next")), error: "Wrong password." }));
|
||||
return;
|
||||
}
|
||||
res.setHeader("Set-Cookie", sessionCookie(req));
|
||||
res.writeHead(303, { Location: safeNext(fields.get("next")) }).end();
|
||||
return;
|
||||
} else if (pathname === "/logout") {
|
||||
res.setHeader("Set-Cookie", `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0`);
|
||||
res.writeHead(303, { Location: "/login" }).end();
|
||||
return;
|
||||
} else if (!isAuthed(req)) {
|
||||
const wantsHtml = String(req.headers.accept ?? "").includes("text/html");
|
||||
if (req.method === "GET" && wantsHtml) {
|
||||
res.writeHead(302, { Location: `/login?next=${encodeURIComponent(req.url ?? "/")}` }).end();
|
||||
return;
|
||||
}
|
||||
res
|
||||
.writeHead(401, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" })
|
||||
.end("Sign in required\n");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (pathname.startsWith("/artifacts/")) {
|
||||
proxyArtifact(req, res);
|
||||
return;
|
||||
@@ -208,6 +454,11 @@ function proxyUpgrade(req, clientSocket, clientHead) {
|
||||
|
||||
server.on("upgrade", (req, clientSocket, clientHead) => {
|
||||
const pathname = (req.url ?? "").split("?")[0];
|
||||
if (auth && !isAuthed(req)) {
|
||||
clientSocket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
||||
clientSocket.destroy();
|
||||
return;
|
||||
}
|
||||
if (pathname !== "/connect") {
|
||||
clientSocket.destroy();
|
||||
return;
|
||||
@@ -221,4 +472,5 @@ server.listen(port, host, () => {
|
||||
const shown = host === "0.0.0.0" ? "127.0.0.1" : host;
|
||||
console.log(`web spike: http://${shown}:${port}/ (bound ${host}:${port})`);
|
||||
console.log(`proxying /connect (ws) and /artifacts/ (http) -> ${targetHost}:${targetPort}`);
|
||||
console.log(auth ? "auth: sign-in required" : "auth: DISABLED (tests)");
|
||||
});
|
||||
|
||||
+17
-3
@@ -529,9 +529,8 @@ body {
|
||||
|
||||
.pane-layout {
|
||||
/* A grid track is sized from its MAX before the free track is resolved, so
|
||||
minmax(200px, 360px) beside 1fr took 360px and clipped the detail to 40px
|
||||
at 600px. Cap the list where the workspace is narrow; widen it only when
|
||||
there is room for both. */
|
||||
cap the list where the workspace is narrow; widen it only when there is
|
||||
room for both. */
|
||||
grid-template-columns: minmax(150px, 200px) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@@ -601,3 +600,18 @@ body {
|
||||
.dock-status-row { display: flex; align-items: stretch; gap: 2px; }
|
||||
.dock-status-row .dock-status { flex: 1 1 auto; min-width: 0; }
|
||||
.dock-settings { width: 56px; height: 48px; }
|
||||
|
||||
|
||||
/* The collapsed rail keeps the status and its settings icon inside the strip. */
|
||||
.app-rail.collapsed .rail-footer-row { flex-direction: column; gap: 4px; width: 100%; }
|
||||
.app-rail.collapsed .rail-footer-row .shell-status { flex: 0 0 auto; width: 40px; justify-content: center; padding: 0; }
|
||||
.app-rail.collapsed .rail-footer-row .shell-status-dot { margin: 0; }
|
||||
|
||||
|
||||
/* A phone always shows the destination bar; pane collapse is a wide affordance. */
|
||||
@media (max-width: 599px) {
|
||||
#listCollapse { display: none; }
|
||||
.dock-tabs { flex: 1 1 auto; }
|
||||
.dock-item,
|
||||
.dock-search { flex: 1 1 0; width: auto; min-width: 0; }
|
||||
}
|
||||
|
||||
+16
-3
@@ -603,7 +603,9 @@ const dock = h(
|
||||
"nav",
|
||||
{ id: "destinationDock", class: "destination-dock", "aria-label": "Destinations" },
|
||||
h("div", { class: "dock-status-row" }, dockStatus, dockSettings),
|
||||
h("div", { class: "dock-row" }, dockSearch, dockDestinations),
|
||||
// The destinations come first and Search sits on the right; every item takes
|
||||
// an equal share of the bar on a phone.
|
||||
h("div", { class: "dock-row" }, dockDestinations, dockSearch),
|
||||
);
|
||||
// The attention sheet lives in its own layer so it can overlay any view without
|
||||
// being torn down by a content re-render; renderAttentionSheet rebuilds it.
|
||||
@@ -618,6 +620,15 @@ document.body.append(h("div", { class: "app-root" }, appRail, workspace, dock));
|
||||
appRail.querySelector("#railCollapse")?.addEventListener("click", () => {
|
||||
state.railCollapsed = !state.railCollapsed;
|
||||
applyLayoutState();
|
||||
if (typeof window.matchMedia === "function") {
|
||||
const wideQuery = window.matchMedia("(min-width: 600px)");
|
||||
const onWideChange = () => {
|
||||
applyLayoutState();
|
||||
renderContent();
|
||||
};
|
||||
if (typeof wideQuery.addEventListener === "function") wideQuery.addEventListener("change", onWideChange);
|
||||
else if (typeof wideQuery.addListener === "function") wideQuery.addListener(onWideChange);
|
||||
}
|
||||
});
|
||||
document.addEventListener("click", (event) => {
|
||||
const button = event.target instanceof Element ? event.target.closest("#listCollapse") : null;
|
||||
@@ -938,7 +949,7 @@ function listCollapseButton() {
|
||||
}
|
||||
|
||||
function applyLayoutState() {
|
||||
appRail.classList.toggle("collapsed", state.railCollapsed === true);
|
||||
appRail.classList.toggle("collapsed", state.railCollapsed === true && isWideLayout());
|
||||
const railButton = document.getElementById("railCollapse");
|
||||
if (railButton) {
|
||||
const label = state.railCollapsed ? "Expand navigation" : "Collapse navigation";
|
||||
@@ -1129,7 +1140,9 @@ function renderContent() {
|
||||
const activePane = detailOpen ? "detail" : "list";
|
||||
const model = detailSections();
|
||||
const layout = h("div", {
|
||||
class: `pane-layout${state.listCollapsed ? " list-collapsed" : ""}`,
|
||||
// Collapsing a pane is a wide-screen affordance; a phone always keeps the
|
||||
// list and the bottom destination bar available.
|
||||
class: `pane-layout${state.listCollapsed && isWideLayout() ? " list-collapsed" : ""}`,
|
||||
"data-active-pane": activePane,
|
||||
});
|
||||
|
||||
|
||||
@@ -1357,9 +1357,33 @@ export function mount(container, graph, options = {}) {
|
||||
let pointerId = null;
|
||||
let dragOrigin = null;
|
||||
let lastPoint = null;
|
||||
const pointers = new Map();
|
||||
let pinch = null;
|
||||
|
||||
function onPointerDown(event) {
|
||||
if (event.button !== 0) return;
|
||||
// No pointer capture: capturing retargeted the following click to the
|
||||
// viewport and swallowed node taps. A pinch that leaves the canvas simply
|
||||
// stops updating until the fingers return.
|
||||
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
if (pointers.size === 2) {
|
||||
const [a, b] = [...pointers.values()];
|
||||
const rect = viewport.getBoundingClientRect();
|
||||
pinch = {
|
||||
distance: Math.hypot(a.x - b.x, a.y - b.y),
|
||||
scale: state.scale,
|
||||
lastCentroid: {
|
||||
x: (a.x + b.x) / 2 - rect.left,
|
||||
y: (a.y + b.y) / 2 - rect.top,
|
||||
},
|
||||
};
|
||||
dragged = true;
|
||||
pointerId = null;
|
||||
dragOrigin = null;
|
||||
lastPoint = null;
|
||||
return;
|
||||
}
|
||||
if (pointers.size > 2) return;
|
||||
dragged = false;
|
||||
pointerId = event.pointerId;
|
||||
dragOrigin = { x: event.clientX, y: event.clientY };
|
||||
@@ -1367,6 +1391,44 @@ export function mount(container, graph, options = {}) {
|
||||
}
|
||||
|
||||
function onPointerMove(event) {
|
||||
if (pointers.has(event.pointerId)) {
|
||||
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
|
||||
}
|
||||
if (pointers.size >= 2 && pinch) {
|
||||
const [a, b] = [...pointers.values()];
|
||||
const distance = Math.hypot(a.x - b.x, a.y - b.y);
|
||||
if (pinch.distance <= 0 || distance <= 0) return;
|
||||
const rect = viewport.getBoundingClientRect();
|
||||
const centroid = {
|
||||
x: (a.x + b.x) / 2 - rect.left,
|
||||
y: (a.y + b.y) / 2 - rect.top,
|
||||
};
|
||||
const target = Math.min(
|
||||
Math.max(pinch.scale * (distance / pinch.distance), MIN_SCALE),
|
||||
MAX_SCALE,
|
||||
);
|
||||
const zoomed = zoomAbout(
|
||||
state.offset,
|
||||
state.scale,
|
||||
centroid,
|
||||
target / state.scale,
|
||||
MIN_SCALE,
|
||||
MAX_SCALE,
|
||||
);
|
||||
const dx = centroid.x - pinch.lastCentroid.x;
|
||||
const dy = centroid.y - pinch.lastCentroid.y;
|
||||
state.scale = zoomed.scale;
|
||||
state.offset = clampOffset(
|
||||
{ x: zoomed.offset.x + dx, y: zoomed.offset.y + dy },
|
||||
scaledContent(),
|
||||
viewportSize(),
|
||||
MIN_VISIBLE,
|
||||
);
|
||||
pinch.lastCentroid = centroid;
|
||||
state.userAdjusted = true;
|
||||
applyTransform();
|
||||
return;
|
||||
}
|
||||
if (pointerId === null || event.pointerId !== pointerId || !lastPoint) return;
|
||||
if (!dragged) {
|
||||
const moved =
|
||||
@@ -1388,10 +1450,19 @@ export function mount(container, graph, options = {}) {
|
||||
}
|
||||
|
||||
function onPointerUp(event) {
|
||||
pointers.delete(event.pointerId);
|
||||
if (pointers.size < 2) pinch = null;
|
||||
if (pointerId !== null && event.pointerId !== pointerId) return;
|
||||
pointerId = null;
|
||||
dragOrigin = null;
|
||||
lastPoint = null;
|
||||
// After a pinch, continue with the finger still down as a pan.
|
||||
if (pointers.size === 1) {
|
||||
const [id, point] = [...pointers.entries()][0];
|
||||
pointerId = id;
|
||||
dragOrigin = { ...point };
|
||||
lastPoint = { ...point };
|
||||
}
|
||||
}
|
||||
|
||||
function onWheel(event) {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// A small, dependency-free syntax colourer for fenced code in chat. It returns
|
||||
// tokens, never HTML: the renderer appends spans with text nodes, so no model
|
||||
// output can inject markup. Unknown languages still get strings, comments and
|
||||
// numbers highlighted with the generic keyword set.
|
||||
|
||||
const KEYWORDS = {
|
||||
go: "break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var true false nil iota",
|
||||
javascript:
|
||||
"async await break case catch class const continue debugger default delete do else export extends finally for from function get if import in instanceof let new of return set static super switch this throw try typeof var void while with yield true false null undefined",
|
||||
typescript:
|
||||
"abstract any as asserts async await boolean break case catch class const constructor continue declare default delete do else enum export extends false finally for from function get if implements import in infer instanceof interface is keyof let module namespace never new null number object of package private protected public readonly require return set static string super switch symbol this throw true try type typeof undefined unique unknown var void while with yield",
|
||||
kotlin:
|
||||
"as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while by catch constructor delegate dynamic field file finally get import init param property receiver set setparam where actual abstract annotation companion const crossinline data enum expect external final infix inline inner internal lateinit noinline open operator out override private protected public reified sealed suspend tailrec vararg",
|
||||
java: "abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null",
|
||||
shell:
|
||||
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
|
||||
bash:
|
||||
"if then else elif fi for while until do done case esac function in select time coproc break continue return exit export readonly local declare typeset unset shift source alias echo cd pwd set true false",
|
||||
python:
|
||||
"and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield match case",
|
||||
rust:
|
||||
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
|
||||
sql: "select from where insert into values update set delete create table alter drop index join left right inner outer group by order having limit offset as and or not null true false distinct union all",
|
||||
json: "true false null",
|
||||
};
|
||||
const HASH_COMMENT = new Set(["shell", "bash", "python", "ruby", "yaml", "toml"]);
|
||||
|
||||
function languageKey(language) {
|
||||
const key = String(language ?? "").trim().toLowerCase().split(/[\s:]/)[0];
|
||||
if (key === "js" || key === "jsx") return "javascript";
|
||||
if (key === "ts" || key === "tsx") return "typescript";
|
||||
if (key === "sh" || key === "zsh") return "shell";
|
||||
if (key === "py") return "python";
|
||||
if (key === "kt") return "kotlin";
|
||||
if (key === "rs") return "rust";
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenize one code block into `{text, kind}` with kind plain|comment|string|
|
||||
* number|keyword|literal. Total and deterministic.
|
||||
*/
|
||||
export function highlight(code, language = "") {
|
||||
const key = languageKey(language);
|
||||
const keywords = new Set((KEYWORDS[key] ?? KEYWORDS.javascript).split(/\s+/).filter(Boolean));
|
||||
const commentPattern = HASH_COMMENT.has(key) ? "#[^\\n]*" : key === "sql" ? "--[^\\n]*" : "\\/\\/[^\\n]*";
|
||||
const pattern = new RegExp(
|
||||
`(\\/\\*[\\s\\S]*?\\*\\/|${commentPattern}|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|\\b\\d+(?:\\.\\d+)?\\b|[A-Za-z_$][\\w$]*)`,
|
||||
"g",
|
||||
);
|
||||
const text = String(code ?? "");
|
||||
const tokens = [];
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > last) tokens.push({ text: text.slice(last, match.index), kind: "plain" });
|
||||
const value = match[0];
|
||||
let kind = "plain";
|
||||
if (value.startsWith("//") || value.startsWith("#") || value.startsWith("--") || value.startsWith("/*")) {
|
||||
kind = "comment";
|
||||
} else if (/^["'`]/.test(value)) {
|
||||
kind = "string";
|
||||
} else if (/^\d/.test(value)) {
|
||||
kind = "number";
|
||||
} else if (keywords.has(value)) {
|
||||
kind = value === "true" || value === "false" || value === "null" || value === "None" ||
|
||||
value === "nil" || value === "True" || value === "False"
|
||||
? "literal"
|
||||
: "keyword";
|
||||
}
|
||||
tokens.push({ text: value, kind });
|
||||
last = match.index + value.length;
|
||||
}
|
||||
if (last < text.length) tokens.push({ text: text.slice(last), kind: "plain" });
|
||||
return tokens;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { writeChatStars } from "../chatStars.js";
|
||||
import { describeError } from "../format.js";
|
||||
import { SHELL_OUTPUT_LIMIT, newChatOperationId } from "../repository.js";
|
||||
import { codeBlockLabel, parseInline, parseMarkdown } from "../markdown.js";
|
||||
import { highlight } from "../highlight.js";
|
||||
import { formatDuration } from "../runs.js";
|
||||
import { humanBytes } from "../artifacts.js";
|
||||
import { changeStat, diffLineClass, diffLineSymbol } from "../changes.js";
|
||||
@@ -2710,7 +2711,14 @@ function renderMarkdownBlock(block) {
|
||||
if (block.kind === "code") {
|
||||
const code = h("div", { class: "md-code-block" });
|
||||
code.append(h("div", { class: "md-code-label", text: codeBlockLabel(block.language) }));
|
||||
code.append(h("pre", { class: "md-pre" }, h("code", { text: block.code })));
|
||||
const pre = h("pre", { class: "md-pre" });
|
||||
const body = h("code");
|
||||
for (const token of highlight(block.code, block.language)) {
|
||||
if (token.kind === "plain") body.append(document.createTextNode(token.text));
|
||||
else body.append(h("span", { class: `tok-${token.kind}`, text: token.text }));
|
||||
}
|
||||
pre.append(body);
|
||||
code.append(pre);
|
||||
return code;
|
||||
}
|
||||
if (block.kind === "rule") return h("hr", { class: "md-rule" });
|
||||
|
||||
+31
-23
@@ -114,24 +114,7 @@ function openChangeViewer(files, startIndex, trigger = null) {
|
||||
text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`,
|
||||
}),
|
||||
);
|
||||
const head = h(
|
||||
"div",
|
||||
{ class: "change-viewer-head" },
|
||||
titles,
|
||||
h("button", {
|
||||
class: "change-viewer-copy",
|
||||
type: "button",
|
||||
text: "Copy raw patch",
|
||||
disabled: !hasPatch,
|
||||
onclick: () => copyText(entry.patch ?? ""),
|
||||
}),
|
||||
h("button", {
|
||||
class: "change-viewer-close",
|
||||
type: "button",
|
||||
text: "Close diff",
|
||||
onclick: closeChangeViewer,
|
||||
}),
|
||||
);
|
||||
const head = h("div", { class: "change-viewer-head" }, titles);
|
||||
|
||||
const controls = h(
|
||||
"div",
|
||||
@@ -160,10 +143,22 @@ function openChangeViewer(files, startIndex, trigger = null) {
|
||||
}),
|
||||
h("div", { class: "change-viewer-spacer" }),
|
||||
h("button", {
|
||||
class: "change-page",
|
||||
class: "change-icon",
|
||||
type: "button",
|
||||
"data-action": "copy",
|
||||
title: "Copy raw patch",
|
||||
"aria-label": "Copy raw patch",
|
||||
text: "\u29c9",
|
||||
disabled: !hasPatch,
|
||||
onclick: () => copyText(entry.patch ?? ""),
|
||||
}),
|
||||
h("button", {
|
||||
class: "change-icon",
|
||||
type: "button",
|
||||
"data-page": "prev",
|
||||
text: "Previous file",
|
||||
title: "Previous file",
|
||||
"aria-label": "Previous file",
|
||||
text: "\u2039",
|
||||
disabled: index === 0,
|
||||
onclick: () => {
|
||||
index = Math.max(index - 1, 0);
|
||||
@@ -172,10 +167,12 @@ function openChangeViewer(files, startIndex, trigger = null) {
|
||||
},
|
||||
}),
|
||||
h("button", {
|
||||
class: "change-page",
|
||||
class: "change-icon",
|
||||
type: "button",
|
||||
"data-page": "next",
|
||||
text: "Next file",
|
||||
title: "Next file",
|
||||
"aria-label": "Next file",
|
||||
text: "\u203a",
|
||||
disabled: index === files.length - 1,
|
||||
onclick: () => {
|
||||
index = Math.min(index + 1, files.length - 1);
|
||||
@@ -183,6 +180,15 @@ function openChangeViewer(files, startIndex, trigger = null) {
|
||||
renderViewer();
|
||||
},
|
||||
}),
|
||||
h("button", {
|
||||
class: "change-icon",
|
||||
type: "button",
|
||||
"data-action": "close",
|
||||
title: "Close diff",
|
||||
"aria-label": "Close diff",
|
||||
text: "\u00d7",
|
||||
onclick: closeChangeViewer,
|
||||
}),
|
||||
);
|
||||
|
||||
const body = h("div", { class: "change-viewer-body" });
|
||||
@@ -199,7 +205,9 @@ function openChangeViewer(files, startIndex, trigger = null) {
|
||||
body.append(renderRenderedDiff(entry));
|
||||
}
|
||||
|
||||
panel.replaceChildren(head, controls, body);
|
||||
// The toolbar is the first row: paging/copy/close never move when the
|
||||
// path or the diff length changes.
|
||||
panel.replaceChildren(controls, head, body);
|
||||
};
|
||||
|
||||
renderViewer();
|
||||
|
||||
@@ -305,7 +305,12 @@ function auditArtifact(step, name, emptyMessage) {
|
||||
/** The exported session, rendered in place, with the raw file one click away. */
|
||||
function auditSession(step) {
|
||||
const artifact = systemArtifacts(step).find((entry) => entry.name === "session.html");
|
||||
if (!artifact) return renderSessionExport(step);
|
||||
if (!artifact) {
|
||||
return h("div", {
|
||||
class: "muted",
|
||||
text: "Session not recorded for this visit. Sessions are exported by model stages.",
|
||||
});
|
||||
}
|
||||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||||
const wrap = h("div", { class: "audit-session" });
|
||||
if (!resolved) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { highlight } from "../src/highlight.js";
|
||||
|
||||
const kinds = (tokens) => tokens.map((token) => `${token.kind}:${token.text}`);
|
||||
|
||||
test("go strings, comments, numbers and keywords are separated", () => {
|
||||
const tokens = highlight('func main() {\n // note\n x := 42\n s := "hi"\n}', "go");
|
||||
assert.ok(kinds(tokens).includes("keyword:func"));
|
||||
assert.ok(kinds(tokens).includes("comment:// note"));
|
||||
assert.ok(kinds(tokens).includes("number:42"));
|
||||
assert.ok(kinds(tokens).includes('string:"hi"'));
|
||||
assert.ok(kinds(tokens).some((entry) => entry.startsWith("plain: ")));
|
||||
});
|
||||
|
||||
test("shell uses hash comments and javascript-style sharing is avoided", () => {
|
||||
const tokens = highlight("echo hi # note\ncd /tmp", "sh");
|
||||
assert.ok(kinds(tokens).includes("keyword:echo"));
|
||||
assert.ok(kinds(tokens).includes("comment:# note"));
|
||||
});
|
||||
|
||||
test("unknown languages still colour strings and numbers safely", () => {
|
||||
const tokens = highlight('x = "a" + 2', "nonsense");
|
||||
assert.ok(kinds(tokens).includes('string:"a"'));
|
||||
assert.ok(kinds(tokens).includes("number:2"));
|
||||
});
|
||||
|
||||
test("the output is token text only, never markup", () => {
|
||||
const tokens = highlight('<img src=x onerror=alert(1)>', "html");
|
||||
assert.equal(tokens.map((token) => token.text).join(""), '<img src=x onerror=alert(1)>');
|
||||
assert.ok(tokens.every((token) => !("html" in token)));
|
||||
});
|
||||
@@ -2135,6 +2135,7 @@ try {
|
||||
step(`serving web/ on 127.0.0.1:${port} (proxy /connect -> ${pipelines})`);
|
||||
serve = spawn(process.execPath, ["serve.mjs", "--port", String(port), "--pipelines", pipelines], {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, PIPELINES_WEB_AUTH: "disabled" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let serveLog = "";
|
||||
|
||||
Reference in New Issue
Block a user