fix: bound workspace Git scans (#11572)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Workspaces let users and agents inspect files that belong to an
issue
> - Changed-file views use full-tree Git status scans
> - Many issue views could start those scans at the same time and make
the server unresponsive
> - Route-level limits did not protect the process or coalesce work for
one repository
> - This pull request adds one bounded scheduler for every expensive
workspace Git scan
> - It also starts browser scans only when the file panel is open and
visible
> - The benefit is bounded child-process use and responsive health
checks during request storms

## Linked Issues or Issue Description

**What happened?**

Many changed-file requests could start full `git status --porcelain=v1
-z --untracked-files=all` scans at the same time. One production
incident produced about 270 direct Git child processes. The Node process
stayed alive but stopped answering health requests in time.

**Expected behavior**

Paperclip must bound expensive Git work across all companies, actors,
issues, repositories, and browser tabs. Duplicate requests for one
worktree must share work. Excess requests must fail fast with a
retryable response. Hidden or closed file panels must not start scans.

**Steps to reproduce**

1. Open changed-file views for many issue and actor keys.
2. Send requests for two large workspace roots at the same time.
3. Observe that route-level limiter keys allow many full Git scans to
run together.
4. Observe delayed health responses and accumulated Git children.

**Paperclip version or commit**

Reproduced on master before commit `43ab441f0f`.

**Deployment mode**

Self-hosted server with local workspace repositories.

## What Changed

- Add a process-wide scheduler with configurable concurrency, queue
capacity, timeout, and cache TTL.
- Add fair admission, a bounded queue, canonical worktree keys,
single-flight joins, and bounded result caching.
- Add subprocess timeouts, TERM-to-KILL escalation, bounded output,
waiter cancellation, and slot cleanup.
- Route full-tree status work from file resources, workspace runtime,
execution workspaces, and adapter overlay sync through the scheduler.
- Return stable retryable `503` and `504` error codes for saturation and
timeout.
- Add structured logs with safe workspace hashes, durations, queue
state, cache use, joins, and terminal outcomes.
- Gate UI queries on panel and document visibility. Cancel queries on
close, hide, unmount, and workspace change.
- Disable focus and reconnect bursts. Keep one explicit refresh action
and a retryable unavailable state.
- Document the 10-second default freshness tradeoff and all
configuration variables.
- Add unit, route, UI, adapter, and deterministic 500-request load
coverage.

## Verification

- `pnpm -r typecheck`
- `pnpm build`
- `pnpm check:token-gates`
- `pnpm --filter @paperclipai/server exec vitest run
src/services/workspace-git-operation-scheduler.test.ts
src/__tests__/file-resources-git-scan-load.test.ts --reporter=dot` — 16
tests passed.
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/WorkspaceFileBrowser.test.tsx
src/lib/page-visibility.test.ts --reporter=dot` — 38 tests passed.
- `pnpm --filter @paperclipai/adapter-utils exec vitest run
src/git-workspace-sync.test.ts --reporter=dot` — 16 tests passed.
- Existing file-resource, workspace-runtime, and execution-workspace
regression selections passed.
- Two cleanup safety regressions prove failed scans preserve the
worktree before archive and at the final deletion fence.
- Before: the incident produced about 270 Git children and health
requests timed out.
- After: 500 concurrent requests across 500 issue keys, 73 actors, and
two roots started two underlying scans. Peak scan concurrency was 2. All
500 requests succeeded. Health p99 was 4.94 ms. The harness found zero
unreaped children.
- The full local Vitest run passed 4,267 tests. Ten existing fixed-port
HTTPS exposure tests could not run because this host already owns
Tailnet listeners on ports 42000 and 52000. Clean GitHub CI is the final
full-suite result.
- Latest-head GitHub CI passed all required test, typecheck, build,
canary, e2e, policy, and security gates.
- Greptile completed at 5/5 with zero unresolved comments,
recommendations, or follow-ups.

## Risks

- Changed-file results can be up to 10 seconds old by default. Explicit
refresh remains available.
- A full queue returns a retryable `503` instead of waiting without a
bound.
- A scan that exceeds the default 8-second deadline returns a retryable
`504` and terminates its process group.
- Operators can tune all limits with documented environment variables.
Safe defaults protect local and shared servers.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, GPT-5 family. The runtime does not expose the exact
deployment ID or context-window size. High reasoning, tool use, and code
execution were enabled.

## 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
- [x] All Paperclip CI gates are green
- [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-08-17 22:11:30 -05:00
1 parent 48f4ae16ac
commit 8087661bb8
21 files changed
+2158 -78

No files matched your search

+110 -43
View File
@@ -7,14 +7,16 @@ import {
type KeyboardEvent,
type ReactNode,
} from "react";
import { useQueries, useQuery } from "@tanstack/react-query";
import { AlertTriangle, ChevronDown, ChevronRight, Cloud, Download, FileCode2, FolderOpen, Loader2, Search } from "lucide-react";
import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, ChevronDown, ChevronRight, Cloud, Download, FileCode2, FolderOpen, Loader2, RefreshCcw, Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { fileResourcesApi } from "@/api/file-resources";
import { projectsApi } from "@/api/projects";
import { ApiError } from "@/api/client";
import { queryKeys } from "@/lib/queryKeys";
import { usePageVisibility } from "@/lib/page-visibility";
import { parseWorkspaceFileRef } from "@/lib/workspace-file-parser";
import type {
Project,
@@ -103,13 +105,24 @@ export function describeUnavailable(reason: string): { title: string; body: stri
};
}
function StateMessage({ icon, title, body }: { icon: ReactNode; title: string; body?: string }) {
function StateMessage({
icon,
title,
body,
actions,
}: {
icon: ReactNode;
title: string;
body?: string;
actions?: ReactNode;
}) {
return (
<div className="flex items-start gap-3 px-1 py-8 text-sm">
{icon}
<div className="space-y-1">
<p className="font-medium text-foreground">{title}</p>
{body ? <p className="text-muted-foreground">{body}</p> : null}
{actions ? <div className="pt-1">{actions}</div> : null}
</div>
</div>
);
@@ -475,6 +488,8 @@ export interface WorkspaceFileBrowserProps {
selectedPath?: string | null;
selectedProjectId?: string | null;
selectedWorkspaceId?: string | null;
/** True only while the containing Files panel is actually open. */
active?: boolean;
className?: string;
}
@@ -491,8 +506,11 @@ export function WorkspaceFileBrowser({
selectedPath,
selectedProjectId: activeProjectId,
selectedWorkspaceId: activeWorkspaceId,
active = true,
className,
}: WorkspaceFileBrowserProps) {
const queryClient = useQueryClient();
const { visible: pageVisible } = usePageVisibility();
const source: BrowserSource =
initialProjectId && initialWorkspaceId ? "other" : "current";
const workspace: WorkspaceFileSelector = "auto";
@@ -594,6 +612,7 @@ export function WorkspaceFileBrowser({
const targetWorkspaceId = source === "other" ? selectedWorkspaceId : null;
const effectiveWorkspace: WorkspaceFileSelector = source === "other" ? "project" : workspace;
const canListFiles = source === "current" || Boolean(targetProjectId && targetWorkspaceId);
const queriesEnabled = active && pageVisible && canListFiles;
const targetRef = targetProjectId && targetWorkspaceId
? { projectId: targetProjectId, workspaceId: targetWorkspaceId }
: {};
@@ -607,8 +626,19 @@ export function WorkspaceFileBrowser({
});
}, [folderPath, onBrowseStateChange, searchInput, targetProjectId, targetWorkspaceId]);
const listQueryKey = useMemo(() => queryKeys.issues.fileResources(issueId, {
workspace: effectiveWorkspace,
projectId: targetProjectId,
workspaceId: targetWorkspaceId,
mode,
q,
limit: LIST_LIMIT,
offset: 0,
path: folderPath,
}), [effectiveWorkspace, folderPath, issueId, mode, q, targetProjectId, targetWorkspaceId]);
const listQuery = useQuery({
queryKey: queryKeys.issues.fileResources(issueId, {
queryKey: listQueryKey,
queryFn: ({ signal }) => fileResourcesApi.list(issueId, {
workspace: effectiveWorkspace,
projectId: targetProjectId,
workspaceId: targetWorkspaceId,
@@ -617,22 +647,21 @@ export function WorkspaceFileBrowser({
limit: LIST_LIMIT,
offset: 0,
path: folderPath,
}),
queryFn: () => fileResourcesApi.list(issueId, {
workspace: effectiveWorkspace,
projectId: targetProjectId,
workspaceId: targetWorkspaceId,
mode,
q,
limit: LIST_LIMIT,
offset: 0,
path: folderPath,
}),
enabled: canListFiles,
}, { signal }),
enabled: queriesEnabled,
retry: false,
staleTime: 15_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
useEffect(() => {
if (active && pageVisible) return;
void queryClient.cancelQueries({
queryKey: ["issues", "file-resources", issueId, "list"],
});
}, [active, issueId, pageVisible, queryClient]);
const data = listQuery.data;
const items = useMemo(() => data?.items ?? [], [data]);
const workspaceLabel = data?.workspace?.workspaceLabel ?? null;
@@ -676,7 +705,7 @@ export function WorkspaceFileBrowser({
offset: spec.offset,
path: spec.path || null,
}),
queryFn: () => fileResourcesApi.list(issueId, {
queryFn: ({ signal }: { signal: AbortSignal }) => fileResourcesApi.list(issueId, {
workspace: effectiveWorkspace,
projectId: targetProjectId,
workspaceId: targetWorkspaceId,
@@ -685,10 +714,12 @@ export function WorkspaceFileBrowser({
limit: LIST_LIMIT,
offset: spec.offset,
path: spec.path || null,
}),
enabled: canListFiles && isLazyBrowse,
}, { signal }),
enabled: queriesEnabled && isLazyBrowse,
retry: false,
staleTime: 15_000,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
})),
});
const lazyItemsByFolder = useMemo(() => {
@@ -989,15 +1020,37 @@ export function WorkspaceFileBrowser({
);
} else if (listQuery.isError) {
const status = listQuery.error instanceof ApiError ? listQuery.error.status : 0;
const errorCode = listQuery.error instanceof ApiError && listQuery.error.body && typeof listQuery.error.body === "object"
? (listQuery.error.body as { code?: unknown }).code
: null;
const changedFilesTemporarilyUnavailable = mode === "changed" && (
status === 503 ||
status === 504 ||
errorCode === "workspace_git_scan_saturated" ||
errorCode === "workspace_git_scan_timeout"
);
body = (
<StateMessage
icon={<AlertTriangle aria-hidden="true" className="h-5 w-5 text-amber-500" />}
title="Couldn't load files"
title={changedFilesTemporarilyUnavailable ? "Changed files temporarily unavailable" : "Couldn't load files"}
body={
status === 404
changedFilesTemporarilyUnavailable
? "Paperclip is limiting workspace scans to keep the server responsive. Try again in a moment."
: status === 404
? "Workspace browsing isn't available for this issue."
: "Something went wrong loading workspace files."
}
actions={changedFilesTemporarilyUnavailable ? (
<Button
type="button"
variant="outline"
size="sm"
disabled={!queriesEnabled}
onClick={() => void listQuery.refetch()}
>
<RefreshCcw aria-hidden="true" className="mr-1 h-3 w-3" /> Retry
</Button>
) : null}
/>
);
} else if (data?.state === "unavailable") {
@@ -1035,28 +1088,42 @@ export function WorkspaceFileBrowser({
return (
<div className={cn("flex min-h-0 min-w-0 flex-col gap-2", className)}>
<div className="relative min-w-0 max-w-full overflow-hidden">
<Search
aria-hidden="true"
className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
/>
<Input
ref={inputRef}
type="search"
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search files by name or path…"
aria-label="Search workspace files"
role="combobox"
aria-expanded={items.length > 0}
aria-controls={items.length > 0 ? listboxId : undefined}
aria-activedescendant={activeOptionId}
autoFocus={autoFocusSearch}
autoComplete="off"
spellCheck={false}
className="h-8 w-full max-w-full min-w-0 pl-8 font-mono text-xs"
/>
<div className="flex min-w-0 max-w-full items-center gap-1 overflow-hidden">
<div className="relative min-w-0 flex-1">
<Search
aria-hidden="true"
className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
/>
<Input
ref={inputRef}
type="search"
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search files by name or path…"
aria-label="Search workspace files"
role="combobox"
aria-expanded={items.length > 0}
aria-controls={items.length > 0 ? listboxId : undefined}
aria-activedescendant={activeOptionId}
autoFocus={autoFocusSearch}
autoComplete="off"
spellCheck={false}
className="h-8 w-full max-w-full min-w-0 pl-8 font-mono text-xs"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => void listQuery.refetch()}
disabled={!queriesEnabled || listQuery.isFetching}
aria-label="Refresh workspace files"
title="Refresh workspace files"
className="h-8 w-8 shrink-0"
>
<RefreshCcw aria-hidden="true" className={cn("h-3.5 w-3.5", listQuery.isFetching && "animate-spin")} />
</Button>
</div>
<WorkspaceFileBreadcrumbs