mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI keeps company lists fresh from live task activity events > - The dashboard, the activity feed and board chat read the full company task list, and every burst of task activity refetches it > - One full list request costs the server 60 statements and 61-90 MB of allocation for 500 tasks, and the staging server is saturated by allocation and garbage collection > - This pull request moves those three views to the compact task index under its own key, and task activity refreshes that key at most once per 30 seconds > - The benefit is about one tenth of the server allocation per open dashboard tab while agents work, with the same rows on screen ## Linked Issues or Issue Description **What existing behavior does this improve?** The dashboard, the activity feed and board chat load the full company task list. Every burst of task activity refetches that list. **Subsystem affected** Board UI: live updates, the dashboard, the activity feed and board chat. **Current behavior** The three views read the full company task list (`GET /api/companies/:id/issues`, no view) with the key `["issues", companyId]`. `LiveUpdatesProvider` invalidates that key on every task activity event. Each open tab refetches the list at most every 5 seconds while agents work. One request costs the server 60 statements and 61-90 MB of allocation for 500 tasks (local measurement). The staging server allocates 57.6 MB per second and is saturated by garbage collection. **Proposed behavior** The views read only the fields they show, from the compact task index. Task activity from other people refreshes the index at most once per window. The viewer's own task changes refresh it at once. **Reason and benefit** Less server allocation and fewer statements per open tab, with the same rows on screen. **Breaking changes** None. No API, schema or server change. ## What Changed - The dashboard, the activity feed and board chat read `view=index` under a new key `issues.listIndex(companyId)`. - Task activity from other people refreshes that key at most once per 30 seconds (`TASK_INDEX_REFRESH_WINDOW_MS`). The viewer's own task activity refreshes it at once. The first event after a quiet window refetches at once. Later events in the window share one trailing refetch. Nothing from the event goes into the cache. An unwatched index is marked stale and refetches on the next mount. The user's own task changes still invalidate the whole `["issues", companyId]` prefix immediately. - The dashboard takes its ten recent tasks from the index, sorted by updatedAt as before. It reads the status glyph fields for those ten tasks from `issues/summaries`, because the index omits displayStatus and blockerAttention. - Toast and route lookups that read the full list cache also read the index cache. - `server/scripts/query-cost/` is the per-caller query cost harness used for the measurements below. It records the caller of each query at construction, the bytes allocated to build it, the rows it returns and the statements sent. ## Verification - `pnpm --filter @paperclipai/ui exec vitest run src/context/LiveUpdatesProvider src/pages/Dashboard.test.ts`: 261 pass. - Red/green: `LiveUpdatesProvider.task-index.test.ts` fails 6 of its first 10 cases against the provider on master and passes with this change. The tests cover a burst of events (4 index fetches in 90 seconds), the first event after a quiet window, a new task, a deleted task, a hidden task, a status/title/priority change, an event for a task outside the cache, an event for a task the viewer cannot read (nothing from the event goes into the cache), the viewer's own activity (refreshes at once), a task change made in this tab (refreshes at once through the company list invalidation), the trailing refresh (the last state shows when the window ends after activity stops), an unwatched index, and the live-event batcher path. - Other readers of `["issues", companyId]` (My Tasks, the task properties picker, the command palette, task detail cache writes, filtered and board-column lists) are not changed. The broad invalidation excludes only the new index key, so they refresh as before. A hidden tab keeps today's behavior: the live-event batcher still turns its refetches into stale marks. - Field parity (local, 1,500 tasks): the index returns the same 500 ids as the full list, with 0 differences in id, identifier, title, status, priority, createdAt, updatedAt and assigneeAgentId. It omits displayStatus and blockerAttention on all 500 rows, so the recent rows take those fields from summaries. - Real browser (headless Chromium, Playwright) against a local server from this branch, started with `test-drive --data-dir <scratch dir>`, which sets `PAPERCLIP_HOME` and `PAPERCLIP_CONFIG` to that directory: - Dashboard: the recent tasks and the "Tasks by Status" chart show the new tasks. The page sent 0 full-list requests, 2 index requests and 1 summaries request. - A task rename by this board user showed on the dashboard after 0.8 seconds, with 1 index refetch. - A second tab on the dashboard showed the same tasks. - Board chat loaded with 0 full-list requests and 3 index requests. Its activity feed showed the task names. - Not checked in the browser: activity from another actor. An agent key cannot edit a task without a heartbeat run context, so the window for other people's activity is covered by the unit tests only. - Nothing visual changed. The views keep their render code. Only their data source changed. - Cost per request (local, embedded PostgreSQL, Node 26, uninstrumented pass, 5 requests each), measured: `TSX_DISABLE_CACHE=1 UNITS=board ROUTES="issues list,issues list view=index,issues/summaries (10 ids)" REPEAT=5 NODE_OPTIONS=--expose-gc pnpm --filter @paperclipai/server exec tsx scripts/query-cost/drive.ts` | Request | Statements | Allocated | | --- | --- | --- | | full list | 60 | 61-90 MB | | view=index | 12 | 22-37 MB | | summaries, 10 ids | 23 | 2.8 MB | The ranges show the difference between runs. - Estimate, not measured: per open dashboard tab with continuous task activity, before about 13 MB/s (one full list per 5 seconds), after about 1.3 MB/s (one index per 30 seconds and one 10-id summaries request per 5 seconds). At the day-1 staging route rate (0.116 full lists per second) that is about 6.5 MB/s less. The real rate of task activity events on staging is not measured. ## Risks - Freshness: the dashboard's task charts and recent-task order, the activity feed's task names and board chat's task lookup can lag task activity from other people by up to 30 seconds. The status glyphs of the ten recent tasks stay on the 5-second lane. The viewer's own task changes refresh at once. The window is one constant, `TASK_INDEX_REFRESH_WINDOW_MS` in `LiveUpdatesProvider.tsx`, so a different value is a one-line change. - The index returns the same rows as the full list, so the charts count the same tasks. - The recent-task rows have no task description. The rows do not show it. - My Tasks, the task properties picker and the command palette still read the full list. They are not in this change. ## Model Used - Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (no documentation describes this behavior) - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
310 lines
10 KiB
TypeScript
310 lines
10 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { existsSync, readFileSync } from "node:fs";
|
|
import path from "node:path";
|
|
import { act, forwardRef, useImperativeHandle } from "react";
|
|
import type { ReactNode } from "react";
|
|
import { createRoot, type Root } from "react-dom/client";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { BoardChat } from "./BoardChat";
|
|
|
|
/**
|
|
* Regression coverage for the post-wizard Conference Room intro (PAP-134,
|
|
* plan: PAP-133 A+B): a fresh mount shows the three-dot typing bubble for
|
|
* ~2s, then the CEO welcome, then the suggestion chips ~700ms later. The
|
|
* staged reveal must hold while the onboarding wizard overlay is open or
|
|
* the tab is hidden, and must fast-forward when the user already replied.
|
|
*/
|
|
|
|
const mockAgentsApi = vi.hoisted(() => ({ list: vi.fn() }));
|
|
const mockGoalsApi = vi.hoisted(() => ({ list: vi.fn() }));
|
|
const mockIssuesApi = vi.hoisted(() => ({
|
|
listCompact: vi.fn(),
|
|
listComments: vi.fn(),
|
|
listFeedbackVotes: vi.fn(),
|
|
}));
|
|
const mockDialogState = vi.hoisted(() => ({ onboardingOpen: false }));
|
|
|
|
vi.mock("../api/agents", () => ({ agentsApi: mockAgentsApi }));
|
|
vi.mock("../api/goals", () => ({ goalsApi: mockGoalsApi }));
|
|
vi.mock("../api/issues", () => ({ issuesApi: mockIssuesApi }));
|
|
|
|
vi.mock("../context/CompanyContext", () => ({
|
|
useCompany: () => ({
|
|
selectedCompanyId: "company-1",
|
|
selectedCompany: { id: "company-1", name: "Acme Robotics", issuePrefix: "PAP" },
|
|
}),
|
|
}));
|
|
|
|
vi.mock("../context/BreadcrumbContext", () => ({
|
|
useBreadcrumbs: () => ({ setBreadcrumbs: vi.fn() }),
|
|
}));
|
|
|
|
vi.mock("../context/DialogContext", () => ({
|
|
useDialogState: () => ({ onboardingOpen: mockDialogState.onboardingOpen }),
|
|
}));
|
|
|
|
// Heavy children that are irrelevant to the staged intro.
|
|
vi.mock("../components/ActivityFeed", () => ({
|
|
ActivityFeed: () => <div data-testid="activity-feed" />,
|
|
}));
|
|
vi.mock("../components/MarkdownBody", () => ({
|
|
MarkdownBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
|
}));
|
|
vi.mock("../components/ChatComposer", () => ({
|
|
ChatComposer: forwardRef((_props, ref) => {
|
|
useImperativeHandle(ref, () => ({ focus: vi.fn() }));
|
|
return <div data-testid="chat-composer" />;
|
|
}),
|
|
}));
|
|
vi.mock("../components/AgentBubbleActionRow", () => ({
|
|
AgentBubbleActionRow: () => null,
|
|
agentBubbleDateLabel: () => "",
|
|
}));
|
|
vi.mock("../components/AgentIconPicker", () => ({
|
|
AgentIcon: () => null,
|
|
}));
|
|
vi.mock("@/components/ui/tooltip", () => ({
|
|
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
|
|
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
|
|
TooltipContent: () => null,
|
|
}));
|
|
vi.mock("@/components/ui/sheet", () => ({
|
|
Sheet: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
|
SheetTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
|
|
SheetContent: () => null,
|
|
}));
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
|
|
|
class ResizeObserverStub {
|
|
observe() {}
|
|
unobserve() {}
|
|
disconnect() {}
|
|
}
|
|
|
|
const CEO_AGENT = {
|
|
id: "agent-ceo",
|
|
name: "Alex",
|
|
role: "ceo",
|
|
status: "active",
|
|
icon: null,
|
|
};
|
|
const BOARD_ISSUE = { id: "issue-board", title: "Board Operations", status: "in_progress" };
|
|
const USER_COMMENT = {
|
|
id: "comment-user-1",
|
|
body: "Hi Alex!",
|
|
authorAgentId: null,
|
|
authorUserId: "user-1",
|
|
createdAt: "2026-06-10T00:00:00.000Z",
|
|
};
|
|
|
|
function hasTypingDots(container: HTMLElement) {
|
|
return container.querySelectorAll(".typing-dots").length > 0;
|
|
}
|
|
|
|
function hasWelcome(container: HTMLElement) {
|
|
return (container.textContent ?? "").includes("Welcome to");
|
|
}
|
|
|
|
function hasChips(container: HTMLElement) {
|
|
return (container.textContent ?? "").includes("Draft an Organization Brief");
|
|
}
|
|
|
|
describe("BoardChat staged typing intro", () => {
|
|
let container: HTMLDivElement;
|
|
let root: Root | null = null;
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.stubGlobal("ResizeObserver", ResizeObserverStub);
|
|
container = document.createElement("div");
|
|
document.body.appendChild(container);
|
|
mockDialogState.onboardingOpen = false;
|
|
mockAgentsApi.list.mockResolvedValue([CEO_AGENT]);
|
|
mockGoalsApi.list.mockResolvedValue([
|
|
{ id: "goal-1", title: "Build affordable robots", status: "active" },
|
|
]);
|
|
mockIssuesApi.listCompact.mockResolvedValue([BOARD_ISSUE]);
|
|
mockIssuesApi.listComments.mockResolvedValue([]);
|
|
mockIssuesApi.listFeedbackVotes.mockResolvedValue([]);
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await act(async () => {
|
|
root?.unmount();
|
|
});
|
|
root = null;
|
|
container.remove();
|
|
sessionStorage.clear();
|
|
vi.unstubAllGlobals();
|
|
vi.useRealTimers();
|
|
vi.clearAllMocks();
|
|
// Drop any per-test document.visibilityState override.
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
delete (document as any).visibilityState;
|
|
});
|
|
|
|
let queryClient: QueryClient | null = null;
|
|
|
|
function buildElement() {
|
|
// A fresh element every time — rendering an identical element reference
|
|
// lets React bail out of re-rendering, which would hide mock-state flips.
|
|
return (
|
|
<QueryClientProvider client={queryClient!}>
|
|
<BoardChat />
|
|
</QueryClientProvider>
|
|
);
|
|
}
|
|
|
|
async function render() {
|
|
queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: false } },
|
|
});
|
|
root = createRoot(container);
|
|
await act(async () => {
|
|
root!.render(buildElement());
|
|
});
|
|
// Let the agent/goal/issue queries resolve, plus the follow-up render
|
|
// that enables the comments query off boardIssueId. react-query batches
|
|
// notifications through zero-delay timers, so flush those too.
|
|
for (let i = 0; i < 6; i++) {
|
|
await act(async () => {
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Re-render the existing tree so hooks re-read mutated mock state. */
|
|
async function rerender() {
|
|
await act(async () => {
|
|
root!.render(buildElement());
|
|
});
|
|
await act(async () => {
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
|
|
async function advance(ms: number) {
|
|
await act(async () => {
|
|
await vi.advanceTimersByTimeAsync(ms);
|
|
});
|
|
await act(async () => {
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
});
|
|
}
|
|
|
|
it("reveals typing dots, then the welcome at 2s, then chips at +700ms", async () => {
|
|
await render();
|
|
|
|
// Fresh mount: dots only.
|
|
expect(hasTypingDots(container)).toBe(true);
|
|
expect(hasWelcome(container)).toBe(false);
|
|
|
|
// Just before the reveal: still dots.
|
|
await advance(1900);
|
|
expect(hasTypingDots(container)).toBe(true);
|
|
expect(hasWelcome(container)).toBe(false);
|
|
|
|
// t=2s: welcome bubble lands, dots leave, chips not yet.
|
|
await advance(100);
|
|
expect(hasWelcome(container)).toBe(true);
|
|
expect(hasTypingDots(container)).toBe(false);
|
|
expect(hasChips(container)).toBe(false);
|
|
|
|
// t=2.7s: chips stage in.
|
|
await advance(700);
|
|
expect(hasChips(container)).toBe(true);
|
|
});
|
|
|
|
it("skips the staged reveal when a user comment already exists", async () => {
|
|
mockIssuesApi.listComments.mockResolvedValue([USER_COMMENT]);
|
|
await render();
|
|
|
|
// Fast-forwarded: no dots, welcome immediately, no timer needed.
|
|
expect(hasTypingDots(container)).toBe(false);
|
|
expect(hasWelcome(container)).toBe(true);
|
|
});
|
|
|
|
it("holds the dots while the onboarding wizard overlay is open (PAP-134)", async () => {
|
|
mockDialogState.onboardingOpen = true;
|
|
await render();
|
|
|
|
// The 2s window must not burn behind the wizard overlay.
|
|
await advance(2500);
|
|
expect(hasTypingDots(container)).toBe(true);
|
|
expect(hasWelcome(container)).toBe(false);
|
|
|
|
// Wizard closes → reveal timer starts fresh.
|
|
mockDialogState.onboardingOpen = false;
|
|
await rerender();
|
|
await advance(2000);
|
|
expect(hasWelcome(container)).toBe(true);
|
|
expect(hasTypingDots(container)).toBe(false);
|
|
});
|
|
|
|
it("holds the dots while the document is hidden (PAP-134)", async () => {
|
|
let visibility: DocumentVisibilityState = "hidden";
|
|
Object.defineProperty(document, "visibilityState", {
|
|
configurable: true,
|
|
get: () => visibility,
|
|
});
|
|
await render();
|
|
|
|
// The 2s window must not burn while the tab is hidden.
|
|
await advance(2500);
|
|
expect(hasTypingDots(container)).toBe(true);
|
|
expect(hasWelcome(container)).toBe(false);
|
|
|
|
// Tab becomes visible → reveal timer starts fresh.
|
|
visibility = "visible";
|
|
await act(async () => {
|
|
document.dispatchEvent(new Event("visibilitychange"));
|
|
});
|
|
await advance(2000);
|
|
expect(hasWelcome(container)).toBe(true);
|
|
expect(hasTypingDots(container)).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("typing-dots CSS animation guard (PAP-54 failure mode)", () => {
|
|
// PAP-54: the .typing-dots CSS block was silently dropped from index.css
|
|
// during a theme migration, leaving static markup with no animation. Guard
|
|
// the source so the block can't vanish again without failing a test. The
|
|
// browser-computed `animationName !== "none"` assertion lives in
|
|
// tests/e2e/conference-room-typing-intro.spec.ts.
|
|
// Locate ui/src/index.css regardless of whether vitest runs from ui/ or
|
|
// the workspace root (import.meta.url is an http URL under jsdom, and the
|
|
// css pipeline swallows `?raw` imports — plain fs is the reliable path).
|
|
function readIndexCss(): string {
|
|
let dir = process.cwd();
|
|
for (let depth = 0; depth < 6; depth++) {
|
|
for (const candidate of [
|
|
path.join(dir, "src/index.css"),
|
|
path.join(dir, "ui/src/index.css"),
|
|
]) {
|
|
if (existsSync(candidate)) return readFileSync(candidate, "utf8");
|
|
}
|
|
dir = path.dirname(dir);
|
|
}
|
|
throw new Error("ui/src/index.css not found from " + process.cwd());
|
|
}
|
|
const css = readIndexCss();
|
|
|
|
it("keeps the bounce animation wired to .typing-dots span", () => {
|
|
const spanRules = [...css.matchAll(/\.typing-dots span\s*\{[^}]*\}/g)].map(
|
|
(m) => m[0],
|
|
);
|
|
expect(spanRules.length).toBeGreaterThan(0);
|
|
expect(
|
|
spanRules.some((rule) => /animation:\s*typing-bounce/.test(rule)),
|
|
).toBe(true);
|
|
});
|
|
|
|
it("keeps the typing-bounce keyframes", () => {
|
|
expect(css).toMatch(/@keyframes typing-bounce\s*\{/);
|
|
});
|
|
});
|