Files
PaperClipAI/ui/src/components/chat/AgentWorkPanels.tsx
T
DottaandClaude Opus 5.5 b184e40108 perf(ui): serve every project list from one includeArchived read (#20395)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI reads the company project list in many places: the
sidebar, starred projects, the command palette, the new-task dialog, and
archive-aware pages such as the Mine inbox
> - Active-only consumers read `GET /projects`, and archive-aware ones
read `GET /projects?includeArchived=true`, under two React Query keys
> - A Mine load therefore fetched the same large payload twice (580–590
KB each on our dev instance)
> - The two responses differ only by archived rows; the server's active
list is exactly the rows where `archivedAt` is null
> - This pull request makes every consumer share the
`includeArchived=true` query, and active-only consumers filter it with
`select`
> - The benefit is one project read per page instead of two

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Duplicate project list reads on page load.

**Subsystem affected**
Board UI project queries (`ui/src/lib/company-projects-query.ts` and its
consumers).

**Current behavior**
A cold Mine load sends both `/companies/:id/projects` (sidebar) and
`/companies/:id/projects?includeArchived=true` (inbox).

**Proposed behavior**
One `includeArchived=true` read serves both. Active-only consumers apply
`selectActiveProjects`.

**Reason and benefit**
The project list is one of the largest shell payloads. Reading it once
saves a large response on every page that has both kinds of consumer.

## What Changed

- New `companyProjectsQuery(companyId, { includeArchived? })` in
`ui/src/lib/company-projects-query.ts`. It always uses the
`includeArchived: true` key and fetch. For active-only use it adds a
stable, module-level `select` that keeps rows without `archivedAt`.
- 22 files that read the active list now spread
`companyProjectsQuery(...)`, and so do the plugin SDK project picker and
16 archive-aware pages that wrote the shared key and fetcher inline.
Their `enabled` and other options are unchanged. `OnboardingWizard`'s
one imperative read is unchanged. `pages/Inbox.tsx` already reads the
same key and fetcher, so it shares the entry without an edit.
- Invalidation: project mutations and live events invalidate
`queryKeys.projects.all(companyId)`, which matches the shared key. The
onboarding wizard invalidated the old active-only key; it now
invalidates `projects.all`.
- Tests: new `company-projects-query.test.tsx` (one request for both
consumers, correct filtering, and one refetch after `projects.all`
invalidation). Three existing tests (`CommandPalette`, `CompanyExport`,
`GitHubBotManagement`) now seed or expect the shared key.
- New browser check
`tests/perf/collections/shared-project-list.spec.ts`: after the Mine
inbox read completes, the page has sent no active-only project request.

## Verification

- `pnpm verify` passes.
- `ui`: the consumer suites (`CoordinatorSidebar`, `SidebarProjects`,
`SidebarStarredProjects`, `CommandPalette`, `NewIssueDialog`,
`AgentWorkPanels`, `CoordinatorNeedsYou`, `IssueDetail`,
`ProjectDetail`, `Projects`, `CompanyExport`, `ChatExecutionDefaults`,
`GatewaysList`, `Search`, `IssueProperties`, `persisted-query-cache`)
pass.
- Browser check:
`PAPERCLIP_COLLECTION_PERF_BASE_URL=http://127.0.0.1:<port> pnpm exec
playwright test --config tests/perf/collections/playwright.config.ts
shared-project-list.spec.ts`. It passes on this branch and fails on
`master`.

## Risks

- A page that needs only active projects now downloads archived rows
too. For most companies that is a small difference; the duplicate read
it removes is a full copy.
- The server does not order either list, and consumers sort for display,
so filtering on the client keeps behavior.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, file edits, browser). 1M-token context window. Extended
thinking was off.

## 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
- [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>
2026-11-09 17:42:47 -06:00

332 lines
13 KiB
TypeScript

import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpDown, File, FileText, Image, Search, Video } from "lucide-react";
import type { CompanyArtifact, Issue } from "@paperclipai/shared";
import { artifactsApi } from "@/api/artifacts";
import { issuesApi } from "@/api/issues";
import { IssueFiltersPopover } from "@/components/IssueFiltersPopover";
import { StatusIcon } from "@/components/StatusIcon";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
applyIssueFilters,
countActiveIssueFilters,
defaultIssueFilterState,
issueStatusOrder,
type IssueFilterState,
} from "@/lib/issue-filters";
import { queryKeys } from "@/lib/queryKeys";
import { Link } from "@/lib/router";
import { cn, formatDate, relativeTime } from "@/lib/utils";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
import { companyProjectsQuery } from "@/lib/company-projects-query";
/**
* The agent-scoped side panels shown beside an agent chat: every task the
* agent has worked on, and every artifact it produced. Both are card stacks
* so the chat's right column reads as "what this agent has been doing"
* rather than the properties of the conversation issue itself.
*/
const AGENT_TASK_LIMIT = 200;
const ARTIFACT_PAGE_SIZE = 100;
const ARTIFACT_MAX_PAGES = 5;
export type AgentTaskSortField = "updated" | "created" | "status" | "title";
const SORT_OPTIONS: ReadonlyArray<[AgentTaskSortField, string]> = [
["updated", "Last updated"],
["created", "Created"],
["status", "Status"],
["title", "Title"],
];
export function sortAgentTasks(
tasks: Issue[],
field: AgentTaskSortField,
dir: "asc" | "desc",
): Issue[] {
const sign = dir === "asc" ? 1 : -1;
return [...tasks].sort((a, b) => {
switch (field) {
case "status":
return sign * (issueStatusOrder.indexOf(a.status) - issueStatusOrder.indexOf(b.status));
case "title":
return sign * a.title.localeCompare(b.title);
case "created":
return sign * (new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
default:
return sign * (new Date(a.updatedAt).getTime() - new Date(b.updatedAt).getTime());
}
});
}
function PanelMessage({ children, tone = "muted" }: { children: React.ReactNode; tone?: "muted" | "error" }) {
return (
<p className={cn("px-1 py-6 text-center text-sm", tone === "error" ? "text-destructive" : "text-muted-foreground")}>
{children}
</p>
);
}
const cardClassName =
"flex flex-col gap-1 rounded-lg border border-border bg-card p-3 transition-colors hover:border-foreground/20 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
export function AgentTaskCard({ task }: { task: Issue }) {
return (
<Link
// design-allow(card-pattern): navigation <Link> card; Card renders a div and would break anchor semantics
to={`/issues/${task.identifier ?? task.id}`}
disableIssueQuicklook
target="_blank"
rel="noreferrer"
data-testid="agent-task-card"
className={cardClassName}
>
<div className="flex min-w-0 items-start gap-2">
<StatusIcon
{...taskStatusIconProps(task)}
className="mt-0.5 shrink-0"
/>
<span className="min-w-0 flex-1 line-clamp-2 text-sm font-medium text-foreground">
{task.title}
</span>
</div>
<div className="flex items-center gap-1.5 pl-6 text-xs text-muted-foreground">
<span className="font-mono">{task.identifier ?? task.id.slice(0, 8)}</span>
<span aria-hidden>·</span>
<time dateTime={new Date(task.updatedAt).toISOString()} title={new Date(task.updatedAt).toLocaleString()}>
{relativeTime(task.updatedAt)}
</time>
</div>
</Link>
);
}
export function AgentTasksPanel({
companyId,
agentId,
excludeIssueId,
}: {
companyId: string;
agentId: string;
/** The conversation issue itself, which is not one of the agent's tasks. */
excludeIssueId?: string;
}) {
const [query, setQuery] = useState("");
const [filters, setFilters] = useState<IssueFilterState>(defaultIssueFilterState);
const [sortField, setSortField] = useState<AgentTaskSortField>("updated");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
const tasksQuery = useQuery({
queryKey: queryKeys.issues.listParticipatedByAgent(companyId, agentId),
queryFn: () => issuesApi.list(companyId, {
participantAgentId: agentId,
sortField: "updated",
sortDir: "desc",
limit: AGENT_TASK_LIMIT,
}),
});
const tasksView = useQueryView(tasksQuery);
const projectsQuery = useQuery({
...companyProjectsQuery(companyId),
});
const visible = useMemo(() => {
const needle = query.trim().toLowerCase();
const scoped = (tasksQuery.data ?? []).filter((task) => {
if (task.id === excludeIssueId) return false;
if (!needle) return true;
return task.title.toLowerCase().includes(needle)
|| (task.identifier ?? "").toLowerCase().includes(needle);
});
return sortAgentTasks(applyIssueFilters(scoped, filters), sortField, sortDir);
}, [tasksQuery.data, excludeIssueId, query, filters, sortField, sortDir]);
const activeFilterCount = countActiveIssueFilters(filters);
const total = (tasksQuery.data ?? []).filter((task) => task.id !== excludeIssueId).length;
// Search and filters run on the most recently updated tasks only.
const capped = (tasksQuery.data?.length ?? 0) >= AGENT_TASK_LIMIT;
return (
<section className="flex flex-col gap-3" aria-label="Agent tasks">
<div className="flex items-center gap-1">
<div className="relative min-w-0 flex-1">
<Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search tasks"
aria-label="Search tasks"
className="h-8 pl-7 text-sm"
/>
</div>
<IssueFiltersPopover
state={filters}
onChange={(patch) => setFilters((current) => ({ ...current, ...patch }))}
activeFilterCount={activeFilterCount}
projects={projectsQuery.data?.map((project) => ({ id: project.id, name: project.name }))}
enableExternalObjectFilters={false}
buttonVariant="outline"
iconOnly
presentation="streamlined"
/>
<Popover>
<PopoverTrigger asChild>
<Button variant="outline" size="icon" className="h-8 w-8 shrink-0" title="Sort" aria-label="Sort tasks">
<ArrowUpDown className="h-3.5 w-3.5" />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-48 p-0">
<div className="space-y-0.5 p-2">
{SORT_OPTIONS.map(([field, label]) => (
<button
key={field}
type="button"
className={cn(
"flex w-full items-center justify-between rounded-sm px-2 py-1.5 text-sm",
sortField === field ? "bg-accent/50 text-foreground" : "text-muted-foreground hover:bg-accent/50",
)}
onClick={() => {
if (sortField === field) setSortDir(sortDir === "asc" ? "desc" : "asc");
else {
setSortField(field);
setSortDir(field === "updated" || field === "created" ? "desc" : "asc");
}
}}
>
<span>{label}</span>
{sortField === field ? (
<span className="text-xs text-muted-foreground">{sortDir === "asc" ? "↑" : "↓"}</span>
) : null}
</button>
))}
</div>
</PopoverContent>
</Popover>
</div>
{tasksView.kind === "loading" || tasksView.kind === "reconnecting" ? (
<PanelMessage>Loading tasks…</PanelMessage>
) : tasksView.kind === "error" ? (
<div className="py-4">
<QueryErrorState
error={tasksQuery.error}
action="load this agent's tasks"
onRetry={tasksView.retry}
retrying={tasksView.isFetching}
/>
</div>
) : total === 0 ? (
<PanelMessage>This agent hasn't worked on any tasks yet.</PanelMessage>
) : visible.length === 0 ? (
<PanelMessage>
{capped
? `No tasks match these filters among the ${AGENT_TASK_LIMIT} most recently updated.`
: "No tasks match these filters."}
</PanelMessage>
) : (
<div className="flex flex-col gap-2">
{visible.map((task) => <AgentTaskCard key={task.id} task={task} />)}
{capped ? (
<p className="px-1 text-xs text-muted-foreground">
Showing the {AGENT_TASK_LIMIT} most recently updated tasks.
</p>
) : null}
</div>
)}
</section>
);
}
function ArtifactKindIcon({ artifact }: { artifact: CompanyArtifact }) {
const className = "mt-0.5 h-4 w-4 shrink-0 text-muted-foreground";
switch (artifact.mediaKind) {
case "image": return <Image className={className} aria-hidden />;
case "video": return <Video className={className} aria-hidden />;
case "text":
case "document": return <FileText className={className} aria-hidden />;
default: return <File className={className} aria-hidden />;
}
}
export function AgentArtifactCard({ artifact }: { artifact: CompanyArtifact }) {
return (
<Link
// design-allow(card-pattern): navigation <Link> card; Card renders a div and would break anchor semantics
to={artifact.href}
disableIssueQuicklook
target="_blank"
rel="noreferrer"
data-testid="agent-artifact-card"
className={cardClassName}
>
<div className="flex min-w-0 items-start gap-2">
<ArtifactKindIcon artifact={artifact} />
<span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground" title={artifact.title}>
{artifact.title}
</span>
</div>
<div className="flex items-center gap-1.5 pl-6 text-xs text-muted-foreground">
<span>Updated {formatDate(artifact.updatedAt)}</span>
<span aria-hidden>·</span>
<span className="font-mono">{artifact.issue.identifier}</span>
</div>
</Link>
);
}
/**
* This agent's artifacts, newest first, filtered on the server. Pages are
* capped so an unusually prolific agent can't stall the panel; the cap only
* ever drops its oldest artifacts.
*/
async function listAgentArtifacts(companyId: string, agentId: string) {
const artifacts: CompanyArtifact[] = [];
let cursor: string | undefined;
for (let page = 0; page < ARTIFACT_MAX_PAGES; page += 1) {
const response = await artifactsApi.list(companyId, { agentId, limit: ARTIFACT_PAGE_SIZE, cursor });
artifacts.push(...response.artifacts);
if (!response.nextCursor) return { artifacts, truncated: false };
cursor = response.nextCursor;
}
return { artifacts, truncated: true };
}
export function AgentArtifactsPanel({ companyId, agentId }: { companyId: string; agentId: string }) {
const artifactsQuery = useQuery({
queryKey: queryKeys.artifacts.byAgent(companyId, agentId),
queryFn: () => listAgentArtifacts(companyId, agentId),
});
const artifactsView = useQueryView(artifactsQuery);
if (artifactsView.kind === "loading" || artifactsView.kind === "reconnecting") return <PanelMessage>Loading artifacts…</PanelMessage>;
if (artifactsView.kind === "error") {
return (
<div className="py-4">
<QueryErrorState
error={artifactsQuery.error}
action="load this agent's artifacts"
onRetry={artifactsView.retry}
retrying={artifactsView.isFetching}
/>
</div>
);
}
const loaded = artifactsQuery.data;
if (!loaded) return null;
const { artifacts, truncated } = loaded;
if (artifacts.length === 0) return <PanelMessage>This agent hasn't produced any artifacts yet.</PanelMessage>;
return (
<section className="flex flex-col gap-2" aria-label="Agent artifacts">
{artifacts.map((artifact) => <AgentArtifactCard key={artifact.id} artifact={artifact} />)}
{truncated ? (
<p className="px-1 text-xs text-muted-foreground">Showing this agent's {artifacts.length} most recent artifacts.</p>
) : null}
</section>
);
}