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
85 changes: 85 additions & 0 deletions pm-stack/aggregator/src/board-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Shared saved-view filtering for the board surfaces (#1276, #8521).
//
// /board and its Datastar fragment twin /frag/board MUST agree on
// what a view keeps: PR #4013 applied resolveView to /board (and the
// /api/*.json twins) but never to /frag/board, so a saved view that
// filtered the full page was silently dropped on the fragment path
// (#8521). Both handlers now compose through filterBoardForView —
// the twin agreement is by construction, and the tests in
// test/board-view-8521.test.ts pin the semantics.

import type { BoardItem, GhItem, ProjectPoolItem, RefKey } from "./model.ts";
import { itemMatchesView, type ViewFilters, type ViewItemLike } from "./views.ts";

/** The ViewItemLike projection of a canonical GitHub item: the
* item's own project fields win, the pool row fills the gaps. */
export function ghItemLike(item: GhItem, pool?: ProjectPoolItem | null): ViewItemLike {
return {
ref: item.ref,
repo: item.ref.replace(/#\d+$/, ""),
area: item.projectArea ?? pool?.area ?? null,
horizon: item.projectHorizon ?? pool?.horizon ?? null,
owner: item.author,
state: item.state,
epic: pool?.epicRef ?? null,
};
}

/** A board card / roadmap row matches when its own fields match, or
* when any canonical item it links to matches. */
export function linkedLike(
own: ViewItemLike,
links: readonly { ref: RefKey }[],
items: Map<RefKey, GhItem>,
poolByRef: Map<RefKey, ProjectPoolItem>,
filters: ViewFilters,
): boolean {
if (itemMatchesView(own, filters)) return true;
for (const l of links) {
const item = items.get(l.ref);
if (item && itemMatchesView(ghItemLike(item, poolByRef.get(l.ref)), filters)) return true;
}
return false;
}

/** The /board view rule (#4013), shared verbatim with /frag/board
* (#8521): keep a card when the linkedLike rule matches it; the
* items map keeps every item a kept card links to (its metadata
* renders on the card even when the item fails the filter itself)
* plus every item that matches the view directly. */
export function filterBoardForView(
board: readonly BoardItem[],
items: Map<RefKey, GhItem>,
poolByRef: Map<RefKey, ProjectPoolItem>,
filters: ViewFilters,
): { board: BoardItem[]; items: Map<RefKey, GhItem> } {
const keptBoard = board.filter((b) =>
linkedLike({ ref: b.id, repo: b.repo, state: b.status }, b.links, items, poolByRef, filters),
);
const keptRefs = new Set<string>();
for (const b of keptBoard) for (const l of b.links) keptRefs.add(l.ref);
const keptItems = new Map(
[...items].filter(
([ref, it]) => keptRefs.has(ref) || itemMatchesView(ghItemLike(it, poolByRef.get(ref)), filters),
),
);
return { board: keptBoard, items: keptItems };
}

/** The view-naming query params of a request (view id, viewer, vf.*
* filter params), re-encoded — the params a fragment URL must carry
* so a refresh re-resolves the same view instead of dropping it. */
export function viewParamsQuery(params: URLSearchParams): string {
const out = new URLSearchParams();
for (const [k, v] of params) {
if (k === "view" || k === "viewer" || k.startsWith("vf.")) out.set(k, v);
}
return out.toString();
}

/** The /frag/board URL for a request: bare when no view is named,
* view-carrying otherwise (#8521). */
export function fragBoardUrl(params: URLSearchParams): string {
const q = viewParamsQuery(params);
return q ? `/frag/board?${q}` : "/frag/board";
}
5 changes: 3 additions & 2 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1600,10 +1600,11 @@ export function renderBoard(

/** The Datastar shell for / (#1444): heading + intro paint at once;
* the board itself streams in from /frag/board. */
export function renderBoardShell(provenance: Provenance, detail?: ProvenanceDetail): string {
export function renderBoardShell(provenance: Provenance, detail?: ProvenanceDetail, viewQuery = ""): string {
const fragBoard = viewQuery ? `/frag/board?${viewQuery}` : "/frag/board";
return layout(
"Cross-repo WIP board",
`<h1>Cross-repo WIP board</h1><p class="muted">What is being worked on now is the <strong>in-flight</strong> lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards.</p><noscript><meta http-equiv="refresh" content="0; url=/board"></noscript><div id="board-main" data-frag data-on-load="@get('/frag/board')" data-on-dashrefresh__window="@get('/frag/board')"><div class="skel">Loading the board…</div></div>`,
`<h1>Cross-repo WIP board</h1><p class="muted">What is being worked on now is the <strong>in-flight</strong> lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards.</p><noscript><meta http-equiv="refresh" content="0; url=/board"></noscript><div id="board-main" data-frag data-on-load="@get('${fragBoard}')" data-on-dashrefresh__window="@get('${fragBoard}')"><div class="skel">Loading the board…</div></div>`,
provenance,
"/board",
ACTION_SCRIPT,
Expand Down
50 changes: 9 additions & 41 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
import { commentKindCounts, CommentsStore, queuedComments, validateNewComment } from "./comments.ts";
import type { SavedView, ViewFilters, ViewItemLike } from "./views.ts";
import { ViewsStore, filtersFromQuery, itemMatchesView, ownerKey } from "./views.ts";
import { filterBoardForView, fragBoardUrl, ghItemLike, linkedLike } from "./board-view.ts";
import { EventsStore, emitEvent, pageEvents } from "./events.ts";
import { FreshnessStore, type FreshnessInput } from "./freshness.ts";
import { createFreshnessIpcHandler } from "./freshness-ipc.ts";
Expand Down Expand Up @@ -1030,18 +1031,6 @@ async function resolveView(url: URL): Promise<ResolvedView | null> {
return null;
}

function ghItemLike(item: GhItem, pool?: ProjectPoolItem | null): ViewItemLike {
return {
ref: item.ref,
repo: item.ref.replace(/#\d+$/, ""),
area: item.projectArea ?? pool?.area ?? null,
horizon: item.projectHorizon ?? pool?.horizon ?? null,
owner: item.author,
state: item.state,
epic: pool?.epicRef ?? null,
};
}

function poolItemLike(item: ProjectPoolItem): ViewItemLike {
return {
ref: item.ref,
Expand Down Expand Up @@ -1081,23 +1070,6 @@ function eventFilterFromUrl(
};
}

/** A board card / roadmap row matches when its own fields match, or
* when any canonical item it links to matches. */
function linkedLike(
own: ViewItemLike,
links: readonly { ref: RefKey }[],
items: Map<RefKey, GhItem>,
poolByRef: Map<RefKey, ProjectPoolItem>,
filters: ViewFilters,
): boolean {
if (itemMatchesView(own, filters)) return true;
for (const l of links) {
const item = items.get(l.ref);
if (item && itemMatchesView(ghItemLike(item, poolByRef.get(l.ref)), filters)) return true;
}
return false;
}

/** Apply a preference view verb to the views store (#1276). Returns a
* result note for the action record, or throws — the caller maps a
* throw to a rejected action so the audit trail says what happened. */
Expand Down Expand Up @@ -1627,17 +1599,7 @@ async function handler(req: Request): Promise<Response> {
}),
);
}
const poolByRef = act.poolByRef;
const keptBoard = board.filter((b) =>
linkedLike({ ref: b.id, repo: b.repo, state: b.status }, b.links, items, poolByRef, resolved.filters),
);
const keptRefs = new Set<string>();
for (const b of keptBoard) for (const l of b.links) keptRefs.add(l.ref);
const keptItems = new Map(
[...items].filter(
([ref, it]) => keptRefs.has(ref) || itemMatchesView(ghItemLike(it, poolByRef.get(ref)), resolved.filters),
),
);
const { board: keptBoard, items: keptItems } = filterBoardForView(board, items, act.poolByRef, resolved.filters);
return html(
renderBoard(keptBoard, keptItems, prov(), counts, provDetail(), act, {
showAllDone: url.searchParams.get("done") === "all",
Expand All @@ -1646,7 +1608,13 @@ async function handler(req: Request): Promise<Response> {
}
if (path === "/frag/board") {
const { board, items, counts, act } = await boardRender();
const wrapped = `<div id="board-main" data-frag data-on-load="@get('/frag/board')" data-on-dashrefresh__window="@get('/frag/board')">${renderBoardBody(board, items, counts, act)}</div>`;
// #8521: the fragment twin applies the same saved view as /board
// (PR #4013 missed it), and its refresh URLs re-name the view so
// a reload does not silently drop the filter.
const fragUrl = fragBoardUrl(url.searchParams);
const resolved = await resolveView(url);
const view = resolved ? filterBoardForView(board, items, act.poolByRef, resolved.filters) : { board, items };
const wrapped = `<div id="board-main" data-frag data-on-load="@get('${fragUrl}')" data-on-dashrefresh__window="@get('${fragUrl}')">${renderBoardBody(view.board, view.items, counts, act)}</div>`;
return sseResponse(ssePatch("#board-main", wrapped));
}

Expand Down
120 changes: 120 additions & 0 deletions pm-stack/aggregator/test/board-view-8521.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { filterBoardForView, fragBoardUrl, viewParamsQuery } from "../src/board-view.ts";
import type { BoardItem, GhItem, ProjectPoolItem, RefKey } from "../src/model.ts";

// #8521: PR #4013 applied saved-view filtering (resolveView) to
// /board but not to its Datastar fragment twin /frag/board — the
// fragment rendered the full unfiltered board and its refresh URLs
// carried no view params, so a saved view was silently dropped on
// the fragment path. Oracle: the /board rule itself (#4013) — the
// same view must yield the same card set from both twins, and the
// fragment's own refresh URL must re-name the view. Both handlers
// now compose through filterBoardForView / fragBoardUrl, so these
// tests pin the shared composition plus the handler wiring.

const item = (ref: RefKey, author = "someone", state: GhItem["state"] = "open"): GhItem => ({
ref,
kind: "issue",
url: `https://github.com/${ref.replace("#", "/issues/")}`,
title: `item ${ref}`,
state,
labels: [],
author,
updatedAt: new Date().toISOString(),
});

const card = (title: string, repo: string, status: BoardItem["status"], links: string[]): BoardItem => ({
id: `kaneo:${title}`,
title,
repo,
source: "kaneo",
status,
updatedAt: new Date().toISOString(),
links: links.map((ref) => ({ ref, relation: "tracks" as const })),
});

const noPool = new Map<RefKey, ProjectPoolItem>();

describe("filterBoardForView (#8521, the /board rule shared with /frag/board)", () => {
test("a card is kept when a linked item matches, dropped when neither it nor its links match", () => {
const board = [
card("via-link", "dezren39/darwin-nix", "in-progress", ["developing-today/code#1"]),
card("no-match", "dezren39/darwin-nix", "in-progress", ["dezren39/darwin-nix#2"]),
card("via-own-repo", "developing-today/code", "in-progress", []),
];
const items = new Map([
["developing-today/code#1", item("developing-today/code#1")],
["dezren39/darwin-nix#2", item("dezren39/darwin-nix#2")],
] as [RefKey, GhItem][]);
const out = filterBoardForView(board, items, noPool, { repo: "developing-today/code" });
expect(out.board.map((b) => b.title)).toEqual(["via-link", "via-own-repo"]);
});

test("the items map keeps a kept card's non-matching links and directly matching items only", () => {
const board = [
card("kept", "example/other", "in-progress", ["developing-today/code#1", "developing-today/code#2"]),
card("dropped", "example/other", "in-progress", ["developing-today/code#3"]),
];
const items = new Map(
[
["developing-today/code#1", item("developing-today/code#1", "alice")],
["developing-today/code#2", item("developing-today/code#2", "bob")],
["developing-today/code#3", item("developing-today/code#3", "bob")],
["developing-today/code#4", item("developing-today/code#4", "alice")],
] as [RefKey, GhItem][],
);
const out = filterBoardForView(board, items, noPool, { owner: "alice" });
expect(out.board.map((b) => b.title)).toEqual(["kept"]);
// #1 matches and is linked from the kept card; #2 stays because a
// kept card links it (its metadata renders on the card); #3 is
// linked only from the dropped card; #4 matches directly.
expect([...out.items.keys()].sort()).toEqual([
"developing-today/code#1",
"developing-today/code#2",
"developing-today/code#4",
]);
});

test("a state filter matches the card's own status", () => {
const board = [card("done-card", "example/other", "done", []), card("wip-card", "example/other", "in-progress", [])];
const out = filterBoardForView(board, new Map(), noPool, { state: "done" });
expect(out.board.map((b) => b.title)).toEqual(["done-card"]);
});
});

describe("fragBoardUrl (#8521 view-param propagation)", () => {
test("carries view, viewer and vf.* params and drops unrelated params", () => {
const params = new URLSearchParams("view=vw-1&viewer=drew%3Adrew&vf.repo=developing-today%2Fcode&done=all&full=1");
const url = fragBoardUrl(params);
expect(url.startsWith("/frag/board?")).toBe(true);
const q = new URLSearchParams(url.split("?")[1]);
expect(q.get("view")).toBe("vw-1");
expect(q.get("viewer")).toBe("drew:drew");
expect(q.get("vf.repo")).toBe("developing-today/code");
expect(q.get("done")).toBeNull();
expect(q.get("full")).toBeNull();
});

test("is the bare fragment path when no view is named", () => {
expect(fragBoardUrl(new URLSearchParams("done=all"))).toBe("/frag/board");
expect(viewParamsQuery(new URLSearchParams())).toBe("");
});
});

describe("/frag/board handler wiring (#8521 regression pin)", () => {
const server = readFileSync(join(import.meta.dir, "../src/server.ts"), "utf8");
const fragBlock = server.slice(server.indexOf('if (path === "/frag/board")'), server.indexOf('if (path === "/today")'));
const boardBlock = server.slice(server.indexOf('if (path === "/board")'), server.indexOf('if (path === "/frag/board")'));

test("the fragment handler resolves the view and filters through the shared composition", () => {
expect(fragBlock).toContain("resolveView(url)");
expect(fragBlock).toContain("filterBoardForView");
expect(fragBlock).toContain("fragBoardUrl(url.searchParams)");
});

test("/board uses the same shared composition, so the twins cannot drift", () => {
expect(boardBlock).toContain("filterBoardForView");
});
});
Loading