perf(ui): speed up Tasks and Inbox startup (#18492)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Tasks and Inbox are the main entry points for that work.
> - Earlier changes made their data reads and row counts smaller.
> - Those changes remain, but shared controls now pull in the whole
task-detail bundle.
> - A cold open can also read a remembered organization before selecting
the one in the URL.
> - This pull request separates collection code and selects the
addressed organization first.
> - It warms task code after collection paint, so the next task open
stays fast.

## Linked Issues or Issue Description

Refs #17756, #18323, #16849, #17041, #17983, #17960, #18461.

**What happened?**

Tasks and Inbox still use their optimized index reads and row budgets.
However, small shared controls and hooks were placed in the task-detail
chunk. A collection had to download that whole chunk. The HTML also
preloaded it on every route. The original production profile loaded
about 6.5 MB of decoded JavaScript before useful rows, or 1.9 MB
transferred with compression.

Company bootstrap could select a different remembered organization
before Layout selected the URL's organization. This started unnecessary
company reads. A retained multi-company browser fixture reproduced two
attention-count requests for different companies.

**Expected behavior**

Show correctly scoped, stable collection rows without waiting for
task-detail code. Keep compact reads, bounded rendering, direct task
preloading, immediate New Task input, and fast follow-on navigation.

**Steps to reproduce**

1. Use a production UI build with Coordinator enabled and two active
organizations.
2. Remember one organization, then cold-open Tasks or Mine in the other.
3. Inspect startup script and company requests before the first useful
row.

The baseline UI revision is `91fdf02e95`. This is a UI change. It has no
API, schema, migration, or authorization changes.

## What Changed

- Group the static collection dependency trees above the task-detail
group. Keep the existing startup and task grouping strategy.
- Preload task detail and its static dependency closure early on direct
task and agent-chat URLs. Keep collection aliases out of that preload.
- Fetch the immutable task chunk at low priority after a collection
paints, or on a same-origin task-link hint. After a successful immutable
response is fully read, module-preload the cached chunk so it can
compile without executing. A failed HTTP probe skips module preload.
- Prefer an addressed active organization during bootstrap. Preserve
manual selection, archived-company handling, and account-scoped company
lists.
- Preserve a task reading anchor when a programmatic scroll event
reports an unchanged offset during restore reflow. Strengthen the Back
journey to wait for a completed collection navigation.
- Add production-browser checks for delayed indexes, correct company
scope, stable row geometry, failed speculation, and early direct-task
preload. Update collection verification notes and the feature map.

## Verification

Final source: `e402ab7fc6`; baseline UI: `91fdf02e95`.

- All **234 focused unit cases** and **44 production-browser journeys**
passed on the final source: 33 task journeys and 11 collection journeys.
Coverage includes compact history, saved cards, draft persistence,
avatar continuity, failed-probe recovery, delayed data, pagination, deep
links, desktop/mobile and reading-position restoration through Back.
Desktop and mobile screenshots were inspected.
- Workspace typecheck, full production build, map checks, token gates
and diff checks passed. The default local `pnpm test:run` still stops
before executing tests because the existing chat-test line selector
reports `No test found` (1,816 skipped). This is not a passed full local
test suite. Focused tests and remote CI remain separate evidence.
- Greptile reviewed the exact final commit at **5/5**, with zero open
review threads. Final code CI passed. The complete check inventory is
**55 successful, 3 skipped, 1 neutral**. The neutral result is the
separate Paperclip Review: its agent finished without completing an
assessment, so it is not a passing review score.

Five alternating baseline/candidate pairs per scenario, Chromium
151.0.7922.34, 1440×900, 4× CPU, 50ms latency, approximately 9Mbps down
/ 1.5Mbps up. Cold cases use fresh browser contexts with normal cache
writes enabled; warm cases use the same context and normal application
query cache. Both previews use the server's immutable hashed-asset cache
policy and uncached HTML, with real local feature settings and no
request interception. All task-owned builds and suites were stopped
during timing; other host activity was uncontrolled. Readiness requires
useful rows and editable search, or the readable task thread and
editable composer, followed by two animation frames.

| Journey | Baseline median (range) | PR median (range) | Median paired
saving |
| --- | --- | --- | --- |
| Cold Tasks | 3239 ms (3189–3333) | 2545 ms (2441–2682) | +752 ms |
| Cold Inbox | 3207 ms (3203–3268) | 2679 ms (2502–3062) | +541 ms |
| Warm Inbox | 717 ms (701–917) | 760 ms (745–768) | -47 ms |
| Warm Tasks | 1150 ms (1126–1207) | 1136 ms (1119–1174) | +18 ms |
| First task click | 943 ms (932–1008) | 1007 ms (976–1098) | -74 ms |
| Back to Tasks | 584 ms (568–617) | 566 ms (559–575) | +10 ms |
| Cold direct task control | 3389 ms (3377–3402) | 3415 ms (3395–3896) |
-13 ms |

All five pairs improved for each cold collection. The signed saving is
baseline minus candidate for each pair; it is distinct from the
difference of medians. Warm navigation is broadly similar. First task
click was 74ms slower by median paired difference. Direct-task median
paired difference was 13ms slower, with one slower 3.90s candidate
sample retained in the range; this is not a claimed direct-task speedup.

Completed script transfers by collection readiness fell from about
**1.91MB to 1.14MB** (Tasks), and **1.90MB to 1.14MB** (Inbox). Task
code warms after rows paint. At the test bandwidth, the removed 0.77MB
critical transfer represents roughly 0.65s of download time; CPU and
network overlap, so their savings are not added. Unthrottled loopback
API control medians stayed about 17–18ms in both variants. All 30 cold
samples had zero browser errors.

Rejected experiments remain separate: automatic splitting produced over
200 startup requests; disabling recursive grouping slowed direct tasks;
HTTP-only warming improved collection startup but slowed first task
opens. The final correction preloads direct dependencies and compiles
successfully cached code after paint. Routing disables HTTP caching, so
intercepted runs were kept as diagnostic evidence rather than used for
warm-cache acceptance; see [Playwright's cache
behavior](https://playwright.dev/docs/api/class-page#page-route). Vite
preview's default asset `no-cache` policy was also corrected to match
the shipped server before final measurement.


## Risks

- Bundle placement affects shared consumers. Browser checks cover
collections and task navigation; the full PR checks also cover other
routes.
- Code warming still transfers the task chunk if the user stays on a
populated collection. It moves that download past first paint and does
not execute it. This is a startup latency improvement, not a claim that
all eventual bytes disappear.
- A direct click before warming finishes still loads code on demand.
Direct task and chat URLs retain early module preload.
- Local browser evidence does not establish a deployed staging speedup.
This PR does not merge or deploy itself.

## Model Used

OpenAI GPT-6 (Codex), with reasoning, tool use and local code execution.
The context-window size is not exposed in this environment.

## 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 the relevant tests locally and they pass (234 unit
cases and 44 browser journeys; the full-command limitation is documented
above)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All code CI gates are green (the separate Paperclip Review is
neutral because its agent did not complete an assessment)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-31 22:12:41 -05:00
1 parent 34f8d25089
commit d38cdf261a
21 files changed
+382 -34

No files matched your search

+5
View File
@@ -98,6 +98,11 @@ owns a compact complete task-ID index. Navigation reuses either page response. C
the instance Streamlined UI setting is off. The loopback browser checks in
[collection startup](../../tests/perf/collections/startup.spec.ts) exercise these
reads and the initial task row budget. They do not establish deployed latency.
Collection startup selects the addressed active organization before starting
company reads. Shared controls load separately from task detail. A painted
collection or task-link intent starts a low-priority code fetch; direct task URLs keep
early module preload. The collection
browser cases cover a remembered different organization and failed speculation.
The [Inbox component checks](../../ui/src/pages/Inbox.test.tsx) cover the source
barrier and selected-source query; [badge tests](../../server/src/__tests__/inbox-dismissals.test.ts)
cover unread counts. Browser timing and layout proof remain separate from these tests.
+1 -1
View File
@@ -63,7 +63,7 @@ test("a refreshed company consumer reads the retained provider", async ({ page }
const body = pathname === "/api/auth/get-session"
? { user: { id: "test-user" }, session: { userId: "test-user" } }
: pathname === "/api/companies"
? [{ id: "test-company", name: "Test company", status: "active" }]
? [{ id: "test-company", name: "Test company", issuePrefix: "TST", status: "active" }]
: [];
await route.fulfill({ json: body });
});
+18
View File
@@ -22,3 +22,21 @@ attention task index. Screenshots and failure traces stay in `test-results`.
Request counts and row budgets are acceptance checks. They do not establish an
end-to-end latency improvement. Measure cold, warm, and Back timings separately
with the same fixture, assets, cache, viewport, and CPU/network settings.
Startup cases also check that shared collection controls do not require the
task-detail bundle before reveal, even when a different organization is remembered.
Code warms after the collection paints, or on task-link intent. A successful
immutable response allows module preloading to compile the cached chunk without
executing it. A failed fetch leaves the collection usable and permits navigation
without a document reload. Direct task URLs preload their static dependencies
while identity is pending. These cases must run with
production assets: development modules do not exercise the bundle boundaries.
The functional cases route feature settings and delayed responses. Routing
disables browser HTTP caching. For warm-cache timings, set the real local feature
settings and use fresh browser contexts without request interception. Keep normal
cache writes enabled so code warmed after paint can be used on the next task open.
Retain intercepted runs as separate diagnostic evidence.
Match the server's hashed asset cache policy (`public, max-age=31536000, immutable`);
Vite preview's default `no-cache` policy adds revalidation that the shipped server
does not require. Keep HTML uncached and return 404 for missing assets.
+20 -5
View File
@@ -1,8 +1,25 @@
import fs from "node:fs/promises";
import { expect, type APIRequestContext, type Page } from "@playwright/test";
export type CollectionFixture = { company: { id: string; issuePrefix: string }; taskIds: string[] };
export type CollectionFixture = { company: { id: string; issuePrefix: string }; taskIds: string[]; otherCompanyId?: string };
export const fixturePath = "test-results/collections/fixture.json";
async function retainOtherCompany(request: APIRequestContext, fixture: CollectionFixture): Promise<CollectionFixture> {
const response = await request.get("/api/companies");
expect(response.ok(), await response.text()).toBeTruthy();
const companies = await response.json() as Array<{ id: string; name: string; status: string }>;
const other = companies.find(company => company.id === fixture.otherCompanyId && company.id !== fixture.company.id && company.status !== "archived")
?? companies.find(company => company.name === "Other collection organization" && company.id !== fixture.company.id && company.status !== "archived");
let otherCompanyId = other?.id;
if (!otherCompanyId) {
const created = await request.post("/api/companies", { data: { name: "Other collection organization" } });
expect(created.ok(), await created.text()).toBeTruthy();
otherCompanyId = (await created.json()).id;
}
const retained = { ...fixture, otherCompanyId };
await fs.mkdir("test-results/collections", { recursive: true });
await fs.writeFile(fixturePath, JSON.stringify(retained));
return retained;
}
export async function collectionFixture(request: APIRequestContext): Promise<CollectionFixture> {
const saved = await fs.readFile(fixturePath, "utf8").then(JSON.parse).catch(error => {
if (error.code !== "ENOENT") throw error;
@@ -10,7 +27,7 @@ export async function collectionFixture(request: APIRequestContext): Promise<Col
});
if (saved) {
const existing = await request.get(`/api/companies/${saved.company.id}`);
if (existing.ok()) return saved;
if (existing.ok()) return retainOtherCompany(request, saved);
expect(existing.status(), await existing.text()).toBe(404);
}
const created = await request.post("/api/companies", { data: { name: "Collection performance fixture" } });
@@ -34,9 +51,7 @@ export async function collectionFixture(request: APIRequestContext): Promise<Col
expect(response.ok(), await response.text()).toBeTruthy();
}));
const fixture = { company, taskIds };
await fs.mkdir("test-results/collections", { recursive: true });
await fs.writeFile(fixturePath, JSON.stringify(fixture));
return fixture;
return retainOtherCompany(request, fixture);
}
export async function coordinatorPreference(page: Page, streamlined = true) {
await page.route("**/api/workspace-preferences/me", async route => {
+86 -1
View File
@@ -2,7 +2,59 @@ import { expect, test } from "@playwright/test";
import { collectionFixture, coordinatorPreference, type CollectionFixture } from "./fixture";
let fixture: CollectionFixture;
test.beforeAll(async ({ request }) => { fixture = await collectionFixture(request); });
let otherCompanyId: string;
test.beforeAll(async ({ request }) => {
fixture = await collectionFixture(request);
expect(fixture.otherCompanyId).toBeTruthy();
otherCompanyId = fixture.otherCompanyId!;
});
test("repeated fixture setup retains both companies without growing the instance", async ({ request }) => {
const before = await (await request.get("/api/companies")).json();
const again = await collectionFixture(request);
const after = await (await request.get("/api/companies")).json();
expect(again.company.id).toBe(fixture.company.id);
expect(again.otherCompanyId).toBe(otherCompanyId);
expect(after.map((company: { id: string }) => company.id).sort()).toEqual(before.map((company: { id: string }) => company.id).sort());
});
for (const route of ["issues", "inbox/mine"]) test(`${route} leaves task-detail code out of collection startup`, async ({ page }) => {
await coordinatorPreference(page);
await page.addInitScript(id => localStorage.setItem("paperclip.selectedCompanyId", id), otherCompanyId);
const detailReads: string[] = [];
const companyReads: string[] = [];
page.on("request", request => {
if (/\/assets\/issue-detail-[^/]+\.js$/.test(request.url())) detailReads.push(request.url());
const companyId = new URL(request.url()).pathname.match(/^\/api\/companies\/([^/]+)\//)?.[1];
if (companyId) companyReads.push(companyId);
});
let release!: () => void;
const held = new Promise<void>(resolve => { release = resolve; });
const isIndex = (url: URL) => url.pathname === `/api/companies/${fixture.company.id}/issues` && url.searchParams.get("view") === "index";
await page.route(isIndex, async request => { await held; await request.continue(); });
const indexRequest = page.waitForRequest(request => isIndex(new URL(request.url())));
const warmed = page.waitForResponse(response => /\/assets\/issue-detail-[^/]+\.js$/.test(response.url()));
try {
await page.goto(`/${fixture.company.issuePrefix}/${route}`);
await indexRequest;
expect(detailReads).toEqual([]);
} finally { release(); }
const first = page.getByRole("main").locator("[data-inbox-issue-link]").first();
await expect(first).toBeVisible();
const node = await first.elementHandle();
const before = await first.boundingBox();
await (await warmed).finished();
const after = await first.boundingBox();
expect(await node!.evaluate(element => element.isConnected)).toBe(true);
expect(Math.abs(before!.y - after!.y)).toBeLessThan(1);
expect(Math.abs(before!.height - after!.height)).toBeLessThan(1);
expect(new Set(companyReads)).toEqual(new Set([fixture.company.id]));
await first.focus();
await first.press("Enter");
await expect(page.getByTestId("task-chat-thread").locator(':scope > [aria-busy="false"]')).toBeVisible();
await expect(page.getByTestId("issue-detail-header")).toBeVisible();
await expect(page.getByTestId("task-chat-composer-stack").locator('[contenteditable="true"]')).toBeEditable();
});
for (const mobile of [false, true]) test(`Tasks use a bounded render and a shared count on ${mobile ? "mobile" : "desktop"}`, async ({ page }) => {
if (mobile) await page.setViewportSize({ width: 390, height: 844 });
await coordinatorPreference(page);
@@ -26,6 +78,39 @@ for (const mobile of [false, true]) test(`Tasks use a bounded render and a share
await page.screenshot({ path: test.info().outputPath("tasks.png") });
});
test("a failed speculative preload keeps the collection usable and permits task navigation", async ({ page }) => {
await coordinatorPreference(page);
let navigations = 0;
page.on("request", request => { if (request.isNavigationRequest() && request.frame() === page.mainFrame()) navigations++; });
const pattern = /\/assets\/issue-detail-[^/]+\.js$/;
await page.route(pattern, route => route.abort("failed"));
const failure = page.waitForEvent("requestfailed", request => pattern.test(request.url()));
await page.goto(`/${fixture.company.issuePrefix}/issues`);
const first = page.getByRole("main").locator("[data-inbox-issue-link]").first();
await expect(first).toBeVisible();
await first.focus();
await failure;
await expect(page.getByRole("textbox", { name: "Search tasks", exact: true })).toBeEditable();
expect(navigations).toBe(1);
await page.unroute(pattern);
await first.press("Enter");
await expect(page.getByTestId("task-chat-composer-stack").locator('[contenteditable="true"]')).toBeEditable();
expect(navigations).toBe(1);
});
test("direct task opens preload their code while identity is still loading", async ({ page }) => {
await coordinatorPreference(page);
let release!: () => void;
const held = new Promise<void>(resolve => { release = resolve; });
await page.route("**/api/auth/get-session", async route => { await held; await route.continue(); });
try {
const detailRequest = page.waitForRequest(request => /\/assets\/issue-detail-[^/]+\.js$/.test(request.url()));
await page.goto(`/${fixture.company.issuePrefix}/issues/${fixture.taskIds[0]}`);
await detailRequest;
} finally { release(); }
await expect(page.getByTestId("task-chat-composer-stack").locator('[contenteditable="true"]')).toBeEditable();
});
test("Coordinator Inbox retains index reads when Streamlined UI is disabled", async ({ page }) => {
await coordinatorPreference(page, false);
const reads: URL[] = [];
@@ -95,9 +95,14 @@ test("Inbox click reveals once after reordered initial responses; refresh retain
});
test("reading anchor survives late media, composer resizing, older history and browser Back", async ({ page }) => {
await page.route("**/api/workspace-preferences/me", async route => {
const response = await route.fetch();
await route.fulfill({ json: { ...await response.json(), coordinatorWorkspaceEnabled: false } });
});
await installMeasurements(page);
await page.goto(`/${prefix}/issues/${issue.identifier}`);
await ready(page);
await expect(page.getByRole("button", { name: "Hide properties", exact: true })).toBeVisible();
const scroller = page.getByTestId("task-chat-scroller");
await page.getByRole("button", { name: "More messages", exact: true }).click();
await expect(page.getByText("Historical message 10", { exact: true })).toBeAttached();
@@ -134,6 +139,9 @@ test("reading anchor survives late media, composer resizing, older history and b
await expect.poll(async () => Math.abs(await offset() - anchor.top)).toBeLessThanOrEqual(2);
await page.getByRole("link", { name: "Tasks", exact: true }).first().click();
await page.waitForURL(`**/${prefix}/issues`);
await expect(page.getByRole("main").getByRole("textbox", { name: "Search tasks", exact: true })).toBeEditable();
await expect(page.getByTestId("task-chat-thread")).toHaveCount(0);
await page.goBack();
await ready(page);
await expect.poll(async () => Math.abs(await offset() - anchor.top)).toBeLessThanOrEqual(2);
+2
View File
@@ -1,4 +1,5 @@
import { useIssueRowDetails } from "../hooks/useIssueRowDetails";
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
import { IssueRowDetailsNotice } from "./IssueRowDetailsNotice";
import { useShowAgentCreatedTasks } from "../hooks/useShowAgentCreatedTasks";
import { useIssueHierarchyContext } from "../hooks/useIssueHierarchyContext";
@@ -1324,6 +1325,7 @@ function StreamlinedIssuesList({
// Resolve the initial tree before reveal: inserting ancestors/children later would move rows.
// Hierarchy queries retain existing context during subsequent reads.
const collectionLoading = Boolean(isLoading || externalObjectFilterLoading || (hierarchyEnabled && hierarchy.isLoading));
useWarmTaskDetailCode(!collectionLoading && !error && filtered.length > 0);
const baseGroupedContent = useMemo(() => {
if (viewState.groupBy === "none") {
return [{ key: "__all", label: null as string | null, items: filtered }];
+2
View File
@@ -1,4 +1,5 @@
import { saveTaskCollectionPreferences } from "../lib/task-collection-preferences";
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
import { useShowAgentCreatedTasks } from "../hooks/useShowAgentCreatedTasks";
import { useIssueHierarchyContext } from "../hooks/useIssueHierarchyContext";
import { includeIssueHierarchyContext } from "../lib/issue-hierarchy-context";
@@ -1219,6 +1220,7 @@ export function IssuesList({
hierarchyEnabled,
hierarchyRowBudget,
);
useWarmTaskDetailCode(!isLoading && !error && (!hierarchyEnabled || !hierarchy.isLoading) && filtered.length > 0);
const baseGroupedContent = useMemo(() => {
if (viewState.groupBy === "none") {
return [{ key: "__all", label: null as string | null, items: filtered }];
@@ -211,6 +211,10 @@ describe("TaskMessageScroller", () => {
width = 500; rowTop = 80;
for (const callback of resize) callback();
expect(scroller().scrollTop).toBe(130);
rowTop = 70;
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
for (const callback of resize) callback();
expect(scroller().scrollTop).toBe(120);
width = 600; rowTop = 60;
await dispatch(scroller(), new Event("scroll", { bubbles: true }));
for (const callback of resize) callback();
@@ -191,6 +191,7 @@ export function TaskMessageScroller({ children, contentKey, className, scrolling
const handleScroll = useCallback(() => {
if (!ref.current?.clientHeight) return;
const top = ref.current.scrollTop;
const moved = top !== previousScrollTop.current;
const scrollingUp = top < previousScrollTop.current;
previousScrollTop.current = top;
if ((scrollingUp || upwardIntent.current) && top <= 192 && !easingRef.current) requestEarlierHistory();
@@ -213,11 +214,11 @@ export function TaskMessageScroller({ children, contentKey, className, scrolling
pinnedRef.current = true;
hidePill();
}
rememberAnchor();
rememberAnchor(moved);
return;
}
pinnedRef.current = pinned;
rememberAnchor();
rememberAnchor(moved);
if (pinned) hidePill();
else showPill();
}, [
+40
View File
@@ -87,6 +87,24 @@ function Probe({ onSelectedCompanyId }: { onSelectedCompanyId: (companyId: strin
}
describe("resolveBootstrapCompanySelection", () => {
it("boots the addressed company before the remembered company", () => {
expect(resolveBootstrapCompanySelection({
companies: [activeCompany, secondActiveCompany], sidebarCompanies: [activeCompany, secondActiveCompany],
selectedCompanyId: null, storedCompanyId: activeCompany.id, routeCompanyId: secondActiveCompany.id,
})).toBe(secondActiveCompany.id);
});
it("retains a manual selection and does not bootstrap into an archived route", () => {
expect(resolveBootstrapCompanySelection({
companies: [activeCompany, secondActiveCompany], sidebarCompanies: [activeCompany, secondActiveCompany],
selectedCompanyId: activeCompany.id, storedCompanyId: activeCompany.id, routeCompanyId: secondActiveCompany.id,
})).toBe(activeCompany.id);
expect(resolveBootstrapCompanySelection({
companies: [activeCompany, archivedCompany], sidebarCompanies: [activeCompany],
selectedCompanyId: null, storedCompanyId: activeCompany.id, routeCompanyId: archivedCompany.id,
})).toBe(activeCompany.id);
});
it("does not expose a stale stored company id before companies load", () => {
expect(resolveBootstrapCompanySelection({
companies: [],
@@ -218,6 +236,28 @@ describe("CompanyProvider", () => {
vi.clearAllMocks();
});
it("publishes the URL company without first exposing the remembered company", async () => {
const previousUrl = window.location.href;
window.history.replaceState(null, "", "/TWO/issues");
localStorage.setItem("paperclip.selectedCompanyId", "company-1");
queryClient.setQueryData(queryKeys.auth.session, null);
queryClient.setQueryData(queryKeys.companies.list(null), {
companies: [{ ...makeCompany("company-1"), issuePrefix: "ONE" }, { ...makeCompany("company-2"), issuePrefix: "TWO" }],
unauthorized: false,
});
mockCompaniesApi.list.mockImplementation(() => new Promise(() => {}));
const seen: Array<string | null> = [];
try {
await act(async () => root.render(<QueryClientProvider client={queryClient}><CompanyProvider>
<Probe onSelectedCompanyId={id => seen.push(id)} />
</CompanyProvider></QueryClientProvider>));
expect(seen.filter(Boolean)).toEqual(["company-2"]);
expect(localStorage.getItem("paperclip.selectedCompanyId")).toBe("company-2");
} finally {
window.history.replaceState(null, "", previousUrl);
}
});
it("keeps the stored company when the company request fails", async () => {
// The seam the predicate test above cannot reach: the provider defaults a
// failed request to an empty list, so the effect has to be told the
+7
View File
@@ -58,6 +58,7 @@ export function resolveBootstrapCompanySelection(input: {
sidebarCompanies: Array<Pick<Company, "id">>;
selectedCompanyId: string | null;
storedCompanyId: string | null;
routeCompanyId?: string | null;
}) {
if (input.companies.length === 0) return null;
@@ -75,6 +76,9 @@ export function resolveBootstrapCompanySelection(input: {
if (input.selectedCompanyId && input.companies.some((company) => company.id === input.selectedCompanyId)) {
return input.selectedCompanyId;
}
if (input.routeCompanyId && input.sidebarCompanies.some((company) => company.id === input.routeCompanyId)) {
return input.routeCompanyId;
}
if (input.storedCompanyId && selectableCompanies.some((company) => company.id === input.storedCompanyId)) {
return input.storedCompanyId;
}
@@ -182,6 +186,9 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
sidebarCompanies,
selectedCompanyId,
storedCompanyId: localStorage.getItem(STORAGE_KEY),
routeCompanyId: companies.find(company =>
company.issuePrefix.toLowerCase() === window.location.pathname.split("/")[1]?.toLowerCase(),
)?.id,
});
if (next === null || next === selectedCompanyId) return;
setSelectedCompanyIdState(next);
+16
View File
@@ -0,0 +1,16 @@
import { useEffect } from "react";
import { TASK_COLLECTION_PAINTED_EVENT } from "@/lib/issue-detail-preload-events";
export function useWarmTaskDetailCode(ready: boolean) {
useEffect(() => {
if (!ready || typeof window.requestAnimationFrame !== "function") return;
let second: number | undefined;
const first = window.requestAnimationFrame(() => {
second = window.requestAnimationFrame(() => window.dispatchEvent(new Event(TASK_COLLECTION_PAINTED_EVENT)));
});
return () => {
window.cancelAnimationFrame(first);
if (second !== undefined) window.cancelAnimationFrame(second);
};
}, [ready]);
}
@@ -0,0 +1 @@
export const TASK_COLLECTION_PAINTED_EVENT = "paperclip:task-collection-painted";
@@ -0,0 +1,83 @@
import { runInNewContext } from "node:vm";
import { expect, it } from "vitest";
import { preloadIssueDetail } from "./vite-issue-detail-preload";
import { TASK_COLLECTION_PAINTED_EVENT } from "./issue-detail-preload-events";
function bootstrap(pathname: string, imports: Record<string, string[]> = {}, responseOk = true, cacheControl = "public, max-age=31536000, immutable") {
const hook = preloadIssueDetail().transformIndexHtml;
if (typeof hook !== "function") throw new Error("Missing HTML transform");
const tags = hook.call({} as never, "", { bundle: { detail: {
type: "chunk", fileName: "assets/issue-detail-fixture.js", moduleIds: ["/app/src/pages/IssueDetail.tsx"],
imports: imports["assets/issue-detail-fixture.js"] ?? [],
}, ...Object.fromEntries(Object.entries(imports).filter(([fileName]) => fileName !== "assets/issue-detail-fixture.js").map(([fileName, dependencies]) => [fileName, {
type: "chunk", fileName, moduleIds: [], imports: dependencies,
}])) } } as never) as { tag: string; children: string }[];
const links: { rel: string; href: string; crossOrigin: string }[] = [];
const fetches: unknown[][] = [];
const listeners = new Map<string, (event: unknown) => void>();
runInNewContext(tags[0].children, {
location: { pathname, origin: "https://board.example" },
fetch: (...args: unknown[]) => { fetches.push(args); return Promise.resolve({ ok: responseOk, headers: { get: () => cacheControl }, arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)) }); },
window: { addEventListener: (name: string, listener: (event: unknown) => void) => listeners.set(name, listener) },
document: {
createElement: () => ({}),
head: { appendChild: (link: typeof links[number]) => links.push(link) },
addEventListener: (name: string, listener: (event: unknown) => void) => listeners.set(name, listener),
},
});
return { links, fetches, painted: () => listeners.get(TASK_COLLECTION_PAINTED_EVENT)!({}), intent: (type: string, pathname: string, origin = "https://board.example") => {
listeners.get(type)!({ target: { closest: () => ({ pathname, origin }) } });
} };
}
it.each(["/PAP/issues/PAP-1", "/PAP/issues/PAP-1/", "/issues/PAP-1", "/PAP/chats/helper"])("preloads a direct conversation at %s", pathname => {
expect(bootstrap(pathname).links).toEqual([{ rel: "modulepreload", href: "/assets/issue-detail-fixture.js", crossOrigin: "" }]);
});
it.each(["/PAP/issues", "/PAP/inbox", "/PAP/inbox/mine", "/PAP/chats", "/PAP/issues/all", "/PAP/issues/active", "/PAP/issues/backlog", "/PAP/issues/done", "/PAP/issues/recent", "/issues", "/auth"])("leaves task detail out of %s startup", pathname => {
expect(bootstrap(pathname).links).toEqual([]);
});
it.each(["pointerover", "pointerdown", "focusin"])("preloads once on same-origin task or chat %s intent", type => {
const page = bootstrap("/PAP/inbox/mine");
page.intent(type, "/PAP/issues");
page.intent(type, "/PAP/issues/PAP-1", "https://other.example");
expect(page.links).toEqual([]);
expect(page.fetches).toEqual([]);
page.intent(type, "/PAP/issues/PAP-1");
page.intent(type, "/PAP/chats/helper");
expect(page.links).toEqual([]);
expect(page.fetches).toEqual([["/assets/issue-detail-fixture.js", { credentials: "same-origin", cache: "force-cache", priority: "low" }]]);
});
it("does not add a preload when the build has no task-detail chunk", () => {
const hook = preloadIssueDetail().transformIndexHtml;
if (typeof hook !== "function") throw new Error("Missing HTML transform");
expect(hook.call({} as never, "", { bundle: {} } as never)).toEqual([]);
});
it("warms code after a collection paints without executing it or repeating the fetch", () => {
const page = bootstrap("/PAP/issues");
expect(page.fetches).toEqual([]);
page.painted();
page.intent("focusin", "/PAP/issues/PAP-1");
expect(page.links).toEqual([]);
expect(page.fetches).toHaveLength(1);
});
it("preloads direct-task dependencies once, including cycles without external imports", () => {
const page = bootstrap("/PAP/issues/PAP-1", {
"assets/issue-detail-fixture.js": ["assets/shared.js"],
"assets/shared.js": ["assets/nested.js", "assets/issue-detail-fixture.js", "external"],
"assets/nested.js": [],
});
expect(page.links.map(link => link.href)).toEqual(["/assets/issue-detail-fixture.js", "/assets/shared.js", "/assets/nested.js"]);
});
it.each([[true, "public, max-age=31536000, immutable", 1], [false, "public, max-age=31536000, immutable", 0], [true, "no-cache", 0]] as const)("compiles warmed code only after a successful immutable response (%s, %s)", async (ok, cacheControl, linkCount) => {
const page = bootstrap("/PAP/issues", {}, ok, cacheControl);
page.painted();
await new Promise(resolve => setImmediate(resolve));
expect(page.links).toHaveLength(linkCount);
expect(page.fetches).toHaveLength(1);
});
+63
View File
@@ -0,0 +1,63 @@
import type { Plugin } from "vite";
import { TASK_COLLECTION_PAINTED_EVENT } from "./issue-detail-preload-events";
export function preloadIssueDetail(): Plugin {
return {
name: "paperclip-preload-issue-detail",
apply: "build",
transformIndexHtml(_html, { bundle }) {
const issueDetail = Object.values(bundle ?? {}).find((chunk) =>
chunk.type === "chunk" && chunk.moduleIds.some((id) => id.endsWith("/src/pages/IssueDetail.tsx")),
);
if (!issueDetail) return [];
const chunks = new Map(Object.values(bundle ?? {}).filter(chunk => chunk.type === "chunk").map(chunk => [chunk.fileName, chunk]));
const dependencies = new Set<string>();
const visit = (fileName: string) => {
if (!chunks.has(fileName) || dependencies.has(fileName)) return;
dependencies.add(fileName);
for (const imported of chunks.get(fileName)?.imports ?? []) visit(imported);
};
visit(issueDetail.fileName);
return [{
tag: "script",
injectTo: "head-prepend",
children: `(() => {
const isDetail = pathname => {
const parts = pathname.split("/").filter(Boolean);
const route = parts.length === 3 ? parts[1] : parts.length === 2 ? parts[0] : null;
return route === "chats" || (route === "issues" && !["all", "active", "backlog", "done", "recent"].includes(parts[parts.length - 1]));
};
const append = href => {
const link = document.createElement("link");
link.rel = "modulepreload";
link.href = href;
link.crossOrigin = "";
document.head.appendChild(link);
};
let requested = false;
const preload = (speculative = false) => {
if (requested) return;
requested = true;
if (speculative) {
void fetch(${JSON.stringify(`/${issueDetail.fileName}`)}, { credentials: "same-origin", cache: "force-cache", priority: "low" }).then(async response => {
await response.arrayBuffer();
if (response.ok && response.headers.get("cache-control")?.split(",").some(value => value.trim().toLowerCase() === "immutable")) append(${JSON.stringify(`/${issueDetail.fileName}`)});
}).catch(() => {});
return;
}
for (const href of ${JSON.stringify([...dependencies].map(fileName => `/${fileName}`))}) append(href);
};
if (isDetail(location.pathname)) preload();
window.addEventListener(${JSON.stringify(TASK_COLLECTION_PAINTED_EVENT)}, () => preload(true), { once: true });
const onIntent = event => {
const link = event.target.closest?.("a[href]");
if (link?.origin === location.origin && isDetail(link.pathname)) preload(true);
};
document.addEventListener("pointerover", onIntent, { passive: true });
document.addEventListener("pointerdown", onIntent, { passive: true });
document.addEventListener("focusin", onIntent);
})();`,
}];
},
};
}
+2
View File
@@ -1,4 +1,5 @@
import { useDeferredValue, useEffect, useRef } from "react";
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
import { useInfiniteQuery, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { ListChecks, SearchX } from "lucide-react";
import { accessApi } from "@/api/access";
@@ -180,6 +181,7 @@ export function CoordinatorTasks() {
?? (collection.filters.liveOnly ? liveRuns.error : null);
const pending = (needsAttention ? attention.isPending || attentionTasks.some(task => task.isPending) : tasks.isPending)
|| (collection.filters.liveOnly && liveRuns.isPending);
useWarmTaskDetailCode(!pending && !error && items.length > 0);
const { enrichIssueRow, error: rowDetailsError, retry: retryRowDetails } = useIssueRowDetails(
companyId, listRef,
`${collection.visibleItems.map(item => item.issue.id).join(",")}:${[...collection.collapsedIds].join(",")}:${collection.layout}`,
+5 -2
View File
@@ -928,13 +928,16 @@ describe("Inbox toolbar", () => {
act(() => root.unmount());
});
it("can select a company after a cold inbox mount", async () => {
it.each([true, false])("can select a company after a cold inbox mount (Streamlined UI=%s)", async streamlined => {
companyState.selectedCompanyId = null;
const settings = { enableStreamlinedUi: streamlined, enableIsolatedWorkspaces: false };
apiMocks.experimentalSettings.mockResolvedValue(settings);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });
queryClient.setQueryData(queryKeys.instance.experimentalSettings, settings);
const root = createRoot(container);
const render = () => root.render(<QueryClientProvider client={queryClient}><Inbox /></QueryClientProvider>);
await act(render);
await vi.waitFor(() => expect(container.textContent).toContain("Select an organization"));
await vi.waitFor(() => expect(container.textContent).toContain(streamlined ? "Select an organization" : "Select a company"));
companyState.selectedCompanyId = "company-1";
apiMocks.issuesList.mockResolvedValue([createIssue({ title: "Cold company task" })]);
await act(render);
+2
View File
@@ -1,4 +1,5 @@
import { useCoordinatorPresentation } from "@/components/coordinator/CoordinatorPresentation";
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
import { describeError } from "../api/errors";
import { useIssueRowDetails } from "../hooks/useIssueRowDetails";
import { IssueRowDetailsNotice } from "../components/IssueRowDetailsNotice";
@@ -2483,6 +2484,7 @@ function StreamlinedInbox({
if (initialSourcesSettled && !listError) setRevealedScope(revealScope);
}, [initialSourcesSettled, listError, revealScope]);
const allLoaded = initialSourcesSettled || revealedScope === revealScope;
useWarmTaskDetailCode(allLoaded && !listError && tab !== "blocked" && showWorkItemsSection);
const showSeparatorBefore = (key: SectionKey) => visibleSections.indexOf(key) > 0;
const { enrichIssueRow, error: rowDetailsError, retry: retryRowDetails } = useIssueRowDetails(
+11 -9
View File
@@ -1,4 +1,5 @@
import { describeError } from "../api/errors";
import { useWarmTaskDetailCode } from "@/hooks/useWarmTaskDetailCode";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation, useNavigate } from "@/lib/router";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
@@ -2209,6 +2210,16 @@ export function Inbox() {
if (row) row.scrollIntoView({ block: "nearest" });
}, [selectedIndex]);
const allLoaded =
!isJoinRequestsLoading &&
!isApprovalsLoading &&
!isDashboardLoading &&
!isIssuesLoading &&
!isMineIssuesLoading &&
!isTouchedIssuesLoading &&
!isRunsLoading;
useWarmTaskDetailCode(Boolean(selectedCompanyId) && allLoaded && tab !== "blocked" && totalVisibleWorkItems > 0);
if (!selectedCompanyId) {
return <EmptyState icon={InboxIcon} message="Select a company to view inbox." />;
}
@@ -2243,15 +2254,6 @@ export function Inbox() {
showWorkItemsSection ? "work_items" : null,
].filter((key): key is SectionKey => key !== null);
const allLoaded =
!isJoinRequestsLoading &&
!isApprovalsLoading &&
!isDashboardLoading &&
!isIssuesLoading &&
!isMineIssuesLoading &&
!isTouchedIssuesLoading &&
!isRunsLoading;
const showSeparatorBefore = (key: SectionKey) => visibleSections.indexOf(key) > 0;
const markAllReadIssues = (tab === "mine" ? visibleMineIssues : unreadTouchedIssues)
.filter((issue) => issue.isUnreadForMe && !fadingOutIssues.has(issue.id) && !archivingIssueIds.has(issue.id));
+3 -14
View File
@@ -1,27 +1,15 @@
import path from "path";
import { defineConfig, type Plugin } from "vite";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
import { createUiDevWatchOptions } from "./src/lib/vite-watch";
import { createApiProxy } from "./src/lib/vite-api-proxy";
import { serviceWorkerBuildIdPlugin } from "./src/lib/vite-sw-build-id";
import { readBrowserBuildCommit } from "./src/lib/vite-build-commit";
import { preloadIssueDetail } from "./src/lib/vite-issue-detail-preload";
const apiProxy = createApiProxy();
function preloadIssueDetail(): Plugin {
return {
name: "paperclip-preload-issue-detail",
apply: "build",
transformIndexHtml(_html, { bundle }) {
const issueDetail = Object.values(bundle ?? {}).find((chunk) =>
chunk.type === "chunk" && chunk.moduleIds.some((id) => id.endsWith("/src/pages/IssueDetail.tsx")),
);
return issueDetail ? [{ tag: "link", attrs: { rel: "modulepreload", href: `/${issueDetail.fileName}`, crossorigin: "" }, injectTo: "head" }] : [];
},
};
}
export default defineConfig(({ mode }) => ({
define: {
__PAPERCLIP_BUILD_COMMIT__: JSON.stringify(
@@ -36,6 +24,7 @@ export default defineConfig(({ mode }) => ({
codeSplitting: {
groups: [
{ name: "board-startup", tags: ["$initial"], priority: 10 },
{ name: "collections", test: /\/src\/pages\/(?:Issues|Inbox|LegacyInbox|CoordinatorTasks)\.tsx$/, priority: 6 },
{ name: "issue-detail", test: /\/src\/pages\/IssueDetail\.tsx$/, priority: 5 },
],
},