Refresh the SSH account branch from master

Keep the SSH base current so the stacked Tailscale migrations can follow the
latest upstream schema sequence. The merge preserves managed SSH account
selection, host-auth compatibility, and the PATH-only ACP prerequisite check.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip committed 2026-11-13 09:03:27 -08:00
commit e8a0316483
262 files changed
+13201 -1135

No files matched your search

+12
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockApi = vi.hoisted(() => ({
get: vi.fn(),
post: vi.fn(),
}));
vi.mock("./client", () => ({
@@ -19,6 +20,17 @@ afterEach(() => {
vi.unstubAllGlobals();
});
describe("heartbeatsApi.cancel", () => {
it("sends an uncorrelated Stop so a run still waiting in line can be stopped", async () => {
// Correlated Stop (cancellationRequestId) is only for native runs; the
// server rejects it for a queued legacy run. Task Stop must not send it.
mockApi.post.mockReset();
mockApi.post.mockResolvedValue({ id: "waiting-run", status: "cancelled" });
await expect(heartbeatsApi.cancel("waiting-run")).resolves.toMatchObject({ status: "cancelled" });
expect(mockApi.post).toHaveBeenCalledWith("/heartbeat-runs/waiting-run/cancel", {});
});
});
describe("heartbeatsApi.list", () => {
beforeEach(() => {
mockApi.get.mockReset();
+2 -2
View File
@@ -446,8 +446,8 @@ export const issuesApi = {
api.post<{ runId: string; resultId: string | null; status: "queued" }>(`/issues/${id}/recovery-actions/resume-workspace-finalization`, data),
retryWorkspaceExport: (id: string, data: { actionId: string; runId: string; repairNote: string }) =>
api.post<{ runId: string; resultId: string; leaseId: string; status: "queued" }>(`/issues/${id}/recovery-actions/retry-workspace-export`, data),
retryTask: (issueId: string, body: { idempotencyKey: string; observedRunId: string | null }) =>
api.post<{ requestId: string | null; accepted: boolean; stale: boolean;
retryTask: (issueId: string, body: { idempotencyKey: string; observedRunId: string | null; retryAction?: "move_forward" }) =>
api.post<{ requestId: string | null; accepted: boolean; stale: boolean; alreadyMovedOn?: boolean;
scheduledRetry?: { outcome: "promoted" | "already_promoted" | "gate_suppressed" | "waiting" | "no_scheduled_retry"; message: string };
presentation: import("@paperclipai/shared").TaskInterruptionPresentation | null }>(`/issues/${issueId}/retry`, body),
recoverWorkspace: (id: string, data: { actionId: string; runId: string; idempotencyKey: string }) =>
+9 -1
View File
@@ -1,4 +1,4 @@
import type { McpAppCallToolResult, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
import type { McpAppCallToolResult, McpAppModelContext, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
import { api } from "./client";
/** MCP Apps views recorded for a task's tool calls. */
@@ -9,4 +9,12 @@ export const mcpAppsApi = {
api.get<McpAppViewDetail>(`/issues/${issueId}/mcp-app-views/${viewId}`, { cache: "no-store", signal }),
callTool: (issueId: string, viewId: string, name: string, args: Record<string, unknown>) =>
api.post<McpAppCallToolResult>(`/issues/${issueId}/mcp-app-views/${viewId}/tool-calls`, { name, arguments: args }),
/** Stores the view's latest context for the task's next run; null clears it. */
updateModelContext: (issueId: string, viewId: string, context: McpAppModelContext | null) =>
api.put<{ updated: boolean }>(`/issues/${issueId}/mcp-app-views/${viewId}/model-context`, context
? { ...(context.text ? { content: [{ type: "text", text: context.text }] } : {}), ...(context.structuredContent ? { structuredContent: context.structuredContent } : {}) }
: {}),
/** Records that the viewer sent a view's proposed message (sent with this client request id). */
messageSent: (issueId: string, viewId: string, clientRequestId: string) =>
api.post<{ commentId: string }>(`/issues/${issueId}/mcp-app-views/${viewId}/messages`, { clientRequestId }),
};
+3
View File
@@ -1,4 +1,5 @@
import type { AggregatorAppsResponse, ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps";
import type { ProviderToolIconsResponse } from "@paperclipai/shared";
import type { ComposioAppAccountInput, ComposioAppSetupInput, ComposioAppSetupResult, ComposioAppSnapshot, ComposioAppsResponse } from "@paperclipai/shared";
import type {
ToolApplication,
@@ -430,6 +431,8 @@ export const toolsApi = {
}),
refreshCatalog: (connectionId: string) =>
api.post<ToolCatalogRefreshResult>(`/tool-connections/${connectionId}/catalog/refresh`, {}),
listProviderToolIcons: (companyId: string) =>
api.get<ProviderToolIconsResponse>(`/companies/${companyId}/tool-icons`),
listCatalog: (connectionId: string) =>
api.get<ToolCatalogResponse>(`/tool-connections/${connectionId}/catalog`),
listConnectionActivity: (connectionId: string, limit = 20) =>
+67
View File
@@ -0,0 +1,67 @@
import type { ExecutionAgentQueue } from "@paperclipai/shared";
import { Hourglass } from "lucide-react";
import { Link } from "@/lib/router";
import { agentQueueConfigureHref, agentQueueWaitParts } from "@/lib/agent-queue-wait";
import { cn } from "@/lib/utils";
/**
* A run that waits for one of its agent's concurrency slots:
* "Waiting for Codie · 20 slots max · 41 of 295 in line · Configure".
* It is a quiet system wait, not work in progress: no spinner, no elapsed timer.
*/
export function AgentQueueWait({
queue,
showConfigure = true,
className,
}: {
queue: ExecutionAgentQueue;
showConfigure?: boolean;
className?: string;
}) {
const [waiting, limit, line] = agentQueueWaitParts(queue);
return (
<span
className={cn("flex min-w-0 flex-wrap items-center gap-x-1.5 text-sm text-muted-foreground", className)}
data-testid="agent-queue-wait"
aria-live="polite"
aria-atomic="true"
>
<span className="flex size-5 shrink-0 items-center justify-center">
<Hourglass className="size-3.5" aria-hidden="true" />
</span>
<span className="font-medium text-foreground/80">{waiting}</span>
<span aria-hidden="true">·</span>
<span>{limit}</span>
<span aria-hidden="true">·</span>
<span>{line}</span>
{showConfigure ? (
<>
<span aria-hidden="true">·</span>
<Link
to={agentQueueConfigureHref(queue)}
className="text-foreground/80 underline-offset-2 hover:text-foreground hover:underline"
aria-label={`Configure ${queue.agentName}'s concurrent run limit`}
>
Configure
</Link>
</>
) : null}
</span>
);
}
/** List-row form: one muted word, the full sentence on hover. */
export function AgentQueueWaitChip({ queue }: { queue: ExecutionAgentQueue | null }) {
const title = queue ? agentQueueWaitParts(queue).join(" · ") : "Waiting to start";
return (
<span
className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground"
title={title}
aria-label={title}
data-testid="agent-queue-wait-chip"
>
<Hourglass className="size-3" aria-hidden="true" />
Waiting
</span>
);
}
@@ -66,6 +66,26 @@ describe("ordinary task interruption", () => {
it.each(["working", "resolved"] as const)("does not duplicate the thread indicator for %s", async state => {
await render({ ...failed, state }); expect(container.textContent).toBe("");
});
it("offers to move a waiting continuation forward in plain words, without reporting a failure", async () => {
await render({ ...failed, state: "working", retryAction: "move_forward" });
expect(container.textContent).toContain("Paperclip continues this task by itself.");
expect(container.textContent).not.toMatch(/Couldn’t finish|failed|continuation|queue|run\b/i);
const button = container.querySelector<HTMLButtonElement>('[data-testid="task-execution-move-forward"]');
expect(button?.textContent).toBe("Move it forward now");
expect(container.querySelectorAll("button")).toHaveLength(1);
await act(async () => button!.click());
expect(retry).toHaveBeenCalledOnce();
});
it("shows a waiting continuation without the button to a read-only user, or once the move was requested", async () => {
await act(async () => root.render(<ExecutionBlockerNotice presentation={{ ...failed, state: "working", retryAction: "move_forward" }}
canRetry={false} onRetry={retry} />));
expect(container.textContent).toContain("Paperclip continues this task by itself.");
expect(container.querySelector("button")).toBeNull();
await render({ ...failed, state: "working", canRetry: false });
expect(container.textContent).toBe("");
});
it("names the admission hold a task that has not started waits for", async () => {
await render({ ...failed, state: "working", canRetry: false, sourceRunIds: [], observedRunId: null,
retryWait: { reason: "budget.blocked", message: "Waiting for the budget to allow new work. The task starts automatically when it does." } });
@@ -71,6 +71,11 @@ export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimi
}
if (step && presentation?.state === "working") return <div role="status" aria-label="Task status"
className={cn("text-sm text-muted-foreground", className)}>{`${step}…`}</div>;
if (!optimistic && presentation?.state === "working" && presentation.retryAction === "move_forward" && presentation.canRetry)
return <div role="status" aria-label="Task status" className={cn("flex items-center justify-between gap-3 text-sm text-muted-foreground", className)}>
<span className="min-w-0 flex-1">Waiting for the agent to finish other work. Paperclip continues this task by itself.</span>
{canRetry && <Button variant="outline" size="sm" className="shrink-0" onClick={onRetry} data-testid="task-execution-move-forward">Move it forward now</Button>}
</div>;
// A task that has not started yet names the admission hold it waits for.
if (!optimistic && presentation?.state === "working" && presentation.retryWait) {
const dependencies = presentation.retryWait.reason === "dependency_blocked" ? blockers ?? [] : [];
@@ -459,6 +459,25 @@ describe("IssueChatThread", () => {
markdownBodyRenderMock.mockClear();
});
it("offers Stop for a run still waiting in line and calls the task's stop action", async () => {
const root = createRoot(container);
const onCancelRun = vi.fn(async () => {});
const waitingRun = {
id: "waiting-run", issueId: "issue-1", status: "queued", invocationSource: "assignment", triggerDetail: null,
startedAt: null, finishedAt: null, createdAt: "2026-11-13T12:00:00.000Z",
agentId: "agent-1", agentName: "Codie", adapterType: "codex_local",
};
act(() => renderIssueThread(root, { liveRuns: [waitingRun], issueStatus: "todo", onCancelRun }));
const stop = container.querySelector<HTMLButtonElement>('button[aria-label="Stop"]');
expect(stop).not.toBeNull();
await act(async () => { stop!.click(); });
expect(onCancelRun).toHaveBeenCalledOnce();
act(() => renderIssueThread(root, { liveRuns: [], issueStatus: "todo", onCancelRun }));
expect(container.querySelector('button[aria-label="Stop"]')).toBeNull();
act(() => root.unmount());
});
it("drops the count heading and does not use an internal scrollbox", () => {
const root = createRoot(container);
+3 -1
View File
@@ -6925,7 +6925,9 @@ export function IssueChatThread({
mentions={mentions}
agentMap={agentMap}
hasActiveRun={!!hasActiveRun}
onStop={hasActiveRun ? onCancelRun : undefined}
// A run still waiting in line is stoppable too: Stop takes the
// task out of the agent's queue before it ever starts.
onStop={activeRunIds.size > 0 ? onCancelRun : undefined}
stopPending={stopPending}
stopScope={stopScope}
currentUserId={currentUserId}
+8 -1
View File
@@ -1,4 +1,6 @@
import { AgentIdentity } from "@/components/AgentIdentity";
import { AgentQueueWaitChip } from "./AgentQueueWait";
import type { IssueWaiting } from "../lib/liveIssueIds";
import type { AvatarAgent } from "./AgentAvatar";
import type { ReactNode } from "react";
import { deriveOriginatingActor, type Issue } from "@paperclipai/shared";
@@ -183,6 +185,7 @@ export function IssueColumnPicker({
export function InboxIssueMetaLeading({
issue,
isLive,
waiting = null,
subtreeLiveCount = 0,
showSubtreeLiveChip = true,
showStatus = true,
@@ -192,6 +195,8 @@ export function InboxIssueMetaLeading({
}: {
issue: Issue;
isLive: boolean;
/** Set when every live run of the task is still waiting to start. */
waiting?: IssueWaiting | null;
subtreeLiveCount?: number;
showSubtreeLiveChip?: boolean;
showStatus?: boolean;
@@ -216,7 +221,9 @@ export function InboxIssueMetaLeading({
{issue.identifier ?? issue.id.slice(0, 8)}
</span>
) : null}
{isLive && (
{isLive && waiting ? (
<AgentQueueWaitChip queue={waiting.queue} />
) : isLive && (
<Badge variant="ghost"
className={cn(
"px-1.5 sm:gap-1.5 sm:px-2",
@@ -1131,7 +1131,8 @@ describe("IssueRecoveryActionCard owner-sticky retry lineage", () => {
expect(section?.getAttribute("data-recovery-state")).toBe("needed");
expect(section?.getAttribute("data-recovery-lane")).toBe("board");
expect(node.textContent).toContain("Automatic recovery is exhausted");
expect(node.textContent).toContain("Board decision required");
expect(node.textContent).toContain("Waiting for you");
expect(node.textContent).not.toContain("Board decision required");
const recoveryOwner = node.querySelector("[data-testid='recovery-recovery-owner']");
expect(recoveryOwner?.textContent).toContain("Board");
expect(recoveryOwner?.textContent).toContain("decides the next step only");
@@ -771,10 +771,10 @@ function readWakePolicySummary(action: IssueRecoveryAction): string | null {
if (type === "bounded_owner_disposition_repair") {
return "Paperclip is retrying the original owner";
}
if (type === "bounded_recovery_owner") return "A recovery owner is repairing the next step";
if (type === "board_escalation") return "Board decision required";
if (type === "bounded_recovery_owner") return "An agent is choosing the next step";
if (type === "board_escalation") return "Waiting for you";
if (type === "manual") return "Manual follow-up needed";
if (type === "manual_repair_required") return "Repair needed before retry";
if (type === "manual_repair_required") return "Needs a fix before Retry";
if (type === "monitor") {
const interval = readEvidenceString(policy.intervalLabel);
return interval ? `Check scheduled · ${interval}` : "Check scheduled";
+7 -2
View File
@@ -1,4 +1,6 @@
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { AgentQueueWait } from "./AgentQueueWait";
import { agentQueueWaitOf, isWaitingToStart } from "../lib/agent-queue-wait";
import type { ActivityEvent, Issue, Agent, ProviderTraceMetadata } from "@paperclipai/shared";
import {
isResponsibleUserDenialCode,
@@ -846,6 +848,7 @@ export function IssueRunLedgerContent({
}
const run = item.run;
const nextAction = run.execution ? run.execution.nextAction : run.nextAction;
const agentQueue = isWaitingToStart(run) ? agentQueueWaitOf(run.execution) : null;
const liveness = livenessCopyForRun(run);
const stopReason = stopReasonLabel(run);
const duration = formatDuration(run.startedAt, run.finishedAt);
@@ -889,7 +892,7 @@ export function IssueRunLedgerContent({
<span className="rounded-md border border-border px-1.5 py-0.5 text-(length:--text-micro) capitalize text-muted-foreground">
{statusLabel(run.status)}
</span>
{run.isLive ? (
{run.isLive && !isWaitingToStart(run) ? (
<span className="inline-flex items-center gap-1 rounded-md border border-blue-500/30 bg-blue-500/10 px-1.5 py-0.5 text-(length:--text-micro) text-blue-700 dark:text-blue-300">
<span className="h-1.5 w-1.5 rounded-full bg-blue-500" />
live
@@ -1005,7 +1008,9 @@ export function IssueRunLedgerContent({
/>
) : null}
{nextAction ? (
{agentQueue ? (
<AgentQueueWait queue={agentQueue} className="text-xs" />
) : nextAction ? (
<div className="min-w-0 rounded-md bg-accent/40 px-2 py-1.5 text-xs leading-5">
<span className="font-medium text-foreground">
Next action:{" "}
+5 -2
View File
@@ -59,7 +59,7 @@ import {
} from "../lib/inbox";
import { cn, formatDurationMs, formatTokens } from "../lib/utils";
import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
import { collectSubtreeLiveCounts } from "../lib/liveIssueIds";
import { collectSubtreeLiveCounts, issueWaitingOf } from "../lib/liveIssueIds";
import {
InboxIssueMetaLeading,
InboxIssueTrailingColumns,
@@ -1147,7 +1147,8 @@ function StreamlinedIssuesList({
);
const availableIssueColumnSet = useMemo(() => new Set(availableIssueColumns), [availableIssueColumns]);
const subtreeLiveCounts = useMemo(
() => collectSubtreeLiveCounts(issues, liveIssueIds ?? new Set<string>()),
// The row chip counts only started sub-tasks; waiting ones are not running below.
() => collectSubtreeLiveCounts(issues, liveIssueIds ?? new Set<string>(), { startedOnly: true }),
[issues, liveIssueIds],
);
const visibleTrailingIssueColumns = useMemo(
@@ -2376,6 +2377,7 @@ function StreamlinedIssuesList({
<InboxIssueMetaLeading
issue={issue}
isLive={liveIssueIds?.has(issue.id) === true}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={subtreeLiveCounts.get(issue.id) ?? 0}
showStatus={false}
showIdentifier={false}
@@ -2411,6 +2413,7 @@ function StreamlinedIssuesList({
<InboxIssueMetaLeading
issue={issue}
isLive={liveIssueIds?.has(issue.id) === true}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={subtreeLiveCounts.get(issue.id) ?? 0}
showStatus={visibleIssueColumnSet.has("status") && availableIssueColumnSet.has("status")}
showIdentifier={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
+4 -2
View File
@@ -58,7 +58,7 @@ import {
} from "../lib/inbox";
import { cn, formatDurationMs, formatTokens } from "../lib/utils";
import { SHOW_TASK_PRIORITY_UI } from "../lib/ui-flags";
import { collectSubtreeLiveCounts } from "../lib/liveIssueIds";
import { collectSubtreeLiveCounts, issueWaitingOf } from "../lib/liveIssueIds";
import {
InboxIssueMetaLeading,
InboxIssueTrailingColumns,
@@ -1050,7 +1050,8 @@ export function IssuesList({
);
const availableIssueColumnSet = useMemo(() => new Set(availableIssueColumns), [availableIssueColumns]);
const subtreeLiveCounts = useMemo(
() => collectSubtreeLiveCounts(issues, liveIssueIds ?? new Set<string>()),
// The row chip counts only started sub-tasks; waiting ones are not running below.
() => collectSubtreeLiveCounts(issues, liveIssueIds ?? new Set<string>(), { startedOnly: true }),
[issues, liveIssueIds],
);
const visibleTrailingIssueColumns = useMemo(
@@ -2229,6 +2230,7 @@ export function IssuesList({
<InboxIssueMetaLeading
issue={issue}
isLive={liveIssueIds?.has(issue.id) === true}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={subtreeLiveCounts.get(issue.id) ?? 0}
showStatus={visibleIssueColumnSet.has("status") && availableIssueColumnSet.has("status")}
showIdentifier={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
@@ -68,6 +68,17 @@ const routes = (
</>
);
/**
* The page's clock starts at navigation start. A test process can be older
* than the 30 s page-load timeout, which would turn the hard load (start 0)
* into a timeout, so the clock is restarted for each test.
*/
function restartPageClock() {
const realNow = performance.now.bind(performance);
const origin = realNow();
vi.spyOn(performance, "now").mockImplementation(() => realNow() - origin);
}
describe("PageLoadTracker", () => {
let container: HTMLDivElement;
let root: Root | null = null;
@@ -81,6 +92,7 @@ describe("PageLoadTracker", () => {
measurements.ended.length = 0;
resetPageSessionSampleForTest();
window.history.replaceState(null, "", "/PAP/issues");
restartPageClock();
});
afterEach(() => {
@@ -88,6 +100,7 @@ describe("PageLoadTracker", () => {
root = null;
container.remove();
vi.clearAllMocks();
vi.mocked(performance.now).mockRestore?.();
});
async function render(initialPath: string) {
+155
View File
@@ -0,0 +1,155 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { McpIcon } from "@paperclipai/shared";
import { TaskChatToolCard } from "./task-chat/TaskChatToolCard";
import {
gatewayToolNameIn,
ProviderToolIcon,
ProviderToolIconsStaticProvider,
providerToolIconLookup,
} from "./ProviderToolIcon";
import { ThemeProvider, useTheme } from "@/context/ThemeContext";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
function Fallback(props: { className?: string; "data-testid"?: string }) {
return <span data-fallback="true" data-testid={props["data-testid"]} className={props.className} />;
}
let root: Root | null = null;
afterEach(() => {
act(() => root?.unmount());
root = null;
});
async function render(node: React.ReactNode) {
const container = document.createElement("div");
root = createRoot(container);
await act(async () => root!.render(node));
return container;
}
const PNG: McpIcon = { src: "https://cdn.example.com/meetings.png", mimeType: "image/png" };
describe("ProviderToolIcon", () => {
it("renders the provider icon as an image without a referrer, never inline markup", async () => {
const container = await render(<ProviderToolIcon icons={[PNG]} fallback={Fallback} testId="icon" />);
const img = container.querySelector("img")!;
expect(img.getAttribute("src")).toBe(PNG.src);
expect(img.getAttribute("referrerpolicy")).toBe("no-referrer");
expect(img.getAttribute("alt")).toBe("");
expect(container.querySelector("svg")).toBeNull();
expect(container.querySelector("[data-fallback]")).toBeNull();
});
it("keeps an inline SVG icon inside an img", async () => {
const container = await render(<ProviderToolIcon icons={[{ src: "data:image/svg+xml;base64,PHN2Zy8+" }]} fallback={Fallback} />);
expect(container.querySelector("img")?.getAttribute("src")).toBe("data:image/svg+xml;base64,PHN2Zy8+");
expect(container.querySelector("svg")).toBeNull();
});
it("falls back to the taxonomy icon when there is no icon, an unsafe one, or the image fails", async () => {
expect((await render(<ProviderToolIcon icons={null} fallback={Fallback} />)).querySelector("[data-fallback]")).not.toBeNull();
act(() => root?.unmount());
// Re-checked at render time even if a stored value slipped past parsing.
const unsafe = await render(<ProviderToolIcon icons={[{ src: "javascript:alert(1)" }]} fallback={Fallback} />);
expect(unsafe.querySelector("img")).toBeNull();
expect(unsafe.querySelector("[data-fallback]")).not.toBeNull();
act(() => root?.unmount());
const failing = await render(<ProviderToolIcon icons={[PNG]} fallback={Fallback} />);
await act(async () => failing.querySelector("img")!.dispatchEvent(new Event("error")));
expect(failing.querySelector("img")).toBeNull();
expect(failing.querySelector("[data-fallback]")).not.toBeNull();
});
});
describe("provider icons in task chat tool rows", () => {
const NATIVE = "app_mcp_circleback_1a2b3c4d_displaymeetings_0123456789ab";
const entries = [{ gatewayToolName: "mcp.circleback-1a2b3c4d:displaymeetings", nativeToolName: NATIVE, icons: [PNG] }];
it("finds the gateway tool name inside agent transcript names", () => {
expect(gatewayToolNameIn("mcp__paperclip__mcp.circleback-1a2b3c4d:displaymeetings")).toBe("mcp.circleback-1a2b3c4d:displaymeetings");
expect(gatewayToolNameIn("Bash")).toBeNull();
const lookup = providerToolIconLookup(entries);
expect(lookup("mcp.circleback-1a2b3c4d:displaymeetings")).toEqual([PNG]);
// The gateway's duplicate-name suffix still finds the tool.
expect(lookup("mcp.circleback-1a2b3c4d:displaymeetings-0f0f0f0f")).toEqual([PNG]);
expect(lookup("mcp.other-99999999:displaymeetings")).toBeNull();
});
it("shows the provider icon on a matching row and the taxonomy icon elsewhere", async () => {
const container = await render(
<ProviderToolIconsStaticProvider entries={entries}>
<TaskChatToolCard item={{ kind: "tool", id: "t1", name: "Display meetings", rawName: "mcp__paperclip__mcp.circleback-1a2b3c4d:displaymeetings", status: "completed" }} />
<TaskChatToolCard item={{ kind: "tool", id: "t2", name: "Bash", rawName: "Bash", status: "completed" }} />
</ProviderToolIconsStaticProvider>,
);
const icons = container.querySelectorAll("[data-testid='task-chat-tool-icon']");
expect(icons).toHaveLength(2);
expect(icons[0]!.tagName).toBe("IMG");
expect(icons[0]!.getAttribute("referrerpolicy")).toBe("no-referrer");
expect(icons[1]!.tagName.toLowerCase()).toBe("svg");
});
it("indexes a company's icons once and finds each row's icon in constant work at realistic size", async () => {
const ENTRIES = 500;
const ROWS = 600;
const big = Array.from({ length: ENTRIES }, (_, index) => ({
gatewayToolName: `mcp.app${index % 25}-${(index % 25).toString(16).padStart(8, "0")}:tool-${index}`,
icons: [PNG],
}));
const rawName = (index: number) => `mcp__paperclip__mcp.app${index % 25}-${(index % 25).toString(16).padStart(8, "0")}:tool-${index % ENTRIES}`;
const set = vi.spyOn(Map.prototype, "set");
const lookup = providerToolIconLookup(big);
// The index is built once: one insert per entry.
expect(set.mock.calls.length).toBe(ENTRIES);
set.mockRestore();
const get = vi.spyOn(Map.prototype, "get");
let found = 0;
for (let index = 0; index < ROWS; index += 1) if (lookup(rawName(index))) found += 1;
// At most two index reads per row (exact name, then without a duplicate suffix); no scans.
expect(get.mock.calls.length).toBeLessThanOrEqual(2 * ROWS);
get.mockRestore();
expect(found).toBe(ROWS);
const container = await render(
<ProviderToolIconsStaticProvider entries={big}>
{Array.from({ length: 300 }, (_, index) => (
<TaskChatToolCard key={index} item={{ kind: "tool", id: `t${index}`, name: `Tool ${index}`, rawName: rawName(index), status: "completed" }} />
))}
</ProviderToolIconsStaticProvider>,
);
expect(container.querySelectorAll("img[data-provider-icon=true]")).toHaveLength(300);
});
it("re-picks the icon when the theme changes", async () => {
const themed: McpIcon[] = [
{ src: "https://cdn.example.com/light.png", theme: "light" },
{ src: "https://cdn.example.com/dark.png", theme: "dark" },
];
let setTheme!: (theme: "light" | "dark") => void;
function Toggle() { setTheme = useTheme().setTheme; return null; }
const container = await render(
<ThemeProvider><Toggle /><ProviderToolIcon icons={themed} fallback={Fallback} /></ThemeProvider>,
);
await act(async () => setTheme("light"));
expect(container.querySelector("img")!.getAttribute("src")).toBe("https://cdn.example.com/light.png");
await act(async () => setTheme("dark"));
expect(container.querySelector("img")!.getAttribute("src")).toBe("https://cdn.example.com/dark.png");
});
it("finds icons for native runner tool names", async () => {
const lookup = providerToolIconLookup(entries);
expect(lookup(NATIVE)).toEqual([PNG]);
expect(lookup(`mcp__paperclip__${NATIVE}`)).toEqual([PNG]);
expect(lookup("app_mcp_circleback_1a2b3c4d_displaymeetings_ffffffffffff")).toBeNull();
const container = await render(
<ProviderToolIconsStaticProvider entries={entries}>
<TaskChatToolCard item={{ kind: "tool", id: "n1", name: "Display meetings", rawName: NATIVE, status: "completed" }} />
</ProviderToolIconsStaticProvider>,
);
expect(container.querySelector("[data-testid='task-chat-tool-icon']")!.tagName).toBe("IMG");
});
});
+112
View File
@@ -0,0 +1,112 @@
import { createContext, useContext, useMemo, useState, type ComponentType, type ReactNode, type SVGProps } from "react";
import { useQuery } from "@tanstack/react-query";
import { pickMcpIcon, sanitizeMcpIconSrc, type McpIcon, type ProviderToolIconEntry } from "@paperclipai/shared";
import { toolsApi } from "@/api/tools";
import { queryKeys } from "@/lib/queryKeys";
import { useResolvedTheme } from "@/context/ThemeContext";
import { cn } from "@/lib/utils";
type IconComponent = ComponentType<SVGProps<SVGSVGElement>>;
/**
* A provider's tool icon (MCP SEP-973) with the taxonomy icon as fallback.
* The icon is always an `<img>` with no referrer, never inlined markup, so an
* SVG icon's scripts never run. The source is re-checked at render time and
* a failed load falls back to the taxonomy icon.
*/
export function ProviderToolIcon({
icons,
fallback: Fallback,
className,
testId,
}: {
icons: readonly McpIcon[] | null | undefined;
fallback: IconComponent;
className?: string;
testId?: string;
}) {
// Subscribed, so a theme switch re-picks the icon for the new theme.
const icon = pickMcpIcon(icons, useResolvedTheme());
const src = icon ? sanitizeMcpIconSrc(icon.src, icon.mimeType) : null;
const [failedSrc, setFailedSrc] = useState<string | null>(null);
if (!src || failedSrc === src) {
return <Fallback className={className} aria-hidden data-testid={testId} />;
}
return (
<img
src={src}
alt=""
aria-hidden
referrerPolicy="no-referrer"
loading="lazy"
decoding="async"
draggable={false}
width={14}
height={14}
data-testid={testId}
data-provider-icon="true"
onError={() => setFailedSrc(src)}
className={cn("object-contain", className)}
/>
);
}
/** Gateway tool name (`mcp.<app>-<connection>:<tool>`) inside a transcript tool name. */
const GATEWAY_TOOL_NAME = /(?:mcp|app)\.[a-z0-9-]+-[a-z0-9]{1,8}:[a-z0-9-]+/i;
export function gatewayToolNameIn(rawName: string | null | undefined): string | null {
return rawName ? GATEWAY_TOOL_NAME.exec(rawName)?.[0]?.toLowerCase() ?? null : null;
}
/** Native runner tool name (`app_<name>_<12-hex digest>`) inside a transcript tool name. */
const NATIVE_TOOL_NAME = /app_[A-Za-z0-9_]*_[0-9a-f]{12}(?![0-9a-f])/;
export function nativeToolNameIn(rawName: string | null | undefined): string | null {
return rawName ? NATIVE_TOOL_NAME.exec(rawName)?.[0] ?? null : null;
}
export type ProviderToolIconLookup = (rawName: string | null | undefined) => McpIcon[] | null;
export function providerToolIconLookup(entries: readonly ProviderToolIconEntry[]): ProviderToolIconLookup {
const byName = new Map(entries.map((entry) => [entry.gatewayToolName.toLowerCase(), entry.icons]));
const byNativeName = new Map(entries.flatMap((entry) => entry.nativeToolName ? [[entry.nativeToolName, entry.icons] as const] : []));
return (rawName) => {
const name = gatewayToolNameIn(rawName);
if (!name) {
// Native runners name tools `app_<name>_<digest>` in their transcripts.
const native = nativeToolNameIn(rawName);
return native ? byNativeName.get(native) ?? null : null;
}
// Same-named tools on one connection get a `-<id>` suffix from the gateway.
return byName.get(name) ?? byName.get(name.replace(/-[0-9a-f]{8}$/, "")) ?? null;
};
}
const NO_ICONS: ProviderToolIconLookup = () => null;
const ProviderToolIconsContext = createContext<ProviderToolIconLookup>(NO_ICONS);
/**
* Loads a company's provider tool icons once (one small, cached request) so
* every tool row in the chat finds its icon without a request of its own.
*/
export function ProviderToolIconsProvider({ companyId, children }: { companyId: string | null | undefined; children: ReactNode }) {
const query = useQuery({
queryKey: queryKeys.tools.providerIcons(companyId ?? ""),
queryFn: () => toolsApi.listProviderToolIcons(companyId!),
enabled: Boolean(companyId),
staleTime: 10 * 60_000,
});
const entries = query.data?.icons;
const lookup = useMemo(() => (entries?.length ? providerToolIconLookup(entries) : NO_ICONS), [entries]);
return <ProviderToolIconsContext.Provider value={lookup}>{children}</ProviderToolIconsContext.Provider>;
}
/** Static icons, for stories and tests. */
export function ProviderToolIconsStaticProvider({ entries, children }: { entries: readonly ProviderToolIconEntry[]; children: ReactNode }) {
const lookup = useMemo(() => providerToolIconLookup(entries), [entries]);
return <ProviderToolIconsContext.Provider value={lookup}>{children}</ProviderToolIconsContext.Provider>;
}
export function useProviderToolIcons(rawName: string | null | undefined): McpIcon[] | null {
return useContext(ProviderToolIconsContext)(rawName);
}
+2 -1
View File
@@ -1,3 +1,4 @@
import { isWaitingToStart } from "../lib/agent-queue-wait";
import {
Inbox,
ListChecks,
@@ -76,7 +77,7 @@ export function Sidebar() {
refetchInterval: sharedLiveRuns.refetchInterval,
});
usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);
const liveRunCount = liveRuns?.length ?? 0;
const liveRunCount = (liveRuns ?? []).filter((run) => !isWaitingToStart(run)).length;
const showWorkspacesLink = experimentalSettings?.enableIsolatedWorkspaces === true;
const showApps = experimentalSettings?.enableApps === true;
const showStatusCards = experimentalSettings?.enableStatusCards === true;
+2 -1
View File
@@ -1,4 +1,5 @@
import { CoordinatorSidebar } from "./CoordinatorSidebar";
import { isWaitingToStart } from "../lib/agent-queue-wait";
import { useCoordinatorWorkspaceEnabled } from "@/hooks/useCoordinatorWorkspaceEnabled";
import {
Inbox,
@@ -94,7 +95,7 @@ function ClassicSidebar({ children }: { children?: ReactNode }) {
refetchInterval: sharedLiveRuns.refetchInterval,
});
usePublishSharedQueryData(sharedLiveRuns, liveRuns, liveRunsUpdatedAt);
const liveRunCount = liveRuns?.length ?? 0;
const liveRunCount = (liveRuns ?? []).filter((run) => !isWaitingToStart(run)).length;
const liveIssueIds = new Set(
(liveRuns ?? []).flatMap((run) => run.issueId ? [run.issueId] : []),
);
@@ -1,4 +1,5 @@
import { usePrimaryAgentPresentation } from "@/components/primary-agent/PrimaryAgentPresentation";
import { isWaitingToStart } from "../lib/agent-queue-wait";
import { AgentAvatar } from "@/components/AgentAvatar";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation } from "@/lib/router";
@@ -359,18 +360,17 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
const liveCountByAgent = useMemo(() => {
const counts = new Map<string, number>();
// "N live" counts work that started; queued runs only wait for a slot.
for (const run of liveRuns ?? []) {
if (isWaitingToStart(run)) continue;
counts.set(run.agentId, (counts.get(run.agentId) ?? 0) + 1);
}
return counts;
}, [liveRuns]);
const liveAgentIds = useMemo(() => {
const ids = new Set<string>();
for (const [agentId, count] of liveCountByAgent) {
if (count > 0) ids.add(agentId);
}
return ids;
}, [liveCountByAgent]);
const liveAgentIds = useMemo(
() => new Set((liveRuns ?? []).map((run) => run.agentId)),
[liveRuns],
);
const visibleAgents = useMemo(() => {
const filtered = (agents ?? []).filter(
+7 -7
View File
@@ -1,4 +1,5 @@
import { usePrimaryAgentPresentation } from "@/components/primary-agent/PrimaryAgentPresentation";
import { isWaitingToStart } from "../lib/agent-queue-wait";
import { AgentAvatar } from "@/components/AgentAvatar";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation } from "@/lib/router";
@@ -359,18 +360,17 @@ export function SidebarAgents({ streamlined = false }: { streamlined?: boolean }
const liveCountByAgent = useMemo(() => {
const counts = new Map<string, number>();
// "N live" counts work that started; queued runs only wait for a slot.
for (const run of liveRuns ?? []) {
if (isWaitingToStart(run)) continue;
counts.set(run.agentId, (counts.get(run.agentId) ?? 0) + 1);
}
return counts;
}, [liveRuns]);
const liveAgentIds = useMemo(() => {
const ids = new Set<string>();
for (const [agentId, count] of liveCountByAgent) {
if (count > 0) ids.add(agentId);
}
return ids;
}, [liveCountByAgent]);
const liveAgentIds = useMemo(
() => new Set((liveRuns ?? []).map((run) => run.agentId)),
[liveRuns],
);
const visibleAgents = useMemo(() => {
const filtered = (agents ?? []).filter(
+10
View File
@@ -6095,6 +6095,16 @@ describe("TaskChatThread composer execution controls", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} issueStatus="in_progress" activeRun={run} onCancelRun={onStop} stopPending />);
expect(container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-stop"]')?.disabled).toBe(true);
});
it("offers Stop where a running task's Stop lives while its run is still waiting in line", async () => {
const onStop = vi.fn(async () => {});
const waiting = { id: "waiting-run", status: "queued", invocationSource: "assignment", triggerDetail: null, startedAt: null,
finishedAt: null, createdAt: "2026-11-13T12:00:00Z", agentId: "agent-1", agentName: "Codie", adapterType: "codex_local" };
render(<TaskChatThread comments={[]} onAdd={async () => {}} issueStatus="todo" liveRuns={[waiting]} onCancelRun={onStop} />);
const button = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-stop"]');
expect(button).not.toBeNull();
await act(async () => { button!.click(); });
expect(onStop).toHaveBeenCalledOnce();
});
it("does not offer Stop for settled work even when a callback is available", () => {
render(<TaskChatThread comments={[]} onAdd={async () => {}} issueStatus="todo" onCancelRun={vi.fn()} />);
expect(container.querySelector('[data-testid="task-chat-composer-stop"]')).toBeNull();
+10 -1
View File
@@ -45,6 +45,7 @@ import {
import { useNativeRunTranscripts } from "@/components/transcript/useNativeRunTranscripts";
import { TaskChatLiveTail } from "@/components/task-chat/TaskChatLiveTail";
import { McpAppIssueProvider } from "@/components/mcp-app/McpAppIssueContext";
import { ProviderToolIconsProvider } from "@/components/ProviderToolIcon";
import { McpAppTurnViews, mcpAppRunRefreshKey } from "@/components/mcp-app/McpAppTurnViews";
import { TaskChatRunnerHeader, TaskChatRunnerTurn } from "@/components/task-chat/TaskChatRunnerTurn";
import { partitionRunHealthItems } from "@/components/task-chat/TaskChatRunHealthBanner";
@@ -2930,6 +2931,12 @@ export function TaskChatThread(props: TaskChatThreadProps) {
},
[beginSubmission, rejectSubmission, onAdd, pendingComposerInputs, selectedPendingInput, dismissInput, agentMap, takeoverMode],
);
// A message an MCP Apps view proposed, sent only after the viewer clicked
// Send, through the same path as a typed message.
const sendMcpAppMessage = useCallback(
(body: string, clientRequestId: string) => handleThreadAdd(body, undefined, undefined, undefined, clientRequestId),
[handleThreadAdd],
);
const optimisticRunnerStartup =
hasAgentAssignee &&
!startupBlocked &&
@@ -3363,7 +3370,8 @@ export function TaskChatThread(props: TaskChatThreadProps) {
return (
<TaskChatRequestHistoryContext.Provider value={issueId ?? "unknown"}>
<McpAppIssueProvider issueId={issueId}>
<McpAppIssueProvider issueId={issueId} sendMessage={composerDisabledReason ? null : sendMcpAppMessage}>
<ProviderToolIconsProvider companyId={companyId}>
<TaskChatExpansionState.Provider value={expansionState.current}>
<TaskChatScrollReady.Provider value={(historyRevealed || !historyPending || historyWaitExpired) && !scrollTargetPending}>
<TaskChatPresentationProvider
@@ -3711,6 +3719,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
</TaskChatPresentationProvider>
</TaskChatScrollReady.Provider>
</TaskChatExpansionState.Provider>
</ProviderToolIconsProvider>
</McpAppIssueProvider>
</TaskChatRequestHistoryContext.Provider>
);
+71 -12
View File
@@ -1,7 +1,14 @@
import { useLayoutEffect, useMemo, useRef, useState } from "react";
import type { McpAppCallToolResult, McpAppResource } from "@paperclipai/shared";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { McpAppCallToolResult, McpAppModelContext, McpAppResource } from "@paperclipai/shared";
import { cn } from "@/lib/utils";
import { createMcpAppHost, mcpAppDocument, type McpAppHostContext } from "./mcp-app-host";
import {
createMcpAppHost,
MCP_APP_HOST_DISPLAY_MODES,
mcpAppDocument,
type McpAppContainerDimensions,
type McpAppDisplayMode,
type McpAppHostContext,
} from "./mcp-app-host";
const MAX_HEIGHT = 640;
const INITIAL_HEIGHT = 120;
@@ -38,6 +45,14 @@ export interface McpAppFrameProps {
toolInput: Record<string, unknown>;
toolResult: McpAppCallToolResult;
callTool: (name: string, args: Record<string, unknown>) => Promise<McpAppCallToolResult>;
/** How this frame is shown. A fullscreen frame fills its container. */
displayMode?: McpAppDisplayMode;
/** The view asked for another display mode. Without it, the view stays where it is. */
onRequestDisplayMode?: (mode: McpAppDisplayMode) => void;
/** `ui/message`: resolves once the viewer sent the text, rejects when they did not. */
proposeMessage?: (text: string) => Promise<void>;
/** `ui/update-model-context`. */
updateModelContext?: (context: McpAppModelContext | null) => Promise<void>;
className?: string;
}
@@ -48,7 +63,10 @@ export interface McpAppFrameProps {
* the origins its server declared. Everything else goes through the
* postMessage protocol in `mcp-app-host.ts`.
*/
export function McpAppFrame({ title, viewId, toolName, resource, toolInput, toolResult, callTool, className }: McpAppFrameProps) {
export function McpAppFrame({
title, viewId, toolName, resource, toolInput, toolResult, callTool,
displayMode = "inline", onRequestDisplayMode, proposeMessage, updateModelContext, className,
}: McpAppFrameProps) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [height, setHeight] = useState(INITIAL_HEIGHT);
// One mount is one iframe element and one document. A second `load` means the
@@ -57,14 +75,21 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
const srcDoc = useMemo(() => mcpAppDocument(resource.html, resource.csp), [resource.html, resource.csp]);
// A refetch of the same view hands over new object identities. The host reads
// the latest values through refs, so it lives exactly as long as its document.
const latest = useRef({ callTool, toolInput, toolResult });
latest.current = { callTool, toolInput, toolResult };
const latest = useRef({ callTool, toolInput, toolResult, displayMode, onRequestDisplayMode, proposeMessage, updateModelContext });
latest.current = { callTool, toolInput, toolResult, displayMode, onRequestDisplayMode, proposeMessage, updateModelContext };
const hostRef = useRef<ReturnType<typeof createMcpAppHost> | null>(null);
const canProposeMessages = Boolean(proposeMessage);
const canUpdateModelContext = Boolean(updateModelContext);
const canChangeDisplayMode = Boolean(onRequestDisplayMode);
// A different document is a different frame: remount the iframe with a new host.
const documentVersion = useRef({ srcDoc, version: 0 });
if (documentVersion.current.srcDoc !== srcDoc) {
documentVersion.current = { srcDoc, version: documentVersion.current.version + 1 };
}
const frameKey = `${generation}:${documentVersion.current.version}`;
// Capabilities are advertised once, in `ui/initialize`, so a change in them
// needs a new document and handshake, not a new host on the old document.
const capabilityKey = `${proposeMessage ? "m" : ""}${updateModelContext ? "c" : ""}${onRequestDisplayMode ? "d" : ""}`;
const frameKey = `${generation}:${documentVersion.current.version}:${capabilityKey}`;
// Layout effect: the listener must exist before the view's first script posts `ui/initialize`.
useLayoutEffect(() => {
@@ -72,9 +97,9 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
if (!iframe) return;
const hostContext = (): McpAppHostContext => ({
theme: resolvedTheme(),
displayMode: "inline",
availableDisplayModes: ["inline"],
containerDimensions: { maxHeight: MAX_HEIGHT, ...(iframe.clientWidth ? { width: iframe.clientWidth } : {}) },
displayMode: latest.current.displayMode,
availableDisplayModes: canChangeDisplayMode ? [...MCP_APP_HOST_DISPLAY_MODES] : ["inline"],
containerDimensions: containerDimensionsFor(iframe, latest.current.displayMode),
locale: navigator.language,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
platform: "web",
@@ -91,12 +116,20 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
get toolResult() { return latest.current.toolResult; },
callTool: (name, args) => latest.current.callTool(name, args),
openLink: (url) => window.open(url, "_blank", "noopener,noreferrer"),
...(canProposeMessages ? { proposeMessage: (text: string) => latest.current.proposeMessage!(text) } : {}),
...(canUpdateModelContext ? { updateModelContext: (context: McpAppModelContext | null) => latest.current.updateModelContext!(context) } : {}),
...(canChangeDisplayMode ? { setDisplayMode: (mode: McpAppDisplayMode) => latest.current.onRequestDisplayMode?.(mode) } : {}),
// Escape inside a full-screen view closes the dialog, as it does outside the frame.
onEscape: () => {
if (latest.current.displayMode === "fullscreen") latest.current.onRequestDisplayMode?.("inline");
},
onSizeChanged: ({ height: next }) => {
if (typeof next === "number" && Number.isFinite(next) && next > 0) {
setHeight(Math.min(MAX_HEIGHT, Math.ceil(next)));
}
},
});
hostRef.current = host;
let loads = 0;
let navigatedAway = false;
const onLoad = () => {
@@ -115,7 +148,16 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
window.addEventListener("message", onMessage);
const themeObserver = new MutationObserver(() => host.hostContextChanged({ theme: resolvedTheme(), styles: { variables: hostStyleVariables() } }));
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
// A fullscreen view has a fixed container: tell it when that container resizes.
const resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => {
if (latest.current.displayMode === "fullscreen") {
host.hostContextChanged({ containerDimensions: containerDimensionsFor(iframe, "fullscreen") });
}
});
resizeObserver?.observe(iframe);
return () => {
resizeObserver?.disconnect();
if (hostRef.current === host) hostRef.current = null;
themeObserver.disconnect();
iframe.removeEventListener("load", onLoad);
host.teardown();
@@ -123,8 +165,18 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
};
// srcDoc is captured by frameKey; tool input and result are read through `latest`.
// eslint-disable-next-line react-hooks/exhaustive-deps
// The capability flags are part of frameKey.
}, [frameKey, viewId, toolName]);
// The view hears about a mode change with its new container.
const lastDisplayMode = useRef(displayMode);
useEffect(() => {
if (lastDisplayMode.current === displayMode) return;
lastDisplayMode.current = displayMode;
const iframe = iframeRef.current;
if (iframe) hostRef.current?.hostContextChanged({ displayMode, containerDimensions: containerDimensionsFor(iframe, displayMode) });
}, [displayMode]);
return (
<iframe
key={frameKey}
@@ -138,8 +190,15 @@ export function McpAppFrame({ title, viewId, toolName, resource, toolInput, tool
referrerPolicy="no-referrer"
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; fullscreen 'none'"
data-testid="mcp-app-frame"
style={{ height }}
className={cn("block w-full border-0 bg-transparent", className)}
data-display-mode={displayMode}
style={displayMode === "fullscreen" ? undefined : { height }}
className={cn("block w-full border-0 bg-transparent", displayMode === "fullscreen" && "h-full", className)}
/>
);
}
/** Inline views size themselves up to a maximum height; a fullscreen view gets a fixed container. */
function containerDimensionsFor(iframe: HTMLIFrameElement, mode: McpAppDisplayMode): McpAppContainerDimensions {
if (mode === "fullscreen") return { height: iframe.clientHeight, width: iframe.clientWidth };
return { maxHeight: MAX_HEIGHT, ...(iframe.clientWidth ? { width: iframe.clientWidth } : {}) };
}
@@ -1,19 +1,40 @@
import { createContext, useContext, useEffect, useRef, type ReactNode } from "react";
import { createContext, useContext, useEffect, useMemo, useRef, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { McpAppViewSummary } from "@paperclipai/shared";
import { mcpAppsApi } from "@/api/mcpApps";
import { queryKeys } from "@/lib/queryKeys";
import { mcpAppViewIndexFor } from "./mcp-app-matching";
/** The task whose chat is showing, so a run's replies can find their MCP Apps views. */
const McpAppIssueContext = createContext<string | null>(null);
/**
* Sends a message as the viewer's own comment through the chat's normal send
* path (the same one the composer uses), with this client request id.
*/
export type McpAppSendMessage = (body: string, clientRequestId: string) => Promise<void>;
export function McpAppIssueProvider({ issueId, children }: { issueId: string | null | undefined; children: ReactNode }) {
return <McpAppIssueContext.Provider value={issueId ?? null}>{children}</McpAppIssueContext.Provider>;
interface McpAppIssueValue {
issueId: string | null;
sendMessage: McpAppSendMessage | null;
}
/** The task whose chat is showing, so a run's replies can find their MCP Apps views. */
const McpAppIssueContext = createContext<McpAppIssueValue>({ issueId: null, sendMessage: null });
export function McpAppIssueProvider({ issueId, sendMessage, children }: {
issueId: string | null | undefined;
/** Omitted when the viewer can't send messages here: views then can't propose any. */
sendMessage?: McpAppSendMessage | null;
children: ReactNode;
}) {
const value = useMemo(() => ({ issueId: issueId ?? null, sendMessage: sendMessage ?? null }), [issueId, sendMessage]);
return <McpAppIssueContext.Provider value={value}>{children}</McpAppIssueContext.Provider>;
}
export function useMcpAppIssueId(): string | null {
return useContext(McpAppIssueContext);
return useContext(McpAppIssueContext).issueId;
}
export function useMcpAppSendMessage(): McpAppSendMessage | null {
return useContext(McpAppIssueContext).sendMessage;
}
const NO_VIEWS: McpAppViewSummary[] = [];
+26 -10
View File
@@ -1,8 +1,10 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import type { McpAppViewSummary } from "@paperclipai/shared";
import { Maximize2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useMcpAppIssueId, useMcpAppViewsForRun, type McpAppViewsFreshness } from "./McpAppIssueContext";
import { McpAppView } from "./McpAppView";
import type { McpAppDisplayMode } from "./mcp-app-host";
/** "DisplayMeetings" → "Display meetings". */
export function mcpAppToolDisplayName(toolName: string): string {
@@ -12,14 +14,29 @@ export function mcpAppToolDisplayName(toolName: string): string {
function McpAppRunView({ issueId, view }: { issueId: string; view: McpAppViewSummary }) {
const displayName = mcpAppToolDisplayName(view.upstreamToolName);
const [displayMode, setDisplayMode] = useState<McpAppDisplayMode>("inline");
const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
const markNear = useCallback(() => setNear(true), []);
return (
<section data-testid="mcp-app-turn-view" aria-label={`${view.applicationName}: ${displayName}`} className="flex min-w-0 flex-col gap-2">
<div className="flex min-w-0 items-baseline gap-2 text-xs">
<span className="text-muted-foreground">Widget from {view.applicationName}</span>
<span className="truncate font-medium text-foreground">{displayName}</span>
<div className="flex min-w-0 items-center gap-2 text-xs">
<span className="shrink-0 text-muted-foreground">Widget from {view.applicationName}</span>
<span className="min-w-0 truncate font-medium text-foreground">{displayName}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="ml-auto shrink-0 text-xs text-muted-foreground"
onClick={() => { setNear(true); setDisplayMode("fullscreen"); }}
disabled={displayMode === "fullscreen"}
aria-label={`Open ${view.applicationName} ${displayName} full screen`}
>
<Maximize2 aria-hidden="true" />
Open full screen
</Button>
</div>
<NearViewport placeholderLabel={`${view.applicationName}: ${displayName}`}>
<McpAppView issueId={issueId} view={view} displayName={displayName} />
<NearViewport placeholderLabel={`${view.applicationName}: ${displayName}`} near={near} onNear={markNear}>
<McpAppView issueId={issueId} view={view} displayName={displayName} displayMode={displayMode} onDisplayModeChange={setDisplayMode} />
</NearViewport>
</section>
);
@@ -35,17 +52,16 @@ export const MCP_APP_VIEWS_PER_RUN = 5;
* its iframe) only once the placeholder nears the viewport. A long chat with
* many recorded views pays only for the ones the reader reaches.
*/
function NearViewport({ children, placeholderLabel }: { children: ReactNode; placeholderLabel: string }) {
function NearViewport({ children, placeholderLabel, near, onNear }: { children: ReactNode; placeholderLabel: string; near: boolean; onNear: () => void }) {
const ref = useRef<HTMLDivElement>(null);
const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined");
useEffect(() => {
if (near || !ref.current) return;
const observer = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) setNear(true);
if (entries.some((entry) => entry.isIntersecting)) onNear();
}, { rootMargin: NEAR_VIEWPORT_MARGIN });
observer.observe(ref.current);
return () => observer.disconnect();
}, [near]);
}, [near, onNear]);
if (near) return <>{children}</>;
return <div ref={ref} role="status" aria-label={`${placeholderLabel} (not loaded yet)`} data-testid="mcp-app-view-placeholder" className="h-24 rounded-lg border border-border bg-muted/30" />;
}
+89 -3
View File
@@ -2,8 +2,11 @@
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("@/api/mcpApps", () => ({ mcpAppsApi: { messageSent: vi.fn(async () => ({ commentId: "c1" })) } }));
import type { McpAppViewDetail } from "@paperclipai/shared";
import { McpAppViewContent } from "./McpAppView";
import { McpAppViewContent, useMcpAppMessageProposal, type McpAppViewContentProps } from "./McpAppView";
import { McpAppFrame } from "./McpAppFrame";
import { McpAppIssueProvider } from "./McpAppIssueContext";
import { mcpAppNavigationGuardSupported } from "./mcp-app-host";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -16,15 +19,22 @@ const detail: McpAppViewDetail = {
resource: { uri: "ui://circleback/meetings", html: "<p>cards</p>", csp: {}, permissions: {}, prefersBorder: true },
};
async function render() {
async function render(props: Partial<McpAppViewContentProps> = {}) {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => root.render(
<McpAppViewContent detail={detail} status="ready" callTool={async () => ({ content: [] })} displayName="Display meetings" />,
<McpAppViewContent detail={detail} status="ready" callTool={async () => ({ content: [] })} displayName="Display meetings" {...props} />,
));
return { container, root };
}
function button(label: string): HTMLButtonElement {
const found = [...document.querySelectorAll("button")].find((element) => element.textContent?.trim() === label);
if (!found) throw new Error(`No button "${label}"`);
return found as HTMLButtonElement;
}
afterEach(() => vi.unstubAllGlobals());
describe("McpAppViewContent", () => {
@@ -42,4 +52,80 @@ describe("McpAppViewContent", () => {
expect(container.querySelector("iframe")).not.toBeNull();
await act(async () => root.unmount());
});
it("shows a view's proposed message under the widget and sends it only on Send", async () => {
vi.stubGlobal("navigation", { addEventListener: () => undefined });
const onSendProposal = vi.fn();
const onDismissProposal = vi.fn();
const { container, root } = await render({
proposal: { text: "Summarize the Heavybit meeting", status: "pending" }, onSendProposal, onDismissProposal,
});
const card = container.querySelector("[data-testid=mcp-app-message-proposal]")!;
expect(card.textContent).toContain("Circleback wants to send:");
expect(card.textContent).toContain("Summarize the Heavybit meeting");
// The card comes after the widget.
expect(container.querySelector("iframe")!.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(onSendProposal).not.toHaveBeenCalled();
await act(async () => button("Dismiss").click());
expect(onDismissProposal).toHaveBeenCalledTimes(1);
await act(async () => button("Send").click());
expect(onSendProposal).toHaveBeenCalledTimes(1);
await act(async () => root.unmount());
container.remove();
});
it("shows the view full screen in a dialog, with one frame at a time", async () => {
vi.stubGlobal("navigation", { addEventListener: () => undefined });
const onDisplayModeChange = vi.fn();
const { container, root } = await render({ displayMode: "fullscreen", onDisplayModeChange });
const dialog = document.querySelector("[data-testid=mcp-app-fullscreen]")!;
expect(dialog).not.toBeNull();
expect(dialog.querySelectorAll("iframe")).toHaveLength(1);
expect(dialog.querySelector("iframe")!.getAttribute("data-display-mode")).toBe("fullscreen");
expect(document.querySelectorAll("iframe")).toHaveLength(1);
expect(container.querySelector("[data-testid=mcp-app-view-fullscreen-placeholder]")).not.toBeNull();
await act(async () => button("Exit full screen").click());
expect(onDisplayModeChange).toHaveBeenCalledWith("inline");
await act(async () => root.unmount());
container.remove();
});
it("starts a new frame when the host's capabilities change, so the view handshakes again", async () => {
const container = document.createElement("div");
const root = createRoot(container);
const frame = (proposeMessage?: (text: string) => Promise<void>) => (
<McpAppFrame title="Circleback" viewId="view-1" toolName="DisplayMeetings" resource={detail.resource}
toolInput={{}} toolResult={{ content: [] }} callTool={async () => ({ content: [] })} proposeMessage={proposeMessage} />
);
await act(async () => root.render(frame()));
const first = container.querySelector("iframe");
await act(async () => root.render(frame(async () => undefined)));
expect(container.querySelector("iframe")).not.toBe(first);
await act(async () => root.unmount());
});
it("retries a failed Send with the same request id, so the comment is posted once", async () => {
const sendMessage = vi.fn()
.mockRejectedValueOnce(new Error("Network error"))
.mockResolvedValueOnce(undefined);
let api: ReturnType<typeof useMcpAppMessageProposal> | null = null;
function Harness() {
api = useMcpAppMessageProposal("issue-1", "view-1");
return null;
}
const container = document.createElement("div");
const root = createRoot(container);
await act(async () => root.render(<McpAppIssueProvider issueId="issue-1" sendMessage={sendMessage}><Harness /></McpAppIssueProvider>));
let settled = false;
await act(async () => { void api!.proposeMessage!("Summarize m1").then(() => { settled = true; }); });
await act(async () => { api!.onSend!(); });
expect(api!.proposal).toMatchObject({ status: "error" });
expect(settled).toBe(false);
await act(async () => { api!.onSend!(); });
expect(sendMessage).toHaveBeenCalledTimes(2);
expect(sendMessage.mock.calls[0]![1]).toBe(sendMessage.mock.calls[1]![1]);
expect(settled).toBe(true);
expect(api!.proposal).toBeNull();
await act(async () => root.unmount());
});
});
+204 -25
View File
@@ -1,25 +1,80 @@
import { useCallback } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import type { McpAppCallToolResult, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
import type { McpAppCallToolResult, McpAppModelContext, McpAppViewDetail, McpAppViewSummary } from "@paperclipai/shared";
import { mcpAppsApi } from "@/api/mcpApps";
import { ApiError } from "@/api/client";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { queryKeys } from "@/lib/queryKeys";
import { cn } from "@/lib/utils";
import { McpAppFrame } from "./McpAppFrame";
import { mcpAppNavigationGuardSupported } from "./mcp-app-host";
import { useMcpAppSendMessage } from "./McpAppIssueContext";
import { mcpAppNavigationGuardSupported, type McpAppDisplayMode } from "./mcp-app-host";
const UNSUPPORTED_BROWSER_MESSAGE = "This browser can't show this app's widget safely. The tool result is still in the activity.";
/** A message a view proposed for the chat, waiting for the viewer. */
export interface McpAppMessageProposal {
text: string;
status: "pending" | "sending" | "error";
errorMessage?: string | null;
}
/**
* "Circleback wants to send: …". Nothing is sent until the viewer clicks Send;
* the text is shown exactly as it will be posted.
*/
export function McpAppMessageProposalCard({ applicationName, proposal, onSend, onDismiss }: {
applicationName: string;
proposal: McpAppMessageProposal;
onSend: () => void;
onDismiss: () => void;
}) {
const sending = proposal.status === "sending";
return (
<div
role="group"
aria-label={`${applicationName} wants to send a message`}
data-testid="mcp-app-message-proposal"
className="flex min-w-0 flex-col gap-2 rounded-lg border border-border bg-muted/30 p-3"
>
<p className="text-xs text-muted-foreground">{applicationName} wants to send:</p>
<blockquote className="max-h-48 overflow-y-auto whitespace-pre-wrap break-words border-l-2 border-border pl-2.5 text-sm text-foreground">
{proposal.text}
</blockquote>
{proposal.status === "error" ? (
<p role="alert" className="text-xs text-destructive">{proposal.errorMessage ?? "The message could not be sent."}</p>
) : null}
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={onDismiss} disabled={sending}>Dismiss</Button>
<Button type="button" size="sm" onClick={onSend} disabled={sending}>{sending ? "Sending…" : "Send"}</Button>
</div>
</div>
);
}
export interface McpAppViewContentProps {
detail: McpAppViewDetail | undefined;
status: "loading" | "error" | "ready";
errorMessage?: string | null;
callTool: (name: string, args: Record<string, unknown>) => Promise<McpAppCallToolResult>;
displayName: string;
displayMode?: McpAppDisplayMode;
/** The view or the viewer changed the display mode. Without it, views stay inline. */
onDisplayModeChange?: (mode: McpAppDisplayMode) => void;
proposeMessage?: (text: string) => Promise<void>;
updateModelContext?: (context: McpAppModelContext | null) => Promise<void>;
proposal?: McpAppMessageProposal | null;
onSendProposal?: () => void;
onDismissProposal?: () => void;
}
/** Presentational shell, shared by the live view and its stories. */
export function McpAppViewContent({ detail, status, errorMessage, callTool, displayName }: McpAppViewContentProps) {
export function McpAppViewContent({
detail, status, errorMessage, callTool, displayName,
displayMode = "inline", onDisplayModeChange, proposeMessage, updateModelContext,
proposal, onSendProposal, onDismissProposal,
}: McpAppViewContentProps) {
const unsupported = !mcpAppNavigationGuardSupported();
if (status === "error" || unsupported) {
return (
@@ -28,27 +83,69 @@ export function McpAppViewContent({ detail, status, errorMessage, callTool, disp
</div>
);
}
const applicationName = detail?.applicationName ?? "App";
const fullscreen = displayMode === "fullscreen" && Boolean(detail) && Boolean(onDisplayModeChange);
// One frame at a time: the fullscreen dialog hosts its own frame while the
// inline slot waits, so the view never runs twice.
const frame = detail ? (
<McpAppFrame
title={`${detail.applicationName}: ${displayName}`}
viewId={detail.id}
toolName={detail.upstreamToolName}
resource={detail.resource}
toolInput={detail.toolInput}
toolResult={detail.toolResult}
callTool={callTool}
displayMode={fullscreen ? "fullscreen" : "inline"}
onRequestDisplayMode={onDisplayModeChange}
proposeMessage={proposeMessage}
updateModelContext={updateModelContext}
className={fullscreen ? "min-h-0 flex-1" : undefined}
/>
) : null;
const proposalCard = proposal && onSendProposal && onDismissProposal ? (
<McpAppMessageProposalCard applicationName={applicationName} proposal={proposal} onSend={onSendProposal} onDismiss={onDismissProposal} />
) : null;
return (
<div
data-testid="mcp-app-view"
className={cn(
"min-w-0 max-w-full overflow-hidden",
detail?.resource.prefersBorder !== false && "rounded-lg border border-border bg-card p-3",
)}
>
{status === "loading" || !detail ? (
<div role="status" aria-label={`Loading ${detail?.applicationName ?? "app"} view`} className="h-24 animate-pulse bg-muted/40" />
) : (
<McpAppFrame
title={`${detail.applicationName}: ${displayName}`}
viewId={detail.id}
toolName={detail.upstreamToolName}
resource={detail.resource}
toolInput={detail.toolInput}
toolResult={detail.toolResult}
callTool={callTool}
/>
)}
<div className="flex min-w-0 flex-col gap-2">
<div
data-testid="mcp-app-view"
className={cn(
"min-w-0 max-w-full overflow-hidden",
detail?.resource.prefersBorder !== false && "rounded-lg border border-border bg-card p-3",
)}
>
{status === "loading" || !detail ? (
<div role="status" aria-label={`Loading ${detail?.applicationName ?? "app"} view`} className="h-24 animate-pulse bg-muted/40" />
) : fullscreen ? (
<div role="status" data-testid="mcp-app-view-fullscreen-placeholder" className="flex items-center justify-between gap-2 py-2 text-xs text-muted-foreground">
<span>Showing full screen</span>
<Button type="button" variant="ghost" size="sm" onClick={() => onDisplayModeChange?.("inline")}>Back to chat</Button>
</div>
) : frame}
</div>
{fullscreen ? null : proposalCard}
{fullscreen ? (
<Dialog open onOpenChange={(open) => { if (!open) onDisplayModeChange?.("inline"); }}>
<DialogContent
data-testid="mcp-app-fullscreen"
showCloseButton={false}
className="inset-4 top-4 left-4 flex h-auto w-auto max-w-none translate-x-0 translate-y-0 flex-col gap-0 p-0 sm:max-w-none md:top-4 md:translate-y-0"
>
<div className="flex min-w-0 items-center justify-between gap-2 border-b border-border px-4 py-2">
<div className="min-w-0">
<DialogTitle className="truncate text-sm font-medium">{displayName}</DialogTitle>
<DialogDescription className="text-xs">Widget from {applicationName}</DialogDescription>
</div>
<Button type="button" variant="ghost" size="sm" onClick={() => onDisplayModeChange?.("inline")}>Exit full screen</Button>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-2 p-3">
{frame}
{proposalCard}
</div>
</DialogContent>
</Dialog>
) : null}
</div>
);
}
@@ -58,8 +155,72 @@ function viewErrorMessage(error: unknown, applicationName: string): string {
return `${applicationName} could not show this view. The tool result is still in the row above.`;
}
function sendErrorMessage(error: unknown): string {
return error instanceof Error && error.message ? error.message : "The message could not be sent.";
}
/**
* The view's `ui/message` proposals. At most one waits per view; the view
* hears "sent" only after the viewer clicked Send and the comment went out.
*/
export function useMcpAppMessageProposal(issueId: string, viewId: string) {
const sendMessage = useMcpAppSendMessage();
const [proposal, setProposal] = useState<McpAppMessageProposal | null>(null);
// One request id per proposal: a retry after a lost response reuses it, so
// the comment endpoint's duplicate protection keeps it to one comment.
const pending = useRef<{ text: string; clientRequestId: string; resolve: () => void; reject: (error: Error) => void } | null>(null);
useEffect(() => () => {
pending.current?.reject(new Error("The view was closed"));
pending.current = null;
}, []);
const proposeMessage = useCallback((text: string) => new Promise<void>((resolve, reject) => {
if (pending.current) {
reject(new Error("A message from this view is already waiting for the user"));
return;
}
pending.current = { text, clientRequestId: crypto.randomUUID(), resolve, reject };
setProposal({ text, status: "pending" });
}), []);
const onSend = useCallback(async () => {
const current = pending.current;
if (!current || !sendMessage) return;
setProposal({ text: current.text, status: "sending" });
const { clientRequestId } = current;
try {
await sendMessage(current.text, clientRequestId);
} catch (error) {
setProposal({ text: current.text, status: "error", errorMessage: sendErrorMessage(error) });
return;
}
// The comment is sent; recording where it came from must not undo that.
void mcpAppsApi.messageSent(issueId, viewId, clientRequestId).catch(() => undefined);
pending.current = null;
setProposal(null);
current.resolve();
}, [issueId, viewId, sendMessage]);
const onDismiss = useCallback(() => {
pending.current?.reject(new Error("Message sending denied"));
pending.current = null;
setProposal(null);
}, []);
return sendMessage
? { proposeMessage, proposal, onSend: () => void onSend(), onDismiss }
: { proposeMessage: undefined, proposal: null, onSend: undefined, onDismiss: undefined };
}
/** Loads a recorded view and renders it under its tool row. */
export function McpAppView({ issueId, view, displayName }: { issueId: string; view: McpAppViewSummary; displayName: string }) {
export function McpAppView({ issueId, view, displayName, displayMode, onDisplayModeChange }: {
issueId: string;
view: McpAppViewSummary;
displayName: string;
displayMode?: McpAppDisplayMode;
onDisplayModeChange?: (mode: McpAppDisplayMode) => void;
}) {
const query = useQuery({
queryKey: queryKeys.mcpApps.detail(issueId, view.id),
queryFn: ({ signal }) => mcpAppsApi.detail(issueId, view.id, signal),
@@ -72,6 +233,17 @@ export function McpAppView({ issueId, view, displayName }: { issueId: string; vi
(name: string, args: Record<string, unknown>) => mcpAppsApi.callTool(issueId, view.id, name, args),
[issueId, view.id],
);
const { proposeMessage, proposal, onSend, onDismiss } = useMcpAppMessageProposal(issueId, view.id);
// Context goes with messages: a viewer who can't post here can't steer the agent either.
// Writes are ordered per view, across frames: a write from a frame replaced
// by the full-screen one always lands before the new frame's writes.
const contextWrites = useRef<Promise<unknown>>(Promise.resolve());
const updateModelContext = useCallback((context: McpAppModelContext | null) => {
const write = contextWrites.current.catch(() => undefined)
.then(() => mcpAppsApi.updateModelContext(issueId, view.id, context));
contextWrites.current = write;
return write.then(() => undefined);
}, [issueId, view.id]);
return (
<McpAppViewContent
detail={query.data}
@@ -79,6 +251,13 @@ export function McpAppView({ issueId, view, displayName }: { issueId: string; vi
errorMessage={!query.data && query.error ? viewErrorMessage(query.error, view.applicationName) : null}
callTool={callTool}
displayName={displayName}
displayMode={displayMode}
onDisplayModeChange={onDisplayModeChange}
proposeMessage={proposeMessage}
updateModelContext={proposeMessage ? updateModelContext : undefined}
proposal={proposal}
onSendProposal={onSend}
onDismissProposal={onDismiss}
/>
);
}
+146 -2
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { createMcpAppHost, MCP_APP_NAVIGATION_GUARD, mcpAppDocument, safeExternalUrl, type McpAppHostContext } from "./mcp-app-host";
import { createMcpAppHost, MCP_APP_ESCAPE_NOTIFICATION, MCP_APP_NAVIGATION_GUARD, mcpAppDocument, safeExternalUrl, type McpAppHostContext } from "./mcp-app-host";
const hostContext: McpAppHostContext = {
theme: "dark",
@@ -106,6 +106,132 @@ describe("createMcpAppHost", () => {
});
});
describe("view requests that act for the user", () => {
const init = (host: ReturnType<typeof createMcpAppHost>, params: Record<string, unknown> = {}) =>
host.receive({ jsonrpc: "2.0", id: "init", method: "ui/initialize", params });
const reply = (posted: any[], id: unknown) => posted.find((message) => message.id === id);
it("advertises messages and model context only when the host implements them", async () => {
const bare = setup();
init(bare.host);
await flush();
expect(Object.keys(reply(bare.posted, "init").result.hostCapabilities)).not.toEqual(expect.arrayContaining(["message"]));
expect(reply(bare.posted, "init").result.hostCapabilities.updateModelContext).toBeUndefined();
const full = setup({ proposeMessage: vi.fn(), updateModelContext: vi.fn() });
init(full.host);
await flush();
expect(reply(full.posted, "init").result.hostCapabilities).toMatchObject({ message: { text: {} }, updateModelContext: { text: {}, structuredContent: {} } });
});
it("answers ui/message only after the viewer decides, one proposal at a time", async () => {
let decide!: { resolve: () => void; reject: (error: Error) => void };
const proposeMessage = vi.fn(() => new Promise<void>((resolve, reject) => { decide = { resolve, reject }; }));
const { host, posted } = setup({ proposeMessage });
init(host);
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/message", params: { role: "user", content: { type: "text", text: "Summarize m1" } } });
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/message", params: { role: "user", content: [{ type: "text", text: "And m2" }] } });
await flush();
expect(proposeMessage).toHaveBeenCalledTimes(1);
expect(proposeMessage).toHaveBeenCalledWith("Summarize m1");
// Nothing is answered while the viewer has not decided, and a second proposal is refused.
expect(reply(posted, 1)).toBeUndefined();
expect(reply(posted, 2)).toMatchObject({ error: { code: -32000 } });
decide.resolve();
await flush();
expect(reply(posted, 1)).toMatchObject({ result: {} });
// Dismissed: the view hears that sending was denied.
host.receive({ jsonrpc: "2.0", id: 3, method: "ui/message", params: { role: "user", content: [{ type: "text", text: "Again" }] } });
await flush();
decide.reject(new Error("dismissed"));
await flush();
expect(reply(posted, 3)).toMatchObject({ error: { code: -32000, message: "Message sending denied" } });
// Not text, or not from the user: invalid.
host.receive({ jsonrpc: "2.0", id: 4, method: "ui/message", params: { role: "assistant", content: [{ type: "text", text: "x" }] } });
host.receive({ jsonrpc: "2.0", id: 5, method: "ui/message", params: { role: "user", content: [{ type: "image", data: "…" }] } });
await flush();
expect(reply(posted, 4)).toMatchObject({ error: { code: -32602 } });
expect(reply(posted, 5)).toMatchObject({ error: { code: -32602 } });
expect(proposeMessage).toHaveBeenCalledTimes(2);
});
it("stores model context in order, dedupes identical updates and rejects oversize ones", async () => {
const stored: unknown[] = [];
let releaseFirst!: () => void;
const updateModelContext = vi.fn(async (context: unknown) => {
if (stored.length === 0 && !releaseFirst) await new Promise<void>((resolve) => { releaseFirst = resolve; });
stored.push(context);
});
const { host, posted } = setup({ updateModelContext });
init(host);
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/update-model-context", params: { content: [{ type: "text", text: "first" }] } });
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/update-model-context", params: { content: [{ type: "text", text: "second" }], structuredContent: { meetingId: "m1" } } });
host.receive({ jsonrpc: "2.0", id: 3, method: "ui/update-model-context", params: { content: [{ type: "text", text: "second" }], structuredContent: { meetingId: "m1" } } });
await flush();
releaseFirst();
await flush();
await flush();
// A slow first write never lands after a later one; the repeat is not sent.
expect(stored).toEqual([
{ text: "first", structuredContent: null },
{ text: "second", structuredContent: { meetingId: "m1" } },
]);
expect([1, 2, 3].map((id) => reply(posted, id))).toEqual([1, 2, 3].map(() => expect.objectContaining({ result: {} })));
host.receive({ jsonrpc: "2.0", id: 4, method: "ui/update-model-context", params: { content: [{ type: "text", text: "x".repeat(20_000) }] } });
await flush();
expect(reply(posted, 4)).toMatchObject({ error: { code: -32602 } });
expect(updateModelContext).toHaveBeenCalledTimes(2);
});
it("drops a torn-down view's queued context updates", async () => {
let release!: () => void;
const updateModelContext = vi.fn(async () => { if (!release) await new Promise<void>((resolve) => { release = resolve; }); });
const { host } = setup({ updateModelContext });
init(host);
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/update-model-context", params: { content: [{ type: "text", text: "first" }] } });
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/update-model-context", params: { content: [{ type: "text", text: "stale" }] } });
await flush();
host.teardown();
release();
await flush();
await flush();
expect(updateModelContext).toHaveBeenCalledTimes(1);
});
it("switches display mode only to a mode both the host and the view support", async () => {
let mode: "inline" | "fullscreen" = "inline";
const setDisplayMode = vi.fn((next: "inline" | "fullscreen") => { mode = next; });
const { host, posted } = setup({ setDisplayMode, hostContext: () => ({ ...hostContext, displayMode: mode, availableDisplayModes: ["inline", "fullscreen"] }) });
init(host, { appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] } });
host.receive({ jsonrpc: "2.0", id: 1, method: "ui/request-display-mode", params: { mode: "pip" } });
host.receive({ jsonrpc: "2.0", id: 2, method: "ui/request-display-mode", params: { mode: "fullscreen" } });
await flush();
expect(reply(posted, 1)).toMatchObject({ result: { mode: "inline" } });
expect(reply(posted, 2)).toMatchObject({ result: { mode: "fullscreen" } });
expect(setDisplayMode).toHaveBeenCalledWith("fullscreen");
host.receive({ jsonrpc: "2.0", id: 3, method: "ui/request-display-mode", params: { mode: "inline" } });
await flush();
expect(reply(posted, 3)).toMatchObject({ result: { mode: "inline" } });
// A view that declared only inline is never switched to fullscreen.
const inlineOnly = setup({ setDisplayMode: vi.fn() });
init(inlineOnly.host, { appCapabilities: { availableDisplayModes: ["inline"] } });
inlineOnly.host.receive({ jsonrpc: "2.0", id: 1, method: "ui/request-display-mode", params: { mode: "fullscreen" } });
await flush();
expect(reply(inlineOnly.posted, 1)).toMatchObject({ result: { mode: "inline" } });
expect(inlineOnly.options.setDisplayMode).not.toHaveBeenCalled();
});
it("tells the view about a new display mode and container", () => {
const { host, posted } = setup();
host.receive({ jsonrpc: "2.0", method: "ui/notifications/initialized" });
host.hostContextChanged({ displayMode: "fullscreen", containerDimensions: { height: 800, width: 1200 } });
expect(posted.at(-1)).toMatchObject({ method: "ui/notifications/host-context-changed", params: { displayMode: "fullscreen", containerDimensions: { height: 800, width: 1200 } } });
});
});
describe("mcpAppDocument", () => {
it("installs the CSP before the view's markup and keeps one doctype", () => {
const doc = mcpAppDocument("<!DOCTYPE html><html><head><script>1</script></head></html>", { connectDomains: ["https://api.circleback.ai"] });
@@ -131,7 +257,7 @@ describe("mcpAppDocument", () => {
{ href: "javascript:alert(1)", attrs: { href: "javascript:alert(1)" } },
];
let clickHandler: ((event: unknown) => void) | null = null;
const fakeWindow: Record<string, unknown> = { open: () => "real window" };
const fakeWindow: Record<string, unknown> = { open: () => "real window", addEventListener: () => undefined };
const fakeDocument = {
baseURI: "about:srcdoc",
addEventListener: (type: string, handler: (event: unknown) => void) => { if (type === "click") clickHandler = handler; },
@@ -156,6 +282,24 @@ describe("mcpAppDocument", () => {
]);
});
it("reports an Escape the view did not handle, so full screen can close", () => {
const posted: unknown[] = [];
let keydown: ((event: unknown) => void) | null = null;
const fakeWindow = { open: () => null, addEventListener: (type: string, handler: (event: unknown) => void) => { if (type === "keydown") keydown = handler; } };
const fakeDocument = { baseURI: "about:srcdoc", addEventListener: () => undefined };
new Function("window", "document", "parent", MCP_APP_NAVIGATION_GUARD)(fakeWindow, fakeDocument, { postMessage: (message: unknown) => posted.push(message) });
keydown!({ key: "Escape", defaultPrevented: true });
keydown!({ key: "Enter", defaultPrevented: false });
expect(posted).toEqual([]);
keydown!({ key: "Escape", defaultPrevented: false });
expect(posted).toEqual([{ jsonrpc: "2.0", method: MCP_APP_ESCAPE_NOTIFICATION }]);
const onEscape = vi.fn();
const { host } = setup({ onEscape });
host.receive(posted[0]);
expect(onEscape).toHaveBeenCalledTimes(1);
});
it("allows only http(s) external urls", () => {
expect(safeExternalUrl("https://circleback.ai")).toBe("https://circleback.ai/");
expect(safeExternalUrl("data:text/html,x")).toBeNull();
+128 -10
View File
@@ -1,7 +1,10 @@
import {
buildMcpAppCsp,
MCP_APPS_PROTOCOL_VERSION,
normalizeMcpAppModelContext,
readMcpAppMessageText,
type McpAppCallToolResult,
type McpAppModelContext,
type McpAppResourceCsp,
} from "@paperclipai/shared";
@@ -11,11 +14,19 @@ import {
* it answers through `post`.
*/
export type McpAppDisplayMode = "inline" | "fullscreen";
/** Display modes Paperclip can show a view in. Picture-in-picture is not supported. */
export const MCP_APP_HOST_DISPLAY_MODES: readonly McpAppDisplayMode[] = ["inline", "fullscreen"];
export type McpAppContainerDimensions =
| { maxHeight: number; width?: number }
| { height: number; width: number };
export interface McpAppHostContext {
theme: "light" | "dark";
displayMode: "inline";
availableDisplayModes: ["inline"];
containerDimensions: { maxHeight: number; width?: number };
displayMode: McpAppDisplayMode;
availableDisplayModes: McpAppDisplayMode[];
containerDimensions: McpAppContainerDimensions;
locale: string;
timeZone: string;
platform: "web";
@@ -33,8 +44,29 @@ export interface McpAppHostOptions {
openLink: (url: string) => void;
onSizeChanged: (size: { width?: number; height?: number }) => void;
onLog?: (entry: unknown) => void;
/**
* `ui/message`: shows the proposed text to the viewer. Resolves once the
* viewer sent it, rejects when they dismissed it or sending failed. Never
* sends on its own. Without it, `ui/message` is not supported.
*/
proposeMessage?: (text: string) => Promise<void>;
/** `ui/update-model-context`: stores the view's latest context for the agent (null clears it). */
updateModelContext?: (context: McpAppModelContext | null) => Promise<void>;
/**
* `ui/request-display-mode`: switches the view to a mode both sides support.
* Without it, the view stays inline.
*/
setDisplayMode?: (mode: McpAppDisplayMode) => void;
/**
* Escape pressed inside the view and not handled by it. Keyboard events
* never leave the sandboxed frame, so the navigation guard reports it.
*/
onEscape?: () => void;
}
/** Paperclip-only notification from the navigation guard; not part of the MCP Apps spec. */
export const MCP_APP_ESCAPE_NOTIFICATION = "paperclip/escape-pressed";
type JsonRpcId = string | number;
interface JsonRpcMessage {
jsonrpc: "2.0";
@@ -77,6 +109,12 @@ export function createMcpAppHost(options: McpAppHostOptions) {
let toolDataSent = false;
let nextRequestId = 1;
let disposed = false;
// One proposal at a time per view: a view cannot queue messages behind the viewer's back.
let messagePending = false;
let lastModelContext: string | undefined;
let contextQueue: Promise<void> = Promise.resolve();
// Display modes the view declared in `ui/initialize`; undefined means it did not say.
let appDisplayModes: McpAppDisplayMode[] | undefined;
const respond = (id: JsonRpcId, result: unknown) => options.post({ jsonrpc: "2.0", id, result });
const fail = (id: JsonRpcId, code: number, message: string) => options.post({ jsonrpc: "2.0", id, error: { code, message } });
@@ -99,8 +137,12 @@ export function createMcpAppHost(options: McpAppHostOptions) {
return;
}
switch (message.method) {
case "ui/initialize":
case "ui/initialize": {
handshakeStarted = true;
const declared = record(params.appCapabilities)?.availableDisplayModes;
appDisplayModes = Array.isArray(declared)
? declared.filter((mode): mode is McpAppDisplayMode => mode === "inline" || mode === "fullscreen")
: undefined;
respond(message.id, {
protocolVersion: MCP_APPS_PROTOCOL_VERSION,
hostInfo: { name: "Paperclip", version: "1.0.0" },
@@ -108,11 +150,14 @@ export function createMcpAppHost(options: McpAppHostOptions) {
openLinks: {},
serverTools: {},
logging: {},
...(options.proposeMessage ? { message: { text: {} } } : {}),
...(options.updateModelContext ? { updateModelContext: { text: {}, structuredContent: {} } } : {}),
sandbox: { permissions: {}, csp: {} },
},
hostContext: options.hostContext(),
});
return;
}
case "ping":
respond(message.id, {});
return;
@@ -140,13 +185,81 @@ export function createMcpAppHost(options: McpAppHostOptions) {
respond(message.id, {});
return;
}
case "ui/request-display-mode":
respond(message.id, { mode: "inline" });
case "ui/request-display-mode": {
const current = options.hostContext().displayMode;
const requested = params.mode;
const allowed = (requested === "inline" || requested === "fullscreen")
&& options.setDisplayMode !== undefined
&& (requested === "inline" || appDisplayModes === undefined || appDisplayModes.includes(requested));
if (!allowed || requested === current) {
respond(message.id, { mode: current });
return;
}
options.setDisplayMode!(requested);
respond(message.id, { mode: requested });
return;
case "ui/update-model-context":
// Accepted; Paperclip does not yet feed view context back to the agent.
respond(message.id, {});
}
case "ui/message": {
if (!options.proposeMessage) {
fail(message.id, METHOD_NOT_FOUND, "ui/message is not supported by Paperclip");
return;
}
const text = readMcpAppMessageText(params);
if (!text) {
fail(message.id, INVALID_PARAMS, "Invalid message format");
return;
}
if (messagePending) {
fail(message.id, SERVER_ERROR, "A message from this view is already waiting for the user");
return;
}
messagePending = true;
try {
await options.proposeMessage(text);
respond(message.id, {});
} catch {
fail(message.id, SERVER_ERROR, "Message sending denied");
} finally {
messagePending = false;
}
return;
}
case "ui/update-model-context": {
if (!options.updateModelContext) {
respond(message.id, {});
return;
}
let context: McpAppModelContext | null;
try {
context = normalizeMcpAppModelContext(params);
} catch {
fail(message.id, INVALID_PARAMS, "Invalid content format");
return;
}
// Updates are applied in order, so a slow earlier write never lands
// after a later one. Identical updates are deduped.
const serialized = JSON.stringify(context);
const update = options.updateModelContext;
const id = message.id;
contextQueue = contextQueue.then(async () => {
// A torn-down view's queued updates are dropped: its replacement
// reports its own current context.
if (disposed) return;
if (serialized === lastModelContext) {
respond(id, {});
return;
}
try {
await update(context);
lastModelContext = serialized;
respond(id, {});
} catch {
fail(id, SERVER_ERROR, "Context update denied");
}
});
await contextQueue;
return;
}
default:
fail(message.id, METHOD_NOT_FOUND, `${message.method} is not supported by Paperclip`);
}
@@ -168,6 +281,9 @@ export function createMcpAppHost(options: McpAppHostOptions) {
case "notifications/message":
options.onLog?.(params);
return;
case MCP_APP_ESCAPE_NOTIFICATION:
options.onEscape?.();
return;
default:
return;
}
@@ -229,7 +345,8 @@ export function mcpAppNavigationGuardSupported(target: unknown = typeof window =
* `ui/open-link` (http and https only, opened in a new tab with noopener):
* - cross-document navigations of the frame are cancelled (Navigation API);
* - link clicks, whatever their target, are routed to the host;
* - `window.open` posts to the host and returns null.
* - `window.open` posts to the host and returns null;
* - an Escape the view did not handle is reported, so a full-screen dialog closes.
* Same-document navigations (pushState, hashes) still work.
*/
export const MCP_APP_NAVIGATION_GUARD = `(function(){
@@ -237,5 +354,6 @@ var n=0;function open(u){try{u=String(new URL(String(u),document.baseURI))}catch
window.open=function(u){if(u!=null&&u!=="")open(u);return null;};
var nav=window.navigation;
if(nav&&nav.addEventListener)nav.addEventListener("navigate",function(e){var d=e.destination;if(!d||d.sameDocument||e.downloadRequest||!e.cancelable)return;e.preventDefault();open(d.url);});
window.addEventListener("keydown",function(e){if(e.key==="Escape"&&!e.defaultPrevented)parent.postMessage({jsonrpc:"2.0",method:"paperclip/escape-pressed"},"*");});
document.addEventListener("click",function(e){var t=e.target,a=t&&t.closest?t.closest("a[href]"):null;if(!a||e.defaultPrevented)return;if((a.getAttribute("href")||"").charAt(0)==="#")return;e.preventDefault();open(a.href);},true);
})();`;
@@ -262,6 +262,32 @@ describe("TaskChatInteractionCard", () => {
expect(preview).not.toMatch(/[`*_~[\]]|(^|\s)- /);
});
// Full cohort 11: the unanswered-question chip and the composer takeover showed the same
// pending question at once, both with id "interaction-<id>", so the page had a duplicate id.
it("keeps the interaction id unique while its timeline chip and takeover card are both shown", () => {
const interaction = pendingAskUserQuestionsInteraction;
flushSync(() => {
root.render(
<TooltipProvider>
<ThemeProvider>
<TaskChatInteractionCard item={interactionItem(interaction)} showUnansweredQuestion onReviewRequest={() => {}} />
<div data-testid="task-chat-composer-takeover">
<TaskChatInteractionCard item={interactionItem(interaction)} presentation="takeover" />
</div>
</ThemeProvider>
</TooltipProvider>,
);
});
const anchors = container.querySelectorAll(`[id="interaction-${interaction.id}"]`);
expect(anchors).toHaveLength(1);
expect(anchors[0]!.getAttribute("data-testid")).toBe("task-chat-unanswered-question");
const takeover = container.querySelector(`[data-testid="task-chat-composer-takeover"] [data-interaction-id="${interaction.id}"]`);
expect(takeover).not.toBeNull();
expect(takeover!.id).toBe("");
const ids = [...container.querySelectorAll("[id]")].map(node => node.id);
expect(new Set(ids).size).toBe(ids.length);
});
it("renders a plan confirmation as a linked document preview", () => {
const interaction = createRequestConfirmation({
sourceRunId: "run-plan",
@@ -50,8 +50,12 @@ export function TaskChatInteractionCard({
}: TaskChatInteractionCardProps) {
const { enabled: coordinatorEnabled } = useCoordinatorWorkspaceEnabled();
const interaction = item.interaction;
// The timeline item owns the interaction's page anchor. The composer takeover
// shows the same interaction at the same time, so it carries only the data
// attribute: a DOM id must stay unique.
const anchorId = presentation === "takeover" ? undefined : `interaction-${interaction.id}`;
if (coordinatorEnabled && interaction.kind === "suggest_tasks" && !shouldHideInteractionCard(interaction)) {
return <div id={`interaction-${interaction.id}`} data-testid="task-chat-interaction" className="w-full">
return <div id={anchorId} data-interaction-id={interaction.id} data-testid="task-chat-interaction" className="w-full">
<TaskChatCompactInteractionCard interaction={interaction} presentation={presentation} draftKey={draftKey} {...cardProps} />
</div>;
}
@@ -60,7 +64,7 @@ export function TaskChatInteractionCard({
return (
<button
type="button"
id={`interaction-${interaction.id}`}
id={anchorId} data-interaction-id={interaction.id}
data-testid="task-chat-unanswered-question"
aria-label={`Answer question: ${prompt}`}
disabled={!onReviewRequest}
@@ -79,7 +83,7 @@ export function TaskChatInteractionCard({
return <IssueThreadInteractionCard interaction={interaction} {...cardProps} />;
}
return (
<div id={`interaction-${interaction.id}`} data-testid="task-chat-tool-review" className="w-full space-y-2">
<div id={anchorId} data-interaction-id={interaction.id} data-testid="task-chat-tool-review" className="w-full space-y-2">
{interaction.status === "pending" ? (
<div className="flex flex-wrap items-center gap-2 text-sm">
<AppLogo name={action.appDisplayName || action.toolDisplayName} size={36} />
@@ -108,7 +112,7 @@ export function TaskChatInteractionCard({
return (
<div className="w-full space-y-2">
{showPlan ? <TaskChatPlanPreviewCard source={{ kind: "saved", document: planDocument }} testId="plan-review-preview" /> : null}
<button type="button" id={`interaction-${interaction.id}`} data-testid="task-chat-pending-request"
<button type="button" id={anchorId} data-interaction-id={interaction.id} data-testid="task-chat-pending-request"
aria-label={`Open request: ${label}`} disabled={!onReviewRequest}
onClick={() => onReviewRequest?.(interaction.id)}
className="group flex w-full items-center gap-2 rounded-sm px-1 py-1.5 text-left text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
@@ -140,7 +144,7 @@ export function TaskChatInteractionCard({
if (!isPlanReview || !showPlanPreview) return null;
return (
<div
id={`interaction-${interaction.id}`}
id={anchorId} data-interaction-id={interaction.id}
data-testid="task-chat-interaction"
>
<TaskChatPlanPreviewCard
@@ -169,7 +173,7 @@ export function TaskChatInteractionCard({
// card while it is current, and the receipt records who decided and why.
return (
<div
id={`interaction-${interaction.id}`}
id={anchorId} data-interaction-id={interaction.id}
className="w-full space-y-2"
data-testid="task-chat-interaction"
>
@@ -193,7 +197,7 @@ export function TaskChatInteractionCard({
if (presentation === "timeline" && interaction.status !== "pending") {
return (
<div
id={`interaction-${interaction.id}`}
id={anchorId} data-interaction-id={interaction.id}
className="tc-enter-bubble w-full"
data-testid="task-chat-interaction"
>
@@ -210,7 +214,7 @@ export function TaskChatInteractionCard({
}
return (
<div
id={`interaction-${interaction.id}`}
id={anchorId} data-interaction-id={interaction.id}
className="tc-enter-bubble w-full"
data-testid="task-chat-interaction"
>
@@ -5,6 +5,9 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ExecutionProjection } from "@paperclipai/shared";
import type { TranscriptEntry } from "../../adapters";
import { MemoryRouter } from "@/lib/router";
vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompany: null }) }));
import { TaskChatLiveRunPill, toolCountSummaryFromEntries } from "./TaskChatLiveRunPill";
function toolCall(overrides: Partial<Extract<TranscriptEntry, { kind: "tool_call" }>>): TranscriptEntry {
@@ -101,6 +104,29 @@ describe("TaskChatLiveRunPill", () => {
},
);
it("shows a queued run that waits for an agent slot as waiting, not working", () => {
const execution = {
phase: "queued", label: "Waiting for Codie", cause: "agent_at_capacity",
agentQueue: { agentId: "agent-1", agentName: "Codie", maxConcurrentRuns: 20, runningCount: 20, position: 41, queuedCount: 295 },
} as ExecutionProjection;
act(() => root.render(
<MemoryRouter>
<TaskChatLiveRunPill status="queued" execution={execution} startedAtMs={Date.now() - 3 * 60 * 60_000} toolSummary={null} />
</MemoryRouter>,
));
expect(container.textContent).toContain("Waiting for Codie·20 slots max·41 of 295 in line·Configure");
expect(container.textContent).not.toContain("Working");
expect(container.querySelector(".animate-spin")).toBeNull();
expect(container.querySelector("a")?.getAttribute("href")).toBe("/agents/codie/advanced");
});
it("names another server hold on a queued run instead of Working", () => {
const execution = { phase: "queued", label: "Waiting for maintenance", cause: "task_drain" } as ExecutionProjection;
act(() => root.render(<TaskChatLiveRunPill status="queued" execution={execution} startedAtMs={Date.now()} toolSummary={null} />));
expect(container.textContent).toContain("Waiting for maintenance");
expect(container.textContent).not.toContain("Working");
});
it("settles to a static 'Worked' summary once the run is terminal", () => {
const startedAtMs = 1_000;
act(() => {
@@ -7,6 +7,8 @@ import { formatDurationWords } from "@/lib/issue-chat-messages";
import { isCommandTool } from "@/lib/transcriptPresentation";
import { isTerminalRunStatus } from "@/components/task-chat/transcript-adapter";
import { useTaskChatShimmer } from "./TaskChatShimmer";
import { AgentQueueWait } from "@/components/AgentQueueWait";
import { agentQueueWaitOf } from "@/lib/agent-queue-wait";
/**
* "ran N commands, called M tools" for the live tail's status pill, counted off
@@ -46,6 +48,7 @@ export function toolCountSummaryFromEntries(entries: readonly TranscriptEntry[])
*/
export function TaskChatLiveRunPill({
status,
execution,
startedAtMs,
finishedAtMs,
toolSummary,
@@ -60,9 +63,12 @@ export function TaskChatLiveRunPill({
}) {
const active = !isTerminalRunStatus(status);
const shimmer = useTaskChatShimmer("working");
const agentQueue = status === "queued" ? agentQueueWaitOf(execution) : null;
// A specific server hold (maintenance, agent setup) names the wait instead of "Working".
const holdLabel = status === "queued" && execution?.cause ? execution.label : null;
// One shared page-wide ticker drives the live elapsed readout, matching the
// default view's `useLiveElapsed`.
useSecondTick(active && startedAtMs != null);
useSecondTick(active && startedAtMs != null && !agentQueue);
const elapsedMs =
startedAtMs == null ? null : (active ? Date.now() : finishedAtMs ?? Date.now()) - startedAtMs;
@@ -70,9 +76,17 @@ export function TaskChatLiveRunPill({
? formatDurationWords(elapsedMs)
: null;
const failed = ["failed", "timed_out", "cancelled", "interrupted"].includes(status);
const verb = active ? "Working" : failed ? "Stopped" : "Worked";
const verb = active ? holdLabel ?? "Working" : failed ? "Stopped" : "Worked";
const suffix = elapsed ? `for ${elapsed}` : null;
if (agentQueue) {
return (
<div className="flex min-w-0 items-center gap-2 py-2" data-testid="task-chat-live-run-pill">
<AgentQueueWait queue={agentQueue} />
</div>
);
}
return (
<div
className="flex min-w-0 items-center gap-2 py-2"
@@ -1,4 +1,6 @@
import { groupImageResources } from "./image-resources";
import { AgentQueueWait } from "@/components/AgentQueueWait";
import { agentQueueWaitOf } from "@/lib/agent-queue-wait";
import { McpAppTurnViews, mcpAppRunRefreshKey } from "@/components/mcp-app/McpAppTurnViews";
import { useRef, type ReactNode } from "react";
import type { ExecutionProjection } from "@paperclipai/shared";
@@ -139,11 +141,15 @@ function runnerWaitingLabel({ runId, status, execution, preparationLabel }: Runn
return status === "queued" && execution?.cause ? execution.label : null;
}
function agentQueueWaitFor({ status, execution }: Pick<RunnerHeaderProps, "status" | "execution">) {
return status === "queued" ? agentQueueWaitOf(execution) : null;
}
/** One identity stays mounted while admission discovers the run's renderer. */
export function TaskChatRunnerHeader({ statusContent, ...props }: RunnerHeaderProps & { statusContent?: ReactNode }) {
return <div className="flex min-h-8 min-w-0 items-center gap-2 pb-1 pt-2" data-testid="task-chat-runner-identity-row">
{props.agentName ? <TaskChatAgentIdentity agentName={props.agentName} agentIcon={props.agentIcon} agent={props.agent} /> : null}
{statusContent ?? <RunnerTurnStatus status={props.status} startedAtMs={props.startedAtMs} finishedAtMs={props.finishedAtMs}
{statusContent ?? (agentQueueWaitFor(props) ? <AgentQueueWait queue={agentQueueWaitFor(props)!} /> : null) ?? <RunnerTurnStatus status={props.status} startedAtMs={props.startedAtMs} finishedAtMs={props.finishedAtMs}
continuedAfterSteering={props.continuedAfterSteering} waitingLabel={runnerWaitingLabel(props)} />}
</div>;
}
@@ -13,6 +13,7 @@ import { toolTaxonomy } from "./tool-taxonomy";
import { useTaskChatShimmer } from "./TaskChatShimmer";
import { TaskChatDiffCounts, TaskChatDiffView } from "./TaskChatDiffView";
import { useTaskReferenceLabel, withTaskReference } from "./task-reference";
import { ProviderToolIcon, useProviderToolIcons } from "@/components/ProviderToolIcon";
const STATUS_ICON = {
pending: { Icon: Loader2, spin: false, tone: "text-muted-foreground" },
@@ -51,6 +52,7 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
const { Icon, spin, tone } = STATUS_ICON[item.status];
const shimmer = useTaskChatShimmer(item.id);
const RowIcon = toolTaxonomy(item.rawName ?? item.name).icon;
const providerIcons = useProviderToolIcons(item.rawName ?? item.name);
const [showDetail, setShowDetail] = useTaskChatExpansion(item.id, false);
const expandable = Boolean(item.target || item.detail || item.diff);
@@ -68,10 +70,11 @@ export function TaskChatToolCard({ item }: { item: TaskChatToolItem }) {
)}
>
<span className="flex w-5 shrink-0 items-center justify-center">
<RowIcon
<ProviderToolIcon
icons={providerIcons}
fallback={RowIcon}
className="h-3.5 w-3.5 shrink-0"
aria-hidden
data-testid="task-chat-tool-icon"
testId="task-chat-tool-icon"
/>
</span>
<span data-conversation-tool-running={item.status === "in_progress" && shimmer ? "true" : undefined} className="flex min-w-0 flex-1 items-baseline gap-2 overflow-hidden">
@@ -47,6 +47,23 @@ describe("compactAdjacentErrors", () => {
expect(compactAdjacentErrors([failed, legacy]).items).toEqual([legacy]);
});
it.each([
"Paperclip tried to start this task again, but it still could not start. Press Retry to start it again.",
"Paperclip tried to continue this task again, but it still could not continue after 3 tries. Press Retry to start it again from the saved work.",
])("recognizes the current recovery notice: %s", (text) => {
const titled = { ...recovery, text, presentation: { ...recovery.presentation!, title: "Task could not continue" } };
expect(compactAdjacentErrors([failed, titled]).items).toEqual([titled]);
const unstructured = { ...recovery, text, presentation: null };
expect(compactAdjacentErrors([failed, unstructured]).items).toEqual([unstructured]);
const retitled: TaskChatMessageItem = { ...recovery, text,
presentation: { ...recovery.presentation!, title: "Automatic recovery blocked" },
metadata: { version: 1, sections: [{ title: "Recovery", rows: [
{ type: "key_value", label: "Recovery action", value: "recovery-action-1" }] }] } };
expect(compactAdjacentErrors([failed, retitled]).items).toEqual([retitled]);
const quoted = { ...recovery, presentation: null, text: `Child task report: ${text}` };
expect(compactAdjacentErrors([failed, quoted]).items).toEqual([failed, quoted]);
});
it.each(["Automatic recovery blocked", "Error: usage limit reached"])(
"recognizes a saved stranded-recovery notice with the producer title %s", (title) => {
// buildStrandedRecoveryEscalationNotice saves this metadata even when
@@ -1,10 +1,15 @@
import type { TaskChatItem, TaskChatMarkerItem, TaskChatMessageItem } from "./task-chat-model";
const RECOVERY_STATEMENT = /^Paperclip tried to (?:start|continue) this task again, but it still could not (?:start|continue)\b/i;
const LEGACY_RECOVERY_STATEMENT = /^Paperclip (?:automatically )?retried (?:dispatch|continuation|this issue's run)\b[^\r\n]*\bit still has no live execution path\b/i;
const RECOVERY_TITLES = new Set(["task could not continue", "no live execution path"]);
export function isNoLiveExecutionPathNotice(item: TaskChatMessageItem): boolean {
if (item.author !== "system") return false;
const recoveryStatement = /^Paperclip (?:automatically )?retried (?:dispatch|continuation|this issue's run)\b[^\r\n]*\bit still has no live execution path\b/i.test(item.text.trim());
const text = item.text.trim();
const recoveryStatement = RECOVERY_STATEMENT.test(text) || LEGACY_RECOVERY_STATEMENT.test(text);
if (item.presentation) {
if (item.presentation.title?.trim().toLowerCase() === "no live execution path") return true;
if (RECOVERY_TITLES.has(item.presentation.title?.trim().toLowerCase() ?? "")) return true;
// The stranded-recovery producer can replace the family title with
// "Automatic recovery blocked" or a classified source-run failure.
// Require both its recovery statement and saved action metadata so an
+8
View File
@@ -111,3 +111,11 @@ export function useTheme() {
}
return context;
}
/**
* The current theme, re-rendering on change. Outside a ThemeProvider (tests,
* isolated stories) it falls back to the document's class.
*/
export function useResolvedTheme(): Theme {
return useContext(ThemeContext)?.theme ?? resolveThemeFromDocument();
}
+13
View File
@@ -57,6 +57,19 @@ describe("optimistic task Retry", () => {
await render({ ...waiting, interruption: { ...presentation, state: "working", canRetry: false } } as Issue);
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("sends the move-forward intent from the offer and says plainly when the task already moved on", async () => {
const presentation = { intentId: null, responsibility: "system" as const, state: "working" as const, canRetry: true,
retryAction: "move_forward" as const, nextRetryAt: null, userAction: null, sourceRunIds: ["continuation"], observedRunId: "continuation" };
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: null, accepted: false, stale: false, alreadyMovedOn: true,
presentation: { ...presentation, canRetry: false, retryAction: undefined } } as Awaited<ReturnType<typeof issuesApi.retryTask>>);
await render({ ...issue, interruption: presentation } as Issue);
await act(async () => container.querySelector("button")!.click());
expect(issuesApi.retryTask).toHaveBeenCalledExactlyOnceWith("task", {
observedRunId: "continuation", retryAction: "move_forward", idempotencyKey: expect.any(String),
});
expect(container.querySelector('[role="alert"]')?.textContent).toContain("already moved on, so nothing new was started");
});
it("shows nothing extra when Retry promoted the scheduled run", async () => {
vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: "retry", accepted: true, stale: false,
scheduledRetry: { outcome: "promoted", message: "Retry promoted" }, presentation: null });
+7 -2
View File
@@ -6,12 +6,16 @@ import { issuesApi } from "../api/issues";
import { queryKeys } from "../lib/queryKeys";
import { createUuid } from "../lib/uuid";
type RetryRequest = { issueId: string; identifier?: string | null; idempotencyKey: string; observedRunId: string | null };
type RetryRequest = { issueId: string; identifier?: string | null; idempotencyKey: string; observedRunId: string | null;
retryAction?: "move_forward" };
type RetryResult = Awaited<ReturnType<typeof issuesApi.retryTask>>;
export const STALE_TASK_RETRY_MESSAGE = "This attempt was already replaced, so Retry did not start new work. The task now shows its current state.";
export const ALREADY_MOVED_ON_MESSAGE = "The task already moved on, so nothing new was started. It now shows its current state.";
export function taskRetryNotStartedReason(result: RetryResult): string | null {
if (!result.accepted && result.alreadyMovedOn) return ALREADY_MOVED_ON_MESSAGE;
if (!result.accepted) return STALE_TASK_RETRY_MESSAGE;
const outcome = result.scheduledRetry?.outcome;
if (outcome && outcome !== "promoted" && outcome !== "already_promoted") return result.scheduledRetry!.message;
@@ -95,7 +99,8 @@ export function useTaskRetry(issue: Issue | undefined) {
setNotStarted(null);
mutation.reset();
request.current ??= { issueId: issue.id, identifier: issue.identifier, idempotencyKey: createUuid(),
observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null };
observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null,
...(issue.interruption?.retryAction === "move_forward" ? { retryAction: "move_forward" as const } : {}) };
setOptimistic(true);
setTakingLonger(false);
mutation.mutate(request.current);
+29
View File
@@ -0,0 +1,29 @@
import type { ExecutionAgentQueue, ExecutionProjection } from "@paperclipai/shared";
import { agentDetailHref } from "../pages/agent-detail-navigation";
import { agentRouteRef } from "./utils";
/** The server's explanation that a run waits for a free slot of its agent. */
export function agentQueueWaitOf(
execution: Pick<ExecutionProjection, "cause" | "agentQueue"> | null | undefined,
): ExecutionAgentQueue | null {
return execution?.cause === "agent_at_capacity" && execution.agentQueue ? execution.agentQueue : null;
}
/** A run the server accepted but never started: it waits, it is not working. */
export function isWaitingToStart(run: { status: string; startedAt?: string | Date | null }): boolean {
return run.status === "queued" && !run.startedAt;
}
/** "Waiting for Codie", "20 slots max", "41 of 295 in line". */
export function agentQueueWaitParts(queue: ExecutionAgentQueue): [string, string, string] {
return [
`Waiting for ${queue.agentName}`,
`${queue.maxConcurrentRuns} ${queue.maxConcurrentRuns === 1 ? "slot" : "slots"} max`,
`${queue.position} of ${queue.queuedCount} in line`,
];
}
/** Where the agent's concurrency limit is edited (its run policy, in the Advanced view). */
export function agentQueueConfigureHref(queue: Pick<ExecutionAgentQueue, "agentId" | "agentName">): string {
return agentDetailHref(agentRouteRef({ id: queue.agentId, name: queue.agentName }), "advanced");
}
@@ -5,6 +5,7 @@ import { QueryClient } from "@tanstack/react-query";
import type { BrowserTracingConfig } from "@paperclipai/shared";
import type { PageLoadMeasurement } from "./page-load-recorder";
import {
observeApiResources,
resetPageSessionSampleForTest,
SDK_LOAD_DEADLINE_MS,
startBrowserTracingController,
@@ -19,14 +20,101 @@ const config: BrowserTracingConfig = {
sampleRate: 1,
};
/**
* The page's clock starts at navigation start. A test process can be older
* than the 30 s page-load timeout, which would turn the hard load (start 0)
* into a timeout, so the clock is restarted for each test.
*/
function restartPageClock() {
const realNow = performance.now.bind(performance);
const origin = realNow();
vi.spyOn(performance, "now").mockImplementation(() => realNow() - origin);
}
describe("startBrowserTracingController", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "requestAnimationFrame", "cancelAnimationFrame"] });
resetPageSessionSampleForTest();
restartPageClock();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
setVisibility("visible");
});
function setVisibility(state: DocumentVisibilityState) {
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state });
}
function hangingQueryClient() {
const queryClient = new QueryClient();
void queryClient.fetchQuery({ queryKey: ["hangs"], queryFn: () => new Promise(() => {}) });
return queryClient;
}
function recordingSdk(ended: PageLoadMeasurement[]) {
return vi.fn(async (): Promise<TracingSdkModule> => ({
startTracingSdk: (_config, recorder) => {
recorder.attachSink({ begin: () => {}, end: (m) => ended.push({ ...m }) });
return { forceFlush: async () => {}, shutdown: async () => {} };
},
}));
}
it("ends a hard load in a background tab as hidden instead of a 30 s timeout", async () => {
setVisibility("hidden");
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]).toMatchObject({ loadType: "hard", outcome: "hidden", startTime: 0, endTime: 0, wasHidden: true });
controller?.stop();
});
it("ends an open load as hidden when the tab hides", async () => {
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(1_000);
setVisibility("hidden");
const hiddenAt = performance.now();
document.dispatchEvent(new Event("visibilitychange"));
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]!.outcome).toBe("hidden");
expect(ended[0]!.endTime).toBeGreaterThanOrEqual(hiddenAt);
expect(ended[0]!.endTime).toBeLessThan(hiddenAt + 1_000);
controller?.stop();
});
it("records the all-tasks page view from the URL", async () => {
window.history.replaceState(null, "", "/PAP/issues?view=mine&q=private-search");
const ended: PageLoadMeasurement[] = [];
const controller = startBrowserTracingController(config, {
queryClient: hangingQueryClient(),
initialPathname: "/PAP/issues",
initialRouteTemplate: "/:companyPrefix/issues",
loadSdk: recordingSdk(ended),
scheduleSdkLoad: () => () => {},
});
await vi.advanceTimersByTimeAsync(SDK_LOAD_DEADLINE_MS);
await vi.waitFor(() => expect(ended).toHaveLength(1));
expect(ended[0]!.view).toBe("mine");
controller?.stop();
window.history.replaceState(null, "", "/");
});
it("still loads the SDK and exports a timed-out hard load when the page never settles", async () => {
@@ -79,3 +167,58 @@ describe("startBrowserTracingController", () => {
controller?.stop();
});
});
describe("observeApiResources", () => {
type Listener = (list: { getEntries(): PerformanceEntry[] }) => void;
function fakeObserver() {
const state: { listener: Listener | null; options: PerformanceObserverInit | null; disconnected: boolean } = {
listener: null,
options: null,
disconnected: false,
};
class FakeObserver {
static supportedEntryTypes = ["resource"];
constructor(listener: Listener) {
state.listener = listener;
}
observe(options: PerformanceObserverInit) {
state.options = options;
}
disconnect() {
state.disconnected = true;
}
}
return { state, Observer: FakeObserver as unknown as typeof PerformanceObserver };
}
const entry = (name: string, initiatorType = "fetch") => ({ name, initiatorType, entryType: "resource", startTime: 5 }) as unknown as PerformanceEntry;
it("keeps only this origin's /api/ fetches, including ones already buffered", () => {
const { state, Observer } = fakeObserver();
const collector = observeApiResources("https://acme.paperclip.app", Observer);
expect(state.options).toEqual({ type: "resource", buffered: true });
state.listener!({
getEntries: () => [
entry("https://acme.paperclip.app/api/issues?view=mine"),
entry("https://acme.paperclip.app/api/companies", "xmlhttprequest"),
entry("https://acme.paperclip.app/assets/index.js", "script"),
entry("https://acme.paperclip.app.evil.com/api/issues"),
entry("https://api.honeycomb.io/v1/traces"),
],
});
expect(collector.entries().map((e) => e.name)).toEqual([
"https://acme.paperclip.app/api/issues?view=mine",
"https://acme.paperclip.app/api/companies",
]);
collector.stop();
expect(state.disconnected).toBe(true);
expect(collector.entries()).toEqual([]);
});
it("does nothing where resource timing is unavailable", () => {
const collector = observeApiResources("https://acme.paperclip.app", null);
expect(collector.entries()).toEqual([]);
collector.stop();
});
});
+85 -5
View File
@@ -6,7 +6,10 @@
// - decides once per page session whether this session is sampled; an
// unsampled session does nothing else and downloads nothing,
// - measures the hard load and every client-side navigation
// (`page-load-recorder.ts`), and
// (`page-load-recorder.ts`),
// - keeps the Resource Timing entries of this origin's `/api/` requests
// until the SDK loads, so the SDK can show the hard load's API requests,
// and
// - after the page settles, downloads the tracing SDK chunk (`sdk.ts`),
// which exports the measurements, Web Vitals, and API request spans.
// See doc/browser-performance-tracing.md.
@@ -16,6 +19,7 @@ import type { BrowserTracingConfig } from "@paperclipai/shared";
import { whenPageSettles } from "@/lib/when-page-settles";
import { readPageContentGates } from "./page-content-gates";
import { createPageLoadRecorder, PAGE_LOAD_TIMEOUT_MS, type PageLoadRecorder } from "./page-load-recorder";
import { pageViewFor } from "./page-view";
export type RouterNavigationType = "PUSH" | "POP" | "REPLACE";
@@ -30,8 +34,19 @@ export interface TracingSdkHandle {
shutdown(): Promise<void>;
}
/** Resource Timing entries for this origin's `/api/` requests, kept until the SDK takes them. */
export interface ApiResourceCollector {
entries(): readonly PerformanceResourceTiming[];
/** Stops observing and drops the entries. */
stop(): void;
}
export interface TracingSdkModule {
startTracingSdk(config: BrowserTracingConfig, recorder: PageLoadRecorder): TracingSdkHandle;
startTracingSdk(
config: BrowserTracingConfig,
recorder: PageLoadRecorder,
options?: { apiResources?: ApiResourceCollector },
): TracingSdkHandle;
}
export interface BrowserTracingControllerOptions {
@@ -71,6 +86,67 @@ export function hasPendingPrimaryData(queryClient: QueryClient): boolean {
return queryClient.isFetching({ predicate: (query) => query.state.data === undefined }) > 0;
}
/** At most this many entries are kept; a hard load makes far fewer requests. */
const API_RESOURCE_LIMIT = 500;
/**
* Collects Resource Timing entries for `fetch`/XHR requests to `origin/api/`.
* `buffered: true` delivers the requests that finished before this ran (the
* hard load's session request, for example), and an observer keeps receiving
* entries after the browser's resource buffer (250 entries by default) is
* full. One observer callback per batch of finished requests; nothing else.
*/
export function observeApiResources(
origin: string,
Observer: typeof PerformanceObserver | null = typeof PerformanceObserver === "function" ? PerformanceObserver : null,
): ApiResourceCollector {
let kept: PerformanceResourceTiming[] = [];
if (!Observer || !(Observer.supportedEntryTypes ?? []).includes("resource")) {
return { entries: () => kept, stop: () => {} };
}
const prefix = `${origin}/api/`;
let observer: PerformanceObserver | null = null;
try {
observer = new Observer((list) => {
for (const entry of list.getEntries() as PerformanceResourceTiming[]) {
if (kept.length >= API_RESOURCE_LIMIT) break;
if ((entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") && entry.name.startsWith(prefix)) {
kept.push(entry);
}
}
});
observer.observe({ type: "resource", buffered: true });
} catch {
observer = null;
}
return {
entries: () => kept,
stop() {
observer?.disconnect();
observer = null;
kept = [];
},
};
}
/**
* When the tab was first hidden since navigation start, or null if it has
* been visible throughout. Chromium records each visibility change as a
* `visibility-state` performance entry (including the initial state); where
* it does not, a tab that is hidden now counts as hidden from the start, as
* `web-vitals` assumes.
*/
function firstHiddenTime(): number | null {
try {
const entries = performance.getEntriesByType?.("visibility-state") ?? [];
const hidden = entries.find((entry) => entry.name === "hidden");
if (hidden) return hidden.startTime;
} catch {
// Not supported.
}
return document.visibilityState === "hidden" ? 0 : null;
}
function pathnameOf(url: string | URL | null | undefined): string | null {
if (url === null || url === undefined) return null;
try {
@@ -136,15 +212,17 @@ export function startBrowserTracingController(
isDocumentHidden: () => document.visibilityState === "hidden",
hasPendingPrimaryData: () => hasPendingPrimaryData(options.queryClient),
readGates: readPageContentGates,
readView: (routeTemplate) => pageViewFor(routeTemplate, window.location.search),
});
const apiResources = observeApiResources(window.location.origin);
const history = trackHistoryChanges(now);
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") recorder.noteHidden();
if (document.visibilityState === "hidden") recorder.noteHidden(now());
};
document.addEventListener("visibilitychange", onVisibilityChange);
// The hard load started at navigation start (time 0), before this code ran.
recorder.begin({ routeTemplate: options.initialRouteTemplate, loadType: "hard", startTime: 0 });
recorder.begin({ routeTemplate: options.initialRouteTemplate, loadType: "hard", startTime: 0, hiddenAt: firstHiddenTime() });
let lastPathname = options.initialPathname;
let stopped = false;
@@ -161,10 +239,11 @@ export function startBrowserTracingController(
void loadSdk()
.then((module) => {
if (stopped) return;
sdk = module.startTracingSdk(config, recorder);
sdk = module.startTracingSdk(config, recorder, { apiResources });
})
.catch(() => {
// Tracing is optional; a failed chunk load must not affect the page.
apiResources.stop();
});
};
const deadline = window.setTimeout(startLoad, options.sdkLoadDeadlineMs ?? SDK_LOAD_DEADLINE_MS);
@@ -191,6 +270,7 @@ export function startBrowserTracingController(
history.stop();
document.removeEventListener("visibilitychange", onVisibilityChange);
recorder.stop();
apiResources.stop();
void sdk?.shutdown();
sdk = null;
},
@@ -10,6 +10,7 @@ function createHarness() {
const state = {
pendingData: false,
hidden: false,
view: null as string | null,
gates: { blockingCount: 0, contentCount: 0, pendingContentCount: 0, lastContentReadyAt: null } as PageContentGateSnapshot,
};
const recorder = createPageLoadRecorder({
@@ -32,6 +33,7 @@ function createHarness() {
isDocumentHidden: () => state.hidden,
hasPendingPrimaryData: () => state.pendingData,
readGates: () => state.gates,
readView: () => state.view,
});
const ended: PageLoadMeasurement[] = [];
const begun: PageLoadMeasurement[] = [];
@@ -58,6 +60,10 @@ function createHarness() {
}
}
},
/** Move the clock without firing timers or frames, as a suspended computer does. */
jump(ms: number) {
time += ms;
},
advance(ms: number) {
time += ms;
for (const [id, timer] of timers) {
@@ -132,6 +138,17 @@ describe("createPageLoadRecorder", () => {
expect(harness.recorder.open()?.routeTemplate).toBe("/b");
});
it("ends an interrupted measurement where the next one starts, so their windows never overlap", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
harness.advance(250);
// The router commits after the history change that started the navigation.
harness.recorder.begin({ routeTemplate: "/b", loadType: "client", startTime: 200 });
expect(harness.ended[0]).toMatchObject({ routeTemplate: "/a", outcome: "interrupted", endTime: 200 });
});
it("continues a measurement through a redirect under the new route", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
@@ -154,14 +171,118 @@ describe("createPageLoadRecorder", () => {
expect(harness.ended[0]).toMatchObject({ outcome: "timeout", endTime: 30_000, readySignal: null });
});
it("marks a measurement whose tab was hidden", () => {
it("ends a measurement as hidden, at the moment the tab hid, instead of waiting for frames that never come", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
harness.recorder.noteHidden();
harness.advance(400);
harness.state.hidden = true;
harness.recorder.noteHidden(400);
expect(harness.ended).toEqual([expect.objectContaining({ outcome: "hidden", endTime: 400, readySignal: null, wasHidden: true })]);
harness.advance(30_000);
expect(harness.ended).toHaveLength(1);
});
it("ends a load that starts in a hidden tab immediately as hidden, never as a 30 s timeout", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.hidden = true;
harness.state.pendingData = true;
harness.advance(900);
harness.recorder.begin({ routeTemplate: "/", loadType: "hard", startTime: 0, hiddenAt: 0 });
expect(harness.ended).toEqual([expect.objectContaining({ outcome: "hidden", endTime: 0, loadType: "hard" })]);
harness.advance(30_000);
expect(harness.ended).toHaveLength(1);
});
it("ends a hard load that was hidden before tracing started at the time it hid", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.advance(900);
// Visible again by now, but rendering was paused while it was hidden.
harness.recorder.begin({ routeTemplate: "/a", loadType: "hard", startTime: 0, hiddenAt: 350 });
expect(harness.ended[0]).toMatchObject({ outcome: "hidden", endTime: 350 });
});
it("keeps a redirect after a hidden hard load on the same measurement", () => {
const harness = createHarness();
harness.state.hidden = true;
harness.recorder.begin({ routeTemplate: "/", loadType: "hard", startTime: 0, hiddenAt: 0 });
expect(harness.recorder.redirect("/:companyPrefix/dashboard")).toBe(true);
harness.recorder.attachSink(harness.sink);
expect(harness.ended).toEqual([expect.objectContaining({ routeTemplate: "/:companyPrefix/dashboard", outcome: "hidden" })]);
expect(harness.recorder.hardLoadRouteTemplate()).toBe("/:companyPrefix/dashboard");
});
it("ends a timeout at start + timeout however late the timer fires, and marks a suspend", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/slow", loadType: "hard", startTime: 0 });
// The computer slept: the 30 s timer fires about two hours later.
harness.advance(7_758_250);
expect(harness.ended).toEqual([expect.objectContaining({ outcome: "timeout", endTime: 30_000, suspended: true })]);
});
it("does not mark an ordinarily late timeout as suspended", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/slow", loadType: "client", startTime: 0 });
harness.advance(30_400);
expect(harness.ended[0]).toMatchObject({ outcome: "timeout", endTime: 30_000, suspended: false });
});
it("reports a load that only became ready after the deadline, across a suspend, as a capped timeout", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
harness.frame();
harness.jump(2 * 60 * 60 * 1000);
harness.state.pendingData = false;
// Frames resume before the overdue timer runs.
harness.frame();
harness.frame();
expect(harness.ended[0]).toMatchObject({ wasHidden: true });
expect(harness.ended).toEqual([expect.objectContaining({ outcome: "timeout", endTime: 30_000, readySignal: null, suspended: true })]);
});
it("marks a ready load that spanned a suspend shorter than the timeout", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.recorder.begin({ routeTemplate: "/a", loadType: "client", startTime: 0 });
harness.frame();
harness.jump(20_000);
harness.state.pendingData = false;
harness.frame();
harness.frame();
expect(harness.ended[0]).toMatchObject({ outcome: "ready", suspended: true });
});
it("records the page view, read again when the measurement ends", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.view = "default";
harness.recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "hard", startTime: 0 });
expect(harness.begun[0]).toMatchObject({ view: "default" });
// The page writes the resolved view into the URL while loading.
harness.state.view = "mine";
harness.frame();
harness.frame();
expect(harness.ended[0]).toMatchObject({ view: "mine", suspended: false });
});
it("keeps the view an interrupted measurement had, not the next page's", () => {
const harness = createHarness();
harness.recorder.attachSink(harness.sink);
harness.state.pendingData = true;
harness.state.view = "mine";
harness.recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "client", startTime: 0 });
harness.state.view = null;
harness.recorder.begin({ routeTemplate: "/b", loadType: "client", startTime: 10 });
expect(harness.ended[0]).toMatchObject({ outcome: "interrupted", view: "mine" });
});
it("buffers measurements that finish before the SDK attaches and replays them in order", () => {
@@ -12,13 +12,26 @@
// (the end time is the latest gate's paint time), otherwise
// 2b. no query that has no data yet is fetching (the end time is the first
// such frame).
// A new navigation interrupts an open one. A measurement that has not ended
// after `timeoutMs` ends with outcome `timeout`.
// A new navigation interrupts an open one.
//
// A measurement in a tab that is hidden when it starts, or that hides before
// it is ready, ends with outcome `hidden` at the moment the tab hid. Browsers
// stop painting hidden tabs, so it could never become ready; the same rule as
// `web-vitals`, which stops reporting LCP and FCP once the page has been
// hidden.
//
// A measurement that has not ended `timeoutMs` after it started ends with
// outcome `timeout`, and its end time is exactly start + `timeoutMs`. Any end
// observed after that deadline (a timer that fired late, a frame that ran
// after the computer woke up) is reported as that timeout, never as a longer
// duration. When the observed end, or a gap between two frames, is more than
// `SUSPEND_GRACE_MS` late, the measurement is marked `suspended`: the
// computer slept or the tab was frozen while it was open.
import type { PageContentGateSnapshot } from "./page-content-gates";
export type PageLoadType = "hard" | "client";
export type PageLoadOutcome = "ready" | "timeout" | "interrupted";
export type PageLoadOutcome = "ready" | "timeout" | "interrupted" | "hidden";
export type PageLoadReadySignal = "content" | "idle";
export interface PageLoadMeasurement {
@@ -32,6 +45,10 @@ export interface PageLoadMeasurement {
readySignal: PageLoadReadySignal | null;
/** The tab was hidden at some point during the measurement. */
wasHidden: boolean;
/** The computer slept or the tab froze while the measurement was open. */
suspended: boolean;
/** The page's `?view=`, from an allowlist (`page-view.ts`); null for pages without views. */
view: string | null;
}
/** Receives measurements; implemented by the lazily loaded tracing SDK. */
@@ -49,6 +66,8 @@ export interface PageLoadRecorderDeps {
isDocumentHidden(): boolean;
hasPendingPrimaryData(): boolean;
readGates(): PageContentGateSnapshot;
/** The current page view for `routeTemplate` (`pageViewFor`). */
readView?(routeTemplate: string): string | null;
}
export interface PageLoadRecorderOptions {
@@ -59,21 +78,29 @@ export interface PageLoadRecorderOptions {
}
export interface PageLoadRecorder {
begin(input: { routeTemplate: string; loadType: PageLoadType; startTime: number }): PageLoadMeasurement;
/**
* `hiddenAt`: when the tab was first hidden after `startTime`, if it was
* hidden before this call (a hard load opened in a background tab).
*/
begin(input: { routeTemplate: string; loadType: PageLoadType; startTime: number; hiddenAt?: number | null }): PageLoadMeasurement;
/**
* A redirect (history replace) while a measurement is open continues it
* under the new route. Returns false when no measurement is open.
* under the new route, as does one right after a measurement that ended
* hidden and has not been exported yet. Returns false otherwise.
*/
redirect(routeTemplate: string): boolean;
open(): PageLoadMeasurement | null;
currentRouteTemplate(): string | null;
hardLoadRouteTemplate(): string | null;
noteHidden(): void;
/** The tab became hidden at `time`: an open measurement ends as `hidden`. */
noteHidden(time: number): void;
attachSink(sink: PageLoadSink): void;
stop(): void;
}
export const PAGE_LOAD_TIMEOUT_MS = 30_000;
/** An end, or a frame, this much later than expected means the computer slept. */
export const SUSPEND_GRACE_MS = 5_000;
export function createPageLoadRecorder(
deps: PageLoadRecorderDeps,
@@ -93,6 +120,8 @@ export function createPageLoadRecorder(
let timer: unknown = null;
let streak = 0;
let streakStart = 0;
let lastFrameAt: number | null = null;
let lastEnded: PageLoadMeasurement | null = null;
const buffered: PageLoadMeasurement[] = [];
function cancelScheduled() {
@@ -102,14 +131,31 @@ export function createPageLoadRecorder(
timer = null;
}
function readView(routeTemplate: string): string | null {
return deps.readView ? deps.readView(routeTemplate) : null;
}
function finish(measurement: PageLoadMeasurement, outcome: PageLoadOutcome, endTime: number, signal: PageLoadReadySignal | null) {
if (current === measurement) {
current = null;
cancelScheduled();
}
const deadline = measurement.startTime + timeoutMs;
if (endTime > deadline) {
// Not ready by the deadline, whatever happened after it.
if (endTime - deadline > SUSPEND_GRACE_MS) measurement.suspended = true;
outcome = "timeout";
signal = null;
endTime = deadline;
}
if (outcome === "hidden") measurement.wasHidden = true;
// An interrupted measurement keeps the view it had: the URL already
// belongs to the next page.
if (outcome !== "interrupted") measurement.view = readView(measurement.routeTemplate);
measurement.outcome = outcome;
measurement.readySignal = signal;
measurement.endTime = Math.max(measurement.startTime, endTime);
lastEnded = measurement;
if (measurement.loadType === "hard") hardLoadRoute = measurement.routeTemplate;
if (sink) {
sink.end(measurement);
@@ -123,7 +169,13 @@ export function createPageLoadRecorder(
frame = null;
const measurement = current;
if (!measurement || stopped) return;
if (deps.isDocumentHidden()) measurement.wasHidden = true;
const time = deps.now();
if (deps.isDocumentHidden()) {
finish(measurement, "hidden", time, null);
return;
}
if (lastFrameAt !== null && time - lastFrameAt > SUSPEND_GRACE_MS) measurement.suspended = true;
lastFrameAt = time;
const gates = deps.readGates();
let signal: PageLoadReadySignal | null = null;
@@ -138,7 +190,7 @@ export function createPageLoadRecorder(
if (signal === null) {
streak = 0;
} else {
if (streak === 0) streakStart = deps.now();
if (streak === 0) streakStart = time;
streak += 1;
if (streak >= stableFrames) {
const endTime = signal === "content" && gates.lastContentReadyAt !== null
@@ -153,6 +205,7 @@ export function createPageLoadRecorder(
function schedule(measurement: PageLoadMeasurement) {
streak = 0;
lastFrameAt = null;
frame = deps.requestFrame(tick);
const remaining = Math.max(0, measurement.startTime + timeoutMs - deps.now());
timer = deps.setTimer(() => {
@@ -162,8 +215,11 @@ export function createPageLoadRecorder(
}
return {
begin({ routeTemplate, loadType, startTime }) {
if (current) finish(current, "interrupted", deps.now(), null);
begin({ routeTemplate, loadType, startTime, hiddenAt = null }) {
// The open measurement ends where this one starts, so no request or
// time is counted under both.
if (current) finish(current, "interrupted", Math.min(deps.now(), startTime), null);
const hidden = hiddenAt !== null || deps.isDocumentHidden();
const measurement: PageLoadMeasurement = {
id: nextId++,
routeTemplate,
@@ -172,18 +228,31 @@ export function createPageLoadRecorder(
endTime: null,
outcome: null,
readySignal: null,
wasHidden: deps.isDocumentHidden(),
wasHidden: hidden,
suspended: false,
view: readView(routeTemplate),
};
latestRoute = routeTemplate;
if (stopped) return measurement;
current = measurement;
sink?.begin(measurement);
schedule(measurement);
if (hidden) finish(measurement, "hidden", hiddenAt ?? startTime, null);
else schedule(measurement);
return measurement;
},
redirect(routeTemplate) {
latestRoute = routeTemplate;
if (!current) return false;
if (!current) {
// A load in a background tab ends as soon as it starts; its redirect
// (for example `/` to the dashboard) renames it rather than starting
// a second, also hidden, measurement.
const ended = lastEnded;
if (ended?.outcome !== "hidden" || !deps.isDocumentHidden() || !buffered.includes(ended)) return false;
ended.routeTemplate = routeTemplate;
ended.view = readView(routeTemplate);
if (ended.loadType === "hard") hardLoadRoute = routeTemplate;
return true;
}
current.routeTemplate = routeTemplate;
streak = 0;
return true;
@@ -191,8 +260,8 @@ export function createPageLoadRecorder(
open: () => current,
currentRouteTemplate: () => latestRoute,
hardLoadRouteTemplate: () => hardLoadRoute ?? (current?.loadType === "hard" ? current.routeTemplate : null),
noteHidden() {
if (current) current.wasHidden = true;
noteHidden(time) {
if (current) finish(current, "hidden", time, null);
},
attachSink(next) {
if (stopped) return;
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { TASK_VIEW_KEYS } from "@/lib/task-views";
import { pageViewFor } from "./page-view";
describe("pageViewFor", () => {
it("reports the all-tasks page's view from ?view=", () => {
expect(pageViewFor("/:companyPrefix/issues", "?view=mine")).toBe("mine");
expect(pageViewFor("/:companyPrefix/issues", "?q=secret&view=needs_attention")).toBe("needs_attention");
for (const key of TASK_VIEW_KEYS) expect(pageViewFor("/:companyPrefix/issues", `?view=${key}`)).toBe(key);
});
it("never reports free text: an unknown view becomes other", () => {
expect(pageViewFor("/:companyPrefix/issues", "?view=PAP-1234")).toBe("other");
expect(pageViewFor("/:companyPrefix/issues", "?view=someone%40example.com")).toBe("other");
expect(pageViewFor("/:companyPrefix/decisions", "?view=mine%20x")).toBe("other");
});
it("reports the page's default when the URL names no view", () => {
expect(pageViewFor("/:companyPrefix/issues", "")).toBe("default");
expect(pageViewFor("/:companyPrefix/decisions", "?other=1")).toBe("mine");
expect(pageViewFor("/:companyPrefix/decisions", "?view=unassigned")).toBe("unassigned");
});
it("reports nothing for a page without views", () => {
expect(pageViewFor("/:companyPrefix/issues/:issueId", "?view=mine")).toBeNull();
expect(pageViewFor("/:companyPrefix/skills", "?view=catalog")).toBeNull();
});
});
+46
View File
@@ -0,0 +1,46 @@
// The `paperclip.page.view` dimension: which view a page's `?view=` selects,
// for the pages where that parameter picks a different list (for example
// `/:companyPrefix/issues?view=mine`). Main-bundle code, no OpenTelemetry.
//
// Only fixed view names from the code's own view registries are reported. A
// value that is not in the page's list becomes `other`, so a hand-edited URL
// never puts free text into a span.
import { ATTENTION_PERSONAL_VIEWS } from "@paperclipai/shared";
import { TASK_VIEW_KEYS, TASK_VIEW_PARAM } from "@/lib/task-views";
import { ATTENTION_VIEW_PARAM } from "@/lib/attention-views";
/** Reported for a `?view=` value that is not one of the page's views. */
export const OTHER_PAGE_VIEW = "other";
interface PageViewRule {
param: string;
views: ReadonlySet<string>;
/** Reported when the URL has no `?view=`. */
missing: string;
}
const PAGE_VIEW_RULES: ReadonlyMap<string, PageViewRule> = new Map([
// Tasks resolves a missing view from the last one used and writes it into
// the URL, so a finished measurement usually sees the resolved view.
["/:companyPrefix/issues", { param: TASK_VIEW_PARAM, views: new Set<string>(TASK_VIEW_KEYS), missing: "default" }],
// Decisions shows "For you" (`mine`) when the URL names no view.
["/:companyPrefix/decisions", { param: ATTENTION_VIEW_PARAM, views: new Set<string>(ATTENTION_PERSONAL_VIEWS), missing: "mine" }],
]);
/**
* The view for `routeTemplate` given the URL's query string, or null for a
* page that has no views.
*/
export function pageViewFor(routeTemplate: string, search: string): string | null {
const rule = PAGE_VIEW_RULES.get(routeTemplate);
if (!rule) return null;
let value: string | null;
try {
value = new URLSearchParams(search).get(rule.param);
} catch {
return OTHER_PAGE_VIEW;
}
if (value === null || value === "") return rule.missing;
return rule.views.has(value) ? value : OTHER_PAGE_VIEW;
}
+180 -1
View File
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { InMemorySpanExporter } from "@opentelemetry/sdk-trace-web";
import type { BrowserTracingConfig } from "@paperclipai/shared";
import { createPageLoadRecorder, type PageLoadRecorder } from "./page-load-recorder";
import { honeycombSampleRate, nonApiUrlPattern, startTracingSdk } from "./sdk";
import { honeycombSampleRate, nonApiUrlPattern, pageLoadAttributes, startTracingSdk } from "./sdk";
import { apiAreaFromUrl } from "./span-sanitizer";
import type { TracingSdkHandle } from "./controller";
@@ -126,7 +126,186 @@ describe("startTracingSdk", () => {
});
});
describe("hard-load API spans from Resource Timing", () => {
let exporter: InMemorySpanExporter;
let handle: TracingSdkHandle | null = null;
beforeEach(() => {
exporter = new InMemorySpanExporter();
});
afterEach(async () => {
await handle?.shutdown();
handle = null;
});
const origin = () => window.location.origin;
const resource = (name: string, startTime: number, responseEnd: number, extra: Record<string, unknown> = {}) =>
({ name, initiatorType: "fetch", entryType: "resource", startTime, responseEnd, ...extra }) as unknown as PerformanceResourceTiming;
it("backfills child spans under a hard load that finished before the SDK loaded", async () => {
const recorder = idleRecorder();
recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "hard", startTime: 0 });
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
const loadEnd = performance.now();
let stopped = false;
const entries = [
resource(`${origin()}/api/auth/get-session`, 0.5, 1, { responseStatus: 200 }),
resource(`${origin()}/api/companies/0f6b6d1e-2c4f-4b5e/issues?view=mine&q=secret`, 1, 2, { responseStatus: 404 }),
// Before the browser exposes a status, none is invented.
resource(`${origin()}/api/issues/PAP-77`, 1.5, 3),
// Started after the load ended: not part of it.
resource(`${origin()}/api/issues`, loadEnd + 1, loadEnd + 2),
];
handle = startTracingSdk(config, recorder, {
exporter,
apiResources: { entries: () => entries, stop: () => { stopped = true; } },
earlyResourceGraceMs: 0,
});
await handle.forceFlush();
const spans = exporter.getFinishedSpans();
const pageSpan = spans.find((span) => span.name === "page.load")!;
const children = spans.filter((span) => span.name !== "page.load");
expect(children.map((span) => span.name)).toEqual(["HTTP", "HTTP", "HTTP"]);
for (const child of children) {
expect(child.parentSpanContext?.spanId).toBe(pageSpan.spanContext().spanId);
expect(child.spanContext().traceId).toBe(pageSpan.spanContext().traceId);
const serialized = JSON.stringify(child.attributes);
expect(serialized).not.toContain("://");
expect(serialized).not.toContain("0f6b6d1e");
expect(serialized).not.toContain("PAP-77");
expect(serialized).not.toContain("secret");
expect(child.attributes["url.full"]).toBeUndefined();
}
expect(children.map((span) => span.attributes)).toEqual([
{ "paperclip.api.area": "auth", "paperclip.api.timing_source": "resource_timing", "http.response.status_code": 200, "paperclip.page.route": "/:companyPrefix/issues", SampleRate: 4 },
{ "paperclip.api.area": "companies", "paperclip.api.timing_source": "resource_timing", "http.response.status_code": 404, "paperclip.page.route": "/:companyPrefix/issues", SampleRate: 4 },
{ "paperclip.api.area": "issues", "paperclip.api.timing_source": "resource_timing", "paperclip.page.route": "/:companyPrefix/issues", SampleRate: 4 },
]);
await new Promise((resolve) => setTimeout(resolve, 10));
expect(stopped).toBe(true);
});
it("backfills every buffered navigation, not only the first one replayed", async () => {
const recorder = idleRecorder();
const flush = (recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames;
recorder.begin({ routeTemplate: "/:companyPrefix/dashboard", loadType: "hard", startTime: 0 });
flush();
const clientStart = performance.now();
recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "client", startTime: clientStart });
flush();
const clientEnd = performance.now();
let entries: PerformanceResourceTiming[] = [
resource(`${origin()}/api/companies`, 0.5, 1, { responseStatus: 200 }),
resource(`${origin()}/api/issues`, clientStart, clientEnd, { responseStatus: 200 }),
];
handle = startTracingSdk(config, recorder, {
exporter,
// A real collector drops its entries when stopped.
apiResources: { entries: () => entries, stop: () => { entries = []; } },
});
await handle.forceFlush();
const spans = exporter.getFinishedSpans();
const pages = spans.filter((span) => span.name === "page.load");
const childrenOf = (route: string) => {
const page = pages.find((span) => span.attributes["paperclip.page.route"] === route)!;
return spans.filter((span) => span.parentSpanContext?.spanId === page.spanContext().spanId).map((span) => span.attributes["paperclip.api.area"]);
};
expect(childrenOf("/:companyPrefix/dashboard")).toEqual(["companies"]);
expect(childrenOf("/:companyPrefix/issues")).toEqual(["issues"]);
});
it("keeps early entries for a navigation that started before the SDK loaded but commits after it", async () => {
const recorder = idleRecorder();
const flush = (recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames;
recorder.begin({ routeTemplate: "/:companyPrefix/dashboard", loadType: "hard", startTime: 0 });
flush();
// The user clicks (history change) just before the SDK finishes loading;
// the route commits after it.
const historyChange = performance.now();
let entries: PerformanceResourceTiming[] = [
resource(`${origin()}/api/companies`, 0.5, 1, { responseStatus: 200 }),
resource(`${origin()}/api/issues`, historyChange, historyChange + 5, { responseStatus: 200 }),
];
let stopped = false;
handle = startTracingSdk(config, recorder, {
exporter,
apiResources: { entries: () => entries, stop: () => { stopped = true; entries = []; } },
});
expect(stopped).toBe(false);
recorder.begin({ routeTemplate: "/:companyPrefix/issues", loadType: "client", startTime: historyChange });
flush();
await handle.forceFlush();
const spans = exporter.getFinishedSpans();
const childrenOf = (route: string) => {
const page = spans.find((span) => span.name === "page.load" && span.attributes["paperclip.page.route"] === route)!;
return spans.filter((span) => span.parentSpanContext?.spanId === page.spanContext().spanId).map((span) => span.attributes["paperclip.api.area"]);
};
expect(childrenOf("/:companyPrefix/dashboard")).toEqual(["companies"]);
expect(childrenOf("/:companyPrefix/issues")).toEqual(["issues"]);
// Released once a navigation that started after the SDK loaded begins.
recorder.begin({ routeTemplate: "/:companyPrefix/agents", loadType: "client", startTime: performance.now() + 1 });
expect(stopped).toBe(true);
});
it("releases early entries after the grace period when no later navigation happens", async () => {
const recorder = idleRecorder();
recorder.begin({ routeTemplate: "/", loadType: "hard", startTime: 0 });
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
let stopped = false;
handle = startTracingSdk(config, recorder, {
exporter,
apiResources: { entries: () => [], stop: () => { stopped = true; } },
earlyResourceGraceMs: 0,
});
expect(stopped).toBe(false);
await new Promise((resolve) => setTimeout(resolve, 10));
expect(stopped).toBe(true);
});
it("does not backfill requests that the live fetch instrumentation already traces", async () => {
const recorder = idleRecorder();
recorder.begin({ routeTemplate: "/", loadType: "hard", startTime: 0 });
const afterSdk = () => performance.now() + 1;
const entries: PerformanceResourceTiming[] = [];
handle = startTracingSdk(config, recorder, {
exporter,
apiResources: { entries: () => entries, stop: () => {} },
});
entries.push(resource(`${origin()}/api/issues`, afterSdk(), afterSdk() + 1));
(recorder as PageLoadRecorder & { flushFrames(): void }).flushFrames();
await handle.forceFlush();
expect(exporter.getFinishedSpans().map((span) => span.name)).toEqual(["page.load"]);
});
});
describe("browser tracing helpers", () => {
it("reports hidden, suspended, and view attributes on page.load", () => {
expect(pageLoadAttributes({
id: 1,
routeTemplate: "/:companyPrefix/issues",
loadType: "hard",
startTime: 0,
endTime: 30_000,
outcome: "timeout",
readySignal: null,
wasHidden: false,
suspended: true,
view: "mine",
})).toEqual({
"paperclip.page.route": "/:companyPrefix/issues",
"paperclip.page.load_type": "hard",
"paperclip.page.outcome": "timeout",
"paperclip.page.ready_signal": "none",
"paperclip.page.was_hidden": false,
"paperclip.page.suspended": true,
"paperclip.page.view": "mine",
});
});
it("ignores every URL outside this origin's API", () => {
const pattern = nonApiUrlPattern("https://acme.paperclip.app");
expect(pattern.test("https://acme.paperclip.app/api/issues")).toBe(false);
+88 -2
View File
@@ -13,8 +13,11 @@
// web_vital.lcp|inp|cls Core Web Vitals
// GET|POST|… same-origin `/api/` fetches, with W3C trace context
// so the server's request span joins the trace
// HTTP same-origin `/api/` requests made before this chunk
// loaded, rebuilt from Resource Timing under the
// page.load they belong to (no method, no server join)
import { context, propagation, trace, ROOT_CONTEXT, type Context, type Span } from "@opentelemetry/api";
import { context, propagation, trace, ROOT_CONTEXT, SpanKind, type Attributes, type Context, type Span } from "@opentelemetry/api";
import {
AlwaysOnSampler,
BatchSpanProcessor,
@@ -27,7 +30,7 @@ import { FetchInstrumentation } from "@opentelemetry/instrumentation-fetch";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { onCLS, onINP, onLCP, type Metric } from "web-vitals";
import type { BrowserTracingConfig } from "@paperclipai/shared";
import type { TracingSdkHandle } from "./controller";
import type { ApiResourceCollector, TracingSdkHandle } from "./controller";
import type { PageLoadMeasurement, PageLoadRecorder } from "./page-load-recorder";
import { OtlpFetchExporter } from "./otlp-fetch-exporter";
import { SanitizingSpanExporter } from "./span-sanitizer";
@@ -83,9 +86,46 @@ export function pageLoadAttributes(measurement: PageLoadMeasurement): Record<str
"paperclip.page.outcome": measurement.outcome ?? "interrupted",
"paperclip.page.ready_signal": measurement.readySignal ?? "none",
"paperclip.page.was_hidden": measurement.wasHidden,
...(measurement.suspended ? { "paperclip.page.suspended": true } : {}),
...(measurement.view !== null ? { "paperclip.page.view": measurement.view } : {}),
};
}
/** Span name for a request whose method is unknown (OpenTelemetry HTTP semantics). */
export const UNKNOWN_METHOD_SPAN_NAME = "HTTP";
/**
* Child spans for the `/api/` requests a page load made before the SDK
* loaded, from their Resource Timing entries: requests that started inside
* the load's window and before `before` (from then on the live fetch spans
* cover them). Windows do not overlap (an interrupted load ends where the
* next one starts), so each request becomes exactly one span. The URL goes into `url.full` only for the sanitizer, which
* turns it into `paperclip.api.area` and drops it, as for live fetch spans.
*/
function backfillApiSpans(
tracer: ReturnType<WebTracerProvider["getTracer"]>,
pageSpan: Span,
measurement: PageLoadMeasurement,
entries: readonly PerformanceResourceTiming[],
before: number,
) {
const windowEnd = Math.min(measurement.endTime ?? before, before);
const parent = trace.setSpan(ROOT_CONTEXT, pageSpan);
for (const entry of entries) {
if (entry.startTime < measurement.startTime || entry.startTime >= windowEnd) continue;
const attributes: Attributes = {
"url.full": entry.name,
"paperclip.api.timing_source": "resource_timing",
"paperclip.page.route": measurement.routeTemplate,
};
// Only where the browser exposes it (Chromium); never guessed.
const status = (entry as PerformanceResourceTiming & { responseStatus?: number }).responseStatus;
if (typeof status === "number" && status > 0) attributes["http.response.status_code"] = status;
const span = tracer.startSpan(UNKNOWN_METHOD_SPAN_NAME, { kind: SpanKind.CLIENT, startTime: entry.startTime, attributes }, parent);
span.end(Math.max(entry.startTime, entry.responseEnd));
}
}
/** Honeycomb weights each event by its `SampleRate` (1 in N). */
export function honeycombSampleRate(sampleRate: number): number | null {
return sampleRate >= 1 ? null : Math.max(1, Math.round(1 / sampleRate));
@@ -94,8 +134,19 @@ export function honeycombSampleRate(sampleRate: number): number | null {
export interface TracingSdkOptions {
/** Replaces the OTLP exporter (tests). Spans are still sanitized. */
exporter?: SpanExporter;
/** `/api/` requests recorded before the SDK loaded (`observeApiResources`). */
apiResources?: ApiResourceCollector;
/** Overrides `EARLY_RESOURCE_GRACE_MS` (tests). */
earlyResourceGraceMs?: number;
}
/**
* After this long, a navigation whose history change preceded the SDK has
* long since committed, so early entries no open measurement claims are
* released even if the user never navigates again.
*/
export const EARLY_RESOURCE_GRACE_MS = 60_000;
export function startTracingSdk(
config: BrowserTracingConfig,
recorder: PageLoadRecorder,
@@ -150,8 +201,30 @@ export function startTracingSdk(
enabled: false,
});
fetchInstrumentation.setTracerProvider(provider);
// Requests from here on get live fetch spans; earlier ones are backfilled.
const liveFetchSince = performance.now();
fetchInstrumentation.enable();
// Who may still claim the early Resource Timing entries: any measurement
// that started before `liveFetchSince` and has not ended, including one not
// yet begun (a navigation's start is its history change, which can precede
// the SDK while its route commits after it). Navigation starts only move
// forward, so once a measurement that started after `liveFetchSince` has
// begun, or the grace period has passed, no new claimant can appear; the
// entries are released when, in addition, no claimant is open.
const apiResources = options.apiResources ?? null;
const earlyOpen = new Set<number>();
let noNewEarlyClaimants = false;
const releaseIfUnclaimed = () => {
if (apiResources && noNewEarlyClaimants && earlyOpen.size === 0) apiResources.stop();
};
const graceTimer = apiResources
? window.setTimeout(() => {
noNewEarlyClaimants = true;
releaseIfUnclaimed();
}, options.earlyResourceGraceMs ?? EARLY_RESOURCE_GRACE_MS)
: undefined;
recorder.attachSink({
begin(measurement) {
const span = tracer.startSpan("page.load", {
@@ -164,6 +237,12 @@ export function startTracingSdk(
});
pageSpans.set(measurement.id, span);
if (measurement.endTime === null) openPageSpan = span;
if (measurement.startTime < liveFetchSince) {
earlyOpen.add(measurement.id);
} else {
noNewEarlyClaimants = true;
releaseIfUnclaimed();
}
},
end(measurement) {
const span = pageSpans.get(measurement.id);
@@ -172,7 +251,12 @@ export function startTracingSdk(
if (openPageSpan === span) openPageSpan = null;
span.setAttributes(pageLoadAttributes(measurement));
if (measurement.loadType === "hard") span.setAttributes(navigationTimingAttributes());
if (apiResources && measurement.startTime < liveFetchSince) {
backfillApiSpans(tracer, span, measurement, apiResources.entries(), liveFetchSince);
}
span.end(measurement.endTime ?? performance.now());
earlyOpen.delete(measurement.id);
releaseIfUnclaimed();
},
});
@@ -207,6 +291,8 @@ export function startTracingSdk(
pageSpans.clear();
openPageSpan = null;
fetchInstrumentation.disable();
window.clearTimeout(graceTimer);
apiResources?.stop();
await provider.shutdown().catch(() => undefined);
trace.disable();
context.disable();
@@ -16,6 +16,8 @@ export const ALLOWED_SPAN_ATTRIBUTES: ReadonlySet<string> = new Set([
"paperclip.page.outcome",
"paperclip.page.ready_signal",
"paperclip.page.was_hidden",
"paperclip.page.suspended",
"paperclip.page.view",
"paperclip.page.navigation_type",
"paperclip.page.ttfb_ms",
"paperclip.page.dom_content_loaded_ms",
@@ -24,6 +26,7 @@ export const ALLOWED_SPAN_ATTRIBUTES: ReadonlySet<string> = new Set([
"paperclip.web_vital.value",
"paperclip.web_vital.rating",
"paperclip.api.area",
"paperclip.api.timing_source",
"http.request.method",
"http.response.status_code",
"error.type",
+12 -4
View File
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import type { Issue, IssueBlockerAttention } from "@paperclipai/shared";
import {
resolveInboxIssueBlockerAttention,
resolveIssueLiveDescendantCount,
} from "./inbox-live-descendants";
import { resolveInboxIssueBlockerAttention, resolveIssueLiveDescendantCount, resolveIssueRunningDescendantCount } from "./inbox-live-descendants";
function makeIssue(overrides: Partial<Issue>): Issue {
return {
@@ -88,3 +85,14 @@ describe("inbox live descendant status helpers", () => {
).toBeNull();
});
});
describe("resolveIssueRunningDescendantCount", () => {
it("counts only started sub-tasks for the chip and keeps live coverage separate", () => {
const issue = { liveDescendantCount: 3, runningDescendantCount: 1 };
expect(resolveIssueRunningDescendantCount(issue, 0)).toBe(1);
expect(resolveIssueRunningDescendantCount(issue, 2)).toBe(2);
expect(resolveIssueLiveDescendantCount(issue, 0)).toBe(3);
// Older servers send only the live count.
expect(resolveIssueRunningDescendantCount({ liveDescendantCount: 2 }, 0)).toBe(2);
});
});
+11
View File
@@ -1,5 +1,16 @@
import type { Issue, IssueBlockerAttention } from "@paperclipai/shared";
/** The "n live below" chip: descendants whose run started (server count, else live count). */
export function resolveIssueRunningDescendantCount(
issue: Pick<Issue, "liveDescendantCount" | "runningDescendantCount">,
loadedSubtreeRunningCount = 0,
): number {
return Math.max(
normalizeLiveDescendantCount(issue.runningDescendantCount ?? issue.liveDescendantCount),
normalizeLiveDescendantCount(loadedSubtreeRunningCount),
);
}
type InboxLiveDescendantIssue = Pick<Issue, "status" | "blockerAttention" | "liveDescendantCount">;
interface InboxLiveDescendantOptions {
+28 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { LiveRunForIssue } from "../api/heartbeats";
import { collectLiveIssueIds, collectSubtreeLiveCounts } from "./liveIssueIds";
import { collectLiveIssueIds, collectSubtreeLiveCounts, issueWaitingOf } from "./liveIssueIds";
function liveRun(overrides: Partial<LiveRunForIssue>): LiveRunForIssue {
return {
@@ -204,3 +204,30 @@ describe("collectSubtreeLiveCounts", () => {
expect(counts.has("a")).toBe(false);
});
});
describe("issueWaitingOf", () => {
const queue = { agentId: "agent", agentName: "Codie", maxConcurrentRuns: 20, runningCount: 20, position: 41, queuedCount: 295 };
const waiting = (overrides: Partial<LiveRunForIssue>) => liveRun({ status: "queued", startedAt: null, ...overrides });
it("marks a task whose live runs have not started as waiting, with the agent's line", () => {
const ids = collectLiveIssueIds([
waiting({ id: "plain", issueId: "a" }),
waiting({ id: "line", issueId: "a", execution: { cause: "agent_at_capacity", agentQueue: queue } as LiveRunForIssue["execution"] }),
]);
expect(ids.has("a")).toBe(true);
expect(issueWaitingOf(ids, "a")).toEqual({ queue });
});
it("keeps a task with a started run live", () => {
const ids = collectLiveIssueIds([waiting({ id: "queued", issueId: "a" }), liveRun({ id: "running", issueId: "a" })]);
expect(issueWaitingOf(ids, "a")).toBeNull();
expect(issueWaitingOf(new Set(["a"]), "a")).toBeNull();
});
it("counts a waiting sub-task as live work, but not as running below", () => {
const ids = collectLiveIssueIds([waiting({ id: "queued", issueId: "child" })]);
const tree = [{ id: "parent", parentId: null }, { id: "child", parentId: "parent" }];
expect(collectSubtreeLiveCounts(tree, ids).get("parent")).toBe(1);
expect(collectSubtreeLiveCounts(tree, ids, { startedOnly: true }).size).toBe(0);
});
});
+30 -4
View File
@@ -1,4 +1,5 @@
import type { IssueStatus } from "@paperclipai/shared";
import type { ExecutionAgentQueue, IssueStatus } from "@paperclipai/shared";
import { agentQueueWaitOf, isWaitingToStart } from "./agent-queue-wait";
import type { LiveRunForIssue } from "../api/heartbeats";
function isLiveRunStatus(status: string): boolean {
@@ -58,18 +59,40 @@ function shouldReplaceIssueStatusSnapshot(
return !isTerminalIssueStatus(existing.status) && isTerminalIssueStatus(candidate.status);
}
/** A task whose live runs have all not started yet; `queue` names the agent's line when the server reports it. */
export interface IssueWaiting {
queue: ExecutionAgentQueue | null;
}
const waitingByIssueIds = new WeakMap<ReadonlySet<string>, ReadonlyMap<string, IssueWaiting>>();
export function collectLiveIssueIds(
liveRuns: readonly LiveRunForIssue[] | null | undefined,
issues?: readonly LiveIssueStatusNode[] | null,
): Set<string> {
const ids = new Set<string>();
const started = new Set<string>();
const waiting = new Map<string, IssueWaiting>();
const statusByIssueId = collectIssueStatusById(issues);
for (const run of liveRuns ?? []) {
if (run.issueId && isLiveIssueRun(run, statusByIssueId.get(run.issueId))) ids.add(run.issueId);
if (!run.issueId || !isLiveIssueRun(run, statusByIssueId.get(run.issueId))) continue;
ids.add(run.issueId);
if (!isWaitingToStart(run)) started.add(run.issueId);
else if (!waiting.get(run.issueId)?.queue) waiting.set(run.issueId, { queue: agentQueueWaitOf(run.execution) });
}
for (const issueId of started) waiting.delete(issueId);
waitingByIssueIds.set(ids, waiting);
return ids;
}
/** Whether a live task from {@link collectLiveIssueIds} is only waiting to start. */
export function issueWaitingOf(
liveIssueIds: ReadonlySet<string> | null | undefined,
issueId: string,
): IssueWaiting | null {
return liveIssueIds ? waitingByIssueIds.get(liveIssueIds)?.get(issueId) ?? null : null;
}
/**
* Minimal tree node shape needed to roll live descendants up to their ancestors.
* Both list and inbox issue objects satisfy this.
@@ -94,6 +117,7 @@ export interface SubtreeLiveNode {
export function collectSubtreeLiveCounts(
issues: readonly SubtreeLiveNode[] | null | undefined,
liveIssueIds: ReadonlySet<string>,
options: { startedOnly?: boolean } = {},
): Map<string, number> {
const counts = new Map<string, number>();
if (!issues || issues.length === 0 || liveIssueIds.size === 0) return counts;
@@ -102,8 +126,10 @@ export function collectSubtreeLiveCounts(
for (const issue of issues) parentById.set(issue.id, issue.parentId);
for (const liveId of liveIssueIds) {
// Only roll up live issues that belong to the loaded tree.
if (!parentById.has(liveId)) continue;
// Only roll up live issues that belong to the loaded tree. With
// `startedOnly`, a sub-task that only waits to start is not running below;
// it still counts as live work that covers a blocked parent.
if (!parentById.has(liveId) || (options.startedOnly && issueWaitingOf(liveIssueIds, liveId))) continue;
const seen = new Set<string>([liveId]);
let parentId = parentById.get(liveId) ?? null;
while (parentId && !seen.has(parentId)) {
+1
View File
@@ -59,6 +59,7 @@ export const queryKeys = {
activity: (endpointId: string) => ["chat-endpoints", endpointId, "activity"] as const,
},
tools: {
providerIcons: (companyId: string) => ["tools", companyId, "provider-icons"] as const,
aggregatorApps: (connectionId: string, userId: string | null) => ["tools", "aggregator-apps", connectionId, userId] as const,
composioApps: (connectionId: string) => ["tools", "composio-apps", connectionId] as const,
applications: (companyId: string) =>
+9 -1
View File
@@ -74,7 +74,15 @@ describe("humanizeSystemNotice", () => {
"Paperclip automatically retried dispatch, but it still has no live execution path. " +
"Moving it to `blocked` so it is visible for intervention.",
});
expect(result.title).toBe("Task paused — waiting on a recovery owner");
expect(result.title).toBe("Task could not continue");
});
it("humanizes the current recovery notice saved without a presentation title", () => {
const result = humanizeSystemNotice({
body: "Paperclip tried to continue this task again, but it still could not continue. "
+ "Press Retry to start it again from the saved work.",
});
expect(result).toEqual({ title: "Task could not continue", tone: "warning" });
});
it("falls back to System update plus a truncated first sentence", () => {
+3 -2
View File
@@ -74,12 +74,13 @@ export function humanizeSystemNotice(input: {
tone: presentationTone ?? "warning",
};
}
if (body.includes("no live execution path")) {
if (body.includes("no live execution path")
|| /^Paperclip tried to (?:start|continue) this task again\b/.test(body.trim())) {
const owner = recoveryOwnerName(body);
return {
title: owner
? `Task paused — waiting on ${owner}`
: "Task paused — waiting on a recovery owner",
: "Task could not continue",
tone: presentationTone ?? "warning",
};
}
+14 -8
View File
@@ -44,7 +44,7 @@ import {
normalizeIssueFilterState,
type IssueFilterState,
} from "../lib/issue-filters";
import { collectLiveIssueIds, collectSubtreeLiveCounts } from "../lib/liveIssueIds";
import { collectLiveIssueIds, collectSubtreeLiveCounts, issueWaitingOf } from "../lib/liveIssueIds";
import { formatAssigneeUserLabel } from "../lib/assignees";
import { buildCompanyUserLabelMap, buildCompanyUserProfileMap } from "../lib/company-members";
import {
@@ -64,7 +64,7 @@ import {
} from "../lib/keyboardShortcuts";
import {
resolveInboxIssueBlockerAttention,
resolveIssueLiveDescendantCount,
resolveIssueRunningDescendantCount,
} from "../lib/inbox-live-descendants";
import {
beginLocalInboxArchive,
@@ -416,7 +416,7 @@ export function FailedRunInboxRow({
confirm_owner_stop: "Confirm the previous server stopped",
confirm_run_stopped: "Confirm the previous run stopped",
}[interruption.userAction ?? "resume"]) : runFailureMessage(run);
const retryAvailable = !interruption || interruption.canRetry;
const retryAvailable = !interruption || (interruption.canRetry && interruption.retryAction !== "move_forward");
const showUnreadSlot = unreadState !== null;
const showUnreadDot = unreadState === "visible" || unreadState === "fading";
@@ -1822,7 +1822,7 @@ function StreamlinedInbox({
flatNavItemsRef.current = flatNavItems;
// Roll live descendant runs up to their ancestors across the loaded inbox tree
// so a parent that is not itself live can still surface "n live below".
const subtreeLiveCounts = useMemo(() => {
const subtreeCounts = useMemo(() => {
const nodes: { id: string; parentId: string | null }[] = [];
const seen = new Set<string>();
const pushIssue = (issue: Issue) => {
@@ -1838,8 +1838,12 @@ function StreamlinedInbox({
for (const child of children) pushIssue(child);
}
}
return collectSubtreeLiveCounts(nodes, liveIssueIds);
return {
live: collectSubtreeLiveCounts(nodes, liveIssueIds),
running: collectSubtreeLiveCounts(nodes, liveIssueIds, { startedOnly: true }),
};
}, [groupedSections, liveIssueIds]);
const subtreeLiveCounts = subtreeCounts.live;
const topFlatIndex = useMemo(() => {
const map = new Map<string, number>();
flatNavItems.forEach((entry, index) => {
@@ -3057,7 +3061,7 @@ function StreamlinedInbox({
originatingActor?.kind === "user" ? originatingActor.viaAgentId ?? null : null;
const isLive = liveIssueIds.has(issue.id);
const loadedSubtreeLiveCount = subtreeLiveCounts.get(issue.id) ?? 0;
const liveDescendantCount = resolveIssueLiveDescendantCount(issue, loadedSubtreeLiveCount);
const runningDescendantCount = resolveIssueRunningDescendantCount(issue, subtreeCounts.running.get(issue.id) ?? 0);
const blockerAttention = resolveInboxIssueBlockerAttention(issue, {
isLive,
loadedSubtreeLiveCount,
@@ -3108,7 +3112,8 @@ function StreamlinedInbox({
<InboxIssueMetaLeading
issue={issue}
isLive={isLive}
subtreeLiveCount={liveDescendantCount}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={runningDescendantCount}
showSubtreeLiveChip={showSubtreeLiveChip}
showStatus={false}
showIdentifier={false}
@@ -3140,7 +3145,8 @@ function StreamlinedInbox({
<InboxIssueMetaLeading
issue={issue}
isLive={isLive}
subtreeLiveCount={liveDescendantCount}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={runningDescendantCount}
showSubtreeLiveChip={showSubtreeLiveChip}
showStatus={showStatus}
showIdentifier={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
@@ -125,6 +125,7 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload {
enableWorkspaceDirtyQuarantineRepair: true,
enableOwnerInstanceAdmin: false,
enableSandboxDuplexBridge: false,
enableMcpTasks: false,
enableRunnerPreviewIngress: false,
enableWorktreeRunExecution: false,
worktreeRunExecutionActivatedAt: null,
@@ -414,6 +414,18 @@ export function InstanceExperimentalSettings() {
ariaLabel="Toggle decisions experimental setting"
/>
<ExperimentalToggleCard
title="Durable app actions (MCP Tasks)"
description="Let connected apps run long actions, such as CI runs or deploys, as tasks Paperclip keeps track of. If an action outlasts a call, a restart, or a deploy, the agent collects the result later and the work is never started twice."
footnote="Applies to apps that support MCP Tasks. Turning this off stops new tasks; apps then answer as before."
checked={experimentalQuery.data?.enableMcpTasks === true}
onCheckedChange={(checked) => toggleMutation.mutate({ enableMcpTasks: checked })}
disabled={toggleMutation.isPending}
settingKey="enableMcpTasks"
managed={managedKeys.enableMcpTasks}
ariaLabel="Toggle durable app actions experimental setting"
/>
<ExperimentalToggleCard
title="Enable Environments"
description="Show environment management in company settings and allow project and agent environment assignment controls."
+34 -6
View File
@@ -414,7 +414,10 @@ import {
type WorkspaceFileRef,
workspaceFileRefSchema,
isUuidLike,
type ExecutionAgentQueue,
} from "@paperclipai/shared";
import { AgentQueueWaitChip } from "@/components/AgentQueueWait";
import { agentQueueWaitOf, isWaitingToStart } from "@/lib/agent-queue-wait";
import { taskStatusIconProps } from "@/lib/task-status-presentation";
// Stable empty array for React Query `data` defaults. A literal `= []` default
@@ -521,6 +524,20 @@ export function shouldScrollIssueDetailToTopOnNavigation(input: {
return input.previousIssueId !== input.nextIssueId;
}
type LiveRunSummary = { count: number; waitingOnly: boolean; agentQueue: ExecutionAgentQueue | null };
const EMPTY_LIVE_RUN_SUMMARY: LiveRunSummary = { count: 0, waitingOnly: false, agentQueue: null };
function summarizeLiveRuns(
runs: ReadonlyArray<Pick<LiveRunForIssue | ActiveRunForIssue, "status" | "startedAt" | "execution">>,
): LiveRunSummary {
if (!runs.length) return EMPTY_LIVE_RUN_SUMMARY;
return {
count: runs.length,
waitingOnly: runs.every(run => isWaitingToStart(run)),
agentQueue: runs.map(run => agentQueueWaitOf(run.execution)).find(Boolean) ?? null,
};
}
function resolveInterruptibleIssueRun(
activeRun: ActiveRunForIssue | null | undefined,
liveRuns: readonly LiveRunForIssue[] | undefined,
@@ -3622,38 +3639,45 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
recordIssueDetailReadiness({ issue: !!loadedIssue, comments: !commentsLoading, interactions: !interactionsLoading, attachments: !attachmentsLoading, "work-products": !workProductsLoading });
}, [issueId, loadedIssue, commentsLoading, interactionsLoading, attachmentsLoading, workProductsLoading]);
const { data: liveRunCount = 0 } = useQuery<LiveRunForIssue[], Error, number>(
const { data: liveRunSummary = EMPTY_LIVE_RUN_SUMMARY } = useQuery<LiveRunForIssue[], Error, LiveRunSummary>(
{
queryKey: queryKeys.issues.liveRuns(issueId!),
queryFn: () => heartbeatsApi.liveRunsForIssue(issueId!),
enabled: !!issueId,
refetchInterval: (query) => liveRunRefetchInterval(hasLiveConnection, query.state, 3000),
select: (runs) => runs.length,
select: summarizeLiveRuns,
placeholderData: keepPreviousDataForSameQueryTail<LiveRunForIssue[]>(
issueId ?? "pending",
),
},
);
const { data: hasActiveRun = false } = useQuery<
const liveRunCount = liveRunSummary.count;
const { data: activeRunSummary = EMPTY_LIVE_RUN_SUMMARY } = useQuery<
ActiveRunForIssue | null,
Error,
boolean
LiveRunSummary
>({
queryKey: queryKeys.issues.activeRun(issueId!),
queryFn: () => heartbeatsApi.activeRunForIssue(issueId!),
enabled:
!!issueId && (!!issue?.executionRunId || issue?.status === "in_progress"),
refetchInterval: (query) => liveRunCount > 0 ? false : liveRunRefetchInterval(hasLiveConnection, query.state, 3000),
select: (run) => !!run,
select: (run) => summarizeLiveRuns(run ? [run] : []),
placeholderData: keepPreviousDataForSameQueryTail<ActiveRunForIssue | null>(
issueId ?? "pending",
),
});
const hasActiveRun = activeRunSummary.count > 0;
const resolvedHasActiveRun = issue
? shouldTrackIssueActiveRun(issue) && hasActiveRun
: hasActiveRun;
const hasLiveRuns = liveRunCount > 0 || resolvedHasActiveRun;
// Every live run is still waiting to start: say so instead of "Live".
const headerWaiting = hasLiveRuns
&& (liveRunCount === 0 || liveRunSummary.waitingOnly)
&& (!resolvedHasActiveRun || activeRunSummary.waitingOnly);
const headerAgentQueue = liveRunSummary.agentQueue ?? (resolvedHasActiveRun ? activeRunSummary.agentQueue : null);
useEffect(() => {
if (!hasLiveRuns && locallyQueuedCommentRunIds.size > 0) {
setLocallyQueuedCommentRunIds(new Map());
@@ -7738,7 +7762,11 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
{issue.identifier ?? issue.id.slice(0, 8)}
</span>
) : null}
{hasLiveRuns && (
{headerWaiting ? (
<span className="shrink-0" data-testid="issue-header-waiting">
<AgentQueueWaitChip queue={headerAgentQueue} />
</span>
) : hasLiveRuns && (
<Badge
variant="outline"
className={cn("gap-1.5 text-(length:--text-nano)", liveBlueBadge)}
+11 -6
View File
@@ -35,7 +35,7 @@ import {
countActiveIssueFilters,
type IssueFilterState,
} from "../lib/issue-filters";
import { collectLiveIssueIds, collectSubtreeLiveCounts } from "../lib/liveIssueIds";
import { collectLiveIssueIds, collectSubtreeLiveCounts, issueWaitingOf } from "../lib/liveIssueIds";
import { formatAssigneeUserLabel } from "../lib/assignees";
import { buildCompanyUserLabelMap, buildCompanyUserProfileMap } from "../lib/company-members";
import {
@@ -55,7 +55,7 @@ import {
} from "../lib/keyboardShortcuts";
import {
resolveInboxIssueBlockerAttention,
resolveIssueLiveDescendantCount,
resolveIssueRunningDescendantCount,
} from "../lib/inbox-live-descendants";
import {
beginLocalInboxArchive,
@@ -1538,7 +1538,7 @@ export function Inbox() {
flatNavItemsRef.current = flatNavItems;
// Roll live descendant runs up to their ancestors across the loaded inbox tree
// so a parent that is not itself live can still surface "n live below".
const subtreeLiveCounts = useMemo(() => {
const subtreeCounts = useMemo(() => {
const nodes: { id: string; parentId: string | null }[] = [];
const seen = new Set<string>();
const pushIssue = (issue: Issue) => {
@@ -1554,8 +1554,12 @@ export function Inbox() {
for (const child of children) pushIssue(child);
}
}
return collectSubtreeLiveCounts(nodes, liveIssueIds);
return {
live: collectSubtreeLiveCounts(nodes, liveIssueIds),
running: collectSubtreeLiveCounts(nodes, liveIssueIds, { startedOnly: true }),
};
}, [groupedSections, liveIssueIds]);
const subtreeLiveCounts = subtreeCounts.live;
const topFlatIndex = useMemo(() => {
const map = new Map<string, number>();
flatNavItems.forEach((entry, index) => {
@@ -2686,7 +2690,7 @@ export function Inbox() {
originatingActor?.kind === "user" ? originatingActor.viaAgentId ?? null : null;
const isLive = liveIssueIds.has(issue.id);
const loadedSubtreeLiveCount = subtreeLiveCounts.get(issue.id) ?? 0;
const liveDescendantCount = resolveIssueLiveDescendantCount(issue, loadedSubtreeLiveCount);
const runningDescendantCount = resolveIssueRunningDescendantCount(issue, subtreeCounts.running.get(issue.id) ?? 0);
const blockerAttention = resolveInboxIssueBlockerAttention(issue, {
isLive,
loadedSubtreeLiveCount,
@@ -2740,7 +2744,8 @@ export function Inbox() {
<InboxIssueMetaLeading
issue={issue}
isLive={isLive}
subtreeLiveCount={liveDescendantCount}
waiting={issueWaitingOf(liveIssueIds, issue.id)}
subtreeLiveCount={runningDescendantCount}
showSubtreeLiveChip={showSubtreeLiveChip}
showStatus={showStatus}
showIdentifier={visibleIssueColumnSet.has("id") && availableIssueColumnSet.has("id")}
+3 -1
View File
@@ -62,8 +62,10 @@ vi.mock("../components/AttentionQueueRow", () => ({
),
}));
const cardAt = new Date().toISOString();
function card(id: string, audience: AttentionItem["audience"]) {
const at = new Date().toISOString();
const at = cardAt;
return { id, sourceKind: "issue_thread_interaction", subject: { id: `${id}-interaction`, kind: "interaction", title: `Card ${id}`, metadata: {} },
audience, dismissal: null, dismissalKey: `attention:${id}`, changeFingerprint: `${id}.me`, closeModes: ["archive", "snooze"], obligationKey: null, obligationLeadId: null, activityAt: at, createdAt: at, updatedAt: at, inlineResolvable: false, decisionVerbs: [], queues: [], shelf: false,
severity: "medium", relatedIssue: null, project: null } as unknown as AttentionItem;
@@ -13,6 +13,12 @@ import { cn } from "@/lib/utils";
import { type InstallState } from "@/lib/tool-installs";
import { QuarantinedActionsReview } from "./SetupPanel";
import { ActionTestDialog } from "./ActionTestDialog";
import { ProviderToolIcon } from "@/components/ProviderToolIcon";
/** Action rows without a provider icon show none, as before. */
function NoIcon() {
return null;
}
import type { AccessDraft, AppDetailSectionProps } from "./types";
type ActionPermission = "off" | "ask" | "allowed";
@@ -493,6 +499,9 @@ function ActionRow({
>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
{action.icons?.length ? (
<ProviderToolIcon icons={action.icons} fallback={NoIcon} className="h-4 w-4 shrink-0" testId="app-action-icon" />
) : null}
<span className="text-sm font-medium text-foreground">{title}</span>
{/* PAP-659 C7: the gate is only as good as the classifier, so say
what each action was classified as. A misfiled tool is then one
@@ -0,0 +1,105 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import type { ExecutionAgentQueue, ExecutionProjection, Issue } from "@paperclipai/shared";
import { expect, within } from "storybook/test";
import { AgentQueueWait } from "@/components/AgentQueueWait";
import { InboxIssueMetaLeading } from "@/components/IssueColumns";
import { TaskChatLiveRunPill } from "@/components/task-chat/TaskChatLiveRunPill";
import { TaskChatRunnerHeader } from "@/components/task-chat/TaskChatRunnerTurn";
const codieQueue: ExecutionAgentQueue = {
agentId: "8f14e45f-ceea-467a-9575-6f1d0b2c9a01",
agentName: "Codie",
maxConcurrentRuns: 20,
runningCount: 20,
position: 41,
queuedCount: 295,
};
const waitingExecution: ExecutionProjection = {
canStop: true,
phase: "queued",
label: "Waiting for Codie",
cause: "agent_at_capacity",
lastConfirmedActivityAt: null,
retryAt: null,
attempt: 1,
maxAttempts: 3,
recoveryOwner: null,
nextAction: "Codie is running 20 of 20 tasks at once. This task is 41 of 295 in line and starts automatically when a slot frees.",
permittedActions: ["inspect_run"],
predecessorRunId: null,
successorRunId: null,
agentQueue: codieQueue,
};
const issue = {
id: "b6d1a4c2-6a43-4c55-9d0a-2f0d6f2b1c11",
identifier: "PAP-4281",
title: "Migrate billing exports",
status: "in_progress",
priority: "medium",
} as Issue;
const meta = {
id: "runs-agent-queue-wait",
title: "Agents and reusable capabilities/Runs, harnesses, and model accounts/Waiting for an agent slot",
component: AgentQueueWait,
parameters: { paperclip: {
capabilities: ["runs-adapters/runs", "tasks/discussion"],
status: "current",
implementation: "production",
boundary: "fixtures",
notes: "A queued run that never started because its agent's concurrency limit is full. The server's execution projection supplies the agent, limit and place in the dispatch line; these fixtures do not prove dispatch order.",
} },
decorators: [(Story) => <div className="mx-auto flex w-full max-w-2xl flex-col gap-4 p-4"><Story /></div>],
args: { queue: codieQueue },
} satisfies Meta<typeof AgentQueueWait>;
export default meta;
type Story = StoryObj<typeof meta>;
/** The full sentence: who it waits for, the limit, its place in line, and where to change the limit. */
export const WaitingInLine: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByText("Waiting for Codie")).toBeVisible();
await expect(canvas.getByText("20 slots max")).toBeVisible();
await expect(canvas.getByText("41 of 295 in line")).toBeVisible();
await expect(canvas.getByRole("link", { name: /Configure Codie/ })).toHaveAttribute("href", expect.stringMatching(/\/agents\/codie\/advanced$/));
},
};
/** The task chat's live turn: the waiting line replaces "Working" and its timer. */
export const InTaskChat: Story = {
render: () => <>
<TaskChatRunnerHeader agentName="Codie" status="queued" execution={waitingExecution} startedAtMs={Date.now() - 4 * 60 * 60_000}
statusContent={<TaskChatLiveRunPill status="queued" execution={waitingExecution} startedAtMs={Date.now() - 4 * 60 * 60_000} toolSummary={null} />} />
<TaskChatRunnerHeader agentName="Codie" status="queued" execution={waitingExecution} startedAtMs={Date.now() - 4 * 60 * 60_000} />
</>,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getAllByText("Waiting for Codie")).toHaveLength(2);
await expect(canvas.queryByText("Working")).not.toBeInTheDocument();
},
};
/** Task lists and the inbox: a quiet "Waiting" instead of a pulsing "Live". */
export const InTaskList: Story = {
render: () => <div className="flex items-center gap-2">
<InboxIssueMetaLeading issue={issue} isLive waiting={{ queue: codieQueue }} />
<span className="truncate text-sm">{issue.title}</span>
</div>,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByLabelText("Waiting for Codie · 20 slots max · 41 of 295 in line")).toBeVisible();
await expect(canvas.queryByText("Live")).not.toBeInTheDocument();
},
};
export const SingleSlot: Story = {
args: { queue: { ...codieQueue, maxConcurrentRuns: 1, runningCount: 1, position: 2, queuedCount: 3 } },
play: async ({ canvasElement }) => {
await expect(within(canvasElement).getByText("1 slot max")).toBeVisible();
},
};
export const Mobile: Story = { globals: { viewport: { value: "mobile", isRotated: false } } };
@@ -1,10 +1,11 @@
import { useState, type ReactNode } from "react";
import { useCallback, useRef, useState, type ReactNode } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { useQueryClient } from "@tanstack/react-query";
import type { McpAppCallToolResult } from "@paperclipai/shared";
import { McpAppIssueProvider } from "@/components/mcp-app/McpAppIssueContext";
import { McpAppTurnViews } from "@/components/mcp-app/McpAppTurnViews";
import { McpAppViewContent } from "@/components/mcp-app/McpAppView";
import { McpAppViewContent, type McpAppMessageProposal } from "@/components/mcp-app/McpAppView";
import type { McpAppDisplayMode } from "@/components/mcp-app/mcp-app-host";
import { queryKeys } from "@/lib/queryKeys";
import {
ISSUE_ID,
@@ -13,6 +14,9 @@ import {
MEETINGS_VIEW_SUMMARY,
RUN_ID,
} from "../../support/mcp-app/fixtures";
import { ProviderToolIconsStaticProvider } from "@/components/ProviderToolIcon";
import { TaskChatToolCard } from "@/components/task-chat/TaskChatToolCard";
import type { TaskChatToolItem } from "@/components/task-chat/task-chat-model";
function Frame({ children }: { children: ReactNode }) {
return <div className="mx-auto w-full max-w-(--tc-shell-max-w) p-6">{children}</div>;
@@ -91,3 +95,99 @@ export const Ready: Story = { name: "02 · View (Refresh calls a tool)", args: {
export const Loading: Story = { name: "03 · Loading", args: { state: "loading" } };
export const ErrorFallback: Story = { name: "04 · View unavailable", args: { state: "error" } };
export const ToolCallNeedsApproval: Story = { name: "05 · Tool call needs approval", args: { state: "tool-call-denied" } };
const PROPOSED_TEXT = "Summarize the action items from Paperclip <> Heavybit, Partner Meeting.";
/**
* A view's `ui/message`. The card starts with a proposal; the view's "Ask the
* agent" button proposes another once it is handled. Send only appends to the
* story's sent list: nothing is sent without the click.
*/
function MessageConfirmationStory() {
const [proposal, setProposal] = useState<McpAppMessageProposal | null>({ text: PROPOSED_TEXT, status: "pending" });
const [sent, setSent] = useState<string[]>([]);
const pending = useRef<{ resolve: () => void; reject: (error: Error) => void } | null>(null);
const proposeMessage = useCallback((text: string) => new Promise<void>((resolve, reject) => {
if (pending.current) {
reject(new Error("A message from this view is already waiting for the user"));
return;
}
pending.current = { resolve, reject };
setProposal({ text, status: "pending" });
}), []);
const settle = (send: boolean) => {
if (send && proposal) setSent((list) => [...list, proposal.text]);
if (send) pending.current?.resolve();
else pending.current?.reject(new Error("Message sending denied"));
pending.current = null;
setProposal(null);
};
return (
<Frame>
<McpAppViewContent
detail={MEETINGS_VIEW_DETAIL}
status="ready"
callTool={async () => refreshedResult}
displayName="Display meetings"
proposeMessage={proposeMessage}
proposal={proposal}
onSendProposal={() => settle(true)}
onDismissProposal={() => settle(false)}
/>
{sent.length > 0 ? (
<div className="mt-3 flex flex-col gap-1 text-sm text-foreground" data-testid="story-sent-messages">
{sent.map((text, index) => <p key={index}>You: {text}</p>)}
</div>
) : null}
</Frame>
);
}
/** The view full screen. "Exit full screen", Escape or the view's own button return it to the chat. */
function FullscreenStory() {
const [mode, setMode] = useState<McpAppDisplayMode>("fullscreen");
return (
<Frame>
<McpAppViewContent
detail={MEETINGS_VIEW_DETAIL}
status="ready"
callTool={async () => refreshedResult}
displayName="Display meetings"
displayMode={mode}
onDisplayModeChange={setMode}
/>
</Frame>
);
}
export const MessageConfirmation: Story = { name: "06 · View asks to send a message", render: () => <MessageConfirmationStory />, args: { state: "ready" } };
export const Fullscreen: Story = { name: "07 · Full screen", render: () => <FullscreenStory />, args: { state: "ready" } };
/* Provider tool icons (SEP-973) on task chat tool rows. */
const CIRCLEBACK_ICON = `data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7" fill="#6d28d9"/><circle cx="8" cy="8" r="3" fill="#fff"/></svg>')}`;
const ICON_ENTRIES = [
{ gatewayToolName: "mcp.circleback-1a2b3c4d:displaymeetings", icons: [{ src: CIRCLEBACK_ICON, mimeType: "image/svg+xml" }] },
{ gatewayToolName: "mcp.circleback-1a2b3c4d:searchmeetings", icons: [{ src: CIRCLEBACK_ICON, mimeType: "image/svg+xml" }] },
// An icon that fails to load falls back to the taxonomy icon.
{ gatewayToolName: "mcp.linear-5e6f7a8b:list-issues", icons: [{ src: "https://icons.invalid/linear.png", mimeType: "image/png" }] },
];
const ICON_ROWS: TaskChatToolItem[] = [
{ kind: "tool", id: "icon-1", name: "Search meetings", rawName: "mcp__paperclip__mcp.circleback-1a2b3c4d:searchmeetings", target: "Heavybit", status: "completed" },
{ kind: "tool", id: "icon-2", name: "Display meetings", rawName: "mcp__paperclip__mcp.circleback-1a2b3c4d:displaymeetings", status: "completed" },
{ kind: "tool", id: "icon-3", name: "List issues", rawName: "mcp__paperclip__mcp.linear-5e6f7a8b:list-issues", status: "completed" },
{ kind: "tool", id: "icon-4", name: "Bash", rawName: "Bash", target: "pnpm test", status: "completed" },
];
export const ProviderToolIcons: Story = {
name: "08 · Tool rows with provider icons",
render: () => (
<ProviderToolIconsStaticProvider entries={ICON_ENTRIES}>
<Frame>
<div className="flex flex-col gap-1">
{ICON_ROWS.map((item) => <TaskChatToolCard key={item.id} item={item} />)}
</div>
</Frame>
</ProviderToolIconsStaticProvider>
),
args: { state: "ready" },
};
+36 -3
View File
@@ -28,7 +28,7 @@ export const MEETING_CARDS_VIEW_HTML = String.raw`<!doctype html>
</head>
<body>
<div id="list"><div class="who">Waiting for the meeting list…</div></div>
<div class="actions"><button id="refresh" type="button">Refresh</button><span class="status" id="status"></span></div>
<div class="actions"><button id="refresh" type="button">Refresh</button> <button id="ask" type="button" hidden>Ask the agent</button> <button id="mode" type="button" hidden>Full screen</button><span class="status" id="status"></span></div>
<script>
let nextId = 1;
const pending = new Map();
@@ -38,8 +38,15 @@ export const MEETING_CARDS_VIEW_HTML = String.raw`<!doctype html>
return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
}
function notify(method, params) { parent.postMessage({ jsonrpc: "2.0", method, params }, "*"); }
let displayMode = "inline";
let capabilities = {};
let meetingNames = [];
function applyContext(context) {
if (!context) return;
if (context.displayMode) displayMode = context.displayMode;
const modeButton = document.getElementById("mode");
if (context.availableDisplayModes) modeButton.hidden = !context.availableDisplayModes.includes("fullscreen");
modeButton.textContent = displayMode === "fullscreen" ? "Back to chat" : "Full screen";
if (context.theme) document.documentElement.style.colorScheme = context.theme;
const vars = context.styles && context.styles.variables;
if (vars) for (const key of Object.keys(vars)) document.documentElement.style.setProperty(key, vars[key]);
@@ -62,6 +69,11 @@ export const MEETING_CARDS_VIEW_HTML = String.raw`<!doctype html>
list.appendChild(row);
}
if (!meetings.length) list.innerHTML = '<div class="who">No meetings</div>';
meetingNames = meetings.map((meeting) => meeting.name);
// Tell the agent what the user is looking at, where the host supports it.
if (capabilities.updateModelContext) {
request("ui/update-model-context", { content: [{ type: "text", text: "Meetings shown: " + meetingNames.join("; ") }], structuredContent: { meetingIds: meetings.map((meeting) => meeting.id) } }).catch(() => undefined);
}
reportSize();
}
function reportSize() { notify("ui/notifications/size-changed", { height: Math.ceil(document.body.getBoundingClientRect().height) }); }
@@ -89,8 +101,29 @@ export const MEETING_CARDS_VIEW_HTML = String.raw`<!doctype html>
}
reportSize();
});
request("ui/initialize", { protocolVersion: "2026-01-26", appCapabilities: { availableDisplayModes: ["inline"] }, clientInfo: { name: "meeting-cards-fixture", version: "1" } })
.then((result) => { applyContext(result.hostContext); notify("ui/notifications/initialized", {}); reportSize(); });
document.getElementById("ask").addEventListener("click", async () => {
const status = document.getElementById("status");
status.textContent = "Waiting for you to send it…";
try {
await request("ui/message", { role: "user", content: [{ type: "text", text: "Summarize the action items from " + (meetingNames[1] || meetingNames[0] || "my last meeting") + "." }] });
status.textContent = "Sent";
} catch (error) {
status.textContent = "Not sent";
}
reportSize();
});
document.getElementById("mode").addEventListener("click", async () => {
const result = await request("ui/request-display-mode", { mode: displayMode === "fullscreen" ? "inline" : "fullscreen" });
applyContext({ displayMode: result.mode });
});
request("ui/initialize", { protocolVersion: "2026-01-26", appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] }, clientInfo: { name: "meeting-cards-fixture", version: "1" } })
.then((result) => {
capabilities = result.hostCapabilities || {};
document.getElementById("ask").hidden = !capabilities.message;
applyContext(result.hostContext);
notify("ui/notifications/initialized", {});
reportSize();
});
</script>
</body>
</html>`;