Merge remote-tracking branch 'origin/feat/external-request-logs' into HEAD

# Conflicts:
#	deploy/logging/sanitize.vrl
#	public/asset-manifest.json
#	public/script/vendor.min.js
#	src/core/log-record.ts
This commit is contained in:
Thomas Durieux committed 2026-11-29 13:11:41 +00:00
commit cc5e06022f
42 files changed
+4638 -353

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
const { strict: assert } = require("node:assert");
const http = require("node:http");
const { randomUUID } = require("node:crypto");
const { setTimeout } = require("node:timers");
const { Agent } = require("undici");
const got = require("got");
require("ts-node/register/transpile-only");
const { logContext } = require("../src/core/log-context");
const { installExternalRequestLogging, githubEndpoint, externalErrorCode } = require("../src/core/external-request-logging");
const localAgent = new http.Agent({ lookup: (host, options, callback) => lookup(host, options, callback) });
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Resolve every name to the local fixture so requests look like they go to GitHub.
const lookup = (_host, options, callback) => {
if (typeof options === "function") callback = options;
if (options && options.all) callback(null, [{ address: "127.0.0.1", family: 4 }]);
else callback(null, "127.0.0.1", 4);
};
async function captureLogs(run) {
const records = [];
const write = process.stdout.write;
process.stdout.write = function (chunk, ...rest) {
for (const line of String(chunk).split("\n")) {
try { const record = JSON.parse(line); if (record && record.severity) { records.push(record); continue; } } catch { /* not a record */ }
if (line) write.call(process.stdout, line + "\n");
}
const callback = rest.find((arg) => typeof arg === "function");
if (callback) callback();
return true;
};
try { await run(); await wait(50); } finally { process.stdout.write = write; }
return records.filter((record) => record.event === "external_request");
}
describe("external request logging", function () {
this.timeout(10000);
let server, port;
before(async () => {
installExternalRequestLogging();
server = http.createServer((req, res) => {
req.resume();
if (req.url.startsWith("/login/oauth")) { res.writeHead(200, { "content-type": "application/json" }); res.end("{}"); return; }
if (req.url.startsWith("/slow")) return; // never answers
if (req.url.startsWith("/reset")) { req.socket.destroy(); return; }
if (req.url.startsWith("/cut")) { res.writeHead(200, { "content-length": "100" }); res.write("partial"); setTimeout(() => req.socket.destroy(), 20); return; }
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ message: "Not Found" }));
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
port = server.address().port;
});
after(() => new Promise((resolve) => server.close(resolve)));
it("labels GitHub endpoints without owners, repositories, paths or identifiers", () => {
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo/contents/private/notes.md?ref=main"), "/repos/{owner}/{repo}/contents/*");
assert.equal(githubEndpoint("/repos/secret-owner/secret-repo"), "/repos/{owner}/{repo}");
assert.equal(githubEndpoint("/repos/o/r/git/trees/abc123?recursive=1"), "/repos/{owner}/{repo}/git/trees/*");
assert.equal(githubEndpoint("/repos/o/r/pulls/12"), "/repos/{owner}/{repo}/pulls/{id}");
assert.equal(githubEndpoint("/user/repos?per_page=100&page=2"), "/user/repos");
assert.equal(githubEndpoint("/applications/Iv1.client/token"), "/applications/{id}/token");
assert.equal(githubEndpoint("/app/installations/42/access_tokens"), "/app/installations/{id}/access_tokens");
assert.equal(githubEndpoint("/login/oauth/access_token"), "/login/oauth/access_token");
assert.equal(githubEndpoint("/secret-owner/secret-repo.git/info/refs"), "/{id}/{id}/{id}/refs");
});
it("keeps only fixed endpoint labels in the logger and the collector", () => {
const { logRecord } = require("../src/core/log-record");
const { UPSTREAM_ENDPOINT_SEGMENTS } = require("../src/core/log-schema");
const endpoint = (value) => logRecord("info", "external-request", ["external request", { upstreamEndpoint: value }]).upstreamEndpoint;
assert.equal(endpoint("/repos/{owner}/{repo}/contents/*"), "/repos/{owner}/{repo}/contents/*");
assert.equal(endpoint("/repos/secretowner/secretrepo"), undefined);
assert.equal(endpoint("/user/reposx"), undefined);
const vrl = require("node:fs").readFileSync(require("node:path").join(__dirname, "../deploy/logging/sanitize.vrl"), "utf8");
const segments = /record\.upstreamEndpoint\), r'\^\/\(\?:\(\?:([a-z_|]+)\|/.exec(vrl);
assert.ok(segments, "collector rule for upstreamEndpoint");
assert.deepEqual(segments[1].split("|"), UPSTREAM_ENDPOINT_SEGMENTS);
});
it("logs a got request to GitHub with its status and the caller's requestId", async () => {
const requestId = randomUUID();
let status;
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
const response = await got(`http://api.github.com:${port}/repos/secret-owner/secret-repo/contents/private.md?ref=main`,
{ agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
status = response.statusCode;
}));
assert.equal(status, 404);
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].severity, "info");
assert.equal(records[0].requestId, requestId);
assert.equal(records[0].upstreamHost, "api.github.com");
assert.equal(records[0].upstreamMethod, "GET");
assert.equal(records[0].upstreamStatus, 404);
assert.equal(records[0].upstreamEndpoint, "/repos/{owner}/{repo}/contents/*");
assert.equal(typeof records[0].ms, "number");
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
});
it("logs a fetch request (the Octokit transport)", async () => {
const requestId = randomUUID();
const records = await captureLogs(() => logContext.run({ requestId }, async () => {
const response = await globalThis.fetch(`http://github.com:${port}/login/oauth/access_token?code=secret-code`,
{ method: "POST", body: "client_secret=secret", dispatcher: new Agent({ connect: { lookup } }) });
await response.text();
}));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].requestId, requestId);
assert.equal(records[0].upstreamHost, "github.com");
assert.equal(records[0].upstreamMethod, "POST");
assert.equal(records[0].upstreamStatus, 200);
assert.equal(records[0].upstreamEndpoint, "/login/oauth/access_token");
assert.ok(!JSON.stringify(records).includes("secret"), JSON.stringify(records));
});
it("logs a connection failure with its code and no status", async () => {
const closed = http.createServer();
await new Promise((resolve) => closed.listen(0, "127.0.0.1", resolve));
const closedPort = closed.address().port;
await new Promise((resolve) => closed.close(resolve));
const records = await captureLogs(() => got(`http://codeload.github.com:${closedPort}/o/r/zip/main`,
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].upstreamHost, "codeload.github.com");
assert.equal(records[0].errorCode, "ECONNREFUSED");
assert.equal(records[0].upstreamStatus, undefined);
assert.equal(records[0].upstreamEndpoint, undefined);
});
it("logs our own cancellation as ABORT_ERR, not a reset by GitHub", async () => {
const records = await captureLogs(async () => {
const stream = got.stream(`http://api.github.com:${port}/slow`, { agent: { http: localAgent }, retry: 0 });
stream.on("error", () => {});
await wait(50);
stream.destroy();
});
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].errorCode, "ABORT_ERR");
});
it("keeps a code for undici socket errors", async () => {
const records = await captureLogs(() => globalThis.fetch(`http://api.github.com:${port}/reset`,
{ dispatcher: new Agent({ connect: { lookup } }) }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].errorCode, "ECONNRESET");
assert.equal(externalErrorCode({ code: "UND_ERR_HEADERS_TIMEOUT" }), "ETIMEDOUT");
assert.equal(externalErrorCode({ code: "EAI_AGAIN" }), "ENOTFOUND");
assert.equal(externalErrorCode({ code: "SOMETHING_NEW" }), "upstream_error");
assert.equal(externalErrorCode({ name: "AbortError" }), "ABORT_ERR");
});
it("reports a body cut after its headers as a failure, not a 200", async () => {
const records = await captureLogs(() => got(`http://codeload.github.com:${port}/cut`,
{ agent: { http: localAgent }, retry: 0 }).catch(() => undefined));
assert.equal(records.length, 1, JSON.stringify(records));
assert.equal(records[0].upstreamStatus, 200);
assert.equal(records[0].errorCode, "ECONNRESET");
});
it("skips internal hops such as the streamer", async () => {
const records = await captureLogs(async () => {
await got(`http://127.0.0.1:${port}/api/file`, { throwHttpErrors: false, retry: 0 });
await got(`http://streamer:${port}/api/file`, { agent: { http: localAgent }, throwHttpErrors: false, retry: 0 });
});
assert.deepEqual(records, []);
});
});
+9 -2
View File
@@ -29,6 +29,13 @@ function harness(date) {
context.createListeners = () => (target, name, callback) => target.addEventListener(name, callback);
vm.runInNewContext(fs.readFileSync(path.join(__dirname, "../public/script/billing.js"), "utf8").replaceAll("export function", "function"), context);
context.createPageState = parent => Object.create(parent);
context.nextTick = fn => Promise.resolve().then(fn);
context.window.document = context.document;
// Modules the controllers import: outline helpers, the diff parser and the reviewer pages.
for (const name of ["outline.js", "formatters.js", "table-analysis.js", "review-pages.js"]) {
const moduleSource = fs.readFileSync(path.join(__dirname, "../public/script", name), "utf8");
vm.runInNewContext(moduleSource.replace(/^import .*;$/gm, "").replace(/export function/g, "function").replace(/export const/g, "var"), context);
}
const viewerSource = fs.readFileSync(path.join(__dirname, "../public/script/file-viewer.js"), "utf8");
vm.runInNewContext(viewerSource.replace(/^import .*;$/gm, "").replace(/export const/g, "var"), context);
const names = [...source.matchAll(/export const (\w+)/g)].map(match => match[1]);
@@ -358,11 +365,11 @@ describe("frontend production regressions", function () {
request.resolve({ data: { contents: ["title", "MASK", "MASK comment"] } }); await h.flush();
expect(h.scope.anonymizePrContent("Alice")).to.equal("MASK");
});
it("selects the diff tab after asynchronous PR loading", async function () {
it("selects the files tab after asynchronous PR loading when there is no conversation", async function () {
const h = harness(); h.defs.pullRequestController(h.scope, h.http, {}, { pullRequestId: "pr" }, {});
h.requests[0].resolve({ data: {} }); await h.flush();
h.requests[1].resolve({ data: { diff: "patch" } }); await h.flush();
expect(h.scope.tabState.active).to.equal("diff");
expect(h.scope.tabState.active).to.equal("files");
const template = fs.readFileSync(path.join(__dirname, "../public/partials/pullRequest.htm"), "utf8");
expect(template).not.to.include('ng-init="tabState');
});
+85
View File
@@ -0,0 +1,85 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const { default: Gist } = require("../src/core/Gist");
function makeGist(options) {
return new Gist({
gistId: "g-test",
owner: "000000000000000000000001",
source: { gistId: "abc" },
options: { terms: ["Alice"], content: true, title: true, image: true, ...options },
gist: {
description: "By Alice",
files: [
{ filename: "notes-Alice.md", content: "Written by Alice", language: "Markdown", size: 16 },
{ filename: "plot-Alice.png", content: "iVBORw0KGgoAlice==", encoding: "base64", size: 12, type: "image/png" },
{ filename: "paper.pdf", content: "JVBERi0xLjQK", encoding: "base64", size: 9, type: "application/pdf" },
{ filename: "huge.bin", content: "", encoding: "base64", size: 99999999, tooLarge: true },
],
},
});
}
describe("Gist.content() binary files", function () {
it("anonymizes text files and names, passes image bytes through, and never serves other binaries", function () {
const [md, png, pdf, huge] = makeGist().content().files;
expect(md).to.include({ filename: "notes-XXXX-1.md", content: "Written by XXXX-1" });
expect(md).to.not.have.property("encoding");
expect(png).to.include({ filename: "plot-XXXX-1.png", encoding: "base64", content: "iVBORw0KGgoAlice==" });
// A PDF stored by an older version keeps its author metadata: never served.
expect(pdf).to.include({ encoding: "base64" });
expect(pdf.content).to.be.undefined;
expect(huge).to.include({ tooLarge: true, encoding: "base64" });
expect(huge.content).to.be.undefined;
});
it("withholds images unless images are displayed, as for repositories", function () {
for (const image of [false, undefined]) {
const [, png] = makeGist({ image }).content().files;
expect(png.content).to.be.undefined;
expect(png.hidden).to.equal(true);
}
});
});
describe("Gist download of binary files", function () {
const GitHubUtils = require("../src/core/GitHubUtils");
let originalOctokit, originalFetch, fetched;
beforeEach(() => { originalOctokit = GitHubUtils.octokit; originalFetch = global.fetch; fetched = []; });
afterEach(() => { GitHubUtils.octokit = originalOctokit; global.fetch = originalFetch; });
async function download(files, respond) {
GitHubUtils.octokit = () => ({
rest: { gists: { get: async () => ({ data: { files, owner: { login: "alice" } } }) } },
paginate: async () => [],
});
global.fetch = async (url) => { fetched.push(url); return respond(url); };
const gist = makeGist();
gist._model.set = () => {}; gist._model.markModified = () => {};
await gist["downloadContent"]("token");
return Object.fromEntries(gist._gistPayload.files.map((f) => [f.filename, f]));
}
const raw = (name) => `https://gist.githubusercontent.com/alice/abc/raw/1/${name}`;
const ok = (bytes) => ({ ok: true, status: 200, arrayBuffer: async () => bytes });
it("stores images only, within the per-gist budget, and skips unreadable ones", async function () {
const MB = 1024 * 1024;
const files = {
"paper.pdf": { filename: "paper.pdf", size: 10, raw_url: raw("paper.pdf") },
"a.png": { filename: "a.png", size: 3 * MB, raw_url: raw("a.png") },
"b.png": { filename: "b.png", size: 3 * MB, raw_url: raw("b.png") },
"c.png": { filename: "c.png", size: 3 * MB, raw_url: raw("c.png") },
"big.png": { filename: "big.png", size: 5 * MB, raw_url: raw("big.png") },
"gone.png": { filename: "gone.png", size: 10, raw_url: raw("gone.png") },
"elsewhere.png": { filename: "elsewhere.png", size: 10, raw_url: "http://169.254.169.254/x.png" },
};
const stored = await download(files, (url) => url.endsWith("gone.png") ? { ok: false, status: 404 } : ok(new Uint8Array(8)));
expect(fetched.some((u) => u.endsWith("paper.pdf"))).to.equal(false);
expect(fetched.some((u) => u.includes("169.254"))).to.equal(false);
expect(stored["paper.pdf"]).to.include({ encoding: "base64", content: "" });
expect(stored["big.png"].tooLarge).to.equal(true);
// 8 MB budget: two 3 MB images fit, the third does not.
expect(["a.png", "b.png", "c.png"].filter((n) => stored[n].tooLarge)).to.have.length(1);
expect(stored["gone.png"]).to.include({ content: "" });
});
});
+122
View File
@@ -0,0 +1,122 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const { default: PullRequest, reviewThreads, commitMessage } = require("../src/core/PullRequest");
const at = (day) => new Date(`2026-03-${String(day).padStart(2, "0")}T10:00:00Z`);
function makePullRequest(options) {
return new PullRequest({
pullRequestId: "pr-test",
owner: "000000000000000000000001",
anonymizeDate: at(20),
source: { pullRequestId: 12, repositoryFullName: "alice/secret-project" },
options: { terms: ["Alice", "secret-project"], image: true, link: true, ...options },
pullRequest: {
title: "Fix by Alice",
body: "Body",
diff: "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-Alice\n+Bob\n",
state: "open",
author: "Alice",
baseRef: "main",
headRef: "Alice/fix-secret-project",
creationDate: at(1),
updatedDate: at(2),
comments: [],
commits: [
{ message: "First commit by Alice\n\nDetails for secret-project", author: "Alice", date: at(3) },
{ message: "Second", author: "bob", date: at(4) },
],
reviewComments: [
{ commentId: 11, path: "src/Alice.py", line: 4, body: "Why Alice?", author: "bob", creationDate: at(5), updatedDate: at(5) },
{ commentId: 13, inReplyTo: 11, path: "src/Alice.py", line: 4, body: "Because", author: "Alice", creationDate: at(7), updatedDate: at(7) },
{ commentId: 12, path: "README.md", line: 1, body: "Typo", author: "carol", creationDate: at(6), updatedDate: at(6) },
],
},
});
}
const all = { title: true, body: true, comments: true, diff: true, username: true, date: true, origin: false };
describe("PullRequest.content() commits, branches and review threads", function () {
it("anonymizes the author, and shows branch names only with the origin", function () {
const out = makePullRequest(all).content();
expect(out.author).to.equal("XXXX-1");
expect(out).to.not.have.property("baseRef");
expect(out).to.not.have.property("headRef");
const withOrigin = makePullRequest({ ...all, origin: true }).content();
expect(withOrigin.baseRef).to.equal("main");
expect(withOrigin.headRef).to.equal("XXXX-1/fix-XXXX-2");
});
it("strips people from commit messages even without matching terms", function () {
const message = "Merge pull request #3 from asmith/fix-x\n\nFix x <asmith@uni.edu>\n\nSigned-off-by: Ann Smith <ann@uni.edu>\nCo-authored-by: Bo <bo@x.org>\n";
expect(commitMessage(message, { origin: false })).to.equal("Merge pull request #3\n\nFix x");
expect(commitMessage(message, { origin: true })).to.equal("Merge pull request #3 from fix-x\n\nFix x");
expect(commitMessage("Merge branch 'main' of github.com:asmith/repo into dev", { origin: true })).to.equal("Merge branch 'main' into dev");
expect(commitMessage("Merge branch 'asmith/x'", { origin: false })).to.equal("Merge branch");
expect(commitMessage("Plain message", { origin: false })).to.equal("Plain message");
const pr = makePullRequest(all);
pr.model.pullRequest.commits = [{ message: "Merge pull request #3 from asmith/fix\n\nSigned-off-by: Ann Smith <ann@uni.edu>", author: "asmith", date: at(3) }];
expect(pr.content().commits[0].message).to.equal("Merge pull request #3");
});
it("hides the author without the username option", function () {
const out = makePullRequest({ ...all, username: false }).content();
expect(out.author).to.be.undefined;
expect(out.commits[0]).to.not.have.property("author");
expect(out.reviewComments[0].comments[0]).to.not.have.property("author");
});
it("lists commits with anonymized messages and no SHA", function () {
const out = makePullRequest(all).content();
expect(out.commits).to.have.length(2);
expect(out.commits[0].message).to.equal("First commit by XXXX-1\n\nDetails for XXXX-2");
expect(out.commits[0].author).to.equal("XXXX-1");
expect(out.commits[0].date).to.deep.equal(at(3));
expect(Object.keys(out.commits[0])).to.have.members(["message", "author", "date"]);
});
it("drops commits when the diff is hidden, and dates when dates are hidden", function () {
expect(makePullRequest({ ...all, diff: false }).content().commits).to.be.undefined;
expect(makePullRequest({ ...all, date: false }).content().commits[0]).to.not.have.property("date");
});
it("groups review comments into threads without GitHub ids", function () {
const out = makePullRequest(all).content();
expect(out.reviewComments).to.have.length(2);
const [first, second] = out.reviewComments;
expect(first.path).to.equal("src/XXXX-1.py");
expect(first.line).to.equal(4);
expect(first.comments.map((c) => c.body)).to.deep.equal(["Why XXXX-1?", "Because"]);
expect(first.comments[1].author).to.equal("XXXX-1");
expect(second.path).to.equal("README.md");
expect(JSON.stringify(out.reviewComments)).to.not.match(/commentId|inReplyTo|"1[123]"/);
});
it("omits review threads without the comments option", function () {
expect(makePullRequest({ ...all, comments: false }).content().reviewComments).to.be.undefined;
});
it("keeps pull requests stored before commits and review comments readable", function () {
const pr = makePullRequest(all);
delete pr.model.pullRequest.commits;
delete pr.model.pullRequest.reviewComments;
const out = pr.content();
expect(out.commits).to.be.undefined;
expect(out.reviewComments).to.be.undefined;
expect(out.diff).to.include("XXXX-1");
});
});
describe("reviewThreads()", function () {
it("attaches replies to their thread even when they arrive out of order", function () {
const threads = reviewThreads([
{ commentId: 3, inReplyTo: 1, path: "a", line: 2, body: "reply 2", author: "x", creationDate: at(9), updatedDate: at(9) },
{ commentId: 1, path: "a", line: 2, body: "root", author: "x", creationDate: at(1), updatedDate: at(1) },
{ commentId: 2, inReplyTo: 1, path: "a", line: 2, body: "reply 1", author: "y", creationDate: at(2), updatedDate: at(2) },
{ commentId: 4, inReplyTo: 99, path: "b", line: 5, body: "orphan", author: "z", creationDate: at(3), updatedDate: at(3) },
]);
expect(threads.map((t) => t.comments.map((c) => c.body))).to.deep.equal([["root", "reply 1", "reply 2"], ["orphan"]]);
expect(threads[1]).to.include({ path: "b", line: 5 });
});
});
+166
View File
@@ -0,0 +1,166 @@
const { expect } = require("chai");
const { JSDOM } = require("jsdom");
const path = require("path");
const { pathToFileURL } = require("url");
const load = (name) => import(pathToFileURL(path.join(__dirname, "../public/script", name)).href);
describe("Reviewer page outlines and diffs", function () {
let outline, formatters, pages, dom, vue;
// The pages register their scroll listeners in the controller's effect scope.
const inScope = (fn) => { const scope = vue.effectScope(); scope.run(fn); return scope; };
before(async () => {
dom = new JSDOM("<!doctype html><body></body>", { pretendToBeVisual: true });
global.window = dom.window;
outline = await load("outline.js");
formatters = await load("formatters.js");
pages = await load("review-pages.js");
vue = await import("vue");
});
after(() => { delete global.window; dom.window.close(); });
it("splits redaction masks into slot parts", () => {
expect(outline.redactParts("Results from XXXX-2 cluster")).to.deep.equal([{ t: "Results from " }, { n: "2" }, { t: " cluster" }]);
expect(outline.redactParts("")).to.deep.equal([]);
});
it("outlines h1-h3 with redaction slots read back from the chips", () => {
const html = '<h1 id="t">Guide</h1><h2 id="a">Setup</h2><h3 id="b">Data</h3><h4 id="c">Skip</h4>'
+ '<h2 id="r">Results from <mark class="redact-chip" data-term="XXXX-2"><i>2</i></mark> cluster</h2>';
const list = outline.headingOutline(html);
expect(list.map((h) => [h.id, h.level, h.depth])).to.deep.equal([["t", 1, 0], ["a", 2, 1], ["b", 3, 2], ["r", 2, 1]]);
expect(list[3].parts).to.deep.equal([{ t: "Results from " }, { n: "2" }, { t: " cluster" }]);
});
it("starts depth at the shallowest heading", () => {
const list = outline.headingOutline('<h2 id="a">A</h2><h3 id="b">B</h3>');
expect(list.map((h) => h.depth)).to.deep.equal([0, 1]);
});
it("highlights the last section above the reading line", () => {
const doc = dom.window.document;
doc.body.innerHTML = '<h2 id="one">1</h2><h2 id="two">2</h2><h2 id="three">3</h2>';
const tops = { one: -400, two: 120, three: 700 };
for (const id of Object.keys(tops)) doc.getElementById(id).getBoundingClientRect = () => ({ top: tops[id] });
const view = { innerHeight: 900, scrollY: 400 };
expect(outline.activeSection(["one", "two", "three"], { doc, view })).to.equal("two");
tops.two = 400;
expect(outline.activeSection(["one", "two", "three"], { doc, view })).to.equal("one");
tops.one = 50;
tops.two = 300; tops.three = 600;
expect(outline.activeSection(["one", "two", "three"], { doc, view: { innerHeight: 900, scrollY: 0 } })).to.equal("one");
});
it("parses a diff into files with status and counts, without a phantom last line", () => {
const files = formatters.parseDiff([
"diff --git a/a.py b/a.py", "--- a/a.py", "+++ b/a.py", "@@ -1,2 +1,2 @@", " keep", "-old", "+new",
"diff --git a/gone.sh b/gone.sh", "deleted file mode 100644", "--- a/gone.sh", "+++ /dev/null", "@@ -1,2 +0,0 @@", "-x", "-y",
"diff --git a/new.md b/new.md", "new file mode 100644", "--- /dev/null", "+++ b/new.md", "@@ -0,0 +1 @@", "+hi",
"\\ No newline at end of file", "",
].join("\n"));
expect(files.map((f) => [f.path, f.status, f.additions, f.deletions, f.lines.length])).to.deep.equal([
["a.py", "modified", 1, 1, 4], ["gone.sh", "deleted", 0, 2, 3], ["new.md", "added", 1, 0, 2],
]);
expect(files[0].lines[3]).to.include({ kind: "add", newNo: 2 });
});
it("keeps removed '-- ' and added '++ ' lines inside a hunk as content", () => {
const files = formatters.parseDiff([
"diff --git a/q.sql b/q.sql", "--- a/q.sql", "+++ b/q.sql", "@@ -1,3 +1,3 @@", " select 1;", "--- old comment", "+++ new counter", " end;",
"diff --git a/b.txt b/b.txt", "--- a/b.txt", "+++ b/b.txt", "@@ -1 +1 @@", "-x", "+y",
].join("\n"));
expect(files.map((f) => [f.path, f.additions, f.deletions])).to.deep.equal([["q.sql", 1, 1], ["b.txt", 1, 1]]);
expect(files[0].lines.map((l) => l.text)).to.deep.equal(["@@ -1,3 +1,3 @@", "select 1;", "-- old comment", "++ new counter", "end;"]);
});
it("places a LEFT thread on the removed line and a RIGHT one on the new line with the same number", () => {
const state = { details: {
diff: "--- a/a.py\n+++ b/a.py\n@@ -1,2 +1,2 @@\n-gone\n+added\n keep\n",
reviewComments: [{ path: "a.py", line: 1, side: "LEFT", comments: [{ body: "old" }] }, { path: "a.py", line: 1, side: "RIGHT", comments: [{ body: "new" }] }],
}, fmt: { date: (d) => d } };
const scope = inScope(() => pages.setupPullRequestPage(state));
const [file] = state.prFiles();
expect(file.lines.filter((l) => l.threads).map((l) => [l.kind, l.threads[0].comments[0].body])).to.deep.equal([["remove", "old"], ["add", "new"]]);
scope.stop();
});
it("renders the legacy diff HTML from the same parser", () => {
const html = formatters.diff("--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a<b\n+b\n");
expect(html).to.include('diff-file-status-modified').and.include("a&lt;b");
expect((html.match(/<tr/g) || []).length).to.equal(3);
});
it("places review threads on their diff line and keeps the rest at the end of the file", () => {
const state = { details: {
diff: "--- a/src/a.py\n+++ b/src/a.py\n@@ -1,2 +1,3 @@\n one\n+two\n three\n",
reviewComments: [{ path: "src/a.py", line: 2, comments: [{ body: "here" }] }, { path: "src/a.py", line: 40, comments: [{ body: "elsewhere" }] }, { path: "other", line: 1, comments: [] }],
comments: [{ body: "c", creationDate: "2026-03-02" }],
commits: [{ message: "First\n\nBody", date: "2026-03-01" }, { message: "Second", date: "2026-03-01" }],
}, fmt: { date: (d) => d.slice(0, 10) } };
const scope = inScope(() => pages.setupPullRequestPage(state));
const [file] = state.prFiles();
expect(file).to.include({ path: "src/a.py", dir: "src/", name: "a.py", threads: 2, id: "diff-1" });
expect(file.lines.find((l) => l.threads)).to.include({ newNo: 2, text: "two" });
expect(file.looseThreads.map((t) => t.line)).to.deep.equal([40]);
expect(state.prStats()).to.deep.equal({ files: 1, additions: 1, deletions: 0 });
expect(state.diffBar(file)).to.deep.equal(["add", "add", "add", "add", "add"]);
expect(state.commitGroups()).to.deep.equal([{ day: "2026-03-01", commits: [
{ message: "First\n\nBody", date: "2026-03-01", index: 1, headline: "First", detail: "Body" },
{ message: "Second", date: "2026-03-01", index: 2, headline: "Second", detail: "" },
] }]);
expect(state.prTimeline().map((i) => i.kind)).to.deep.equal(["comment", "review", "review", "review"]);
state.toggleAllFiles();
expect(state.allCollapsed()).to.equal(true);
scope.stop();
});
it("opens a pull request on its conversation, or on the files without one", () => {
expect(pages.defaultPullRequestTab({ body: "x", diff: "d" })).to.equal("conversation");
expect(pages.defaultPullRequestTab({ diff: "d", comments: [] })).to.equal("files");
expect(pages.defaultPullRequestTab({ commits: [{}] })).to.equal("commits");
});
it("lists gist files with language, lines and nested Markdown headings", () => {
const state = { tabState: { active: "files" }, details: { files: [
{ filename: "NOTES-XXXX-1.md", language: "Markdown", content: "# A\n\n## B\n" },
{ filename: "run.sh", language: "Shell", content: "a\nb\nc\n" },
] } };
const scope = inScope(() => pages.setupGistPage(state));
state.setFileOutline(0, [{ id: "file-1-a", level: 1, depth: 0, parts: [{ t: "A" }] }]);
const toc = state.gistToc();
expect(toc.map((f) => [f.id, f.language, f.lines, f.headings.length])).to.deep.equal([["file-1", "Markdown", 3, 1], ["file-2", "Shell", 3, 0]]);
expect(toc[0].parts).to.deep.equal([{ t: "NOTES-" }, { n: "1" }, { t: ".md" }]);
expect(state.showGistToc()).to.equal(true);
state.activeAnchor = "file-1-a";
expect(state.activeFileIndex()).to.equal(0);
state.details.files.pop();
expect(state.showGistToc()).to.equal(false);
scope.stop();
});
it("chooses the explorer viewer for each gist file and a source language", () => {
const kind = (file) => pages.gistFileKind(file);
expect(kind({ filename: "a.md", content: "# x" })).to.equal("markdown");
expect(kind({ filename: "notes", language: "Markdown", content: "x" })).to.equal("markdown");
expect(kind({ filename: "a.ipynb", content: "{}" })).to.equal("notebook");
expect(kind({ filename: "a.tsv", content: "a\tb" })).to.equal("csv");
expect(kind({ filename: "a.csv", content: "x".repeat(1024 * 1024 + 1) })).to.equal("code");
expect(kind({ filename: "a.svg", content: "<svg/>" })).to.equal("svg");
expect(kind({ filename: "a.py", content: "x" })).to.equal("code");
expect(kind({ filename: "a.png", encoding: "base64", content: "AA==" })).to.equal("image");
expect(kind({ filename: "a.pdf", encoding: "base64", content: "AA==" })).to.equal("pdf");
expect(kind({ filename: "a.webm", encoding: "base64", content: "AA==" })).to.equal("video");
expect(kind({ filename: "a.mp3", encoding: "base64", content: "AA==" })).to.equal("audio");
expect(kind({ filename: "a.bin", encoding: "base64", content: "AA==" })).to.equal("binary");
expect(kind({ filename: "a.png", encoding: "base64", hidden: true })).to.equal("hidden");
expect(kind({ filename: "a.bin", encoding: "base64", tooLarge: true })).to.equal("too-large");
expect(kind({ filename: "a.txt", content: "" })).to.equal("empty");
expect(["markdown", "notebook", "csv", "svg", "code", "image"].map(pages.hasRenderedView)).to.deep.equal([true, true, true, true, false, false]);
expect(pages.gistSourceLanguage({ filename: "a.ipynb" }, "notebook")).to.equal("json");
expect(pages.gistSourceLanguage({ filename: "a.py", language: "Python" }, "code")).to.equal("Python");
});
it("parses quoted CSV cells with the explorer's parser", () => {
expect(formatters.parseDelimited('a,"b ""q"", c"\r\n1,2\n', ",")).to.deep.equal([["a", 'b "q", c'], ["1", "2"]]);
});
});
+259
View File
@@ -0,0 +1,259 @@
const { expect } = require("chai");
const { JSDOM } = require("jsdom");
const path = require("path");
const { pathToFileURL } = require("url");
const load = (name) => import(pathToFileURL(path.join(__dirname, "../public/script", name)).href);
describe("Table analysis", function () {
let T, chart, formatters;
before(async () => {
T = await load("table-analysis.js");
chart = await load("table-chart.js");
formatters = await load("formatters.js");
});
const table = (text, sep = ",") => T.analyzeTable(formatters.parseDelimited(text, sep));
const all = (t) => [...Array(t.size).keys()];
const RESULTS = "model,seed,accuracy,plausible\nBaseline,1,71.0,410\nBaseline,2,71.4,414\n+ Aug.,1,73.8,445\n+ Aug.,2,74.2,449\nOurs,1,78.7,501\nOurs,2,79.1,\n";
describe("numeric parsing", () => {
it("reads grouped thousands, percents, exponents, signs and the Unicode minus", () => {
expect(["1,234", "12%", "1e-3", "-0.5", "+3", "−2", ".5", " 7 ", "1,234.5"].map(T.parseNumber)).to.deep.equal([1234, 12, 0.001, -0.5, 3, -2, 0.5, 7, 1234.5]);
});
it("rejects text, misplaced separators and bare signs", () => {
expect(["1,2", "12,34", "abc", "-", "", "1.2.3", "0x10", "Infinity", "12 %"].map(T.parseNumber)).to.deep.equal([null, null, null, null, null, null, null, null, null]);
});
it("counts decimals as written, including exponents", () => {
expect(["78.90", "1e-3", "1.38e-3", "12", "2.5e2", "0.3"].map(T.decimalsOf)).to.deep.equal([2, 3, 5, 0, 0, 1]);
});
});
describe("type detection", () => {
it("detects numbers, dates and text, ignoring empty and NA cells", () => {
expect(T.detectType(["1", "2.5", "", "NA", "1,000"])).to.equal("number");
expect(T.detectType(["2026-03-01", "2026-03-02T10:00Z", "", "Mar 3, 2026"])).to.equal("date");
expect(T.detectType(["Baseline", "12"])).to.equal("text");
expect(T.detectType(["03/01/2026", "04/01/2026"])).to.equal("text");
expect(T.detectType(["", ""])).to.equal("text");
});
it("keeps a column's precision, unit and scientific notation", () => {
const t = table("a,b,c,d\n1,12%,1.38e-3,x\n2.25,8%,2.1e-4,y\n");
expect(t.columns.map((c) => [c.type, c.decimals, c.unit])).to.deep.equal([["number", 2, ""], ["number", 0, "%"], ["number", 5, ""], ["text", 0, ""]]);
expect(t.columns[2].scientific).to.equal(2);
expect(T.summarize(t.columns[2], all(t), "mean").text).to.equal("7.950e-4");
expect(T.summarize(t.columns[1], all(t), "mean").text).to.equal("10.0%");
});
it("parses unambiguous dates only", () => {
expect(T.parseDate("2026-03-01")).to.equal(Date.UTC(2026, 2, 1));
expect(T.parseDate("2026/3/1 10:30")).to.equal(Date.UTC(2026, 2, 1, 10, 30));
expect(T.parseDate("1 March 2026")).to.equal(Date.UTC(2026, 2, 1));
expect(T.parseDate("2026-13-01")).to.equal(null);
expect(T.parseDate("03/01/2026")).to.equal(null);
});
});
describe("aggregates", () => {
const keys = [3, null, 1, 4, 1, 5];
const rows = [0, 1, 2, 3, 4, 5];
it("skips empty cells", () => {
expect(T.aggregate(keys, rows, "count")).to.equal(5);
expect(T.aggregate(keys, rows, "sum")).to.equal(14);
expect(T.aggregate(keys, rows, "mean")).to.equal(2.8);
expect(T.aggregate(keys, rows, "min")).to.equal(1);
expect(T.aggregate(keys, rows, "max")).to.equal(5);
});
it("computes the median for odd and even counts", () => {
expect(T.aggregate(keys, rows, "median")).to.equal(3);
expect(T.aggregate([4, 1, 3, 2], [0, 1, 2, 3], "median")).to.equal(2.5);
});
it("uses the sample standard deviation and needs two values", () => {
expect(T.aggregate([2, 4, 4, 4, 5, 5, 7, 9], [0, 1, 2, 3, 4, 5, 6, 7], "std")).to.be.closeTo(2.138, 1e-3);
expect(T.aggregate([5, null], [0, 1], "std")).to.equal(null);
expect(T.aggregate([null], [0], "mean")).to.equal(null);
expect(T.aggregate([null], [0], "count")).to.equal(0);
});
it("formats a summary with the column's precision, over the given rows only", () => {
const t = table(RESULTS);
expect(T.summarize(t.columns[2], all(t), "mean").text).to.equal("74.7");
expect(T.summarize(t.columns[2], [0, 1], "mean").text).to.equal("71.2");
expect(T.summarize(t.columns[3], all(t), "mean").text).to.equal("443.8");
expect(T.summarize(t.columns[3], all(t), "count").text).to.equal("5");
expect(T.summarize(t.columns[3], all(t), "sum").text).to.equal("2,219");
// Text columns count distinct values; identifier columns stay empty.
expect(T.summarize(t.columns[0], all(t)).text).to.equal("3 distinct");
expect(T.summarize(t.columns[1], all(t), "mean").kind).to.equal("none");
expect(T.summarize(t.columns[1], all(t), "mean", () => true).text).to.equal("1.5");
});
});
describe("identifier columns", () => {
const ids = (text) => table(text).columns.map((c) => c.identifier);
it("recognizes seed, id, run, fold, index and year by name", () => {
expect(ids("seed,run_id,fold,index,year,Trial,accuracy\n1,10,0,5,2024,3,71.2\n2,11,1,6,2025,4,71.4\n")).to.deep.equal([true, true, true, true, true, true, false]);
expect(ids("modelId,seeds,n_runs\n4,1,7\n9,2,8\n")).to.deep.equal([true, true, true]);
});
it("recognizes small consecutive whole numbers that repeat across rows", () => {
expect(ids("k,v\n1,5\n2,9\n3,4\n1,7\n2,2\n3,1\n")).to.deep.equal([true, false]);
expect(ids("k\n0\n1\n0\n1\n")).to.deep.equal([true]);
});
it("leaves measures alone: decimals, percents, gaps, big ranges, negatives, unique values", () => {
expect(ids("a,b,c,d,e\n1.0,1%,1,410,-1\n2.0,2%,3,414,0\n1.0,1%,1,445,-1\n2.0,2%,3,449,0\n")).to.deep.equal([false, false, false, false, false]);
expect(ids("epochs,plausible\n10,410\n20,414\n")).to.deep.equal([false, false]);
expect(ids("seed,name\nx,y\n")).to.deep.equal([false, false]);
expect(ids("seed\n1.5\n2.5\n")).to.deep.equal([false]);
});
});
describe("sorting", () => {
it("sorts numbers numerically and keeps empty cells last in both directions", () => {
const t = table("k,v\na,10\nb,\nc,9\nd,-1\ne,1e1\n");
expect(T.sortIndices(t, all(t), 1, "asc")).to.deep.equal([3, 2, 0, 4, 1]);
expect(T.sortIndices(t, all(t), 1, "desc")).to.deep.equal([0, 4, 2, 3, 1]);
});
it("is stable: ties keep their current order", () => {
const t = table(RESULTS);
expect(T.sortIndices(t, all(t), 0, "asc")).to.deep.equal([2, 3, 0, 1, 4, 5]);
const bySeed = T.sortIndices(t, all(t), 1, "desc");
expect(bySeed).to.deep.equal([1, 3, 5, 0, 2, 4]);
expect(T.sortIndices(t, bySeed, 0, "asc")).to.deep.equal([3, 2, 1, 0, 5, 4]);
});
it("sorts text naturally and dates chronologically", () => {
const t = table("name,date\nrun 10,Mar 3 2026\nrun 2,2026-03-01\nRun 1,2026-02-28\n");
expect(T.sortIndices(t, all(t), 0, "asc")).to.deep.equal([2, 1, 0]);
expect(t.columns[1].type).to.equal("date");
expect(T.sortIndices(t, all(t), 1, "desc")).to.deep.equal([0, 1, 2]);
const d = table("date\n2026-03-10\n2026-02-28\n2026-03-01\n");
expect(T.sortIndices(d, all(d), 0, "asc")).to.deep.equal([1, 2, 0]);
});
});
describe("filtering", () => {
it("combines the search box, numeric ranges and value sets", () => {
const t = table(RESULTS);
expect(T.filterIndices(t, { query: "aug" })).to.deep.equal([2, 3]);
expect(T.filterIndices(t, { ranges: { 2: [74, null] } })).to.deep.equal([3, 4, 5]);
expect(T.filterIndices(t, { ranges: { 3: [null, 450] } })).to.deep.equal([0, 1, 2, 3]);
expect(T.filterIndices(t, { values: { 0: ["Ours", "Baseline"] }, ranges: { 1: [2, 2] } })).to.deep.equal([1, 5]);
});
});
describe("grouping", () => {
it("reproduces the mean per model over seeds", () => {
const t = table(RESULTS);
const g = T.groupTable(t, all(t), 0, "mean");
expect(g.header).to.deep.equal(["model", "Rows", "accuracy", "plausible"]);
expect(g.body).to.deep.equal([["Baseline", "2", "71.2", "412.0"], ["+ Aug.", "2", "74.0", "447.0"], ["Ours", "2", "78.9", "501.0"]]);
// "Treat as number" brings the seed back.
expect(T.groupTable(t, all(t), 0, "mean", () => true).header).to.deep.equal(["model", "Rows", "seed", "accuracy", "plausible"]);
expect(g.columns[2].agg).to.equal("mean");
expect(g.columns[2].keys[0]).to.be.closeTo(71.2, 1e-9);
});
it("groups only the filtered rows and can be sorted, counted and exported", () => {
const t = table(RESULTS);
const g = T.groupTable(t, T.filterIndices(t, { ranges: { 1: [1, 1] } }), 0, "max");
expect(g.body.map((r) => r[0])).to.deep.equal(["Baseline", "+ Aug.", "Ours"]);
const order = T.sortIndices(g, [0, 1, 2], 2, "desc");
expect(order.map((i) => g.body[i][0])).to.deep.equal(["Ours", "+ Aug.", "Baseline"]);
expect(T.toMarkdown(g.header, order.map((i) => g.body[i]), g.columns.map((c) => c.type === "number")).split("\n")[1]).to.equal("| --- | ---: | ---: | ---: |");
});
it("labels empty groups", () => {
const t = table("k,v\na,1\n,2\na,3\n");
expect(T.groupTable(t, all(t), 0, "sum").body).to.deep.equal([["a", "2", "4"], ["(empty)", "1", "2"]]);
});
it("keeps 'none', 'NA' and '-' as categories in text columns", () => {
const t = table("augmentation,acc\nnone,1\nflip,2\nnone,3\nNA,4\n-,5\n,6\n");
expect(t.columns[0].type).to.equal("text");
expect(t.columns[0].empty).to.equal(1);
expect(T.groupTable(t, all(t), 0, "sum").body.map((r) => r[0])).to.deep.equal(["none", "flip", "NA", "-", "(empty)"]);
// In a number column they still mean "no value".
expect(table("v\n1\nNA\n-\n3\n").columns[0]).to.include({ type: "number", empty: 2 });
});
});
describe("export", () => {
it("quotes CSV cells only when needed and escapes Markdown pipes", () => {
expect(T.toDelimited(["a", "b"], [["x,y", 'say "hi"'], ["plain", ""]])).to.equal('a,b\n"x,y","say ""hi"""\nplain,\n');
expect(T.toMarkdown(["a|b"], [["c|d"]])).to.equal("| a\\|b |\n| --- |\n| c\\|d |\n");
});
});
describe("shareable state", () => {
it("round-trips through the fragment and stays empty by default", () => {
expect(T.writeHashState("table", T.DEFAULT_STATE)).to.equal("");
const state = { ...T.DEFAULT_STATE, view: "chart", group: "model", agg: "median", sort: { column: "accuracy", dir: "desc" }, values: { model: ["Ours", "+ Aug."] }, ranges: { accuracy: [70, null] }, sums: { accuracy: "std" }, chart: "bar", y: ["accuracy", "plausible"] };
const hash = T.writeHashState("table-2", state);
expect(hash).to.match(/^#table-2:view=chart&sort=accuracy:desc&group=model&agg=median/);
const back = T.readHashState(hash, "table-2");
expect(back).to.deep.include({ view: "chart", group: "model", agg: "median", chart: "bar" });
expect(back.sort).to.deep.equal({ column: "accuracy", dir: "desc" });
expect(back.values).to.deep.equal({ model: ["Ours", "+ Aug."] });
expect(back.ranges).to.deep.equal({ accuracy: [70, null] });
expect(back.y).to.deep.equal(["accuracy", "plausible"]);
expect(T.readHashState(hash, "table")).to.equal(null);
expect(T.readHashState("#L12", "table")).to.equal(null);
expect(T.isTableHash("#L12")).to.equal(false);
});
});
describe("column stats and charts", () => {
it("summarizes a column with a histogram", () => {
const t = table(RESULTS);
const s = T.columnStats(t.columns[3], all(t), 4);
expect(s).to.include({ type: "number", count: 5, empty: 1, distinct: 5, min: 410, max: 501 });
expect(s.histogram.map((b) => b.count)).to.deep.equal([2, 2, 0, 1]);
expect(T.columnStats(t.columns[0], all(t)).top[0]).to.deep.equal(["+ Aug.", 2]);
});
it("defaults to a bar of the first measure by the first text column, skipping seeds", () => {
const t = table(RESULTS);
expect(chart.defaultChart(t, false)).to.deep.equal({ type: "bar", x: "model", y: ["accuracy"] });
const g = T.groupTable(t, all(t), 0, "mean");
expect(chart.defaultChart(g, true)).to.deep.equal({ type: "bar", x: "model", y: ["accuracy"] });
});
it("averages repeated categories in a bar chart and says so", () => {
const t = table(RESULTS);
const c = chart.buildChart(t, all(t), { type: "bar", x: "model", y: ["accuracy"], agg: "mean" }, { width: 600 });
expect(c.categories.map((x) => x.label)).to.deep.equal(["Baseline", "+ Aug.", "Ours"]);
expect(c.categories[2].tip.rows[0].value).to.equal("78.9");
expect(c.notes[0]).to.equal("Average per model over 6 rows.");
expect(c.marks.every((m) => m.h <= 24)).to.equal(true);
});
it("draws lines on a date axis in order and scatter points with their rows", () => {
const t = table("date\tv\n2026-03-03\t3\n2026-03-01\t1\n2026-03-02\t2\n", "\t");
const line = chart.buildChart(t, all(t), { type: "line", x: "date", y: ["v"] }, { width: 600 });
expect(line.points.map((p) => p.title)).to.deep.equal(["date 2026-03-01", "date 2026-03-02", "date 2026-03-03"]);
expect(line.series[0].path.startsWith("M")).to.equal(true);
const scatter = chart.buildChart(t, all(t), { type: "scatter", x: "v", y: ["v"] }, { width: 600 });
expect(scatter.series[0].dots).to.have.length(3);
// An ID-like text x column is refused instead of measuring every label.
const ids = table("id,v\n" + Array.from({ length: 200000 }, (_, i) => `row-${i},${i % 7}`).join("\n"));
const many = chart.buildChart(ids, all(ids), { type: "scatter", x: "id", y: ["v"] }, { width: 600 });
expect(many.empty).to.match(/200,000 different values/);
});
it("explains an empty chart", () => {
const t = table(RESULTS);
expect(chart.buildChart(t, [], { type: "bar", x: "model", y: ["accuracy"] }, { width: 600 }).empty).to.match(/No rows/);
expect(chart.buildChart(t, all(t), { type: "bar", x: "model", y: [] }, { width: 600 }).empty).to.match(/numeric/);
});
it("picks round ticks", () => {
expect(chart.niceTicks(0, 79.1, 5).ticks).to.deep.equal([0, 20, 40, 60, 80]);
expect(chart.tickLabel(25000, 5000)).to.equal("25K");
expect(chart.tickLabel(0.775, 0.025)).to.equal("0.775");
});
});
describe("Markdown and notebook tables", () => {
let dom;
before(() => { dom = new JSDOM("<!doctype html><body></body>"); global.window = dom.window; });
after(() => { delete global.window; dom.window.close(); });
it("reads redaction chips and slots back as XXXX-n and the pandas header rows", async () => {
const enhance = await load("table-enhance.js");
const doc = dom.window.document;
doc.body.innerHTML = '<table class="dataframe"><thead><tr><th></th><th>acc</th></tr><tr><th>model</th><th></th></tr></thead><tbody>'
+ '<tr><th>Ours</th><td>78.9</td></tr><tr><th><mark class="redact-chip" data-term="XXXX-2"><i>2</i></mark></th><td>71.2</td></tr></tbody></table>';
const data = enhance.tableData(doc.querySelector("table"));
expect(data.rows).to.deep.equal([["model", "acc"], ["Ours", "78.9"], ["XXXX-2", "71.2"]]);
doc.body.innerHTML = '<table><tr><td colspan="2">x</td></tr><tr><td>1</td><td>2</td></tr></table>';
expect(enhance.tableData(doc.querySelector("table"))).to.equal(null);
});
});
});
+276
View File
@@ -2984,6 +2984,282 @@ describe("Vue 3 UI", function () {
expect(ui.app.router.currentRoute.value.path).to.equal("/");
});
it("renders the pull request header, threaded conversation, commits and collapsible files", async function () {
const diff = "diff --git a/src/a.py b/src/a.py\n--- a/src/a.py\n+++ b/src/a.py\n@@ -1,2 +1,3 @@\n one\n+two by XXXX-1\n three\n"
+ "diff --git a/old.sh b/old.sh\ndeleted file mode 100644\n--- a/old.sh\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n";
ui = await browser("/pr/pr-1/", {
"/api/pr/pr-1/options": { url: null },
"/api/pr/pr-1/content": {
state: "open", title: "Fix XXXX-1 harness", author: "XXXX-2", baseRef: "main", headRef: "XXXX-2/fix", diff,
comments: [{ author: "XXXX-3", body: "Looks good", creationDate: "2026-03-03" }],
reviewComments: [{ path: "src/a.py", line: 2, comments: [{ author: "XXXX-3", body: "Why?", creationDate: "2026-03-02" }, { author: "XXXX-2", body: "Because", creationDate: "2026-03-04" }] }],
commits: [{ message: "First", author: "XXXX-2", date: "2026-03-01" }],
},
});
await delay(60);
const doc = ui.window.document;
expect(doc.querySelector(".pr-title").textContent.replace(/\s+/g, " ").trim()).to.equal("Fix 1 harness");
expect(doc.querySelectorAll(".pr-title .redact-slot")).to.have.length(1);
// A fully redacted author is one unit: its slot, without a stray "@".
const author = doc.querySelector(".pr-summary .pr-author");
expect(author.classList.contains("is-redacted")).to.equal(true);
expect(author.textContent.trim()).to.equal("2");
expect(doc.querySelector(".pr-state").textContent.trim()).to.equal("Open");
expect(doc.querySelector(".pr-summary").textContent.replace(/\s+/g, " ")).to.include("wants to merge 1 commit into main from 2/fix");
const tabs = [...doc.querySelectorAll(".pr-tabs [role=tab]")].map((t) => t.textContent.replace(/\s+/g, " ").trim());
expect(tabs).to.deep.equal(["Conversation2", "Commits1", "Files changed2"]);
expect(doc.querySelector(".pr-tabs [aria-selected=true]").id).to.equal("pr-conversation-tab");
expect(doc.querySelectorAll(".pr-timeline-item")).to.have.length(3);
expect(doc.querySelectorAll(".pr-timeline-item.is-review .pr-thread-comment.is-reply")).to.have.length(1);
doc.querySelector("#pr-commits-tab").click(); await delay(20);
expect(doc.querySelector(".pr-commit-headline").textContent).to.equal("First");
doc.querySelector("#pr-files-tab").click(); await delay(20);
const blocks = doc.querySelectorAll(".diff-file-block");
expect(blocks).to.have.length(2);
expect(doc.querySelectorAll(".pr-file-toc .toc-diff-file")).to.have.length(2);
expect(blocks[0].querySelector(".diff-file-stat").textContent).to.include("+1");
expect(blocks[0].querySelectorAll(".diff-thread-row")).to.have.length(1);
expect(blocks[0].querySelector(".diff-row-add .redact-slot")).to.not.equal(null);
// The thread sits in the code column; its comments share one container.
const threadRow = blocks[0].querySelector(".diff-thread-row");
expect(threadRow.querySelector(".diff-thread-gutter").getAttribute("colspan")).to.equal("3");
expect(threadRow.querySelectorAll(".diff-thread-cell > .pr-thread > .pr-thread-comment")).to.have.length(2);
expect(threadRow.querySelectorAll(".pr-thread .pr-thread")).to.have.length(0);
expect(blocks[1].querySelector(".diff-file-status").textContent).to.equal("deleted");
blocks[0].querySelector(".diff-file-toggle").click(); await delay(20);
expect(blocks[0].querySelector(".diff-file-body")).to.equal(null);
expect(blocks[0].querySelector(".diff-file-toggle").getAttribute("aria-expanded")).to.equal("false");
expect(ui.errors).to.deep.equal([]);
});
it("outlines a gist's files on the files tab", async function () {
ui = await browser("/gist/g-1/", {
"/api/gist/g-1/options": { url: null },
"/api/gist/g-1/content": { description: "Notes", files: [
{ filename: "a-XXXX-1.py", language: "Python", content: "x = 1\ny = 2\n" },
{ filename: "b.json", language: "JSON", content: "{}\n" },
] },
});
await delay(60);
const doc = ui.window.document;
const items = [...doc.querySelectorAll(".page-toc .toc-file")];
expect(items.map((a) => a.getAttribute("href"))).to.deep.equal(["#file-1", "#file-2"]);
expect(items[0].querySelector(".toc-file-meta").textContent).to.equal("Python · 2 lines");
expect(items[0].querySelector(".redact-slot")).to.not.equal(null);
expect(items[0].classList.contains("is-active")).to.equal(true);
expect(doc.querySelectorAll(".gist-file-card")).to.have.length(2);
expect(doc.getElementById("file-2")).to.not.equal(null);
expect(ui.errors).to.deep.equal([]);
});
it("outlines Markdown h1-h3 with redaction slots and hides short outlines", async function () {
const doc = "# Guide\n\nIntro.\n\n## Setup\n\nText.\n\n### Data\n\nText.\n\n## Results from XXXX-2\n\nText.\n";
ui = await browser("/r/test/GUIDE.md", {
"/api/repo/test/files/": [{ name: "GUIDE.md", path: "", sha: "1", size: 80 }, { name: "SHORT.md", path: "", sha: "2", size: 20 }],
"/api/repo/test/file/GUIDE.md": doc,
"/api/repo/test/file/SHORT.md": "# Short\n\n## Only\n",
});
await delay(150);
const document = ui.window.document;
const rail = [...document.querySelectorAll(".readme-toc .toc-rail a")];
expect(rail.map((a) => a.textContent.trim())).to.deep.equal(["Guide", "Setup", "Data", "Results from 2"]);
expect(rail.map((a) => a.className.match(/lvl-\d/)[0])).to.deep.equal(["lvl-2", "lvl-2", "lvl-3", "lvl-2"]);
expect(rail[3].querySelector(".redact-slot")).to.not.equal(null);
expect(rail[1].getAttribute("href")).to.equal("#" + document.querySelector(".markdown-body h2").id);
expect(document.querySelectorAll(".tb-toc-menu, .tb-toc-m")).to.have.length(1);
await ui.go("/r/test/SHORT.md");
await delay(150);
expect(document.querySelector(".readme-toc")).to.equal(null);
expect(document.querySelector(".tb-toc-m")).to.equal(null);
expect(ui.errors).to.deep.equal([]);
});
it("renders each gist format with the explorer's viewers and toggles a file's source", async function () {
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
const files = [
{ filename: "README.md", language: "Markdown", content: "# Notes by XXXX-1\n\nText.\n" },
{ filename: "data.csv", content: "name,score\nXXXX-2,3\nb,4\n" },
{ filename: "run.ipynb", content: JSON.stringify({ nbformat: 4, nbformat_minor: 5, metadata: {}, cells: [{ cell_type: "markdown", metadata: {}, source: ["# Cell"] }] }) },
{ filename: "plot.svg", content: "<svg xmlns='http://www.w3.org/2000/svg' width='4' height='4'/>" },
{ filename: "train.py", language: "Python", content: "print(1)\n" },
{ filename: "fig.png", encoding: "base64", size: 70, content: png },
// The API never sends bytes for binaries other than images.
{ filename: "talk.mp4", encoding: "base64", size: 4 },
{ filename: "beep.wav", encoding: "base64", size: 4 },
{ filename: "model.bin", encoding: "base64", size: 4 },
{ filename: "big.parquet", encoding: "base64", size: 400000000, tooLarge: true },
{ filename: "photo.jpg", encoding: "base64", size: 10, hidden: true },
{ filename: "empty.txt", content: "" },
];
let blobs = 0;
ui = await browser("/gist/g-2/", { "/api/gist/g-2/options": { url: null }, "/api/gist/g-2/content": { description: "Formats", files } });
ui.window.URL.createObjectURL = () => "blob:http://localhost/" + (++blobs);
ui.window.URL.revokeObjectURL = () => {};
const copied = [];
Object.defineProperty(ui.window.navigator, "clipboard", { value: { writeText: async (text) => copied.push(text) }, configurable: true });
await ui.go("/faq"); await ui.go("/gist/g-2/");
await delay(150);
const doc = ui.window.document;
const body = (i) => doc.querySelectorAll(".gist-file-card")[i].querySelector(".gist-file-body");
expect(body(0).querySelector("markdown.markdown-body h1")).to.not.equal(null);
expect(body(1).querySelectorAll(".csv-table tbody tr")).to.have.length(2);
expect(body(1).querySelector(".csv-table tbody .redact-slot")).to.not.equal(null);
expect(body(2).querySelector("notebook")).to.not.equal(null);
expect(body(3).querySelector("img.image-content").getAttribute("src")).to.match(/^blob:/);
expect(body(4).querySelector("pre code")).to.not.equal(null);
expect(body(5).querySelector("img.image-content")).to.not.equal(null);
for (const i of [6, 7, 8]) {
expect(body(i).querySelector(".file-state-title").textContent).to.equal("This file isn't shared");
expect(body(i).querySelector("a[download]")).to.equal(null);
expect(doc.querySelectorAll(".gist-file-card")[i].querySelector(".gist-file-actions")).to.equal(null);
}
expect(body(9).querySelector(".file-state-title").textContent).to.equal("This file is too large to preview");
expect(body(10).querySelector(".file-state-title").textContent).to.equal("Image not shown");
expect(body(11).querySelector(".file-state-title").textContent).to.equal("This file is empty");
// Preview/Source only where the two differ; Raw and copy on every readable file.
const toggles = [...doc.querySelectorAll(".gist-file-card")].map((card) => !!card.querySelector(".gist-view-toggle"));
expect(toggles).to.deep.equal([true, true, true, true, false, false, false, false, false, false, false, false]);
const card = doc.querySelectorAll(".gist-file-card")[0];
expect(card.querySelector(".gist-file-actions a[target=_blank]").getAttribute("href")).to.match(/^blob:/);
card.querySelector(".gist-file-actions button").click(); await delay(20);
expect(copied).to.deep.equal([files[0].content]);
const [preview, source] = card.querySelectorAll(".gist-view-toggle .seg-chip");
source.click(); await delay(60);
expect(source.getAttribute("aria-checked")).to.equal("true");
expect(body(0).querySelector("markdown")).to.equal(null);
expect(body(0).querySelector("pre code").textContent).to.equal(files[0].content);
expect(doc.querySelector(".page-toc .toc-heading")).to.equal(null);
preview.click(); await delay(60);
expect(body(0).querySelector("markdown h1")).to.not.equal(null);
// CSV: Table, Chart and Source.
const csvChips = () => doc.querySelectorAll(".gist-file-card")[1].querySelectorAll(".gist-view-toggle .seg-chip");
expect([...csvChips()].map((c) => c.textContent)).to.deep.equal(["Table", "Chart", "Source"]);
csvChips()[1].click(); await delay(40);
expect(body(1).querySelector(".dt-chart")).to.not.equal(null);
expect(body(1).querySelector(".csv-table")).to.equal(null);
csvChips()[2].click(); await delay(40);
expect(body(1).querySelector(".csv-table")).to.equal(null);
expect(body(1).querySelector("pre code").textContent).to.equal(files[1].content);
expect(ui.errors).to.deep.equal([]);
});
describe("table analysis", function () {
const CSV = "model,seed,accuracy\nBaseline,1,71.0\nBaseline,2,71.4\nOurs,1,78.7\nOurs,2,79.1\nXXXX-2,1,\n";
const open = async (hash = "") => {
const page = await browser("/r/test/results.csv" + hash, {
"/api/repo/test/files/": [{ name: "results.csv", path: "", sha: "1", size: CSV.length }],
"/api/repo/test/file/results.csv": CSV,
});
await delay(120);
return page;
};
const cells = (doc, col) => [...doc.querySelectorAll(".dt-table tbody tr")].map((tr) => tr.cells[col].textContent);
const sortButton = (doc, name) => [...doc.querySelectorAll(".dt-sort")].find((b) => b.textContent.trim() === name);
it("sorts by a header, shows the summary row and keeps redaction slots", async function () {
ui = await open();
const doc = ui.window.document;
expect(cells(doc, 1)).to.deep.equal(["Baseline", "Baseline", "Ours", "Ours", "2"]);
expect(doc.querySelector(".dt-table tbody .redact-slot").textContent).to.equal("2");
// Σ, distinct count for text, nothing for the seed (an identifier), "Avg ▾ value" per measure.
const cellsOf = () => [...doc.querySelectorAll(".dt-summary td")];
expect(cellsOf()[0].textContent.trim()).to.match(/^Σ/);
expect(cellsOf()[1].textContent.trim()).to.equal("3 distinct");
expect(cellsOf()[2].textContent.trim()).to.equal("");
expect(doc.querySelectorAll(".dt-summary select")).to.have.length(1);
expect(doc.querySelector(".dt-sum-fn-label").textContent).to.equal("Avg");
const foot = () => [...doc.querySelectorAll(".dt-sum-value")].map((b) => b.textContent);
expect(foot()).to.deep.equal(["75.1"]);
sortButton(doc, "accuracy").click(); await delay(30);
expect(cells(doc, 3)).to.deep.equal(["71.0", "71.4", "78.7", "79.1", ""]);
sortButton(doc, "accuracy").click(); await delay(30);
expect(cells(doc, 3)).to.deep.equal(["79.1", "78.7", "71.4", "71.0", ""]);
expect(doc.querySelector("th[aria-sort=descending]").textContent).to.contain("accuracy");
sortButton(doc, "accuracy").click(); await delay(30);
expect(cells(doc, 3)).to.deep.equal(["71.0", "71.4", "78.7", "79.1", ""]);
expect(doc.querySelector("th[aria-sort=ascending], th[aria-sort=descending]")).to.equal(null);
const select = doc.querySelector(".dt-summary select");
select.value = "max"; select.dispatchEvent(new ui.window.Event("change")); await delay(30);
expect(foot()).to.deep.equal(["79.1"]);
expect(doc.querySelector(".dt-sum-fn-label").textContent).to.equal("Max");
expect(ui.errors).to.deep.equal([]);
});
it("filters rows, groups them and stores the view in the link", async function () {
ui = await open();
const doc = ui.window.document;
await ui.input(".dt-search-input", "ours");
expect(cells(doc, 1)).to.deep.equal(["Ours", "Ours"]);
expect(doc.querySelector(".dt-count").textContent).to.equal("2 of 5 rows");
expect([...doc.querySelectorAll(".dt-sum-value")].at(-1).textContent).to.equal("78.9");
await ui.input(".dt-search-input", "");
const group = doc.querySelector(".dt-tools .dt-select select");
group.value = "model"; group.dispatchEvent(new ui.window.Event("change")); await delay(30);
expect(cells(doc, 0)).to.deep.equal(["Baseline", "Ours", "2"]);
expect(doc.querySelector(".dt-table tbody tr:last-child .redact-slot")).to.not.equal(null);
expect(cells(doc, 2)).to.deep.equal(["71.2", "78.9", "—"]);
expect(doc.querySelector(".dt-count").textContent).to.equal("3 groups · 5 rows");
await delay(300);
expect(ui.window.location.hash).to.equal("#table:group=model");
expect(ui.errors).to.deep.equal([]);
});
it("opens a shared link on the grouped chart, with a tooltip on hover", async function () {
ui = await open("#table:view=chart&group=model");
const doc = ui.window.document;
expect(doc.querySelector(".csv-toggle .seg-chip.active").textContent).to.equal("Chart");
// jsdom has no layout: give the chart a width.
Object.defineProperty(ui.window.HTMLElement.prototype, "clientWidth", { configurable: true, get() { return this.classList.contains("dt-chart") ? 600 : 0; } });
doc.querySelector(".csv-toggle .seg-chip").click(); await delay(30);
doc.querySelectorAll(".csv-toggle .seg-chip")[1].click(); await delay(60);
const svg = doc.querySelector(".dt-svg");
expect(svg.getAttribute("aria-label")).to.equal("Bar chart of accuracy by model");
expect([...doc.querySelectorAll(".dt-cat")].map((t) => t.textContent)).to.deep.equal(["Baseline", "Ours", "XXXX-2"]);
svg.dispatchEvent(new ui.window.KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true })); await delay(30);
expect(doc.querySelector(".dt-tip b").textContent).to.equal("71.2");
expect(doc.querySelector(".dt-tip-title").textContent).to.equal("Baseline");
delete ui.window.HTMLElement.prototype.clientWidth;
expect(ui.errors).to.deep.equal([]);
});
it("copies the current view as Markdown", async function () {
ui = await open("#table:group=model&sort=accuracy:desc");
const copied = [];
Object.defineProperty(ui.window.navigator, "clipboard", { value: { writeText: async (text) => copied.push(text) }, configurable: true });
const doc = ui.window.document;
doc.querySelector(".dt-copy-btn").click(); await delay(20);
[...doc.querySelectorAll(".dt-copy-menu button")].find((b) => /Markdown/.test(b.textContent)).click(); await delay(30);
expect(copied[0].split("\n").slice(0, 4)).to.deep.equal(["| model | Rows | accuracy |", "| --- | ---: | ---: |", "| Ours | 2 | 78.9 |", "| Baseline | 2 | 71.2 |"]);
expect(ui.errors).to.deep.equal([]);
});
it("sorts a Markdown table, adds a summary row and opens it as a table", async function () {
const md = "# Results\n\n| Model | Accuracy |\n| --- | ---: |\n| Baseline | 71.2 |\n| XXXX-3 | 77.5 |\n| Ours | 78.9 |\n";
ui = await browser("/r/test/README.md", {
"/api/repo/test/files/": [{ name: "README.md", path: "", sha: "1", size: md.length }],
"/api/repo/test/file/README.md": md,
});
await delay(200);
const doc = ui.window.document;
const table = doc.querySelector(".markdown-body table");
expect(table.closest(".md-table")).to.not.equal(null);
const firstCol = () => [...table.querySelectorAll("tbody tr")].map((tr) => tr.cells[0].textContent.trim());
table.querySelectorAll("th")[1].click(); table.querySelectorAll("th")[1].click(); await delay(20);
expect(firstCol()).to.deep.equal(["Ours", "3", "Baseline"]);
expect(table.querySelector("tbody .redact-chip, tbody .redact-slot")).to.not.equal(null);
doc.querySelector(".md-sigma").click(); await delay(20);
expect(table.querySelector("tfoot td").textContent).to.match(/^Σ/);
expect(table.querySelector("tfoot .dt-sum-fn-label").textContent).to.equal("Avg");
expect(table.querySelector("tfoot .dt-sum-value").textContent).to.equal("75.9");
doc.querySelector(".md-open").click(); await delay(60);
const dialog = doc.querySelector(".dt-dialog");
expect(dialog.querySelector(".dt-dialog-title").textContent).to.equal("Table · Results");
expect([...dialog.querySelectorAll(".dt-table tbody tr")].map((tr) => tr.cells[1].textContent)).to.deep.equal(["Baseline", "3", "Ours"]);
dialog.querySelector(".dt-dialog-close").click(); await delay(20);
expect(doc.querySelector(".dt-dialog")).to.equal(null);
expect(ui.errors).to.deep.equal([]);
});
});
describe("workspace polish (r19)", () => {
it("keeps the dashboard tabs and counts rendered while a tab reloads", async () => {
const item = (repoId, status) => ({ _type: "repo", repoId, status, source: { fullName: "owner/" + repoId }, options: {} });