From b7ea45ae9c356a0c5586643795287ca6ca414e83 Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 8 Oct 2026 10:28:42 -0500 Subject: [PATCH] Preserve cancelled native questions and their Stop evidence Use the canonical question converter for durable fallbacks. Retire pending native input only on its confirmed cancelled turn. Pass cancelled status to shared account and billing checks and retain the original browser acknowledgement before polling. Co-Authored-By: Paperclip --- doc/plans/2026-10-06-hermes-native-runner.md | 46 +++++++++++++++ packages/paperclip-runner/README.md | 5 +- .../src/drivers/codex/codex-session-state.ts | 12 +++- .../drivers/codex/codex-session-terminal.ts | 2 +- .../src/native-session-runtime.test.ts | 48 +++++++++++++++ .../native-session-executor.test.ts | 30 +++++++++- .../native-runtime/native-session-executor.ts | 58 +++---------------- tests/runner-e2e/catalog.ts | 2 +- tests/runner-e2e/hermes-api-connections.ts | 1 + tests/runner-e2e/runner.spec.ts | 4 +- 10 files changed, 146 insertions(+), 62 deletions(-) diff --git a/doc/plans/2026-10-06-hermes-native-runner.md b/doc/plans/2026-10-06-hermes-native-runner.md index b6bc527d6cc..0aa6a73be67 100644 --- a/doc/plans/2026-10-06-hermes-native-runner.md +++ b/doc/plans/2026-10-06-hermes-native-runner.md @@ -1350,3 +1350,49 @@ recovery state is retained; original per-run cost is unavailable and its existin allocation hold remains reserved. This attempt does not qualify native Stop. Definition version 4 records the corrected navigation and bounded cleanup wait; the earlier attempt remains a separate failed measurement. + +The corrected Stop campaign at `1b16732f9d5be2d59d21139d10ea6f5e11785d55` +reaches the real browser Stop control and a same-scope acknowledged cancellation, +but retains its failed/cleanup-failed grade after 33.304 seconds. Shutdown emits +a provider-loss input expiry. Its durable fallback drops the legacy custom-answer +fields, so shared interaction creation rejects two canonical/legacy mismatches +and the run ends `native_session_interrupted`. The public native receipt reports +31,700 input and 169 output tokens, with unpriced cost and no ready accounting +receipt. All nine observed owned process identities have retired by cleanup. +The private recovery state and unknown-cost hold remain retained. + +The form-conversion fix uses the existing shared canonical-to-storage converter +and passes nine focused fallback regressions, including a mixed custom-answer +batch, a synthetic-option ID collision and rejection of a genuinely incomplete +storage form. It preserves the canonical input and keeps shared validation +strict. Intentional Stop still needs investigation of the provider-loss path, +followed by new live acceptance; this fix alone does not qualify Stop. + +The controller's native terminal mapper caused that provider-loss expiry: it +expired every pending structured input, including inputs on a confirmed +cancelled turn. A regression using the production driver and a scripted +transport reproduced the cancelled-to-expired conversion. The correction uses +the exact cancelled terminal's turn identity to retire its input once, with a +canonical cancellation outcome. Completed, failed and interrupted terminals +retain their prior non-replayable fallback behavior. All 186 related runtime +and request tests pass, including the four terminal outcomes. Nine fallback +regressions and direct server/runner TypeScript checks pass. + +Definition version 5 also passes the cancelled-run expectation into the shared +account and OpenRouter settlement checks after the Stop helper returns. The +earlier definition incorrectly required a successful run at that final shared +boundary. The browser Stop response is now retained before terminal polling, +so a later failure does not discard that original public acknowledgement. +These changes need a fresh paid browser attempt; neither failed attempt is +regraded, and unknown-cost holds remain reserved. + +At `6b3c3a6708a2481a98edaffe15b722b6559dac6e`, cloud Mac native fixtures pass. +Cloud Linux provisioning fails with HTTP 429 before fixture execution. The +cloud Docker context check separately fails at Docker Hub's pinned Node image +manifest request with HTTP 502. Original CI failures remain recorded. + +The server's composite typecheck unexpectedly invoked its Rust build. That +local build is not qualification evidence. The completed build left no live +compiler; its 850,932,819 bytes of disposable target output were removed and +the staged runner restored to the verified cloud-built binary. Subsequent +checks invoke TypeScript directly and perform no local Rust or Docker build. diff --git a/packages/paperclip-runner/README.md b/packages/paperclip-runner/README.md index cd2ef3fef5d..677336c3a41 100644 --- a/packages/paperclip-runner/README.md +++ b/packages/paperclip-runner/README.md @@ -135,10 +135,7 @@ Ordinary remote Cursor startup uses the packaged Linux daemon and verifies every image asset against that manifest. A mismatched image fails before the provider starts; install the matching package and image together. -Hermes native integration is documented in [Hermes](docs/hermes.md). Its explicit -public setup command is `paperclipai runtime setup hermes`, with uv 0.12.17 on -PATH. Setup verifies the pinned Python closure in the execution account's cache; -Hermes remains pending live qualification. +Hermes native integration is documented in [Hermes](docs/hermes.md). Remote Codex sessions relay assigned app tools through the server's configured gateway. Small catalogs are sent directly. When a catalog would exceed the diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts index d38dd5b0317..b70f5ba3c90 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-state.ts @@ -302,11 +302,17 @@ export class CodexSessionState { } } - cancelPendingRequests(reason: string): void { + cancelPendingRequests(reason: string, cancelledTurnId?: string): void { for (const pending of this.pendingRuntimeRequestMap.values()) { + // Only an authoritative cancelled terminal can retire its input as + // cancelled. Other terminal/transport losses keep the durable fallback. + const cancelledInput = pending.request.input !== undefined && + pending.request.turnId === cancelledTurnId; this.emit( - pending.request.input === undefined ? "runtime_request.cancelled" : "runtime_request.expired", - pending.request.input === undefined + pending.request.input === undefined || cancelledInput ? "runtime_request.cancelled" : "runtime_request.expired", + cancelledInput + ? { ...harnessRuntimeRequestOutcome(pending.request, { reason, action: "cancel" }), requestKind: "runtime" } + : pending.request.input === undefined ? harnessRuntimeRequestOutcome(pending.request, { reason }) : harnessRuntimeInputExpiredOutcome(pending.request, "provider_process_lost"), { turnId: pending.request.turnId, itemId: pending.request.itemId }, diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts index 47612b9267b..47f61133f6a 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-terminal.ts @@ -157,7 +157,7 @@ export function mapTerminalTurn( : status === "cancelled" ? "turn.cancelled" : "turn.completed"; - state.cancelPendingRequests("turn_terminal"); + state.cancelPendingRequests("turn_terminal", status === "cancelled" ? turnId : undefined); state.activeTurnId = null; state.turnStarted = false; state.emit( diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 6938f9a4b10..ea1a7b4d081 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -1,6 +1,8 @@ import { createHash } from "node:crypto"; import { QUALIFIED_ACPX_PROFILES } from "./drivers/acpx/qualified-profiles.js"; import { describe, expect, it, vi } from "vitest"; +import { FakeCodexTransport, WORKSPACE, makeDriver, collectUntilTerminal } from "./drivers/codex/codex-app-server-driver.test-support.js"; +import { validatePrpEvent } from "./protocol/replay-contract.js"; import type { ControlPlanePort } from "./contracts/control-plane-port.js"; import type { NativeExecutionInputV1, NativeExecutionInputV5 } from "./contracts/native-execution.js"; @@ -42,6 +44,52 @@ const identity = { agentId: "agent-recovery", }; +describe("native question cancellation terminal", () => { + it.each(["cancelled", "interrupted", "completed", "failed"] as const)("preserves the %s terminal without reviving a cancelled question", async status => { + const transport = new FakeCodexTransport(); + const session = await makeDriver([transport]).openSession({ + runId: `native-question-${status}`, normalizedSessionId: `native-question-${status}`, workingDirectory: WORKSPACE, + }); + try { + const events = collectUntilTerminal(session.events()); + const { turnId } = await session.startTurn({ message: { role: "user", text: "Ask before continuing." } }); + const questionSet = { schema: "paperclip.question_set.v1", questions: [{ + id: "color", prompt: "Which color?", answerMode: "single_select", required: true, + options: [{ id: "cobalt", label: "Cobalt" }, { id: "amber", label: "Amber" }], + customAnswer: { enabled: true, label: "Other", placeholder: "Enter a color" }, + }] }; + const settled = vi.fn(); + const response = transport.invoke({ id: "native-question", method: "_hermes/ask_questions", + params: { threadId: transport.threadId, turnId, itemId: "native-question-item", questionSet } }).then(settled); + await vi.waitFor(() => expect(session.pendingRuntimeRequests?.()).toHaveLength(1)); + const terminal = { method: "turn/completed", params: { threadId: transport.threadId, turn: { id: turnId, status, error: null } } }; + transport.queue.push(terminal); + const observed = await events; + await response; + const outcomes = observed.filter(event => ["runtime_request.cancelled", "runtime_request.expired", "runtime_request.resolved"].includes(event.eventType)); + expect(outcomes).toHaveLength(1); + expect(outcomes[0]).toMatchObject({ + eventType: status === "cancelled" ? "runtime_request.cancelled" : "runtime_request.expired", + turnId, itemId: "native-question-item", payload: { + requestId: "native-question", requestKind: "runtime", requestType: "input", turnId, itemId: "native-question-item", + ...(status === "cancelled" ? { action: "cancel", reason: "turn_terminal" } : { reason: "provider_process_lost", replayAllowed: false, request: { input: questionSet } }), + }, + }); + expect(validatePrpEvent(outcomes[0]!)).toMatchObject({ ok: true }); + if (status === "cancelled") { + expect(outcomes[0]!.payload).not.toHaveProperty("request"); + expect(outcomes[0]!.payload).not.toHaveProperty("response"); + expect(outcomes[0]!.payload).not.toHaveProperty("replayAllowed"); + } + expect(observed.at(-1)).toMatchObject({ eventType: `turn.${status}`, payload: { status, error: null } }); + expect(session.pendingRuntimeRequests?.()).toHaveLength(0); + transport.queue.push(terminal); + await session.close({ reason: "fixture complete" }); + expect(settled).toHaveBeenCalledOnce(); + } finally { await session.close({ reason: "fixture cleanup" }); } + }); +}); + const result: PrpStructuredRunResult = { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 758a6c36989..0f1885bbf6d 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,3 +1,4 @@ +import { createIssueThreadInteractionSchema } from "@paperclipai/shared"; import { configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; @@ -2555,6 +2556,33 @@ describe("runtime question fallback", () => { ], }; + it.each(["provider_process_lost", "durable_handoff"])("preserves a complete custom-answer batch after %s", reason => { + const form = { schema: "paperclip.question_set.v1" as const, questions: [ + { id: "color", prompt: "Choose color", required: true, answerMode: "single_select" as const, + options: [{ id: "cobalt", label: "Cobalt" }], customAnswer: { enabled: true, label: "Another color" } }, + { id: "targets", prompt: "Choose targets", required: true, answerMode: "multi_select" as const, + options: [{ id: "paperclip_custom_answer", label: "Linux" }], customAnswer: { enabled: true, placeholder: "Name a target" } }, + { id: "notes", prompt: "Describe constraint", required: true, answerMode: "text" as const }, + ] }; + const fallback = runtimeQuestionFallbackFromEvent({ eventType: "runtime_request.expired", runId: "00000000-0000-4000-8000-000000000001", + payload: { requestId: "native-batch", requestKind: "runtime", requestType: "input", reason, replayAllowed: false, + request: { schema: "paperclip.runtime_request.v2", requestKind: "runtime", type: "input", status: "pending", + requestId: "native-batch", turnId: "turn", itemId: "item", input: form } } }); + expect(fallback).not.toBeNull(); + expect(createIssueThreadInteractionSchema.safeParse(fallback).success).toBe(true); + expect(fallback!.payload.questionSet).toEqual(form); + expect(fallback!.payload.questions[0]!.options).toEqual([{ id: "cobalt", label: "Cobalt" }, + { id: "paperclip_custom_answer", label: "Another color", freeText: true }]); + expect(fallback!.payload.questions[1]!.options).toEqual([{ id: "paperclip_custom_answer", label: "Linux" }, + { id: "paperclip_custom_answer_2", label: "Other", description: "Name a target", freeText: true }]); + expect(fallback!.payload.questions[1]!.selectionMode).toBe("multi"); + expect(fallback!.payload.questions[2]!.options[0]!.freeText).toBe(true); + const incomplete = structuredClone(fallback!); + incomplete.payload.questions[1]!.options.pop(); + incomplete.payload.questions[1]!.allowOther = false; + expect(createIssueThreadInteractionSchema.safeParse(incomplete).success).toBe(false); + }); + it.each(["provider_process_lost", "durable_handoff"])( "materializes one idempotent durable interaction after %s", (reason) => { @@ -2602,7 +2630,7 @@ describe("runtime question fallback", () => { { id: "replicas", selectionMode: "single", - options: [{ id: "__paperclip_text__", freeText: true }], + options: [{ id: "paperclip_text_answer", freeText: true }], }, ], }, diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index f1832ea90bc..ec2d3686eab 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -77,7 +77,7 @@ import type { AdapterExecutionResult, AdapterRuntimeEvent, } from "../../adapters/index.js"; -import { usdToUnits, type NativeFinalizationResult } from "@paperclipai/shared"; +import { usdToUnits, questionSetToAskUserQuestionsPayload, type AskUserQuestionsPayload, type NativeFinalizationResult } from "@paperclipai/shared"; import type { HarnessRuntimeRequestResolution, NativeExecutionInput, @@ -722,24 +722,12 @@ type RuntimeQuestionFallback = { continuationPolicy: "wake_assignee"; payload: { version: 1; - title?: string; - submitLabel?: string; + title?: string | null; + submitLabel?: string | null; supersedeOnUserComment: false; runtimeRequestId: string; questionSet: PaperclipQuestionSet; - questions: Array<{ - id: string; - prompt: string; - helpText?: string; - selectionMode: "single" | "multi"; - required: boolean; - options: Array<{ - id: string; - label: string; - description?: string; - freeText?: boolean; - }>; - }>; + questions: AskUserQuestionsPayload["questions"]; }; }; @@ -775,35 +763,7 @@ export function runtimeQuestionFallbackFromEvent( } catch { return null; } - const questions = questionSet.questions.map((question) => ({ - id: question.id, - prompt: question.prompt, - ...(question.helpText ? { helpText: question.helpText } : {}), - selectionMode: - question.answerMode === "multi_select" - ? ("multi" as const) - : ("single" as const), - required: question.required, - options: - question.answerMode === "text" - ? [ - { - id: "__paperclip_text__", - label: - question.textValidation?.inputType === "integer" - ? "Enter an integer" - : question.textValidation?.inputType === "number" - ? "Enter a number" - : "Enter your answer", - freeText: true, - }, - ] - : (question.options ?? []).map((option) => ({ - id: option.id, - label: option.label, - ...(option.description ? { description: option.description } : {}), - })), - })); + const storagePayload = questionSetToAskUserQuestionsPayload(questionSet); return { kind: "ask_user_questions", idempotencyKey: `runtime-input-durable:v1:${event.runId}:${request.requestId}`, @@ -812,15 +772,11 @@ export function runtimeQuestionFallbackFromEvent( summary: questionSet.description?.slice(0, 1000) ?? null, continuationPolicy: "wake_assignee", payload: { - version: 1, - ...(questionSet.title ? { title: questionSet.title.slice(0, 240) } : {}), - ...(questionSet.submitLabel - ? { submitLabel: questionSet.submitLabel.slice(0, 120) } - : {}), + ...storagePayload, supersedeOnUserComment: false, runtimeRequestId: request.requestId, questionSet, - questions, + questions: storagePayload.questions, }, }; } diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index 4386d2a51df..bf568c8ec62 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -1220,7 +1220,7 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ environments: runnerEnvironments, tasks: [hermesNativeQuestionTask, hermesNativeQuestionStopTask], excludedExecutionIds: [`${HERMES_NATIVE_INTERACTION_SUITE}.runner-acpx-hermes.daytona.native-question-batch-stop`], expectedMatrixSize: 3, definitionMetadata: { - version: 4, qualification: "pending", scheduling: "explicit-only", accountMethod: "api_key", accountMode: "responsible_user", + version: 5, qualification: "pending", scheduling: "explicit-only", accountMethod: "api_key", accountMode: "responsible_user", providerTurns: 1, lifecycle: "per-turn", nativeMethod: "_hermes/ask_questions", maximumAttemptsPerCell: 1, objectiveAdmission: "production-delivery-guard-question-only", budgetMonthlyCents: HERMES_API_CONNECTION_BUDGET_CENTS, billing: "reported-cost-and-budget-health", diff --git a/tests/runner-e2e/hermes-api-connections.ts b/tests/runner-e2e/hermes-api-connections.ts index c0ff9b01f43..9310d3925f9 100644 --- a/tests/runner-e2e/hermes-api-connections.ts +++ b/tests/runner-e2e/hermes-api-connections.ts @@ -264,6 +264,7 @@ export async function runHermesNativeQuestionStop(input: { const browserResponse = await response.json(); identity = { runId: pending.run.id, turnId: pendingEvent.turnId as string, requestId: request.requestId as string, questionSet, pendingEvent, companyId: fixtures.company.id, callerUserId: input.callerUserId, browserResponse }; + await input.evidence("hermes-native-stop-browser-response.json", { identity, checks }); const stopped = await pollUntil({ label: "Hermes native question cancellation and owned Stop acknowledgement", deadlineAt, intervalMs: 200, load, reject: state => ["succeeded", "failed", "timed_out"].includes(state.run.status) ? "Stop did not produce a cancelled native turn" : undefined, accept: state => state.interactions.length === 1 && state.interactions[0]?.id === card.id && state.interactions[0]?.status === "expired" diff --git a/tests/runner-e2e/runner.spec.ts b/tests/runner-e2e/runner.spec.ts index e5e0bfafa69..720e666d59b 100644 --- a/tests/runner-e2e/runner.spec.ts +++ b/tests/runner-e2e/runner.spec.ts @@ -3013,9 +3013,11 @@ for (const execution of executions) { } if (isHermesConnectionSuite(execution.suite.id)) { if (!fixtures?.aiConnection || !issue?.id || !hermesApiAccountOwner?.expectedResponsibleUserId) throw new Error("Hermes connection qualification is missing its selected account, expected user or task"); + const expectedRunStatus = execution.task.flow === "native_question_stop" ? "cancelled" : "succeeded"; const checks = gradeHermesApiConnection({ companyId: fixtures.company.id, agentId: fixtures.agent.id, issueId: issue.id, connectionId: fixtures.aiConnection.connectionId, provider: fixtures.aiConnection.binding.provider, expectedResponsibleUserId: hermesApiAccountOwner.expectedResponsibleUserId, model: execution.profile.model, runs: selectedRuns, + expectedRunStatus, accountMode: fixtures.aiConnection.binding.mode, ...(execution.profile.managedConnectionRouting ? { expectedGrantId: fixtures.aiConnection.binding.mode === "delegated" ? fixtures.aiConnection.binding.grantId : "" } : {}) }); if (execution.profile.managedConnectionRouting) { @@ -3033,7 +3035,7 @@ for (const execution of executions) { let receipt: Awaited> | undefined; try { await expect.poll(async () => { - receipt = await captureHermesOpenRouterSettlement({ api, ...settlementScope }); + receipt = await captureHermesOpenRouterSettlement({ api, ...settlementScope, expectedRunStatus }); return receipt.checks.every(check => check.passed); }, { timeout: 30_000, message: "OpenRouter billing must settle without pausing the agent before cleanup" }).toBe(true); } finally {