feat: integrate Pi 1.0 into the experimental Runner (#14921)

## Thinking Path

> - Paperclip manages AI agents and their work.
> - The experimental Runner owns provider processes and durable
sessions.
> - Pi needs working task execution and human controls.
> - The five-PR stack must preserve changes already on master.
> - Each layer now carries the complete integrated source for a safe
sequential fallback.
> - This PR belongs to native GitHub stack #15602, ending at #14956.

## Linked Issues or Issue Description

Refs #14436, #14631, #14743 and #14956.

Ship Pi 1.0 through the experimental Paperclip Runner. The five PRs are
#14921, #14922, #14923, #14924 and #14956. The user authorized the
complete merge after checks pass. Existing `pi_local` execution is
unchanged. Accounting and wider provider/platform qualification remain
deferred.

## What Changed

- Recover missing final replies after workspace finalization changes
owners, using accepted-turn evidence without rerunning work or granting
external-chat publication.
- Preserve the admitted Pi instruction root across warm runs, while
retaining changed-root rejection.
- Give Pi a bounded 15-second default shutdown grace so stop, drain
acknowledgement and durable suspension can complete. Explicit deadlines
and other providers retain their existing behavior.
- Integrate the Pi 1.0 runtime and master contracts.
- Use Pi profile 22. Preserve explicit caller-selected models and exact
native thinking levels. Keep Pi's wrapper, helper, extension and
question/control behavior unchanged from the qualified profile-19
runtime.
- Preserve master's Dot lifecycle and consent fields, configured task
environment, status guards and current Codex/Claude dependency versions.
Cursor stays qualified. Copilot stays pending; profile 17 binds the
changed shared protocol validation sources.
- Exclude general AWS IAM credentials from Pi static/custom provider
bindings and selected task projections; preserve the provider-scoped
Bedrock bearer key. Profile 21 is retained as historical provenance.
Rust and cloud install probes use the current declaration.
- Patch bundled brace-expansion 5.0.9 to the exact official 5.0.12
payload. Pin the patch and complete runtime closures. Include the patch
in normal installed setup tooling. Keep the upstream Pi shrinkwrap as
provenance and permit only this exact security correction.
- Include current attestation files in the Docker build context. Keep
the repository lockfile unchanged from master. CI and private image
builds resolve manifest changes before their frozen installation.

## Verification

- Full local `pnpm -r typecheck` passes, including Runner Rust, server
and UI. Focused integration checks pass: 194 Runner
admission/environment tests, 63 profile/credential tests with one
expected skip, 152 Dot/UI configuration tests, and Pi transcript/notice
tests.
- Full local `pnpm build` passes on the final source.
- Fresh final-source checks pass: all 698 Rust workspace tests (32
binaries), 156 credential/profile/controller tests with one expected
skip, Runner TypeScript typecheck, and 20 package/setup/sandbox tests.
- The profile-21 Pi materializer passes on the native host with the
official pinned Node 24.21.0 and its npm. It verifies all 150 locked
packages, the patched dependency and the exact closure. Setup/package
bundle tests and UI token gates pass.
- The old hashes were reproduced for all three supported targets before
calculating the patched graph. New closure hashes are darwin-arm64
`282022db10150c6632b3444df421342e7d534bdf5d5fb1097a2e79d0625a2bcf`,
darwin-x64
`64e251e19009f755c0b04f73ce2138246faab71a961b0f13d75ebfcc34bef12e`, and
linux-x64
`713b1fdff42fb56a1518bdc084f181d70bee8ebadc3e4b1d76321ed9108c8410`.
Independent native platform execution is separate from graph identity
reproduction.
- Historical cloud qualification remains unchanged: all seven core cases
pass on shipping source `10dc43c9ec65d88c2f782d62afb296d09494f215`,
harness `1a4408a48cfb5a1f094a311141c257c92cd7a893`, image
`sha256:5b3a775b383591bda1b0c1889e509acc70ce7f37c53f09733c81d59037f02280`,
and accepted Sonnet 4.6/low fixture. All 215 canonical files and all
seven cleanup checks pass independent verification. These are profile-19
results and are not relabeled as fresh profile-22 runs.
- Current Pi digest:
`sha256:e92078bee3c23bec4100aa589013a44613d054cd686826534025d8019e9f39a9`.
[The readiness
plan](https://github.com/paperclipai/paperclip/blob/codex/pi-production-readiness/doc/plans/2026-10-02-pi-production-readiness.md)
preserves campaign and failed-attempt provenance.
- Merge only after every PR's current-head CI and fresh review pass.
Linux CI covers the full suites, build and browser tests. The local
embedded Postgres API-authority suite cannot start on this macOS/Node 26
host, so Linux CI must confirm that suite.

### Fresh profile-22 core qualification — 2026-10-08

All seven accepted core cases pass canonically on Pi profile 22, with
`openrouter/anthropic/claude-sonnet-4.6` and native-confirmed low
thinking. This model is a fixture; production accepts the caller's
explicit Pi provider/model.

Runtime/install source: `3241a992f2a7703e59e97ed0fd3e5d6405de4401`.
Frozen accepted harness: `1a4408a48cfb5a1f094a311141c257c92cd7a893`.
Immutable cloud image:
`ghcr.io/paperclipai/paperclip-daytona-runner@sha256:506f22db7edd78f37c0c40bec1cc084af1850455026dbf467194bfbb8fcef141`.
Pi digest:
`sha256:e92078bee3c23bec4100aa589013a44613d054cd686826534025d8019e9f39a9`.

[Hosted Linux image and clean-install
verification](https://github.com/paperclipai/paperclip/actions/runs/37868328023)
passes, including all 20 source-bound archives, normal CLI/Pi setup,
companion import and the production pack reader. This exact installation
source includes the latest master integration and the corrected Pi warm
instruction-root fence. Full local typecheck/build and current-head
hosted CI verify the final stack. All 13 focused real-root regressions
pass. The full local executor suite passed 662 tests; 15 database tests
could not start the Mac embedded PostgreSQL service. Hosted Linux CI
passes the full required verification and E2E checks. These fresh
results keep their own source identity; profile-19 results remain
historical.

| Core path | Canonical campaign | Retained archive SHA-256 |
| --- | --- | --- |
| File edit, validation, download and Done |
`pi-core22-replyfix-0-1791511228` | 23 files;
`a473e8603a3dd4737863291f8d3d1e392391f0b16d433c3e0e0e9d8baf7a97b0` |
| Pending question and controller restart |
`pi-core22-replyfix-1-1791511376` | 33 files;
`6b829c4eb74e1f32a89c692a4ae7130dbfc1c6d3cf13915effe2103d9e242c8e` |
| Three-turn session/process/workspace continuity |
`pi-core22-replyfix-2-1791511587` | 23 files;
`7a87021f8f9a3fdd3c58bb4467f8d82c635e3ea4795d6e75f144d9aa14818df8` |
| Four typed questions and browser reconnects |
`pi-core22-replyfix-3-1791511881` | 42 files;
`9e31755252be1f4f9cb0626c984c142d4d1ae5f5bee3a7af08444db8d12c280a` |
| Plan approval and completion | `pi-core22-replyfix-4-1791512031` | 22
files;
`a0383ce1aab38e7b5a25ce0e9dd3bebea5c037ebd96ae6b29dae19015da2ae2c` |
| Same-turn steering and permission denial |
`pi-core22-replyfix-5-1791512261` | 39 files;
`c929b8c7070f0b66aedc17e65ca46e6beab1e363926ac9f7e2a75fb250f05949` |
| Stop during pending permission | `pi-core22-replyfix-6-1791512390` |
33 files;
`7f0a58ae0f4d5bfc76149435f4e322537089c5bd16e7ffe9b5ad71f10a621a07` |

All 215 canonical files (28714587 bytes) are independently
hash-verified. All seven cleanup grades pass, with no owned runtime
process or temporary root after each case. Automatic retries are zero.
The owned cloud host stopped normally after retention. The prior
profile-22 warm attempt remains failed and separately retained: archive
SHA-256
`1e54eba5ec72b50cee1534b23d1d1d4f21a090006b8a64501ba70db972abfde5`. Its
original canonical classification is preserved. Diagnosis reproduced a
product bug comparing an agent-files root against an unset
checkpoint-only field. The fix stores the admitted physical root
separately from the adopted per-run collection capability. The real-root
regression fails before the fix and passes afterward, including
rejection of a changed physical root. Fixture, grader, model and all
seven accepted case IDs are unchanged; this fresh campaign tests
final-reply publication after file registration first. The intermediate
restart attempt also remains failed and retained: archive SHA-256
`5dcaefdf1d17cf4cd54fd4cf810f45e736667392339b8ce7caf08bb4e225277f`. Its
original canonical classification is preserved. Pi resumed, wrote the
verified answer and completed its task; exact runner suspension was
proven, but idle stop consumed about 5.2s and left under 3s for the
drain acknowledgement. The Pi-only default shutdown grace is now 15s,
preserving a full 5s drain round trip and a finite suspension reserve.
Explicit caller deadlines, other provider defaults, literal drain
receipts and exact suspension identity checks remain unchanged. The
timing regression fails before this correction and passes afterward; all
18 focused settlement tests and Runner typecheck pass. The final-source
file attempt is also preserved as failed (`candidate_failure`), archive
SHA-256
`db6767b6773ea618997927ac77bdb005a5ac81492c7b9c0ffbc900449f829bc9`.
Native edit, validation, exact downloadable artifact and Done/succeeded
all passed, and the exact final reply was durably recorded. A workspace
recovery owner completed before the live heartbeat reached presentation,
leaving that reply absent from task chat. Recovery now materializes only
a completed final reply from the accepted turn of an ordinary internal
Done task, preserving issue/run/contract binding, suppression,
external-chat authorization and same-run deduplication. The database
regression covers the generated file-preparation receipt, suppression,
unapproved external continuation and replay. Server typecheck and all 49
response-selection tests pass; hosted Linux verifies the database
regression because embedded PostgreSQL cannot start on this Mac.

The delayed-final-answer database regression passes on [the final
root-source Linux server
shard](https://github.com/paperclipai/paperclip/actions/runs/37868262553/job/113628594152),
alongside 1,108 passing tests. The first root Runner shard had one
unchanged durable-resume test exceed its 5-second timeout; the identical
top-source shard and the isolated exact test passed. One rerun of that
failed job and its required aggregate passed without source or test
changes. The original failed job log and the single-rerun receipt remain
retained.

### October 9 merge verification

Current merge head: `5a8fe63512a7166aaef5cf50065a25008aa8b44b`. All
current-head checks pass, including `ci / verify` and `ci / e2e`;
exact-head Greptile review is 5/5 with no unresolved threads. Current
master conflicts are resolved. The user authorized the maintainer
override of the code-owner review gate after these checks. The seven
retained live core cases remain bound to source
`3241a992f2a7703e59e97ed0fd3e5d6405de4401` and its recorded cloud image.

## Risks

- The security correction changes the dependency closure and profile
identity. Old sessions must reopen on the new profile. Exact identities
and credential bindings fail closed.
- The runner remains experimental and requires explicit selection.
Legacy Pi Local is unchanged. Caller model IDs pass through; the E2E
model is a fixture.
- Accounting and the broad platform/provider matrix remain deferred.
This merge does not publish a release or deploy a service.

## Model Used

OpenAI GPT-6 through Codex assisted with reasoning, repository
inspection, editing and tool use. The exact serving ID and context
window are not exposed in this session. Final live qualification uses Pi
1.0.0 with `openrouter/anthropic/claude-sonnet-4.6` and native-confirmed
low thinking.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-09 08:56:41 -05:00
1 parent 4fb1ab53a8
commit 57e977be72
517 files changed
+61737 -1440

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,16 @@ 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, inspectOrDot?: ((container: HTMLElement) => void) | boolean): Promise<string> {
const openAiDotEnabled = inspectOrDot === true;
const inspect = typeof inspectOrDot === "function" ? inspectOrDot : undefined;
return renderMarkup(
<TooltipProvider>
<CodexLocalConfigFields
@@ -43,7 +46,7 @@ async function renderRunner(config: Record<string, unknown>, expand?: string, op
openAiDotEnabled={openAiDotEnabled}
/>
</TooltipProvider>,
expand,
expand, inspect,
);
}
@@ -96,7 +99,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 +108,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" });
+15 -3
View File
@@ -232,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");
@@ -273,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>
@@ -310,6 +313,15 @@ export function CodexLocalConfigFields({
</select>
</Field>
)}
{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>
)}
{runnerManaged && runnerProvider === "claude_managed" && (
<>
<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");
+85 -24
View File
@@ -1,32 +1,93 @@
import { describe, expect, it } from "vitest";
import { paperclipRunnerUIAdapter } from "./index";
import { createPiProfileExtensionAdapter, PI_NOTICE_METHOD } from "../../../../packages/paperclip-runner/src/drivers/acpx/pi-extension-adapter";
import { transcriptToTaskChatItems } from "../../components/task-chat/transcript-adapter";
const piFailure = (overrides: Record<string, unknown> = {}, eventOverrides: Record<string, unknown> = {}) => ({
type: "paperclip.prp.event",
event: {
runId: "run-1", turnId: "turn-1", normalizedSessionId: "session-1",
eventType: "provider.notice.recorded",
payload: {
schema: "paperclip.provider.notice.v1", noticeId: "notice-1", category: "pi.runtime_failure",
severity: "error", summary: "Pi process exited with code 4", scope: "session",
recoverable: false, userActionable: false,
details: [{ name: "source.method", value: PI_NOTICE_METHOD },
{ name: "source.nativeEvent", value: "runtime_failure" }, { name: "source.sessionId", value: "session-1" },
{ name: "reason", value: "native_process_exited" }],
...overrides,
},
...eventOverrides,
},
});
describe("paperclip runner transcript projection", () => {
it("omits unrelated provider diagnostics and legacy notices from streaming chat", () => {
it("keeps both pinned Pi failure facts while rendering one consecutive diagnostic", async () => {
const adapter = createPiProfileExtensionAdapter({ workspacePath: "/fixture", sessionId: "session-1", turnId: "turn-1" });
const notice = { sessionId: "session-1", category: "runtime_failure", severity: "error",
summary: "Pi process exited with code 4", details: { reason: "native_process_exited" } };
const raw = [...await adapter.notification(PI_NOTICE_METHOD, notice),
...await adapter.notification(PI_NOTICE_METHOD, structuredClone(notice))];
expect(raw).toHaveLength(2);
expect(raw[0]!.payload.noticeId).not.toBe(raw[1]!.payload.noticeId);
const before = structuredClone(raw);
const parse = paperclipRunnerUIAdapter.createStdoutParser!().parseLine;
const event = (eventType: string, payload: Record<string, unknown>) => parse(JSON.stringify({
type: "paperclip.prp.event",
event: { eventType, payload },
}), "2026-10-02T12:00:00.000Z");
const legacyNotice = {
schema: "paperclip.provider.notice.v1",
severity: "warning",
category: "warning",
summary: "ignored unrelated provider information",
userActionable: true,
};
expect(event("harness.diagnostic", { code: "codex_unrelated_information" })).toEqual([]);
expect(event("provider.notice.recorded", legacyNotice)).toEqual([]);
expect(event("provider.notice.recorded", { ...legacyNotice, summary: "Repository is not trusted" }))
.toEqual([expect.objectContaining({ family: "provider_notice" })]);
expect(event("provider.notice.recorded", { ...legacyNotice, severity: "error" }))
.toEqual([expect.objectContaining({ family: "provider_notice" })]);
expect(event("provider.notice.recorded", { ...legacyNotice, category: "configWarning" }))
.toEqual([expect.objectContaining({ family: "provider_notice" })]);
expect(event("harness.diagnostic", { code: "provider_identity_failure", message: "Thread mismatch" }))
.toEqual([expect.objectContaining({ kind: "system", text: "Runner: Thread mismatch" })]);
expect(event("item.completed", { kind: "agentMessage", channel: "final", text: "Here is the answer." }))
.toEqual([expect.objectContaining({ kind: "assistant", text: "Here is the answer." })]);
const entries = raw.flatMap(event => parse(JSON.stringify({ type: "paperclip.prp.event", event: {
runId: "run-1", normalizedSessionId: "session-1", turnId: "turn-1", ...event,
} }), "2026-10-03T07:00:00.000Z"));
expect(entries).toHaveLength(1);
expect(transcriptToTaskChatItems(entries, { runId: "run-1", agentName: "Pi", running: false }))
.toEqual([expect.objectContaining({ kind: "protocol", family: "provider_notice",
details: expect.arrayContaining([{ label: "Severity", value: "error", mono: false }]) })]);
expect(raw).toEqual(before);
});
it("preserves different failure details, severity, authority and run/turn/session scope", () => {
const changed = [
piFailure({ summary: "Provider request failed" }),
piFailure({ severity: "warning" }),
piFailure({ recoverable: true }),
piFailure({ userActionable: true }),
piFailure({ details: piFailure().event.payload.details.map(detail => detail.name === "reason"
? { ...detail, value: "provider_http_429" } : detail) }),
piFailure({ details: piFailure().event.payload.details.map(detail => detail.name === "source.sessionId"
? { ...detail, value: "session-2" } : detail) }),
piFailure({}, { runId: "run-2" }),
piFailure({}, { turnId: "turn-2" }),
piFailure({}, { normalizedSessionId: "session-2" }),
piFailure({}, { runId: undefined }),
piFailure({}, { turnId: undefined }),
];
for (const event of changed) {
const parse = paperclipRunnerUIAdapter.createStdoutParser!().parseLine;
expect(parse(JSON.stringify(piFailure()), "first")).toHaveLength(1);
expect(parse(JSON.stringify(event), "second")).toHaveLength(1);
}
});
it("starts a new diagnostic after retry activity, another event, or parser reset", () => {
const parser = paperclipRunnerUIAdapter.createStdoutParser!();
const parse = (event: unknown) => parser.parseLine(JSON.stringify(event), "2026-10-03T07:00:00.000Z");
expect(parse(piFailure())).toHaveLength(1);
expect(parse(piFailure({ noticeId: "notice-2" }))).toEqual([]);
for (const intervening of [piFailure({ category: "pi.auto_retry_start" }),
piFailure({}, { eventType: "item.delta", payload: { kind: "agentMessage", text: "Retrying" } }),
{ type: "other" }]) {
parse(intervening);
expect(parse(piFailure())).toHaveLength(1);
}
parser.reset();
expect(parse(piFailure())).toHaveLength(1);
});
it("never coalesces other providers or unscoped/unsupported notices", () => {
for (const event of [piFailure({ category: "other.runtime_failure" }),
piFailure({ details: [] }), piFailure({}, { normalizedSessionId: undefined }),
piFailure({}, { runId: undefined }), piFailure({}, { turnId: undefined })]) {
const parse = paperclipRunnerUIAdapter.createStdoutParser!().parseLine;
expect(parse(JSON.stringify(event), "first")).toHaveLength(1);
expect(parse(JSON.stringify(event), "second")).toHaveLength(1);
}
});
it("renders committed PRP semantic tool items with the existing chat parts", () => {
+29 -2
View File
@@ -14,6 +14,7 @@ interface PaperclipRunnerParserState {
itemChannels: Map<string, "progress" | "final" | "summary" | "detail" | "unknown">;
structuredFinalItemIds: Set<string>;
runtimeRequests: Map<string, Extract<TranscriptEntry, { kind: "runtime_request" }>>;
previousPiRuntimeFailure: string | null;
}
function itemChannel(payload: JsonRecord): "progress" | "final" | "summary" | "detail" | "unknown" {
@@ -665,6 +666,22 @@ function semanticToolEntries(eventType: string, payload: JsonRecord, ts: string)
}];
}
function piRuntimeFailureKey(event: JsonRecord, payload: JsonRecord): string | null {
// The frozen Pi projection emits both process-exit and prompt-rejection
// facts. Coalesce their identical consecutive display rows, retaining the
// original PRP log and requiring the complete run/turn/session binding.
if (event.eventType !== "provider.notice.recorded"
|| payload.schema !== "paperclip.provider.notice.v1"
|| payload.category !== "pi.runtime_failure"
|| !text(event.runId) || !text(event.turnId) || !text(event.normalizedSessionId)) return null;
const details = Array.isArray(payload.details) ? payload.details.map(record) : [];
if (!details.some(detail => detail.name === "source.method" && detail.value === "paperclip/pi_notice")
|| !details.some(detail => detail.name === "source.nativeEvent" && detail.value === "runtime_failure")
|| !details.some(detail => detail.name === "source.sessionId" && text(detail.value))) return null;
const { noticeId: _noticeId, ...notice } = payload;
return JSON.stringify([event.runId, event.turnId, event.normalizedSessionId, notice]);
}
function parsePrpEvent(
event: JsonRecord,
ts: string,
@@ -673,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"
@@ -770,6 +790,7 @@ function createParserState(): PaperclipRunnerParserState {
itemChannels: new Map(),
structuredFinalItemIds: new Set(),
runtimeRequests: new Map(),
previousPiRuntimeFailure: null,
};
}
@@ -778,12 +799,18 @@ function parsePaperclipRunnerLine(line: string, ts: string, state: PaperclipRunn
try {
parsed = JSON.parse(line);
} catch {
state.previousPiRuntimeFailure = null;
return parseCodexStdoutLine(line, ts);
}
const envelope = record(parsed);
if (envelope.type !== "paperclip.prp.event") return parseCodexStdoutLine(line, ts);
if (envelope.type !== "paperclip.prp.event") {
state.previousPiRuntimeFailure = null;
return parseCodexStdoutLine(line, ts);
}
const event = record(envelope.event);
return Object.keys(event).length > 0 ? parsePrpEvent(event, ts, state) : [];
if (Object.keys(event).length > 0) return parsePrpEvent(event, ts, state);
state.previousPiRuntimeFailure = null;
return [];
}
export function parsePaperclipRunnerStdoutLine(line: string, ts: string): TranscriptEntry[] {
@@ -63,6 +63,15 @@ const connectionIntentsApiMocks = vi.hoisted(() => ({
decline: vi.fn(),
}));
const routerMocks = vi.hoisted(() => ({
searchParams: new URLSearchParams(),
readSearchParams: vi.fn(),
setSearchParams: vi.fn(),
navigate: vi.fn(),
setBreadcrumbs: vi.fn(),
pushToast: vi.fn(),
}));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
@@ -80,13 +89,38 @@ async function act(callback: () => void | Promise<void>) {
}
vi.mock("@/lib/router", () => ({
useParams: () => ({}),
useSearchParams: () => {
routerMocks.readSearchParams();
return [routerMocks.searchParams, routerMocks.setSearchParams];
},
useNavigate: () => routerMocks.navigate,
Link: ({ to, children, className }: { to: string; children: ReactNode; className?: string }) => (
<a href={to} className={className}>{children}</a>
),
}));
vi.mock("@/context/CompanyContext", async (importOriginal) => ({
...await importOriginal<typeof import("../context/CompanyContext")>(),
useCompany: () => ({ selectedCompanyId: issueThreadInteractionFixtureMeta.companyId, selectedCompany: null }),
}));
vi.mock("@/context/BreadcrumbContext", async (importOriginal) => ({
...await importOriginal<typeof import("../context/BreadcrumbContext")>(),
useBreadcrumbs: () => ({ setBreadcrumbs: routerMocks.setBreadcrumbs }),
}));
vi.mock("@/context/ToastContext", async (importOriginal) => ({
...await importOriginal<typeof import("../context/ToastContext")>(),
useToast: () => ({ pushToast: routerMocks.pushToast }),
}));
vi.mock("@/api/connection-intents", () => ({ connectionIntentsApi: connectionIntentsApiMocks }));
vi.mock("./task-chat/TaskChatRichInput", () => ({
TaskChatRichInput: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => (
<textarea aria-label="Canonical answer" value={value} onChange={(event) => onChange(event.target.value)} />
),
}));
function renderCard(
props: Partial<ComponentProps<typeof IssueThreadInteractionCard>> = {},
) {
@@ -122,9 +156,54 @@ afterEach(() => {
container?.remove();
root = null;
container = null;
localStorage.clear();
routerMocks.readSearchParams.mockClear();
});
describe("IssueThreadInteractionCard", () => {
const canonicalDraftInteraction = {
...pendingAskUserQuestionsInteraction,
payload: {
...pendingAskUserQuestionsInteraction.payload,
questions: [{ id: "draft", prompt: "Edit draft", required: true, selectionMode: "single" as const, options: [{ id: "draft_text", label: "Write an answer", freeText: true }], allowOther: false }],
questionSet: {
schema: "paperclip.question_set.v1" as const,
questions: [{ id: "draft", prompt: "Edit draft", required: true, answerMode: "text" as const, initialText: " Provider draft\n漢字\\n " }],
},
},
};
async function editCanonical(host: HTMLDivElement, value: string) {
const textarea = host.querySelector<HTMLTextAreaElement>("textarea")!;
await act(() => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(textarea, value);
textarea.dispatchEvent(new Event("input", { bubbles: true }));
});
}
it("presents canonical drafts and submits only explicitly edited exact text", async () => {
const submit = vi.fn();
const host = renderCard({ interaction: canonicalDraftInteraction, onSubmitInteractionAnswers: submit });
expect(host.querySelector<HTMLTextAreaElement>("textarea")!.value).toBe(" Provider draft\n漢字\\n ");
expect(submit).not.toHaveBeenCalled();
const edited = "\n Operator edit 漢字\\n\n ";
await editCanonical(host, edited);
await act(() => Array.from(host.querySelectorAll("button")).find((button) => button.textContent === "Submit answers")!.click());
expect(submit).toHaveBeenCalledExactlyOnceWith(canonicalDraftInteraction, [{ questionId: "draft", optionIds: [], otherText: edited }]);
});
it("keeps an explicit cleared canonical draft after reopening and requires an answer", async () => {
const submit = vi.fn();
const host = renderCard({ interaction: canonicalDraftInteraction, onSubmitInteractionAnswers: submit });
await editCanonical(host, "");
await act(() => root!.unmount());
host.remove();
const reopened = renderCard({ interaction: canonicalDraftInteraction, onSubmitInteractionAnswers: submit });
expect(reopened.querySelector<HTMLTextAreaElement>("textarea")!.value).toBe("");
expect(Array.from(reopened.querySelectorAll("button")).find((button) => button.textContent === "Submit answers")!.disabled).toBe(true);
expect(submit).not.toHaveBeenCalled();
});
it("opens the shared connection setup for the addressed user", async () => {
connectionIntentsApiMocks.setupOptions.mockResolvedValue({ existingConnections: [] });
const host = renderCard({
@@ -147,6 +226,15 @@ describe("IssueThreadInteractionCard", () => {
"interaction-connection-intent-default",
),
);
// setupOptions being called precedes React Query publishing its result.
// Wait for the real setup flow, not just the dialog's loading shell.
await vi.waitFor(async () => {
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
const setupDialog = document.body.querySelector('[role="dialog"]');
expect(setupDialog).toBeTruthy();
expect(setupDialog?.textContent).not.toContain("Loading connection options");
expect(routerMocks.readSearchParams).toHaveBeenCalled();
});
const dialog = document.body.querySelector('[role="dialog"]');
expect(dialog).toBeTruthy();
expect(dialog?.textContent).toContain("Connect Notion");
@@ -46,6 +46,7 @@ import { ProposalJustification } from "../pages/secrets/proposal-review";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./ui/dropdown-menu";
import { AppLogo } from "@/pages/apps/AppLogo";
import { ConnectionIntentInteractionBody } from "@/features/connections/ConnectionIntentInteractionBody";
import { QuestionForm } from "./task-chat/QuestionForm";
const OTHER_ANSWER_ID = "__paperclip_other__";
@@ -1196,7 +1197,46 @@ function AskUserQuestionsCard({
</span>
</div>
{interaction.status === "pending" ? (
{interaction.status === "pending" && interaction.payload.questionSet ? (
<QuestionForm
id={interaction.id}
questionSet={interaction.payload.questionSet}
draftKey={`issue-question:${interaction.companyId}:${interaction.id}`}
disabled={!onSubmitInteractionAnswers}
initialResponse={interaction.result?.answers ? {
schema: "paperclip.question_response.v1",
answers: Object.fromEntries(interaction.result.answers.map((answer) => [
answer.questionId,
interaction.payload.questionSet!.questions.find((question) => question.id === answer.questionId)?.answerMode === "text"
? { text: answer.otherText ?? "" }
: { selectedOptionIds: answer.optionIds, ...(typeof answer.otherText === "string" ? { customText: answer.otherText } : {}) },
])),
} : null}
onSubmit={async (response) => {
const answers = interaction.payload.questionSet!.questions.map((question) => {
const answer = response.answers[question.id];
const otherText = question.answerMode === "text" ? answer?.text : answer?.customText?.trim();
return {
questionId: question.id,
optionIds: question.answerMode === "text" ? [] : (answer?.selectedOptionIds ?? []),
...(otherText !== undefined ? { otherText } : {}),
};
});
try {
await onSubmitInteractionAnswers?.(interaction, answers);
} catch (error) {
throw new Error(resolutionErrorMessage(error));
}
}}
onCancel={onCancelInteraction ? async () => {
try {
await onCancelInteraction(interaction);
} catch (error) {
throw new Error(resolutionErrorMessage(error));
}
} : undefined}
/>
) : interaction.status === "pending" ? (
<div className="space-y-4">
{questions.map((question, index) => {
const hasFreeTextOption = question.options.some(
+77
View File
@@ -164,6 +164,17 @@ vi.mock("@mdxeditor/editor", async () => {
className={className}
contentEditable
suppressContentEditableWarning
onKeyDown={(event) => {
if (event.key === "Delete" || event.key === "Backspace") {
setContent("");
onChange?.("");
}
}}
onInput={(event) => {
const next = event.currentTarget.textContent ?? "";
setContent(next);
onChange?.(next);
}}
>
{/* The real editor paints resolved text, never the escapes that carried it in. */}
{content.replace(/\\</g, "<") || placeholder || ""}
@@ -376,6 +387,43 @@ describe("MarkdownEditor", () => {
});
});
it("allows a user to clear loaded text as the first editor change", async () => {
const handleChange = vi.fn();
const root = createRoot(container);
await act(async () => {
root.render(<MarkdownEditor value="Loaded draft" onChange={handleChange} />);
});
await flush();
expect(handleChange).not.toHaveBeenCalled();
const editor = container.querySelector('[contenteditable="true"]')!;
await act(async () => {
editor.textContent = "";
editor.dispatchEvent(new InputEvent("input", {
bubbles: true,
inputType: "deleteContentBackward",
}));
});
expect(handleChange).toHaveBeenCalledExactlyOnceWith("");
await act(async () => root.unmount());
});
it.each(["Delete", "Backspace"])("allows first-change clearing when Lexical handles %s without an input event", async (key) => {
const handleChange = vi.fn();
const root = createRoot(container);
await act(async () => {
root.render(<MarkdownEditor value="Loaded draft" onChange={handleChange} />);
});
await flush();
const editor = container.querySelector('[contenteditable="true"]')!;
await act(async () => {
editor.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key }));
});
expect(handleChange).toHaveBeenCalledExactlyOnceWith("");
await act(async () => root.unmount());
});
it("does not recreate the mention decoration observer when the external value changes", async () => {
const originalMutationObserver = globalThis.MutationObserver;
@@ -864,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);
+22
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)));
}, []);
@@ -1369,8 +1372,27 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
isDragOver && "ring-1 ring-primary/60 bg-accent/20",
className,
)}
onInputCapture={(event) => {
if (
!readOnly
&& event.target instanceof HTMLElement
&& event.target.closest('[contenteditable="true"]')
) {
// Actual input may be the editor's first change. An intentional clear
// must not be mistaken for its programmatic empty mount reset.
initialChildOnChangeRef.current = false;
}
}}
onKeyDownCapture={(e) => {
if (readOnly) return;
if (
(e.key === "Backspace" || e.key === "Delete")
&& e.target instanceof HTMLElement
&& e.target.closest('[contenteditable="true"]')
) {
// Lexical handles deletion on keydown and may suppress DOM input.
initialChildOnChangeRef.current = false;
}
// Cmd/Ctrl+Enter to submit
if (onSubmit && e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
+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;
@@ -0,0 +1,92 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { PaperclipQuestionResponse, PaperclipQuestionSet } from "@paperclipai/adapter-utils";
import { QuestionForm } from "./QuestionForm";
vi.mock("./TaskChatRichInput", () => ({
TaskChatRichInput: ({ value, onChange }: { value: string; onChange(value: string): void }) =>
<textarea aria-label="Answer" value={value} onChange={event => onChange(event.target.value)} />,
}));
vi.mock("@/components/MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <div>{children}</div> }));
const questionSet: PaperclipQuestionSet = { schema: "paperclip.question_set.v1", questions: [
{ id: "draft", prompt: "Edit the draft", required: true, answerMode: "text", initialText: " Draft\n漢字\n" },
] };
describe("QuestionForm initial text", () => {
let container: HTMLDivElement;
let root: Root;
const submit = vi.fn();
beforeEach(() => { localStorage.clear(); submit.mockReset(); container = document.createElement("div"); document.body.append(container); root = createRoot(container); });
afterEach(async () => { await act(async () => root.unmount()); container.remove(); localStorage.clear(); });
const input = () => container.querySelector("textarea")!;
async function render(set = questionSet, initialResponse?: PaperclipQuestionResponse) {
await act(async () => root.render(<QuestionForm id="edit" questionSet={set} initialResponse={initialResponse} draftKey="question-initial-text" onSubmit={submit} />));
}
async function edit(text: string) {
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(input(), text);
input().dispatchEvent(new Event("input", { bubbles: true }));
});
}
async function remount(set = questionSet) { await act(async () => root.unmount()); root = createRoot(container); await render(set); }
it("shows exact editable text without sending until the operator submits", async () => {
await render();
expect(input().value).toBe(" Draft\n漢字\n");
expect(submit).not.toHaveBeenCalled();
await act(async () => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Submit answers")!.click());
expect(submit).toHaveBeenCalledExactlyOnceWith({ schema: "paperclip.question_response.v1", answers: { draft: { text: " Draft\n漢字\n" } } });
});
it("preserves edits through a refreshed request and reload instead of reapplying a default", async () => {
await render(); await edit("Operator edit\n");
const refreshed = { ...questionSet, questions: [{ ...questionSet.questions[0]!, initialText: "New provider default" }] };
await render(refreshed); expect(input().value).toBe("Operator edit\n");
await remount(refreshed); expect(input().value).toBe("Operator edit\n");
expect(submit).not.toHaveBeenCalled();
});
it("retains an explicitly cleared draft and required validation across reload", async () => {
await render(); await edit(""); await remount();
expect(input().value).toBe("");
expect(Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Submit answers")!.disabled).toBe(true);
expect(submit).not.toHaveBeenCalled();
});
it("isolates pending requests with the same field ids and restores each edited draft when switching back", async () => {
async function showRequest(id: string, initialText: string) {
const set = { ...questionSet, questions: [{ ...questionSet.questions[0]!, initialText }] };
await act(async () => root.render(
<QuestionForm id={id} questionSet={set} draftKey={`question:${id}`} onSubmit={submit} />,
));
}
const storedText = (id: string) => JSON.parse(localStorage.getItem(`question:${id}`)!).answers.draft.text;
await showRequest("request-a", "Provider draft A");
await edit("Operator edit A");
await showRequest("request-b", "Provider draft B");
expect(input().value).toBe("Provider draft B");
expect(storedText("request-a")).toBe("Operator edit A");
expect(storedText("request-b")).toBe("Provider draft B");
await edit("Operator edit B");
await showRequest("request-a", "Refreshed provider draft A");
expect(input().value).toBe("Operator edit A");
await showRequest("request-b", "Refreshed provider draft B");
expect(input().value).toBe("Operator edit B");
expect(storedText("request-a")).toBe("Operator edit A");
expect(storedText("request-b")).toBe("Operator edit B");
expect(submit).not.toHaveBeenCalled();
await act(async () => Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Submit answers")!.click());
expect(submit).toHaveBeenCalledExactlyOnceWith({ schema: "paperclip.question_response.v1", answers: { draft: { text: "Operator edit B" } } });
});
it("prefers an existing response and keeps text constraints on defaults", async () => {
await render(questionSet, { schema: "paperclip.question_response.v1", answers: { draft: { text: "Existing answer" } } });
expect(input().value).toBe("Existing answer");
await act(async () => root.unmount()); localStorage.clear(); root = createRoot(container);
await render({ ...questionSet, questions: [{ ...questionSet.questions[0]!, initialText: "bad", textValidation: { minLength: 5 } }] });
expect(input().value).toBe("bad");
expect(Array.from(container.querySelectorAll("button")).find(button => button.textContent === "Submit answers")!.disabled).toBe(true);
expect(submit).not.toHaveBeenCalled();
});
});
+17 -3
View File
@@ -230,7 +230,13 @@ export function QuestionResponseSummary({
);
}
export function QuestionForm({
export function QuestionForm(props: QuestionFormProps) {
// Takeovers can reuse this component for another pending request. Remount
// before draft persistence runs so one request cannot overwrite another.
return <QuestionFormForRequest key={JSON.stringify([props.id, props.draftKey])} {...props} />;
}
function QuestionFormForRequest({
id,
questionSet,
initialResponse,
@@ -243,6 +249,14 @@ export function QuestionForm({
onCancel,
}: QuestionFormProps) {
const takeoverActions = useTaskChatComposerTakeoverActions();
// A provider default is an editable draft only. An existing response or
// saved draft, including an explicitly cleared value, always wins. State
// initialization runs once so request refreshes cannot replace user edits.
const startingAnswers = initialResponse?.answers ?? Object.fromEntries(
questionSet.questions
.filter((question) => question.answerMode === "text" && question.initialText !== undefined)
.map((question) => [question.id, { text: question.initialText! }]),
);
const initialDraft = draftKey
? loadStructuredDraft<{
page: number;
@@ -250,7 +264,7 @@ export function QuestionForm({
customActive: Record<string, boolean>;
}>(draftKey, {
page: 0,
answers: structuredClone(initialResponse?.answers ?? {}),
answers: structuredClone(startingAnswers),
customActive: Object.fromEntries(
Object.entries(initialResponse?.answers ?? {})
.filter(([, answer]) => Boolean(answer.customText))
@@ -261,7 +275,7 @@ export function QuestionForm({
const [page, setPage] = useState(initialDraft?.page ?? 0);
const [answers, setAnswers] = useState<Record<string, Answer>>(
() =>
initialDraft?.answers ?? structuredClone(initialResponse?.answers ?? {}),
initialDraft?.answers ?? structuredClone(startingAnswers),
);
const [customActive, setCustomActive] = useState<Record<string, boolean>>(
() =>
@@ -759,7 +759,7 @@ function AskUserQuestionsCard({
const answer = response.answers[question.id];
const otherText =
question.answerMode === "text"
? answer?.text?.trim()
? (interaction.payload.questionSet ? answer?.text : answer?.text?.trim())
: answer?.customText?.trim();
return {
questionId: question.id,
@@ -717,6 +717,38 @@ describe("TaskChatInteractionCard", () => {
]);
});
it.each(["canonical_text", "canonical_custom", "legacy_custom"])("preserves the %s answer mapping", async (mode) => {
const submit = vi.fn();
const interaction = structuredClone(pendingAskUserQuestionsInteraction);
interaction.payload.questions = [{
id: "draft", prompt: "Edit", selectionMode: "single", required: true,
options: [{ id: "preset", label: "Preset" }, { id: "other", label: "Custom answer", freeText: true }],
}];
interaction.payload.questionSet = mode === "legacy_custom" ? undefined : {
schema: "paperclip.question_set.v1",
questions: [mode === "canonical_text"
? { id: "draft", prompt: "Edit", required: true, answerMode: "text", initialText: "Provider draft" }
: { id: "draft", prompt: "Edit", required: true, answerMode: "single_select", options: [{ id: "preset", label: "Preset" }], customAnswer: { enabled: true, label: "Custom answer" } }],
};
await act(async () => root.render(
<TooltipProvider><ThemeProvider>
<TaskChatInteractionCard item={interactionItem(interaction)} presentation="takeover" onSubmitInteractionAnswers={submit} />
</ThemeProvider></TooltipProvider>,
));
if (mode !== "canonical_text") {
await act(async () => Array.from(container.querySelectorAll("button")).find(button => button.textContent?.includes("Custom answer"))!.click());
}
const edited = "\n Operator 漢字 edit\nLiteral \\n stays literal. \n";
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(container.querySelector("textarea")!, edited);
container.querySelector("textarea")!.dispatchEvent(new Event("input", { bubbles: true }));
});
await act(async () => Array.from(container.querySelectorAll("button")).find(button => button.textContent?.trim() === "Send answers" || button.textContent?.trim() === "Submit answers")!.click());
expect(submit).toHaveBeenCalledExactlyOnceWith(interaction, [{
questionId: "draft", optionIds: [], otherText: mode === "canonical_text" ? edited : edited.trim(),
}]);
});
it("paginates item verdicts instead of expanding the whole review set", async () => {
flushSync(() => {
root.render(
@@ -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="size-(--sz-protocol-notice-icon) 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>
);
}
+1
View File
@@ -234,6 +234,7 @@
`in_queue` is the BLOCKED shape recoloured to the in_progress blue
(replaces the bespoke teal "covered" state). Light values here; the
`.dark` block below overrides the hues that need a mode-specific value. */
--sz-protocol-notice-icon: calc(var(--spacing) * 3.5);
--status-task-icon-backlog: #52585d; /* gray darkened — 7.21:1 on paper */
--status-task-icon-todo: #cc7a00; /* amber darkened — clears 3:1 */
--status-task-icon-in_progress: var(--color-blue-600); /* matches nav dots and live labels */
+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 () => {
+1 -1
View File
@@ -387,7 +387,7 @@ function EnvironmentVariablesEditorShowcase() {
NODE_ENV: { type: "plain", value: "production" },
GH_TOKEN: { type: "secret_ref", secretId: "dg-github", version: "latest" },
DB_URL: { type: "secret_ref", secretId: "dg-db", version: 3 },
STRIPE_API_KEY: { type: "plain", value: "sk-live-51H8xL0aBcDeFgHiJkLmNoPq" },
STRIPE_API_KEY: { type: "plain", value: "demo-value-not-a-credential" },
});
return (
<div className="max-w-(--sz-640px) rounded-md border border-border p-4">