Reconcile Pi prerequisites with the integrated runtime while holding admission

This commit is contained in:
Dotta committed 2026-10-08 15:01:33 -05:00
1 parent 20ce062701
commit f620e7157b
313 files changed
+13086 -2187

No files matched your search

@@ -12,7 +12,7 @@ import { CodexLocalConfigFields } from "./config-fields";
beforeAll(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); });
async function renderMarkup(node: ReactNode, expand?: string): Promise<string> {
async function renderMarkup(node: ReactNode, expand?: string, inspect?: (container: HTMLElement) => void): Promise<string> {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
@@ -20,13 +20,14 @@ async function renderMarkup(node: ReactNode, expand?: string): Promise<string> {
if (expand) await act(async () => {
container.querySelector(`[aria-label="${expand}"]`)?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
const html = document.body.innerHTML;
inspect?.(container);
const html = container.innerHTML + Array.from(document.body.children).filter(child => child !== container).map(child => child.outerHTML).join("");
await act(async () => root.unmount());
container.remove();
return html;
}
async function renderRunner(config: Record<string, unknown>, expand?: string, openAiDotEnabled = false): Promise<string> {
async function renderRunner(config: Record<string, unknown>, expand?: string, inspect?: (container: HTMLElement) => void): Promise<string> {
return renderMarkup(
<TooltipProvider>
<CodexLocalConfigFields
@@ -43,7 +44,7 @@ async function renderRunner(config: Record<string, unknown>, expand?: string, op
openAiDotEnabled={openAiDotEnabled}
/>
</TooltipProvider>,
expand,
expand, inspect,
);
}
@@ -96,7 +97,7 @@ describe("Paperclip Runner Codex configuration", () => {
expect(html).not.toContain("Ask for untrusted operations");
});
it("offers qualified Claude and keeps candidate ACP agents visibly disabled", async () => {
it("offers qualified Claude, Cursor and Pi while keeping Copilot disabled", async () => {
const html = await renderRunner({
provider: "acpx",
acpxAgent: "claude",
@@ -105,18 +106,40 @@ describe("Paperclip Runner Codex configuration", () => {
expect(html).toContain('ACP agents');
expect(html).toContain("ACP agent");
expect(html).toContain('aria-label="ACP agent"');
expect(html.match(/role="option"[^>]*data-disabled=""/g)).toHaveLength(2);
expect(html).toContain('Cursor');
expect(html).not.toContain('Cursor — qualification pending');
expect(html).toContain('GitHub Copilot — qualification pending');
expect(html).toContain('Pi — qualification pending');
const options = new DOMParser().parseFromString(html, "text/html").querySelectorAll('[role="option"]');
expect(Array.from(options, option => ({ label: option.textContent?.trim(), disabled: option.hasAttribute("data-disabled") })))
.toEqual(expect.arrayContaining([
{ label: "Claude", disabled: false }, { label: "Cursor", disabled: false },
{ label: "Pi", disabled: false }, { label: "GitHub Copilot — qualification pending", disabled: true },
]));
expect(html).not.toContain("Codex via ACPX");
expect(html).not.toContain("ACPX Codex");
expect(html).not.toContain("Pi via ACPX");
expect(html).toContain("Allow Paperclip reads");
});
it.each([undefined, "agent", "plan", "ask"])("displays saved Cursor mode %s", async acpxSessionMode => {
const selected = acpxSessionMode ?? "agent";
await renderRunner({ provider: "acpx", acpxAgent: "cursor", acpxSessionMode }, undefined, container => {
const modes = container.querySelectorAll('[aria-label="Cursor mode"]');
expect(modes).toHaveLength(1);
expect((modes[0] as HTMLSelectElement).value).toBe(selected);
});
});
it.each([undefined, "off", "low", "high", "max"])("displays saved Pi thinking level %s", async piThinkingLevel => {
await renderRunner({ provider: "acpx", acpxAgent: "pi", piThinkingLevel }, undefined, container => {
const mode = container.querySelector('[aria-label="Pi thinking level"]');
expect((mode as HTMLSelectElement).value).toBe(piThinkingLevel ?? "low");
});
});
it("shows unsupported saved Pi level without aliasing it", async () => {
expect(await renderRunner({ provider: "acpx", acpxAgent: "pi", piThinkingLevel: "medium" })).toContain("Unsupported saved thinking level");
});
it.each(["claude", "copilot", "pi"])("does not expose Cursor mode for %s", async acpxAgent => {
expect(await renderRunner({ provider: "acpx", acpxAgent })).not.toContain('aria-label="Cursor mode"');
});
it("falls back to the fail-closed Codex permission mode", async () => {
const html = await renderRunner({ codexPermissionMode: "unrestricted" });
+12 -15
View File
@@ -36,7 +36,6 @@ const instructionsFileHint =
"Absolute path to a markdown file (e.g. AGENTS.md) that defines this agent's behavior. Injected into the system prompt at runtime. Note: Codex may still auto-apply repo-scoped AGENTS.md files from the workspace.";
const defaultOpenCodeRunnerModel = "openrouter/deepseek/deepseek-v4-flash-0731";
const defaultAcpxClaudeModel = "claude-sonnet-5";
const defaultAcpxPiModel = "openrouter/deepseek/deepseek-v4-flash-0731";
const defaultClaudeManagedModel = "claude-sonnet-5";
const defaultAwsAgentCoreModel = "global.anthropic.claude-sonnet-4-6";
const runnerHarnessOptions = [
@@ -233,12 +232,14 @@ export function CodexLocalConfigFields({
...values!.adapterSchemaValues,
provider,
acpxSessionMode: undefined,
piThinkingLevel: undefined,
...(provider === "acpx" ? { acpxAgent: grok ? "grok" : "claude" } : {}),
},
});
} else {
mark("adapterConfig", "provider", provider);
mark("adapterConfig", "acpxSessionMode", undefined);
mark("adapterConfig", "piThinkingLevel", undefined);
mark("adapterConfig", "model", model);
if (provider === "openai_dot") {
mark("adapterConfig", "lifecycleMode", "per_turn");
@@ -274,16 +275,17 @@ export function CodexLocalConfigFields({
checked={runnerSchemaValue("allowUnmeteredProvider", false) === true} onChange={value => updateRunnerSchemaValue("allowUnmeteredProvider", value)} />
</>}
{runnerManaged && runnerProvider === "acpx" && runnerSchemaValue("acpxAgent", "claude") !== "grok" && (
<Field configSection="adapter" label="ACP agent" hint="Cursor uses Paperclip questions; per-run cost is unavailable. GitHub Copilot and Pi await qualification.">
<Field configSection="adapter" label="ACP agent" hint="Cursor uses Paperclip questions; per-run cost is unavailable. Pi accepts any provider/model ID. GitHub Copilot awaits qualification.">
<Select
value={String(isCreate ? values!.adapterSchemaValues?.acpxAgent ?? "claude" : eff("adapterConfig", "acpxAgent", config.acpxAgent ?? "claude"))}
onValueChange={(value) => {
const profile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(entry => entry.value === value);
const acpxSessionMode = profile?.value === "cursor" ? "agent" : undefined;
const piThinkingLevel = profile?.value === "pi" ? "low" : undefined;
if (!profile?.qualified) return;
if (isCreate) set!({ model: profile.value === "claude" ? defaultAcpxClaudeModel : "",
adapterSchemaValues: { ...values!.adapterSchemaValues, acpxAgent: profile.value, acpxSessionMode } });
else { mark("adapterConfig", "acpxAgent", profile.value); mark("adapterConfig", "acpxSessionMode", acpxSessionMode); mark("adapterConfig", "model", profile.value === "claude" ? defaultAcpxClaudeModel : ""); }
adapterSchemaValues: { ...values!.adapterSchemaValues, acpxAgent: profile.value, acpxSessionMode, piThinkingLevel } });
else { mark("adapterConfig", "acpxAgent", profile.value); mark("adapterConfig", "acpxSessionMode", acpxSessionMode); mark("adapterConfig", "piThinkingLevel", piThinkingLevel); mark("adapterConfig", "model", profile.value === "claude" ? defaultAcpxClaudeModel : ""); }
}}>
<SelectTrigger className="w-full" aria-label="ACP agent"><SelectValue /></SelectTrigger>
<SelectContent>
@@ -311,17 +313,12 @@ export function CodexLocalConfigFields({
</select>
</Field>
)}
{runnerManaged && runnerProvider === "acpx" && runnerSchemaValue("acpxAgent", "claude") === "cursor" && (
<Field configSection="adapter" label="Cursor mode" hint="Select Cursor's session mode. Permissions and company approval rules still apply.">
<select className={inputClass} aria-label="Cursor mode"
value={String(runnerSchemaValue("acpxSessionMode", "agent"))}
onChange={(event) => updateRunnerSchemaValue("acpxSessionMode", event.target.value)}>
{!["agent", "plan", "ask"].includes(String(runnerSchemaValue("acpxSessionMode", "agent"))) && (
<option value={String(runnerSchemaValue("acpxSessionMode", "agent"))} disabled>Unsupported saved mode — select Agent, Plan, or Ask</option>
)}
<option value="agent">Agent</option>
<option value="plan">Plan</option>
<option value="ask">Ask</option>
{runnerManaged && runnerProvider === "acpx" && runnerSchemaValue("acpxAgent", "claude") === "pi" && (
<Field configSection="adapter" label="Pi thinking level" hint="The runner verifies this exact level before each session can prompt. Changing it starts a new session.">
<select className={inputClass} aria-label="Pi thinking level" value={String(runnerSchemaValue("piThinkingLevel", "low"))}
onChange={(event) => updateRunnerSchemaValue("piThinkingLevel", event.target.value)}>
{!["off", "low", "high", "max"].includes(String(runnerSchemaValue("piThinkingLevel", "low"))) && <option value={String(runnerSchemaValue("piThinkingLevel", "low"))} disabled>Unsupported saved thinking level</option>}
<option value="off">Off</option><option value="low">Low</option><option value="high">High</option><option value="max">Max</option>
</select>
</Field>
)}
+10 -3
View File
@@ -24,7 +24,7 @@ async function renderMarkup(node: ReactNode, expand?: string): Promise<string> {
if (expand) await act(async () => {
container.querySelector(`[aria-label="${expand}"]`)?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
const html = container.innerHTML;
const html = container.innerHTML + Array.from(document.body.children).filter(child => child !== container).map(child => child.outerHTML).join("");
await act(async () => root.unmount());
container.remove();
return html;
@@ -35,6 +35,7 @@ async function renderSection(
adapterType: string,
section: AdapterConfigSection,
config: Record<string, unknown> = {},
expand?: string,
) {
return renderMarkup(
<TooltipProvider>
@@ -52,6 +53,7 @@ async function renderSection(
hideInstructionsFile
/>
</TooltipProvider>,
expand,
);
}
@@ -91,10 +93,15 @@ describe("adapter configuration sections", () => {
it("keeps ACP agent admission choices in the adapter section", async () => {
const config = { provider: "acpx", acpxAgent: "claude" };
const adapter = await renderSection(CodexLocalConfigFields, "paperclip_runner", "adapter", config);
const adapter = await renderSection(CodexLocalConfigFields, "paperclip_runner", "adapter", config, "ACP agent");
const policy = await renderSection(CodexLocalConfigFields, "paperclip_runner", "runPolicy", config);
expect(adapter).toContain('aria-label="ACP agent"');
const options = new DOMParser().parseFromString(adapter, "text/html").querySelectorAll('[role="option"]');
expect(Array.from(options, option => ({ label: option.textContent?.trim(), disabled: option.hasAttribute("data-disabled") })))
.toEqual(expect.arrayContaining([
{ label: "Claude", disabled: false }, { label: "Pi", disabled: false },
{ label: "Cursor", disabled: false }, { label: "GitHub Copilot — qualification pending", disabled: true },
]));
expect(adapter).not.toContain("Runner lifecycle");
expect(policy).toContain("Runner lifecycle");
expect(policy).not.toContain("ACP agent");
@@ -690,6 +690,9 @@ function parsePrpEvent(
const eventType = text(event.eventType);
const payload = record(event.payload);
if (isRunLogOnlyProviderEvent(eventType, payload)) return [];
const failure = piRuntimeFailureKey(event, payload);
if (failure !== null && failure === state.previousPiRuntimeFailure) return [];
state.previousPiRuntimeFailure = failure;
const family = eventType.startsWith("plan.") ? "plan"
: eventType.startsWith("tool.execution.") ? "tool_execution"
: eventType.startsWith("research.") ? "research"
+29
View File
@@ -912,6 +912,35 @@ describe("MarkdownEditor", () => {
});
});
it("handles Markdown paste once before the inner editor receives it", async () => {
const root = createRoot(container);
await act(async () => {
root.render(<MarkdownEditor value="" onChange={() => {}} />);
});
await flush();
const editable = container.querySelector('[data-testid="mdx-editor"]')!;
const innerPaste = vi.fn();
editable.addEventListener("paste", innerPaste);
const pasted = '```json\n{"content":"nonce\\n"}\n```';
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { types: ["text/plain"], getData: () => pasted },
});
await act(async () => { editable.dispatchEvent(event); });
expect(event.defaultPrevented).toBe(true);
expect(mdxEditorMockState.insertedMarkdownValues).toEqual([pasted]);
expect(innerPaste).not.toHaveBeenCalled();
const plain = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(plain, "clipboardData", {
value: { types: ["text/plain"], getData: () => "ordinary text" },
});
await act(async () => { editable.dispatchEvent(plain); });
expect(plain.defaultPrevented).toBe(false);
expect(innerPaste).toHaveBeenCalledOnce();
await act(async () => { root.unmount(); });
});
it("escapes angle brackets in pasted markdown", async () => {
const root = createRoot(container);
+3
View File
@@ -1284,6 +1284,9 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
if (!looksLikeMarkdownPaste(rawText)) return;
event.preventDefault();
// Lexical also handles paste on the editable element. Once Markdown is
// inserted here, prevent that handler from inserting the plain text again.
event.stopPropagation();
ref.current.insertMarkdown(escapeUnsupportedAngleBrackets(normalizeMarkdown(rawText)));
}, []);
+29
View File
@@ -2186,6 +2186,35 @@ describe("TaskChatThread runtime transcript selection", () => {
);
});
it("keeps a pending native permission answerable after same-turn steering", async () => {
const runId = "native-pending-steered";
nativeTranscriptState.transcriptByRun.set(runId, [
{ kind: "runtime_request", ts: "2026-08-25T18:00:01.000Z", requestId: "permission-1",
requestKind: "permission_approval", turnId: "provider-turn-1", requestType: "permission", status: "pending",
prompt: "Pi write", choices: [{ key: "decline", label: "Deny" }], fields: [] },
{ kind: "assistant", ts: "2026-08-25T18:00:03.000Z", text: "Steering acknowledged.", channel: "progress" },
]);
const resolve = vi.spyOn(heartbeatsApi, "resolveRuntimeRequest").mockResolvedValue({} as never);
render(<TaskChatThread comments={[{
id: "pending-steering-comment", companyId: "company-1", issueId: "issue-1", authorType: "user",
authorAgentId: null, authorUserId: "user-1", body: "Change course.", presentation: null, metadata: null,
runId: null, consumedByRunId: runId, steeredIntoRunId: runId,
conversationAnchorAt: new Date("2026-08-25T18:00:02.000Z"),
createdAt: new Date("2026-08-25T18:00:02.000Z"), updatedAt: new Date("2026-08-25T18:00:02.000Z"),
}]} onAdd={async () => {}} issueStatus="in_progress" activeRun={{
id: runId, runtimeMode: "native", status: "running", invocationSource: "issue", triggerDetail: null,
startedAt: "2026-08-25T18:00:00.000Z", finishedAt: null, createdAt: "2026-08-25T18:00:00.000Z",
agentId: "agent-1", agentName: "Runner", adapterType: "paperclip_runner",
}} />);
const deny = Array.from(container.querySelectorAll<HTMLButtonElement>("button")).filter(button => button.textContent === "Deny");
expect(deny).toHaveLength(1);
expect(deny[0].disabled).toBe(false);
expect(container.textContent).not.toContain("Cancelled");
await act(async () => deny[0].click());
expect(resolve).toHaveBeenCalledWith({ runId, requestId: "permission-1", turnId: "provider-turn-1",
requestKind: "permission_approval", resolution: { action: "decline" } });
});
it("labels the live tail as a continuation after the steering bubble", () => {
nativeTranscriptState.transcriptByRun.set("native-live-steered", [
{
+21 -9
View File
@@ -55,6 +55,8 @@ import {
settledRunChildren,
splitTranscriptAtAnchors,
transcriptToTaskChatItems,
runtimeRequestSegmentContext,
reconcileSegmentRuntimeRequests,
type SettledTurnMergeMeta,
} from "@/components/task-chat/transcript-adapter";
import { TaskChatDescriptionBubble } from "@/components/task-chat/TaskChatDescriptionBubble";
@@ -1868,12 +1870,15 @@ export function TaskChatThread(props: TaskChatThreadProps) {
startSlotMs,
timelineAnchors,
);
const runtimeRequests = runtimeRequestSegmentContext(entries, {
runId: source.id, agentName: meta?.agentName, running: false,
});
const projectedSegments = segments.map((segment) => {
const parsedTranscript = transcriptToTaskChatItems(segment.entries, {
const parsedTranscript = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems(segment.entries, {
runId: source.id,
agentName: meta?.agentName,
running: false,
});
}), segment.entries, runtimeRequests);
const parsed =
source.id === planDocumentSourceRunId && planTurnItem
? embedPlanDocumentAtWriteBoundary(parsedTranscript, planTurnItem)
@@ -2016,13 +2021,16 @@ export function TaskChatThread(props: TaskChatThreadProps) {
startSlotMs,
timelineAnchors,
);
const runtimeRequests = runtimeRequestSegmentContext(entries, {
runId: liveRun.id, agentName: liveRun.agentName, running: true,
});
for (const [segmentIndex, segment] of segments.slice(0, -1).entries()) {
if (segment.entries.length === 0) continue;
const parsedTranscript = transcriptToTaskChatItems(segment.entries, {
const parsedTranscript = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems(segment.entries, {
runId: liveRun.id,
agentName: liveRun.agentName,
running: false,
});
}), segment.entries, runtimeRequests);
const parsed =
liveRun.id === planDocumentSourceRunId && planTurnItem
? embedPlanDocumentAtWriteBoundary(parsedTranscript, planTurnItem)
@@ -2251,7 +2259,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
// A fresh array is produced on every render. Track every presentation field
// that can change without changing the entry count or text length so channel,
// lifecycle, result status, and usage-only updates invalidate the projection.
const tailEntryContentKey = tailEntries.reduce((key, entry) => {
const tailEntryContentKey = tailAllEntries.reduce((key, entry) => {
const textIdentity = "text" in entry ? entry.text : "";
const contentIdentity = "content" in entry ? entry.content : "";
const channelIdentity = "channel" in entry ? (entry.channel ?? "") : "";
@@ -2263,8 +2271,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
entry.kind === "result"
? `${entry.subtype}:${entry.inputTokens}:${entry.outputTokens}:${entry.cachedTokens}:${entry.costUsd}`
: "";
return `${key}|${entry.kind}:${channelIdentity}:${lifecycleIdentity}:${statusIdentity}:${usageIdentity}:${textIdentity}:${contentIdentity}`;
}, String(tailEntries.length));
const requestIdentity = entry.kind === "runtime_request" ? JSON.stringify(entry) : "";
return `${key}|${entry.kind}:${channelIdentity}:${lifecycleIdentity}:${statusIdentity}:${usageIdentity}:${textIdentity}:${contentIdentity}:${requestIdentity}`;
}, String(tailAllEntries.length));
const tailContentKey = `${tailSegmentStartMs ?? "run-start"}:${tailEntryContentKey}`;
const blockerContentKey = blockerLinks
? `${blockerLinks.directBlocker.id}:${blockerLinks.ultimateBlocker?.id ?? ""}`
@@ -2341,11 +2350,14 @@ export function TaskChatThread(props: TaskChatThreadProps) {
const tailItems = useMemo(
() => {
if (!tailRunId) return [];
const parsed = transcriptToTaskChatItems(tailEntries, {
const runtimeRequests = runtimeRequestSegmentContext(tailAllEntries, {
runId: tailRunId, agentName: tailAgentName, running: tailStreaming,
});
const parsed = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems(tailEntries, {
runId: tailRunId,
agentName: tailAgentName,
running: tailStreaming,
});
}), tailEntries, runtimeRequests, tailStreaming);
return tailPlanItem
? embedPlanDocumentAtWriteBoundary(parsed, tailPlanItem)
: parsed;
@@ -231,4 +231,22 @@ describe("TaskChatProtocolActivityRow", () => {
expect(row?.querySelector("details")).toBeNull();
expect(row?.querySelector('[aria-expanded]')).toBeNull();
});
it.each([
["info", "informational", "Provider update", "lucide-info"],
["warning", "informational", "Warning", "lucide-triangle-alert"],
["error", "failed", "Error", "lucide-triangle-alert"],
["error", "informational", "Error", "lucide-triangle-alert"],
["info", "failed", "Error", "lucide-triangle-alert"],
] as const)("renders %s/%s notice severity without hiding its summary", (severity, status, label, icon) => {
const summary = "Pi estimates this turn at $0.000617. Billing cost is unverified.";
render({
id: "notice", kind: "protocol", surface: "provider_activity", family: "provider_notice",
eventType: "provider.notice.recorded", status, title: "Provider notice", summary,
details: [{ label: "Severity", value: severity }], steps: [], links: [], children: [],
});
expect(container.textContent).toContain(label);
expect(container.querySelector("p")?.textContent).toBe(summary);
expect(container.querySelector('[data-testid="task-chat-protocol-activity-icon"]')?.classList.contains(icon)).toBe(true);
});
});
@@ -1,6 +1,5 @@
import { useId, useState, type ReactNode } from "react";
import {
AlertTriangle,
Check,
ChevronRight,
Circle,
@@ -23,6 +22,7 @@ import {
protocolActivityIsRunning,
protocolActivityLabel,
protocolActivityPresentation,
providerNoticeSeverity,
} from "./task-chat-activity-presentation";
const COMPACT_RESEARCH_RESULT_LIMIT = 5;
@@ -281,14 +281,16 @@ export function TaskChatProtocolActivityRow({ item }: { item: TaskChatProtocolIt
const presentation = protocolActivityPresentation(item);
if (!presentation) return null;
if (item.surface === "provider_activity" && item.family === "provider_notice") {
const NoticeIcon = presentation.icon;
const severity = providerNoticeSeverity(item);
const summary = item.summary
?? item.details.find((entry) => entry.label === "Summary")?.value
?? "The provider reported a notice without a message.";
return (
<div className="flex min-w-0 flex-col gap-1.5 py-1 text-xs" data-testid="task-chat-protocol-activity-row" data-activity-family="provider_notice">
<div className="flex items-center gap-2 text-muted-foreground">
<AlertTriangle className="h-3.5 w-3.5 shrink-0" aria-hidden data-testid="task-chat-protocol-activity-icon" />
<span className="font-medium">{item.status === "failed" ? "Error" : item.details.find(detail => detail.label === "Severity")?.value === "info" ? "Provider update" : "Warning"}</span>
<NoticeIcon className="h-3.5 w-3.5 shrink-0" aria-hidden data-testid="task-chat-protocol-activity-icon" />
<span className="font-medium">{severity === "error" ? "Error" : severity === "info" ? "Provider update" : "Warning"}</span>
</div>
<p className="min-w-0 whitespace-pre-wrap break-words text-foreground">{summary}</p>
{item.details.some(detail => detail.label !== "Summary") ? (
@@ -1,3 +1,4 @@
import { AlertTriangle, Info } from "lucide-react";
import { describe, expect, it } from "vitest";
import { completedActivitySummary } from "./completed-activity-summary";
import type {
@@ -141,4 +142,48 @@ describe("completedActivitySummary", () => {
completedActivitySummary([tool("mcp__github__get_pull_request")]).label,
).toBe("Used connected tools");
});
it("shows the preserved pricing estimate as informational, not a billing receipt", () => {
const summary = "Pi estimates this turn at $0.000617 from its model prices. Billing cost is unverified.";
expect(completedActivitySummary([{
...provider("provider_notice", "informational"), summary,
details: [{ label: "Severity", value: "info" }],
}])).toEqual({ label: summary, fullLabel: summary, icon: Info });
});
it.each(["warning", "error", undefined])("retains warning/error icons and safe notice text (%s)", (severity) => {
const summary = "Provider request needs attention.";
const result = completedActivitySummary([{
...provider("provider_notice", severity === "error" ? "failed" : "informational"),
details: [
{ label: "Summary", value: summary },
...(severity ? [{ label: "Severity", value: severity }] : []),
],
}]);
expect(result).toEqual({ label: summary, fullLabel: summary, icon: AlertTriangle });
});
it("uses a generic fallback without promoting arbitrary detail fields", () => {
expect(completedActivitySummary([{
...provider("provider_notice", "informational"), summary: " ",
details: [{ label: "Raw input", value: "private-command-or-path" }],
}]).label).toBe("Received a provider update");
});
it("does not hide a failed notice behind informational metadata", () => {
expect(completedActivitySummary([{
...provider("provider_notice", "failed"), summary: "Provider failed.",
details: [{ label: "Severity", value: "info" }],
}]).icon).toBe(AlertTriangle);
});
it("groups distinct notices and keeps a later error visible beside actual work", () => {
const notices = ["info", "info", "warning", "error"].map((severity, index) => ({
...provider("provider_notice", "informational"),
id: `notice-${index}`,
summary: `Distinct provider message ${index}`,
details: [{ label: "Severity", value: severity }],
}));
const result = completedActivitySummary([tool("bash"), ...notices]);
expect(result.label).toBe("Provider error reported, ran commands");
expect(result.fullLabel).toBe(result.label);
expect(result.label).not.toContain("Distinct provider message");
});
});
@@ -5,7 +5,7 @@ import {
type ToolFamily,
type ToolIcon,
} from "./tool-taxonomy";
import { protocolActivityPresentation } from "./task-chat-activity-presentation";
import { protocolActivityPresentation, providerNoticeSeverity } from "./task-chat-activity-presentation";
type Activity = TaskChatActivityPhaseItem["items"][number];
const labels: Record<ToolFamily, string> = {
@@ -42,6 +42,12 @@ export function completedActivitySummary(items: Activity[]) {
completed: boolean;
order: number;
}> = [];
const notices: Array<{
summary: string | undefined;
severity: "info" | "warning" | "error";
icon: ToolIcon;
order: number;
}> = [];
for (const [order, item] of items.entries()) {
if (item.kind === "tool") {
const p = toolActivityPresentation({
@@ -67,6 +73,13 @@ export function completedActivitySummary(items: Activity[]) {
} else {
const p = protocolActivityPresentation(item);
if (!p) continue;
if (item.surface === "provider_activity" && item.family === "provider_notice") {
// Reuse only the normalized notice text already available in the row.
const summary = item.summary?.trim()
|| item.details.find((entry) => entry.label === "Summary")?.value.trim();
notices.push({ summary, severity: providerNoticeSeverity(item), icon: p.icon, order });
continue;
}
const family =
item.surface === "provider_activity" ? item.family : item.surface;
const label =
@@ -84,7 +97,6 @@ export function completedActivitySummary(items: Activity[]) {
safety: "Reviewed safety",
terminal: "Ran commands",
wait: "Waited",
provider_notice: "Received a provider update",
workspace_change: "Worked on files",
workspace_file: "Referenced files",
resource: "Added resources",
@@ -94,6 +106,21 @@ export function completedActivitySummary(items: Activity[]) {
}
}
}
if (notices.length) {
const strongest = notices.find((notice) => notice.severity === "error")
?? notices.find((notice) => notice.severity === "warning")
?? notices[0]!;
const label = notices.length === 1
? strongest.summary || "Received a provider update"
: strongest.severity === "error"
? "Provider error reported"
: strongest.severity === "warning"
? "Provider warning reported"
: "Received provider updates";
// One notice category leaves room for actual work. Keep warnings and errors
// visible when the compact label truncates other activity categories.
add(label, strongest.icon, strongest.severity === "info" ? notices[0]!.order : -1);
}
const completedFamilies = new Set(
tools.filter((tool) => tool.completed).map((tool) => tool.family),
);
@@ -9,6 +9,7 @@ import {
FilePenLine,
FileText,
GitBranch,
Info,
ListChecks,
PackageCheck,
Search,
@@ -40,6 +41,12 @@ export interface TaskChatActivityPresentation {
detail?: string;
}
export function providerNoticeSeverity(item: TaskChatProviderActivityItem): "info" | "warning" | "error" {
const severity = item.details.find((entry) => entry.label === "Severity")?.value;
if (item.status === "failed" || severity === "error") return "error";
return severity === "info" ? "info" : "warning";
}
function providerDetail(item: TaskChatProviderActivityItem, ...labels: string[]): string | undefined {
return item.details.find((entry) => labels.includes(entry.label))?.value;
}
@@ -135,7 +142,7 @@ export function providerActivityPresentation(item: TaskChatProviderActivityItem)
case "wait":
return { icon: Clock3, runningLabel: "Waiting", completedLabel: "Finished waiting", failedLabel: "Wait failed", interruptedLabel: "Wait stopped", detail };
case "provider_notice":
return { icon: AlertTriangle, runningLabel: "Provider notice", completedLabel: "Provider notice", failedLabel: "Provider error", interruptedLabel: "Provider notice", detail };
return { icon: providerNoticeSeverity(item) === "info" ? Info : AlertTriangle, runningLabel: "Provider notice", completedLabel: "Provider notice", failedLabel: "Provider error", interruptedLabel: "Provider notice", detail };
}
}
@@ -24,6 +24,8 @@ import {
splitTranscriptAtAnchors,
toolDisplayName,
transcriptToTaskChatItems,
runtimeRequestSegmentContext,
reconcileSegmentRuntimeRequests,
type SettledTurnMergeMeta,
type ThreadBackboneEntry,
} from "./transcript-adapter";
@@ -32,11 +34,43 @@ import type {
TaskChatPlanDocumentItem,
TaskChatTurnItem,
} from "./task-chat-model";
import { latestPendingRuntimeRequest } from "./task-chat-model";
import { providerActivityPresentation } from "./task-chat-activity-presentation";
import { nativeRunEventsToTranscript } from "../transcript/native-run-events";
const TS = "2026-07-31T12:00:00.000Z";
describe("runtime requests across steering sections", () => {
it("selects the newer request when an older pending permission crosses steering", () => {
const older: TranscriptEntry = { kind: "runtime_request", ts: TS, requestId: "older-permission",
requestKind: "permission_approval", turnId: "provider-turn", requestType: "permission", status: "pending",
prompt: "Earlier write", choices: [{ key: "decline", label: "Deny" }], fields: [] };
const newer: TranscriptEntry = { ...older, ts: "2026-07-31T12:00:02.000Z", requestId: "newer-permission", prompt: "Later write" };
const options = { runId: "run-steering", running: true };
const context = runtimeRequestSegmentContext([older, newer], options);
const tail = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems([newer], options), [newer], context, true);
expect(tail.map(item => item.id)).toEqual(["run-steering:runtime-request:older-permission", "run-steering:runtime-request:newer-permission"]);
expect(latestPendingRuntimeRequest(tail)?.requestId).toBe("newer-permission");
});
it.each(["pending", "resolved", "cancelled"] as const)("keeps one %s permission under whole-run authority", status => {
const request: TranscriptEntry = { kind: "runtime_request", ts: TS, requestId: "permission-1",
requestKind: "permission_approval", turnId: "provider-turn", requestType: "permission", status: "pending",
prompt: "Pi write", choices: [{ key: "decline", label: "Deny" }], fields: [] };
const after: TranscriptEntry[] = [{ kind: "assistant", ts: "2026-07-31T12:00:01.000Z", text: "Continued.", channel: "progress" }];
if (status === "resolved") after.push({ ...request, ts: "2026-07-31T12:00:02.000Z", status, resolvedAction: "decline" });
const entries = [request, ...after];
const options = { runId: "run-steering", running: status !== "cancelled" };
const context = runtimeRequestSegmentContext(entries, options);
const history = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems([request], { ...options, running: false }), [request], context);
const tail = reconcileSegmentRuntimeRequests(transcriptToTaskChatItems(after, options), after, context, options.running);
const cards = [...history, ...tail].filter(item => item.kind === "protocol" && item.surface === "runtime_request");
expect(cards).toEqual([expect.objectContaining({ requestId: "permission-1", turnId: "provider-turn", status })]);
expect(history.filter(item => item.kind === "protocol")).toHaveLength(status === "pending" ? 0 : 1);
expect(tail.filter(item => item.kind === "protocol")).toHaveLength(status === "pending" ? 1 : 0);
});
});
describe("accepted native response-wake answers", () => {
const runId = "native-response-wake";
const summary =
@@ -20,6 +20,7 @@ import type {
TaskChatRunResultItem,
TaskChatMessageItem,
TaskChatPlanDocumentItem,
TaskChatRuntimeRequestItem,
} from "./task-chat-model";
import {
humanizeToolName,
@@ -570,6 +571,52 @@ interface TranscriptAdapterOptions {
running: boolean;
}
/** Request authority follows the whole run, even when steering splits its display. */
export function runtimeRequestSegmentContext(
entries: readonly TranscriptEntry[],
options: TranscriptAdapterOptions,
) {
const requests = entries.filter(entry => entry.kind === "runtime_request");
const origins = new Map<string, TranscriptEntry>();
for (const entry of requests) {
if (!origins.has(entry.requestId)) origins.set(entry.requestId, entry);
}
const context = new Map<string, { item: TaskChatRuntimeRequestItem; origin: TranscriptEntry }>();
for (const item of transcriptToTaskChatItems(requests, options)) {
if (item.kind === "protocol" && item.surface === "runtime_request") {
context.set(item.id, { item, origin: origins.get(item.requestId)! });
}
}
return context;
}
/** Carry live requests to the tail; retain closed cards at their original position. */
export function reconcileSegmentRuntimeRequests(
items: readonly TaskChatItem[],
entries: readonly TranscriptEntry[],
context: ReturnType<typeof runtimeRequestSegmentContext>,
carryPending = false,
): TaskChatItem[] {
const owned = new Set(entries);
const retained = new Set<string>();
const result = items.flatMap<TaskChatItem>(item => {
if (item.kind !== "protocol" || item.surface !== "runtime_request") return [item];
const state = context.get(item.id);
if (!state || (state.item.status === "pending" ? !carryPending : !owned.has(state.origin))) return [];
retained.add(item.id);
return [state.item];
});
const carried: TaskChatItem[] = [];
if (carryPending) {
for (const { item } of context.values()) {
if (item.status === "pending" && !retained.has(item.id)) carried.push(item);
}
}
// A carried request predates this section. Keep newer requests last so the
// composer selects the latest input instead of reviving an older one.
return [...carried, ...result];
}
/**
* Reduce a transcript into ordered items, coalescing consecutive thinking and
* assistant deltas and threading tool_result/diff onto their tool_call. Mirrors
@@ -73,4 +73,3 @@ export function StepHeader({
</div>
);
}
+5 -1
View File
@@ -770,7 +770,11 @@ describe("CompanyEnvironments — test provider button", () => {
// bindings even when the environment has none yet.
"company-1",
);
expect(getEnvironmentFormPage()).toBeNull();
// Saving awaits query invalidation before navigating away. A single flush
// can observe the API call before that asynchronous success path settles.
await waitForAssertion(() => {
expect(getEnvironmentFormPage()).toBeNull();
});
});
it("confirms before cancelling the edit page with unsaved environment variable drafts", async () => {