Add workspace file viewer and artifact links (#7681)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent work is issue-centered, and reviewers often need to inspect
files, artifacts, and path references produced during that work.
> - Before this branch, workspace-relative paths and artifact file
references were not first-class inspectable objects in the board UI.
> - Safe file viewing needs shared resource contracts, server-side
workspace boundary checks, and UI that opens files without exposing
arbitrary host paths.
> - The workspace file viewer branch needed to stay as one active PR and
be rebased onto current `paperclipai/paperclip:master` for review.
> - This pull request adds the workspace file resource API, issue-page
file viewer and browser, markdown file-reference links, and artifact
file chips.
> - The benefit is that board users can inspect relevant files from
issue context while preserving workspace boundaries and auditability.

## Linked Issues or Issue Description

No public GitHub issue exists for this branch. Internal Paperclip
issues: `PAP-1953`, `PAP-10539`, `PAP-10733`.

Problem / motivation:
- Board users need to open workspace-relative files mentioned by agents
or attached as work-product metadata without switching to a terminal.
- The UI needs to support both direct file-path opening and workspace
browsing/searching from an issue page.
- The server must enforce company access, workspace boundaries, size
limits, rate limits, and safe audit logging.

Related PR:
- Prior closed attempt: #4442
- Single active PR for this branch: #7681

## What Changed

- Added shared workspace file resource types, validators, and
workspace-file `resourceRef` metadata validation for work products.
- Added server routes/services for resolving, listing, and previewing
workspace-relative files with access checks, scan caps, list-specific
limits, and audit logging.
- Added the issue file viewer provider, sheet, workspace browser,
command-palette action, markdown workspace-file autolinks, and artifact
file chips.
- Updated issue workspace UI and stories/tests for file browsing and
workspace file opening.
- Rebased the branch onto current `paperclipai/paperclip:master` and
updated the existing single PR branch.
- Addressed current-head Greptile follow-ups by applying `offset`
consistently across search/recent/changed file listings, restoring
stopped-service port ownership checks before auto-port reuse, and
stabilizing the workspace browser pagination test.

## Verification

Current local verification after rebase to `public/master`:
- `pnpm exec vitest run packages/shared/src/work-product.test.ts
server/src/__tests__/file-resources.test.ts
server/src/__tests__/instance-settings-routes.test.ts
server/src/__tests__/instance-settings-service.test.ts
server/src/__tests__/workspace-runtime.test.ts
ui/src/components/FileViewerSheet.test.tsx
ui/src/components/FileViewerSheet.copy.test.tsx
ui/src/components/WorkspaceFileBrowser.test.tsx
ui/src/components/WorkspaceFileMarkdownBody.test.tsx
ui/src/context/FileViewerContext.test.ts
ui/src/lib/remark-workspace-file-refs.test.ts
ui/src/lib/workspace-file-parser.test.ts
ui/src/components/IssueWorkspaceCard.test.tsx` - 13 files passed, 197
tests passed.
- `pnpm -r --filter @paperclipai/shared --filter @paperclipai/server
--filter @paperclipai/ui typecheck` - passed.
- `pnpm exec vitest run ui/src/components/WorkspaceFileBrowser.test.tsx`
- 1 file passed, 25 tests passed.
- `pnpm exec vitest run server/src/__tests__/file-resources.test.ts
server/src/__tests__/workspace-runtime.test.ts` - 2 files passed, 90
tests passed.
- `pnpm -r --filter @paperclipai/server typecheck` - passed.
- Confirmed branch is `0` behind and `46` ahead of current
`public/master` after rebase and follow-up commits.
- Confirmed the PR diff does not include `pnpm-lock.yaml`.
- Confirmed the PR diff does not include `.github/workflows` changes.
- Searched GitHub for duplicate or related workspace file viewer
PRs/issues; #4442 is the prior closed attempt and this PR is the single
active PR for the branch.
- No screenshots were committed; the task explicitly asked not to add
design screenshots or images unless they were part of the work.

Current remote verification on head
`a698a7bc10137baf7d25bd5722e1d6e0343387c1`:
- Greptile Review - success, 64 files reviewed, 0 comments added, no
unresolved Greptile review threads.
- PR workflow `verify` - success.
- Typecheck + Release Registry, General tests, workspace test shards,
serialized server suites, Build, Canary Dry Run, e2e, Socket, and Snyk -
success.
- `security-review` - neutral, with output saying a draft advisory was
filed for maintainer review and is not a merge block.
- `commitperclip PR Review / review` - cancelled after the security gate
detected flags and timed out while creating/reviewing the advisory. I
reran it once and it cancelled the same way; no actionable code/test
failure was exposed in the job logs.

## Risks

- This is a broad UI/server feature PR, so review needs to pay attention
to route authorization, workspace boundary handling, and markdown
autolink false positives.
- Workspace browsing intentionally caps list results and scan depth;
very large workspaces may require users to refine search terms.
- Remote workspace preview remains unavailable until remote file-access
support is implemented.
- The neutral commitperclip security-review advisory needs maintainer
review, but the check output says it is not a merge block.

> 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 coding agent in a Paperclip/Codex local tool-use
environment, medium reasoning, with shell/GitHub CLI tool use for branch
inspection, verification, rebase, PR update, Greptile review, and CI
inspection.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] If this change affects the UI, I have included before/after
screenshots
- [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
- [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>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Dotta
2026-06-09 17:17:43 -05:00
committed by GitHub
parent bf62e3fbf1
commit 468edd8b22
64 changed files with 10816 additions and 82 deletions
@@ -210,6 +210,8 @@ export function InstanceExperimentalSettings() {
experimentalQuery.data?.enableStreamlinedLeftNavigation === true;
const enableIssuePlanDecompositions =
experimentalQuery.data?.enableIssuePlanDecompositions === true;
const enableExperimentalFileViewer =
experimentalQuery.data?.enableExperimentalFileViewer === true;
const enableCloudSync = experimentalQuery.data?.enableCloudSync === true;
const autoRestartDevServerWhenIdle = experimentalQuery.data?.autoRestartDevServerWhenIdle === true;
const enableIssueGraphLivenessAutoRecovery =
@@ -286,6 +288,27 @@ export function InstanceExperimentalSettings() {
</div>
</section>
<section className="rounded-xl border border-border bg-card p-5">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1.5">
<h2 className="text-sm font-semibold">Experimental File Viewer</h2>
<p className="max-w-2xl text-sm text-muted-foreground">
Show task detail controls for browsing and previewing workspace files relative to a task.
</p>
</div>
<ToggleSwitch
checked={enableExperimentalFileViewer}
onCheckedChange={() =>
toggleMutation.mutate({
enableExperimentalFileViewer: !enableExperimentalFileViewer,
})
}
disabled={toggleMutation.isPending}
aria-label="Toggle experimental file viewer setting"
/>
</div>
</section>
<section className="rounded-xl border border-border bg-card p-5">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1.5">
+81 -2
View File
@@ -3,10 +3,11 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent, Issue, IssueAttachment, IssueTreeControlPreview, IssueTreeHold, IssueWorkProduct } from "@paperclipai/shared";
import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from "react";
import { NavigationType } from "react-router-dom";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { canBoardResolveRecoveryAction, IssueDetail } from "./IssueDetail";
import { canBoardResolveRecoveryAction, IssueDetail, shouldScrollIssueDetailToTopOnNavigation } from "./IssueDetail";
const mockIssuesApi = vi.hoisted(() => ({
get: vi.fn(),
@@ -74,6 +75,7 @@ const mockPushToast = vi.hoisted(() => vi.fn());
const mockIssuesListRender = vi.hoisted(() => vi.fn());
const mockIssueChatThreadRender = vi.hoisted(() => vi.fn());
const mockImageGalleryRender = vi.hoisted(() => vi.fn());
const mockIssueWorkspaceCardRender = vi.hoisted(() => vi.fn());
vi.mock("../api/issues", () => ({
issuesApi: mockIssuesApi,
@@ -281,7 +283,10 @@ vi.mock("../components/IssueRunLedger", () => ({
}));
vi.mock("../components/IssueWorkspaceCard", () => ({
IssueWorkspaceCard: () => <div>Workspace</div>,
IssueWorkspaceCard: (props: { onBrowseFiles?: () => void; onOpenFileByPath?: () => void }) => {
mockIssueWorkspaceCardRender(props);
return <div>Workspace</div>;
},
}));
vi.mock("../components/ImageGalleryModal", () => ({
@@ -355,6 +360,7 @@ vi.mock("@/components/ui/sheet", () => ({
Sheet: ({ children, open }: { children?: ReactNode; open?: boolean }) => (open ? <div>{children}</div> : null),
SheetContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
SheetHeader: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
SheetDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
SheetTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
}));
@@ -932,11 +938,13 @@ describe("IssueDetail", () => {
});
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableIssuePlanDecompositions: false,
enableExperimentalFileViewer: false,
});
mockIssuesApi.listAcceptedPlanDecompositions.mockResolvedValue([]);
mockIssuesListRender.mockClear();
mockIssueChatThreadRender.mockClear();
mockImageGalleryRender.mockClear();
mockIssueWorkspaceCardRender.mockClear();
});
afterEach(async () => {
@@ -992,10 +1000,55 @@ describe("IssueDetail", () => {
expect(mockIssuesApi.listAcceptedPlanDecompositions).not.toHaveBeenCalled();
});
it("hides file viewer entry points by default", async () => {
mockIssuesApi.get.mockResolvedValue(createIssue());
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<IssueDetail />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.querySelector('[aria-label="Open file in this issue"]')).toBeNull();
const latestWorkspaceProps = mockIssueWorkspaceCardRender.mock.calls.at(-1)?.[0];
expect(latestWorkspaceProps?.onBrowseFiles).toBeUndefined();
expect(latestWorkspaceProps?.onOpenFileByPath).toBeUndefined();
});
it("shows file viewer entry points when the experimental flag is enabled", async () => {
mockIssuesApi.get.mockResolvedValue(createIssue());
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableIssuePlanDecompositions: false,
enableExperimentalFileViewer: true,
});
await act(async () => {
root.render(
<QueryClientProvider client={queryClient}>
<IssueDetail />
</QueryClientProvider>,
);
});
await flushReact();
await flushReact();
expect(container.querySelector('[aria-label="Open file in this issue"]')).not.toBeNull();
const latestWorkspaceProps = mockIssueWorkspaceCardRender.mock.calls.at(-1)?.[0];
expect(latestWorkspaceProps?.onBrowseFiles).toEqual(expect.any(Function));
expect(latestWorkspaceProps?.onOpenFileByPath).toEqual(expect.any(Function));
});
it("shows the plan decomposition panel when the experimental flag is enabled", async () => {
mockIssuesApi.get.mockResolvedValue(createIssue());
mockInstanceSettingsApi.getExperimental.mockResolvedValue({
enableIssuePlanDecompositions: true,
enableExperimentalFileViewer: false,
});
mockIssuesApi.listAcceptedPlanDecompositions.mockResolvedValue([
{
@@ -1960,3 +2013,29 @@ describe("canBoardResolveRecoveryAction", () => {
).toBe(false);
});
});
describe("shouldScrollIssueDetailToTopOnNavigation", () => {
it("does not scroll when only URL search params changed for the same issue", () => {
expect(shouldScrollIssueDetailToTopOnNavigation({
previousIssueId: "PAP-10306",
nextIssueId: "PAP-10306",
navigationType: NavigationType.Push,
})).toBe(false);
});
it("scrolls on forward navigation to a different issue", () => {
expect(shouldScrollIssueDetailToTopOnNavigation({
previousIssueId: "PAP-1",
nextIssueId: "PAP-2",
navigationType: NavigationType.Push,
})).toBe(true);
});
it("does not scroll on browser back or forward restoration", () => {
expect(shouldScrollIssueDetailToTopOnNavigation({
previousIssueId: "PAP-1",
nextIssueId: "PAP-2",
navigationType: NavigationType.Pop,
})).toBe(false);
});
});
+130 -2
View File
@@ -87,6 +87,9 @@ import { IssueRunLedger } from "../components/IssueRunLedger";
import { IssueWorkspaceCard } from "../components/IssueWorkspaceCard";
import type { MentionOption } from "../components/MarkdownEditor";
import { ImageGalleryModal } from "../components/ImageGalleryModal";
import { FileViewerProvider, useRequiredFileViewer } from "../context/FileViewerContext";
import { FileViewerSheet } from "../components/FileViewerSheet";
import { ArtifactFileChip } from "../components/ArtifactFileChip";
import { ScrollToBottom } from "../components/ScrollToBottom";
import { StatusIcon } from "../components/StatusIcon";
import { PriorityIcon } from "../components/PriorityIcon";
@@ -132,6 +135,7 @@ import {
Eye,
EyeOff,
Flag,
FileCode2,
Hexagon,
ListTree,
MessageSquare,
@@ -164,6 +168,8 @@ import {
type RequestConfirmationInteraction,
type SuggestTasksInteraction,
type IssueTreeControlMode,
type WorkspaceFileRef,
workspaceFileRefSchema,
} from "@paperclipai/shared";
type StopAndFinalizeRunError = Error & {
@@ -261,6 +267,15 @@ export function canBoardResolveRecoveryAction(
return membership.membershipRole !== "viewer" && membership.membershipRole !== null;
}
export function shouldScrollIssueDetailToTopOnNavigation(input: {
previousIssueId: string | undefined;
nextIssueId: string | undefined;
navigationType: ReturnType<typeof useNavigationType>;
}): boolean {
if (input.navigationType === "POP") return false;
return input.previousIssueId !== input.nextIssueId;
}
function resolveRunningIssueRun(
activeRun: ActiveRunForIssue | null | undefined,
liveRuns: readonly LiveRunForIssue[] | undefined,
@@ -298,6 +313,15 @@ function asRecord(value: unknown): Record<string, unknown> | null {
return value as Record<string, unknown>;
}
function extractWorkspaceFileRefFromWorkProduct(
workProduct: { metadata: Record<string, unknown> | null },
): WorkspaceFileRef | null {
const metadata = asRecord(workProduct.metadata);
if (!metadata) return null;
const parsed = workspaceFileRefSchema.safeParse(metadata.resourceRef);
return parsed.success ? parsed.data : null;
}
function usageNumber(usage: Record<string, unknown> | null, ...keys: string[]) {
if (!usage) return 0;
for (const key of keys) {
@@ -1276,6 +1300,7 @@ export function IssueDetail() {
const [moreOpen, setMoreOpen] = useState(false);
const [copied, setCopied] = useState(false);
const [mobilePropsOpen, setMobilePropsOpen] = useState(false);
const [fileViewerPromptOpen, setFileViewerPromptOpen] = useState(false);
const [detailTab, setDetailTab] = useState("chat");
const [handoffFocusSignal, setHandoffFocusSignal] = useState(0);
const [pendingApprovalAction, setPendingApprovalAction] = useState<{
@@ -1296,6 +1321,7 @@ export function IssueDetail() {
const [pendingCommentComposerFocusKey, setPendingCommentComposerFocusKey] = useState(0);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const lastMarkedReadIssueIdRef = useRef<string | null>(null);
const lastScrollIssueIdRef = useRef<string | undefined>(undefined);
const commentComposerRef = useRef<IssueChatComposerHandle | null>(null);
const cancelledQueuedOptimisticCommentIdsRef = useRef(new Set<string>());
const resolvedIssueDetailState = useMemo(
@@ -1494,6 +1520,7 @@ export function IssueDetail() {
const feedbackDataSharingPreference = instanceGeneralSettings?.feedbackDataSharingPreference ?? "prompt";
const showPlanDecompositionsSection =
instanceExperimentalSettings?.enableIssuePlanDecompositions === true;
const fileViewerEnabled = instanceExperimentalSettings?.enableExperimentalFileViewer === true;
const { orderedProjects } = useProjectOrder({
projects: projects ?? [],
companyId: selectedCompanyId,
@@ -2759,7 +2786,9 @@ export function IssueDetail() {
// Scroll to top on forward navigation (PUSH/REPLACE) so issue doesn't
// inherit the inbox/issues-list scroll position on mobile.
useEffect(() => {
if (navigationType === "POP") return;
const previousIssueId = lastScrollIssueIdRef.current;
lastScrollIssueIdRef.current = issueId;
if (!shouldScrollIssueDetailToTopOnNavigation({ previousIssueId, nextIssueId: issueId, navigationType })) return;
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
const main = document.getElementById("main-content");
if (main) main.scrollTop = 0;
@@ -2923,6 +2952,12 @@ export function IssueDetail() {
setDetailTab("chat");
setPendingCommentComposerFocusKey((current) => current + 1);
}
if (action === "open_file_viewer") {
if (!fileViewerEnabled) return;
event.preventDefault();
event.stopPropagation();
setFileViewerPromptOpen(true);
}
};
document.addEventListener("pointerdown", handlePointerDown, true);
@@ -2934,7 +2969,7 @@ export function IssueDetail() {
document.removeEventListener("focusin", handleFocusIn, true);
document.removeEventListener("keydown", handleKeyDown, true);
};
}, [keyboardShortcutsEnabled, navigate, sourceBreadcrumb.href]);
}, [fileViewerEnabled, keyboardShortcutsEnabled, navigate, sourceBreadcrumb.href]);
useEffect(() => {
const hash = location.hash;
@@ -2982,6 +3017,20 @@ export function IssueDetail() {
commentComposerRef.current?.focus();
}, [detailTab, pendingCommentComposerFocusKey]);
useEffect(() => {
if (!fileViewerEnabled) return;
const handleOpenFileViewer = () => {
setFileViewerPromptOpen(true);
};
window.addEventListener("paperclip:open-file-viewer", handleOpenFileViewer as EventListener);
return () => {
window.removeEventListener(
"paperclip:open-file-viewer",
handleOpenFileViewer as EventListener,
);
};
}, [fileViewerEnabled]);
const promotedOutputAttachmentIds = useMemo(() => getPromotedOutputAttachmentIds(workProducts), [workProducts]);
const attachmentList = useMemo(
() => (attachments ?? []).filter((attachment) => !promotedOutputAttachmentIds.has(attachment.id)),
@@ -3423,6 +3472,7 @@ export function IssueDetail() {
);
return (
<FileViewerProvider issueId={issue.id} enabled={fileViewerEnabled}>
<div className="max-w-3xl space-y-6">
{/* Parent chain breadcrumb */}
{ancestors.length > 0 && (
@@ -3672,6 +3722,17 @@ export function IssueDetail() {
<Archive className="h-4 w-4" />
</Button>
)}
{fileViewerEnabled ? (
<Button
variant="ghost"
size="icon-xs"
onClick={() => setFileViewerPromptOpen(true)}
title="Open file... (g f)"
aria-label="Open file in this issue"
>
<FileCode2 className="h-4 w-4" />
</Button>
) : null}
<Button
variant="ghost"
size="icon-xs"
@@ -3996,8 +4057,35 @@ export function IssueDetail() {
issue={issue}
project={resolvedProject}
onUpdate={(data) => updateIssue.mutate(data)}
onBrowseFiles={fileViewerEnabled ? () => setFileViewerPromptOpen(true) : undefined}
onOpenFileByPath={fileViewerEnabled ? () => setFileViewerPromptOpen(true) : undefined}
/>
{fileViewerEnabled && issue.workProducts && issue.workProducts.length > 0 && (() => {
const workProductsWithFileRefs = issue.workProducts
.map((product) => ({ product, fileRef: extractWorkspaceFileRefFromWorkProduct(product) }))
.filter(({ fileRef }) => fileRef !== null);
if (workProductsWithFileRefs.length === 0) return null;
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-medium text-muted-foreground">Artifacts</h3>
</div>
<div className="flex flex-wrap gap-2">
{workProductsWithFileRefs.map(({ product, fileRef }) => (
<ArtifactFileChip
key={product.id}
workspaceFileRef={fileRef!}
title={product.title}
/>
))}
</div>
</div>
);
})()}
<Separator />
<Tabs value={detailTab} onValueChange={setDetailTab} className="space-y-3">
@@ -4314,7 +4402,47 @@ export function IssueDetail() {
</ScrollArea>
</SheetContent>
</Sheet>
{fileViewerEnabled ? (
<IssueFileViewer
issueId={issue.id}
companyId={issue.companyId}
promptOpen={fileViewerPromptOpen}
onPromptOpenChange={setFileViewerPromptOpen}
/>
) : null}
<ScrollToBottom />
</div>
</FileViewerProvider>
);
}
function IssueFileViewer({
issueId,
companyId,
promptOpen,
onPromptOpenChange,
}: {
issueId: string;
companyId: string;
promptOpen: boolean;
onPromptOpenChange: (next: boolean) => void;
}) {
const viewer = useRequiredFileViewer();
const open = viewer.state !== null || viewer.browse || promptOpen;
const showPromptWhenEmpty = (promptOpen || viewer.browse) && viewer.state === null;
return (
<FileViewerSheet
issueId={issueId}
companyId={companyId}
open={open}
showPromptWhenEmpty={showPromptWhenEmpty}
onOpenChange={(next) => {
if (!next) {
onPromptOpenChange(false);
// Clears any file view and browse state from the URL.
viewer.close();
}
}}
/>
);
}