diff --git a/apps/web/e2e/speed.spec.ts b/apps/web/e2e/speed.spec.ts new file mode 100644 index 0000000..db39de8 --- /dev/null +++ b/apps/web/e2e/speed.spec.ts @@ -0,0 +1,247 @@ +/** + * Speed budgets (roadmap Track B, decision 033) on a 2,000-task board: + * - the first poll after a page load is a 304 (the page and /sync agree on the ETag); + * - switching list / board / timeline sends no request and renders within budget; + * - a task opens in the side panel without a page load; + * - an edit shows before the server answers, and rolls back when the server refuses. + * GitHub is not reachable in E2E, so the test writes the cache rows directly and stubs PATCH. + */ +import { type Page, type Request, expect, test } from "@playwright/test"; +import { ghIssues, ghProjectFields, ghProjectItems, ghProjects, ghRepos, workspaceGithub, workspaceRepos } from "@gitwork/db"; +import { openSqlite } from "@gitwork/db/node"; +import { emailCount, signInCode } from "./outbox"; + +const TASKS = 2_000; +/** Script time for one view switch, measured in the page. Generous for CI machines; local runs are far lower. */ +const SWITCH_BUDGET_MS = Number(process.env.SWITCH_BUDGET_MS ?? 400); + +async function signIn(page: Page, email: string) { + const before = emailCount(email); + await page.goto("/sign-in"); + await page.getByLabel("Email").fill(email); + await page.getByRole("button", { name: "Email me a sign-in code" }).click(); + await page.getByLabel("Code").fill(await signInCode(email, before)); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); +} + +async function seedBigBoard(workspaceId: string) { + const { db } = openSqlite("file:.data/e2e.sqlite"); + const now = new Date(); + const at = new Date("2026-05-01T00:00:00Z"); + const options = [ + { id: "s-todo", name: "Todo" }, + { id: "s-doing", name: "Doing" }, + { id: "s-done", name: "Done" }, + ]; + await db.batch([ + db.insert(ghRepos).values({ + nodeId: "R_big", + githubId: 501, + installationId: 98, + owner: "bigco", + name: "app", + fullName: "bigco/app", + private: true, + htmlUrl: "https://github.com/bigco/app", + syncedAt: now, + }), + db.insert(ghProjects).values({ nodeId: "PVT_big", installationId: 98, ownerLogin: "bigco", number: 5, title: "Big", url: "https://github.com/orgs/bigco/projects/5", syncedAt: now }), + db.insert(ghProjectFields).values([ + { nodeId: "F_bstatus", projectNodeId: "PVT_big", name: "Status", dataType: "SINGLE_SELECT", config: options, syncedAt: now }, + { nodeId: "F_bstart", projectNodeId: "PVT_big", name: "Start date", dataType: "DATE", config: null, syncedAt: now }, + { nodeId: "F_btarget", projectNodeId: "PVT_big", name: "Target date", dataType: "DATE", config: null, syncedAt: now }, + ]), + db.insert(workspaceGithub).values({ workspaceId, installationId: 98, projectNodeId: "PVT_big", linkedAt: now }), + db.insert(workspaceRepos).values({ workspaceId, repoNodeId: "R_big" }), + ]); + const day = (n: number) => new Date(Date.UTC(2026, 5, 1 + (n % 60))).toISOString().slice(0, 10); + for (let start = 1; start <= TASKS; start += 200) { + const ns = Array.from({ length: Math.min(200, TASKS - start + 1) }, (_, i) => start + i); + await db.batch([ + db.insert(ghIssues).values( + ns.map((n) => ({ + nodeId: `I_big#${n}`, + repoNodeId: "R_big", + number: n, + title: `Task number ${n}`, + body: `Body of task ${n}`, + state: "open", + labels: [], + assignees: [], + htmlUrl: `https://github.com/bigco/app/issues/${n}`, + createdAtGh: at, + githubUpdatedAt: at, + syncedAt: now, + })), + ), + db.insert(ghProjectItems).values( + ns.map((n) => { + const o = options[n % 3]!; + return { + nodeId: `PVTI_big${n}`, + projectNodeId: "PVT_big", + contentType: "ISSUE", + contentNodeId: `I_big#${n}`, + fieldValues: { + F_bstatus: { type: "single_select", optionId: o.id, name: o.name }, + F_bstart: { type: "date", date: day(n) }, + F_btarget: { type: "date", date: day(n + 3) }, + } as never, + githubUpdatedAt: at, + syncedAt: now, + }; + }), + ), + ]); + } +} + +let workspaceId = ""; + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ browser }) => { + // A clean context: test.use's storageState below does not exist yet. + const context = await browser.newContext({ storageState: { cookies: [], origins: [] } }); + const page = await context.newPage(); + await signIn(page, "speed-owner@example.com"); + await page.getByLabel("Account name").fill("Speed Agency"); + await page.getByLabel("First workspace").fill("Speed Board"); + await page.getByRole("button", { name: "Create" }).click(); + await expect(page.getByRole("heading", { name: "Speed Board" })).toBeVisible(); + workspaceId = /\/w\/([^/?#]+)/.exec(page.url())![1]!; + await seedBigBoard(workspaceId); + await context.storageState({ path: ".data/speed-owner.json" }); + await context.close(); +}); + +test.use({ storageState: ".data/speed-owner.json" }); + +/** + * Requests other than the background poll and Next.js link prefetches. Next re-prefetches the + * header and nav links after the URL changes; those warm its router cache and carry no task data. + */ +function watchRequests(page: Page) { + const seen: string[] = []; + const prefetches: string[] = []; + const onRequest = (r: Request) => { + if (r.url().includes("/sync")) return; + if (r.headers()["next-router-prefetch"]) prefetches.push(r.url()); + else seen.push(`${r.method()} ${r.url()}`); + }; + page.on("request", onRequest); + return { seen, prefetches, stop: () => page.off("request", onRequest) }; +} + +/** + * Clicks a view button and returns the time until the new view's `count` items are in the DOM. + * React commits in a microtask after the click, so the clock stops on the DOM, not on click(). + */ +async function switchView(page: Page, label: string, testId: string, count: number): Promise { + return page.evaluate( + ({ name, testId, count }) => + new Promise((resolve) => { + const button = [...document.querySelectorAll('nav[aria-label="Views"] button')].find((b) => b.textContent === name)!; + const done = () => document.querySelectorAll(`[data-testid="${testId}"]`).length === count; + const t0 = performance.now(); + const observer = new MutationObserver(() => { + if (!done()) return; + observer.disconnect(); + resolve(performance.now() - t0); + }); + observer.observe(document.body, { childList: true, subtree: true }); + button.click(); + }), + { name: label, testId, count }, + ); +} + +test("the first poll is a 304: the page and /sync agree", async ({ page }) => { + await page.goto(`/w/${workspaceId}`); + await expect(page.getByTestId("task-row")).toHaveCount(TASKS); + const poll = page.waitForResponse((r) => r.url().endsWith(`/workspaces/${workspaceId}/sync`)); + await page.evaluate(() => window.dispatchEvent(new Event("focus"))); + expect((await poll).status()).toBe(304); +}); + +test("switching views sends no request and stays within budget", async ({ page }) => { + await page.goto(`/w/${workspaceId}?view=list`); + await expect(page.getByTestId("task-row")).toHaveCount(TASKS); + const requests = watchRequests(page); + const times: Record = {}; + for (const [label, testId] of [ + ["Board", "task-card"], + ["Timeline", "timeline-row"], + ["List", "task-row"], + ] as const) { + times[label] = await switchView(page, label, testId, TASKS); + await expect(page.getByTestId(testId)).toHaveCount(TASKS); + } + requests.stop(); + console.log(`[speed] view switch script ms: ${JSON.stringify(times)}`); + expect(requests.seen).toEqual([]); + // No prefetch may load the workspace's tasks page data under another name. + for (const url of requests.prefetches) expect(url).not.toContain("/tasks/"); + expect(new URL(page.url()).searchParams.get("view")).toBe("list"); + for (const [label, ms] of Object.entries(times)) expect(ms, `${label} switch`).toBeLessThan(SWITCH_BUDGET_MS); +}); + +test("a task opens in the side panel without a page load", async ({ page }) => { + await page.goto(`/w/${workspaceId}?view=list`); + const url = page.url(); + // A page load would be a document request or a non-prefetch server-component request. + const loads: string[] = []; + page.on("request", (r) => { + if (r.isNavigationRequest() || (r.url().includes("_rsc") && !r.headers()["next-router-prefetch"])) loads.push(r.url()); + }); + await page.getByRole("link", { name: "Task number 7", exact: true }).click(); + const panel = page.getByTestId("peek-panel"); + await expect(panel.getByRole("heading", { name: "Task number 7" })).toBeVisible(); + await expect(panel.getByText("Body of task 7")).toBeVisible(); + expect(page.url()).toBe(url); + expect(loads).toEqual([]); + await page.keyboard.press("Escape"); + await expect(panel).toHaveCount(0); +}); + +test("an edit shows before the server answers, and rolls back on refusal", async ({ page }) => { + await page.goto(`/w/${workspaceId}?view=list`); + const row = page.getByTestId("task-row").filter({ has: page.getByRole("link", { name: "Task number 9", exact: true }) }); + await expect(row).toContainText("Todo"); // 9 % 3 = 0 → Todo + + let release!: () => void; + const gate = new Promise((r) => (release = r)); + await page.route(`**/api/v1/workspaces/${workspaceId}/tasks/PVTI_big9`, async (route) => { + if (route.request().method() !== "PATCH") return route.fallback(); + await gate; + await route.fulfill({ status: 502, json: { error: { code: "github_error", message: "GitHub refused the request." } } }); + }); + + await page.getByRole("link", { name: "Task number 9", exact: true }).click(); + await page.getByTestId("peek-panel").getByLabel("Status").selectOption({ label: "Done" }); + // Before the server answers: the row already shows the new status. + await expect(row).toContainText("Done"); + release(); + await expect(page.getByRole("status")).toContainText("Could not change Status"); + await expect(row).toContainText("Todo"); +}); + +test("a successful edit keeps the server's answer", async ({ page }) => { + await page.goto(`/w/${workspaceId}?view=list`); + const row = page.getByTestId("task-row").filter({ has: page.getByRole("link", { name: "Task number 10", exact: true }) }); + await expect(row).toContainText("Doing"); // 10 % 3 = 1 + const sync = await page.request.get(`/api/v1/workspaces/${workspaceId}/sync`); + const task = ((await sync.json()) as { board: { tasks: { id: string; fields: Record }[] } }).board.tasks.find( + (t) => t.id === "PVTI_big10", + )!; + await page.route(`**/api/v1/workspaces/${workspaceId}/tasks/PVTI_big10`, async (route) => { + if (route.request().method() !== "PATCH") return route.fallback(); + await route.fulfill({ + json: { task: { ...task, fields: { ...task.fields, F_bstatus: { type: "single_select", optionId: "s-done", name: "Done" } } } }, + }); + }); + await page.getByRole("link", { name: "Task number 10", exact: true }).click(); + await page.getByTestId("peek-panel").getByLabel("Status").selectOption({ label: "Done" }); + await expect(row).toContainText("Done"); +}); diff --git a/apps/web/e2e/tasks.spec.ts b/apps/web/e2e/tasks.spec.ts index 39edec4..1579ba8 100644 --- a/apps/web/e2e/tasks.spec.ts +++ b/apps/web/e2e/tasks.spec.ts @@ -158,6 +158,15 @@ test("Read Only never receives a hidden task or one from an unlinked repo", asyn expect((await reader.request.get(`/api/v1/workspaces/${workspaceId}/tasks/${id}`)).status()).toBe(404); } + // The client store's snapshot (decision 033): the same two tasks, no hidden title or id. + const synced = await reader.request.get(`/api/v1/workspaces/${workspaceId}/sync`); + expect(synced.status()).toBe(200); + const syncText = await synced.text(); + await expectNoSecrets(syncText); + const snapshot = JSON.parse(syncText) as { role: string; board: { tasks: { id: string }[] } }; + expect(snapshot.role).toBe("read_only"); + expect(snapshot.board.tasks.map((t) => t.id).sort()).toEqual(["PVTI_site1", "PVTI_site3"]); + // Every view, and the task pages. for (const view of ["list", "board", "timeline"]) { await reader.goto(`/w/${workspaceId}?view=${view}`); @@ -176,6 +185,15 @@ test("Read Only never receives a hidden task or one from an unlinked repo", asyn expect(r?.status()).toBe(404); } + // The side panel: opens from the store, no edit controls, nothing hidden. + await reader.goto(`/w/${workspaceId}?view=list`); + await reader.getByRole("link", { name: "Pricing table" }).click(); + const panel = reader.getByTestId("peek-panel"); + await expect(panel.getByRole("heading", { name: "Pricing table" })).toBeVisible(); + await expect(panel.getByText("Pricing table body")).toBeVisible(); + await expect(panel.getByRole("combobox")).toHaveCount(0); + await expectNoSecrets(await reader.content()); + // Read Only cannot write. await reader.goto(`/w/${workspaceId}`); await expect(reader.getByRole("button", { name: "New task" })).toHaveCount(0); diff --git a/apps/web/src/app/w/[workspaceId]/board-context.tsx b/apps/web/src/app/w/[workspaceId]/board-context.tsx new file mode 100644 index 0000000..62e9dff --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/board-context.tsx @@ -0,0 +1,145 @@ +"use client"; +import type { FieldView, TaskDetail, TaskView } from "@gitwork/server"; +import { type ReactNode, createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { api } from "@/lib/api"; +import { BoardStore, type LinkedBoard, type Snapshot, startPolling } from "@/lib/board-store"; +import { type FieldInput, currentInput, withField } from "@/lib/field-values"; + +async function fetchSnapshot(workspaceId: string, etag: string | null) { + const res = await fetch(`/api/v1/workspaces/${workspaceId}/sync`, { + headers: etag ? { "if-none-match": etag } : {}, + cache: "no-store", + }); + if (res.status === 304) return null; + if (res.status === 401 || res.status === 403 || res.status === 404) { + // Signed out or removed from the workspace: let the server decide what to show. + window.location.reload(); + return null; + } + if (!res.ok) throw new Error(`Sync failed (${res.status}).`); + return { snapshot: (await res.json()) as Snapshot, etag: res.headers.get("etag") ?? "" }; +} + +interface BoardContextValue { + workspaceId: string; + store: BoardStore; + /** The task open in the side panel. */ + peekId: string | null; + openPeek: (taskId: string) => void; + closePeek: () => void; + /** The task with its body. Cached per version, so hovering prefetches. */ + loadDetail: (task: TaskView) => Promise; + notice: string | null; + notify: (message: string) => void; +} + +const BoardContext = createContext(null); + +export function BoardProvider({ workspaceId, initial, etag, children }: { workspaceId: string; initial: Snapshot; etag: string; children: ReactNode }) { + const [store] = useState(() => new BoardStore(initial, etag, { fetchSnapshot: (e) => fetchSnapshot(workspaceId, e) })); + const [peekId, setPeekId] = useState(null); + const [notice, setNotice] = useState(null); + const details = useRef(new Map>()); + const noticeTimer = useRef | undefined>(undefined); + + useEffect(() => startPolling(store, document, window), [store]); + + const loadDetail = useCallback( + (task: TaskView) => { + const key = `${task.id}@${task.updatedAt}`; + let found = details.current.get(key); + if (!found) { + found = api<{ task: TaskDetail }>("GET", `/workspaces/${workspaceId}/tasks/${encodeURIComponent(task.id)}`).then((r) => r.task); + found.catch(() => details.current.delete(key)); + details.current.set(key, found); + } + return found; + }, + [workspaceId], + ); + + const notify = useCallback((message: string) => { + setNotice(message); + clearTimeout(noticeTimer.current); + noticeTimer.current = setTimeout(() => setNotice(null), 5_000); + }, []); + + const value = useMemo( + () => ({ workspaceId, store, peekId, openPeek: setPeekId, closePeek: () => setPeekId(null), loadDetail, notice, notify }), + [workspaceId, store, peekId, loadDetail, notice, notify], + ); + return {children}; +} + +export function useBoardContext(): BoardContextValue { + const ctx = useContext(BoardContext); + if (!ctx) throw new Error("useBoardContext outside BoardProvider"); + return ctx; +} + +export function useSnapshot(): Snapshot { + const { store } = useBoardContext(); + return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot); +} + +/** The linked board. Only rendered under a linked workspace. */ +export function useBoard(): LinkedBoard { + const snapshot = useSnapshot(); + if (!snapshot.board.linked) throw new Error("useBoard on an unlinked workspace"); + return snapshot.board; +} + +export function useSyncState() { + const { store } = useBoardContext(); + return useSyncExternalStore(store.subscribe, store.getSyncState, store.getSyncState); +} + +/** Task edits: optimistic, rolled back with a notice on failure, undoable. */ +export function useTaskActions() { + const { workspaceId, store, notify } = useBoardContext(); + return useMemo(() => taskActions(workspaceId, store, notify), [workspaceId, store, notify]); +} + +function taskActions(workspaceId: string, store: BoardStore, notify: (message: string) => void) { + const patch = (taskId: string, body: Record) => + api<{ task: TaskView }>("PATCH", `/workspaces/${workspaceId}/tasks/${encodeURIComponent(taskId)}`, body).then((r) => r.task); + + async function setField(task: TaskView, field: FieldView, input: FieldInput | null, undoable = true): Promise { + const previous = currentInput(field, task); + try { + await store.mutate( + task.id, + withField(field, input), + () => patch(task.id, { fields: { [field.id]: input } }), + undoable ? { label: `${field.name} change`, run: () => setField(task, field, previous, false) } : undefined, + ); + } catch (error) { + notify(`Could not change ${field.name}: ${(error as Error).message}`); + } + } + + async function setState(task: TaskView, state: "open" | "closed", undoable = true): Promise { + const previous = task.state === "closed" ? "closed" : "open"; + try { + await store.mutate( + task.id, + (t) => ({ ...t, state, stateReason: state === "closed" ? "completed" : null }), + () => patch(task.id, { state, stateReason: state === "closed" ? "completed" : "reopened" }), + undoable ? { label: state === "closed" ? "Close" : "Reopen", run: () => setState(task, previous, false) } : undefined, + ); + } catch (error) { + notify(`Could not ${state === "closed" ? "close" : "reopen"} the task: ${(error as Error).message}`); + } + } + + async function undo(): Promise { + try { + const label = await store.undo(); + notify(label ? `Undone: ${label}` : "Nothing to undo."); + } catch (error) { + notify(`Could not undo: ${(error as Error).message}`); + } + } + + return { setField, setState, undo, upsert: (task: TaskView) => store.upsert(task) }; +} diff --git a/apps/web/src/app/w/[workspaceId]/page.tsx b/apps/web/src/app/w/[workspaceId]/page.tsx index b87a1db..7597847 100644 --- a/apps/web/src/app/w/[workspaceId]/page.tsx +++ b/apps/web/src/app/w/[workspaceId]/page.tsx @@ -1,28 +1,24 @@ -import { authorize, can } from "@gitwork/core"; -import { installUrl, listTasks } from "@gitwork/server"; +import { authorize } from "@gitwork/core"; +import { type BoardSnapshot, installUrl, serializedSnapshot } from "@gitwork/server"; import Link from "next/link"; import { Header } from "@/components/header"; import { Card } from "@/components/kit"; import { getDeps } from "@/server/context"; import { requireWorkspacePage } from "@/server/pages"; -import { NewTaskButton } from "./tasks/new-task"; -import { KanbanView, ListView, TimelineView } from "./tasks/task-views"; +import { VIEWS } from "./views"; +import { WorkspaceBoard } from "./workspace-board"; import { WorkspaceNav } from "./workspace-nav"; -const VIEWS = [ - { id: "list", label: "List" }, - { id: "board", label: "Board" }, - { id: "timeline", label: "Timeline" }, -] as const; - export default async function WorkspacePage({ params, searchParams }: PageProps<"/w/[workspaceId]">) { const { workspaceId } = await params; const { view: viewParam } = await searchParams; const { user, access, db } = await requireWorkspacePage(workspaceId, `/w/${workspaceId}`); - const board = await listTasks(db, access); + // The same bytes and ETag as GET /sync, so the client's first poll is a 304. + const { body, etag } = await serializedSnapshot(db, access); + const snapshot = JSON.parse(body) as BoardSnapshot; const view = VIEWS.find((v) => v.id === viewParam)?.id ?? "list"; - if (!board.linked) { + if (!snapshot.board.linked) { const { github } = await getDeps(); const install = authorize(access.actor, "github.install_app", access.settings); return ( @@ -57,46 +53,12 @@ export default async function WorkspacePage({ params, searchParams }: PageProps< ); } - const canWrite = can(access.actor, "tasks.write", access.settings); - const props = { workspaceId, tasks: board.tasks, fields: board.fields, mapping: board.mapping, canWrite }; return ( <>
-
-
- - {board.board.url && ( - - {board.board.title} on GitHub - - )} -
- {canWrite && board.board.available && board.repos.length > 0 && ( - f.id === board.mapping.kanbanFieldId) ?? null} - /> - )} -
- {!board.board.available &&

The GitHub board is not reachable right now.

} - {view === "list" && } - {view === "board" && } - {view === "timeline" && } +
); diff --git a/apps/web/src/app/w/[workspaceId]/tasks/[itemId]/task-editor.tsx b/apps/web/src/app/w/[workspaceId]/tasks/[itemId]/task-editor.tsx index ef4b0ba..c457616 100644 --- a/apps/web/src/app/w/[workspaceId]/tasks/[itemId]/task-editor.tsx +++ b/apps/web/src/app/w/[workspaceId]/tasks/[itemId]/task-editor.tsx @@ -1,50 +1,10 @@ "use client"; -import type { ProjectFieldValue } from "@gitwork/db"; import type { FieldView, TaskDetail } from "@gitwork/server"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { Button, Card, ErrorText, Input, Label, Select, Textarea } from "@/components/kit"; import { api } from "@/lib/api"; - -type FieldInput = - | { type: "single_select"; optionId: string } - | { type: "date"; date: string } - | { type: "text"; text: string } - | { type: "number"; number: number } - | { type: "iteration"; iterationId: string }; - -/** The form's string value for a field, and back. */ -function toInputValue(v: ProjectFieldValue | undefined): string { - if (!v) return ""; - switch (v.type) { - case "single_select": - return v.optionId; - case "iteration": - return v.iterationId; - case "date": - return v.date; - case "text": - return v.text; - case "number": - return String(v.number); - } -} - -function fromInputValue(field: FieldView, value: string): FieldInput | null { - if (value === "") return null; - switch (field.dataType) { - case "SINGLE_SELECT": - return { type: "single_select", optionId: value }; - case "ITERATION": - return { type: "iteration", iterationId: value }; - case "DATE": - return { type: "date", date: value }; - case "NUMBER": - return { type: "number", number: Number(value) }; - default: - return { type: "text", text: value }; - } -} +import { fromInputValue, toInputValue } from "@/lib/field-values"; export function TaskEditor({ workspaceId, task, fields }: { workspaceId: string; task: TaskDetail; fields: FieldView[] }) { const router = useRouter(); diff --git a/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx b/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx index 3773fd9..0806c82 100644 --- a/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx +++ b/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx @@ -1,18 +1,21 @@ "use client"; -import type { FieldView } from "@gitwork/server"; -import { useRouter } from "next/navigation"; +import type { TaskView } from "@gitwork/server"; import { useState } from "react"; import { Button, ErrorText, Input, Label, Select, Textarea } from "@/components/kit"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"; import { api } from "@/lib/api"; +import { useBoard, useBoardContext, useTaskActions } from "../board-context"; -export function NewTaskButton(props: { - workspaceId: string; - repos: { nodeId: string; fullName: string }[]; - defaultRepo: string | null; - statusField: FieldView | null; -}) { - const router = useRouter(); +export function NewTaskButton() { + const board = useBoard(); + const { workspaceId, openPeek } = useBoardContext(); + const { upsert } = useTaskActions(); + const props = { + workspaceId, + repos: board.repos, + defaultRepo: board.lastRepoNodeId, + statusField: board.fields.find((f) => f.id === board.mapping.kanbanFieldId) ?? null, + }; const [open, setOpen] = useState(false); const [repo, setRepo] = useState(props.defaultRepo ?? props.repos[0]?.nodeId ?? ""); const [title, setTitle] = useState(""); @@ -26,7 +29,7 @@ export function NewTaskButton(props: { setBusy(true); setError(""); try { - const { task } = await api<{ task: { id: string } }>("POST", `/workspaces/${props.workspaceId}/tasks`, { + const { task } = await api<{ task: TaskView }>("POST", `/workspaces/${props.workspaceId}/tasks`, { repoNodeId: repo, title, body: body || undefined, @@ -35,7 +38,9 @@ export function NewTaskButton(props: { setOpen(false); setTitle(""); setBody(""); - router.push(`/w/${props.workspaceId}/tasks/${encodeURIComponent(task.id)}`); + // The new task joins the store and opens beside the list: no page load. + upsert(task); + openPeek(task.id); } catch (err) { setError((err as Error).message); } finally { diff --git a/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx b/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx new file mode 100644 index 0000000..b83c20f --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx @@ -0,0 +1,186 @@ +"use client"; +import type { FieldView, TaskDetail, TaskView } from "@gitwork/server"; +import Link from "next/link"; +import { useEffect, useState } from "react"; +import { Button, Input, Select } from "@/components/kit"; +import { Badge } from "@/components/ui/badge"; +import { fromInputValue, toInputValue } from "@/lib/field-values"; +import { useBoard, useBoardContext, useSnapshot, useTaskActions } from "../board-context"; +import { editableFields } from "./fields"; +import { Ref, StateBadge } from "./task-views"; + +/** + * The task beside the list. Everything but the body comes from the store, so it opens in the + * same frame as the click. Edits are optimistic (useTaskActions). + */ +export function PeekPanel() { + const { peekId, closePeek, workspaceId } = useBoardContext(); + const { tasks } = useBoard(); + const task = peekId ? tasks.find((t) => t.id === peekId) : undefined; + + useEffect(() => { + if (!peekId) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape" && !e.defaultPrevented) closePeek(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [peekId, closePeek]); + + if (!peekId) return null; + return ( + + ); +} + +function PeekBody({ task }: { task: TaskView }) { + const { loadDetail } = useBoardContext(); + const { fields } = useBoard(); + const { canWrite } = useSnapshot(); + const { setState } = useTaskActions(); + const [detail, setDetail] = useState(null); + const [failed, setFailed] = useState(false); + + useEffect(() => { + let live = true; + loadDetail(task).then( + (d) => live && setDetail(d), + () => live && setFailed(true), + ); + return () => { + live = false; + }; + }, [task, loadDetail]); + + return ( +
+
+

{task.title || "(untitled)"}

+
+ + {task.labels.map((l) => ( + + {l.name} + + ))} + {task.assignees.length > 0 && {task.assignees.map((a) => a.login).join(", ")}} +
+
+ +
+ {editableFields(fields).map((f) => ( + + ))} +
+ + {canWrite && task.kind === "issue" && ( + + )} + +
+ {detail ? ( + detail.body?.trim() ? ( +

{detail.body}

+ ) : ( +

No description.

+ ) + ) : failed ? ( +

Could not load the description.

+ ) : ( +

Loading…

+ )} +
+
+ ); +} + +function FieldRow({ field, task, canWrite }: { field: FieldView; task: TaskView; canWrite: boolean }) { + const { setField } = useTaskActions(); + const value = toInputValue(task.fields[field.id]); + const id = `peek-${field.id}`; + const [draft, setDraft] = useState(value); + // A new value from the store (another edit, a poll) replaces an untouched draft. + const [shown, setShown] = useState(value); + if (shown !== value) { + setShown(value); + setDraft(value); + } + const commit = (next: string) => { + if (next !== value) void setField(task, field, fromInputValue(field, next)); + }; + + return ( + <> +
+ +
+
+ {!canWrite ? ( + {value ? displayValue(field, value) : "—"} + ) : field.dataType === "SINGLE_SELECT" || field.dataType === "ITERATION" ? ( + + ) : ( + setDraft(e.target.value)} + onBlur={() => commit(draft)} + onKeyDown={(e) => { + if (e.key === "Enter") commit(draft); + if (e.key === "Escape") { + e.preventDefault(); // keep the panel open; just drop the draft + setDraft(value); + } + }} + /> + )} +
+ + ); +} + +function options(field: FieldView) { + return field.dataType === "SINGLE_SELECT" + ? (field.options ?? []).map((o) => ({ id: o.id, name: o.name })) + : (field.iterations ?? []).map((i) => ({ id: i.id, name: i.title })); +} + +function displayValue(field: FieldView, value: string) { + return options(field).find((o) => o.id === value)?.name ?? value; +} diff --git a/apps/web/src/app/w/[workspaceId]/tasks/task-views.tsx b/apps/web/src/app/w/[workspaceId]/tasks/task-views.tsx index 6354c42..3282e0e 100644 --- a/apps/web/src/app/w/[workspaceId]/tasks/task-views.tsx +++ b/apps/web/src/app/w/[workspaceId]/tasks/task-views.tsx @@ -1,30 +1,33 @@ "use client"; -import type { FieldMapping, FieldView, TaskView } from "@gitwork/server"; +import type { TaskView } from "@gitwork/server"; import Link from "next/link"; -import { useRouter } from "next/navigation"; import { useState } from "react"; -import { ErrorText } from "@/components/kit"; import { Badge } from "@/components/ui/badge"; -import { api } from "@/lib/api"; +import { useBoard, useBoardContext, useSnapshot, useTaskActions } from "../board-context"; import { fieldText, optionOf, spanOf, treeOrder } from "./fields"; -interface ViewProps { - workspaceId: string; - tasks: TaskView[]; - fields: FieldView[]; - mapping: FieldMapping; - canWrite: boolean; -} - -function TaskLink({ workspaceId, task }: { workspaceId: string; task: TaskView }) { +/** Opens the side panel on a plain click; a modified click (new tab) follows the link. Hover prefetches the body. */ +export function TaskLink({ task, className }: { task: TaskView; className?: string }) { + const { workspaceId, openPeek, loadDetail } = useBoardContext(); return ( - + { + if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; + e.preventDefault(); + openPeek(task.id); + }} + onMouseEnter={() => void loadDetail(task).catch(() => undefined)} + > {task.title || "(untitled)"} ); } -function Ref({ task }: { task: TaskView }) { +export function Ref({ task }: { task: TaskView }) { if (task.kind === "draft") return Draft; return ( @@ -33,14 +36,15 @@ function Ref({ task }: { task: TaskView }) { ); } -function StateBadge({ task }: { task: TaskView }) { +export function StateBadge({ task }: { task: TaskView }) { if (task.state !== "closed") return null; return {task.stateReason === "not_planned" ? "Not planned" : "Closed"}; } // ---- List ------------------------------------------------------------------------------------- -export function ListView({ workspaceId, tasks, mapping }: ViewProps) { +export function ListView() { + const { tasks, mapping } = useBoard(); if (tasks.length === 0) return ; return (
@@ -59,7 +63,7 @@ export function ListView({ workspaceId, tasks, mapping }: ViewProps) {
{depth > 0 && ↳} - + {task.labels.map((l) => ( @@ -84,9 +88,10 @@ export function ListView({ workspaceId, tasks, mapping }: ViewProps) { // ---- Kanban ----------------------------------------------------------------------------------- -export function KanbanView({ workspaceId, tasks, fields, mapping, canWrite }: ViewProps) { - const router = useRouter(); - const [error, setError] = useState(""); +export function KanbanView() { + const { tasks, fields, mapping } = useBoard(); + const { canWrite } = useSnapshot(); + const { setField } = useTaskActions(); const [dragging, setDragging] = useState(null); const [groupBy, setGroupBy] = useState(mapping.kanbanFieldId); const singleSelects = fields.filter((f) => f.dataType === "SINGLE_SELECT"); @@ -94,17 +99,9 @@ export function KanbanView({ workspaceId, tasks, fields, mapping, canWrite }: Vi if (!field) return

This board has no single-select field to group by.

; const columns = [...(field.options ?? []).map((o) => ({ id: o.id as string | null, name: o.name })), { id: null, name: `No ${field.name}` }]; - async function move(taskId: string, optionId: string | null) { - setError(""); - try { - await api("PATCH", `/workspaces/${workspaceId}/tasks/${encodeURIComponent(taskId)}`, { - fields: { [field!.id]: optionId ? { type: "single_select", optionId } : null }, - }); - router.refresh(); - } catch (err) { - setError((err as Error).message); - } - } + // Optimistic: the card moves at once; a refusal moves it back with a notice. + const move = (task: TaskView, optionId: string | null) => + setField(task, field, optionId ? { type: "single_select", optionId } : null); return (
@@ -120,7 +117,6 @@ export function KanbanView({ workspaceId, tasks, fields, mapping, canWrite }: Vi )} - {error}
{columns.map((col) => { const cards = tasks.filter((t) => optionOf(t, field.id) === col.id); @@ -135,7 +131,7 @@ export function KanbanView({ workspaceId, tasks, fields, mapping, canWrite }: Vi const id = e.dataTransfer.getData("text/plain"); setDragging(null); const task = tasks.find((t) => t.id === id); - if (task && optionOf(task, field.id) !== col.id) void move(id, col.id); + if (task && optionOf(task, field.id) !== col.id) void move(task, col.id); }} >

@@ -153,7 +149,7 @@ export function KanbanView({ workspaceId, tasks, fields, mapping, canWrite }: Vi className="space-y-1 rounded-lg bg-card p-2 text-sm shadow-xs ring-1 ring-foreground/10" data-testid="task-card" > - +
@@ -175,7 +171,8 @@ const ROW = 36; const DAY_PX = 24; const BAR = 20; -export function TimelineView({ workspaceId, tasks, mapping }: ViewProps) { +export function TimelineView() { + const { tasks, mapping } = useBoard(); // Read the clock once per mount, not on every render. const [now] = useState(() => Date.now()); if (!mapping.startFieldId && !mapping.targetFieldId && !mapping.iterationFieldId) { @@ -208,7 +205,7 @@ export function TimelineView({ workspaceId, tasks, mapping }: ViewProps) {
{scheduled.map(({ task }) => (
- +
))}
@@ -266,7 +263,7 @@ export function TimelineView({ workspaceId, tasks, mapping }: ViewProps) {
    {unscheduled.map((task) => (
  • - +
  • ))}
diff --git a/apps/web/src/app/w/[workspaceId]/views.ts b/apps/web/src/app/w/[workspaceId]/views.ts new file mode 100644 index 0000000..0e21d54 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/views.ts @@ -0,0 +1,7 @@ +/** The task views. Plain data: the server page and the client board both read it. */ +export const VIEWS = [ + { id: "list", label: "List" }, + { id: "board", label: "Board" }, + { id: "timeline", label: "Timeline" }, +] as const; +export type ViewId = (typeof VIEWS)[number]["id"]; diff --git a/apps/web/src/app/w/[workspaceId]/workspace-board.tsx b/apps/web/src/app/w/[workspaceId]/workspace-board.tsx new file mode 100644 index 0000000..4f68d18 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/workspace-board.tsx @@ -0,0 +1,78 @@ +"use client"; +import { useState } from "react"; +import type { Snapshot } from "@/lib/board-store"; +import { BoardProvider, useBoard, useBoardContext, useSnapshot, useSyncState } from "./board-context"; +import { PeekPanel } from "./tasks/peek-panel"; +import { NewTaskButton } from "./tasks/new-task"; +import { KanbanView, ListView, TimelineView } from "./tasks/task-views"; +import { VIEWS, type ViewId } from "./views"; + +/** The tasks area of a linked workspace. View switches stay in the browser: no server render. */ +export function WorkspaceBoard(props: { workspaceId: string; initial: Snapshot; etag: string; initialView: ViewId }) { + return ( + + + + ); +} + +function Board({ initialView }: { initialView: ViewId }) { + const [view, setView] = useState(initialView); + const board = useBoard(); + const { canWrite } = useSnapshot(); + const { peekId, notice } = useBoardContext(); + + function show(next: ViewId) { + setView(next); + const url = new URL(window.location.href); + url.searchParams.set("view", next); + window.history.replaceState(window.history.state, "", url); + } + + return ( +
+
+
+ + {board.board.url && ( + + {board.board.title} on GitHub + + )} + +
+ {canWrite && board.board.available && board.repos.length > 0 && } +
+ {!board.board.available &&

The GitHub board is not reachable right now.

} + {view === "list" && } + {view === "board" && } + {view === "timeline" && } + +
+ {notice &&

{notice}

} +
+
+ ); +} + +function SyncStatus() { + const sync = useSyncState(); + if (!sync.error) return null; + return ( + + Not synced — retrying + + ); +} diff --git a/apps/web/src/lib/board-store.test.ts b/apps/web/src/lib/board-store.test.ts new file mode 100644 index 0000000..1dabfc1 --- /dev/null +++ b/apps/web/src/lib/board-store.test.ts @@ -0,0 +1,153 @@ +import type { TaskView } from "@gitwork/server"; +import { describe, expect, it, vi } from "vitest"; +import { BoardStore, type Snapshot, startPolling } from "./board-store"; + +const task = (id: string, title: string): TaskView => ({ + id, + kind: "issue", + title, + state: "open", + stateReason: null, + number: 1, + repo: { nodeId: "R", fullName: "acme/site" }, + url: null, + labels: [], + assignees: [], + fields: {}, + parentId: null, + blockedBy: [], + updatedAt: "2026-11-10T00:00:00.000Z", +}); + +const snap = (...tasks: TaskView[]): Snapshot => ({ + role: "member", + canWrite: true, + board: { + linked: true, + board: { title: "B", url: "", available: true }, + repos: [], + fields: [], + mapping: { kanbanFieldId: null, startFieldId: null, targetFieldId: null, iterationFieldId: null }, + tasks, + lastRepoNodeId: null, + }, +}); + +const titles = (s: Snapshot) => (s.board.linked ? s.board.tasks.map((t) => t.title) : []); + +function deferred() { + let resolve!: (v: T) => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe("BoardStore", () => { + it("shows an edit at once, then keeps the server's version", async () => { + const store = new BoardStore(snap(task("a", "Old")), '"e1"', { fetchSnapshot: async () => null }); + const server = deferred(); + const done = store.mutate("a", (t) => ({ ...t, title: "New" }), () => server.promise); + expect(titles(store.getSnapshot())).toEqual(["New"]); + server.resolve(task("a", "New (server)")); + await done; + expect(titles(store.getSnapshot())).toEqual(["New (server)"]); + }); + + it("rolls back a failed edit and rethrows", async () => { + const store = new BoardStore(snap(task("a", "Old")), null, { fetchSnapshot: async () => null }); + await expect(store.mutate("a", (t) => ({ ...t, title: "New" }), async () => Promise.reject(new Error("GitHub refused")))).rejects.toThrow( + "GitHub refused", + ); + expect(titles(store.getSnapshot())).toEqual(["Old"]); + }); + + it("keeps a pending edit on top of a snapshot that arrives meanwhile", async () => { + const fetchSnapshot = vi.fn(async () => ({ snapshot: snap(task("a", "Old"), task("b", "Other")), etag: '"e2"' })); + const store = new BoardStore(snap(task("a", "Old")), '"e1"', { fetchSnapshot }); + const server = deferred(); + const done = store.mutate("a", (t) => ({ ...t, title: "New" }), () => server.promise); + await store.poll(); + expect(titles(store.getSnapshot())).toEqual(["New", "Other"]); + server.resolve(task("a", "New")); + await done; + expect(titles(store.getSnapshot())).toEqual(["New", "Other"]); + }); + + it("discards a poll that started before an edit finished, and fetches fresh next time", async () => { + const stale = deferred<{ snapshot: Snapshot; etag: string }>(); + const fetchSnapshot = vi.fn().mockReturnValueOnce(stale.promise).mockResolvedValueOnce({ snapshot: snap(task("a", "New")), etag: '"e3"' }); + const store = new BoardStore(snap(task("a", "Old")), '"e1"', { fetchSnapshot }); + const poll = store.poll(); + await store.mutate("a", (t) => ({ ...t, title: "New" }), async () => task("a", "New")); + stale.resolve({ snapshot: snap(task("a", "Old")), etag: '"e2"' }); + await poll; + expect(titles(store.getSnapshot())).toEqual(["New"]); // no flicker back to "Old" + await store.poll(); + expect(fetchSnapshot).toHaveBeenLastCalledWith(null); // the ETag was dropped + }); + + it("sends the ETag and keeps the snapshot on 304", async () => { + const fetchSnapshot = vi.fn(async () => null); + const initial = snap(task("a", "Old")); + const store = new BoardStore(initial, '"e1"', { fetchSnapshot }); + await store.poll(); + expect(fetchSnapshot).toHaveBeenCalledWith('"e1"'); + expect(store.getSnapshot()).toBe(initial); + }); + + it("drops tasks the new snapshot no longer has (a task hidden from this viewer)", async () => { + const store = new BoardStore(snap(task("a", "A"), task("b", "B")), '"e1"', { + fetchSnapshot: async () => ({ snapshot: snap(task("a", "A")), etag: '"e2"' }), + }); + await store.poll(); + expect(titles(store.getSnapshot())).toEqual(["A"]); + }); + + it("shares one request between concurrent polls and reports errors", async () => { + const fetchSnapshot = vi.fn(async () => { + throw new Error("offline"); + }); + const store = new BoardStore(snap(), null, { fetchSnapshot }); + await Promise.all([store.poll(), store.poll()]); + expect(fetchSnapshot).toHaveBeenCalledTimes(1); + expect(store.getSyncState().error).toBe("offline"); + }); + + it("returns a stable snapshot between changes", () => { + const store = new BoardStore(snap(task("a", "A")), null, { fetchSnapshot: async () => null }); + expect(store.getSnapshot()).toBe(store.getSnapshot()); + }); + + it("undoes the newest edit", async () => { + const store = new BoardStore(snap(task("a", "Old")), null, { fetchSnapshot: async () => null }); + const run = vi.fn(async () => undefined); + await store.mutate("a", (t) => ({ ...t, title: "New" }), async () => task("a", "New"), { label: "Rename", run }); + expect(store.canUndo()).toBe(true); + expect(await store.undo()).toBe("Rename"); + expect(run).toHaveBeenCalledOnce(); + expect(await store.undo()).toBeNull(); + }); +}); + +describe("startPolling", () => { + it("polls only while visible, and at once on focus", () => { + vi.useFakeTimers(); + const store = { poll: vi.fn(async () => undefined) } as unknown as BoardStore; + const handlers: Record void> = {}; + const doc = { visibilityState: "hidden" as DocumentVisibilityState, addEventListener: (e: string, h: () => void) => (handlers[e] = h), removeEventListener: vi.fn() }; + const win = { addEventListener: (e: string, h: () => void) => (handlers[e] = h), removeEventListener: vi.fn() }; + const stop = startPolling(store, doc as never, win as never, 5_000); + vi.advanceTimersByTime(5_000); + expect(store.poll).not.toHaveBeenCalled(); + doc.visibilityState = "visible"; + vi.advanceTimersByTime(5_000); + expect(store.poll).toHaveBeenCalledTimes(1); + handlers.focus!(); + expect(store.poll).toHaveBeenCalledTimes(2); + stop(); + vi.useRealTimers(); + }); +}); diff --git a/apps/web/src/lib/board-store.ts b/apps/web/src/lib/board-store.ts new file mode 100644 index 0000000..3a0c1e1 --- /dev/null +++ b/apps/web/src/lib/board-store.ts @@ -0,0 +1,178 @@ +/** + * The client-side store for one workspace's tasks (decisions 026, 033). Framework-free so it can be + * unit-tested; React reads it through useSyncExternalStore (see board-context.tsx). + * + * - `base` is the last snapshot the server sent. It holds only what this viewer may see. + * - `pending` edits are layered over `base` until the server answers, so a poll that started + * before an edit never shows the old value again (no flicker back). + * - A poll whose request started before an edit finished is discarded: its snapshot may predate it. + */ +import type { BoardSnapshot, TaskView } from "@gitwork/server"; + +export type LinkedBoard = Extract; +export type Snapshot = BoardSnapshot; + +/** Changes a task locally. Must be pure. */ +export type TaskPatch = (task: TaskView) => TaskView; + +interface Pending { + id: number; + taskId: string; + patch: TaskPatch; +} + +export interface UndoEntry { + label: string; + run: () => Promise; +} + +export type SyncState = { status: "idle" | "syncing"; lastSyncedAt: number; error: string | null }; + +export interface StoreDeps { + /** GET /sync. Returns null on 304. */ + fetchSnapshot: (etag: string | null) => Promise<{ snapshot: Snapshot; etag: string } | null>; + now?: () => number; +} + +export class BoardStore { + private base: Snapshot; + private etag: string | null; + private pending: Pending[] = []; + private nextId = 1; + /** Bumped when an edit settles. A poll started under an older value is stale. */ + private writes = 0; + private merged: Snapshot | null = null; + private listeners = new Set<() => void>(); + private undoStack: UndoEntry[] = []; + private sync: SyncState; + private inFlight: Promise | null = null; + + constructor( + initial: Snapshot, + etag: string | null, + private deps: StoreDeps, + ) { + this.base = initial; + this.etag = etag; + this.sync = { status: "idle", lastSyncedAt: this.now(), error: null }; + } + + private now() { + return (this.deps.now ?? Date.now)(); + } + + subscribe = (listener: () => void) => { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + }; + + private emit() { + this.merged = null; + for (const l of this.listeners) l(); + } + + /** The snapshot with pending edits applied. Stable between changes (useSyncExternalStore). */ + getSnapshot = (): Snapshot => { + if (this.merged) return this.merged; + if (this.pending.length === 0 || !this.base.board.linked) return (this.merged = this.base); + const byTask = new Map(); + for (const p of this.pending) byTask.set(p.taskId, [...(byTask.get(p.taskId) ?? []), p.patch]); + const tasks = this.base.board.tasks.map((t) => (byTask.get(t.id) ?? []).reduce((acc, patch) => patch(acc), t)); + return (this.merged = { ...this.base, board: { ...this.base.board, tasks } }); + }; + + getSyncState = () => this.sync; + + private setSync(next: Partial) { + this.sync = { ...this.sync, ...next }; + this.emit(); + } + + /** Fetches a new snapshot if the server has one. Concurrent calls share one request. */ + poll(): Promise { + this.inFlight ??= this.doPoll().finally(() => { + this.inFlight = null; + }); + return this.inFlight; + } + + private async doPoll() { + const startedAt = this.writes; + this.setSync({ status: "syncing" }); + try { + const result = await this.deps.fetchSnapshot(this.etag); + if (this.writes !== startedAt) { + // An edit finished while this request ran; its answer may not include the edit. + this.etag = null; + this.setSync({ status: "idle", error: null }); + return; + } + if (result) { + this.base = result.snapshot; + this.etag = result.etag; + } + this.setSync({ status: "idle", lastSyncedAt: this.now(), error: null }); + } catch (error) { + this.setSync({ status: "idle", error: (error as Error).message }); + } + } + + /** + * Applies `patch` at once, then runs `request`. On success the server's task replaces the local + * one; on failure the patch is dropped (the edit rolls back) and the error is rethrown. + */ + async mutate(taskId: string, patch: TaskPatch, request: () => Promise, undo?: UndoEntry): Promise { + const entry: Pending = { id: this.nextId++, taskId, patch }; + this.pending.push(entry); + this.emit(); + try { + const task = await request(); + this.upsert(task); + if (undo) this.undoStack.push(undo); + return task; + } finally { + this.pending = this.pending.filter((p) => p.id !== entry.id); + this.writes++; + this.emit(); + } + } + + /** Puts a task from a write response into the base snapshot (new or changed). */ + upsert(task: TaskView) { + if (!this.base.board.linked) return; + const tasks = this.base.board.tasks; + const i = tasks.findIndex((t) => t.id === task.id); + const next = i === -1 ? [...tasks, task] : tasks.map((t, j) => (j === i ? task : t)); + this.base = { ...this.base, board: { ...this.base.board, tasks: next } }; + // The ETag no longer matches what we hold; the next poll must fetch. + this.etag = null; + this.emit(); + } + + canUndo() { + return this.undoStack.length > 0; + } + + /** Undoes the newest edit. Returns its label, or null when there is nothing to undo. */ + async undo(): Promise { + const entry = this.undoStack.pop(); + if (!entry) return null; + await entry.run(); + return entry.label; + } +} + +/** Polls every `everyMs` while the page is visible, and at once when it becomes visible again. */ +export function startPolling(store: BoardStore, doc: Pick, win: Pick, everyMs = 5_000) { + const tick = () => { + if (doc.visibilityState === "visible") void store.poll(); + }; + const timer = setInterval(tick, everyMs); + doc.addEventListener("visibilitychange", tick); + win.addEventListener("focus", tick); + return () => { + clearInterval(timer); + doc.removeEventListener("visibilitychange", tick); + win.removeEventListener("focus", tick); + }; +} diff --git a/apps/web/src/lib/field-values.test.ts b/apps/web/src/lib/field-values.test.ts new file mode 100644 index 0000000..f5600bd --- /dev/null +++ b/apps/web/src/lib/field-values.test.ts @@ -0,0 +1,40 @@ +import type { FieldView, TaskView } from "@gitwork/server"; +import { describe, expect, it } from "vitest"; +import { currentInput, fromInputValue, toInputValue, valueOf, withField } from "./field-values"; + +const status: FieldView = { id: "F_s", name: "Status", dataType: "SINGLE_SELECT", options: [{ id: "o1", name: "Todo" }, { id: "o2", name: "Done" }] }; +const sprint: FieldView = { id: "F_i", name: "Sprint", dataType: "ITERATION", iterations: [{ id: "i1", title: "Sprint 1", startDate: "2026-11-02", duration: 14 }] }; +const due: FieldView = { id: "F_d", name: "Due", dataType: "DATE" }; +const task = { id: "t", fields: { F_s: { type: "single_select", optionId: "o1", name: "Todo" } } } as unknown as TaskView; + +describe("field values", () => { + it("round-trips form strings for every type", () => { + expect(fromInputValue(status, "o2")).toEqual({ type: "single_select", optionId: "o2" }); + expect(fromInputValue(sprint, "i1")).toEqual({ type: "iteration", iterationId: "i1" }); + expect(fromInputValue(due, "2026-12-01")).toEqual({ type: "date", date: "2026-12-01" }); + expect(fromInputValue({ id: "n", name: "Est", dataType: "NUMBER" }, "3")).toEqual({ type: "number", number: 3 }); + expect(fromInputValue(due, "")).toBeNull(); + expect(toInputValue({ type: "number", number: 3 })).toBe("3"); + }); + + it("fills option names and iteration dates like the server cache", () => { + expect(valueOf(status, { type: "single_select", optionId: "o2" })).toEqual({ type: "single_select", optionId: "o2", name: "Done" }); + expect(valueOf(sprint, { type: "iteration", iterationId: "i1" })).toEqual({ + type: "iteration", + iterationId: "i1", + title: "Sprint 1", + startDate: "2026-11-02", + duration: 14, + }); + expect(valueOf(status, { type: "single_select", optionId: "nope" })).toBeNull(); + }); + + it("sets and clears a field without touching the original task", () => { + const moved = withField(status, { type: "single_select", optionId: "o2" })(task); + expect(moved.fields.F_s).toEqual({ type: "single_select", optionId: "o2", name: "Done" }); + expect(task.fields.F_s).toMatchObject({ optionId: "o1" }); + expect(withField(status, null)(task).fields.F_s).toBeUndefined(); + expect(currentInput(status, task)).toEqual({ type: "single_select", optionId: "o1" }); + expect(currentInput(due, task)).toBeNull(); + }); +}); diff --git a/apps/web/src/lib/field-values.ts b/apps/web/src/lib/field-values.ts new file mode 100644 index 0000000..41c1b39 --- /dev/null +++ b/apps/web/src/lib/field-values.ts @@ -0,0 +1,83 @@ +/** + * Board field values: the API's input shape, form strings, and the cached value shape. Pure, so + * optimistic edits produce exactly what the server will store. + */ +import type { ProjectFieldValue } from "@gitwork/db"; +import type { FieldView, TaskView } from "@gitwork/server"; + +export type FieldInput = + | { type: "single_select"; optionId: string } + | { type: "date"; date: string } + | { type: "text"; text: string } + | { type: "number"; number: number } + | { type: "iteration"; iterationId: string }; + +/** The form's string value for a field. */ +export function toInputValue(v: ProjectFieldValue | undefined): string { + if (!v) return ""; + switch (v.type) { + case "single_select": + return v.optionId; + case "iteration": + return v.iterationId; + case "date": + return v.date; + case "text": + return v.text; + case "number": + return String(v.number); + } +} + +/** A form string as the API's input; "" clears the field. */ +export function fromInputValue(field: FieldView, value: string): FieldInput | null { + if (value === "") return null; + switch (field.dataType) { + case "SINGLE_SELECT": + return { type: "single_select", optionId: value }; + case "ITERATION": + return { type: "iteration", iterationId: value }; + case "DATE": + return { type: "date", date: value }; + case "NUMBER": + return { type: "number", number: Number(value) }; + default: + return { type: "text", text: value }; + } +} + +/** The cached value an input produces, or null if the option or iteration is unknown. */ +export function valueOf(field: FieldView, input: FieldInput): ProjectFieldValue | null { + switch (input.type) { + case "single_select": { + const o = field.options?.find((x) => x.id === input.optionId); + return o ? { type: "single_select", optionId: o.id, name: o.name } : null; + } + case "iteration": { + const it = field.iterations?.find((x) => x.id === input.iterationId); + return it ? { type: "iteration", iterationId: it.id, title: it.title, startDate: it.startDate, duration: it.duration } : null; + } + case "date": + return { type: "date", date: input.date }; + case "text": + return { type: "text", text: input.text }; + case "number": + return { type: "number", number: input.number }; + } +} + +/** A patch that sets (or, with null, clears) one field on a task. */ +export function withField(field: FieldView, input: FieldInput | null) { + return (task: TaskView): TaskView => { + const fields = { ...task.fields }; + const value = input ? valueOf(field, input) : null; + if (value) fields[field.id] = value; + else delete fields[field.id]; + return { ...task, fields }; + }; +} + +/** The input that restores a task's current value of a field (for undo). */ +export function currentInput(field: FieldView, task: TaskView): FieldInput | null { + return fromInputValue(field, toInputValue(task.fields[field.id])); +} diff --git a/docs/INDEX.md b/docs/INDEX.md index b294d47..17cfc0a 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -42,6 +42,7 @@ | 030 | [Assignees are GitHub users only](decisions/030-assignees.md) | | 031 | [Linear features out of scope for v1](decisions/031-v1-scope.md) | | 032 | [Triage is linked-repo issues not on the board](decisions/032-triage.md) | +| 033 | [Sync by snapshot ETag, not a change table; no IndexedDB yet](decisions/033-snapshot-etag-sync.md) | ## Features @@ -53,3 +54,4 @@ | [features/tasks.md](features/tasks.md) | Board and repo link, list / kanban / timeline, task edits, visibility filter, audit log. | | [features/self-host.md](features/self-host.md) | Docker image, config check, /setup/health, backup, release pipeline, DCO. | | [self-host/README.md](self-host/README.md) | Self-host guide: Docker, Cloudflare, upgrades, backups, troubleshooting. | +| [features/speed.md](features/speed.md) | Client store, /sync with ETag, optimistic edits, side panel, measured budgets. | diff --git a/docs/STATE.md b/docs/STATE.md index 5fad4ac..29c38bd 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -18,7 +18,7 @@ Last updated: 2026-11-10 ## In Progress -Track B + C + D (speed, keyboard, layout) — next after PR #7. +Track C (keyboard, command menu) and Track D (app shell) — next after PR #8. Roadmap: `docs/roadmap.md` (PR #6). ## Completed @@ -30,6 +30,7 @@ Track B + C + D (speed, keyboard, layout) — next after PR #7. | Phase 2 — GitHub App (PR #3) | 2026-10-15 | [features/github-app.md](features/github-app.md) | | Phase 3 — Tasks on web (PR #4) | 2026-10-16 | [features/tasks.md](features/tasks.md) | | Track A — Self-host release (PR #7, in review; GitHub half of the exit check waits on the live check) | 2026-11-10 | [features/self-host.md](features/self-host.md) | +| Track B — Speed foundation (PR #8, in review) | 2026-11-10 | [features/speed.md](features/speed.md) | ## Backlog diff --git a/docs/decisions/033-snapshot-etag-sync.md b/docs/decisions/033-snapshot-etag-sync.md new file mode 100644 index 0000000..66d427b --- /dev/null +++ b/docs/decisions/033-snapshot-etag-sync.md @@ -0,0 +1,37 @@ +# 033 — Sync by snapshot ETag, not a change table; no IndexedDB yet + +Date: 2026-11-10 · Status: Accepted (default; owner may override) · Amends 026 + +## Context +Decision 026 planned a `workspace_changes` table, an opaque cursor, tombstones for IDs the client +holds, and an IndexedDB cache. Building it showed two problems: +- The cache's `syncedAt` column does not mark every change (`markIssuesDeleted`, + `setReposAvailable` skip it), so a change table needs a write in every cache path. +- Each leak rule in 026 (tombstones, cursor gaps, stale cache after a role change) exists only + because of deltas. + +## Decision +- `GET /api/v1/workspaces/:id/sync` returns the viewer's whole filtered snapshot + (`role`, `canWrite`, `board`) with a strong ETag: SHA-256 of the exact bytes this viewer gets. + With a matching `If-None-Match` it answers 304 and no body. +- Headers: `Cache-Control: private, no-cache` and `Vary: Cookie`, so no proxy shares a snapshot. +- The server-rendered page computes the same bytes and ETag, so the client's first poll is a 304. +- The client polls every 5 s while the tab is visible, and on focus (as 026). +- The browser keeps the snapshot in memory only. **IndexedDB is deferred** until offline use needs + it (the Mac app has its own cache). This departs from the answer to Q4; the owner may override. + +## Why it is safe +A change to an item the viewer cannot see leaves the viewer's bytes, and so the ETag, unchanged: +the poll is a 304, exactly as if nothing happened. A role or hide-setting change changes the bytes, +so the client replaces everything it holds. No tombstones, no cursor, nothing to leak. + +## Alternatives considered +- **Change table + cursor (026):** smaller responses on change; more code in every cache write and + three leak rules to keep right. +- **Per-task hashes, then fetch changed tasks:** a later optimization if snapshots grow large. + +## Consequences +- Each poll runs the filtered board query on the server (one join over the board's items). Each + change sends the whole snapshot. Its size at 2,000 tasks is not measured yet; measure it before + choosing per-task hashes. +- Revisit with per-task hashes when boards pass about 5,000 tasks. diff --git a/docs/features/speed.md b/docs/features/speed.md new file mode 100644 index 0000000..4853e14 --- /dev/null +++ b/docs/features/speed.md @@ -0,0 +1,69 @@ +# Speed foundation — client store, polling sync, optimistic edits, side panel + +Shipped 2026-11-10 (roadmap Track B). Branch `feature/speed`. Decisions 021, 026, 027, 033. + +## What it does +- **View switches stay in the browser.** List, board, and timeline read one client store. The URL + updates with `history.replaceState`; nothing goes to the server. +- **Live data without reloads.** The store polls `GET …/sync` every 5 s while the tab is visible + and on focus. Unchanged data is a 304 with no body. +- **Optimistic edits.** A status change (side panel or kanban drag) shows at once. If the server + refuses, the change rolls back and a notice says why. Each edit is undoable (`useTaskActions().undo`; + the `Cmd+Z` key arrives with Track C). +- **Side panel ("peek").** A click on a task opens it beside the list from the store, with no page + load. The description loads from the API; hovering a task prefetches it. A modified click (new + tab) still opens the full task page. +- **New tasks** join the store and open in the panel, with no page load. + +## How it works + +| File | Role | +|---|---| +| `packages/server/src/services/board-sync.ts` | `boardSnapshot()`, `snapshotEtag()`, `serializedSnapshot()`. | +| `packages/server/src/api/routes.ts` | `GET /workspaces/:id/sync`: 200 + ETag, or 304. | +| `apps/web/src/lib/board-store.ts` | `BoardStore`: base snapshot, pending patches, polling, undo stack. Framework-free. | +| `apps/web/src/lib/field-values.ts` | Field input ↔ form string ↔ cached value; `withField()` patches. | +| `apps/web/src/app/w/[workspaceId]/board-context.tsx` | `BoardProvider`, `useBoard()`, `useTaskActions()`, detail cache, notices. | +| `apps/web/src/app/w/[workspaceId]/workspace-board.tsx` | View switch, sync status, notices, panel. | +| `apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx` | The side panel; fields edit in place. | + +**No flicker back.** Pending edits stay layered over every snapshot until the server answers. A +poll that started before an edit finished is discarded, and the next poll fetches without an ETag. + +## Measured (2,000 tasks, local Chromium, `e2e/speed.spec.ts`) + +| Action | Time | Requests | +|---|---|---| +| Switch to list | 23 ms | none | +| Switch to board | 53 ms | none | +| Switch to timeline | 60 ms | none | +| Open a task in the panel | same frame; body after one API call | 1 (`GET tasks/:id`) | +| First poll after load | — | 1 (`/sync`, 304) | + +The roadmap budget is under 16 ms. Virtualized rows (roadmap B6) are the follow-up to reach it; +the test budget is 400 ms (`SWITCH_BUDGET_MS`) so slower CI machines pass. + +## Testing +- `api-tasks.test.ts` (both drivers): 401; 200 with private ETag headers; 304 on a match; a Member's + ETag differs from Read Only's; **leak test** — edits to a hidden issue, an unlinked repo's issue, + and a draft give Read Only a 304 while the Member gets 200; a visible edit gives 200; a role + change changes the snapshot. **Proven red:** hashing all cached issues fails the leak test. +- `board-store.test.ts`: optimistic apply, rollback, pending edit over a new snapshot, stale poll + discarded, ETag sent and 304 kept, tasks dropped when the snapshot drops them, one request for + concurrent polls, stable snapshot identity, undo; polling only while visible. +- `field-values.test.ts`: every field type; option names and iteration dates as the server stores. +- E2E `tasks.spec.ts` (exit check): Read Only's `/sync` has exactly the visible tasks and no hidden + title or id; the panel shows no edit controls and nothing hidden. +- E2E `speed.spec.ts`: first poll 304; view switches with no request (proven red before task-link + prefetch was turned off); panel without a page load; optimistic edit visible before a stubbed + 502, then rolled back with a notice; a stubbed success keeps the server's answer. + +## Gotchas +- **A server component cannot read plain data from a `"use client"` module**; it gets a client + reference. `VIEWS` lives in `views.ts`. +- **Next.js re-prefetches nav links after `history.replaceState`.** The speed test ignores + requests with `next-router-prefetch`; task links set `prefetch={false}`. +- **React commits after `click()` returns.** Time a view switch until the DOM has the rows (a + MutationObserver), not around `click()`. +- **The React Compiler lint rejects self-referencing `useCallback`s.** Task actions are plain + functions built once in `useMemo`. diff --git a/packages/server/src/api/routes.ts b/packages/server/src/api/routes.ts index 69afb38..4878bd0 100644 --- a/packages/server/src/api/routes.ts +++ b/packages/server/src/api/routes.ts @@ -18,6 +18,7 @@ import { installUrl, isInstanceAdmin, removeGitHubApp, startManifestFlow } from import { conflict, forbidden } from "../errors"; import { getWorkspaceLink, linkWorkspace, listLinkCandidates, MAX_LINKED_REPOS, unlinkWorkspace } from "../services/link"; import { createTask, getTask, listTasks, resolveMapping, setFieldMapping, updateTask } from "../services/tasks"; +import { serializedSnapshot } from "../services/board-sync"; import { updateWorkspaceSettings } from "../services/workspace-settings"; import { type RouteContext, createApiHandler, route } from "./router"; @@ -112,6 +113,20 @@ export const routes = [ }, }), + // The client store polls this (decision 033). 304 when nothing this viewer can see changed. + route({ + method: "GET", + pattern: "/workspaces/:workspaceId/sync", + async handler({ deps, session, params, request }) { + const access = await requireWorkspaceAccess(deps.database.db, session!.user.id, params.workspaceId!); + const { body, etag } = await serializedSnapshot(deps.database.db, access); + // Per-user data: no shared cache (a proxy or CDN) may store or reuse it. + const headers = { etag, "cache-control": "private, no-cache", vary: "Cookie" }; + if (request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers }); + return new Response(body, { status: 200, headers: { ...headers, "content-type": "application/json" } }); + }, + }), + route({ method: "GET", pattern: "/workspaces/:workspaceId/tasks/:itemId", diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 2e413c2..fa9dbdf 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -11,6 +11,7 @@ export { export { getSignupPolicy, setSignupPolicy, type SignupPolicy } from "./instance-settings"; export { signInEmail } from "./sign-in-email"; export { type ConfigIssue, type InstanceHealth, type RuntimeName, checkConfig, instanceHealth } from "./config-check"; +export { type BoardSnapshot, boardSnapshot, serializedSnapshot, snapshotEtag } from "./services/board-sync"; export { mayCreateUser } from "./signup"; export { ServiceError } from "./errors"; export { diff --git a/packages/server/src/services/board-sync.ts b/packages/server/src/services/board-sync.ts new file mode 100644 index 0000000..4227236 --- /dev/null +++ b/packages/server/src/services/board-sync.ts @@ -0,0 +1,38 @@ +import { can } from "@gitwork/core"; +import type { Db } from "@gitwork/db"; +import type { WorkspaceAccess } from "./access"; +import { type BoardView, listTasks } from "./tasks"; + +/** + * Everything a client needs to render a workspace's tasks (decision 033). Built from the same + * filtered read as GET /tasks, so it holds only what this viewer may see. + */ +export interface BoardSnapshot { + role: WorkspaceAccess["role"]; + canWrite: boolean; + board: BoardView; +} + +export async function boardSnapshot(db: Db, access: WorkspaceAccess): Promise { + return { + role: access.role, + canWrite: can(access.actor, "tasks.write", access.settings), + board: await listTasks(db, access), + }; +} + +/** + * A strong ETag over the exact bytes this viewer receives. A change only to items the viewer + * cannot see leaves the bytes, and so the ETag, unchanged: polling reveals nothing about them. + */ +export async function snapshotEtag(body: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)); + const b64 = btoa(String.fromCharCode(...new Uint8Array(digest))); + return `"${b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}"`; +} + +/** The serialized snapshot and its ETag, for the API route and the server-rendered page alike. */ +export async function serializedSnapshot(db: Db, access: WorkspaceAccess): Promise<{ body: string; etag: string }> { + const body = JSON.stringify(await boardSnapshot(db, access)); + return { body, etag: await snapshotEtag(body) }; +} diff --git a/packages/server/test/api-tasks.test.ts b/packages/server/test/api-tasks.test.ts index 2081b94..7cfd440 100644 --- a/packages/server/test/api-tasks.test.ts +++ b/packages/server/test/api-tasks.test.ts @@ -1,4 +1,5 @@ -import type { Database } from "@gitwork/db"; +import { type Database, ghIssues, ghProjectItems } from "@gitwork/db"; +import { eq } from "drizzle-orm"; import { type TestDriver, allTestDrivers } from "@gitwork/db/testing"; import { afterAll, beforeEach, describe, expect, it } from "vitest"; import type { ApiDeps } from "../src/api/router"; @@ -17,8 +18,8 @@ describe.each(drivers)("/api/v1 tasks on $name", (driver: TestDriver) => { let auth: ReturnType; const cookies: Record = {}; - function api(method: string, path: string, opts: { as?: string; body?: unknown } = {}) { - const headers = new Headers({ origin: BASE_URL }); + function api(method: string, path: string, opts: { as?: string; body?: unknown; headers?: Record } = {}) { + const headers = new Headers({ origin: BASE_URL, ...opts.headers }); if (opts.as) headers.set("cookie", cookies[opts.as]!); if (opts.body !== undefined) headers.set("content-type", "application/json"); return handleApiRequest( @@ -107,4 +108,64 @@ describe.each(drivers)("/api/v1 tasks on $name", (driver: TestDriver) => { // Reads never need GitHub. expect((await api("GET", "/tasks", { as: "max" })).status).toBe(200); }); + + // ---- /sync (decision 033) --------------------------------------------------------------------- + + const sync = (as: string, etag?: string) => api("GET", "/sync", { as, headers: etag ? { "if-none-match": etag } : {} }); + const setTitle = (nodeId: string, title: string) => database.db.update(ghIssues).set({ title }).where(eq(ghIssues.nodeId, nodeId)); + + it("sync: 401 without a session", async () => { + expect((await api("GET", "/sync")).status).toBe(401); + }); + + it("sync: serves the filtered snapshot with a private ETag, and 304 when nothing changed", async () => { + await link("jane"); + await api("PATCH", "/settings", { as: "jane", body: { hideLabel: "Internal" } }); + const res = await sync("rita"); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("private, no-cache"); + expect(res.headers.get("vary")).toBe("Cookie"); + const etag = res.headers.get("etag")!; + expect(etag).toMatch(/^"[A-Za-z0-9_-]{43}"$/); + const body = (await res.json()) as { role: string; canWrite: boolean; board: { tasks: { title: string }[] } }; + expect(body.role).toBe("read_only"); + expect(body.canWrite).toBe(false); + expect(body.board.tasks.map((t) => t.title).sort()).toEqual(["Homepage hero", "Pricing table"]); + + const again = await sync("rita", etag); + expect(again.status).toBe(304); + expect(await again.text()).toBe(""); + // The ETag is per viewer: a Member sees more, so the same ETag does not match. + expect((await sync("max", etag)).status).toBe(200); + }); + + it("sync: a change only to hidden or unlinked items gives Read Only a 304; a visible change gives 200", async () => { + await link("jane"); + await api("PATCH", "/settings", { as: "jane", body: { hideLabel: "Internal" } }); + const rita0 = (await sync("rita")).headers.get("etag")!; + const max0 = (await sync("max")).headers.get("etag")!; + + await setTitle("I_acme/site#2", "Internal pricing notes v2"); // hidden by label + await setTitle("I_acme/internal#1", "Secret roadmap v2"); // repo not linked + await database.db.update(ghProjectItems).set({ draftTitle: "Idea: light mode" }).where(eq(ghProjectItems.nodeId, "PVTI_draft")); + expect((await sync("rita", rita0)).status).toBe(304); + // The same edits are visible to a Member, so the Member's snapshot changes: the check can fail. + expect((await sync("max", max0)).status).toBe(200); + + await setTitle("I_acme/site#1", "Homepage hero v2"); // visible to everyone + const changed = await sync("rita", rita0); + expect(changed.status).toBe(200); + expect(changed.headers.get("etag")).not.toBe(rita0); + const body = (await changed.json()) as { board: { tasks: { title: string }[] } }; + expect(body.board.tasks.map((t) => t.title).sort()).toEqual(["Homepage hero v2", "Pricing table"]); + }); + + it("sync: a role change changes the snapshot", async () => { + await link("jane"); + const before = (await sync("rita")).headers.get("etag")!; + await api("PATCH", `/members/rita`, { as: "jane", body: { role: "member" } }); + const after = await sync("rita", before); + expect(after.status).toBe(200); + expect(((await after.json()) as { role: string; canWrite: boolean }).canWrite).toBe(true); + }); }); diff --git a/vitest.config.ts b/vitest.config.ts index 85bb715..d86c49f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,6 +6,8 @@ export default defineConfig({ { test: { name: "core", root: "packages/core", include: ["src/**/*.test.ts"] } }, { test: { name: "server", root: "packages/server", include: ["test/**/*.test.ts"], testTimeout: 30_000, hookTimeout: 60_000 } }, { test: { name: "db", root: "packages/db", include: ["test/**/*.test.ts"], testTimeout: 30_000, hookTimeout: 60_000 } }, + // Framework-free browser code (stores, keymap matching). Components are covered by Playwright. + { test: { name: "web", root: "apps/web", include: ["src/**/*.test.ts"] } }, ], }, });