Initial import of streamline

This commit is contained in:
2026-11-16 17:26:44 -08:00
commit 8e4aec1855
1221 changed files with 274256 additions and 0 deletions
@@ -0,0 +1,87 @@
import { describe, expect, test } from "bun:test";
import { auditEvidenceFiles, auditFiledIssues, auditListTitle, auditSourceId, auditWorkOrderTitle } from "../src/lib/auditPresentation";
describe("filed audit snapshots", () => {
test("restores the original source and all unique screenshot files", () => {
const description = "[UI] 搜索不刷新\n\n来源:验证任务「Close Friends」(abc-123)\n\n证据:`en-search.png`\n证据:`de-search.png`\n证据:`en-search.png`";
expect(auditSourceId(description)).toBe("abc-123");
expect(auditEvidenceFiles(description)).toEqual(["en-search.png", "de-search.png"]);
});
test("ordinary bug descriptions do not get an unrelated source section", () => {
expect(auditSourceId("复现:点开来源任务 abc-123")).toBeNull();
expect(auditEvidenceFiles("代码位置:`Search.swift:12` ")).toEqual([]);
});
test("long quoted titles are not cut before their available two lines", () => {
const text = "在「Add to Highlight」页点「See reposts」后出现第二步引导「Tap to collapse」,此时点返回键、点空白处都没反应,用户必须先点那个折叠按钮才能离开页面";
expect(auditListTitle({ text })).toBe(text);
expect(auditListTitle({ text })).not.toContain("…");
});
test("short list labels preserve the full issue snapshot", () => {
const issue = { text: "搜索结果未刷新", detail: "点击清空后仍保留上一次的搜索结果,需要再次输入才刷新。" };
const before = JSON.stringify(issue);
expect(auditListTitle(issue)).toBe("搜索结果未刷新");
expect(JSON.stringify(issue)).toBe(before);
});
});
describe("read-only filed issue cards", () => {
test("shows a saved expectation as text and keeps evidence collapsed separately", () => {
const description = "来源:验证任务「报告」(abc)\n\n## P2 · 功能 · profile/search @ en\n清空搜索后未刷新\n\n**复现条件**:搜索后点击清空\n取证:界面仍保留旧结果\n**期望**:清空后显示全部成员\n第二行补充\n代码位置:`Search.swift:12`\n证据:`search.png`";
const [issue] = auditFiledIssues(description);
expect(issue.headline).toBe("清空搜索后未刷新");
expect(issue.expected).toBe("清空后显示全部成员\n第二行补充");
expect(issue.evidence).toContain("界面仍保留旧结果");
expect(issue.evidence).not.toContain("清空后显示全部成员");
expect(issue.files).toEqual(["search.png"]);
});
test("merged issues retain their own screenshots and omit empty expectations", () => {
const issues = auditFiledIssues("## P1 · 功能 · page-a @ en\n问题 A\n证据:`a.png`\n\n## P3 · 布局 · page-b @ de\n问题 B\n**期望**: \n证据:`b.png`");
expect(issues.map((i) => i.files)).toEqual([["a.png"], ["b.png"]]);
expect(issues.map((i) => i.expected)).toEqual(["", ""]);
});
});
test("restores old truncated audit titles without rewriting unrelated work orders", () => {
const description = "来源:验证任务「走查」(abc)\n\n## P2 · 功能 · dm @ en\n群聊 Notifications 当前选项没有选中\n证据:`dm.png`";
expect(auditWorkOrderTitle("[UI] 群聊 Notifications…", description)).toBe("[UI] 群聊 Notifications 当前选项没有选中");
expect(auditWorkOrderTitle("自定义标题", description)).toBe("自定义标题");
expect(auditWorkOrderTitle("其他问题…", "普通问题描述")).toBe("其他问题…");
});
describe("merged audit work orders", () => {
test("parses every issue the merged renderer writes, with TOS screenshots and boxes", async () => {
const { renderAuditFixDescription } = await import("@bbbug/shared/audit_fix_plan");
const iss = (n: number, text: string) => ({ n, sev: "P2" as const, cat: "组件规范", langs: ["en"], text, code: "a/B.kt", repro: "Inbox → Requests", cause: "图标资源传错" });
const report = {
title: "走查", meta: [], langs: ["en"], blocked: [], totals: { issues: 2, instances: 2, bySev: {}, byCat: {} }, coverage: { ok: 0, issue: 0, missing: 0 },
pages: [{ id: "s1-dm/03-requests", surface: "面 1 · DM 私信", title: "消息请求页", coverage: ["issue" as const], issues: [iss(1, "返回是尖角。"), iss(2, "标题偏左。")] }],
};
const g = { trusted: true, surface: "面 1 · DM 私信", title: "[UI] 返回是尖角 等 2 个问题 · DM 私信", sev: "P2" as const, picks: [{ pageId: "s1-dm/03-requests", n: 1, lang: "en" }, { pageId: "s1-dm/03-requests", n: 2, lang: "en" }] };
const description = renderAuditFixDescription(g, {
data: { report, shots: [{ pageId: "s1-dm/03-requests", lang: "en", file: "a.png", boxes: { 1: [{ x: 1.9, y: 7.6, w: 9.7, h: 4.8 }] } }] },
source: { id: "553ebfef-ba45", title: "导航栏" }, notes: { "s1-dm/03-requests#2": { note: "左对齐 16dp" } },
files: { "a.png": "images/plan-11111111-1111-1111-1111-111111111111.png" },
});
expect(auditSourceId(description)).toBe("553ebfef-ba45");
const issues = auditFiledIssues(description);
expect(issues.map((i) => [i.fid, i.severity, i.pageId, i.pageTitle, i.lang, i.headline])).toEqual([
["F-01", "P2", "s1-dm/03-requests", "消息请求页", "en", "返回是尖角。"],
["F-02", "P2", "s1-dm/03-requests", "消息请求页", "en", "标题偏左。"],
]);
expect(issues[0].image).toBe("https://voffline.byted.org/download/tos/schedule/streamline/img_upload/plan-11111111-1111-1111-1111-111111111111.png");
expect(issues[0].boxes).toEqual([{ x: 1.9, y: 7.6, w: 9.7, h: 4.8 }]);
expect(issues[0].expected).toBe("");
expect(issues[1].expected).toBe("左对齐 16dp");
expect(issues[0].repro).toBe("Inbox → Requests");
expect(issues[0].cause).toBe("图标资源传错");
expect(issues[0].code).toBe("a/B.kt");
});
});
test("page titles that contain their own parentheses still parse", () => {
const d = "来源:验证任务「x」(v-1)\n\n## F-38 · P2 · 布局 · `s3-story/10-post-page`(主拍发布页(Post)) @ en\n- 实际:发布按钮矮一截。\n- 期望:(复核人没写。按 TUX 规范)\n";
const [i] = auditFiledIssues(d);
expect([i.fid, i.pageTitle, i.lang, i.headline, i.expected]).toEqual(["F-38", "主拍发布页(Post)", "en", "发布按钮矮一截。", ""]);
});
@@ -0,0 +1,39 @@
import { describe, expect, test } from "bun:test";
import { issueParam, normCat, parseIssueParam } from "../src/components/AuditIssueReport";
import { parseLocation, routeToPath } from "../src/lib/router";
/** 交付报告按六个类别分页签:新报告照 prompt 填固定词,老报告的自由类别按关键词归进来。 */
describe("normCat", () => {
test("固定词原样", () => {
for (const c of ["功能", "热区", "文案与多语言", "颜色", "布局", "组件规范"]) expect(normCat(c)).toBe(c as never);
});
test("老报告的自由类别", () => {
expect(normCat("文案截断 / 折行")).toBe("文案与多语言");
expect(normCat("热区异常或过小")).toBe("热区");
expect(normCat("老旧组件样式 / 颜色一致性")).toBe("颜色");
expect(normCat("功能缺陷 / 持久化同步")).toBe("功能");
expect(normCat("间距")).toBe("布局");
expect(normCat("")).toBe("其他");
});
});
/** 单条问题的分享链接:/verify?id=…&issue=<页面 id>:<序号>。页面 id 里带斜杠和冒号也得原样回来。 */
describe("分享链接", () => {
test("issue 参数解析", () => {
expect(parseIssueParam(issueParam("s1-profile/30-friends-list-empty", 3))).toEqual({ pageId: "s1-profile/30-friends-list-empty", n: 3 });
expect(parseIssueParam("a:b/c:12")).toEqual({ pageId: "a:b/c", n: 12 });
expect(parseIssueParam("no-number")).toBeNull();
expect(parseIssueParam(":3")).toBeNull();
expect(parseIssueParam("p:0")).toBeNull();
});
test("路由往返,页面加载时规范化地址不会把 issue 丢掉", () => {
const route = { view: "detail" as const, kind: "verify" as const, id: "e3c30b3d", issue: issueParam("s1-profile/12-find-friends", 1) };
const path = routeToPath(route);
expect(path).toBe("/verify?id=e3c30b3d&issue=s1-profile%2F12-find-friends%3A1");
const [pathname, search] = path.split("?");
expect(parseLocation({ pathname, search: `?${search}` })).toEqual(route);
});
test("别的任务类型不认 issue", () => {
expect(parseLocation({ pathname: "/bugfix", search: "?id=x&issue=p:1" })).toEqual({ view: "detail", kind: "bug", id: "x" });
});
});
+25
View File
@@ -0,0 +1,25 @@
import { test, expect } from "bun:test";
import { reviewItemsAwaitingMyToken } from "../src/lib/bitsTokenNudge";
import type { BoardItem } from "../src/types";
const ME = "zhang.san@bytedance.com";
const mk = (over: Record<string, unknown>): BoardItem =>
({ kind: "bug", id: "x", title: "t", status: "manual_review", mrUrl: null, watchers: [ME], ...over } as unknown as BoardItem);
test("名下待复核、没 MR 的 Bug / Feature 才算", () => {
const items = [
mk({ id: "bug" }),
mk({ id: "feature", kind: "feature" }),
mk({ id: "has-mr", mrUrl: "https://bits.bytedance.net/code/x/merge_requests/1" }),
mk({ id: "running", status: "fixing" }),
mk({ id: "security", kind: "security" }),
mk({ id: "others", watchers: ["li.si@bytedance.com", "oc_group"] }),
];
expect(reviewItemsAwaitingMyToken(items, ME).map((it) => it.id)).toEqual(["bug", "feature"]);
});
test("邮箱大小写不敏感;没有身份就不提醒", () => {
const items = [mk({ watchers: ["Zhang.San@ByteDance.com"] })];
expect(reviewItemsAwaitingMyToken(items, ME)).toHaveLength(1);
expect(reviewItemsAwaitingMyToken(items, "")).toHaveLength(0);
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, test } from "bun:test";
import { boardColumnOf } from "../src/lib/board";
import type { BoardItem } from "../src/types";
/** 批量任务的任务清单用首页看板的列名写状态:同一张卡在两处必须是同一个词。 */
const bug = (x: Partial<BoardItem> & { status: string }) => ({ kind: "bug", meegoState: null, mrState: null, mergedIntoBaseAt: null, watchWithdrawn: null, ...x }) as unknown as BoardItem;
describe("boardColumnOf:首页看板上的列", () => {
test("待人工复核 → 结果审阅;评估中和待确认拆成两列", () => {
expect(boardColumnOf(bug({ status: "manual_review" })).label).toBe("col.review");
expect(boardColumnOf(bug({ status: "initializing" })).label).toBe("col.evaluating");
expect(boardColumnOf(bug({ status: "info_required" })).label).toBe("col.confirm");
expect(boardColumnOf(bug({ status: "awaiting_fix" })).label).toBe("col.queued");
expect(boardColumnOf(bug({ status: "fixing" })).label).toBe("col.running");
});
test("复核通过之后按 MR / Meego 分:待 QA、MR 待合入、已完成、QA 打回", () => {
expect(boardColumnOf(bug({ status: "fix_succeeded" })).label).toBe("col.qa");
expect(boardColumnOf(bug({ status: "fix_succeeded", meegoState: "CLOSED", mrState: "opened" })).label).toBe("col.awaitingMerge");
expect(boardColumnOf(bug({ status: "fix_succeeded", meegoState: "CLOSED", mrState: "merged" })).label).toBe("col.done");
expect(boardColumnOf(bug({ status: "fix_succeeded", meegoState: "REOPENED" })).label).toBe("col.qaReopened");
});
test("托管期间撤回的算「平台没跑」,负责人归档的算归档", () => {
expect(boardColumnOf(bug({ status: "cancelled", watchWithdrawn: "meego_closed" })).label).toBe("col.notRunSplit");
expect(boardColumnOf(bug({ status: "archived", watchWithdrawn: "owner_archived" })).label).toBe("col.archived");
expect(boardColumnOf(bug({ status: "cancelled" })).label).toBe("col.failed");
});
});
+55
View File
@@ -0,0 +1,55 @@
import { test, expect, describe, afterEach } from "bun:test";
import { startBoardBoot } from "../src/lib/boardLoad";
// Records every request path in order and answers with a list shaped for it.
const realFetch = globalThis.fetch;
let seen: string[] = [];
function mockFetch(): void {
seen = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = new URL(String(input), "http://x");
const path = url.pathname + url.search;
seen.push(path);
const key = url.pathname.split("/").pop()!;
const phase = url.searchParams.get("phase") ?? "all";
const body: Record<string, unknown> =
key === "tasks" ? { tasks: [{ id: `t-${phase}` }], currentId: null }
: key === "nodes" ? { nodes: [], eval: { inFlight: 0, capacity: 0 }, fix: { inFlight: 0, capacity: 0 } }
: { [key]: [{ id: `${key}-${phase}` }] };
return new Response(JSON.stringify(body), { headers: { "content-type": "application/json" } });
}) as typeof fetch;
}
afterEach(() => { globalThis.fetch = realFetch; });
describe("startBoardBoot", () => {
test("first phase asks for the active slice; done follows it", async () => {
mockFetch();
const boot = startBoardBoot(null);
const a = await boot.active;
expect(a.tasks.map((t) => t.id)).toEqual(["t-active"]);
expect(a.features.map((f) => f.id)).toEqual(["features-active"]);
expect(a.prototypes.map((p) => p.id)).toEqual(["prototypes-all"]);
const d = await boot.done;
expect(d.tasks.map((t) => t.id)).toEqual(["t-done"]);
expect(d.security.map((s) => s.id)).toEqual(["security-done"]);
const firstDone = seen.findIndex((p) => p.includes("phase=done"));
const lastActive = Math.max(...seen.map((p, i) => (p.includes("phase=active") ? i : -1)));
expect(firstDone).toBeGreaterThan(lastActive);
// Prototypes / verifications are never sliced.
expect(seen.filter((p) => p.startsWith("/api/prototypes"))).toEqual(["/api/prototypes"]);
expect(seen.filter((p) => p.startsWith("/api/verifications"))).toEqual(["/api/verifications"]);
});
test("a pending hold gates every request", async () => {
mockFetch();
let release!: () => void;
const hold = new Promise<void>((r) => { release = r; });
const boot = startBoardBoot(hold);
await new Promise((r) => setTimeout(r, 20));
expect(seen).toEqual([]);
release();
await boot.active;
expect(seen.some((p) => p === "/api/tasks?phase=active")).toBe(true);
expect(seen.some((p) => p === "/api/nodes")).toBe(true);
});
});
+188
View File
@@ -0,0 +1,188 @@
import { test, expect, describe, beforeEach } from "bun:test";
import type { BoardItem } from "../src/types";
import {
mergeMissing, removeOne, replaceRows, sameRow, shallowEqualArr, tagItem, upsertOne, upsertRows,
} from "../src/lib/boardRows";
import { columnSections } from "../src/lib/board";
import {
applyClusterSnapshot, applyListEval, getClusterState, resetClusterStoreForTest, setClusterState,
} from "../src/lib/clusterStore";
type R = { id: string; status: string; n?: number };
const row = (id: string, status = "fixing", n = 0): R => ({ id, status, n });
describe("tagItem — stable identity per source row", () => {
test("same source object → same tagged object", () => {
const r = row("a");
const t1 = tagItem("bug", r as never);
const t2 = tagItem("bug", r as never);
expect(t1).toBe(t2);
expect(t1).toEqual({ kind: "bug", ...r } as unknown as BoardItem);
});
test("a replaced source row gets a new tagged object", () => {
const a = row("a");
const b = { ...a, status: "fix_failed" };
expect(tagItem("bug", a as never)).not.toBe(tagItem("bug", b as never));
});
test("one WS update re-tags exactly one row", () => {
const rows = [row("a"), row("b"), row("c")];
const before = rows.map((r) => tagItem("feature", r as never));
const next = upsertOne(rows, row("b", "implementing", 1));
const after = next.map((r) => tagItem("feature", r as never));
expect(after[0]).toBe(before[0]);
expect(after[1]).not.toBe(before[1]);
expect(after[2]).toBe(before[2]);
});
});
describe("upsertOne / removeOne", () => {
test("identical payload is a no-op (same array back)", () => {
const rows = [row("a"), row("b")];
expect(upsertOne(rows, { ...rows[1] })).toBe(rows);
});
test("changed payload replaces in place, unknown id appends", () => {
const rows = [row("a"), row("b")];
const changed = upsertOne(rows, row("a", "done"));
expect(changed.map((r) => r.status)).toEqual(["done", "fixing"]);
expect(changed[1]).toBe(rows[1]);
expect(upsertOne(rows, row("c")).map((r) => r.id)).toEqual(["a", "b", "c"]);
});
test("removeOne of a missing id returns the same array", () => {
const rows = [row("a")];
expect(removeOne(rows, "zz")).toBe(rows);
expect(removeOne(rows, "a")).toEqual([]);
});
});
describe("replaceRows — full refetch keeps unchanged rows", () => {
test("nothing changed → previous array", () => {
const prev = [row("a"), row("b")];
const fetched = prev.map((r) => ({ ...r }));
expect(replaceRows(prev, fetched)).toBe(prev);
});
test("one changed, one gone, one new", () => {
const prev = [row("a"), row("b"), row("c")];
const fetched = [{ ...prev[0] }, row("b", "fix_failed"), row("d")];
const out = replaceRows(prev, fetched);
expect(out.map((r) => r.id)).toEqual(["a", "b", "d"]);
expect(out[0]).toBe(prev[0]);
expect(out[1]).not.toBe(prev[1]);
});
test("skip drops rows deleted while the request was in flight", () => {
const out = replaceRows([], [row("a"), row("b")], new Set(["a"]));
expect(out.map((r) => r.id)).toEqual(["b"]);
});
test("reordered but identical rows still report a change (order matters to callers)", () => {
const prev = [row("a"), row("b")];
const out = replaceRows(prev, [{ ...prev[1] }, { ...prev[0] }]);
expect(out).not.toBe(prev);
expect(out[0]).toBe(prev[1]);
});
});
describe("two-phase load merge", () => {
test("active upsert keeps rows outside the slice", () => {
const prev = [row("done1", "fix_succeeded"), row("q1", "awaiting_fix", 1)];
const out = upsertRows(prev, [row("q1", "awaiting_fix", 2), row("q2", "awaiting_fix")]);
expect(out.map((r) => r.id)).toEqual(["done1", "q1", "q2"]);
expect(out[0]).toBe(prev[0]);
expect(out[1].n).toBe(2);
});
test("active upsert with nothing new → previous array", () => {
const prev = [row("a"), row("b")];
expect(upsertRows(prev, [{ ...prev[0] }])).toBe(prev);
});
test("done merge inserts only missing ids — a fresher WS row wins", () => {
const wsFresh = row("x", "fix_succeeded", 9);
const prev = [row("a"), wsFresh];
const out = mergeMissing(prev, [row("x", "fix_succeeded", 1), row("d1", "fix_succeeded")]);
expect(out.map((r) => r.id)).toEqual(["a", "x", "d1"]);
expect(out[1]).toBe(wsFresh);
});
test("an old server ignoring ?phase returns everything twice — harmless", () => {
const all = [row("a"), row("b", "fix_succeeded"), row("c", "archived")];
const afterActive = upsertRows([], all.map((r) => ({ ...r })));
const afterDone = mergeMissing(afterActive, all.map((r) => ({ ...r })));
expect(afterDone).toBe(afterActive);
expect(afterDone.map((r) => r.id)).toEqual(["a", "b", "c"]);
});
test("a row deleted over the WS meanwhile is not resurrected", () => {
const out = mergeMissing([row("a")], [row("gone"), row("d")], new Set(["gone"]));
expect(out.map((r) => r.id)).toEqual(["a", "d"]);
});
test("duplicate ids inside one response collapse to one row", () => {
expect(upsertRows([], [row("a"), row("a", "x")]).length).toBe(1);
expect(mergeMissing([], [row("a"), row("a")]).length).toBe(1);
});
});
describe("small helpers", () => {
test("sameRow / shallowEqualArr", () => {
expect(sameRow({ a: 1, b: [1] }, { a: 1, b: [1] })).toBe(true);
expect(sameRow({ a: 1 }, { a: 2 })).toBe(false);
const x = row("x"); const y = row("y");
expect(shallowEqualArr([x, y], [x, y])).toBe(true);
expect(shallowEqualArr([x, y], [x, { ...y }])).toBe(false);
expect(shallowEqualArr([x], [x, y])).toBe(false);
});
});
describe("columnSections", () => {
const items = [row("1", "merged"), row("2", "merged"), row("3", "evaluate_finish"), row("4", "archived"), row("5", "archived")];
const dividers = [
{ before: (it: R) => it.status === "evaluate_finish", label: "EF" },
{ before: (it: R) => it.status === "archived", label: "AR" },
];
test("splits at the first match of each divider", () => {
expect(columnSections(items, dividers)).toEqual([
{ key: "head", label: null, start: 0, end: 2 },
{ key: "d0", label: "EF", start: 2, end: 3 },
{ key: "d1", label: "AR", start: 3, end: 5 },
]);
});
test("a divider matching index 0 or nothing adds no section", () => {
expect(columnSections(items, [{ before: (it: R) => it.status === "merged", label: "M" }, { before: () => false, label: "Z" }]))
.toEqual([{ key: "head", label: null, start: 0, end: 5 }]);
});
test("two dividers at the same index: the later label wins", () => {
const s = columnSections(items, [
{ before: (it: R) => it.status === "archived", label: "first" },
{ before: (it: R) => it.id === "4", label: "second" },
]);
expect(s).toEqual([
{ key: "head", label: null, start: 0, end: 3 },
{ key: "d1", label: "second", start: 3, end: 5 },
]);
});
test("no dividers / empty list", () => {
expect(columnSections(items)).toEqual([{ key: "head", label: null, start: 0, end: 5 }]);
expect(columnSections([], dividers)).toEqual([{ key: "head", label: null, start: 0, end: 0 }]);
});
});
describe("clusterStore", () => {
beforeEach(() => resetClusterStoreForTest());
const node = (id: string, lastSeenAt = 1) => ({ id, lastSeenAt, platform: "ios", status: "online" }) as never;
test("an identical snapshot changes nothing (same references)", () => {
applyClusterSnapshot({ nodes: [node("n1")], eval: { inFlight: 1, capacity: 2 }, fix: { inFlight: 0, capacity: 1 } });
const s1 = getClusterState();
applyClusterSnapshot({ nodes: [node("n1")], eval: { inFlight: 1, capacity: 2 }, fix: { inFlight: 0, capacity: 1 } });
expect(getClusterState()).toBe(s1);
});
test("only the changed slice gets a new reference", () => {
applyClusterSnapshot({ nodes: [node("n1")], eval: { inFlight: 1, capacity: 2 }, fix: { inFlight: 0, capacity: 1 } });
const s1 = getClusterState();
expect(setClusterState({ eval: { inFlight: 2, capacity: 2 } })).toBe(true);
const s2 = getClusterState();
expect(s2).not.toBe(s1);
expect(s2.nodes).toBe(s1.nodes);
expect(s2.eval).toEqual({ inFlight: 2, capacity: 2 });
});
test("the list's eval figure is only a fallback before any snapshot", () => {
applyListEval({ inFlight: 3, capacity: 4 });
expect(getClusterState().eval).toEqual({ inFlight: 3, capacity: 4 });
applyClusterSnapshot({ nodes: [], eval: { inFlight: 1, capacity: 4 }, fix: { inFlight: 0, capacity: 0 } });
applyListEval({ inFlight: 9, capacity: 9 });
expect(getClusterState().eval).toEqual({ inFlight: 1, capacity: 4 });
});
});
@@ -0,0 +1,37 @@
import { expect, test } from "bun:test";
import { checkpointBugText } from "../src/components/CheckpointBugFiling";
const source = { id: "5a9c7764-6f98-47c2-b3e0-f2599143d471", title: "Add to Story 草稿恢复", platform: "android", clusters: [] };
const c = {
id: "C03", path: ["普通快拍草稿里的 @ 贴纸不受影响"], pre: "登录任意账号", step: "1. 添加 @ 贴纸\n2. 保存草稿再打开", videos: [],
checkpoints: [] as never[],
};
const p = { no: 5, expect: "重新打开后 @ 贴纸仍在、只有一个", verdict: "fail" as const, actual: "@ 贴纸往左上偏了约 40px", detail: "复现 2 次", shot: "c05.png" };
const meta = [
{ label: "被测提交", value: "5f856ef24f56 · fix/x" }, { label: "被测包", value: "47.6.0" }, { label: "设备", value: "Pixel 7" },
];
test("首行是标题(写了期望就用期望);期望、实际、用例、截图、被测提交和来源都在;设备这类无关元信息不进", () => {
const t = checkpointBugText(source, c, p, "贴纸应该停在保存前的位置", { meta, shotUrl: "https://cdn/x/c05.png" });
const lines = t.split("\n");
expect(lines[0]).toBe("【验证转单】普通快拍草稿里的 @ 贴纸不受影响 · 贴纸应该停在保存前的位置");
expect(t).toContain("**应该是什么样**:贴纸应该停在保存前的位置");
expect(t).toContain("**验证时实际看到**:@ 贴纸往左上偏了约 40px");
expect(t).toContain("**细节**:复现 2 次");
expect(t).toContain("用例 C03 · 检查点 #5");
expect(t).toContain("操作步骤:1. 添加 @ 贴纸\n2. 保存草稿再打开");
expect(t).toContain("检查点预期:重新打开后 @ 贴纸仍在、只有一个");
expect(t).toContain("截图:https://cdn/x/c05.png");
expect(t).toContain("被测提交:5f856ef24f56 · fix/x");
expect(t).toContain("被测包:47.6.0");
expect(t).not.toContain("Pixel 7");
expect(t).toContain(`?task_id=${source.id}`);
});
test("没写期望就用检查点预期;阻塞的检查点写清卡在哪", () => {
const blocked = { ...c, blocked: { caseId: "C03", where: "没有互关账号", progress: "" } };
const t = checkpointBugText(source, blocked, { ...p, verdict: "blocked" as never, actual: "", detail: "", shot: null }, " ", { meta: [], shotUrl: null });
expect(t.split("\n")[0]).toBe("【验证转单】普通快拍草稿里的 @ 贴纸不受影响 · 重新打开后 @ 贴纸仍在、只有一个");
expect(t).toContain("没走到 —— 卡在:没有互关账号");
expect(t).not.toContain("截图:");
});
+123
View File
@@ -0,0 +1,123 @@
import { test, expect, describe } from "bun:test";
import { primaryCluster, compareNodesByCluster } from "../src/lib/clusters";
import type { ClusterNode } from "../src/types";
import { clustersIntersect } from "../src/types";
const node = (id: string, clusters?: string[] | null): ClusterNode => ({
id, baseUrl: "http://x", platform: "ios", status: "online",
lastSeenAt: 0, evalInFlight: 0, evalCapacity: 3, fixInFlight: 0, fixCapacity: 1,
version: null, createdAt: 0, clusters: clusters ?? undefined,
} as ClusterNode);
const order = (ns: ClusterNode[]) => [...ns].sort(compareNodesByCluster).map((n) => n.id);
describe("primaryCluster", () => {
test("default wins over any other tag it is combined with", () => {
// A node serving the baseline pool belongs with the baseline group no matter
// what else it also carries, otherwise it drifts away from its pool-mates.
expect(primaryCluster(node("a", ["im-sg", "default"]))).toBe("default");
expect(primaryCluster(node("b", ["default"]))).toBe("default");
});
test("otherwise the alphabetically first tag, so the group is stable", () => {
expect(primaryCluster(node("a", ["pns", "im-sg"]))).toBe("im-sg");
});
test("a parked node has none", () => {
expect(primaryCluster(node("a", []))).toBeNull();
expect(primaryCluster(node("a", null))).toBeNull();
});
});
describe("compareNodesByCluster", () => {
test("default group comes first even though 'd' sorts after nothing special", () => {
// 'im-sg' < 'pns' alphabetically, and both would outrank 'default' under a
// plain string sort in some collations — default is pinned, not sorted.
expect(order([
node("z-im", ["im-sg"]),
node("a-pns", ["pns"]),
node("m-def", ["default"]),
])).toEqual(["m-def", "z-im", "a-pns"]);
});
test("named groups follow in alphabetical order", () => {
expect(order([
node("n1", ["pns"]),
node("n2", ["im-sg"]),
node("n3", ["default"]),
])).toEqual(["n3", "n2", "n1"]);
});
test("inside a group, node ids sort numerically", () => {
// fei-ios-10 must not precede fei-ios-2 the way a plain string sort would.
expect(order([
node("fei-ios-10", ["default"]),
node("fei-ios-2", ["default"]),
node("fei-ios-1", ["default"]),
])).toEqual(["fei-ios-1", "fei-ios-2", "fei-ios-10"]);
});
test("parked nodes sink to the end", () => {
expect(order([
node("parked", []),
node("named", ["pns"]),
node("base", ["default"]),
])).toEqual(["base", "named", "parked"]);
});
test("matches the real fleet's expected layout", () => {
const fleet = [
node("pns-android-01.shiro0.icu", ["pns"]),
node("fei-ios-02.shiro0.icu", ["default"]),
node("messaging-sg", ["im-sg"]),
node("fei-android-01.shiro0.icu", ["default"]),
node("messaging-sg-ios", ["im-sg"]),
node("temp-ios-01", ["default"]),
node("fei-ios-01.shiro0.icu", ["default"]),
];
expect(order(fleet)).toEqual([
// default pool, by name
"fei-android-01.shiro0.icu", "fei-ios-01.shiro0.icu", "fei-ios-02.shiro0.icu", "temp-ios-01",
// then #im-sg
"messaging-sg", "messaging-sg-ios",
// then #pns
"pns-android-01.shiro0.icu",
]);
});
test("is a total order — sorting is stable under input shuffling", () => {
const fleet = [
node("b", ["pns"]), node("a", ["default"]), node("c", []), node("d", ["im-sg"]),
];
const once = order(fleet);
expect(order([...fleet].reverse())).toEqual(once);
});
});
/**
* The pool rule the capability strip depends on.
*
* "default" is a real tag, not the absence of one: an untagged task is mapped to
* `{default}` by requiredClustersOf, so it runs on `#default` nodes — while a
* node carrying NO tags is parked and runs nothing. Reading that backwards makes
* the untagged pool look empty, which is how the capability endpoint first
* reported `nodes: 0` for the pool that has three machines in it.
*/
describe("clustersIntersect — which pool an untagged task lands on", () => {
const untagged = { clusters: [] };
test("an untagged task runs on the #default pool", () => {
expect(clustersIntersect(["default"], untagged)).toBe(true);
expect(clustersIntersect(["default", "im-sg"], untagged)).toBe(true);
});
test("a parked node (no tags) runs nothing at all", () => {
expect(clustersIntersect([], untagged)).toBe(false);
expect(clustersIntersect(null, { clusters: ["im-sg"] })).toBe(false);
});
test("a tagged task stays inside its own pool", () => {
expect(clustersIntersect(["im-sg"], { clusters: ["im-sg"] })).toBe(true);
expect(clustersIntersect(["default"], { clusters: ["im-sg"] })).toBe(false);
});
});
+65
View File
@@ -0,0 +1,65 @@
import { test, expect, describe } from "bun:test";
import { rehypeCodeHighlight } from "../src/lib/codeHighlight";
/**
* 抽屉 markdown 的代码高亮换掉了 rehype-highlight(见 lib/codeHighlight.ts 头注释)。
* 这里钉住它和旧插件对齐的那几条:只动 `pre > code`、显式语言才高亮、没标语言的块
* 仍挂 `hljs` 类(样式不变)、不认识的语言和 no-highlight 保留原文。
*/
type N = { type: string; tagName?: string; value?: string; properties?: Record<string, unknown>; children?: N[] };
const text = (value: string): N => ({ type: "text", value });
const code = (cls: string[] | undefined, body: string): N => ({
type: "element", tagName: "code", properties: cls ? { className: cls } : {}, children: [text(body)],
});
const pre = (c: N): N => ({ type: "element", tagName: "pre", properties: {}, children: [c] });
const root = (...children: N[]): N => ({ type: "root", children });
const run = (tree: N) => { rehypeCodeHighlight()(tree); return tree; };
const classes = (n: N) => n.properties?.className as string[] | undefined;
const hasSpans = (n: N) => (n.children ?? []).some((c) => c.type === "element" && c.tagName === "span");
describe("rehypeCodeHighlight", () => {
test("显式语言的围栏代码块被高亮", () => {
const c = code(["language-kotlin"], "fun main() { val x = 1 }");
run(root(pre(c)));
expect(classes(c)?.[0]).toBe("hljs");
expect(hasSpans(c)).toBe(true);
});
test("语言别名(kt / sh / objc / yml)随语法注册生效", () => {
for (const alias of ["kt", "sh", "objc", "yml", "ts", "diff"]) {
const c = code([`language-${alias}`], "a: 1\n+ b\nlet x = 1");
run(root(pre(c)));
expect(classes(c)).toContain("hljs");
}
const c = code(["language-sh"], "echo $HOME");
run(root(pre(c)));
expect(hasSpans(c)).toBe(true);
});
test("没标语言:不做自动识别,但挂 hljs 类(外观与以前一致)", () => {
const c = code(undefined, "const x = { a: 1 };");
run(root(pre(c)));
expect(classes(c)).toEqual(["hljs"]);
expect(c.children).toEqual([text("const x = { a: 1 };")]);
});
test("不认识的语言保留原文,不抛", () => {
const c = code(["language-brainfuck"], "+++[>+<-]");
expect(() => run(root(pre(c)))).not.toThrow();
expect(c.children).toEqual([text("+++[>+<-]")]);
});
test("no-highlight 跳过,连 hljs 类都不加", () => {
const c = code(["language-js", "no-highlight"], "let a");
run(root(pre(c)));
expect(classes(c)).toEqual(["language-js", "no-highlight"]);
});
test("行内 code(不在 pre 里)不动", () => {
const c = code(["language-js"], "let a");
const p: N = { type: "element", tagName: "p", properties: {}, children: [c] };
run(root(p));
expect(classes(c)).toEqual(["language-js"]);
});
});
+410
View File
@@ -0,0 +1,410 @@
import { test, expect, describe } from "bun:test";
import type { BoardItem, ClusterNode } from "../src/types";
import {
computeDashMetrics, isSucceeded, isOutcome, isTaskFinished, pct, pieConic, kindBucketCounts, kindPieSlices, kindOtherSlices, outcomeBandOf, outcomeDisplayN, inStableCohort, stableCohortCutoffExclusiveMs, stableCohortLastDay, PIPELINE_BUCKETS,
} from "../src/lib/dashMetrics";
import { bucketOf, mrIsClosed } from "../src/lib/board";
import { comboTaskStateOf } from "../src/types";
function bug(over: Record<string, unknown>): BoardItem {
return {
kind: "bug", id: "b", title: "t", platform: "android",
status: "awaiting_fix", attempts: 0, createdAt: 1,
...over,
} as BoardItem;
}
function feat(over: Record<string, unknown>): BoardItem {
return {
kind: "feature", id: "f", title: "t", platform: "ios",
status: "awaiting_implementation", attempts: 0, createdAt: 1,
...over,
} as BoardItem;
}
function sec(over: Record<string, unknown>): BoardItem {
return {
kind: "security", id: "s", title: "t", platform: "android",
status: "awaiting_security", attempts: 0, createdAt: 1,
...over,
} as BoardItem;
}
function node(over: Partial<ClusterNode> & { id: string }): ClusterNode {
return {
baseUrl: "http://n", platform: "android", status: "online",
lastSeenAt: 1, evalInFlight: 0, evalCapacity: 1,
fixInFlight: 0, fixCapacity: 1, version: null, createdAt: 1, live: true,
...over,
} as ClusterNode;
}
describe("pct", () => {
test("rounds and guards a zero denominator", () => {
expect(pct(1, 2)).toBe(50);
expect(pct(2, 3)).toBe(67);
expect(pct(0, 0)).toBe(0);
});
});
describe("稳定队列 — 今天 − 14 天(北京日,含截止日)", () => {
// 2026-09-03 18:30 UTC = 北京 9/4 02:30 → 截止日 8/21,次日 0 点 = 8/21 16:00 UTC。
const now = Date.parse("2026-09-03T18:30:00Z");
test("截止日是北京今天减 14 天", () => {
expect(stableCohortLastDay(now)).toBe("2026-08-21");
expect(stableCohortCutoffExclusiveMs(now)).toBe(Date.parse("2026-08-21T16:00:00Z"));
});
test("截止日当天还在队列里,次日 0 点起不算", () => {
expect(inStableCohort({ createdAt: Date.parse("2026-08-21T15:59:59Z") }, now)).toBe(true);
expect(inStableCohort({ createdAt: Date.parse("2026-08-21T16:00:00Z") }, now)).toBe(false);
expect(inStableCohort({ createdAt: 0 }, now)).toBe(false);
});
});
describe("pieConic", () => {
test("空数据是一圈底色,对半切开贴到 180/360", () => {
expect(pieConic([])).toBe("var(--border)");
expect(pieConic([{ color: "#0f0", n: 0 }])).toBe("var(--border)");
expect(pieConic([{ color: "#0f0", n: 1 }, { color: "#f00", n: 1 }]))
.toBe("#0f0 0.0deg 180.0deg, #f00 180.0deg 360.0deg");
});
});
describe("isSucceeded / isOutcome — 三类任务各自的终态", () => {
test("bug 以 fix_succeeded 为通过,cancelled 不进分母", () => {
expect(isSucceeded(bug({ status: "fix_succeeded" }))).toBe(true);
expect(isOutcome(bug({ status: "fix_succeeded" }))).toBe(true);
expect(isOutcome(bug({ status: "fix_failed" }))).toBe(true);
expect(isOutcome(bug({ status: "unreproducible" }))).toBe(true);
expect(isOutcome(bug({ status: "archived" }))).toBe(true);
expect(isSucceeded(bug({ status: "archived" }))).toBe(false);
expect(isOutcome(bug({ status: "cancelled" }))).toBe(false);
expect(isOutcome(bug({ status: "manual_review" }))).toBe(false);
expect(isOutcome(bug({ status: "evaluate_finish" }))).toBe(false);
expect(isSucceeded(bug({ status: "evaluate_finish" }))).toBe(false);
});
test("feature / security 以 completed 为通过", () => {
expect(isSucceeded(feat({ status: "completed" }))).toBe(true);
expect(isOutcome(feat({ status: "implementation_failed" }))).toBe(true);
expect(isOutcome(feat({ status: "archived" }))).toBe(true);
expect(isSucceeded(feat({ status: "archived" }))).toBe(false);
expect(isOutcome(feat({ status: "cancelled" }))).toBe(false);
expect(isSucceeded(sec({ status: "completed" }))).toBe(true);
expect(isOutcome(sec({ status: "unreproducible" }))).toBe(true);
expect(isOutcome(sec({ status: "security_failed" }))).toBe(true);
});
});
describe("isTaskFinished — 流转中 + 待合入 + 已完成 + 确认无法复现", () => {
test("fix_succeeded 全体和确认无法复现算完成;未确认的无法复现不算", () => {
expect(isTaskFinished(bug({
status: "fix_succeeded", mrState: "merged", meegoState: "done",
}))).toBe(true);
expect(isTaskFinished(bug({
status: "fix_succeeded", mergedIntoBaseAt: 1,
}))).toBe(true);
expect(isTaskFinished(bug({
status: "fix_succeeded", mrState: "opened", meegoState: "resolved",
}))).toBe(true);
expect(isTaskFinished(bug({
status: "fix_succeeded", mrState: "opened", meegoState: "done",
}))).toBe(true);
expect(isTaskFinished(feat({ status: "completed" }))).toBe(true);
expect(isTaskFinished(bug({
status: "unreproducible", meegoState: "closed",
}))).toBe(true);
expect(isTaskFinished(bug({
status: "unreproducible", meegoState: "RESOLVED",
}))).toBe(true);
expect(isTaskFinished(bug({ status: "unreproducible", meegoState: "open" }))).toBe(false);
expect(isTaskFinished(bug({ status: "fix_failed" }))).toBe(false);
expect(isTaskFinished(bug({ status: "archived" }))).toBe(false);
expect(isTaskFinished(feat({ status: "archived" }))).toBe(false);
expect(isTaskFinished(bug({ status: "manual_review" }))).toBe(false);
expect(isTaskFinished(bug({ status: "evaluate_finish" }))).toBe(false);
});
test("Meego 已 close/done:MR closed → DONE;开着或没有 MR → 待合入;Bits 已合入 → DONE", () => {
expect(bucketOf(bug({
status: "fix_succeeded", meegoState: "CLOSED", mrState: null,
}))).toBe("awaiting_merge");
expect(bucketOf(bug({
status: "fix_succeeded", meegoState: "done", mrState: "closed",
}))).toBe("merged");
expect(bucketOf(bug({
status: "fix_succeeded", meegoState: "done", mrState: "opened",
}))).toBe("awaiting_merge");
expect(bucketOf(bug({
status: "fix_succeeded", meegoState: "done", mrState: "merged",
}))).toBe("merged");
expect(bucketOf(bug({
status: "fix_succeeded", meegoState: "RESOLVED", mrState: "opened",
}))).toBe("awaiting_qa");
expect(bucketOf(bug({
status: "unreproducible", meegoState: "RESOLVED",
}))).toBe("confirmed_unrepro");
expect(bucketOf(bug({
status: "unreproducible", meegoState: "open",
}))).toBe("unreproducible");
});
test("MR / QA 进度只属于 fix_succeeded:从无法复现打回、带着 OPEN 重跑的单不是待 QA", () => {
for (const status of ["awaiting_fix", "fixing", "manual_review", "unreproducible"]) {
expect(comboTaskStateOf({ status, mrState: null, meegoState: "OPEN" })).toBeNull();
}
expect(bucketOf(bug({ status: "fixing", meegoState: "OPEN" }))).toBe("running");
for (const m of ["OPEN", "IN PROGRESS", "RESOLVED"]) {
expect(comboTaskStateOf({ status: "fix_succeeded", mrState: null, meegoState: m })).toBe("awaiting_qa");
}
expect(comboTaskStateOf({ status: "fix_succeeded", mrState: "merged", meegoState: "REOPENED" })).toBe("qa_reopened");
});
test("QA 打回(fix_succeeded + REOPENED):盖过任何合入信号,算待处理、不算通过;QA 再解决就回到待 QA", () => {
for (const over of [{ mrState: "opened" }, { mrState: "merged" }, { mergedIntoBaseAt: 5 }]) {
const it = bug({ status: "fix_succeeded", meegoState: "REOPENED", ...over });
expect(bucketOf(it)).toBe("qa_reopened");
expect(outcomeBandOf(it)).toBe("pending");
expect(isSucceeded(it)).toBe(false);
expect(isTaskFinished(it)).toBe(false);
}
const back = bug({ status: "fix_succeeded", meegoState: "RESOLVED", mrState: "opened" });
expect(bucketOf(back)).toBe("awaiting_qa");
expect(isSucceeded(back)).toBe(true);
});
test("mrIsClosed — Bits closed/close 才算关,opened / 缺省不算", () => {
expect(mrIsClosed({ mrState: "closed" })).toBe(true);
expect(mrIsClosed({ mrState: "CLOSED" })).toBe(true);
expect(mrIsClosed({ mrState: "close" })).toBe(true);
expect(mrIsClosed({ mrState: "opened" })).toBe(false);
expect(mrIsClosed({ mrState: null })).toBe(false);
expect(mrIsClosed({ mrState: "merged" })).toBe(false);
});
test("搜证另算:completed 和 unreproducible 都算结论,失败不算", () => {
expect(isTaskFinished(sec({ status: "completed" }))).toBe(true);
expect(isTaskFinished(sec({ status: "unreproducible" }))).toBe(true);
expect(isTaskFinished(sec({ status: "security_failed" }))).toBe(false);
expect(isTaskFinished(sec({ status: "manual_review" }))).toBe(false);
});
});
describe("computeDashMetrics", () => {
test("空看板给出零切片,分桶表仍有全部列", () => {
const m = computeDashMetrics([], []);
expect(m.total).toBe(0);
expect(m.live.onlineNodes).toBe(0);
for (const b of PIPELINE_BUCKETS) expect(m.buckets[b].total).toBe(0);
expect(m.byKind.bug.total).toBe(0);
});
test("三类任务分别落入看板分桶,而不是旧的 raw status", () => {
const items: BoardItem[] = [
bug({ id: "1", status: "pending_confirmation" }),
bug({ id: "2", status: "fixing" }),
bug({
id: "3", status: "fix_succeeded",
mrUrl: "https://bits/mr/1", mrState: "opened", meegoState: "done",
}),
bug({
id: "4", status: "fix_succeeded",
mrUrl: "https://bits/mr/2", mrState: "merged", meegoState: "done",
mrMergedAt: 100, finishedAt: 50,
}),
feat({ id: "5", status: "manual_review" }),
feat({ id: "6", status: "completed" }),
sec({ id: "7", status: "security_running" }),
sec({ id: "8", status: "unreproducible" }),
];
expect(bucketOf(items[2])).toBe("awaiting_merge");
expect(bucketOf(items[3])).toBe("merged");
const m = computeDashMetrics(items, [node({ id: "n1" }), node({ id: "n2", live: false, status: "offline" })]);
expect(m.total).toBe(8);
expect(m.byKind.bug.total).toBe(4);
expect(m.byKind.feature.total).toBe(2);
expect(m.byKind.security.total).toBe(2);
expect(m.buckets.confirm.bug).toBe(1);
expect(m.buckets.running.bug).toBe(1);
expect(m.buckets.running.security).toBe(1);
expect(m.buckets.awaiting_merge.bug).toBe(1);
expect(m.buckets.merged.bug).toBe(1);
expect(m.buckets.merged.feature).toBe(1);
expect(m.byKind.bug.finished).toBe(2);
expect(m.byKind.bug.inPlay).toBe(3); // 4 − confirm
expect(kindPieSlices(m, "bug").map((s) => s.bucket))
.toEqual(["running", "awaiting_merge", "merged"]);
expect(kindOtherSlices(m, "bug")).toEqual([{ bucket: "confirm", n: 1 }]);
expect(m.byKind.feature.finished).toBe(1);
expect(m.byKind.security.finished).toBe(1); // unreproducible 另计为结论
expect(m.buckets.review.feature).toBe(1);
expect(m.buckets.unreproducible.security).toBe(1);
expect(m.live.running).toBe(2);
expect(m.live.needsHuman).toBe(3); // confirm + feature review + awaiting_merge
expect(m.live.onlineNodes).toBe(1);
expect(m.live.totalNodes).toBe(2);
expect(kindBucketCounts(m, "bug").map((s) => s.bucket))
.toEqual(["confirm", "running", "awaiting_merge", "merged"]);
expect(kindBucketCounts(m, "feature")).toEqual([
{ bucket: "review", n: 1 },
{ bucket: "merged", n: 1 },
]);
});
test("MR 漏斗只数 bug,合入率分母是已批准且有 MR", () => {
const items: BoardItem[] = [
bug({
id: "open", status: "fix_succeeded",
mrUrl: "https://bits/1", mrState: "opened", meegoState: "resolved",
}),
bug({
id: "wait", status: "fix_succeeded",
mrUrl: "https://bits/2", mrState: "opened", meegoState: "done",
}),
bug({
id: "landed", status: "fix_succeeded",
mrUrl: "https://bits/3", mrState: "merged", meegoState: "done",
mrMergedAt: 200, finishedAt: 100, platform: "ios",
}),
bug({
id: "base", status: "fix_succeeded", mergedIntoBaseAt: 150,
}),
feat({ id: "f", status: "completed", mrUrl: "https://bits/feat" }),
];
const m = computeDashMetrics(items, []);
expect(m.mr.withMr).toBe(3);
expect(m.mr.awaitingQa).toBe(1);
expect(m.mr.awaitingMerge).toBe(1);
expect(m.mr.merged).toBe(2); // bits merged + 合回基线
expect(m.mr.bitsMerged).toBe(1);
expect(m.mr.mergedIntoBase).toBe(1);
expect(m.mr.approvedWithMr).toBe(3);
expect(m.mr.iosMerged).toBe(1);
expect(m.mr.androidMerged).toBe(1);
expect(m.mr.avgMergeMs).toBe(100);
expect(m.byKind.bug.finished).toBe(4); // QA + 待合入 + bits merged + 合回基线
});
test("交付结果:R0/R1/Rn/Fail/Pending 占全期分母;未确认无法复现进 R0;待 QA 不进", () => {
const items: BoardItem[] = [
bug({ id: "r0", status: "fix_succeeded", mrState: "merged", meegoState: "done", humanRejects: 0, totalDurationMs: 1000 }),
bug({ id: "unrepro", status: "unreproducible", meegoState: "open", humanRejects: 3 }),
bug({ id: "r1", status: "fix_succeeded", mrState: "merged", meegoState: "done", humanRejects: 1, totalDurationMs: 3000 }),
bug({ id: "r2", status: "fix_succeeded", mrState: "opened", meegoState: "done", humanRejects: 2 }),
bug({ id: "rn", status: "fix_succeeded", mrState: "merged", meegoState: "done", humanRejects: 3 }),
bug({ id: "closed", status: "fix_succeeded", mrState: "closed", meegoState: "done" }),
bug({ id: "fail", status: "fix_failed" }),
bug({ id: "archived", status: "archived" }),
bug({ id: "pending", status: "manual_review" }),
bug({ id: "qa", status: "fix_succeeded", mrState: "opened", meegoState: "resolved" }),
bug({ id: "confirm", status: "pending_confirmation" }),
feat({ id: "h", status: "completed", attempts: 1, humanRejects: 0, durationMs: 400 }),
feat({ id: "i", status: "awaiting_implementation", attempts: 0 }),
];
expect(outcomeBandOf(items[0])).toBe("r0");
expect(outcomeBandOf(items[1])).toBe("r0");
expect(outcomeBandOf(items[2])).toBe("r1");
expect(outcomeBandOf(items[3])).toBe("r2");
expect(outcomeBandOf(items[4])).toBe("rn");
expect(outcomeBandOf(items[5])).toBe("fail");
expect(outcomeBandOf(items[6])).toBe("fail");
expect(outcomeBandOf(items[7])).toBe("fail");
expect(outcomeBandOf(items[8])).toBe("pending");
expect(outcomeBandOf(items[9])).toBe(null);
expect(outcomeBandOf(items[10])).toBe(null);
const m = computeDashMetrics(items, []);
const bugS = m.byKind.bug;
expect(bugS.outcome).toEqual({ r0: 2, r1: 1, r2: 1, rn: 1, fail: 3, pending: 1, denom: 9 });
expect(outcomeDisplayN(bugS.outcome, "r0")).toBe(2);
expect(outcomeDisplayN(bugS.outcome, "r1")).toBe(3);
expect(outcomeDisplayN(bugS.outcome, "r2")).toBe(4);
expect(outcomeDisplayN(bugS.outcome, "rn")).toBe(5);
expect(outcomeDisplayN(bugS.outcome, "fail")).toBe(3);
expect(bucketOf(items[7])).toBe("archived");
expect(bugS.failed).toBe(2); // fix_failed + archived (closed MR is merged-bucket fail, not failed-bucket)
expect(m.buckets.failed.bug).toBe(2);
expect(bugS.avgDoneMs).toBe(2000);
expect(m.byKind.feature.outcome).toEqual({ r0: 1, r1: 0, r2: 0, rn: 0, fail: 0, pending: 0, denom: 1 });
expect(m.byKind.feature.avgDoneMs).toBe(400);
});
test("archived 落在 Done 分界桶,统计记 Fail", () => {
expect(bucketOf(bug({ status: "archived" }))).toBe("archived");
expect(bucketOf(feat({ status: "archived" }))).toBe("archived");
expect(outcomeBandOf(bug({ status: "archived" }))).toBe("fail");
expect(outcomeBandOf(feat({ status: "archived" }))).toBe("fail");
const m = computeDashMetrics([
bug({ id: "a", status: "archived" }),
feat({ id: "b", status: "archived" }),
], []);
expect(m.byKind.bug.failed).toBe(1);
expect(m.byKind.feature.failed).toBe(1);
expect(m.buckets.failed.bug).toBe(1);
expect(m.buckets.failed.feature).toBe(1);
expect(m.byKind.bug.finished).toBe(0);
expect(m.byKind.feature.finished).toBe(0);
});
test("通过率分母排除 cancelled,平均耗时只算成功的", () => {
const items: BoardItem[] = [
bug({ id: "ok", status: "fix_succeeded", totalDurationMs: 1000 }),
bug({ id: "bad", status: "fix_failed" }),
bug({ id: "abort", status: "cancelled" }),
feat({ id: "okf", status: "completed", durationMs: 400 }),
feat({ id: "badf", status: "implementation_failed" }),
];
const m = computeDashMetrics(items, []);
expect(m.byKind.bug.succeeded).toBe(1);
expect(m.byKind.bug.terminal).toBe(2);
expect(m.byKind.bug.avgSuccessMs).toBe(1000);
expect(m.byKind.feature.succeeded).toBe(1);
expect(m.byKind.feature.terminal).toBe(2);
expect(m.byKind.feature.avgSuccessMs).toBe(400);
});
test("已取消不进交付结果的 Fail,也不进分母", () => {
const cancelledBug = bug({ id: "abort", status: "cancelled" });
const cancelledFeat = feat({ id: "abortf", status: "cancelled" });
expect(outcomeBandOf(cancelledBug)).toBe(null);
expect(outcomeBandOf(cancelledFeat)).toBe(null);
const m = computeDashMetrics([
bug({ id: "bad", status: "fix_failed" }),
cancelledBug,
cancelledFeat,
], []);
expect(m.byKind.bug.outcome).toEqual({ r0: 0, r1: 0, r2: 0, rn: 0, fail: 1, pending: 0, denom: 1 });
expect(m.byKind.feature.outcome.denom).toBe(0);
expect(m.byKind.feature.outcome.fail).toBe(0);
});
test("增量托管没跑的单(只建记录 / 已撤回)落在 Done 的 not_run 桶,不进概览任何比率", () => {
const record = bug({ id: "rec", status: "cancelled", watchWithdrawn: "record:mr" });
const withdrawn = bug({ id: "wd", status: "cancelled", watchWithdrawn: "meego_closed" });
const bond = bug({ id: "bond", status: "cancelled", watchWithdrawn: "mr_bound" });
for (const it of [record, withdrawn, bond]) {
expect(bucketOf(it)).toBe("not_run");
expect(isOutcome(it)).toBe(false);
expect(isTaskFinished(it)).toBe(false);
expect(outcomeBandOf(it)).toBe(null);
}
// 真正的取消(没有增量托管的 watch_withdrawn)还是失败列。
expect(bucketOf(bug({ id: "plain", status: "cancelled" }))).toBe("failed");
const m = computeDashMetrics([record, withdrawn, bug({ id: "ok", status: "fix_succeeded" })], []);
expect(m.total).toBe(1); // 只有 fix_succeeded 那条被数
expect(m.byKind.bug.total).toBe(1);
expect(m.buckets.not_run.bug).toBe(0);
});
test("evaluate_finish 落在 Done 分界桶,不进完成率分子分母也不进交付结果", () => {
expect(bucketOf(bug({ status: "evaluate_finish" }))).toBe("evaluate_finish");
expect(outcomeBandOf(bug({ status: "evaluate_finish" }))).toBe(null);
const parked = bug({ id: "eval", status: "evaluate_finish" });
const pending = bug({ id: "rev", status: "manual_review" });
const done = bug({
id: "ok", status: "fix_succeeded",
mrState: "merged", meegoState: "done", mrMergedAt: 100, finishedAt: 50,
});
const m = computeDashMetrics([parked, pending, done], []);
expect(m.total).toBe(2);
expect(m.byKind.bug.total).toBe(2);
expect(m.byKind.bug.review).toBe(1);
expect(m.byKind.bug.merged).toBe(1);
expect(m.byKind.bug.finished).toBe(1);
expect(m.byKind.bug.inPlay).toBe(2);
expect(m.byKind.bug.outcome.pending).toBe(1);
expect(m.byKind.bug.outcome.denom).toBe(2);
});
});
+96
View File
@@ -0,0 +1,96 @@
import {createRequire} from 'node:module';
import {writeFile,mkdir} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import assert from 'node:assert/strict';
const require = createRequire(process.env.EDDY_HISTORY_PLAYWRIGHT_PACKAGE || import.meta.url);
const {chromium} = require('playwright');
const out = process.env.EDDY_HISTORY_OUTPUT_DIR || join(tmpdir(), 'eddy-history-browser');
await mkdir(out, {recursive:true});
const base = process.argv[2];
if (!['127.0.0.1', 'localhost'].includes(new URL(base).hostname)) throw new Error('Only the local synthetic fixture is allowed');
const source = 'b'.repeat(64), otherSource = 'd'.repeat(64);
const deep = base + '/eddy/tasks?machine=' + 'a'.repeat(16) + '&task=browser-main&source=' + source;
const browser = await chromium.launch({channel:'chrome',headless:true});
const checks=[], errors=[], external=[];
let debugPage;
try {
const context = await browser.newContext({viewport:{width:1370,height:1000}});
await context.addInitScript(() => {
localStorage.setItem('light:ttuae2:local-session','history-browser');
localStorage.setItem('streamline.sso.user',JSON.stringify({email:'history-browser@example.com',name:'Synthetic user'}));
});
const page = await context.newPage();debugPage=page;page.setDefaultTimeout(8000);page.on('pageerror',e=>errors.push(e.message));
page.on('request',r=>{if(!r.url().startsWith(base))external.push(r.url())});
const mode = async value => { const r=await page.request.post(base+'/fixture/mode',{data:{mode:value}});assert(r.ok()); };
const tasks = page.locator('.eh-task');
await page.goto(base+'/eddy/tasks');await tasks.first().waitFor();assert.equal(await tasks.count(),30);
await page.getByRole('button',{name:'加载更多任务',exact:true}).click();await page.waitForFunction(()=>document.querySelectorAll('.eh-task').length===35);
checks.push('Task metadata pages through 35 synthetic tasks from authenticated HTTP/Postgres without loading transcript bodies.');
await tasks.filter({hasText:'Inbox · Story 天窗放大 2 倍'}).first().click();
await page.getByLabel('历史会话记录').getByText('把 Inbox 的 Story 天窗放大 2 倍,其他逻辑保持不变。',{exact:true}).waitFor();
await page.locator('.eh-partial').waitFor();
assert.equal(await page.getByText('继续验证',{exact:true}).count(),2);
assert.equal(await page.locator('.eh-message img').count(),0);
assert.equal(await page.evaluate(()=>window.historyXss),undefined);
await page.getByText('工具调用 · inspect_view',{exact:true}).click();
await page.getByText('{"view":"StorySkylight","scale":2}',{exact:true}).waitFor();
await page.getByText('工具结果 · inspect_view',{exact:true}).click();
await page.getByText('已隐藏可识别的敏感字段',{exact:true}).waitFor();
checks.push('Messages, repeated prompts and collapsed tool calls/results render as inert text; masking and incomplete fragments are explicit.');
await page.getByRole('button',{name:'加载更多记录',exact:true}).click();
await page.getByText('长消息前半🧪后半🧪',{exact:true}).waitFor();assert.equal(await page.locator('.eh-partial').count(),0);
await page.getByText('已读到当前已上传记录的末尾',{exact:true}).waitFor();
checks.push('A message split across the 200-record page boundary reconstructs completely after loading more.');
await page.getByLabel('选择 Agent 会话').selectOption(otherSource);
await page.getByText('Claude 会话的独立消息',{exact:true}).waitFor();assert.equal(await page.getByText('继续验证',{exact:true}).count(),0);
await page.goBack();await page.getByLabel('历史会话记录').getByText('把 Inbox 的 Story 天窗放大 2 倍,其他逻辑保持不变。',{exact:true}).waitFor();
assert(page.url().includes('source='+source));
await page.reload();await page.getByLabel('历史会话记录').getByText('把 Inbox 的 Story 天窗放大 2 倍,其他逻辑保持不变。',{exact:true}).waitFor();
checks.push('Session choice is in the URL; back/forward and reloading a deep link preserve the correct session.');
await page.getByText('任务信息与产物',{exact:true}).click();
await page.getByText('首条用户消息(需求参考)',{exact:true}).waitFor();
await page.getByText('工具结果 · inspect_view',{exact:true}).click();
await page.locator('.eh-main').evaluate(e=>e.scrollTop=0);
await page.screenshot({path:out+'/history-light.png'});
await page.evaluate(()=>document.documentElement.dataset.theme='dark');
await page.waitForTimeout(200); // Let the existing app-wide color transitions settle.
assert(await page.locator('.eh-task').first().evaluate(e=>getComputedStyle(e).color===getComputedStyle(document.querySelector('.eh-page')).color));
await page.screenshot({path:out+'/history-dark.png'});
await page.evaluate(()=>document.documentElement.dataset.theme='light');
await page.waitForTimeout(200);
await tasks.filter({hasText:'Inbox · Story 天窗放大 2 倍'}).nth(1).click();
await page.getByText('第二台设备的独立消息',{exact:true}).waitFor();assert.equal(await page.getByText('继续验证',{exact:true}).count(),0);
checks.push('Two Macs sharing the same task id display separate transcripts.');
await mode('slow');
await tasks.filter({hasText:'Inbox · Story 天窗放大 2 倍'}).first().click();
await tasks.filter({hasText:'Story · 长按主体抠图'}).click();
await page.getByLabel('历史会话记录').getByText('仅抠图任务的消息',{exact:true}).waitFor();await page.waitForTimeout(550);
assert.equal(await page.getByLabel('历史会话记录').getByText('把 Inbox 的 Story 天窗放大 2 倍,其他逻辑保持不变。',{exact:true}).count(),0);
await mode('ok');checks.push('Rapid task changes abort/ignore stale responses and never replace the current task with delayed data.');
await page.getByLabel('搜索 Eddy 任务').fill('does-not-exist');await page.getByText('没有匹配的任务。',{exact:true}).waitFor();
await page.getByLabel('搜索 Eddy 任务').fill('');await tasks.first().waitFor();
await mode('unavailable');await page.getByLabel('刷新任务列表').click();await page.getByRole('alert').waitFor();assert.equal(await tasks.count(),0);
await mode('ok');await page.getByRole('button',{name:'重试',exact:true}).click();await tasks.first().waitFor();
await mode('old');await page.getByLabel('刷新任务列表').click();await page.getByText('当前服务尚未提供历史会话,请稍后重试。',{exact:true}).waitFor();
await mode('ok');await page.getByRole('button',{name:'重试',exact:true}).click();await tasks.first().waitFor();
await page.evaluate(()=>localStorage.removeItem('light:ttuae2:local-session'));await page.getByLabel('刷新任务列表').click();
await page.getByRole('button',{name:'重新登录',exact:true}).click();assert.equal(await page.evaluate(()=>document.documentElement.dataset.relogin),'requested');
await page.evaluate(()=>localStorage.setItem('light:ttuae2:local-session','history-browser'));await page.getByLabel('刷新任务列表').click();await tasks.first().waitFor();
checks.push('Search, unavailable service, older server and expired SSO show actionable states and recover; private stale task rows are cleared.');
await mode('empty');await page.getByLabel('刷新任务列表').click();await page.getByText('还没有已同步的任务。',{exact:true}).waitFor();
await mode('ok');await page.goto(deep);await page.getByLabel('历史会话记录').getByText('把 Inbox 的 Story 天窗放大 2 倍,其他逻辑保持不变。',{exact:true}).waitFor();
await page.setViewportSize({width:390,height:844});
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
assert(await page.locator('.eh-main').evaluate(e=>e.scrollWidth<=e.clientWidth));
await page.screenshot({path:out+'/history-mobile.png'});
await page.getByRole('button',{name:'任务列表',exact:true}).click();await tasks.first().waitFor({state:'visible'});
await page.screenshot({path:out+'/history-mobile-list.png'});
checks.push('Light/dark and 390px layouts render; task list and transcript remain scrollable, narrow task/back navigation works without horizontal overflow.');
assert.deepEqual(errors,[]);assert.deepEqual(external,[]);
const result={passed:true,checks,errors,external,scope:'Synthetic browser → authenticated HTTP → isolated Postgres. No production access.'};
await writeFile(out+'/browser-validation.json',JSON.stringify(result,null,2));process.stdout.write(JSON.stringify(result));
} catch (error) {
if(debugPage){await debugPage.screenshot({path:out+'/failure.png'}).catch(()=>{});console.error(JSON.stringify({errors,external,text:(await debugPage.locator('body').innerText().catch(()=>'')).slice(0,1200),url:debugPage.url()}));}
throw error;
} finally {await browser.close();}
+48
View File
@@ -0,0 +1,48 @@
import { expect, test } from 'bun:test';
import { historyMessages, historyPath, historyScope, historySelection } from '../src/lib/eddyHistory';
import type { ConversationEnvelope } from '@bbbug/shared/eddy_conversations';
const row = (sequence: number, position: number, text: string, part = 0, parts = 1): ConversationEnvelope => ({
sequence, machine: 'a'.repeat(16), taskId: 'task-one', taskTitle: 'Task', sourceId: 'b'.repeat(64), provider: 'codex', receivedAt: 1,
event: {id: String(sequence), streamId: 'c'.repeat(64), position, text, part, parts, block: 0, kind: 'message', role: 'user', redacted: false},
});
test('fragmented Unicode messages reconstruct by file position across pages, preserving repeated text', () => {
const rows = [row(1, 100, '后半🧪', 1, 2), row(2, 200, 'again'), row(3, 100, '前半', 0, 2), row(4, 300, 'again')];
const messages = historyMessages(rows);
expect(messages.map(m => m.text)).toEqual(['前半后半🧪', 'again', 'again']);
expect(messages.every(m => m.complete)).toBe(true);
});
test('missing fragments remain explicit; later pages complete the message and keep masking metadata', () => {
const first = row(1, 0, '尾巴', 1, 2); first.event.redacted = true;
const partial = historyMessages([first])[0];
expect(partial.complete).toBe(false); expect(partial.text).toContain('第 1 段尚未加载');
const complete = historyMessages([first, row(2, 0, '开头', 0, 2)])[0];
expect(complete.text).toBe('开头尾巴'); expect(complete.event.redacted).toBe(true);
});
test('equal offsets from different files and devices never collapse into one message', () => {
const a = row(1, 0, 'first'), b = row(2, 0, 'second'), c = row(3, 0, 'third');
b.event.streamId = 'd'.repeat(64); c.machine = 'f'.repeat(16);
expect(historyMessages([a, b, c]).map(m => m.text)).toEqual(['first', 'second', 'third']);
});
test('links round trip exact task, machine and source, ignoring invalid external selectors', () => {
const selection = {machine: 'a'.repeat(16), taskId: 'task-one', sourceId: 'b'.repeat(64)};
expect(historySelection(historyPath(selection).split('?')[1])).toEqual(selection);
expect(historyPath(null)).toBe('/eddy/tasks');
expect(historySelection('?task=../escape&machine=' + selection.machine)).toBeNull();
expect(historySelection('?task=task-one&machine=host')).toBeNull();
});
test('the administrator all-users view keeps scope and account in the URL', () => {
const machine = 'f'.repeat(16), source = 'a'.repeat(64);
expect(historyScope('?scope=all&owner=Someone@Example.com')).toEqual({ all: true, owner: 'someone@example.com' });
expect(historyScope('?owner=someone@example.com')).toEqual({ all: false });
// A transcript link in the all-users view needs the account it belongs to.
expect(historySelection(`?scope=all&machine=${machine}&task=t1`)).toBeNull();
const selected = historySelection(`?scope=all&owner=someone@example.com&machine=${machine}&task=t1&source=${source}`)!;
expect(selected).toEqual({ machine, taskId: 't1', sourceId: source, owner: 'someone@example.com' });
expect(historyPath(selected, historyScope('?scope=all'))).toBe(`/eddy/tasks?scope=all&owner=someone%40example.com&machine=${machine}&task=t1&source=${source}`);
expect(historyPath(null, { all: true, owner: 'someone@example.com' })).toBe('/eddy/tasks?scope=all&owner=someone%40example.com');
expect(historyPath(null, { all: true })).toBe('/eddy/tasks?scope=all');
// The personal view is unchanged.
expect(historyPath({ machine, taskId: 't1' })).toBe(`/eddy/tasks?machine=${machine}&task=t1`);
expect(historyPath(null)).toBe('/eddy/tasks');
});
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, test } from "bun:test";
import { belongsToProblem, reviewPayload } from "../src/lib/eddyReview";
describe("Eddy review ownership", () => {
const problem = { baseline: "notes-build-a", signature: "hang:window", aliases: ["hang:layout"] };
test("joins aliases only within the same exact baseline", () => {
expect(belongsToProblem(problem, { baseline: "notes-build-a", problem: "hang:layout" })).toBe(true);
expect(belongsToProblem(problem, { baseline: "notes-build-b", problem: "hang:window" })).toBe(false);
expect(belongsToProblem(problem, { baseline: "notes-build-a", problem: "hang:other" })).toBe(false);
});
test("a missing signature does not attach unrelated advice", () => {
expect(belongsToProblem(problem, { baseline: "notes-build-a", problem: null })).toBe(false);
});
});
async function pack(text: string, name = "guard.js") {
const bytes = new TextEncoder().encode(text);
const sha = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))).map((b) => b.toString(16).padStart(2, "0")).join("");
return { manifest: {}, payload_b64: Buffer.from(bytes).toString("base64"), payload_name: name, sha256: sha };
}
describe("Eddy payload review", () => {
test("displays the verified source without executing it", async () => {
const source = 'throw new Error("must never execute"); // 布局';
const p = await pack(source);
expect((await reviewPayload(p, p.sha256)).text).toBe(source);
});
test("rejects bytes changed since the review record was loaded", async () => {
const p = await pack("return {}");
await expect(reviewPayload(p, "0".repeat(64))).rejects.toThrow("SHA-256");
});
test("keeps binary payloads downloadable without treating them as source", async () => {
const p = await pack("PK fixture", "pack.zip");
expect((await reviewPayload(p, p.sha256)).text).toBeNull();
});
});
+66
View File
@@ -0,0 +1,66 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { UsageReport, type UsageMetrics } from "../src/components/EddyUsagePanel";
// The shape GET /api/eddy/admin/usage returned in an end-to-end run (Mac app → runtime → control plane → Postgres),
// plus a signed-in second Mac.
const data: UsageMetrics = {
from: 0, until: 1794477200000, timezone: "UTC", days: 7,
summary: {activeInstallations: 2, activeDevices: 2, activeAccounts: 1, anonymousDevices: 1, portalSessions: 0, shellSessions: 3,
portalActiveMs: 0, shellActiveMs: 360000, appRuntimeMs: 90000},
daily: [{day: "2026-11-12", activeInstallations: 2, activeDevices: 2, actions: 3, portalActiveMs: 0, shellActiveMs: 360000}],
operations: [
{name: "runtime.prepare", action: "first-launch", source: "shell", count: 1, activeInstallations: 1, succeeded: 1, failed: 0, cancelled: 0, successRate: 1, p50Ms: 57876, p95Ms: 57876, p95QueueMs: null},
{name: "app.launch", action: "app", source: "runtime", count: 2, activeInstallations: 2, succeeded: 1, failed: 1, cancelled: 0, successRate: .5, p50Ms: 30000, p95Ms: 30000, p95QueueMs: null},
{name: "view.opened", action: "desk", source: "shell", count: 4, activeInstallations: 1, succeeded: 0, failed: 0, cancelled: 0, successRate: null, p50Ms: null, p95Ms: null, p95QueueMs: null},
],
releases: [{release: "2026.11.12-eddy-home.35", activeInstallations: 2}],
users: [
{user: "anonymous", activeInstallations: 1, activeDevices: 1, portalSessions: 0, shellSessions: 2, actions: 2, launchesSucceeded: 1, launchesFailed: 0, operationsSucceeded: 1, operationsFailed: 1, portalActiveMs: 0, shellActiveMs: 60000, appRuntimeMs: 0, lastAt: 1794477175868},
{user: "someone@example.com", activeInstallations: 1, activeDevices: 1, portalSessions: 0, shellSessions: 1, actions: 1, launchesSucceeded: 0, launchesFailed: 1, operationsSucceeded: 0, operationsFailed: 0, portalActiveMs: 0, shellActiveMs: 300000, appRuntimeMs: 90000, lastAt: 1794477100000},
],
devices: [
{device: "89fead1d", installations: 1, accounts: 0, neverSignedIn: true, firstAt: 1794476800000, lastAt: 1794477175868, shellSessions: 2, shellActiveMs: 60000, actions: 2,
launchesSucceeded: 1, launchesFailed: 0, appRuntimeMs: 0, appVersions: ["0.9.13+15"], profile: {model: "Mac16,7", chip: "m4", memoryGB: 48, macos: "26.6", language: "zh", location: "other"}},
{device: "fedcba98", installations: 1, accounts: 1, neverSignedIn: false, firstAt: 1794470000000, lastAt: 1794477100000, shellSessions: 1, shellActiveMs: 300000, actions: 1,
launchesSucceeded: 0, launchesFailed: 1, appRuntimeMs: 90000, appVersions: [], profile: null},
],
funnel: {firstLaunch: 1, runtimeReady: 1, runtimeReadyP50Ms: 57876, homeShown: 1, homeShownP50Ms: 58255, appInstalled: 0, appInstalledP50Ms: null,
taskOpened: 0, taskOpenedP50Ms: null, firstEdit: 0, firstEditP50Ms: null, firstShare: 0, firstShareP50Ms: null},
retention: [{week: "2026-11-09", devices: 1, d1Eligible: 0, d1: 0, d7Eligible: 0, d7: 0, d28Eligible: 0, d28: 0}],
adoption: {activeDevices: 2, openedTask: 1, designDesk: 1, coldRestart: 0, agentEdit: 0, share: 0, import: 0, relay: 0},
appVersions: [{appVersion: "0.9.13+15", devices: 1, lastAt: 1794477175868}],
flows: [{name: "permission.flow", action: "screen-recording", step: "granted", count: 1, devices: 1}],
details: [
{name: "preview.change", action: "language", detail: "ar", count: 3, devices: 1, succeeded: 2, failed: 1, p50Ms: 21000, freedMB: 0},
{name: "dock.attach", action: "detached", detail: "", count: 2, devices: 1, succeeded: 0, failed: 0, p50Ms: 600000, freedMB: 0},
{name: "agent.entry", action: "app", detail: "claude", count: 4, devices: 1, succeeded: 0, failed: 0, p50Ms: null, freedMB: 0},
{name: "notice.shown", action: "failure", detail: "app", count: 1, devices: 1, succeeded: 0, failed: 0, p50Ms: null, freedMB: 0},
{name: "notice.action", action: "clean-up", detail: "space", count: 1, devices: 1, succeeded: 0, failed: 0, p50Ms: null, freedMB: 0},
{name: "operation.completed", action: "storage.clean", detail: "app-cache", count: 2, devices: 1, succeeded: 2, failed: 0, p50Ms: 900, freedMB: 1500},
{name: "app.crash", action: "app", detail: "app", count: 1, devices: 1, succeeded: 0, failed: 0, p50Ms: null, freedMB: 0},
],
};
test("the usage report shows devices, the activation funnel, retention, feature use and the Mac app", () => {
const html = renderToStaticMarkup(<UsageReport data={data} user="" onUser={() => {}} />);
for (const text of ["活跃设备", "Mac app 会话", "激活漏斗", "运行环境准备好", "57.9 s", "留存", "还没到", "功能使用", "用设计台",
"50.0%", "按设备", "<code>89fead1d</code>", "Mac16,7 · M4 · 48 GB · macOS 26.6 · 不在「应用程序」", "未登录(按设备上传)",
"屏幕录制授权", "已允许", "0.9.13+15", "准备运行环境 · first-launch", "Mac app"]) expect(html).toContain(text);
expect(html).toContain("其中 1 台设备有未登录时上传的数据");
});
test("P1 detail: previews, docking, the Agent entry, failure cards, storage cleaning and crashes", () => {
const html = renderToStaticMarkup(<UsageReport data={{...data, summary: {...data.summary, appCrashes: 1}}} user="" onUser={() => {}} />);
for (const text of ["设计台、预览与吸附", "预览 · 换语言", "العربية", "66.7%", "21.0 s", "吸附 · 松开(吸附时长)", "10.0 min",
"从 eddy 找 Agent", "Agent 入口 · 桌面 App", "提示与失败卡", "出现 · 失败</td><td>App 版本", "点了 · 去清理</td><td>空间不够",
"存储清理", "存储 · 清理</td><td>App 缓存", "1.5 GB", "App 崩溃", "每 App 小时 40.00 次", "<td>崩溃</td><td>App 本身"])
expect(html).toContain(text);
});
test("an old server's answer (schema 1, no device fields) still renders", () => {
const {devices, funnel, retention, adoption, appVersions, flows, ...old} = data;
const html = renderToStaticMarkup(<UsageReport data={{...old, summary: {activeInstallations: 1, portalSessions: 2, portalActiveMs: 1000, appRuntimeMs: 0}}} user="" onUser={() => {}} />);
expect(html).toContain("活跃安装");
expect(html).not.toContain("激活漏斗");
});
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Eddy export · local fixture</title></head><body><div id="root"></div><script type="module" src="./eddy-export.tsx"></script></body></html>
+59
View File
@@ -0,0 +1,59 @@
// Real export components, deterministic local API fixture. No production traffic.
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import { EddyExportBadge } from "../../src/components/EddyExportPanel";
import StatsStrip from "../../src/components/StatsStrip";
import { applyClusterSnapshot } from "../../src/lib/clusterStore";
import type { ClusterNode } from "../../src/types";
import RelayDialog from "../../src/components/RelayDialog";
import { setLang } from "../../src/lib/i18n";
import type { Feature } from "../../src/types";
import type { EddyExport } from "@bbbug/shared/eddy_export";
import "../../src/styles.css";
setLang("zh");
const feature = { id: "eddy-export-fixture", title: "给收藏列表增加排序入口", platform: "ios", status: "completed", branchName: "feature/collection-sort", repoKey: "tiktok-ios", mrUrl: "https://mr.invalid/123", executorNodeId: "fei-ios-01.shiro0.icu" } as Feature;
const record: EddyExport = { id: "11111111-2222-4333-8444-555555555555", featureId: feature.id, nodeId: "fei-ios-01.shiro0.icu", commit: "1234567890abcdef1234567890abcdef12345678", branch: feature.branchName!, phase: "ready", createdAt: Date.now(), updatedAt: Date.now(), expiresAt: Date.now() + 7 * 86400_000, error: null,
result: { baselineId: "tiktokm-fixture", commit: "1234567890abcdef1234567890abcdef12345678", eddyVersion: "v2.8", devicesimSha256: "a".repeat(64), artifacts: { app: { file: "baseline-tiktokm-fixture.zip", bytes: 782000000, sha256: "b".repeat(64) }, source: { file: "baseline-tiktokm-fixture-source.zip", bytes: 418000000, sha256: "c".repeat(64) } } } };
let jobs: EddyExport[] = [], serviceEnabled = true, creates = 0;
// Two satellites: the executor and a peer. Each mode sets which is up and what the job is doing.
const sat = (id: string, live: boolean, fixInFlight: number): ClusterNode => ({ id, baseUrl: "", platform: "ios", status: live ? "online" : "offline", live,
lastSeenAt: Date.now(), evalInFlight: 0, evalCapacity: 3, fixInFlight, fixCapacity: 1, createdAt: 0, clusters: ["default"] } as ClusterNode);
const fleet = (home: [boolean, number], peer: [boolean, number]) =>
applyClusterSnapshot({ nodes: [sat("fei-ios-01.shiro0.icu", ...home), sat("fei-ios-02.shiro0.icu", ...peer)], eval: { inFlight: 0, capacity: 6 }, fix: { inFlight: home[1] + peer[1], capacity: 2 } });
fleet([true, 0], [true, 0]);
window.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (url.endsWith("/handover")) return new Response("# Local relay fixture\n");
if (url.endsWith("/lab-runs/running")) return Response.json({ runs: [] });
if (url.endsWith("/eddy-exports/running")) return Response.json({ exports: jobs.filter(j => ["building", "packaging", "verifying", "uploading"].includes(j.phase))
.map(j => ({ id: j.id, featureId: j.featureId, title: feature.title, nodeId: j.nodeId, phase: j.phase })) });
if (!url.endsWith("/eddy-exports")) throw new Error("Fixture refuses network: " + url);
if (init?.method === "POST") { creates++; jobs = [{ ...record, phase: "queued", result: null, expiresAt: null }]; return Response.json({ export: jobs[0] }); }
return Response.json({ enabled: serviceEnabled, exports: jobs });
}) as typeof fetch;
function Fixture() {
const [version, setVersion] = useState(0);
const [open, setOpen] = useState(false);
const [platform, setPlatform] = useState<"ios" | "android">("ios");
const mode = (phase: string) => {
serviceEnabled = phase !== "disabled";
const [state, where] = phase.split(":");
// queued:busy — executor running another task; queued:offline — executor gone; queued:moved — rerouted to a busy peer.
fleet(where === "offline" ? [false, 0] : [true, where === "busy" ? 1 : state === "building" ? 1 : 0], [true, where === "moved" ? 1 : 0]);
jobs = ["empty", "disabled"].includes(state) ? [] : [{ ...record, phase: state as EddyExport["phase"], nodeId: where === "moved" ? "fei-ios-02.shiro0.icu" : record.nodeId,
error: state === "failed" ? "卫星机执行中断或失去连接,可重试导出" : null }];
setVersion(v => v + 1);
};
return <main style={{ maxWidth: 780, height: "100vh", overflow: "auto", margin: "0 auto", padding: 24 }}>
<p>本地界面验证 · 示例数据 · 不连接线上</p>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 24 }}>{["empty", "queued", "queued:busy", "queued:offline", "queued:moved", "building", "ready", "failed", "expired", "disabled"].map(s => <button key={s} onClick={() => mode(s)}>{s}</button>)}</div>
<button onClick={() => setPlatform(p => p === "ios" ? "android" : "ios")}>切换平台</button>
<h2>{feature.title}</h2><p>Feature · {platform} · 已完成</p>
{platform === "ios" && jobs[0] && <EddyExportBadge job={jobs[0]} />}
<button onClick={() => setOpen(true)}>接力到本地</button>
{open && <RelayDialog key={version + platform} item={{ ...feature, kind: "feature", platform }} onClose={() => setOpen(false)} onChanged={() => setVersion(v => v + 1)} />}
<output>创建请求:{creates}</output>
<div style={{ width: 300, marginTop: 24 }}><StatsStrip key={version} running={[]} queued={[]} evaluating={[]} awaitingEval={[]} onOpenTask={() => {}} onOpenFeature={() => setOpen(true)} /></div>
</main>;
}
createRoot(document.getElementById("root")!).render(<Fixture />);
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Eddy history fixture</title></head><body><div id="root"></div><script type="module" src="./eddy-history.tsx"></script></body></html>
+7
View File
@@ -0,0 +1,7 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import EddyTasksPage from '../../src/components/EddyTasksPage';
import '../../src/styles.css';
// Browser fixture; no API is supplied here. The harness serves isolated synthetic data.
createRoot(document.getElementById('root')!).render(<React.StrictMode><EddyTasksPage email="history-browser@example.com" onLogin={() => { document.documentElement.dataset.relogin = 'requested'; }} /></React.StrictMode>);
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Eddy knowledge review · local fixture</title></head><body><div id="root"></div><script type="module" src="./eddy-review.tsx"></script></body></html>
+22
View File
@@ -0,0 +1,22 @@
// Local rendering of real review components. No server or production requests.
import React from "react";
import { createRoot } from "react-dom/client";
import DialogHost from "../../src/components/DialogHost";
import EddyCompatPanel from "../../src/components/EddyCompatPanel";
import { api } from "../../src/lib/api";
import "../../src/styles.css";
const baseline = 'notes-build-a';
const source = '// review fixture: never execute\nreturn { install(ctx) { ctx.status("installed") }, dispose() {} };';
const bytes = new TextEncoder().encode(source);
const sha = Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))).map(x=>x.toString(16).padStart(2,'0')).join('');
const knowledge = {category:'app-compat',confidence:'suspected',summary:'Notes Catalyst 布局递归:启动后无响应',cause:'父布局回调反复请求子布局',solution:'仅在指定调用栈中抑制重复布局请求',validation:'冷启动 120 秒,内存稳定;未验证真机',rollback:'移除 guard 后下次启动恢复原逻辑'};
const fix = {knowledge,safety:{verdict:'allow',reason:'已自动检查:仅限定进程内布局,无外传行为'}, id:'fixture-layout',rev:1,tier:'frida-guard',problem:'hang:layout',title:'只抑制递归布局请求',state:'published',baseline,author:'local fixture',created:Date.now(),confirmations:{installed:0,stillFailing:0,regression:0},target:{baseline,executableUUID:'EXACT-BUILD-UUID'},runtimeContract:'eddy-compat-js-v1',payload:{path:'guard.js',sha256:sha},verify:{scope:'启动到登录页',durationSeconds:120,finalMiB:156},evidence:{sourceUnchanged:true,uncovered:['真实账号登录','真机回归']},verification:null };
const overview = { baselines:[], observations:[], fixes:[fix], problems:[{knowledge,baseline,signature:'hang:window',aliases:['hang:layout'],kind:'hang',status:'open',firstSeen:Date.now(),lastSeen:Date.now(),scope:{platform:'Catalyst'}},{baseline:'other-build',signature:'hang:window',aliases:[],kind:'hang',status:'open',firstSeen:Date.now(),lastSeen:Date.now(),scope:{}}], advisories:[{knowledge,safety:{verdict:'allow',reason:'检查通过'}, id:'fixture-advice',baseline,problem:'hang:layout',title:'Notes Catalyst 布局循环:启动后无响应',text:'## 现象\n启动后主线程卡住,内存持续增长。\n\n## 根因\n父布局回调再次请求子视图布局,形成循环。\n\n## 处理\n只在指定调用栈中抑制重复布局请求。保持源码不变。\n\n**验证边界:** 冷启动持续 120 秒,未覆盖登录与完整业务回归。\n\n`<script>alert("must not execute")</script>`',state:'verified',manual:false,author:'local fixture',scope:{}}] };
overview.problems.push({knowledge:{...knowledge,category:'devicesim',summary:'Catalyst 窗口尺寸变化导致容器渲染异常'},baseline,signature:'layout:window',aliases:[],kind:'layout',status:'open',firstSeen:Date.now(),lastSeen:Date.now(),scope:{platform:'Catalyst'}});
api.eddyAdmin = async <T,>(path: string, init?: RequestInit): Promise<T> => {
if (init?.method === 'POST') throw new Error('只读本地 fixture,不写入服务');
if (path.endsWith('/overview')) return structuredClone(overview) as T;
if (path.includes('/compat/packs/')) return {manifest:{id:fix.id,rev:1,target:fix.target},payload_b64:btoa(source),payload_name:'guard.js',sha256:sha} as T;
throw new Error('Unexpected fixture request '+path);
};
createRoot(document.getElementById('root')!).render(<main style={{maxWidth:1200,height:'100vh',overflow:'auto',margin:'0 auto',padding:24}}><p>本地审核界面预览 · 示例数据 · 不连接线上</p><EddyCompatPanel /><DialogHost /></main>);
+3
View File
@@ -0,0 +1,3 @@
<!doctype html>
<html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Product profiles · local UI fixture</title></head>
<body><div id="root"></div><script type="module" src="./product-profiles.tsx"></script></body></html>
+35
View File
@@ -0,0 +1,35 @@
// Browser-only fixture. Real components, in-memory API, no production services.
import React, { useState } from "react";
import { createRoot } from "react-dom/client";
import Management from "../../src/components/Management";
import ImportDialog from "../../src/components/ImportDialog";
import { api } from "../../src/lib/api";
import { useI18n, setLang } from "../../src/lib/i18n";
import { defaultProductProfiles, validateProductProfiles } from "@bbbug/shared/product_profiles";
import "../../src/styles.css";
let saved = defaultProductProfiles();
let lastRequest: unknown = null;
api.adminProductProfiles = async () => structuredClone(saved);
api.productProfiles = async () => ({ ...structuredClone(saved), profiles: structuredClone(saved.profiles.filter((p) => p.enabled)) });
api.saveProductProfiles = async (config) => {
if (config.revision !== saved.revision) throw new Error("Configuration changed. Reload before saving.");
saved = { revision: saved.revision + 1, profiles: validateProductProfiles(config.profiles) };
return structuredClone(saved);
};
api.clustersList = async () => ({ clusters: ["default"] });
api.import = async (...args) => { lastRequest = args; return { added: [], skipped: [{ link: "local fixture", reason: JSON.stringify(args) }] }; };
api.createFeature = async (input) => { lastRequest = input; throw new Error(`Local fixture only: ${JSON.stringify(input)}`); };
setLang("zh");
function Fixture() {
const [open, setOpen] = useState(false);
const [request, setRequest] = useState<unknown>(null);
const { lang } = useI18n();
return <main style={{ maxWidth: 1120, padding: 24, margin: "0 auto" }}>
<header style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 20 }}><h2 style={{ marginRight: "auto" }}>Streamline</h2><span>Local UI fixture</span><button onClick={() => setLang(lang === "zh" ? "en" : "zh")}>中 / EN</button><button className="primary" onClick={() => setOpen(true)}>创建任务</button><button onClick={() => setRequest(lastRequest)}>检查请求</button></header>
<Management supers={[]} admins={[]} onSave={async () => {}} nodes={[]} initialTab="products" />
<ImportDialog open={open} onClose={() => setOpen(false)} />
{request != null && <pre>{JSON.stringify(request, null, 2)}</pre>}
</main>;
}
createRoot(document.getElementById("root")!).render(<Fixture />);
+3
View File
@@ -0,0 +1,3 @@
<!doctype html>
<html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Claude usage · local UI fixture</title></head>
<body><div id="root"></div><script type="module" src="./usage.tsx"></script></body></html>
+215
View File
@@ -0,0 +1,215 @@
// Browser-only fixture. Real Management/UsagePanel, no SSO, no production API.
import { createRoot } from "react-dom/client";
import Management from "../../src/components/Management";
import type { ClusterNode } from "../../src/types";
import type { ClaudeUsage, ClaudeTokenTotals, NodeMetrics, ClaudeSourceDay } from "@bbbug/shared/protocol";
import { claudeApiCostUsd, claudeTokenTotal } from "@bbbug/shared/protocol";
import type { ClaudeUsageSource } from "@bbbug/shared/claude_usage_source";
import { api } from "../../src/lib/api";
import { setLang } from "../../src/lib/i18n";
import "../../src/styles.css";
const now = Date.now();
function metrics(usage: ClaudeUsage | null, over: Partial<NodeMetrics> = {}): NodeMetrics {
return {
at: now - 8_000, cores: 10, cpuPct: 22, loadPct: 31, uptimeSec: 86_400,
diskUsedPct: 54, diskFreeBytes: 220e9, memTotalBytes: 32 * 2 ** 30,
memUsedPct: 61, swapUsedBytes: 1.2 * 2 ** 30,
slowAt: now - 20_000, slowError: null, slowMs: 240,
agent: { mode: "pty", loggedIn: true, authMethod: "claude.ai", checkedAt: now - 20_000, error: null, authGateMs: 0 },
claudeUsage: usage,
...over,
};
}
function node(over: Partial<ClusterNode> & { id: string; platform: ClusterNode["platform"] }): ClusterNode {
return {
baseUrl: `http://${over.id}:5180`,
status: "online", lastSeenAt: now - 4_000,
evalInFlight: 0, evalCapacity: 3, fixInFlight: 0, fixCapacity: 1,
version: "local-fixture", createdAt: now - 86400_000, live: true,
clusters: ["default"],
...over,
};
}
const day = 86_400_000;
/**
* A `days`-long daily series ending today, scaled off the lifetime totals so
* the window numbers stay plausible next to them.
*/
function dailySeries(tokens: ClaudeTokenTotals, days: number) {
const share = 1 / (days * 6);
return Array.from({ length: days }, (_, i) => {
const tick = { date: new Date(now - (days - 1 - i) * day).toISOString().slice(0, 10) };
const scale = share * (i % 5 === 0 ? 0 : 1);
const t: ClaudeTokenTotals = {
input: Math.round(tokens.input * scale),
output: Math.round(tokens.output * scale),
cacheRead: Math.round(tokens.cacheRead * scale),
cacheCreation: Math.round(tokens.cacheCreation * scale),
};
const apiCostUsd = claudeApiCostUsd(t, "sonnet");
return { ...tick, tokens: t, apiCostUsd, bySource: splitDay(claudeTokenTotal(t), apiCostUsd, i, days) };
});
}
/**
* [token share, API-price share] per source, from the 10-29 scan of the real
* fleet (evaluator-android-01 / fei-ios-01). The two columns differ on purpose:
* report generation is a sliver of the tokens but a real slice of the price.
*/
const SOURCE_MIX: [ClaudeUsageSource, number, number][] = [
["bugfix", 0.70, 0.66], ["feature", 0.13, 0.12], ["verify", 0.08, 0.075], ["eval", 0.055, 0.07],
["asking", 0.008, 0.012], ["asking_edit", 0.004, 0.006], ["report", 0.003, 0.03],
["human", 0.006, 0.008], ["rsi", 0.001, 0.01], ["eddy", 0.0005, 0.001],
];
/** Split one machine-day; 未识别 ramps up over the last ten days so the 增长 flag has something to flag. */
function splitDay(tokens: number, usd: number, i: number, days: number): ClaudeSourceDay[] {
if (tokens <= 0) return [];
const unknown = i >= days - 10 ? 0.004 * (i - (days - 11)) : 0.002;
const mix: [ClaudeUsageSource, number, number][] = [...SOURCE_MIX, ["unknown", unknown, unknown]];
const tw = mix.reduce((a, m) => a + m[1], 0);
const uw = mix.reduce((a, m) => a + m[2], 0);
return mix.map(([source, t, u], k) => ({
source,
tokens: Math.round(tokens * t / tw),
apiCostUsd: usd * u / uw,
sessions: Math.max(1, Math.round(((k * 7 + i) % 5) + t * 40)),
}));
}
function makeUsage(
{ coveredDays = 30, ...over }: Partial<ClaudeUsage> & {
tokens: ClaudeTokenTotals; tokensAsOf: string; startedAt: number; coveredDays?: number;
},
): ClaudeUsage {
return {
at: now - 35_000, ms: 290, error: null,
email: null, plan: "max", machineId: null,
fiveHour: null, sevenDay: null, sevenDaySonnet: null, sevenDayOpus: null,
quotaAt: null,
apiCostUsd: claudeApiCostUsd(over.tokens, "sonnet"),
daily: dailySeries(over.tokens, coveredDays),
dailyFromAt: now - (coveredDays - 1) * day,
...over,
};
}
const nodes: ClusterNode[] = [
// A Mac running two satellites: same machineId, same account. Both cards
// show the machine's tokens; the fleet totals count them once.
node({
id: "lemon-ios-01.shiro0.icu", platform: "ios",
metrics: metrics(makeUsage({
email: "lemon@bytedance.com", machineId: "mach-lemon",
fiveHour: { usedPct: 91, resetsAt: now + 48 * 60_000 },
sevenDay: { usedPct: 67, resetsAt: now + 2 * day },
quotaAt: now - 35_000,
tokens: { input: 12_400_000, output: 980_000, cacheRead: 88_000_000, cacheCreation: 6_200_000 },
tokensAsOf: "2026-09-12",
startedAt: now - 265 * day,
})),
}),
node({
id: "lemon-android-01.shiro0.icu", platform: "android",
metrics: metrics(makeUsage({
at: now - 41_000, ms: 310,
email: "lemon@bytedance.com", machineId: "mach-lemon",
fiveHour: { usedPct: 91, resetsAt: now + 48 * 60_000 },
sevenDay: { usedPct: 67, resetsAt: now + 2 * day },
quotaAt: now - 41_000,
tokens: { input: 12_400_000, output: 980_000, cacheRead: 88_000_000, cacheCreation: 6_200_000 },
tokensAsOf: "2026-09-12",
startedAt: now - 265 * day,
})),
}),
// Own probe 429'd, so its meters must fill from the sibling on the same
// account and say so, rather than reading 未知.
node({
id: "fei-android-01.shiro0.icu", platform: "android",
metrics: metrics(makeUsage({
at: now - 12_000, ms: 268, error: "oauth usage HTTP 429",
email: "fei@bytedance.com", machineId: "mach-fei-a",
tokens: { input: 7_800_000, output: 620_000, cacheRead: 40_000_000, cacheCreation: 2_400_000 },
tokensAsOf: "2026-09-11",
startedAt: now - 40 * day,
})),
}),
// Same Claude login, different Mac: quota shared, tokens NOT merged.
node({
id: "fei-ios-01.shiro0.icu", platform: "ios",
metrics: metrics(makeUsage({
email: "fei@bytedance.com", machineId: "mach-fei-i",
fiveHour: { usedPct: 38, resetsAt: now + 3 * 3600_000 },
sevenDay: { usedPct: 52, resetsAt: now + 2 * day },
quotaAt: now - 35_000,
tokens: { input: 4_200_000, output: 410_000, cacheRead: 21_000_000, cacheCreation: 1_100_000 },
tokensAsOf: "2026-09-12",
startedAt: now - 80 * day,
})),
}),
// Enrolled 9 days ago: prorates to $200 × 9/30 instead of a full month.
node({
id: "ux-ios-01.shiro0.icu", platform: "ios",
metrics: metrics(makeUsage({
email: "ux@bytedance.com", machineId: "mach-ux",
fiveHour: { usedPct: 12, resetsAt: now + 90 * 60_000 },
sevenDay: { usedPct: 21, resetsAt: now + day },
quotaAt: now - 35_000,
tokens: { input: 3_272, output: 1_289_779, cacheRead: 372_006_214, cacheCreation: 4_336_744 },
tokensAsOf: "2026-09-12",
startedAt: now - 9 * day,
coveredDays: 9,
})),
}),
node({
id: "fei-android-02.shiro0.icu", platform: "android",
metrics: metrics(null),
}),
// Satellite too old for a daily series: left out of the window totals and
// called out, not silently counted as zero.
node({
id: "fei-ios-03.shiro0.icu", platform: "ios",
live: false, status: "offline", lastSeenAt: now - 18 * 60_000,
metrics: metrics({
...makeUsage({
at: now - 20 * 60_000, ms: 301,
email: "ios-03@bytedance.com",
fiveHour: { usedPct: 12, resetsAt: now - 10 * 60_000 },
sevenDay: { usedPct: 44, resetsAt: now + day },
tokens: { input: 1_050_000, output: 90_000, cacheRead: 3_400_000, cacheCreation: 220_000 },
tokensAsOf: "2026-09-10",
startedAt: now - 12 * day,
}),
daily: null, dailyFromAt: null,
}),
}),
];
// The usage tab fetches its per-source detail itself; serve it from the
// fixture nodes instead of a control plane.
(api as { claudeSources: typeof api.claudeSources }).claudeSources = async () => ({
entries: nodes.flatMap((n) => {
const usage = n.metrics?.claudeUsage;
if (!usage) return [];
const withSamples: ClaudeUsage = usage.machineId === "mach-lemon"
? { ...usage, unknownSamples: [
{ prefix: "帮我把 feature/qi-story-widget-thought-sticky rebase 到 develop", cwd: "ai_workspace", sessions: 1, tokens: 20_800_000 },
{ prefix: "I do git fetch --refetch on TikTok and return", cwd: "ai_workspace_ios", sessions: 2, tokens: 1_300_000 },
] }
: usage;
return [{ nodeId: n.id, usage: withSamples }];
}),
});
setLang("zh");
createRoot(document.getElementById("root")!).render(
<div className="page-modal" style={{ position: "static", inset: "auto", width: "100%", minHeight: "100vh", borderRadius: 0 }}>
<div className="page-modal-body" style={{ padding: "24px 32px 48px" }}>
<Management supers={[]} admins={[]} onSave={async () => {}} nodes={nodes} initialTab="usage" />
</div>
</div>,
);
@@ -0,0 +1,21 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import IdeaUploadDialog from "../src/components/IdeaUploadDialog";
import { EDDY_SHARE_ACCEPT, eddyShareBaseName, isEddyShareName } from "../src/lib/eddyShare";
test("上传 Eddy 想法的第一步:文件框收 .eddy,文案不再只说 zip", () => {
const html = renderToStaticMarkup(<IdeaUploadDialog myEmail="someone@example.com" onClose={() => {}} onDone={() => {}} />);
expect(html).toContain(`accept="${EDDY_SHARE_ACCEPT}"`);
expect(EDDY_SHARE_ACCEPT).toContain(".eddy");
expect(html).toContain("或点击选择 .eddy / .eddy.zip 文件");
expect(html).toContain("存下来的 .eddy 文件");
expect(html).not.toContain("选择 .zip 文件");
expect(html).not.toContain("导出 zip");
});
test("弹窗用的文件名判断就是 shared 里那一份", () => {
expect(isEddyShareName("首页换个标题.eddy")).toBe(true);
expect(isEddyShareName("首页换个标题.eddy.zip")).toBe(true);
expect(isEddyShareName("截图.png")).toBe(false);
expect(eddyShareBaseName("首页换个标题.eddy")).toBe("首页换个标题");
});
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, test } from "bun:test";
import { canPublishToIdeas } from "../src/lib/ideas";
/** 抽屉右下「发布到 Ideas」角标只在 Feature 类别出现:Bug 是缺陷单,不是想法。 */
describe("canPublishToIdeas:谁能在详情页把单子发布到 Ideas", () => {
test("Feature + 已登录 → 显示", () => {
expect(canPublishToIdeas("feature", "someone@bytedance.com")).toBe(true);
});
test("其余四类(含 Bug)一律不显示", () => {
expect(canPublishToIdeas("bug", "someone@bytedance.com")).toBe(false);
expect(canPublishToIdeas("security", "someone@bytedance.com")).toBe(false);
expect(canPublishToIdeas("prototype", "someone@bytedance.com")).toBe(false);
expect(canPublishToIdeas("verify", "someone@bytedance.com")).toBe(false);
});
test("没登录(抽屉还没拿到 myEmail)不显示", () => {
expect(canPublishToIdeas("feature", "")).toBe(false);
expect(canPublishToIdeas(null, "someone@bytedance.com")).toBe(false);
expect(canPublishToIdeas(undefined, "someone@bytedance.com")).toBe(false);
});
});
+63
View File
@@ -0,0 +1,63 @@
import { describe, expect, test } from "bun:test";
import type { KbImportProgressEvent } from "@bbbug/shared/kb_import";
import { appendImportStreamChunk, estimatedImportPercent, mergeImportProgressEvent } from "../src/lib/kbImportProgress";
const event = (patch: Partial<KbImportProgressEvent> = {}): KbImportProgressEvent => ({
at: 1, kind: "phase", phase: "agent", percent: 40, ceiling: 68,
message: "Agent 正在运行", ...patch,
});
describe("知识导入进度估算", () => {
test("等待时只向当前真实阶段的上限渐近", () => {
expect(estimatedImportPercent(event(), 1_000, 1_000)).toBe(40);
const later = estimatedImportPercent(event(), 1_000, 61_000);
expect(later).toBeGreaterThan(40);
expect(later).toBeLessThanOrEqual(68);
});
test("不会倒退,也不会在完成事件之前显示 100", () => {
expect(estimatedImportPercent(event({ percent: 20, ceiling: 30 }), 0, 999_999, 57)).toBe(57);
expect(estimatedImportPercent(event({ percent: 99, ceiling: 100 }), 0, 999_999)).toBe(99);
});
test("只有服务器完成事件才能到 100", () => {
expect(estimatedImportPercent(event({ phase: "done", percent: 100, ceiling: 100 }), 0, 0)).toBe(100);
});
test("合并 Cursor 累积式 assistant partial,只保留最新原始帧", () => {
const first = event({ kind: "raw", meta: "stdout", message: "stdout · assistant", detail: "a" });
const second = event({ at: 2, kind: "raw", meta: "stdout", message: "stdout · assistant", detail: "ab" });
expect(mergeImportProgressEvent([first], second)).toEqual([second]);
});
test("不同 token 文本的 assistant partial 会拼成一个连续 stream", () => {
const first = event({ kind: "assistant", meta: "partial", message: "Agent 输出:一", detail: "一" });
const second = event({ at: 2, kind: "assistant", meta: "partial", message: "Agent 输出:个", detail: "个" });
expect(mergeImportProgressEvent(mergeImportProgressEvent([], first), second)).toEqual([
expect.objectContaining({
at: 2, kind: "assistant", message: "Agent 正在流式生成候选条目",
detail: "一个", meta: "streaming · 2 chars",
}),
]);
});
test("兼容累积快照、重复 chunk 和边界重叠", () => {
expect(appendImportStreamChunk("Lemon", "Lemon8")).toBe("Lemon8");
expect(appendImportStreamChunk("Lemon8", "Lemon8")).toBe("Lemon8");
expect(appendImportStreamChunk("Core dy", "dylib")).toBe("Core dylib");
});
test("result 到达后会把增长中的 stream 标为完成", () => {
const partial = mergeImportProgressEvent([], event({ kind: "assistant", detail: "[]" }));
const result = event({ at: 2, kind: "result", message: "Agent 运行结束" });
expect(mergeImportProgressEvent(partial, result)[0]).toMatchObject({
message: "Agent 流式输出完成", meta: "stream complete · 2 chars",
});
});
test("不同工具与 lifecycle 日志仍按时间追加", () => {
const first = event({ kind: "raw", meta: "lifecycle", message: "heartbeat", detail: "10s" });
const second = event({ at: 2, kind: "raw", meta: "lifecycle", message: "heartbeat", detail: "20s" });
expect(mergeImportProgressEvent([first], second)).toEqual([first, second]);
});
});
+129
View File
@@ -0,0 +1,129 @@
import { test, expect, describe } from "bun:test";
import { classifyMrFailure } from "../src/lib/mrFailure";
/**
* 分类错了的代价不对称:
* - 把「没授权」认成 unknown,用户只是少一段引导,还能看到原文;
* - 把别的错认成「没授权」,用户会被指去 Bits 点一圈,回来发现照样失败 —— 更糟。
* 所以用例主体是**生产上真实出现过的原文**(下面每条都抄自面板记录),外加一组
* 「不许误伤」的反例。
*/
const REAL = {
notAuthorized: 'MR 提交失败(as srj.5):create_mr: HTTP 200: {"code":400,"data":null,"message":"尚未登录, 或会话已过期"}',
mrExists: 'MR 提交失败(as tanzhehao):create_mr: HTTP 200: {"code":400,"data":null,"message":"MR has already existed for project_id(TikTok), source_branch(feature/bb-skin-guide-inline-message) and target_branch(latest_but_untested)"}',
branchMissing: 'MR 提交失败(as tanzhehao):create_mr: HTTP 200: {"code":400,"data":null,"message":"Gitlab Error: TikTok {\\"message\\":\\"input: createMergeRequest resource Branch is not found: merge request source branch not found\\"}"}',
legacyBranch: "MR 创建失败(已重试 3 次): 远程分支 bugfix/default-system-font-text-shadow 不存在且本地重推失败: branch bugfix/default-system-font-text-shadow not found in local checkout /Users/fei/ai_workspace/TikTok",
threw: "MR 提交异常:The operation timed out.",
// 控制面自己写的预检失败(bits.ts::unconfiguredRepoError / unpushedBranchError)。
repoUnconfigured: "MR 提交失败(as johnlee):preflight: 分支 feature/lynx-im-page-ui-tree-audit 推在 tt_im_monorepo,"
+ "但这个仓库没有配置 GitLab project id,控制面建不了它的 MR(见 shared/src/repos.ts 的 tt-im-monorepo)。"
+ "请手动建:https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Flynx-im-page-ui-tree-audit",
clickRequired: "MR 提交失败(as johnlee):preflight: 分支 feature/lynx-im-page-ui-tree-audit 推在 tt_im_monorepo,"
+ "这个仓的 MR 不自动建,需要在面板上点「创建 MR」发起。也可以直接自己建:"
+ "https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Flynx-im-page-ui-tree-audit",
devTaskClickRequired: "MR 提交失败(as johnlee):preflight: 分支 feature/lynx-im-page-ui-tree-audit 推在 tt_im_monorepo,"
+ "这个仓的开发任务不自动建,需要在面板上点「创建开发任务」发起。也可以直接自己创建:"
+ "https://bits.bytedance.net/devops/39151416834/develop/update?devops_space_type=server_fe",
neverPushed: "MR 提交失败(as johnlee):preflight: 分支 feature/x 没有推到交付仓 TikTok (Android) 的远端,"
+ "无法建 MR —— 这不是重试能解决的,需要让任务重跑并把分支推上去。",
};
describe("classifyMrFailure", () => {
test("经办人和 watcher 都没绑 Token,仍走绑定后重试", () => {
const d = classifyMrFailure("MR 提交失败:none of watcher could successfully create MR")!;
expect(d.kind).toBe("not_authorized");
expect(d.retryable).toBe(true);
expect(d.bitsUser).toBeNull();
});
test("失效的个人 JWT 归为授权问题", () => {
const d = classifyMrFailure("MR 提交失败(as johnlee):create_dev_task: 当前登录用户 johnlee 保存的 Bits 个人 Token 已失效(Invalid JWT token)");
expect(d?.kind).toBe("not_authorized");
expect(d?.bitsUser).toBe("johnlee");
});
test("Bits 不认这个身份 —— 唯一一种「用户自己能修」的失败", () => {
const d = classifyMrFailure(REAL.notAuthorized)!;
expect(d.kind).toBe("not_authorized");
expect(d.bitsUser).toBe("srj.5");
expect(d.retryable).toBe(true);
});
test("分支上已有 MR —— 重试会去认领它", () => {
expect(classifyMrFailure(REAL.mrExists)!.kind).toBe("mr_exists");
});
test("远端分支不见了 —— 重试没用,只能重跑", () => {
for (const r of [REAL.branchMissing, REAL.legacyBranch]) {
const d = classifyMrFailure(r)!;
expect(d.kind).toBe("branch_missing");
expect(d.retryable).toBe(false);
}
});
test("分支推在没接入的仓库 —— 重试没用,给的是手动建 MR 的直达链接", () => {
const d = classifyMrFailure(REAL.repoUnconfigured)!;
expect(d.kind).toBe("repo_unconfigured");
expect(d.retryable).toBe(false);
expect(d.manualMrUrl).toBe(
"https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/new?merge_request%5Bsource_branch%5D=feature%2Flynx-im-page-ui-tree-audit",
);
});
test("等人点一下建 MR —— 是待办不是失败,而且必须可重试(那个按钮就是它)", () => {
const d = classifyMrFailure(REAL.clickRequired)!;
expect(d.kind).toBe("mr_click_required");
expect(d.retryable).toBe(true);
expect(d.manualMrUrl).toContain("/merge_requests/new?");
});
test("开发任务待创建使用同一待办分类,并提取 Bits 创建入口", () => {
const d = classifyMrFailure(REAL.devTaskClickRequired)!;
expect(d.kind).toBe("mr_click_required");
expect(d.retryable).toBe(true);
expect(d.manualMrUrl).toBe(
"https://bits.bytedance.net/devops/39151416834/develop/update?devops_space_type=server_fe",
);
});
test("哪个仓都没推上去 —— 与「远端分支没了」同一类,都得重跑", () => {
const d = classifyMrFailure(REAL.neverPushed)!;
expect(d.kind).toBe("branch_missing");
expect(d.retryable).toBe(false);
});
test("没有手动链接时不瞎给", () => {
expect(classifyMrFailure(REAL.branchMissing)!.manualMrUrl).toBeNull();
});
test("超时算网络类,可以直接重试", () => {
const d = classifyMrFailure(REAL.threw)!;
expect(d.kind).toBe("network");
expect(d.retryable).toBe(true);
});
test("没见过的形态落到 unknown,但仍然给重试 + 原文", () => {
const d = classifyMrFailure("MR 提交失败(as janice.wang):reviewers_rd: HTTP 500: gateway blew up")!;
expect(d.kind).toBe("unknown");
expect(d.bitsUser).toBe("janice.wang");
expect(d.raw).toContain("gateway blew up");
});
test("空原因不接管,交给「提交 MR」", () => {
expect(classifyMrFailure(null)).toBeNull();
expect(classifyMrFailure("")).toBeNull();
expect(classifyMrFailure(" ")).toBeNull();
});
test("任意非空 failureReason 都走黄卡,认不出的形态落到 unknown", () => {
const d = classifyMrFailure("Fix-Critic 判定证据不足:缺少 MR diff 对照")!;
expect(d.kind).toBe("unknown");
expect(d.raw).toContain("Fix-Critic");
expect(classifyMrFailure("实现失败:编译不过")!.kind).toBe("unknown");
});
test("取不到 as 身份时不瞎猜", () => {
expect(classifyMrFailure("MR 提交失败:create_mr: HTTP 0: fetch failed")!.bitsUser).toBeNull();
});
});
+118
View File
@@ -0,0 +1,118 @@
import { test, expect, describe } from "bun:test";
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
import { dirname, join, relative, resolve } from "node:path";
/**
* src/styles/*.css hold rules that only one lazy overlay panel renders; they
* ship in that panel's async chunk and exist in the page only after it has been
* opened. That's safe only if every element that can carry one of those classes
* is rendered by code that loads the stylesheet. So for each class in a panel
* stylesheet, every source file mentioning it must be unreachable from the app
* (entry + every other lazy chunk) without passing through the panel component
* that imports the stylesheet. A class the board / drawer / another panel also
* uses belongs in styles.css.
*/
const SRC = resolve(import.meta.dir, "../src");
function walk(dir: string, out: string[] = []): string[] {
for (const e of readdirSync(dir)) {
const p = join(dir, e);
if (statSync(p).isDirectory()) walk(p, out);
else if (/\.tsx?$/.test(e)) out.push(p);
}
return out;
}
const files = walk(SRC);
const text = new Map(files.map((f) => [f, readFileSync(f, "utf8")]));
function resolveRel(from: string, spec: string): string | null {
if (!spec.startsWith(".")) return null;
const base = resolve(dirname(from), spec);
for (const c of [base, base + ".ts", base + ".tsx", join(base, "index.ts"), join(base, "index.tsx")]) {
if (existsSync(c) && statSync(c).isFile()) return c;
}
return null;
}
// Static edges (import … from / export … from / side-effect import), and lazy targets.
const staticEdges = new Map<string, string[]>();
const lazyTargets = new Set<string>();
for (const [f, src] of text) {
const deps: string[] = [];
for (const m of src.matchAll(/(?:^|\n)\s*(?:import|export)\s+(?!type\b)(?:[^"';]*?\sfrom\s+)?["']([^"']+)["']/g)) {
const r = resolveRel(f, m[1]); if (r) deps.push(r);
}
staticEdges.set(f, deps);
for (const m of src.matchAll(/import\(\s*["']([^"']+)["']\s*\)/g)) {
const r = resolveRel(f, m[1]); if (r) lazyTargets.add(r);
}
}
function reachable(roots: string[], blocked: string): Set<string> {
const seen = new Set<string>(); const stack = roots.filter((r) => r !== blocked);
while (stack.length) {
const f = stack.pop()!;
if (seen.has(f)) continue;
seen.add(f);
for (const d of staticEdges.get(f) ?? []) if (d !== blocked && !seen.has(d)) stack.push(d);
}
return seen;
}
/** Each complex selector of the sheet → the classes it requires on some element (ignores :not(...)). */
function selectorsIn(css: string): { sel: string; classes: string[] }[] {
const noComments = css.replace(/\/\*[\s\S]*?\*\//g, "");
const out: { sel: string; classes: string[] }[] = [];
for (const m of noComments.matchAll(/([^{}]+)\{/g)) {
const list = m[1].trim();
if (list.startsWith("@")) continue;
for (const sel of list.split(/,(?![^(]*\))/).map((s) => s.trim()).filter(Boolean)) {
const classes = [...sel.replace(/:not\((?:[^()]|\([^()]*\))*\)/g, "").matchAll(/\.([A-Za-z_][\w-]*)/g)].map((c) => c[1]);
out.push({ sel, classes });
}
}
return out;
}
/** Files that could put `cls` on an element: literal token, or a `prefix-${…}` / "prefix-" + … builder. */
function filesUsing(cls: string): string[] {
const esc = cls.replace(/[-]/g, "\\-");
const lit = new RegExp(`(^|[^\\w-])${esc}($|[^\\w-])`);
const out: string[] = [];
for (const [f, src] of text) {
if (lit.test(src)) { out.push(f); continue; }
for (const m of src.matchAll(/([A-Za-z_][\w-]{2,})(?:\$\{|["'`]\s*\+)/g)) {
if (cls.startsWith(m[1]) && cls !== m[1]) { out.push(f); break; }
}
}
return out;
}
const styleDir = join(SRC, "styles");
const sheets = existsSync(styleDir) ? readdirSync(styleDir).filter((f) => f.endsWith(".css")) : [];
describe("panel stylesheets only style their own lazy panel", () => {
test("there are panel stylesheets to check", () => { expect(sheets.length).toBeGreaterThan(0); });
for (const sheet of sheets) {
test(sheet, () => {
const importers = files.filter((f) => new RegExp(`import\\s+["'][./]+styles/${sheet.replace(".", "\\.")}["']`).test(text.get(f)!));
expect(importers.length).toBe(1);
const entry = importers[0];
expect(lazyTargets.has(entry)).toBe(true); // it must be a lazily-loaded component
const outside = reachable([join(SRC, "main.tsx"), ...lazyTargets], entry);
// A selector is scoped when at least one class it requires is panel-only:
// `.lab-row .pill` can only match inside a `.lab-row`, even though `.pill`
// is global. Unscoped selectors (all classes shared, or none) must stay in styles.css.
const cache = new Map<string, string[]>();
const leaksOf = (cls: string) => {
if (!cache.has(cls)) cache.set(cls, filesUsing(cls).filter((f) => outside.has(f)).map((f) => relative(SRC, f)));
return cache.get(cls)!;
};
const unscoped: string[] = [];
for (const { sel, classes } of selectorsIn(readFileSync(join(styleDir, sheet), "utf8"))) {
if (!classes.some((c) => leaksOf(c).length === 0)) {
unscoped.push(`${sel} (${classes.map((c) => `.${c} ← ${leaksOf(c).slice(0, 2).join(", ") || "?"}`).join("; ")})`);
}
}
expect(unscoped).toEqual([]);
});
}
});
+323
View File
@@ -0,0 +1,323 @@
import { test, expect, describe } from "bun:test";
import {
parseSentinels, applyAnswers, normalizeSentinels, nextSentinelIndex, rehypePlanMarks,
type Answer, type Comment,
} from "../src/lib/planDecisions";
/**
* 执行计划确认页把每个 NEEDS_INPUT 哨兵变成一张可操作的卡片。出错的方式不是抛异常,
* 而是安静地少一张卡 —— 用户看不到那处待补充,以为自己已经处理完了,然后带着缺失
* 信息把任务放进修复队列。所以这里盯死两件事:
*
* 1. 渲染出来的卡片数量与顺序,必须和源文本里解析出的哨兵一一对应;
* 2. 「填入计划」写回文本时,必须只替换用户答的那一个哨兵。
*
* 用例形状取自生产上真实的 TestSpec:哨兵嵌在列表项里、提示里引代码(反引号)、
* 同一句提示重复出现、以及夹在代码块里的那种。
*/
const NI = (h: string) => `<<<<<<< NEEDS_INPUT: ${h} >>>>>>>`;
const PLAN = `## 复现条件 // Reproduct condition
- 账号/环境: 泰国测试账号 tt_qa_th_04;设备 ${NI("具体设备型号与系统版本")}
- UI 入口指引:
- ${NI("从首页到拍摄页的入口路径")}
- 其他特殊要求: 无特殊要求
## 复现步骤 // Operations
1. 进入拍摄页,把滤镜强度拖到 80。
2. 切后台:**${NI("切后台的具体操作")}**
3. 回前台观察滤镜强度。
![](images/plan-11111111-2222-3333-4444-555555555555.png)
## 期望与实际
- 期望: ${NI("期望对齐到 `CameraFilterStore.restoreOnResume()` 的哪个分支")}
- 实际: 强度回落到默认值 50。
## 回归风险点
- ${NI("具体设备型号与系统版本")}
- 不得影响既有的相机资源释放降级逻辑。
\`\`\`
${NI("这条在代码块里,渲染扫描看不到")}
\`\`\`
`;
const sentinels = () => parseSentinels(PLAN, "(未分节)", "(未注明)");
describe("parseSentinels", () => {
test("按文档顺序找全哨兵,并记住各自所属章节", () => {
const s = sentinels();
expect(s).toHaveLength(6);
expect(s.map((x) => x.section)).toEqual([
"复现条件 // Reproduct condition",
"复现条件 // Reproduct condition",
"复现步骤 // Operations",
"期望与实际",
"回归风险点",
"回归风险点",
]);
});
test("提示文字剥掉哨兵外壳", () => {
expect(sentinels()[0].hint).toBe("具体设备型号与系统版本");
});
test("同一句提示出现两次时,两处拿到不同的 key", () => {
// 否则答了「复现条件」那处,「回归风险点」那处会跟着一起被判定为已处理。
const s = sentinels();
expect(s[0].raw).toBe(s[4].raw);
expect(s[0].key).not.toBe(s[4].key);
});
});
describe("parseSentinels · @OPTION 候选", () => {
const withOpts = `## 复现条件 // Reproduct condition
- 设备: <<<<<<< NEEDS_INPUT: 具体设备型号与系统版本 @OPTION iPhone 15 Pro · iOS 17.5 | 设备池默认机 | 设备:iPhone 15 Pro / iOS 17.5 @OPTION Pixel 8 · Android 14 | 工单截图状态栏 | 设备:Pixel 8 / Android 14 >>>>>>>
- 门控: <<<<<<< NEEDS_INPUT: 受哪个实验位控制 @OPTION studio_effects_panel_discover | 本地新建(未找到可复用的既有实验位) | 门控 Key:studio_effects_panel_discover(AB Class: StudioEffectsPanelDiscoverExp) >>>>>>>`;
test("候选被解析出来,且不混进 hint", () => {
const s = parseSentinels(withOpts, "-", "-");
expect(s).toHaveLength(2);
expect(s[0].hint).toBe("具体设备型号与系统版本");
expect(s[0].options.map((o) => o.label)).toEqual(["iPhone 15 Pro · iOS 17.5", "Pixel 8 · Android 14"]);
expect(s[0].options[0].source).toBe("设备池默认机");
expect(s[0].options[0].fill).toBe("设备:iPhone 15 Pro / iOS 17.5");
expect(s[1].hint).toBe("受哪个实验位控制");
expect(s[1].options[0].source).toBe("本地新建(未找到可复用的既有实验位)");
});
test("fill 里的竖线不会被当成分隔符", () => {
// 只有前两个分隔符是结构性的,成品文本里出现 "|" 属于正常。
const s = parseSentinels(`<<<<<<< NEEDS_INPUT: h @OPTION L | src | a | b | c >>>>>>>`, "-", "-");
expect(s[0].options[0].fill).toBe("a | b | c");
});
test("缺出处的候选被丢弃,而不是半渲染", () => {
// 没有出处的候选正是绝对不能出现在按钮上的东西 —— 宁可当它不存在。
const s = parseSentinels(
`<<<<<<< NEEDS_INPUT: h @OPTION 只有标签 @OPTION 标签 | | 有 fill 没出处 >>>>>>>`, "-", "-");
expect(s[0].options).toHaveLength(0);
expect(s[0].hint).toBe("h");
});
test("没有候选时 options 为空数组(存量计划走这条路)", () => {
const s = parseSentinels(`<<<<<<< NEEDS_INPUT: 就一句提示 >>>>>>>`, "-", "-");
expect(s[0].options).toEqual([]);
expect(s[0].hint).toBe("就一句提示");
});
test("选中候选后整个哨兵(连同候选)被替换掉", () => {
const s = parseSentinels(withOpts, "-", "-");
const out = applyAnswers(withOpts, { [s[0].key]: { mode: "fill", text: s[0].options[0].fill } });
expect(out).toContain("- 设备: 设备:iPhone 15 Pro / iOS 17.5");
expect(out).not.toContain("@OPTION iPhone");
expect(out).not.toContain("@OPTION Pixel");
// 另一个哨兵原样留着
expect(out).toContain("@OPTION studio_effects_panel_discover");
});
});
describe("normalizeSentinels", () => {
// 行首的 `>>>>>>>` 会被 markdown 解析成七层引用块,哨兵在渲染文本里就永远闭合
// 不了 —— 卡片配不上、退化成不可点的高亮、候选全部消失,而且屏幕上没有任何
// 迹象。模型偶尔会换行,所以加载计划时先把它拍回一行。
test("把跨行的哨兵拍回一行", () => {
const bad = `- 设备: <<<<<<< NEEDS_INPUT: 具体设备型号
@OPTION iPhone 15 Pro | 设备池默认机 | 设备:iPhone 15 Pro / iOS 17.5
>>>>>>>`;
const fixed = normalizeSentinels(bad);
expect(fixed.split("\n")).toHaveLength(1);
expect(parseSentinels(fixed, "-", "-")[0].options).toHaveLength(1);
});
test("哨兵之外的换行不动", () => {
const t = `## 标题\n- 一\n- 二`;
expect(normalizeSentinels(t)).toBe(t);
});
});
describe("applyAnswers", () => {
const answered = (): Record<string, Answer> => {
const s = sentinels();
return {
[s[0].key]: { mode: "fill", text: "iPhone 15 Pro / iOS 17.5" },
[s[2].key]: { mode: "agent", text: "去查主拍页是怎么做的" },
[s[4].key]: { mode: "fill", text: "仅拍摄页滤镜档位" },
};
};
test("fill 就地替换,agent 的哨兵原样留着", () => {
// agent 那条要留下来:下一轮 regen 的 comment 就是锚在这段原文上的,
// 提前抹掉的话 Agent 就不知道这条要求指的是哪儿。
const out = applyAnswers(PLAN, answered());
expect(out).toContain("设备 iPhone 15 Pro / iOS 17.5");
expect(out).toContain(NI("切后台的具体操作"));
expect(out).toContain(NI("从首页到拍摄页的入口路径"));
});
test("ignore 拆掉哨兵,不写回任何文字,也不留给 Agent", () => {
const s = sentinels();
const out = applyAnswers(PLAN, { [s[1].key]: { mode: "ignore", text: "" } });
expect(out).not.toContain(NI("从首页到拍摄页的入口路径"));
expect(out).toContain("UI 入口指引:");
expect(out).toContain(NI("具体设备型号与系统版本"));
});
test("答重复哨兵时只命中用户答的那一处", () => {
const out = applyAnswers(PLAN, answered());
expect(out).toContain("- 仅拍摄页滤镜档位");
expect(out).not.toContain("设备 仅拍摄页滤镜档位");
});
test("计划里的图片引用不受影响", () => {
expect(applyAnswers(PLAN, answered()))
.toContain("images/plan-11111111-2222-3333-4444-555555555555.png");
});
test("没有答案时原样返回", () => {
expect(applyAnswers(PLAN, {})).toBe(PLAN);
});
});
/**
* 渲染层。跑真实的 react-markdown 管线,而不是复刻一遍插件逻辑 —— 这里要验的正是
* 「源文本」与「渲染后的文本」之间那道缝。
*/
async function renderCards(plan: string, comments: Comment[] = []) {
const [{ renderToStaticMarkup }, React, { default: ReactMarkdown }, { default: remarkGfm }] =
await Promise.all([
import("react-dom/server"),
import("react"),
import("react-markdown"),
import("remark-gfm"),
]);
const s = parseSentinels(plan, "(未分节)", "(未注明)");
const html = renderToStaticMarkup(
React.createElement(ReactMarkdown, {
remarkPlugins: [remarkGfm],
rehypePlugins: [rehypePlanMarks(comments, s)],
components: {
// 与 PlanEditor 的 mark 覆写走同一条分支:head 出卡片,其余切片丢掉。
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mark: ({ className, children }: any) => {
const cls = Array.isArray(className) ? className.join(" ") : String(className || "");
const m = cls.match(/snt-(\d+)/);
if (m) {
if (!cls.includes("snt-head")) return null;
return React.createElement("span", { "data-idx": m[1] });
}
return React.createElement("mark", { className: cls }, children);
},
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any, plan),
);
return { html, sentinels: s, idx: [...html.matchAll(/data-idx="(\d+)"/g)].map((x) => Number(x[1])) };
}
describe("rehypePlanMarks", () => {
test("每个哨兵出且只出一张卡片,索引与源顺序一致", async () => {
const { idx } = await renderCards(PLAN);
// 代码块里那条渲染扫描看不到,所以是 5 张而不是 6 张。
expect(idx).toEqual([0, 1, 2, 3, 4]);
});
test("提示里带反引号的哨兵照样出卡片", async () => {
// 这是生产上真实踩到的:评估器很爱在提示里引代码符号,markdown 渲染会把反引号
// 吃掉,源文本里却还在。当初按原文逐字配对,31 份含哨兵的线上计划里有 7 份
// 因此丢卡 —— 退化成不可点的高亮,而用户看不出区别。
const { idx } = await renderCards(PLAN);
expect(idx).toContain(3);
});
test("被 ** 包住的哨兵不会因为跨节点而漏掉", async () => {
const { html } = await renderCards(PLAN);
expect(html).toMatch(/<strong[^>]*><span data-idx="2"><\/span><\/strong>/);
});
test("哨兵原文不会漏到渲染结果里(代码块除外)", async () => {
const { html } = await renderCards(PLAN);
// 代码块是明确的降级路径:扫描跳过 <pre>,那里保留旧的纯文本高亮。
expect(html.replace(/<pre[\s\S]*?<\/pre>/g, "")).not.toContain("NEEDS_INPUT");
expect(html).toContain("这条在代码块里");
});
test("配不上的哨兵不会被错配到相邻那条身上", async () => {
// 代码块里那条(源索引 5)永远进不了渲染文本,前向指针不能因此把后面的卡片
// 整体错位 —— 最后一张卡必须还是 4。
const { idx, sentinels: s } = await renderCards(PLAN);
expect(s).toHaveLength(6);
expect(idx[idx.length - 1]).toBe(4);
});
test("带候选的哨兵仍然只出一张卡", async () => {
// 候选让哨兵变长但仍是一行。真正的陷阱是换行:行首的 `>>>>>>>` 会被 markdown
// 吃成引用块,哨兵在渲染文本里永远闭合不了,卡片直接消失且无任何迹象。
// normalizeSentinels 负责在加载时消除这种情况,这里验证归一化之后确实能配上。
const plan = normalizeSentinels(`## 复现条件
- 设备: <<<<<<< NEEDS_INPUT: 具体设备型号
@OPTION iPhone 15 Pro | 设备池默认机 | 设备:iPhone 15 Pro / iOS 17.5
@OPTION Pixel 8 | 工单截图 | 设备:Pixel 8 / Android 14
>>>>>>>
- 其他: 无`);
const { idx, html, sentinels: s } = await renderCards(plan);
expect(s).toHaveLength(1);
expect(s[0].options).toHaveLength(2);
expect(idx).toEqual([0]);
// 候选行属于哨兵的一部分,必须随卡片一起被替换掉,不能漏到正文里。
expect(html).not.toContain("@OPTION");
expect(html).not.toContain("NEEDS_INPUT");
});
test("哨兵提示里的反引号不会留下空 code 盒子", async () => {
// Evaluators cite symbols with backticks. Markdown turns each into <code>,
// and the card only replaces the head slice — leftover empty <code> tags
// inherit .fix-report-doc code chrome (dark fill + border + radius) and
// show up as a row of blank boxes under the input.
const plan = `- 入口: ${NI("看 `FooAssem` 的 `bar()` 以及 `BazExp` `QuxKey` `Zzz`")}`;
const { html, idx } = await renderCards(plan);
expect(idx).toEqual([0]);
expect(html).not.toMatch(/<code[^>]*>\s*<\/code>/);
expect(html).not.toContain("FooAssem");
expect(html).not.toContain("NEEDS_INPUT");
});
test("批注下划线与卡片共存", async () => {
const { html } = await renderCards(PLAN, [
{ id: 7, start: 0, end: 0, quote: "强度回落到默认值 50", comment: "要写成机制级命题" },
]);
expect(html).toContain("aid-7");
expect(html).toContain("data-idx=");
});
});
describe("nextSentinelIndex", () => {
// 走查按钮是导航,不是任务队列:第二次点击必须移动,哪怕当前卡片还是空的。
// 之前按「第一个未处理项」实现,连点会一直停在同一张卡上。
test("从未点过时落在第一项", () => {
expect(nextSentinelIndex(-1, 3)).toBe(0);
});
test("逐个前进", () => {
expect(nextSentinelIndex(0, 3)).toBe(1);
expect(nextSentinelIndex(1, 3)).toBe(2);
});
test("最后一个绕回第一个", () => {
expect(nextSentinelIndex(2, 3)).toBe(0);
});
test("只有一项时停在原地而不是报错", () => {
expect(nextSentinelIndex(0, 1)).toBe(0);
});
test("没有哨兵时返回 -1", () => {
expect(nextSentinelIndex(-1, 0)).toBe(-1);
});
test("光标越界(计划被编辑短了)时从头开始", () => {
expect(nextSentinelIndex(9, 3)).toBe(0);
});
});
+8
View File
@@ -0,0 +1,8 @@
import { expect, test } from "bun:test";
import { PLATFORM_LABELS } from "../src/lib/platform";
test("platform names are presentation-only; keys keep the wire format", () => {
expect(PLATFORM_LABELS.ios).toBe("iOS");
expect(PLATFORM_LABELS.android).toBe("Android");
expect(Object.keys(PLATFORM_LABELS).sort()).toEqual(["android", "ios"]);
});
+118
View File
@@ -0,0 +1,118 @@
import { test, expect, describe } from "bun:test";
import { layoutPromptGraph, edgePath, LAYOUT } from "../src/lib/promptGraphLayout";
import { PROMPT_NODES, PROMPT_SLOTS, PROMPT_TRACKS } from "@bbbug/shared/prompt_registry";
import type { PromptGraphNode } from "../src/lib/api";
/**
* 图的布局出错不会抛异常,只会把两个节点叠在一起、或者把某个节点画到画布外 ——
* 图还是图,只是读不出结构。这里钉住的就是那几件「看不出来但是错了」的事。
*/
const nodes = PROMPT_NODES.map((n) => ({
...n, dependents: [], library: {
versionCount: 0, activeVersionId: null, activeVersionName: null,
lastVersionAt: null, usingBuiltinDefault: true,
},
})) as unknown as PromptGraphNode[];
const slots = PROMPT_SLOTS.map((s) => ({ ...s }));
const tracks = PROMPT_TRACKS.map((t) => ({ ...t }));
describe("提示词图谱布局", () => {
test("每个节点都被摆放,且只摆一次", () => {
const l = layoutPromptGraph(nodes, slots, tracks);
expect(l.nodes.length).toBe(nodes.length);
expect(new Set(l.nodes.map((n) => n.id)).size).toBe(nodes.length);
});
test("没有两个节点重叠", () => {
// 叠在一起的两个节点看起来就是「一个节点」,整张图静默地少了一项。
const l = layoutPromptGraph(nodes, slots, tracks);
for (let i = 0; i < l.nodes.length; i++) {
for (let j = i + 1; j < l.nodes.length; j++) {
const a = l.nodes[i], b = l.nodes[j];
const overlap = a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
expect(overlap, `${a.id} 与 ${b.id} 重叠`).toBe(false);
}
}
});
test("所有节点都落在画布内", () => {
const l = layoutPromptGraph(nodes, slots, tracks);
for (const n of l.nodes) {
expect(n.x).toBeGreaterThanOrEqual(0);
expect(n.y).toBeGreaterThanOrEqual(l.bodyTop);
expect(n.x + n.w).toBeLessThanOrEqual(l.width);
expect(n.y + n.h).toBeLessThanOrEqual(l.height);
}
});
test("节点的横向位置由它的 slot 决定", () => {
const l = layoutPromptGraph(nodes, slots, tracks);
const byId = new Map(l.nodes.map((n) => [n.id, n]));
const colOf = (id: string) => {
const p = byId.get(id)!;
return l.columns.findIndex((c) => p.x >= c.x && p.x < c.x + c.w);
};
// 评估在执行左边,执行在报告左边 —— 这条读序是整张图的意义所在。
expect(colOf("bug.eval")).toBeLessThan(colOf("bug.run"));
expect(colOf("bug.run")).toBeLessThan(colOf("report.readable"));
expect(colOf("review.asking")).toBeLessThan(colOf("report.readable"));
});
test("片段带在所有类型带的下方", () => {
const l = layoutPromptGraph(nodes, slots, tracks);
const frag = l.bands.find((b) => b.kind === "fragment")!;
for (const b of l.bands.filter((x) => x.kind === "track")) {
expect(frag.y).toBeGreaterThanOrEqual(b.y + b.h);
}
});
test("空的类型带不占位", () => {
// 一条标着 Security 却什么都没有的空行,读起来像图坏了。
const onlyBug = nodes.filter((n) => n.track === "bug");
const l = layoutPromptGraph(onlyBug, slots, tracks);
expect(l.bands.map((b) => b.key)).toEqual(["bug", "fragments"]);
});
test("同一格里的多个节点纵向堆叠,间距一致", () => {
const l = layoutPromptGraph(nodes, slots, tracks);
const byId = new Map(l.nodes.map((n) => [n.id, n]));
const a = byId.get("feature.run.first")!;
const b = byId.get("feature.run.second")!;
expect(a.x).toBe(b.x);
expect(Math.abs(b.y - a.y)).toBe(LAYOUT.nodeH + LAYOUT.vGap);
});
test("没有节点时也给出可画的画布,而不是 NaN", () => {
const l = layoutPromptGraph([], slots, tracks);
expect(l.bands).toEqual([]);
expect(Number.isFinite(l.width)).toBe(true);
expect(Number.isFinite(l.height)).toBe(true);
});
});
describe("连线路径", () => {
const box = (x: number, y: number) => ({ id: "x", x, y, w: 170, h: 54 });
test("路径永远是合法的 SVG path,不含 NaN", () => {
const pairs = [[box(0, 0), box(0, 300)], [box(400, 0), box(0, 300)], [box(0, 100), box(400, 100)]];
for (const [a, b] of pairs) {
const d = edgePath(a, b);
expect(d).toMatch(/^M[\d.,-]+ C[\d.,\s-]+$/);
expect(d).not.toContain("NaN");
}
});
test("上下关系的连线从下边缘出发、到上边缘结束", () => {
const a = box(0, 0), b = box(0, 300);
// 从节点中间穿出去的线会盖住标题;必须走边缘。
expect(edgePath(a, b).startsWith(`M${a.x + a.w / 2},${a.y + a.h}`)).toBe(true);
expect(edgePath(a, b).endsWith(`${b.x + b.w / 2},${b.y}`)).toBe(true);
});
test("同一带内的连线走侧边,不穿过节点自身", () => {
const a = box(0, 100), b = box(400, 100);
const d = edgePath(a, b);
expect(d.startsWith(`M${a.x + a.w},`)).toBe(true);
});
});
+36
View File
@@ -0,0 +1,36 @@
import { test, expect, describe } from "bun:test";
import { qaPolicyNoteText } from "../src/components/QaPolicyNote";
import { DEFAULT_REVIEW_POLICY, QA_FIRST_ACTOR, isQaReopenNote, QA_REOPEN_NOTE_HEAD, type TaskReviewInfo } from "@bbbug/shared/review_policy";
import type { Task } from "../src/types";
const qa = (over: Partial<TaskReviewInfo> = {}): TaskReviewInfo => ({ policy: { id: "qa_first", maxChangedUnits: 5 }, approvedBy: null, unreproToQa: false, route: null, ...over });
const task = (over: Partial<Task>) => ({ status: "manual_review", meegoState: "OPEN", ...over } as Task);
describe("drawer note under the QA-first policy", () => {
test("default policy never shows anything", () => {
const info: TaskReviewInfo = { policy: DEFAULT_REVIEW_POLICY, approvedBy: null, unreproToQa: false, route: null };
for (const t of [task({}), task({ status: "fix_succeeded", meegoState: "REOPENED" }), task({ status: "unreproducible", meegoState: "RESOLVED" })]) {
expect(qaPolicyNoteText(t, info, true)).toBeNull();
}
expect(qaPolicyNoteText(task({}), null, true)).toBeNull();
});
test("review that missed routing says why RD still has it", () => {
const s = qaPolicyNoteText(task({}), qa({ route: { toQa: false, reason: "too_large", units: 8 } }), true)!;
expect(s).toContain("改动 8 处,上限 5");
});
test("a platform hand-off says no RD review; an RD approval says nothing", () => {
expect(qaPolicyNoteText(task({ status: "fix_succeeded", meegoState: "RESOLVED" }), qa({ approvedBy: QA_FIRST_ACTOR }), true)).toContain("未经 RD 复核");
expect(qaPolicyNoteText(task({ status: "fix_succeeded", meegoState: "RESOLVED" }), qa({ approvedBy: "rd.li@bytedance.com" }), true)).toBeNull();
expect(qaPolicyNoteText(task({ status: "fix_succeeded", meegoState: "CLOSED" }), qa({ approvedBy: QA_FIRST_ACTOR }), true)).toBeNull();
});
test("QA reopen waits for the reason; an unrepro reopen only counts after a hand-off", () => {
expect(qaPolicyNoteText(task({ status: "fix_succeeded", meegoState: "REOPENED" }), qa(), true)).toContain("自动按它重修");
expect(qaPolicyNoteText(task({ status: "unreproducible", meegoState: "REOPENED" }), qa({ unreproToQa: true }), true)).toContain("自动按它重修");
expect(qaPolicyNoteText(task({ status: "unreproducible", meegoState: "REOPENED" }), qa(), true)).toBeNull();
expect(qaPolicyNoteText(task({ status: "unreproducible", meegoState: "RESOLVED" }), qa({ unreproToQa: true }), true)).toContain("交 QA 判断");
});
test("QA notes are recognised by their header", () => {
expect(isQaReopenNote(`${QA_REOPEN_NOTE_HEAD}\n还是能复现`)).toBe(true);
expect(isQaReopenNote("颜色是不是还是不对?")).toBe(false);
});
});
+38
View File
@@ -0,0 +1,38 @@
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import RelayDialog from "../src/components/RelayDialog";
import EddyExportPanel from "../src/components/EddyExportPanel";
import type { BoardItem, Feature } from "../src/types";
test("Android relay keeps its Markdown download and never renders Eddy", () => {
const item = { id: "fixture", kind: "feature", platform: "android" } as BoardItem & { kind: "feature" };
const html = renderToStaticMarkup(<RelayDialog item={item} onClose={() => {}} />);
expect(html).toContain("Claude Code / Cursor");
expect(html).not.toContain("Eddy");
expect(renderToStaticMarkup(<EddyExportPanel feature={item as Feature} />)).toBe("");
});
test("iOS feature relay offers both Markdown and Eddy", () => {
const item = { id: "fixture", kind: "feature", platform: "ios", status: "manual_review", branchName: "feature/example", mrUrl: "https://mr.invalid/1", repoKey: "tiktok-ios" } as BoardItem & { kind: "feature" };
const html = renderToStaticMarkup(<RelayDialog item={item} onClose={() => {}} />);
expect(html).toContain("Claude Code / Cursor");
expect(html).toContain("Eddy");
});
test("the Eddy panel says which satellite runs the export and why it is still queued", async () => {
const { exportNodeNotes } = await import("../src/components/EddyExportPanel");
const job = { id: "e", featureId: "f", commit: "a".repeat(40), branch: "feature/x", phase: "queued", createdAt: 0, updatedAt: 0,
expiresAt: null, error: null, result: null, nodeId: "fei-ios-02.shiro0.icu" } as const;
const node = (patch: object) => ({ id: "fei-ios-02.shiro0.icu", platform: "ios", status: "online", live: true, lastSeenAt: 0,
evalInFlight: 0, evalCapacity: 3, fixInFlight: 0, fixCapacity: 1, baseUrl: "", createdAt: 0, ...patch }) as any;
const home = { executorNodeId: "fei-ios-02.shiro0.icu" };
expect(exportNodeNotes(job, home, [node({})], true)).toEqual(["等待 fei-ios-02 领取,通常几秒内开始。"]);
expect(exportNodeNotes(job, home, [node({ fixInFlight: 1 })], true)[0]).toContain("正在执行其他工作");
expect(exportNodeNotes(job, home, [node({ live: false })], true)[0]).toContain("已离线");
expect(exportNodeNotes(job, home, [], true)).toEqual([]); // fleet not loaded yet: no guess
const moved = exportNodeNotes(job, { executorNodeId: "fei-ios-01.shiro0.icu" }, [node({ fixInFlight: 1 })], true);
expect(moved[0]).toBe("执行卫星机 fei-ios-01 离线,已改派到 fei-ios-02,所以接力文档里没有修复报告。");
expect(moved).toHaveLength(2);
expect(exportNodeNotes({ ...job, phase: "building" }, home, [node({ fixInFlight: 1 })], true)).toEqual([]);
expect(exportNodeNotes({ ...job, phase: "failed" }, { executorNodeId: "other" }, [], true)).toEqual([]);
expect(exportNodeNotes(job, home, [node({ fixInFlight: 1 })], false)[0]).toContain("is busy");
});
+67
View File
@@ -0,0 +1,67 @@
import { test, expect, describe } from "bun:test";
import { reportFreshness } from "@bbbug/shared/types";
/**
* 这个判定挡的是一类**不报错**的误读:报告的 live 列只前进不清空(一次失败的重生成
* 不该抹掉上一版好报告),所以新一批开工到新报告生成完之间,页面上挂着的是上一批
* 那份,绿标结论一应俱全。生产上出现过:一条 feature 16:51 开始重修,17:11 面板上
* 仍是 15:50 那份,没有一处提示。
*
* 判错的代价不对称,所以两个方向都要钉住:
* - 漏报(该说旧却说不旧)→ 有人拿上一批的结论下判断;
* - 误报(该说新却说旧)→ 每份报告顶上挂一条狼来了,横幅很快就没人看。
*/
describe("reportFreshness", () => {
test("正在执行这一批 —— 屏幕上的一切都是上一批的", () => {
for (const status of ["fixing", "implementing", "security_running"]) {
const f = reportFreshness({ status, attempts: 10, readableReportRound: 9 });
expect(f.stale).toBe(true);
expect(f.reason).toBe("running");
expect(f.reportRound).toBe(9);
expect(f.currentRound).toBe(10);
}
});
test("执行中即便报告号称是这一批的,也仍然算旧 —— 本批还没收尾", () => {
// 人在执行途中手动重生成过报告:批次号会等于当前批,但那份正文讲的仍然
// 不可能是这一批的结论(ImplReport.md 要等 agent 收尾才落盘)。
const f = reportFreshness({ status: "implementing", attempts: 10, readableReportRound: 10 });
expect(f.stale).toBe(true);
expect(f.reason).toBe("running");
});
test("被打回、重新排队 —— 结论已被推翻,新一批还没开始", () => {
for (const status of ["awaiting_fix", "awaiting_implementation", "awaiting_security", "pending_confirmation"]) {
const f = reportFreshness({ status, attempts: 3, readableReportRound: 3 });
expect(f.stale).toBe(true);
expect(f.reason).toBe("queued");
}
});
test("一批都没跑过的排队不是「上一批的报告」——那是首次排队", () => {
const f = reportFreshness({ status: "awaiting_implementation", attempts: 0, readableReportRound: null });
expect(f.stale).toBe(false);
});
test("这一批已收尾、新报告还没生成完 —— 只有正文旧", () => {
const f = reportFreshness({ status: "manual_review", attempts: 10, readableReportRound: 9 });
expect(f.stale).toBe(true);
expect(f.reason).toBe("pending");
});
test("终态且报告就是这一批的 —— 不提示", () => {
for (const status of ["manual_review", "completed", "fix_succeeded", "implementation_failed"]) {
expect(reportFreshness({ status, attempts: 10, readableReportRound: 10 }).stale).toBe(false);
}
});
test("存量报告(批次未知)在终态不误报,在执行中照样提示", () => {
// 猜一个批次号写进去就是制造假事实,所以终态这一档对存量行沉默……
expect(reportFreshness({ status: "manual_review", attempts: 7, readableReportRound: null }).stale).toBe(false);
// ……但「正在跑」跟批次号无关,存量行同样该提示。
const running = reportFreshness({ status: "implementing", attempts: 7, readableReportRound: null });
expect(running.stale).toBe(true);
expect(running.reportRound).toBeNull();
expect(running.currentRound).toBe(7);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { test, expect, describe } from "bun:test";
import { fetchEvidenceList, fetchReportSource } from "../src/lib/reportSource";
/**
* 一次抽屉打开 = 每种资源一个请求:内联报告和「全屏」FixReportPanel(以及证据弹窗)
* 共用 lib/reportSource 的模块级缓存。钉住三条:在途合并、成功结果复用、失败不缓存。
*/
describe("fetchReportSource", () => {
test("同一条目并发 + 随后再取,只打一次网络", async () => {
const orig = globalThis.fetch;
let calls = 0;
globalThis.fetch = (async () => { calls++; return new Response("# report", { status: 200 }); }) as unknown as typeof fetch;
try {
const [a, b] = await Promise.all([fetchReportSource("bug", "rs-1"), fetchReportSource("bug", "rs-1")]);
const c = await fetchReportSource("bug", "rs-1");
expect(calls).toBe(1);
expect(a.text).toBe("# report");
expect(b.text).toBe("# report");
expect(c.text).toBe("# report");
// 不同类的同一个 id 是另一份报告(五类路由不共享)。
await fetchReportSource("feature", "rs-1");
expect(calls).toBe(2);
} finally { globalThis.fetch = orig; }
});
test("404 不缓存:报告刚写出来时下一次就能取到", async () => {
const orig = globalThis.fetch;
let calls = 0;
globalThis.fetch = (async () => {
calls++;
return calls === 1 ? new Response("nope", { status: 404 }) : new Response("# now", { status: 200 });
}) as unknown as typeof fetch;
try {
const first = await fetchReportSource("bug", "rs-404");
expect(first.status).toBe(404);
expect(first.text).toBeNull();
const second = await fetchReportSource("bug", "rs-404");
expect(second.text).toBe("# now");
expect(calls).toBe(2);
} finally { globalThis.fetch = orig; }
});
});
describe("fetchEvidenceList", () => {
test("在途合并 + 成功复用;失败不缓存", async () => {
let calls = 0;
const list = async () => { calls++; return { files: [{ name: "a.png", size: 1, mtime: 1, isImage: true }] }; };
const [x, y] = await Promise.all([fetchEvidenceList("bug", "ev-1", list), fetchEvidenceList("bug", "ev-1", list)]);
await fetchEvidenceList("bug", "ev-1", list);
expect(calls).toBe(1);
expect(x).toEqual(y);
let failing = 0;
const flaky = async () => { failing++; if (failing === 1) throw new Error("502"); return { files: [] }; };
await expect(fetchEvidenceList("bug", "ev-2", flaky)).rejects.toThrow("502");
expect(await fetchEvidenceList("bug", "ev-2", flaky)).toEqual([]);
expect(failing).toBe(2);
});
});
+109
View File
@@ -0,0 +1,109 @@
import { test, expect, describe } from "bun:test";
import { buildRevisionChain, mergeReviewNotes, hasRevisionChain } from "../src/lib/reviewChain";
import type { ReportRoundEntry, ReportRoundList } from "../src/lib/api";
import type { ReviewNote } from "../src/types";
const note = (round: number, text: string, over: Partial<ReviewNote> = {}): ReviewNote => ({
at: 1_700_000_000_000 + round * 1000, source: "human", round, text, ...over,
});
const entry = (round: number, over: Partial<ReportRoundEntry> = {}): ReportRoundEntry => ({
round,
hasMarkdown: true, markdownAt: 1_700_000_000_000 + round * 100, markdownChars: 500,
hasReadable: true, readableAt: 1_700_000_000_000 + round * 200, readablePromptName: "baseline",
reviewNotes: [], isCurrent: false,
...over,
});
/** 面板真实返回的形状:最新那批在最前面。 */
const list = (currentRound: number, rounds: ReportRoundEntry[]): ReportRoundList => ({
currentRound, rounds: [...rounds].sort((a, b) => b.round - a.round),
});
describe("mergeReviewNotes", () => {
test("folds an mr_review block into the reviewer's own note that follows it", () => {
const merged = mergeReviewNotes([
note(2, "generated block", { source: "mr_review", mrComments: [{ id: "c1", threadId: "t1", path: null, line: null, author: "a", excerpt: "e" }] }),
note(2, "解一下冲突"),
]);
expect(merged).toHaveLength(1);
expect(merged[0].text).toBe("解一下冲突");
expect(merged[0].attached).toHaveLength(1);
});
test("an mr_review with nothing after it still shows up, chips only", () => {
const merged = mergeReviewNotes([
note(2, "block", { source: "mr_review", mrComments: [{ id: "c1", threadId: "t1", path: null, line: null, author: "a", excerpt: "e" }] }),
]);
expect(merged).toHaveLength(1);
expect(merged[0].text).toBe("");
expect(merged[0].attached).toHaveLength(1);
});
});
describe("buildRevisionChain", () => {
// 样本取自真实任务 c55ecb4c:5 批报告,4 次人工打回。
const five = list(5, [
entry(1, { reviewNotes: [note(1, "加 AB 开关")] }),
entry(2, { reviewNotes: [note(2, "mr 有冲突")] }),
entry(3, { reviewNotes: [note(3, "又冲突了")] }),
entry(4, { reviewNotes: [note(4, "AB 加错位置了")] }),
entry(5, { isCurrent: true }),
]);
test("每条意见都指向它催生的那一批,而不是它评的那一批", () => {
const c = buildRevisionChain(five);
expect(c.edges.map((e) => [e.from, e.to])).toEqual([[1, 2], [2, 3], [3, 4], [4, 5]]);
// 「第 5 批因何而来」= 第 4 批之后那条意见。这是横幅唯一的取数口径。
expect(c.byTo.get(5)?.note.text).toBe("AB 加错位置了");
expect(c.byTo.has(1)).toBe(false);
});
test("批次按升序排,即便接口给的是倒序", () => {
expect(buildRevisionChain(five).nodes.map((n) => n.round)).toEqual([1, 2, 3, 4, 5]);
});
test("已经开工、还没落归档的那一批也在链上,标 pending", () => {
const running = list(6, [
entry(4, { reviewNotes: [note(4, "AB 加错位置了")] }),
entry(5, { reviewNotes: [note(5, "深色模式下偏亮")], isCurrent: true }),
]);
const c = buildRevisionChain(running);
const last = c.nodes[c.nodes.length - 1];
expect(last).toMatchObject({ round: 6, pending: true });
// 那条边是真的存在的,只是下游报告还没生成 —— 不能因此说它没催生任何一批。
expect(c.byFrom.get(5)).toMatchObject({ to: 6, pending: true });
});
test("刚打回、还没派发时不编「催生了第几批」", () => {
const c = buildRevisionChain(list(3, [
entry(2),
entry(3, { reviewNotes: [note(3, "再改改")], isCurrent: true }),
]));
expect(c.byFrom.get(3)).toMatchObject({ to: null, pending: false });
});
test("同一间隔里多条意见:最后一条当主意见,其余进 extra", () => {
const c = buildRevisionChain(list(2, [
entry(1, { reviewNotes: [note(1, "critic 打回", { source: "critic" }), note(1, "人也补了一条")] }),
entry(2, { isCurrent: true }),
]));
const e = c.byFrom.get(1)!;
expect(e.note.text).toBe("人也补了一条");
expect(e.extra.map((n) => n.source)).toEqual(["critic"]);
});
test("跳批(中间那批没归档)时边接到下一个真的存在的批次", () => {
const c = buildRevisionChain(list(4, [
entry(1, { reviewNotes: [note(1, "改")] }),
entry(4, { isCurrent: true }),
]));
expect(c.byFrom.get(1)).toMatchObject({ to: 4, pending: false });
});
test("只跑过一批、也没人打回时不画链", () => {
expect(hasRevisionChain(list(1, [entry(1, { isCurrent: true })]))).toBe(false);
// 跑过一批但被打回了(第 2 批正在跑):这时链有话要说。
expect(hasRevisionChain(list(2, [entry(1, { reviewNotes: [note(1, "改")], isCurrent: true })]))).toBe(true);
});
});
+11
View File
@@ -0,0 +1,11 @@
import { describe, expect, test } from "bun:test";
import { isBitsDevTaskUrl } from "../src/lib/reviewDraft";
describe("isBitsDevTaskUrl", () => {
test("只把 Bits 开发任务详情识别为开发任务链接", () => {
expect(isBitsDevTaskUrl("https://bits.bytedance.net/devops/39151416834/develop/detail/2709536?devops_space_type=server_fe")).toBe(true);
expect(isBitsDevTaskUrl("https://bits.bytedance.net/devops/39151416834/code/detail/8327494")).toBe(false);
expect(isBitsDevTaskUrl("https://code.byted.org/tiktok/tt_im_monorepo/merge_requests/594")).toBe(false);
expect(isBitsDevTaskUrl(null)).toBe(false);
});
});
@@ -0,0 +1,80 @@
import { test, expect, describe } from "bun:test";
import { readFileSync } from "node:fs";
import path from "node:path";
import { serverScopeNeedsDecision } from "@bbbug/shared/server_prompt";
/**
* 面板的挂载条件 —— 钉住两条互相拉扯的纪律。
*
* 一、**纯客户端需求看不到任何服务端东西。**线上绝大多数是纯客户端的。
* 二、**入口交给人。**端上 endpoint → PSM 的反查实测唯一命中率只有 4%
* (120 条真实 endpoint 随机抽样),所以「评估器查到了 PSM」是少数情况。
* 如果只在 psms 非空时给入口,96% 的情况下人在闸上根本没有地方补这个值。
*
* 两条的交点是**方案里那一行的形态**:写「无」= 纯客户端,什么都不显示;
* 打 NEEDS_INPUT 哨兵 = 评估器明确说定不了,那正是该交给人的时候。
* 所以这里断言的重点从「psms 非空」挪到了 `serverScopeNeedsDecision` 的行为上 ——
* 那才是真正把两条纪律分开的判据。
*/
const REPO = path.resolve(import.meta.dir, "../..");
const drawer = readFileSync(path.join(REPO, "control-web/src/components/TaskDetailDrawer.tsx"), "utf8");
describe("服务端面板的挂载条件", () => {
test("挂载条件仍然以确认闸为前提", () => {
expect(drawer).toContain("isPendingConfirm &&");
expect(drawer).toContain("<ServerScopePanel");
});
test("两档触发:psms 非空,或方案里那一节还没定", () => {
const cond = drawer.slice(drawer.indexOf("{isPendingConfirm &&"), drawer.indexOf("<ServerScopePanel"));
expect(cond).toContain("item.psms?.length");
expect(cond).toContain("serverScopeNeedsDecision");
});
test("没有任何一处无条件渲染它", () => {
const uses = [...drawer.matchAll(/<ServerScopePanel/g)];
expect(uses.length).toBe(1);
});
});
describe("判据本身:什么时候该把入口交给人", () => {
const sec = (body: string) => `## 目标\n做点什么\n\n## 服务端范围\n${body}\n\n## 验证环境\n- 账号: 任意\n`;
test("写「无」→ 不给入口。这是纯客户端需求的出口,必须一个像素都不出现", () => {
const plan = sec('- 涉及 PSM: 无\n- 服务端改动: 无\n- 服务端验证方式: 无');
expect(serverScopeNeedsDecision(plan, "feature")).toBe(false);
expect(serverScopeNeedsDecision(plan, "bug")).toBe(false);
});
test("打哨兵 → 给入口。4% 的命中率下这是常态,不是例外", () => {
const plan = sec('- 涉及 PSM: <<<<<<< NEEDS_INPUT: 需要补充承载该接口的 PSM 名称 >>>>>>>\n- 服务端改动: 待定');
expect(serverScopeNeedsDecision(plan, "feature")).toBe(true);
});
test("整节缺失 → 不给入口。缺失不等于未定,不要替旧方案臆造一个待决状态", () => {
expect(serverScopeNeedsDecision("## 目标\n做点什么\n", "feature")).toBe(false);
expect(serverScopeNeedsDecision("", "feature")).toBe(false);
});
test("哨兵在别的小节里不算 —— 判据只看「服务端范围」这一节", () => {
// 方案里到处都可能有哨兵;把任何一个哨兵都当成「服务端待定」会让面板对着
// 一堆纯客户端需求弹出来,那就等于破了第一条纪律。
const plan = '## 目标\n<<<<<<< NEEDS_INPUT: 缺产品目标 >>>>>>>\n\n## 服务端范围\n- 涉及 PSM: 无\n\n## 验证环境\n- 账号: 任意\n';
expect(serverScopeNeedsDecision(plan, "feature")).toBe(false);
});
});
describe("凭据不回显", () => {
const panel = readFileSync(path.join(REPO, "control-web/src/components/ServerScopePanel.tsx"), "utf8");
test("输入框是 password 且不自动填充", () => {
expect(panel).toContain('type="password"');
expect(panel).toContain('autoComplete="off"');
});
test("只消费 has(有没有),不消费任何密文字段", () => {
// 服务端从不回密文;面板若试图读它,说明契约被破坏了。
expect(panel).not.toMatch(/\.values\b/);
expect(panel).toContain("meServerlineCreds");
});
});
@@ -0,0 +1,46 @@
import { test, expect, describe } from "bun:test";
import { readFileSync } from "node:fs";
import path from "node:path";
/**
* 附加仓(tt_im_monorepo 等)的 MR 和流水线放在哪、主仓无改动时交付 MR 那一行长什么样。
*
* 生产 ce9bf567:只改了 tt_im_monorepo 的单子,抽屉「产物」区挂着一条 Bits 流水线链接,
* 看上去像子 MR 链接、点进去却是测试流水线;复核清单里交付 MR 那一行又是红色「MR 提交失败」,
* 其实主仓本来就没改动。约定改成:
* 一、附加仓的 MR / 开发任务 / 流水线只在复核清单交付 MR 右边的齿轮「MR 操作」里出现;
* 二、改动只在附加仓时,交付 MR 那一行是灰色「主仓无改动」,点开就是「MR 操作」。
*/
const REPO = path.resolve(import.meta.dir, "../..");
const drawer = readFileSync(path.join(REPO, "control-web/src/components/TaskDetailDrawer.tsx"), "utf8");
describe("附加仓的入口只在齿轮里", () => {
test("「产物」区不再列附加仓 MR / 流水线", () => {
const artifacts = drawer.slice(drawer.indexOf('<h4>{t("drawer.artifacts")}</h4>'), drawer.indexOf("{item.logPath && ("));
expect(artifacts).not.toContain("codeSidecars");
expect(artifacts).not.toContain("pipelines");
});
test("齿轮「MR 操作」里有附加仓那一节和它的流水线", () => {
expect(drawer).toContain('<MrActionSection title={t("drawer.mrActionsSidecarTitle")}>');
expect(drawer).toContain("{sub.peers}");
});
});
describe("主仓无改动", () => {
test("判据走 shared 的 isSidecarOnlyDelivery,且只在还没有交付 MR 时成立", () => {
expect(drawer).toContain("!item.mrUrl && isSidecarOnlyDelivery(item.repoKey, codeSidecars.length)");
});
test("交付 MR 那一行:不当失败分类,点开是「MR 操作」", () => {
expect(drawer).toContain("hasUrl || pipelineOnlyDone || noDeliveryChange ? null : classifyMrFailure(step.failureReason)");
const row = drawer.slice(drawer.indexOf("noDeliveryChange ? ("), drawer.indexOf(") : hasUrl ? ("));
expect(row).toContain("setMrActionsOpen(true)");
expect(row).toContain('t("drawer.mrRowNoChange")');
});
test("gitlab 通道的附加仓不要点的人绑 Bits Token", () => {
expect(drawer).toContain('const needsBitsToken = !(variant === "sub" && step.repo.mrChannel === "gitlab");');
expect(drawer).toContain("needsBitsToken && hasBitsToken !== true ? (");
});
});
+68
View File
@@ -0,0 +1,68 @@
import { test, expect, describe } from "bun:test";
import { readFileSync } from "node:fs";
import path from "node:path";
/**
* 「一次提交全部 MR」—— 钉住的是它<b>怎么失败</b>,而不是它长什么样。
*
* 多仓交付里「部分成功」是常态而不是异常:跨团队仓的写权限往往只批下来一部分
* (试点里 9 堵权限墙分属 9 个平台)。所以这个按钮有两条不能松的性质:
*
* 一、**串行**。每次调用都在 Codebase 上真的建 MR,还各自跑一遍权限闸;并发时
* 失败原因会混在一起分不清是哪个仓。更要命的是这轮实测已确认平台侧在并发下
* 会返回非 success 的响应而**不报错** —— 那会让一次平台故障看起来像
* 「这个仓提交失败」。
* 二、**失败不中断**。第一个仓没权限就停下,会把本来能提的那几个也挡住。
*/
const REPO = path.resolve(import.meta.dir, "../..");
const drawer = readFileSync(path.join(REPO, "control-web/src/components/TaskDetailDrawer.tsx"), "utf8");
const body = drawer.slice(drawer.indexOf("const submitAllMrs"), drawer.indexOf("const isPendingConfirm"));
describe("串行提交", () => {
test("用 for 循环挨个 await,而不是 Promise.all", () => {
expect(body).toContain("for (const st of steps)");
expect(body).toContain("await act.submitMr");
});
test("整个函数体里没有任何并发原语", () => {
for (const banned of ["Promise.all", "Promise.allSettled", "Promise.race"]) {
expect(body).not.toContain(banned);
}
});
});
describe("失败不中断,且逐仓归因", () => {
test("catch 在循环体内 —— 一个仓抛错不能带走整轮", () => {
const loopStart = body.indexOf("for (const st of steps)");
const loopEnd = body.indexOf("setMrRetrying(null)");
const loop = body.slice(loopStart, loopEnd);
expect(loop).toContain("try {");
expect(loop).toContain("catch");
});
test("失败逐条记下来并带上是哪个仓", () => {
expect(body).toContain("failed.push(`${st.key}");
});
test("汇总区分「全成 / 部分成 / 全败」三档", () => {
expect(body).toContain("if (!failed.length)");
expect(body).toContain("else if (ok)");
});
test("Bits Token 失效时仍然唤起补 Token 的入口", () => {
// 这是最常见的一类失败;漏掉它会让人对着一串「提交失败」找不到原因。
expect(body).toContain("Bits 个人 Token 已失效");
expect(body).toContain("setBitsTokenOpen(true)");
});
});
describe("按钮的出现条件", () => {
test("只在两个及以上待提时出现", () => {
// 只剩一个时它与那一行自己的按钮完全等价,多一个入口只是噪音。
expect(drawer).toContain("pending.length > 1 &&");
});
test("待提 = 还没有 MR 链接的那些步骤;主仓无改动时交付仓不算", () => {
expect(drawer).toContain(`codeSteps.filter((st) => !st.url && !(st.key === "delivery" && sidecarOnly))`);
});
});
+27
View File
@@ -0,0 +1,27 @@
import { test, expect } from "bun:test";
import { parseLocation, routeToPath } from "../src/lib/router";
test("/home?tag= round-trips", () => {
const r = parseLocation({ pathname: "/home", search: "?tag=social_relation" });
expect(r).toEqual({ view: "home", tag: "social_relation" });
expect(routeToPath(r)).toBe("/home?tag=social_relation");
});
test("bare / and /home stay tag-less", () => {
expect(parseLocation({ pathname: "/", search: "" })).toEqual({ view: "home" });
expect(routeToPath({ view: "home" })).toBe("/home");
});
test("a tag on / normalizes onto /home", () => {
expect(routeToPath(parseLocation({ pathname: "/", search: "?tag=a" }))).toBe("/home?tag=a");
});
test("/batches 默认停在治理项目,?track=audit 才是 UI 走查修复", () => {
expect(parseLocation({ pathname: "/batches", search: "" })).toEqual({ view: "batches" });
const r = parseLocation({ pathname: "/batches", search: "?track=audit" });
expect(r).toEqual({ view: "batches", track: "audit" });
expect(routeToPath(r)).toBe("/batches?track=audit");
// 不认识的值不进标签页;详情页的地址不带 track。
expect(parseLocation({ pathname: "/batches", search: "?track=x" })).toEqual({ view: "batches" });
expect(parseLocation({ pathname: "/batches", search: "?tag=audit-1&track=audit" })).toEqual({ view: "batches", tag: "audit-1" });
});
+51
View File
@@ -0,0 +1,51 @@
import { test, expect, describe } from "bun:test";
import type { BoardItem } from "../src/types";
import { searchTasks, snippetAround, splitHighlights } from "../src/lib/taskSearch";
function bug(over: Record<string, unknown>): BoardItem {
return {
kind: "bug", id: "b1", title: "登录失败闪退", platform: "android",
status: "awaiting_fix", attempts: 0, createdAt: 1,
watchers: ["jiaopengwen@bytedance.com"],
watcherLabels: { "jiaopengwen@bytedance.com": "焦鹏文" },
clusters: ["tt-client"],
branchName: "fix/login-crash",
baseRef: "develop",
description: "",
failureReason: null,
...over,
} as BoardItem;
}
describe("searchTasks", () => {
const items = [
bug({}),
bug({ id: "b2", title: "iOS 推送丢失", watchers: ["alice@bytedance.com"], watcherLabels: { "alice@bytedance.com": "Alice" }, clusters: ["ios-push"], branchName: "fix/push", description: "APNs token 过期" }),
];
test("matches title, watcher, cluster, branch", () => {
expect(searchTasks(items, "闪退").map((h) => h.item.id)).toEqual(["b1"]);
expect(searchTasks(items, "焦鹏文").map((h) => h.item.id)).toEqual(["b1"]);
expect(searchTasks(items, "tt-client").map((h) => h.item.id)).toEqual(["b1"]);
expect(searchTasks(items, "fix/login").map((h) => h.item.id)).toEqual(["b1"]);
});
test("matches details when the list row still has them", () => {
expect(searchTasks(items, "APNs").map((h) => h.item.id)).toEqual(["b2"]);
expect(searchTasks(items, "APNs")[0].field).toBe("detail");
});
test("empty query returns nothing", () => {
expect(searchTasks(items, " ")).toEqual([]);
});
});
describe("snippetAround / splitHighlights", () => {
test("clips around the first hit", () => {
expect(snippetAround("abcdefghijklmnop", "hij", 2)).toBe("…fghijkl…");
});
test("marks every occurrence", () => {
const parts = splitHighlights("aa x aa", "aa");
expect(parts.filter((p) => p.hit).map((p) => p.text)).toEqual(["aa", "aa"]);
});
});
+245
View File
@@ -0,0 +1,245 @@
import { test, expect, describe } from "bun:test";
import { niceScale, isWeekendDay, toggleSeries, peakOfVisible, SERIES_ALL_ON, createdOf, runsOf, landedOf, allTrendKinds, defaultTrendKinds, toggleTrendKind, isAllTrendKinds, type TrendKind } from "../src/components/TrendChart";
import type { DailyTrendPoint } from "../src/lib/api";
import type { BoardItem } from "../src/types";
import { overlayDailyLanded, accumulateTrend, cnDayKey, allTimeSpanDays } from "../src/lib/trendSeries";
/**
* Y 轴刻度。这块出错不会报任何异常,只是把 86 画到一根 "87" 的顶格线上,或者
* 让刻度落在 33.33 这种数上——图还是图,只是读不出数。
*/
describe("niceScale", () => {
test("刻度落在整数上,且上界覆盖峰值", () => {
for (const peak of [1, 3, 7, 12, 46, 77, 86, 130, 512, 2400]) {
const { max, step } = niceScale(peak);
expect(max).toBeGreaterThanOrEqual(peak);
// 上界必须是步长的整数倍,否则最后一根网格线画不到顶。
expect(Math.abs(max / step - Math.round(max / step))).toBeLessThan(1e-9);
// 计数图的步长必须是整数,否则轴上会出现“2.5 个任务”。
expect(Number.isInteger(step)).toBe(true);
// 3~5 格:太少读不出量级,太多网格盖过数据。
const ticks = max / step;
expect(ticks).toBeGreaterThanOrEqual(3);
expect(ticks).toBeLessThanOrEqual(5);
}
});
test("全 0 的一周也给出可画的轴,而不是除零", () => {
const { max, step } = niceScale(0);
expect(max).toBeGreaterThan(0);
expect(step).toBeGreaterThan(0);
});
test("常见峰值给出的是人读得懂的整数刻度", () => {
expect(niceScale(86)).toEqual({ max: 100, step: 25 });
expect(niceScale(46)).toEqual({ max: 60, step: 20 });
expect(niceScale(12)).toEqual({ max: 15, step: 5 });
});
});
describe("toggleSeries / peakOfVisible — 图例开关", () => {
test("关掉一条,不能把最后一条也关掉", () => {
const one = toggleSeries(SERIES_ALL_ON, "runs");
expect(one).toEqual({ created: true, runs: false, landed: true });
const two = toggleSeries(one, "created");
expect(two).toEqual({ created: false, runs: false, landed: true });
expect(toggleSeries(two, "landed")).toEqual(two);
});
test("峰值只看仍显示的系列,关掉高线后 Y 轴收缩", () => {
const created = [1, 2, 3];
const runs = [10, 80, 40];
const landed = [0, 1, 2];
expect(peakOfVisible(created, runs, landed, SERIES_ALL_ON)).toBe(80);
expect(peakOfVisible(created, runs, landed, { created: true, runs: false, landed: true })).toBe(3);
expect(peakOfVisible(created, runs, landed, { created: false, runs: false, landed: true })).toBe(2);
});
});
describe("isWeekendDay — 按 ISO 日历日,不跟本机时区走", () => {
test("周六日为 true,工作日为 false", () => {
// 2026-01-02 周五 … 01-05 周一。用 UTC 构造,避免 CI 在 UTC-7 上把
// `new Date("YYYY-MM-DD").getDay()` 提前一天。
expect(isWeekendDay("2026-01-02")).toBe(false); // Fri
expect(isWeekendDay("2026-01-03")).toBe(true); // Sat
expect(isWeekendDay("2026-01-04")).toBe(true); // Sun
expect(isWeekendDay("2026-01-05")).toBe(false); // Mon
});
test("坏日期不当周末", () => {
expect(isWeekendDay("")).toBe(false);
expect(isWeekendDay("nope")).toBe(false);
});
});
function pt(over: Partial<DailyTrendPoint> & { day: string }): DailyTrendPoint {
return {
created: 0,
createdByKind: { bug: 0, feature: 0, security: 0 },
runs: 0,
runsByKind: { bug: 0, feature: 0, security: 0 },
...over,
};
}
function bugItem(over: Record<string, unknown>): BoardItem {
return {
kind: "bug", id: "b", title: "t", platform: "android",
status: "fix_succeeded", attempts: 0, createdAt: 1,
...over,
} as BoardItem;
}
function featItem(over: Record<string, unknown>): BoardItem {
return {
kind: "feature", id: "f", title: "t", platform: "ios",
status: "completed", attempts: 0, createdAt: 1,
...over,
} as BoardItem;
}
describe("cnDayKey — 与 stats_daily 同一套 UTC+8 日界", () => {
test("北京午夜前一秒还是前一天", () => {
const midnight = Date.UTC(2026, 7, 12, 16, 0, 0); // 2026-08-13 00:00 CST
expect(cnDayKey(midnight)).toBe("2026-08-13");
expect(cnDayKey(midnight - 1)).toBe("2026-08-12");
});
});
describe("allTimeSpanDays — 全期从最早 createdAt 记到今天", () => {
test("Jun 1 … Sep 2 含首尾 94 天", () => {
const now = Date.UTC(2026, 8, 2, 8, 0, 0); // 2026-09-02 16:00 CST
const first = Date.UTC(2026, 5, 1, 4, 0, 0); // 2026-06-01 12:00 CST
expect(allTimeSpanDays([{ createdAt: first }], now)).toBe(94);
});
test("没有时间戳时至少两天,好画线", () => {
expect(allTimeSpanDays([])).toBe(2);
});
});
describe("overlayDailyLanded — 生产 API 还没有 merged 时从看板补", () => {
test("缺字段时按 mrMergedAt / finishedAt 填当天", () => {
// 2026-08-12 20:00 CST = 12:00 UTC
const tue = Date.UTC(2026, 7, 12, 12, 0, 0);
const wed = Date.UTC(2026, 7, 13, 12, 0, 0);
const points = [
pt({ day: "2026-08-12" }),
pt({ day: "2026-08-13" }),
pt({ day: "2026-08-14" }),
];
const items: BoardItem[] = [
bugItem({ id: "m1", mrMergedAt: tue, mrState: "merged", meegoState: "done" }),
bugItem({ id: "m2", mrMergedAt: tue, mrState: "merged", meegoState: "done" }),
bugItem({ id: "m3", mrMergedAt: wed, mrState: "merged", meegoState: "done" }),
featItem({ id: "f1", finishedAt: tue }),
bugItem({
id: "qa1", status: "fix_succeeded", mrState: "opened", meegoState: "resolved", finishedAt: tue,
}),
bugItem({
id: "u1", status: "unreproducible", meegoState: "done", finishedAt: tue,
}),
];
const out = overlayDailyLanded(points, items);
expect(out.map((p) => p.merged)).toEqual([2, 1, 0]);
expect(out[0].completedByKind).toEqual({ feature: 1, security: 0 });
expect(out[1].completedByKind).toEqual({ feature: 0, security: 0 });
expect(out.map((p) => p.finishedByKind?.bug)).toEqual([4, 1, 0]);
expect(out.map((p) => p.finishedByKind?.feature)).toEqual([1, 0, 0]);
});
test("API 已给出数字时不覆盖(含 0)", () => {
const points = [pt({ day: "2026-08-12", merged: 0, completed: 3, completedByKind: { feature: 2, security: 1 } })];
const items: BoardItem[] = [bugItem({ mrMergedAt: Date.UTC(2026, 7, 12, 12, 0, 0) })];
const out = overlayDailyLanded(points, items);
expect(out[0].merged).toBe(0);
expect(out[0].completed).toBe(3);
expect(out[0].completedByKind).toEqual({ feature: 2, security: 1 });
});
});
describe("accumulateTrend — 按日累加,null 批次不断成 0", () => {
test("创建 / 合入累加,周末也留着", () => {
const points = [
pt({ day: "2026-08-14", created: 2, merged: 1 }), // Fri
pt({ day: "2026-08-15", created: 0, merged: 1 }), // Sat
pt({ day: "2026-08-16", created: 3, merged: 0 }), // Sun
];
const out = accumulateTrend(points);
expect(out.map((p) => p.created)).toEqual([2, 2, 5]);
expect(out.map((p) => p.merged)).toEqual([1, 2, 2]);
expect(out.map((p) => p.day)).toEqual(["2026-08-14", "2026-08-15", "2026-08-16"]);
});
test("ledger 之前 runs 保持 null,从第一天有数开始加", () => {
const points = [
pt({ day: "2026-07-21", runs: null, runsByKind: null, created: 1 }),
pt({ day: "2026-07-22", runs: null, runsByKind: null, created: 1 }),
pt({ day: "2026-07-23", runs: 4, runsByKind: { bug: 4, feature: 0, security: 0 }, created: 1 }),
pt({ day: "2026-07-24", runs: 6, runsByKind: { bug: 1, feature: 5, security: 0 }, created: 1 }),
];
const out = accumulateTrend(points);
expect(out.map((p) => p.runs)).toEqual([null, null, 4, 10]);
expect(out[2].runsByKind).toEqual({ bug: 4, feature: 0, security: 0 });
expect(out[3].runsByKind).toEqual({ bug: 5, feature: 5, security: 0 });
expect(out.map((p) => p.created)).toEqual([1, 2, 3, 4]);
});
});
describe("createdOf / runsOf / landedOf — 搜证加进全部,完成数=创建数", () => {
const p = pt({
day: "2026-09-01",
created: 10,
createdByKind: { bug: 4, feature: 3, security: 3 },
runs: 20,
runsByKind: { bug: 8, feature: 7, security: 5 },
merged: 2,
completedByKind: { feature: 1, security: 0 },
finishedByKind: { bug: 2, feature: 1, security: 0 },
});
const ALL = allTrendKinds();
const one = (k: TrendKind) => new Set<TrendKind>([k]);
test("全部:创建、批次含搜证", () => {
expect(createdOf(p, ALL)).toBe(10);
expect(runsOf(p, ALL)).toBe(20);
});
test("单选与多选:按所选类型相加", () => {
expect(createdOf(p, one("bug"))).toBe(4);
expect(createdOf(p, new Set<TrendKind>(["bug", "feature"]))).toBe(7);
expect(runsOf(p, new Set<TrendKind>(["bug", "security"]))).toBe(13);
});
test("完成线:bug/需求用 finished,搜证用当天创建数", () => {
expect(landedOf(p, one("bug"))).toBe(2);
expect(landedOf(p, one("feature"))).toBe(1);
expect(landedOf(p, one("security"))).toBe(3);
expect(landedOf(p, ALL)).toBe(2 + 1 + 3);
expect(landedOf(p, new Set<TrendKind>(["bug", "security"]))).toBe(2 + 3);
});
});
describe("toggleTrendKind — 与看板类型筛选同一套", () => {
test("默认是 Bugfix + Feature,不含搜证", () => {
const d = defaultTrendKinds();
expect(d.has("bug")).toBe(true);
expect(d.has("feature")).toBe(true);
expect(d.has("security")).toBe(false);
expect(isAllTrendKinds(d)).toBe(false);
});
test("从全部点一项就收成只看该项", () => {
const next = toggleTrendKind(allTrendKinds(), "bug");
expect([...next]).toEqual(["bug"]);
});
test("再点另一项是并上,不是互斥", () => {
const next = toggleTrendKind(new Set<TrendKind>(["bug"]), "feature");
expect(next.has("bug")).toBe(true);
expect(next.has("feature")).toBe(true);
expect(next.size).toBe(2);
});
test("去掉最后一项回到全部", () => {
expect(isAllTrendKinds(toggleTrendKind(new Set<TrendKind>(["security"]), "security"))).toBe(true);
});
});
+72
View File
@@ -0,0 +1,72 @@
import { test, expect, describe } from "bun:test";
import { normaliseWatcherKey, parseWatcherList, watcherKind } from "../src/lib/watcherNames";
/**
* 前端这份归一化必须跟服务端 watchers.ts 的规则逐字一致:分组成员是拿去跟任务
* 的 watchers 直接比字符串的,差一个大小写或者少个域名,筛选就永远是空板——
* 而且不报错。粘贴导入还要负责把"人名打错了"和"这只是分隔符"区分开。
*/
describe("normaliseWatcherKey", () => {
test("裸前缀补上公司域名并转小写", () => {
expect(normaliseWatcherKey("Alice")).toBe("alice@bytedance.com");
expect(normaliseWatcherKey(" bob ")).toBe("bob@bytedance.com");
});
test("别的域名被换成公司域名(跟服务端一样只认前缀)", () => {
expect(normaliseWatcherKey("carol@gmail.com")).toBe("carol@bytedance.com");
});
test("飞书 id 原样返回", () => {
expect(normaliseWatcherKey("oc_abc")).toBe("oc_abc");
expect(normaliseWatcherKey("ou_def")).toBe("ou_def");
});
test("空值和非法 local-part 返回 null", () => {
expect(normaliseWatcherKey("")).toBeNull();
expect(normaliseWatcherKey(" ")).toBeNull();
expect(normaliseWatcherKey("-alice")).toBeNull();
expect(normaliseWatcherKey("alice-")).toBeNull();
expect(normaliseWatcherKey("张三")).toBeNull();
});
});
describe("parseWatcherList — 粘贴导入", () => {
test("换行 / 逗号 / 空格 / 中文标点都算分隔符", () => {
const r = parseWatcherList("alice\nbob, carol;dave、eve,frank;grace");
expect(r.keys).toEqual(
["alice", "bob", "carol", "dave", "eve", "frank", "grace"].map((n) => `${n}@bytedance.com`),
);
expect(r.added).toBe(7);
});
test("已在组里的人算重复,不重复加入", () => {
const r = parseWatcherList("alice, bob", ["alice@bytedance.com"]);
expect(r.keys).toEqual(["bob@bytedance.com"]);
expect(r.dup).toBe(1);
expect(r.added).toBe(1);
});
test("同一次粘贴里的重复也只算一次", () => {
const r = parseWatcherList("alice ALICE@bytedance.com alice@other.com");
expect(r.keys).toEqual(["alice@bytedance.com"]);
expect(r.dup).toBe(2);
});
test("认不出来的 token 被计数而不是被静默吃掉", () => {
const r = parseWatcherList("alice 张三 -bad-");
expect(r.keys).toEqual(["alice@bytedance.com"]);
expect(r.bad).toBe(2);
});
test("空文本不产生任何计数", () => {
expect(parseWatcherList(" \n ")).toEqual({ keys: [], added: 0, dup: 0, bad: 0 });
});
});
describe("watcherKind", () => {
test("邮箱 / 群 / open_id 三分", () => {
expect(watcherKind("alice@bytedance.com")).toBe("email");
expect(watcherKind("oc_abc")).toBe("chat");
expect(watcherKind("ou_abc")).toBe("user");
});
});