Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 59 additions & 18 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,42 @@ window.__dashAfter = window.__dashAfter || function (form, msg) {
window.dispatchEvent(new CustomEvent("dashrefresh"));
if (!document.querySelector("[data-frag]")) location.reload();
};
window.__dashAuthorPickers = window.__dashAuthorPickers || function () {
var fill = function (list) {
document.querySelectorAll("select[name=author][data-author-picker]").forEach(function (s) {
if (s.dataset.hydrated) return;
var cur = s.value;
var frag = document.createDocumentFragment();
list.forEach(function (i) {
var o = document.createElement("option");
o.value = i.kind + "|" + i.id + "|" + (i.sessionId || "");
o.textContent = i.label + (i.kind === "agent" ? " (agent)" : "");
if (i.id === "drew") o.defaultSelected = true;
frag.appendChild(o);
});
s.replaceChildren(frag);
s.value = cur;
s.dataset.hydrated = "1";
});
};
if (window.__dashIdentities) { fill(window.__dashIdentities); return; }
if (window.__dashIdentitiesPromise) return;
window.__dashIdentitiesPromise = fetch("/api/author-identities")
.then(function (r) { return r.json(); })
.then(function (d) { window.__dashIdentities = (d && d.identities) || []; fill(window.__dashIdentities); })
.catch(function () { window.__dashIdentitiesPromise = null; });
};
if (!window.__dashAuthorPickerHook) {
window.__dashAuthorPickerHook = true;
document.addEventListener("pointerdown", function (ev) {
var t = ev.target;
if (t && t.closest && t.closest("select[name=author][data-author-picker], .actbox, .cbox")) window.__dashAuthorPickers();
});
document.addEventListener("focusin", function (ev) {
var t = ev.target;
if (t && t.matches && t.matches("select[name=author][data-author-picker]")) window.__dashAuthorPickers();
});
}
`;

/**
Expand Down Expand Up @@ -696,22 +732,38 @@ export interface CommentFormOpts {
identities: AuthorIdentity[];
}

export function commentFormHtml(objectRef: string, opts: CommentFormOpts): string {
const ghRefs = opts.githubRefs ?? [];
const authorOptions = opts.identities
/**
* The author picker's server-rendered options (#1179): the standing
* identities only. Session identities (one per registry session --
* ~700 and growing) used to be inlined into every card's picker,
* which made list pages quadratic: /program shipped 351 copies of a
* ~123 KB option list (44 MB of HTML), /board 94 copies (12.9 MB).
* The full list now loads on demand from /api/author-identities the
* first time any picker on the page is touched and is applied to
* every picker at once (see DASH_AFTER_JS). Pickers keep working
* without that fetch -- standing identities are the common case.
*/
export function authorOptionsHtml(identities: AuthorIdentity[]): string {
return identities
.filter((i) => !i.sessionId)
.map(
(i) =>
`<option value="${esc(`${i.kind}|${i.id}|${i.sessionId ?? ""}`)}"${i.id === "drew" ? " selected" : ""}>${esc(i.label)}${i.kind === "agent" ? " (agent)" : ""}</option>`,
)
.join("");
}

export function commentFormHtml(objectRef: string, opts: CommentFormOpts): string {
const ghRefs = opts.githubRefs ?? [];
const authorOptions = authorOptionsHtml(opts.identities);
const ghTarget = ghRefs.length
? `<div class="ghtarget" style="display:none"><label>Post to GitHub issue / PR (explicit target)</label><select name="githubRef">${ghRefs.map((r) => `<option value="${esc(r)}">${esc(r)}</option>`).join("")}</select></div>`
: "";
const ghKind = ghRefs.length
? `<label><input type="radio" name="kind" value="github"> Post as GitHub comment</label>`
: "";
return `<form class="cform" data-object="${esc(objectRef)}">
<label>Comment as</label><select name="author">${authorOptions}</select>
<label>Comment as</label><select name="author" data-author-picker>${authorOptions}</select>
<label>Kind</label><div class="kinds">
<label><input type="radio" name="kind" value="note" checked> Note — read when this is next picked up</label>
<label><input type="radio" name="kind" value="message"> ✉ Message to Muse — the orchestrator triages it on its next pass</label>
Expand Down Expand Up @@ -896,18 +948,13 @@ export function cardCommentHtml(
const list = comments?.length
? comments.map((c) => dashCommentHtml(c)).join("")
: `<p class="muted">No comments on this card yet.</p>`;
const authorOptions = opts.identities
.map(
(i) =>
`<option value="${esc(`${i.kind}|${i.id}|${i.sessionId ?? ""}`)}"${i.id === "drew" ? " selected" : ""}>${esc(i.label)}${i.kind === "agent" ? " (agent)" : ""}</option>`,
)
.join("");
const authorOptions = authorOptionsHtml(opts.identities);
const ghBox = ghRef
? `<label><input type="checkbox" name="alsoGithub" value="1"> Also post publicly to the GitHub issue (${esc(ghRef)})</label>`
: `<span class="muted">No GitHub issue on this card — the comment stays internal.</span>`;
return `<div class="cbox"><details><summary>💬 Comments for the orchestrator${comments?.length ? ` (${comments.length})` : ""}</summary>${list}<form class="cform" data-object="${esc(objectRef)}"${ghRef ? ` data-ghref="${esc(ghRef)}"` : ""}>
<input type="hidden" name="kind" value="message">
<label>Comment as</label><select name="author">${authorOptions}</select>
<label>Comment as</label><select name="author" data-author-picker>${authorOptions}</select>
<label>Comment</label><textarea name="body" rows="2" required placeholder="Note for the orchestrator…"></textarea>
<div class="kinds">${ghBox}</div>
<button type="submit">Send comment</button><div class="err"></div></form></details></div>`;
Expand Down Expand Up @@ -976,13 +1023,7 @@ export function quickBarHtml(objectRef: string, tier: "needs-drew" | "needs-orch
}

function authorSelectHtml(identities: AuthorIdentity[]): string {
const options = identities
.map(
(i) =>
`<option value="${esc(`${i.kind}|${i.id}|${i.sessionId ?? ""}`)}"${i.id === "drew" ? " selected" : ""}>${esc(i.label)}${i.kind === "agent" ? " (agent)" : ""}</option>`,
)
.join("");
return `<div class="ahead"><label>Act as</label><select name="author">${options}</select></div>`;
return `<div class="ahead"><label>Act as</label><select name="author" data-author-picker>${authorOptionsHtml(identities)}</select></div>`;
}

interface AFormSpec {
Expand Down
8 changes: 8 additions & 0 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,14 @@ async function handler(req: Request): Promise<Response> {
const prov = () => source.provenance();
const provDetail = () => source.provenanceDetail?.();

// --- Author identities for the on-demand picker (#1179) ------------------
// List pages render author pickers with the standing identities only;
// the full standing + per-session list is fetched once, on first use.
if (req.method === "GET" && path === "/api/author-identities") {
const records = await source.registry().catch(() => []);
return json({ identities: identitiesFromRecords(records) });
}

// --- Dashboard comment writes (#906 §2) --------------------------------
if (req.method === "POST" && path === "/api/comments") {
try {
Expand Down
133 changes: 133 additions & 0 deletions pm-stack/aggregator/test/author-picker-1179.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { spawn, type Subprocess } from "bun";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { authorOptionsHtml, cardCommentHtml, commentFormHtml, statusRequestHtml } from "../src/render.ts";
import { STANDING_IDENTITIES, type AuthorIdentity } from "../src/registry.ts";
import { FIXTURE_REGISTRY } from "../src/sources/fixtures.ts";

// #1179: list pages were quadratic in the session-registry size --
// every card's author picker inlined one <option> per registry
// session (~700 sessions x ~351 cards on /program = 44 MB of HTML).
// Pickers now render the standing identities only and hydrate the
// full list on demand from /api/author-identities. These tests pin
// that: no session identity is ever inlined as a picker option, and
// the endpoint still serves the full list.

const sessions: AuthorIdentity[] = Array.from({ length: 300 }, (_, i) => ({
id: `ses_fake${i}`,
label: `OpenCode · build (laptop) · Fake session ${i} with a reasonably long task title`,
kind: "agent" as const,
sessionId: `ses_fake${i}`,
}));
const identities: AuthorIdentity[] = [...STANDING_IDENTITIES.map((i) => ({ ...i })), ...sessions];

describe("author picker options (#1179)", () => {
test("authorOptionsHtml renders standing identities only", () => {
const html = authorOptionsHtml(identities);
expect(html).toContain('<option value="drew|drew|" selected>Drew</option>');
expect(html).toContain("Muse");
expect(html).toContain("Orchestrator (orchestration-pass) (agent)");
expect(html).not.toContain("ses_fake");
expect(html.match(/<option/g)?.length).toBe(STANDING_IDENTITIES.length);
});

test("the actbox picker is marked for on-demand hydration and carries no session options", () => {
const html = statusRequestHtml("gh:developing-today/code#1179", "developing-today/code#1179", "Todo", {
identities,
});
expect(html).toContain('<select name="author" data-author-picker>');
expect(html).toContain("Act as");
expect(html).not.toContain("ses_fake");
});

test("comment forms (thread + card box) use the same standing-only picker", () => {
const thread = commentFormHtml("gh:developing-today/code#1179", { identities });
const card = cardCommentHtml("gh:developing-today/code#1179", undefined, [], { identities });
for (const html of [thread, card]) {
expect(html).toContain('<select name="author" data-author-picker>');
expect(html).not.toContain("ses_fake");
}
});

test("200 cards with 300 registered sessions stay small (no per-card option duplication)", () => {
const html = Array.from({ length: 200 }, (_, i) =>
statusRequestHtml(`gh:developing-today/code#${1000 + i}`, `developing-today/code#${1000 + i}`, "Todo", {
identities,
}),
).join("");
// Pre-fix this was ~200 x 300 options ~= 9 MB; standing-only
// pickers keep it at the forms' own weight.
expect(new TextEncoder().encode(html).length).toBeLessThan(400_000);
expect(html.match(/<option/g)?.length).toBeLessThan(200 * (STANDING_IDENTITIES.length + 4) + 10);
});
});

let proc: Subprocess | undefined;
let base = "";

beforeAll(async () => {
const dir = await mkdtemp(join(tmpdir(), "pm-author-picker-1179-"));
const port = 5900 + Math.floor(Math.random() * 800);
base = `http://127.0.0.1:${port}`;
proc = spawn({
cmd: ["bun", "run", "src/server.ts"],
cwd: join(import.meta.dir, ".."),
env: {
...Bun.env,
PM_AGG_PORT: String(port),
PM_AGG_FEED_FILE: join(dir, "no-feed.json"),
PM_AGG_REGISTRY_FILE: join(dir, "registry.json"),
PM_AGG_COMMENTS_FILE: join(dir, "comments.json"),
PM_AGG_ACTIONS_FILE: join(dir, "actions.json"),
PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"),
PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"),
PM_AGG_QUOTA_VIEW: join(dir, "no-quota-view.md"),
PM_AGG_QUOTA_REGISTRY: join(dir, "no-quota-registry.md"),
PM_PROJECTOR_URL: "off",
KANEO_ADMIN_EMAIL: "",
KANEO_ADMIN_PASSWORD: "",
GRIST_API_KEY: "",
},
stdout: "pipe",
stderr: "inherit",
});
const deadline = Date.now() + 20_000;
let up = false;
while (Date.now() < deadline && !up) {
try {
const res = await fetch(`${base}/api/health`);
up = res.ok;
} catch {
/* not up yet */
}
if (!up) await Bun.sleep(150);
}
expect(up).toBe(true);
});

afterAll(() => {
proc?.kill();
});

describe("/api/author-identities (#1179)", () => {
test("serves the full standing + session identity list on demand", async () => {
const res = await fetch(`${base}/api/author-identities`);
expect(res.status).toBe(200);
const body = (await res.json()) as { identities: AuthorIdentity[] };
expect(body.identities.length).toBe(STANDING_IDENTITIES.length + FIXTURE_REGISTRY.length);
expect(body.identities.some((i) => i.sessionId === "claude-2026-10-25-slice2-review")).toBe(true);
expect(body.identities[0]?.id).toBe("drew");
});

test("/sessions renders pickers standing-only, with the hydration hook in the page script", async () => {
const res = await fetch(`${base}/sessions`);
expect(res.status).toBe(200);
const html = await res.text();
expect(html).toContain('data-author-picker');
expect(html).toContain("/api/author-identities");
// A registry session must never appear as an inlined picker option.
expect(html).not.toContain('<option value="agent|claude-2026-10-25-slice2-review|');
});
});