mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 02:43:25 +01:00
## 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>
109 lines
8.3 KiB
TypeScript
109 lines
8.3 KiB
TypeScript
import { companyProjectsQuery } from "@/lib/company-projects-query";
|
|
import { useEffect } from "react";
|
|
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { ListChecks, SearchX } from "lucide-react";
|
|
import { accessApi } from "@/api/access";
|
|
import { agentsApi } from "@/api/agents";
|
|
import { useAccountIdentity } from "@/api/companies-query";
|
|
import { issuesApi } from "@/api/issues";
|
|
import { EmptyState } from "@/components/EmptyState";
|
|
import { KanbanBoard } from "@/components/KanbanBoard";
|
|
import { TaskList, type TaskListItem } from "@/components/TaskList";
|
|
import { TaskListToolbar } from "@/components/TaskListToolbar";
|
|
import { TruncatedTextMarqueeProvider } from "@/components/TruncatedText";
|
|
import { Button } from "@/components/ui/button";
|
|
import { useBreadcrumbs } from "@/context/BreadcrumbContext";
|
|
import { useCompany } from "@/context/CompanyContext";
|
|
import { useDialogActions } from "@/context/DialogContext";
|
|
import { useTaskListCollection } from "@/hooks/useTaskListCollection";
|
|
import { formatUserLabel } from "@/lib/assignees";
|
|
import { buildCompanyUserProfileMap } from "@/lib/company-members";
|
|
import { queryKeys } from "@/lib/queryKeys";
|
|
import { taskListViewStorageKey } from "@/lib/task-list-views";
|
|
import type { Issue } from "@paperclipai/shared";
|
|
|
|
const pageSize = 200;
|
|
|
|
/** Real API adapter for the Design proposals / Pages / Tasks composition.
|
|
* All visual and collection behavior comes from the reviewed shared subjects. */
|
|
export function DesignSandboxTasks() {
|
|
const { selectedCompanyId: companyId } = useCompany();
|
|
const { userId } = useAccountIdentity();
|
|
const { openNewIssue } = useDialogActions();
|
|
const { setBreadcrumbs } = useBreadcrumbs();
|
|
const client = useQueryClient();
|
|
useEffect(() => { setBreadcrumbs([{ label: "Tasks" }]); }, [setBreadcrumbs]);
|
|
|
|
const tasks = useInfiniteQuery({
|
|
queryKey: [...queryKeys.issues.list(companyId!), "design-sandbox", userId],
|
|
queryFn: ({ pageParam, signal }) => issuesApi.list(companyId!, {
|
|
limit: pageSize, offset: pageParam, includeAgentCreatedTasks: true,
|
|
includeRoutineExecutions: true, sortField: "id", sortDir: "asc",
|
|
}, { signal }),
|
|
initialPageParam: 0,
|
|
getNextPageParam: (last, _pages, offset) => last.length === pageSize ? offset + pageSize : undefined,
|
|
enabled: !!companyId,
|
|
});
|
|
const agents = useQuery({ queryKey: queryKeys.agents.list(companyId!), queryFn: () => agentsApi.list(companyId!), enabled: !!companyId });
|
|
const projects = useQuery({ ...companyProjectsQuery(companyId!, { includeArchived: true }), enabled: !!companyId });
|
|
const directory = useQuery({ queryKey: queryKeys.access.companyUserDirectory(companyId!), queryFn: () => accessApi.listUserDirectory(companyId!), enabled: !!companyId });
|
|
const labels = useQuery({ queryKey: queryKeys.issues.labels(companyId!), queryFn: () => issuesApi.listLabels(companyId!), enabled: !!companyId });
|
|
// The ordinary organization list does not include viewer read context.
|
|
// Ask the server for the signed-in user's unread set instead of guessing
|
|
// unread state from dates or reusing Storybook fixture flags.
|
|
const unread = useQuery({
|
|
queryKey: [...queryKeys.issues.list(companyId!), "design-sandbox-unread", userId],
|
|
queryFn: async ({ signal }) => {
|
|
const ids = new Set<string>();
|
|
let page: Issue[];
|
|
let offset = 0;
|
|
do {
|
|
page = await issuesApi.list(companyId!, { unreadForUserId: "me", includeAgentCreatedTasks: true,
|
|
includeRoutineExecutions: true, limit: pageSize, offset, sortField: "id", sortDir: "asc" }, { signal });
|
|
for (const issue of page) ids.add(issue.id);
|
|
offset += pageSize;
|
|
} while (page.length === pageSize);
|
|
return ids;
|
|
},
|
|
enabled: !!companyId && !!userId,
|
|
});
|
|
const users = buildCompanyUserProfileMap(directory.data?.users);
|
|
const agentById = new Map(agents.data?.map(agent => [agent.id, agent]));
|
|
const projectById = new Map(projects.data?.map(project => [project.id, project]));
|
|
const items: TaskListItem[] = [...new Map((tasks.data?.pages.flat() ?? []).map(issue => [issue.id, issue])).values()].map(issue => ({
|
|
issue: { ...issue, project: issue.project ?? projectById.get(issue.projectId ?? "") },
|
|
unread: unread.data?.has(issue.id) ?? false,
|
|
createdBy: issue.createdByAgentId ? agentById.get(issue.createdByAgentId)?.name ?? "Unknown agent" : users.get(issue.createdByUserId ?? "")?.label ?? (issue.createdByUserId === "local-board" ? "Board" : "Unknown user"),
|
|
assignee: issue.assigneeAgentId ? agentById.get(issue.assigneeAgentId)?.name ?? "Unknown agent" : users.get(issue.assigneeUserId ?? "")?.label ?? formatUserLabel(issue.assigneeUserId),
|
|
assigneeAgent: agentById.get(issue.assigneeAgentId ?? ""),
|
|
assigneeUserAvatarUrl: users.get(issue.assigneeUserId ?? "")?.image,
|
|
}));
|
|
const collection = useTaskListCollection({ items, companyId, userId,
|
|
viewStorageKey: taskListViewStorageKey("design-integration-sandbox", userId ?? "local-board"),
|
|
});
|
|
const update = useMutation({
|
|
mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) => issuesApi.update(id, data),
|
|
onSuccess: () => { void client.invalidateQueries({ queryKey: queryKeys.issues.list(companyId!) }); },
|
|
});
|
|
const error = tasks.error ?? agents.error ?? projects.error ?? directory.error ?? labels.error ?? unread.error ?? update.error;
|
|
const empty = collection.companyItems.length === 0
|
|
? <EmptyState icon={ListChecks} message="No tasks in this organization" action="New Task" onAction={() => openNewIssue()} />
|
|
: <EmptyState icon={SearchX} message="No tasks match this view" action="Clear filters" hideActionIcon onAction={collection.clear} />;
|
|
|
|
if (!companyId) return <EmptyState icon={ListChecks} message="Select an organization to view tasks." />;
|
|
return <TruncatedTextMarqueeProvider><div className="task-row-design-preview flex flex-col gap-8" data-testid="design-sandbox-tasks">
|
|
<TaskListToolbar view={collection.view} onViewChange={collection.setView} query={collection.query} onQueryChange={collection.setQuery}
|
|
layout={collection.layout} onLayoutChange={collection.setLayout} allExpanded={collection.allExpanded} onToggleExpanded={collection.toggleExpanded}
|
|
onNewTask={() => openNewIssue()} filters={{ state: collection.filters, onChange: collection.updateFilters, activeFilterCount: collection.activeFilterCount,
|
|
enableLiveRunsFilter: false,
|
|
agents: agents.data ?? [], projects: projects.data ?? [], labels: labels.data ?? [], currentUserId: userId, creators: collection.creators }} />
|
|
{error ? <div role="alert" className="flex items-center gap-2 text-sm text-destructive"><span>{error instanceof Error ? error.message : "Could not load tasks"}</span><Button variant="outline" size="sm" onClick={() => { update.reset(); void client.invalidateQueries({ queryKey: queryKeys.issues.list(companyId) }); void agents.refetch(); void projects.refetch(); void directory.refetch(); void labels.refetch(); }}>Retry</Button></div> : null}
|
|
{tasks.isPending ? <p role="status" className="text-sm text-muted-foreground">Loading tasks…</p> : <>
|
|
{collection.narrowed ? <p role="status" className="design-task-results">{collection.matchingItems.length} matching tasks{collection.layout === "list" && collection.visibleItems.length > collection.matchingItems.length ? " · Parent tasks included for context" : ""}</p> : null}
|
|
<div hidden={collection.layout !== "list"} className="design-task-list-panel"><TaskList key={companyId} items={collection.visibleItems} allItems={collection.companyItems} collapsedIds={collection.collapsedIds} onCollapsedIdsChange={collection.setCollapsedIds} emptyState={empty} /></div>
|
|
{collection.layout === "board" ? collection.matchingItems.length ? <KanbanBoard showOverflowFades issues={collection.matchingItems.map(item => item.issue)} agents={agents.data} onUpdateIssue={(id, data) => update.mutate({ id, data })} /> : empty : null}
|
|
{tasks.hasNextPage ? <div className="flex items-center gap-3 text-sm text-muted-foreground"><span>Search, views and filters cover the {items.length} loaded tasks.</span><Button variant="outline" size="sm" disabled={tasks.isFetchingNextPage} onClick={() => void tasks.fetchNextPage()}>{tasks.isFetchingNextPage ? "Loading…" : "Load more tasks"}</Button></div> : null}
|
|
</>}
|
|
</div></TruncatedTextMarqueeProvider>;
|
|
}
|