Files
PaperClipAI/ui/src/components/RunnerInspector.test.tsx
T
DottaandClaude Opus 5.5 b56f240f45 feat(analytics): show session replay text by default, mask only customer content (#22057)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip Cloud records browser sessions with PostHog session
replay
> - Replay masked all text and showed only an allowlist of chrome, so
most replays showed only stars
> - The team cannot see how people use the board, and the allowlist
needed a review for each new label
> - The owner decided to show text by default and mask only marked
customer content, the way PostHog normally works
> - This pull request flips the default, removes the allowlist, and
marks every surface that can show connected-account content
> - The benefit is readable replays, while Google user data and Slack
data stay masked

## Linked Issues or Issue Description

**Subsystem affected**

Hosted Cloud browser analytics: PostHog session replay in the board UI
(`ui/src/lib/analytics/`).

**Problem or motivation**

Replay masked every text node. Only sidebar items and opt-in components
showed text. Replays were almost unreadable. Each new label needed an
`analyticsChrome` opt-in and an allowlist review.

**Proposed solution**

Record text as it is. Mask text only inside `ph-mask` (customer
content), `ph-no-capture` (secrets, blocked) and editable content. Add
`ANALYTICS_MASK_CLASS` to every surface that can show connected-account
content (Gmail, Calendar, Drive and Docs, Slack) or other free-form text
from agents or customers.

**Alternatives considered**

Keep "mask all" and grow the allowlist. This needs a review for each
label and still hides most of the board.

## What Changed

- `privacy.ts`: `ANALYTICS_MASK_TEXT_SELECTOR` is now `.ph-mask,
.ph-no-capture, [contenteditable]:not([contenteditable="false"])`. rrweb
masks a text node only when its parent or an ancestor matches the
selector. Removed `maskReplayText`, `isReplayTextRevealed`,
`ANALYTICS_UNMASK_ATTRIBUTE` and `ANALYTICS_UNMASK_PROPS`.
- `product-analytics.ts`: removed `maskTextFn`, so rrweb uses its
default star masking. `maskAllInputs`, `blockClass`, `maskAttributeFn`,
`mask_all_text` and `mask_all_element_attributes` do not change.
- Removed the `analyticsChrome` prop from `Button`, `Label`,
`TabsTrigger`, `EmptyState` and `SidebarNavItem`, and from all sidebar
call sites.
- Added `ANALYTICS_MASK_CLASS` to the content element (not the chrome)
of these surfaces:
- Link preview cards, task quicklook description, external object pills
and rows, related-work titles.
  - Email message cards and email send intents.
- Connected account names and email addresses (Browse, Connections, app
detail headers, app sidebar, connection choice list, connection access
and repair cards), GitHub login and repositories, Slack workspace names,
chat channel and linked user labels.
- Inbox and decision rows (subject and detail), obligation evidence,
Needs You notes and receipts, decision options and result summaries, and
the interaction card roots (questions, options, answers, tool action
requests, suggested tasks).
- Approval payloads, action card input and reason, recovery card
headline, evidence and options, run ledger retry detail, interrupt
handoff previews.
- Run transcripts, run failure details and run events on the agent page.
- Search result snippets, toast bodies, voice and call transcripts, case
summary, files and fields, attachment previews, artifact previews (text,
tables, patches and documents).
- Replaced `unmask-allowlist.test.ts` with `replay-masking.test.tsx`. It
checks that unmarked chrome records as it is, that each marker masks,
that a rendered voice transcript and run transcript mask, that each
surface above has the class, and that autocapture records no element
text. Updated `privacy.test.ts`, `shared-chrome.test.tsx` and
`product-analytics.test.ts`.
- Updated `doc/cloud-browser-analytics.md`: new default, marker classes,
masked surfaces, and residual risk.

## Verification

- `pnpm exec vitest run src/lib/analytics` in `ui/`: 83 tests pass.
- Vitest for the 48 test files next to the changed components: 994 tests
pass.
- `tsc --noEmit -p ui/tsconfig.json`: no new errors (only the existing
generated Storybook catalog errors).
- `pnpm verify` exits 2 because a doc is a global CI input. Required CI
supplies the broad coverage.
- Manual: I ran an isolated local instance with a Cloud-like browser
analytics config. `PAPERCLIP_POSTHOG_HOST` pointed to a local capture
server, not PostHog. I opened a task page in headless Chromium, hovered
a GitHub pull request link, and decoded the captured `/s/` replay
payloads:
- Clear text: sidebar (`New task`, `Chat`, `Tasks`, `Inbox`, `More`),
breadcrumb, task title `Quarterly launch checklist`, `REP-1`, the
Connectors promo heading and button.
- Masked (stars only): the markdown task body, the chat comment, the
link preview card (pull request title, author, URL, status), and the
company menu.
- Marker strings in the body, comment and preview never appeared in
clear text in any payload.
- The page `<title>` (task title and company name) is in the replay
head. This is accepted residual risk.

## Risks

- Text that is not marked is now recorded. Task titles, agent names,
project names, company names, routine names, artifact and document
titles, and activity rows are visible in replays. The owner accepted
this. An agent can copy email or Slack text into a task title.
- A new surface that shows connected-account content without
`ANALYTICS_MASK_CLASS` is recorded until somebody marks it.
`replay-masking.test.tsx` and the doc list the marked surfaces.
- The masking options in `posthog.init` take precedence over the PostHog
project masking settings (posthog-js 1.450), so a dashboard change
cannot unmask content. Keep the project settings empty to avoid a
console warning.
- Some masked areas also mask nearby fixed labels (for example the
interaction card buttons). This is safe.
- Analytics is off on self-hosted and local installs, so they see no
change.

> 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

- Claude Opus 5.5 (claude-opus-5-5), Anthropic, with tool use and code
execution in Claude Code.

## 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-17 15:18:50 -06:00

888 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @vitest-environment jsdom
import { createElement, type ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "@/api/client";
import { ConnectivityProvider, createConnectivityStore, type ConnectivityStore } from "@/lib/connectivity";
import { RunnerInspector } from "./RunnerInspector";
import { isBlockedFromReplay, replayLeaks } from "@/lib/analytics/replay-recording.test-utils";
const accessMock = vi.hoisted(() => vi.fn());
const eventsMock = vi.hoisted(() => vi.fn());
const traceMock = vi.hoisted(() => vi.fn());
const revealMock = vi.hoisted(() => vi.fn());
const downloadMock = vi.hoisted(() => vi.fn());
const deleteMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/access", () => ({
accessApi: { getCurrentBoardAccess: accessMock },
}));
vi.mock("@/api/heartbeats", () => ({
heartbeatsApi: {
events: eventsMock,
providerTrace: traceMock,
revealProviderTraceFrame: revealMock,
downloadProviderTrace: downloadMock,
deleteProviderTrace: deleteMock,
},
}));
vi.mock("@/components/ui/sheet", () => ({
Sheet: ({ open, children }: { open: boolean; children: ReactNode }) =>
open ? createElement("div", null, children) : null,
SheetContent: ({ children }: { children: ReactNode }) =>
createElement("div", null, children),
SheetDescription: ({ children }: { children: ReactNode }) =>
createElement("p", null, children),
SheetHeader: ({ children }: { children: ReactNode }) =>
createElement("header", null, children),
SheetTitle: ({ children }: { children: ReactNode }) =>
createElement("h2", null, children),
}));
vi.mock("@/components/ui/select", () => ({
Select: ({ children }: { children: ReactNode }) =>
createElement("div", null, children),
SelectContent: ({ children }: { children: ReactNode }) =>
createElement("div", null, children),
SelectItem: ({ children }: { children: ReactNode }) =>
createElement("span", null, children),
SelectTrigger: ({ children }: { children: ReactNode }) =>
createElement("button", { type: "button" }, children),
SelectValue: ({ placeholder }: { placeholder?: string }) =>
createElement("span", null, placeholder),
}));
vi.mock("@/components/ui/scroll-area", () => ({
ScrollArea: ({ children }: { children: ReactNode }) =>
createElement("div", null, children),
}));
(
globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
async function flush() {
for (let index = 0; index < 5; index += 1) {
await Promise.resolve();
await new Promise((resolve) => setTimeout(resolve, 0));
flushSync(() => {});
}
}
function traceInspection(runId: string, marker: string) {
return {
trace: {
id: `trace-${runId}`,
runId,
companyId: "company-1",
status: "complete",
provider: "codex",
frameCount: 1,
byteCount: 31,
digest: `sha256:${"a".repeat(64)}`,
reason: null,
requestedBy: "local-admin",
createdAt: "2026-08-22T12:00:00.000Z",
expiresAt: "2026-08-23T12:00:00.000Z",
deletedAt: null,
schema: "paperclip.provider_trace_metadata.v1",
},
entries: [
{
kind: "frame",
frameId: 1,
direction: "provider_to_client",
byteLength: 31,
parsed: { method: "item/completed", marker },
withheldPaths: ["secret"],
},
],
};
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((next) => {
resolve = next;
});
return { promise, resolve };
}
describe("RunnerInspector", () => {
let container: HTMLDivElement;
let root: Root;
beforeEach(() => {
window.history.replaceState(null, "", "/");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
accessMock.mockResolvedValue({
source: "local_implicit",
isInstanceAdmin: false,
});
eventsMock.mockResolvedValue([]);
traceMock.mockResolvedValue({ trace: null, entries: [] });
});
afterEach(() => {
flushSync(() => root.unmount());
container.remove();
vi.restoreAllMocks();
vi.clearAllMocks();
});
it("keeps canonical inspection available when raw capture was disabled", async () => {
const rerun = vi.fn();
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
onRerunWithTrace={rerun}
/>,
),
);
await flush();
expect(container.textContent).toContain(
"Correlate exact provider traffic with every interpretation stage",
);
expect(container.textContent).toContain(
"Raw provider capture was off for this run.",
);
flushSync(() =>
Array.from(container.querySelectorAll("button"))
.find((button) => button.textContent?.trim() === "Overview")
?.click(),
);
await flush();
expect(container.textContent).toContain("Raw capture off");
expect(container.textContent).not.toContain("Expired");
const rerunButton = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.includes("Re-run with provider trace"),
);
flushSync(() => rerunButton?.click());
expect(rerun).toHaveBeenCalledOnce();
});
it("shows redacted frames by default and warns before exact reveal", async () => {
traceMock.mockResolvedValue({
trace: {
id: "trace-1",
runId: "run-1",
companyId: "company-1",
status: "complete",
provider: "codex",
frameCount: 1,
byteCount: 31,
digest: `sha256:${"a".repeat(64)}`,
reason: null,
requestedBy: "local-admin",
createdAt: "2026-08-22T12:00:00.000Z",
expiresAt: "2026-08-23T12:00:00.000Z",
deletedAt: null,
schema: "paperclip.provider_trace_metadata.v1",
},
entries: [
{
kind: "frame",
frameId: 1,
direction: "provider_to_client",
byteLength: 31,
parsed: { method: "item/completed", authorization: "[withheld]" },
withheldPaths: ["authorization"],
},
],
});
revealMock.mockResolvedValue({
schema: "paperclip.provider_trace_frame.v1",
frameId: 1,
timestamp: "1",
direction: "provider_to_client",
transport: "stdio_jsonl",
provider: "codex",
byteLength: 31,
digest: `sha256:${"b".repeat(64)}`,
rawBase64: btoa(JSON.stringify({ method: "item/completed" })),
});
const confirm = vi.spyOn(window, "confirm").mockReturnValue(true);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
expect(container.textContent).toContain("Withheld paths: authorization");
expect(container.textContent).not.toContain("rawBase64");
const reveal = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.includes("Reveal exact frame"),
);
flushSync(() => reveal?.click());
await flush();
expect(confirm).toHaveBeenCalledWith(
expect.stringContaining("may contain prompts"),
);
expect(revealMock).toHaveBeenCalledWith("run-1", 1);
});
it("does not reuse an exact frame after switching runs with the same frame id", async () => {
traceMock.mockImplementation(async (requestedRunId: string) =>
traceInspection(requestedRunId, `${requestedRunId}-redacted`),
);
revealMock.mockResolvedValue({
schema: "paperclip.provider_trace_frame.v1",
frameId: 1,
timestamp: "1",
direction: "provider_to_client",
transport: "stdio_jsonl",
provider: "codex",
byteLength: 31,
digest: `sha256:${"b".repeat(64)}`,
rawBase64: btoa(JSON.stringify({ secret: "run-one-secret" })),
});
vi.spyOn(window, "confirm").mockReturnValue(true);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
const reveal = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.includes("Reveal exact frame"),
);
flushSync(() => reveal?.click());
await flush();
expect(container.textContent).toContain("run-one-secret");
expect(isBlockedFromReplay("run-one-secret", document.body)).toBe(true);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-2"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
expect(container.textContent).not.toContain("run-one-secret");
await flush();
expect(container.textContent).toContain("run-2-redacted");
expect(container.textContent).not.toContain("run-one-secret");
});
it("blocks an exact frame revealed in the trace view from session replay", async () => {
traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted"));
revealMock.mockResolvedValue({
schema: "paperclip.provider_trace_frame.v1",
frameId: 1,
timestamp: "1",
direction: "provider_to_client",
transport: "stdio_jsonl",
provider: "codex",
byteLength: 31,
digest: `sha256:${"b".repeat(64)}`,
rawBase64: btoa(JSON.stringify({ authorization: "Bearer trace-view-Kq72Lx" })),
});
vi.spyOn(window, "confirm").mockReturnValue(true);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
flushSync(() =>
Array.from(document.querySelectorAll<HTMLButtonElement>('[role="tab"]')).find((tab) => tab.textContent?.includes("Exact trace"))!.click(),
);
await flush();
expect(replayLeaks("run-1-redacted", document.body)).toEqual({ rendered: true, recorded: false });
flushSync(() =>
Array.from(document.querySelectorAll("button")).find((button) => button.textContent?.includes("Reveal exact frame"))!.click(),
);
await flush();
expect(isBlockedFromReplay("Bearer trace-view-Kq72Lx", document.body)).toBe(true);
});
it("clears exact frames when raw-trace access is revoked while open", async () => {
traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted"));
revealMock.mockResolvedValue({
schema: "paperclip.provider_trace_frame.v1",
frameId: 1,
timestamp: "1",
direction: "provider_to_client",
transport: "stdio_jsonl",
provider: "codex",
byteLength: 31,
digest: `sha256:${"b".repeat(64)}`,
rawBase64: btoa(JSON.stringify({ secret: "revoked-secret" })),
});
vi.spyOn(window, "confirm").mockReturnValue(true);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
const reveal = Array.from(container.querySelectorAll("button")).find(
(button) => button.textContent?.includes("Reveal exact frame"),
);
flushSync(() => reveal?.click());
await flush();
expect(container.textContent).toContain("revoked-secret");
accessMock.mockResolvedValue({
source: "session",
isInstanceAdmin: false,
});
window.dispatchEvent(new Event("focus"));
await flush();
expect(accessMock.mock.calls.length).toBeGreaterThan(1);
expect(container.textContent).toContain(
"Raw provider traces require an instance administrator.",
);
expect(container.textContent).not.toContain("Reveal exact frame");
expect(container.textContent).not.toContain("revoked-secret");
});
it("does not let a stale initial access check override a newer denial", async () => {
const pendingInitialAccess = deferred<{
source: "local_implicit";
isInstanceAdmin: false;
}>();
accessMock
.mockReturnValueOnce(pendingInitialAccess.promise)
.mockResolvedValue({ source: "session", isInstanceAdmin: false });
traceMock.mockResolvedValue(traceInspection("run-1", "stale-secret"));
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
window.dispatchEvent(new Event("focus"));
await flush();
expect(container.textContent).toContain(
"Raw provider traces require an instance administrator.",
);
pendingInitialAccess.resolve({
source: "local_implicit",
isInstanceAdmin: false,
});
await flush();
expect(traceMock).not.toHaveBeenCalled();
expect(container.textContent).not.toContain("Reveal exact frame");
expect(container.textContent).not.toContain("stale-secret");
});
it("discards in-flight exact reads and disables privileged controls during deletion", async () => {
traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted"));
const pendingReveal = deferred<{
schema: string;
frameId: number;
timestamp: string;
direction: string;
transport: string;
provider: string;
byteLength: number;
digest: string;
rawBase64: string;
}>();
const pendingDownload = deferred<Blob>();
const pendingDelete = deferred<void>();
const pendingPostDeleteAccess = deferred<{
source: "local_implicit";
isInstanceAdmin: false;
}>();
revealMock.mockReturnValue(pendingReveal.promise);
downloadMock.mockReturnValue(pendingDownload.promise);
deleteMock.mockReturnValue(pendingDelete.promise);
vi.spyOn(window, "confirm").mockReturnValue(true);
const anchorClick = vi
.spyOn(HTMLAnchorElement.prototype, "click")
.mockImplementation(() => undefined);
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
const buttons = () => Array.from(container.querySelectorAll("button"));
flushSync(() =>
buttons()
.find((button) => button.textContent?.includes("Reveal exact frame"))
?.click(),
);
flushSync(() =>
buttons()
.find((button) => button.textContent?.includes("Download exact trace"))
?.click(),
);
await Promise.resolve();
expect(revealMock).toHaveBeenCalledWith("run-1", 1);
expect(downloadMock).toHaveBeenCalledWith("run-1");
flushSync(() =>
buttons()
.find((button) => button.textContent?.includes("Delete trace"))
?.click(),
);
expect(deleteMock).toHaveBeenCalledWith("run-1");
expect(container.textContent).not.toContain("Reveal exact frame");
expect(container.textContent).not.toContain("Download exact trace");
expect(container.textContent).not.toContain("Delete trace");
pendingReveal.resolve({
schema: "paperclip.provider_trace_frame.v1",
frameId: 1,
timestamp: "1",
direction: "provider_to_client",
transport: "stdio_jsonl",
provider: "codex",
byteLength: 31,
digest: `sha256:${"b".repeat(64)}`,
rawBase64: btoa(JSON.stringify({ secret: "late-secret" })),
});
pendingDownload.resolve(new Blob(["late raw trace"]));
await flush();
expect(container.textContent).not.toContain("late-secret");
expect(anchorClick).not.toHaveBeenCalled();
accessMock
.mockReturnValueOnce(pendingPostDeleteAccess.promise)
.mockResolvedValue({ source: "session", isInstanceAdmin: false });
pendingDelete.resolve();
await Promise.resolve();
window.dispatchEvent(new Event("focus"));
await flush();
expect(container.textContent).toContain(
"Raw provider traces require an instance administrator.",
);
pendingPostDeleteAccess.resolve({
source: "local_implicit",
isInstanceAdmin: false,
});
await flush();
expect(container.textContent).toContain(
"Raw provider traces require an instance administrator.",
);
expect(container.textContent).not.toContain("late-secret");
expect(anchorClick).not.toHaveBeenCalled();
});
it("keeps client and provider JSON-RPC id spaces separate when grouping operations", async () => {
eventsMock.mockResolvedValue([{
id: 41,
companyId: "company-1",
runId: "run-1",
agentId: "agent-1",
seq: 9,
eventType: "run.result.proposed",
stream: "stdout",
level: "info",
color: null,
message: null,
payload: { prpEvent: { sourceEventId: "runner:run-1:9", payload: {} } },
createdAt: "2026-08-22T12:00:03.000Z",
}]);
traceMock.mockResolvedValue({
trace: null,
entries: [
{ kind: "frame", frameId: 1, timestamp: "1", direction: "client_to_provider", parsed: { id: 1, method: "initialize" } },
{ kind: "frame", frameId: 2, timestamp: "2", direction: "provider_to_client", parsed: { id: 1, result: {} } },
{ kind: "frame", frameId: 3, timestamp: "3", direction: "provider_to_client", parsed: { id: 1, method: "item/tool/call", params: { callId: "finish-1", tool: "paperclip_finish" } } },
{ kind: "frame", frameId: 4, timestamp: "4", direction: "client_to_provider", parsed: { id: 1, result: { success: true } } },
{ kind: "interpretation", frameId: 3, stage: "typescript_codex_driver_normalization", disposition: "mapped", emittedEventIds: ["runner:run-1:9"], ruleId: "codex_driver.normalize.item/tool/call" },
],
});
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
expect(container.textContent).toContain("frames 1–2 · 0 PRP events");
expect(container.textContent).toContain("frames 3–4 · 1 PRP event");
expect(container.textContent).not.toContain("frames 1–4");
});
it("correlates a Codex web search through every stage to canonical PRP and presentation", async () => {
eventsMock.mockResolvedValue([
{
id: 91,
companyId: "company-1",
runId: "run-1",
agentId: "agent-1",
seq: 42,
eventType: "research.completed",
stream: "stdout",
level: "info",
color: null,
message: null,
payload: {
prpEvent: {
eventType: "research.completed",
sourceEventId: "event_runner_000001",
sourceSequence: 42,
payload: { query: "best bbq sauce", status: "completed" },
},
},
createdAt: "2026-08-22T12:00:01.000Z",
},
]);
traceMock.mockResolvedValue({
trace: {
id: "trace-1",
runId: "run-1",
companyId: "company-1",
status: "complete",
provider: "codex",
frameCount: 1,
byteCount: 512,
digest: `sha256:${"a".repeat(64)}`,
reason: null,
requestedBy: "local-admin",
createdAt: "2026-08-22T12:00:00.000Z",
expiresAt: "2026-08-23T12:00:00.000Z",
deletedAt: null,
schema: "paperclip.provider_trace_metadata.v1",
},
entries: [
{
kind: "frame",
frameId: 27,
timestamp: "1787400001000",
direction: "provider_to_client",
byteLength: 512,
digest: `sha256:${"b".repeat(64)}`,
parsed: {
method: "item/completed",
params: {
item: {
id: "search-1",
type: "webSearch",
query: "best bbq sauce",
results: [{ title: "Sauce guide", url: "https://example.com" }],
},
},
},
withheldPaths: [],
},
{
kind: "interpretation",
frameId: 27,
debugChannel: "rust_native",
debugSequence: 1,
stage: "rust_jsonrpc_parse",
ruleId: "codex.notification",
disposition: "mapped",
emittedEventIds: [],
droppedFields: [],
reason: "Parsed Codex notification",
},
{
kind: "interpretation",
frameId: 27,
debugChannel: "rust_native",
debugSequence: 2,
stage: "rust_durable_normalization",
ruleId: "provider.notification.known",
disposition: "mapped",
emittedEventIds: ["event_runner_000001"],
droppedFields: ["params.item.results"],
fieldMappings: [
{
inputPath: "params.item.query",
outputPath: "payload.query",
action: "copied",
reason: "Preserved the search query",
},
{
inputPath: "params.item.results",
action: "dropped",
reason: "Raw provider results are not part of this semantic event",
},
],
reason: "Normalized provider web search",
},
{
kind: "interpretation",
frameId: 27,
debugChannel: "typescript_runnerd_rehydration",
debugSequence: 1,
stage: "typescript_runnerd_rehydration",
ruleId: "runnerd.rehydrate.research.completed",
disposition: "mapped",
emittedEventIds: ["event_runner_000001"],
droppedFields: [],
reason: "Rehydrated canonical event",
},
{
kind: "interpretation",
frameId: 27,
debugChannel: "typescript_runnerd_rehydration",
debugSequence: 2,
stage: "typescript_codex_driver_normalization",
ruleId: "codex_driver.normalize.item/completed",
disposition: "mapped",
emittedEventIds: ["event_runner_000001"],
droppedFields: [],
reason: "Emitted canonical PRP event",
},
],
});
flushSync(() =>
root.render(
<RunnerInspector
runId="run-1"
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>,
),
);
await flush();
expect(container.textContent).toContain("webSearch");
expect(container.textContent).toContain("rust_jsonrpc_parse");
expect(container.textContent).toContain("rust_durable_normalization");
expect(container.textContent).toContain("typescript_runnerd_rehydration");
expect(container.textContent).toContain("typescript_codex_driver_normalization");
expect(container.textContent).toContain("params.item.results");
expect(container.textContent).toContain("payload.query");
expect(container.textContent).toContain("research.completed");
expect(container.textContent).toContain("Production surface preview");
});
});
describe("RunnerInspector disconnect handling", () => {
let container: HTMLDivElement;
let root: Root;
let store: ConnectivityStore;
let probe: ReturnType<typeof vi.fn<() => Promise<{ reachable: boolean; retryAfterMs: number | null }>>>;
const unavailable = () => new ApiError("Paperclip is restarting.", 503, { error: "tenant_app_unavailable" });
const event = (runId: string, seq: number) => ({
id: seq,
companyId: "company-1",
runId,
agentId: "agent-1",
seq,
eventType: "run.result.proposed",
stream: "stdout",
level: "info",
color: null,
message: null,
payload: { prpEvent: { sourceEventId: `runner:${runId}:${seq}`, payload: {} } },
createdAt: "2026-08-22T12:00:03.000Z",
});
function render(runId = "run-1") {
flushSync(() =>
root.render(
<ConnectivityProvider store={store}>
<RunnerInspector
runId={runId}
run={{ status: "succeeded", resultJson: null }}
open
onOpenChange={vi.fn()}
/>
</ConnectivityProvider>,
),
);
}
beforeEach(() => {
window.history.replaceState(null, "", "/");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
probe = vi.fn(async () => ({ reachable: true, retryAfterMs: null }));
store = createConnectivityStore({ probe: probe as never, browserOnline: true });
accessMock.mockResolvedValue({ source: "local_implicit", isInstanceAdmin: false });
eventsMock.mockResolvedValue([]);
traceMock.mockResolvedValue({ trace: null, entries: [] });
});
afterEach(() => {
flushSync(() => root.unmount());
container.remove();
store.dispose();
vi.restoreAllMocks();
vi.clearAllMocks();
});
it("does not grant trace controls when a recovery read starts during deletion", async () => {
traceMock.mockResolvedValue(traceInspection("run-1", "retained-redacted-frame"));
const pendingDelete = deferred<void>();
deleteMock.mockReturnValue(pendingDelete.promise);
vi.spyOn(window, "confirm").mockReturnValue(true);
render(); await flush();
expect(container.textContent).toContain("Reveal exact frame");
const traceReads = traceMock.mock.calls.length;
const eventReads = eventsMock.mock.calls.length;
flushSync(() => [...container.querySelectorAll("button")].find(button => button.textContent?.includes("Delete trace"))!.click());
expect(deleteMock).toHaveBeenCalledWith("run-1");
probe.mockResolvedValue({ reachable: false, retryAfterMs: null });
store.reportError(unavailable()); await flush();
probe.mockResolvedValue({ reachable: true, retryAfterMs: null });
store.probeNow(); await flush();
expect(store.getSnapshot().status).toBe("online");
expect(eventsMock.mock.calls.length).toBeGreaterThan(eventReads);
expect(traceMock).toHaveBeenCalledTimes(traceReads);
expect(container.textContent).not.toContain("Reveal exact frame");
expect(container.textContent).not.toContain("Download exact trace");
expect(container.textContent).not.toContain("Delete trace");
pendingDelete.resolve(); await flush();
expect(container.textContent).not.toContain("retained-redacted-frame");
});
it("keeps the loaded inspection on screen when the refetch after an outage fails transiently", async () => {
eventsMock.mockResolvedValue([event("run-1", 9)]);
traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted"));
render();
await flush();
expect(container.textContent).toContain("run-1-redacted");
probe.mockResolvedValue({ reachable: false, retryAfterMs: null });
store.reportError(unavailable());
await flush();
expect(store.getSnapshot().status).toBe("reconnecting");
expect(container.textContent).toContain("run-1-redacted");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
// Recovery refetches; a transient failure of that refetch retries quietly.
eventsMock.mockRejectedValue(new ApiError("Too many requests", 429, { error: "rate_limited" }));
probe.mockResolvedValue({ reachable: true, retryAfterMs: null });
store.probeNow();
await flush();
expect(store.getSnapshot().status).toBe("online");
expect(container.textContent).toContain("run-1-redacted");
expect(container.textContent).toContain("Reveal exact frame");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).not.toContain("rate_limited");
});
it("waits quietly for a first load during an outage and fills in on recovery", async () => {
probe.mockResolvedValue({ reachable: false, retryAfterMs: null });
store.reportError(unavailable());
await flush();
expect(store.getSnapshot().status).toBe("reconnecting");
eventsMock.mockResolvedValue([event("run-1", 9)]);
render();
await flush();
expect(accessMock).not.toHaveBeenCalledWith(); // the initial load is paused, not failing
expect(eventsMock).not.toHaveBeenCalled();
expect(container.textContent).toContain("Loading run pipeline…");
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
probe.mockResolvedValue({ reachable: true, retryAfterMs: null });
store.probeNow();
await flush();
expect(store.getSnapshot().status).toBe("online");
expect(eventsMock).toHaveBeenCalledWith("run-1", 0, 1_000);
expect(container.textContent).not.toContain("Loading run pipeline…");
expect(container.textContent).toContain("1 PRP event");
});
it("shows readable copy for a real failure, never raw access, and retries on request", async () => {
traceMock.mockRejectedValueOnce(new ApiError("stale_revision", 409, { error: "stale_revision" }));
render();
await flush();
const alert = container.querySelector('[data-query-view="error"]');
expect(alert).not.toBeNull();
expect(alert?.textContent).toContain("Couldn't load the runner inspection");
expect(alert?.textContent).not.toContain("stale_revision");
expect(container.textContent).not.toContain("Reveal exact frame");
expect(container.textContent).not.toContain("Download exact trace");
traceMock.mockResolvedValue(traceInspection("run-1", "run-1-redacted"));
flushSync(() => alert?.querySelector("button")?.click());
await flush();
expect(container.querySelector('[data-query-view="error"]')).toBeNull();
expect(container.textContent).toContain("run-1-redacted");
});
it("leaves out Retry and keeps raw controls hidden when access is forbidden", async () => {
accessMock.mockRejectedValue(new ApiError("Forbidden", 403, { error: "Forbidden" }));
render();
await flush();
const alert = container.querySelector('[data-query-view="error"]');
expect(alert?.textContent).toContain("Forbidden");
expect(alert?.querySelector("button")).toBeNull();
expect(traceMock).not.toHaveBeenCalled();
expect(container.textContent).not.toContain("Reveal exact frame");
});
it("ignores a load that finishes after the run changed", async () => {
const pendingFirst = deferred<ReturnType<typeof event>[]>();
eventsMock.mockImplementation(async (runId: string) =>
runId === "run-1" ? pendingFirst.promise : [event(runId, 2)],
);
traceMock.mockImplementation(async (runId: string) => traceInspection(runId, `${runId}-redacted`));
render("run-1");
await flush();
expect(container.textContent).toContain("Loading run pipeline…");
render("run-2");
await flush();
expect(container.textContent).toContain("run-2-redacted");
pendingFirst.resolve([event("run-1", 1), event("run-1", 2), event("run-1", 3)]);
await flush();
expect(container.textContent).toContain("run-2-redacted");
expect(container.textContent).not.toContain("run-1-redacted");
expect(container.textContent).toContain("runner:run-2:2");
expect(container.textContent).not.toContain("runner:run-1:");
});
});