mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 17:33:51 +02:00
## 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>
780 lines
35 KiB
TypeScript
780 lines
35 KiB
TypeScript
import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
import { createServer } from "node:http";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import { eq, sql } from "drizzle-orm";
|
|
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
authUsers,
|
|
companies,
|
|
companyMemberships,
|
|
createDb,
|
|
heartbeatRuns,
|
|
heartbeatRunEvents,
|
|
issueComments,
|
|
issueQuestionResponseDeliveries,
|
|
issueThreadInteractions,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
} from "@paperclipai/db";
|
|
import type { PrpEvent } from "@paperclipai/paperclip-runner";
|
|
import { respondIssueThreadInteractionSchema } from "@paperclipai/shared";
|
|
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "../../__tests__/helpers/embedded-postgres.js";
|
|
import { drainHeartbeatRunsToQuiescence } from "../../__tests__/helpers/drain-heartbeat-runs.js";
|
|
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
|
|
import {
|
|
deliverNativeQuestionResponse,
|
|
flushNativeQuestionResponses,
|
|
nativeQuestionBridgeInternals,
|
|
nativeQuestionRunToCancel,
|
|
projectNativeRuntimeRequest,
|
|
registerNativeQuestionCommandTarget,
|
|
requestNativeQuestionRunCancellation,
|
|
validateNativeQuestionResponseInput,
|
|
} from "./native-question-bridge.js";
|
|
import {
|
|
executeIssuePostCommitActions,
|
|
issueService,
|
|
type IssuePostCommitAction,
|
|
} from "../issues.js";
|
|
import { questionResponseDeliveryService } from "../question-response-delivery.js";
|
|
import * as questionPatternValidation from "../question-pattern-validation.js";
|
|
import { heartbeatService } from "../heartbeat.js";
|
|
import { DurablePrpControlPlane } from "../../vendor/paperclip-runner/index.js";
|
|
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
|
|
import { readPendingNativeRuntimeRequest } from "./runtime-request-resolution-authority.js";
|
|
import {
|
|
queueRunnerPrpRuntimeRequestResolution,
|
|
registerRunnerPrpAuthority,
|
|
setupRunnerPrpWebSocketServer,
|
|
} from "../../realtime/runner-prp-ws.js";
|
|
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping native question bridge tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
|
);
|
|
}
|
|
|
|
describeEmbeddedPostgres("native question bridge", () => {
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
let db: ReturnType<typeof createDb>;
|
|
let heartbeat: ReturnType<typeof heartbeatService>;
|
|
let companyId: string;
|
|
let issueId: string;
|
|
let agentId: string;
|
|
let runId: string;
|
|
let sessionId: string;
|
|
let runnerInstanceId: string;
|
|
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-question-");
|
|
db = createDb(temporary.connectionString);
|
|
heartbeat = heartbeatService(db);
|
|
}, 20_000);
|
|
|
|
afterEach(async () => {
|
|
// A cancelled or reaped run can promote and dispatch its agent's next
|
|
// queued run fire-and-forget (see startNextQueuedRunForAgent in
|
|
// heartbeat.ts), so that dispatch can still be writing heartbeat_runs,
|
|
// issues, or activity_log rows when this hook starts. Drain every
|
|
// in-flight run to quiescence first, or its late write races the
|
|
// TRUNCATE below and can deadlock.
|
|
await drainHeartbeatRunsToQuiescence(db, heartbeat);
|
|
nativeQuestionBridgeInternals.resetForTests();
|
|
await db.execute(sql.raw(`
|
|
TRUNCATE TABLE
|
|
"activity_log",
|
|
"issue_thread_interactions",
|
|
"heartbeat_runs",
|
|
"agent_wakeup_requests",
|
|
"issues",
|
|
"agents",
|
|
"companies"
|
|
RESTART IDENTITY CASCADE
|
|
`));
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await temporary?.cleanup();
|
|
});
|
|
|
|
async function seed() {
|
|
companyId = randomUUID();
|
|
issueId = randomUUID();
|
|
agentId = randomUUID();
|
|
runId = randomUUID();
|
|
sessionId = randomUUID();
|
|
runnerInstanceId = randomUUID();
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Native questions",
|
|
issuePrefix: `NQ${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
await db.insert(authUsers).values({
|
|
id: "operator-1", name: "Operator", email: "operator-1@example.test",
|
|
createdAt: new Date(), updatedAt: new Date(),
|
|
}).onConflictDoNothing();
|
|
await db.insert(companyMemberships).values({
|
|
companyId, principalType: "user", principalId: "operator-1", status: "active", membershipRole: "member",
|
|
});
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "Native Codex",
|
|
adapterType: "paperclip_runner",
|
|
status: "running",
|
|
adapterConfig: { provider: "codex" },
|
|
runtimeConfig: {},
|
|
});
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
title: "Answer a native question",
|
|
status: "in_progress",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "operator-1",
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
status: "running",
|
|
runtimeMode: "native",
|
|
runtimeModeResolvedAt: new Date(),
|
|
nativeIssueId: issueId,
|
|
nativeSessionId: sessionId,
|
|
runnerInstanceId,
|
|
driverKind: "codex",
|
|
contextSnapshot: { issueId },
|
|
});
|
|
await db.insert(nativeRunFinalizations).values({
|
|
runId,
|
|
companyId,
|
|
issueId,
|
|
phase: "observed",
|
|
});
|
|
}
|
|
|
|
function runtimeRequestEvent(): PrpEvent {
|
|
return {
|
|
schema: "paperclip.prp.event.v1",
|
|
sourceEventId: "runtime-question-1",
|
|
sourceSeq: 1,
|
|
sourceInstanceId: runnerInstanceId,
|
|
sourceKind: "runner",
|
|
runId,
|
|
normalizedSessionId: sessionId,
|
|
turnId: "turn-1",
|
|
itemId: "item-1",
|
|
eventType: "runtime_request.created",
|
|
schemaVersion: 1,
|
|
priority: 0,
|
|
emittedAt: "2026-08-25T18:00:00.000Z",
|
|
payload: {
|
|
request: {
|
|
schema: "paperclip.runtime_request.v2",
|
|
requestKind: "runtime",
|
|
requestId: "request-1",
|
|
type: "input",
|
|
status: "pending",
|
|
prompt: "Choose a deployment color",
|
|
input: {
|
|
schema: "paperclip.question_set.v1",
|
|
title: "Deployment",
|
|
questions: [{
|
|
id: "color",
|
|
prompt: "Which color?",
|
|
required: true,
|
|
answerMode: "single_select",
|
|
options: [
|
|
{ id: "blue", label: "Blue" },
|
|
{ id: "green", label: "Green" },
|
|
],
|
|
}],
|
|
},
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function binding() {
|
|
return {
|
|
companyId,
|
|
issueId,
|
|
runId,
|
|
agentId,
|
|
normalizedSessionId: sessionId,
|
|
runnerSourceInstanceId: runnerInstanceId,
|
|
completionContractId: randomUUID(),
|
|
completionContractSha256: `sha256:${"a".repeat(64)}`,
|
|
completionContractRevision: "1",
|
|
completionContractCriterionIds: [],
|
|
};
|
|
}
|
|
|
|
function permissionRequestEvent(): PrpEvent {
|
|
return { ...runtimeRequestEvent(), payload: { request: {
|
|
schema: "paperclip.runtime_request.v2", requestKind: "permission_approval",
|
|
requestId: "permission-1", turnId: "turn-1", itemId: "item-1",
|
|
type: "permission", status: "pending", prompt: "Allow editing src/example.ts?",
|
|
choices: [{ key: "accept", label: "Allow once" }, { key: "decline", label: "Deny" }],
|
|
details: { toolCallId: "tool-1" },
|
|
origin: { adapter: "acpx-runtime-sidecar", provider: "acpx", method: "session/request_permission" },
|
|
} } };
|
|
}
|
|
|
|
it("commits and acknowledges an ACP permission, then queues only an admin's exact turn-bound decision", async () => {
|
|
await seed();
|
|
const event = permissionRequestEvent();
|
|
const projection = vi.fn(async (committed: PrpEvent) => {
|
|
await projectNativeRuntimeRequest({ db, binding: binding(), event: committed });
|
|
});
|
|
const port = new PaperclipControlPlanePort(db, {
|
|
companyId, issueId, runId, agentId, sessionId,
|
|
completionContractId: binding().completionContractId,
|
|
completionContractSha256: binding().completionContractSha256,
|
|
sourceInstanceId: runnerInstanceId, controlPlaneSourceInstanceId: "control-1",
|
|
}, { onCommittedEvent: projection });
|
|
const receipt = await port.appendEvent(event);
|
|
expect(receipt).toMatchObject({ disposition: "committed", highestContiguousSourceSeq: 1 });
|
|
expect(projection).toHaveBeenCalledOnce();
|
|
expect(await db.select().from(issueThreadInteractions)).toHaveLength(0);
|
|
const [persisted] = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
|
|
expect(persisted?.payload).toEqual({ prpEvent: event }); // task-chat's exact source, with only offered decisions
|
|
expect(await port.appendEvent(event)).toMatchObject({ disposition: "duplicate" });
|
|
const pending = await readPendingNativeRuntimeRequest(db, { companyId, runId, requestId: "permission-1" });
|
|
expect(pending).toMatchObject({ requestKind: "permission_approval", turnId: "turn-1", resolverPolicy: "instance_admin" });
|
|
expect(await readPendingNativeRuntimeRequest(db, { companyId: randomUUID(), runId, requestId: "permission-1" })).toBeNull();
|
|
|
|
const stateDirectory = mkdtempSync(join(tmpdir(), "native-permission-authority-"));
|
|
const server = createServer();
|
|
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" });
|
|
const authority = new DurablePrpControlPlane({
|
|
stateDirectory,
|
|
identity: { runnerInstanceId, environmentLeaseId: "lease-1", runId, normalizedSessionId: sessionId, turnId: "turn-1", itemId: "item-1" },
|
|
expectedRunnerVersion: "0.3.0", expectedRunnerDigest: `sha256:${"a".repeat(64)}`,
|
|
});
|
|
const registration = await registerRunnerPrpAuthority({ companyId, runId, authority });
|
|
try {
|
|
const commandInput = { companyId, runId, pendingRequest: pending!, resolution: { action: "accept" as const },
|
|
actor: { type: "user" as const, userId: "admin-1", isInstanceAdmin: true } };
|
|
expect(() => queueRunnerPrpRuntimeRequestResolution({ ...commandInput, actor: { ...commandInput.actor, isInstanceAdmin: false } }))
|
|
.toThrow("native_runtime_request_resolver_denied");
|
|
expect(() => queueRunnerPrpRuntimeRequestResolution({ ...commandInput, companyId: randomUUID() }))
|
|
.toThrow("runner_prp_authority_not_active");
|
|
const queued = queueRunnerPrpRuntimeRequestResolution(commandInput);
|
|
expect(queueRunnerPrpRuntimeRequestResolution(commandInput)).toEqual(queued);
|
|
expect(authority.store.state.commands).toHaveLength(1);
|
|
expect(authority.store.state.commands[0]).toMatchObject({ type: "request.resolve", payload: {
|
|
requestId: "permission-1", requestKind: "permission_approval", turnId: "turn-1",
|
|
resolution: { action: "accept" }, resolutionActor: commandInput.actor,
|
|
} });
|
|
expect(() => queueRunnerPrpRuntimeRequestResolution({ ...commandInput, resolution: { action: "decline" } }))
|
|
.toThrow("runtime_request_resolution_conflict");
|
|
// Queueing is not delivery: only the runner's post-write receipt closes
|
|
// the request. ACP sidecar delivery tests exercise that provider edge.
|
|
expect(await readPendingNativeRuntimeRequest(db, { companyId, runId, requestId: "permission-1" })).toEqual(pending);
|
|
await port.appendEvent({ ...event, sourceEventId: "permission-delivered", sourceSeq: 2,
|
|
eventType: "runtime_request.resolved", payload: { requestId: "permission-1", requestKind: "permission_approval",
|
|
turnId: "turn-1", itemId: "item-1", status: "delivered", action: "accept" } });
|
|
expect(await readPendingNativeRuntimeRequest(db, { companyId, runId, requestId: "permission-1" })).toBeNull();
|
|
} finally {
|
|
await registration.release();
|
|
await authority.stop();
|
|
server.close();
|
|
rmSync(stateDirectory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.each([
|
|
{ requestKind: "runtime" }, { type: "input" }, { turnId: "stale-turn" }, { itemId: "wrong-item" },
|
|
{ choices: [] }, { choices: [{ key: "allow_forever", label: "Always" }] },
|
|
{ choices: [{ key: "accept", label: "One" }, { key: "accept", label: "Two" }] },
|
|
])("rejects a malformed permission projection %j", async (override) => {
|
|
await seed();
|
|
const event = permissionRequestEvent();
|
|
Object.assign(event.payload.request as object, override);
|
|
await expect(projectNativeRuntimeRequest({ db, binding: binding(), event })).rejects.toThrow(/native_runtime_/);
|
|
});
|
|
|
|
it("projects an executor question immediately and routes its durable answer into the same live turn", async () => {
|
|
await seed();
|
|
const event = runtimeRequestEvent();
|
|
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId, seq: 1,
|
|
eventType: event.eventType, stream: "system", level: "info", payload: { prpEvent: event } });
|
|
const resolve = vi.fn(async (input: any) => { await input.authorizeBeforeDispatch(); return { commandId: "live-response" }; });
|
|
const bridge = createLocalNativeQuestionBridge({ db, binding: binding(), resolve });
|
|
try {
|
|
await bridge.attach();
|
|
await bridge.observe(event);
|
|
await bridge.observe(event); // replay must not create a second card
|
|
const cards = await issueThreadInteractionService(db).listForIssue(issueId);
|
|
expect(cards).toHaveLength(1);
|
|
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: runId, continuationPolicy: "none" });
|
|
const answered = await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" }, cards[0]!.id,
|
|
{ answers: [{ questionId: "color", optionIds: ["green"] }] }, { userId: "operator-1" },
|
|
);
|
|
if (answered.kind !== "ask_user_questions") throw new Error("wrong question kind");
|
|
expect(await deliverNativeQuestionResponse(db, answered)).toBe("queued");
|
|
expect(resolve).toHaveBeenCalledWith(expect.objectContaining({ runId, requestId: "request-1", turnId: "turn-1",
|
|
resolution: { action: "submit", response: { schema: "paperclip.question_response.v1", answers: { color: { selectedOptionIds: ["green"] } } } },
|
|
}));
|
|
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, runId));
|
|
await expect(resolve.mock.calls[0]![0].authorizeBeforeDispatch()).rejects.toThrow("native_question_not_pending");
|
|
} finally { bridge.close(); }
|
|
});
|
|
|
|
it("delivers saved answers without entering pattern validation again", async () => {
|
|
await seed();
|
|
const event = runtimeRequestEvent();
|
|
(event.payload.request as any).input.questions = [{ id: "url", prompt: "URL?", required: true, answerMode: "text" }];
|
|
const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event });
|
|
const answered = await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" }, interaction!.id,
|
|
{ answers: [{ questionId: "url", optionIds: [], otherText: "https://example.test" }] }, { userId: "operator-1" },
|
|
);
|
|
if (answered.kind !== "ask_user_questions") throw new Error("expected questions");
|
|
const queueCommand = vi.fn(() => ({ commandId: "question", controllerSeq: 1 }));
|
|
const release = registerNativeQuestionCommandTarget({ binding: { companyId, issueId, runId, agentId }, queueCommand });
|
|
const busy = vi.spyOn(questionPatternValidation, "validateQuestionPatterns").mockRejectedValue(new Error("Question format validation is busy; try again"));
|
|
try {
|
|
await flushNativeQuestionResponses(db, runId);
|
|
expect(queueCommand).toHaveBeenCalledWith("request.resolve", expect.objectContaining({
|
|
response: { schema: "paperclip.question_response.v1", answers: { url: { text: "https://example.test" } } },
|
|
}), `question_${interaction!.id}`);
|
|
expect(busy).not.toHaveBeenCalled();
|
|
const [delivery] = await db.select().from(issueQuestionResponseDeliveries);
|
|
expect(delivery).toMatchObject({ status: "delivered" });
|
|
} finally {
|
|
busy.mockRestore();
|
|
release();
|
|
}
|
|
});
|
|
|
|
it.each(["codex", "claude"])("materializes, validates, and durably resumes a %s question response", async (provider) => {
|
|
await seed();
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: { ...runtimeRequestEvent(), payload: {
|
|
request: { ...(runtimeRequestEvent().payload.request as Record<string, unknown>),
|
|
origin: { adapter: provider === "claude" ? "acpx-runtime-sidecar" : "codex-app-server", provider,
|
|
method: provider === "claude" ? "elicitation/create" : "item/tool/requestUserInput" },
|
|
},
|
|
} },
|
|
});
|
|
|
|
expect(interaction).toMatchObject({
|
|
kind: "ask_user_questions",
|
|
status: "pending",
|
|
sourceRunId: runId,
|
|
continuationPolicy: "none",
|
|
effectiveResolverPolicy: "human_only",
|
|
payload: {
|
|
runtimeRequestId: "request-1",
|
|
supersedeOnUserComment: false,
|
|
questionSet: { schema: "paperclip.question_set.v1" },
|
|
questions: [{
|
|
id: "color",
|
|
selectionMode: "single",
|
|
allowOther: false,
|
|
options: [{ id: "blue", label: "Blue" }, { id: "green", label: "Green" }],
|
|
}],
|
|
},
|
|
});
|
|
expect(await db.select().from(activityLog)).toHaveLength(1);
|
|
|
|
const answer = { answers: [{ questionId: "color", optionIds: ["blue"] }] };
|
|
await validateNativeQuestionResponseInput(interaction!, answer);
|
|
await expect(validateNativeQuestionResponseInput(interaction!, {
|
|
answers: [{ questionId: "color", optionIds: ["red"] }],
|
|
})).rejects.toThrow(/unknown option red/);
|
|
|
|
const answered = await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" },
|
|
interaction!.id,
|
|
answer,
|
|
{ userId: "operator-1" },
|
|
);
|
|
const queueCommand = vi.fn(() => ({ commandId: "question", controllerSeq: 1 }));
|
|
const release = registerNativeQuestionCommandTarget({
|
|
binding: { companyId, issueId, runId, agentId },
|
|
queueCommand,
|
|
});
|
|
|
|
await flushNativeQuestionResponses(db, runId);
|
|
expect(queueCommand).toHaveBeenCalledWith(
|
|
"request.resolve",
|
|
{
|
|
requestId: "request-1",
|
|
response: {
|
|
schema: "paperclip.question_response.v1",
|
|
answers: { color: { selectedOptionIds: ["blue"] } },
|
|
},
|
|
},
|
|
`question_${interaction!.id}`,
|
|
);
|
|
expect(queueCommand).toHaveBeenCalledTimes(1);
|
|
const [delivery] = await db.select().from(issueQuestionResponseDeliveries);
|
|
expect(delivery).toMatchObject({
|
|
interactionId: interaction!.id,
|
|
status: "delivered",
|
|
deliveryMode: "steered",
|
|
targetRunId: runId,
|
|
});
|
|
expect(answered.kind).toBe("ask_user_questions");
|
|
if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction");
|
|
await expect(nativeQuestionRunToCancel(db, answered)).resolves.toBe(runId);
|
|
release();
|
|
});
|
|
|
|
it.each(["legacy", "canonical_select"])("keeps %s custom-answer normalization and rejects blank public answers", async (mode) => {
|
|
await seed();
|
|
const event = runtimeRequestEvent();
|
|
const input = (event.payload.request as { input: { questions: Record<string, unknown>[] } }).input;
|
|
input.questions[0]!.customAnswer = { enabled: true };
|
|
const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event });
|
|
if (mode === "legacy") {
|
|
const payload = { ...interaction!.payload };
|
|
if ("questionSet" in payload) delete payload.questionSet;
|
|
await db.update(issueThreadInteractions).set({ payload }).where(eq(issueThreadInteractions.id, interaction!.id));
|
|
}
|
|
const service = issueThreadInteractionService(db);
|
|
await expect(service.answerQuestions({ id: issueId, companyId, status: "in_progress" }, interaction!.id,
|
|
respondIssueThreadInteractionSchema.parse({ answers: [{ questionId: "color", optionIds: [], otherText: " \n " }] }), { userId: "operator-1" },
|
|
)).rejects.toThrow(/requires an answer/);
|
|
const answered = await service.answerQuestions({ id: issueId, companyId, status: "in_progress" }, interaction!.id,
|
|
respondIssueThreadInteractionSchema.parse({ answers: [{ questionId: "color", optionIds: [], otherText: " Extra\\nline " }] }), { userId: "operator-1" },
|
|
);
|
|
expect(answered.result).toMatchObject({ answers: [{ questionId: "color", otherText: "Extra\nline" }] });
|
|
});
|
|
|
|
it("persists initial text without resolving and delivers only an explicit edited answer", async () => {
|
|
await seed();
|
|
const initialText = " Editable draft\n漢字\n";
|
|
const event = runtimeRequestEvent();
|
|
const request = event.payload.request as Record<string, unknown>;
|
|
request.input = { schema: "paperclip.question_set.v1", questions: [{ id: "draft", prompt: "Edit", required: true, answerMode: "text", initialText }] };
|
|
const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event });
|
|
expect(interaction).toMatchObject({ status: "pending", payload: { questionSet: { questions: [{ initialText }] } } });
|
|
const [stored] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interaction!.id));
|
|
expect(stored).toMatchObject({ status: "pending", result: null, payload: { questionSet: { questions: [{ initialText }] } } });
|
|
const queueCommand = vi.fn(() => ({ commandId: "edited", controllerSeq: 1 }));
|
|
const release = registerNativeQuestionCommandTarget({ binding: { companyId, issueId, runId, agentId }, queueCommand });
|
|
try {
|
|
await flushNativeQuestionResponses(db, runId);
|
|
expect(queueCommand).not.toHaveBeenCalled();
|
|
const edited = "\n Operator 漢字 edited\n\nLiteral \\n stays literal. \n";
|
|
await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" }, interaction!.id,
|
|
respondIssueThreadInteractionSchema.parse({ answers: [{ questionId: "draft", optionIds: [], otherText: edited }] }), { userId: "operator-1" },
|
|
);
|
|
await flushNativeQuestionResponses(db, runId);
|
|
expect(queueCommand).toHaveBeenCalledExactlyOnceWith("request.resolve", {
|
|
requestId: "request-1", response: { schema: "paperclip.question_response.v1", answers: { draft: { text: edited } } },
|
|
}, `question_${interaction!.id}`);
|
|
} finally { release(); }
|
|
});
|
|
|
|
it.each(["succeeded", "failed", "cancelled", "timed_out"])("delivers a historical answer exactly once after a %s native run", async status => {
|
|
await seed();
|
|
await db.update(issues).set({ conversationAgentId: agentId, conversationUserId: "operator-1", conversationState: "active", conversationSessionGeneration: 1, executionRunId: null }).where(eq(issues.id, issueId));
|
|
const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event: runtimeRequestEvent() });
|
|
await db.update(heartbeatRuns).set({ status, finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
|
await issueThreadInteractionService(db).answerQuestions({ id: issueId, companyId, status: "in_progress" }, interaction!.id,
|
|
{ answers: [{ questionId: "color", optionIds: ["green"] }] }, { userId: "operator-1" });
|
|
const queueCommand = vi.fn();
|
|
const release = registerNativeQuestionCommandTarget({ binding: { companyId, issueId, runId, agentId }, queueCommand });
|
|
const targetRunId = randomUUID();
|
|
const wakeup = vi.fn(async () => db.insert(heartbeatRuns).values({ id: targetRunId, companyId, agentId, status: "queued",
|
|
contextSnapshot: { issueId } }).returning().then(rows => rows[0]!));
|
|
const service = questionResponseDeliveryService(db, { heartbeat: { wakeup } as never,
|
|
resolveNativeQuestion: candidate => deliverNativeQuestionResponse(db, candidate) });
|
|
expect(await service.deliver(interaction!.id)).toMatchObject({ status: "fallback_queued", targetRunId });
|
|
expect((await service.deliver(interaction!.id))?.duplicate).toBe(true);
|
|
expect(wakeup).toHaveBeenCalledTimes(1);
|
|
expect(JSON.stringify(wakeup.mock.calls)).toContain(interaction!.id);
|
|
const [saved] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interaction!.id));
|
|
expect(saved).toMatchObject({ status: "answered", result: { answers: [{ questionId: "color", optionIds: ["green"] }] } });
|
|
const [delivery] = await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.interactionId, interaction!.id));
|
|
expect(delivery).toMatchObject({ targetRunId, sourceRunId: runId, deliveryMode: "wake_fallback", status: "fallback_queued" });
|
|
expect(queueCommand).not.toHaveBeenCalled();
|
|
release();
|
|
});
|
|
|
|
it("binds projection to the persisted native run and ignores legacy delivery", async () => {
|
|
await seed();
|
|
const mismatched = runtimeRequestEvent();
|
|
mismatched.runId = randomUUID();
|
|
await expect(projectNativeRuntimeRequest({ db, binding: binding(), event: mismatched }))
|
|
.rejects.toThrow("native_runtime_request_binding_mismatch");
|
|
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: runtimeRequestEvent(),
|
|
});
|
|
const answered = await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" },
|
|
interaction!.id,
|
|
{ answers: [{ questionId: "color", optionIds: ["green"] }] },
|
|
{ userId: "operator-1" },
|
|
);
|
|
await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, runId));
|
|
expect(answered.kind).toBe("ask_user_questions");
|
|
if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction");
|
|
await expect(deliverNativeQuestionResponse(db, answered)).resolves.toBe("not_native");
|
|
await expect(nativeQuestionRunToCancel(db, answered)).resolves.toBeNull();
|
|
});
|
|
|
|
it("does not duplicate the task card when the runner replays a request", async () => {
|
|
await seed();
|
|
const first = await projectNativeRuntimeRequest({ db, binding: binding(), event: runtimeRequestEvent() });
|
|
const second = await projectNativeRuntimeRequest({ db, binding: binding(), event: runtimeRequestEvent() });
|
|
expect(second?.id).toBe(first?.id);
|
|
expect(await db.select().from(issueThreadInteractions)).toHaveLength(1);
|
|
expect(await db.select().from(activityLog)).toHaveLength(1);
|
|
});
|
|
|
|
async function addLaterHumanDirection(interactionId: string) {
|
|
const [question] = await db.select().from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interactionId));
|
|
await db.insert(issueComments).values({ companyId, issueId, authorType: "user", authorUserId: "operator-1",
|
|
body: "Continue with the configuration already selected.", createdAt: new Date(question.createdAt.getTime() + 1000) });
|
|
}
|
|
|
|
it.each([false, true])("cancels the active native run when the task is cancelled (historical=%s)", async historical => {
|
|
await seed();
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: runtimeRequestEvent(),
|
|
});
|
|
if (historical) await addLaterHumanDirection(interaction!.id);
|
|
await issueService(db).update(issueId, { status: "cancelled" });
|
|
|
|
const [persistedInteraction] = await db.select({ status: issueThreadInteractions.status })
|
|
.from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interaction!.id));
|
|
const [persistedRun] = await db.select({
|
|
status: heartbeatRuns.status,
|
|
resultJson: heartbeatRuns.resultJson,
|
|
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(persistedInteraction?.status).toBe("expired");
|
|
expect(persistedRun).toMatchObject({
|
|
status: "cancelled",
|
|
resultJson: {
|
|
cancelledByIssueStatus: "cancelled",
|
|
cancelledIssueId: issueId,
|
|
},
|
|
});
|
|
});
|
|
|
|
it.each([false, true])("defers native cancellation until task completion commits (historical=%s)", async historical => {
|
|
await seed();
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: runtimeRequestEvent(),
|
|
});
|
|
if (historical) await addLaterHumanDirection(interaction!.id);
|
|
const postCommitActions: IssuePostCommitAction[] = [];
|
|
await db.transaction(async (tx) => {
|
|
await issueService(db).update(
|
|
issueId,
|
|
{ status: "done" },
|
|
tx,
|
|
undefined,
|
|
postCommitActions,
|
|
);
|
|
const [runInsideTransaction] = await tx.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(runInsideTransaction?.status).toBe("running");
|
|
});
|
|
|
|
expect(postCommitActions).toHaveLength(1);
|
|
await executeIssuePostCommitActions(db, postCommitActions);
|
|
const [persistedRun] = await db.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(persistedRun?.status).toBe("cancelled");
|
|
const [question] = await db.select().from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interaction!.id));
|
|
expect(question.status).toBe(historical ? "pending" : "expired");
|
|
if (historical) {
|
|
await issueThreadInteractionService(db).answerQuestions({ id: issueId, companyId, status: "done" }, interaction!.id,
|
|
{ answers: [{ questionId: "color", optionIds: ["green"] }] }, { userId: "operator-1" });
|
|
expect(await db.select().from(issueQuestionResponseDeliveries)).toEqual([]);
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("done");
|
|
}
|
|
});
|
|
|
|
it.each([false, true])("recovers task closure cancellation after process exit (historical=%s)", async historical => {
|
|
await seed();
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: runtimeRequestEvent(),
|
|
});
|
|
if (historical) await addLaterHumanDirection(interaction!.id);
|
|
const postCommitActions: IssuePostCommitAction[] = [];
|
|
await db.transaction(async (tx) => {
|
|
await issueService(db).update(
|
|
issueId,
|
|
{ status: "done" },
|
|
tx,
|
|
undefined,
|
|
postCommitActions,
|
|
);
|
|
});
|
|
|
|
const [markedRun] = await db.select({
|
|
status: heartbeatRuns.status,
|
|
contextSnapshot: heartbeatRuns.contextSnapshot,
|
|
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(markedRun).toMatchObject({
|
|
status: "running",
|
|
contextSnapshot: {
|
|
nativeQuestionCancellation: {
|
|
version: 1,
|
|
issueId,
|
|
issueStatus: "done",
|
|
},
|
|
},
|
|
});
|
|
|
|
// Simulate process exit before executeIssuePostCommitActions can run.
|
|
await heartbeat.reapOrphanedRuns();
|
|
|
|
const [persistedRun] = await db.select({
|
|
status: heartbeatRuns.status,
|
|
resultJson: heartbeatRuns.resultJson,
|
|
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(persistedRun).toMatchObject({
|
|
status: "cancelled",
|
|
resultJson: {
|
|
cancelledByIssueStatus: "done",
|
|
cancelledIssueId: issueId,
|
|
},
|
|
});
|
|
const [question] = await db.select().from(issueThreadInteractions)
|
|
.where(eq(issueThreadInteractions.id, interaction!.id));
|
|
expect(question.status).toBe(historical ? "pending" : "expired");
|
|
});
|
|
|
|
it("recovers an explicit question withdrawal committed with its cancellation intent", async () => {
|
|
await seed();
|
|
const interaction = await projectNativeRuntimeRequest({
|
|
db,
|
|
binding: binding(),
|
|
event: runtimeRequestEvent(),
|
|
});
|
|
await issueThreadInteractionService(db).withdrawInteraction(
|
|
{ id: issueId, companyId },
|
|
interaction!.id,
|
|
{ reason: "No longer needed" },
|
|
{ userId: "operator-1" },
|
|
{
|
|
afterResolveInTransaction: async (tx, withdrawn) => {
|
|
await expect(requestNativeQuestionRunCancellation(tx, withdrawn, {
|
|
kind: "interaction_withdrawn",
|
|
interactionId: withdrawn.id,
|
|
})).resolves.toBe(runId);
|
|
},
|
|
},
|
|
);
|
|
|
|
const [markedRun] = await db.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, runId));
|
|
expect(markedRun?.contextSnapshot).toMatchObject({
|
|
nativeQuestionCancellation: {
|
|
version: 1,
|
|
kind: "interaction_withdrawn",
|
|
interactionId: interaction!.id,
|
|
issueId,
|
|
},
|
|
});
|
|
|
|
await heartbeat.reapOrphanedRuns();
|
|
|
|
const [cancelledRun] = await db.select({
|
|
status: heartbeatRuns.status,
|
|
resultJson: heartbeatRuns.resultJson,
|
|
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(cancelledRun).toMatchObject({
|
|
status: "cancelled",
|
|
resultJson: {
|
|
withdrawnInteractionId: interaction!.id,
|
|
cancelledIssueId: issueId,
|
|
},
|
|
});
|
|
});
|
|
|
|
it("removes the UI-only marker from a canonical custom response", async () => {
|
|
await seed();
|
|
const event = runtimeRequestEvent();
|
|
const request = event.payload.request as Record<string, unknown>;
|
|
const input = request.input as Record<string, unknown>;
|
|
input.questions = [{
|
|
id: "color",
|
|
prompt: "Which color?",
|
|
required: true,
|
|
answerMode: "single_select",
|
|
options: [{ id: "blue", label: "Blue" }],
|
|
customAnswer: { enabled: true, label: "Another color" },
|
|
}];
|
|
const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event });
|
|
const answer = {
|
|
answers: [{
|
|
questionId: "color",
|
|
optionIds: ["paperclip_custom_answer"],
|
|
otherText: "purple",
|
|
}],
|
|
};
|
|
await validateNativeQuestionResponseInput(interaction!, answer);
|
|
const answered = await issueThreadInteractionService(db).answerQuestions(
|
|
{ id: issueId, companyId, status: "in_progress" },
|
|
interaction!.id,
|
|
answer,
|
|
{ userId: "operator-1" },
|
|
);
|
|
expect(answered.kind).toBe("ask_user_questions");
|
|
if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction");
|
|
|
|
const queueCommand = vi.fn(() => ({ commandId: "question", controllerSeq: 1 }));
|
|
registerNativeQuestionCommandTarget({
|
|
binding: { companyId, issueId, runId, agentId },
|
|
queueCommand,
|
|
});
|
|
await expect(deliverNativeQuestionResponse(db, answered)).resolves.toBe("queued");
|
|
expect(queueCommand).toHaveBeenCalledWith(
|
|
"request.resolve",
|
|
{
|
|
requestId: "request-1",
|
|
response: {
|
|
schema: "paperclip.question_response.v1",
|
|
answers: { color: { selectedOptionIds: [], customText: "purple" } },
|
|
},
|
|
},
|
|
`question_${interaction!.id}`,
|
|
);
|
|
});
|
|
});
|