mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 20:09:10 +01:00
fix(runner): keep the OpenCode session event stream open across turns (#14582)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Runner keeps provider sessions and their event streams for agent runs > - The OpenCode driver closed its event queue after each terminal turn > - A second turn on the same session then lost its response and completion events > - This pull request keeps the queue open between turns and rejects late events for sealed turns > - The benefit is reliable multi-turn OpenCode sessions with visible diagnostics for late provider events ## Linked Issues or Issue Description **What happened?** The OpenCode driver closed its event queue when a turn completed, was cancelled, or failed. A second turn on the same session then lost its response and completion events. **Expected behavior** The session must keep its event stream open between turns. Each turn must deliver its response and one terminal event. The session must close the stream only during session shutdown or an unrecoverable pump error. **Steps to reproduce** 1. Start one OpenCode session. 2. Run one turn and wait for its terminal event. 3. Run a second turn on the same session. 4. Confirm that the second turn delivers its response and terminal event. **Paperclip version or commit** `c0e1d87ddc181329471fa80a2061b2c538bb6618` **Deployment mode** Built from source with the Paperclip Runner package test suite. ## What Changed - Keep the OpenCode event queue open across completed, cancelled, and failed turns. - Track sealed turn ids and reject later events for those turns with a diagnostic event. - Preserve queue shutdown on session close and unrecoverable pump errors. - Give each simulated fixture turn unique provider event ids. - Add regression tests for completed, cancelled, failed, and closed-session paths. ## Verification - Type check: `cd packages/paperclip-runner && node ./node_modules/typescript/bin/tsc -p tsconfig.json --noEmit` passed. - Driver tests: `cd packages/paperclip-runner && npx vitest run src/drivers/opencode/opencode-server-driver.test.ts` passed except for the known pre-existing flaky test described below. - Consumer tests: `cd packages/paperclip-runner && npx vitest run src/native-session-runtime.test.ts src/backends/harness-driver-backend.test.ts src/cli/opencode-app-server-proxy.test.ts src/conformance/harness-driver.test.ts` passed. - The known flaky test reproduced on unmodified `master` because fixture event order depends on a local MCP HTTP round-trip. - CI must run the full pull request suite. ## Risks - The queue now retains sealed turn ids for the session lifetime. OpenCode does not reuse turn ids, so this set grows with the session. - A late provider event cannot reach a later turn. The driver emits a diagnostic event so the rejection remains visible. - The change does not alter session shutdown or unrecoverable pump error handling. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. This pull request fixes an OpenCode Runner bug and does not add a roadmap feature. ## Model Used OpenAI Codex, GPT-5, tool use and code execution; Anthropic Claude Sonnet 5 also assisted with the implementation. The runtime did not provide a context window size. ## 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 #` / `Refs #` 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:
1 parent
f38b5693f6
commit
eb31b926a1
3 files changed
+533
-31
No files matched your search
@@ -23,6 +23,7 @@ import {
|
||||
} from "../../contracts/runtime-context.js";
|
||||
import { createCodexTaskEnvelope } from "../../contracts/codex.js";
|
||||
import { localIntegrityBoundaryGolden } from "../../../test-support/local-integrity-boundary-golden.js";
|
||||
import type { PrpEvent } from "../../protocol/replay-contract.js";
|
||||
import {
|
||||
OpenCodeServerDriver,
|
||||
openCodeServerDriverInternals,
|
||||
@@ -31,6 +32,29 @@ import {
|
||||
const roots: string[] = [];
|
||||
const fixture = resolve("test/fixtures/fake-opencode-server.mjs");
|
||||
|
||||
const TURN_TERMINAL_EVENT_TYPES = new Set([
|
||||
"turn.completed",
|
||||
"turn.failed",
|
||||
"turn.interrupted",
|
||||
"turn.cancelled",
|
||||
]);
|
||||
|
||||
/**
|
||||
* The session event stream stays open past a turn boundary so a session can
|
||||
* run more turns. Read one turn's events by stopping at its terminal event,
|
||||
* the same rule the production consumer applies.
|
||||
*/
|
||||
async function collectTurnEvents(
|
||||
events: AsyncIterable<PrpEvent>,
|
||||
): Promise<PrpEvent[]> {
|
||||
const collected: PrpEvent[] = [];
|
||||
for await (const event of events) {
|
||||
collected.push(event);
|
||||
if (TURN_TERMINAL_EVENT_TYPES.has(event.eventType)) break;
|
||||
}
|
||||
return collected;
|
||||
}
|
||||
|
||||
function runtimeContext(
|
||||
skillRoot: string,
|
||||
instructionRoot: string,
|
||||
@@ -397,6 +421,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
const next = await iterator.next();
|
||||
if (next.done) break;
|
||||
events.push(next.value);
|
||||
if (TURN_TERMINAL_EVENT_TYPES.has(next.value.eventType)) break;
|
||||
}
|
||||
await session.close({ reason: "boundary-golden-test" });
|
||||
|
||||
@@ -623,8 +648,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
const turn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
expect(events.map((event) => event.eventType)).toContain("turn.completed");
|
||||
expect(events).toContainEqual(
|
||||
expect.objectContaining({ eventType: "run.result.proposed" }),
|
||||
@@ -790,8 +814,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "session-aborted" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
expect(events.map((event) => event.eventType)).toContain("turn.cancelled");
|
||||
expect(events.map((event) => event.eventType)).not.toContain("turn.failed");
|
||||
expect(events.map((event) => event.eventType)).not.toContain(
|
||||
@@ -800,6 +823,332 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("runs two consecutive turns on one session and delivers exactly one terminal event per turn", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-multi-turn-"));
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-multi-turn-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-multi-turn",
|
||||
normalizedSessionId: "multi-turn",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
const firstTurn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
const firstTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
firstTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: firstTurn.turnId }]);
|
||||
expect(
|
||||
firstTurnEvents.find(
|
||||
(event) =>
|
||||
event.eventType === "item.completed" &&
|
||||
event.payload.kind === "agentMessage",
|
||||
)?.payload,
|
||||
).toMatchObject({ text: "done [guide](guide.md)" });
|
||||
|
||||
const secondTurn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
expect(secondTurn.turnId).not.toBe(firstTurn.turnId);
|
||||
const secondTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
secondTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: secondTurn.turnId }]);
|
||||
expect(
|
||||
secondTurnEvents.find(
|
||||
(event) =>
|
||||
event.eventType === "item.completed" &&
|
||||
event.payload.kind === "agentMessage",
|
||||
)?.payload,
|
||||
).toMatchObject({ text: "done [guide](guide.md)" });
|
||||
expect(
|
||||
secondTurnEvents.some((event) => event.turnId === firstTurn.turnId),
|
||||
).toBe(false);
|
||||
expect(
|
||||
secondTurnEvents.some((event) => event.eventType === "harness.diagnostic"),
|
||||
).toBe(false);
|
||||
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("drops a distinct late frame for a completed turn instead of attributing it to the next turn", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-late-frame-"),
|
||||
);
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-late-frame-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-late-frame",
|
||||
normalizedSessionId: "late-frame",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
const firstTurn = await session.startTurn({
|
||||
message: { role: "user", text: "late-straggler-source" },
|
||||
});
|
||||
const firstTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
firstTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: firstTurn.turnId }]);
|
||||
|
||||
// The fixture holds a distinct frame for the first turn's message and
|
||||
// delivers it only once this second turn's prompt has been accepted,
|
||||
// simulating a provider frame that arrives after its own turn is
|
||||
// already sealed.
|
||||
const secondTurn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
expect(secondTurn.turnId).not.toBe(firstTurn.turnId);
|
||||
const secondTurnEvents = await collectTurnEvents(session.events());
|
||||
|
||||
expect(
|
||||
secondTurnEvents.some((event) =>
|
||||
JSON.stringify(event.payload).includes(
|
||||
"late straggler text must not reach the next turn",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
secondTurnEvents.some((event) => event.turnId === firstTurn.turnId),
|
||||
).toBe(false);
|
||||
expect(
|
||||
secondTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: secondTurn.turnId }]);
|
||||
expect(
|
||||
secondTurnEvents.find(
|
||||
(event) => event.eventType === "harness.diagnostic",
|
||||
)?.payload,
|
||||
).toMatchObject({
|
||||
code: "opencode_late_terminal_turn_event_dropped",
|
||||
turnId: firstTurn.turnId,
|
||||
});
|
||||
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("keeps rejecting a late frame for a sealed turn no matter how many later turns have already sealed", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-sealed-many-turns-"),
|
||||
);
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-sealed-many-turns-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-sealed-many-turns",
|
||||
normalizedSessionId: "sealed-many-turns",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
// Turn A schedules its own late frame to arrive four prompts later, so
|
||||
// it lands only after three more turns have sealed. The late-frame gate
|
||||
// in `#emit` compares directly against the current active turn, not a
|
||||
// bounded history, so it must still reject this frame no matter how
|
||||
// many turns sealed in between.
|
||||
const turnA = await session.startTurn({
|
||||
message: { role: "user", text: "late-straggler-source-delay-4" },
|
||||
});
|
||||
await collectTurnEvents(session.events());
|
||||
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
await session.startTurn({ message: { role: "user", text: "finish" } });
|
||||
await collectTurnEvents(session.events());
|
||||
}
|
||||
|
||||
// This turn's prompt request is what finally delivers turn A's scheduled
|
||||
// late frame, well after turn A's own turn sealed.
|
||||
const turnE = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
const turnEEvents = await collectTurnEvents(session.events());
|
||||
|
||||
expect(
|
||||
turnEEvents.some((event) =>
|
||||
JSON.stringify(event.payload).includes(
|
||||
"late straggler text must not reach the next turn",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(turnEEvents.some((event) => event.turnId === turnA.turnId)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
turnEEvents.find((event) => event.eventType === "harness.diagnostic")
|
||||
?.payload,
|
||||
).toMatchObject({
|
||||
code: "opencode_late_terminal_turn_event_dropped",
|
||||
turnId: turnA.turnId,
|
||||
});
|
||||
expect(
|
||||
turnEEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: turnE.turnId }]);
|
||||
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("keeps the session usable after a cancelled turn so the next turn on the same session still completes", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-cancel-then-finish-"),
|
||||
);
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-cancel-then-finish-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-cancel-then-finish",
|
||||
normalizedSessionId: "cancel-then-finish",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
const cancelledTurn = await session.startTurn({
|
||||
message: { role: "user", text: "session-aborted" },
|
||||
});
|
||||
const cancelledTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
cancelledTurnEvents.filter(
|
||||
(event) => event.eventType === "turn.cancelled",
|
||||
),
|
||||
).toMatchObject([{ turnId: cancelledTurn.turnId }]);
|
||||
|
||||
const secondTurn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
const secondTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
secondTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: secondTurn.turnId }]);
|
||||
expect(
|
||||
secondTurnEvents.some((event) => event.turnId === cancelledTurn.turnId),
|
||||
).toBe(false);
|
||||
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("keeps the session usable after a failed turn so the next turn on the same session still completes", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-fail-then-finish-"),
|
||||
);
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-fail-then-finish-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-fail-then-finish",
|
||||
normalizedSessionId: "fail-then-finish",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
const failedTurn = await session.startTurn({
|
||||
message: { role: "user", text: "session-failed" },
|
||||
});
|
||||
const failedTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
failedTurnEvents.filter((event) => event.eventType === "turn.failed"),
|
||||
).toMatchObject([{ turnId: failedTurn.turnId }]);
|
||||
|
||||
const secondTurn = await session.startTurn({
|
||||
message: { role: "user", text: "finish" },
|
||||
});
|
||||
const secondTurnEvents = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
secondTurnEvents.filter((event) => event.eventType === "turn.completed"),
|
||||
).toMatchObject([{ turnId: secondTurn.turnId }]);
|
||||
expect(
|
||||
secondTurnEvents.some((event) => event.turnId === failedTurn.turnId),
|
||||
).toBe(false);
|
||||
|
||||
await session.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("still ends the event stream once the session closes", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-close-ends-stream-"),
|
||||
);
|
||||
const workspace = await mkdtemp(
|
||||
join(tmpdir(), "paperclip-opencode-close-ends-stream-workspace-"),
|
||||
);
|
||||
roots.push(root, workspace);
|
||||
const driver = new OpenCodeServerDriver({
|
||||
model: "openrouter/deepseek/deepseek-v4-flash-0731",
|
||||
runtimeDirectory: root,
|
||||
command: fixture,
|
||||
environment: {
|
||||
PATH: process.env.PATH,
|
||||
OPENROUTER_API_KEY: "fixture-key",
|
||||
},
|
||||
});
|
||||
const session = await driver.openSession({
|
||||
runId: "run-close-ends-stream",
|
||||
normalizedSessionId: "close-ends-stream",
|
||||
workingDirectory: workspace,
|
||||
});
|
||||
|
||||
await session.startTurn({ message: { role: "user", text: "finish" } });
|
||||
await collectTurnEvents(session.events());
|
||||
await session.close({ reason: "test" });
|
||||
|
||||
const eventsAfterClose: PrpEvent[] = [];
|
||||
for await (const event of session.events()) eventsAfterClose.push(event);
|
||||
expect(eventsAfterClose).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps OpenCode in an outer supervisor process group when requested", async () => {
|
||||
await chmod(fixture, 0o755);
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-driver-"));
|
||||
@@ -1464,8 +1813,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
const driver = new OpenCodeServerDriver({ model: "openrouter/deepseek/deepseek-v4-flash-0731", runtimeDirectory: root, command: fixture, environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "fixture-key" }, taskEnvelope: createCodexTaskEnvelope({ objective: "Apply the accepted decision", contractRevision: "approval-v2", criteria: [{ id: "human_response", requirement: "Apply the approved response" }] }) });
|
||||
const session = await driver.openSession({ runId: "criteria-repair", normalizedSessionId: "criteria-repair", workingDirectory: workspace });
|
||||
await session.startTurn({ message: { role: "user", text: `repair-criteria-${mode}` } });
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
const results = events.filter((event) => event.eventType === "run.result.proposed");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(events.some((event) => event.eventType === "item.completed" &&
|
||||
@@ -1502,8 +1850,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "block-result" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
events.find((event) => event.eventType === "run.result.proposed")
|
||||
?.payload,
|
||||
@@ -1538,8 +1885,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "text-before-finish" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
const finalMessages = events.filter(
|
||||
(event) =>
|
||||
event.eventType === "item.completed" &&
|
||||
@@ -1584,8 +1930,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "commentary-only-before-work" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
expect(
|
||||
events.filter(
|
||||
(event) =>
|
||||
@@ -1629,8 +1974,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "correlated-final-message" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
const finalMessages = events.filter(
|
||||
(event) =>
|
||||
event.eventType === "item.completed" &&
|
||||
@@ -1714,8 +2058,7 @@ describe("OpenCodeServerDriver", () => {
|
||||
await session.startTurn({
|
||||
message: { role: "user", text: "final-after-tool-commentary" },
|
||||
});
|
||||
const events = [];
|
||||
for await (const event of session.events()) events.push(event);
|
||||
const events = await collectTurnEvents(session.events());
|
||||
const finalMessages = events.filter(
|
||||
(event) =>
|
||||
event.eventType === "item.completed" &&
|
||||
|
||||
@@ -384,6 +384,12 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
readonly #transcript: PrpEvent[] = [];
|
||||
readonly #terminalTurns = new Map<string, string>();
|
||||
readonly #seenProviderEvents = new Set<string>();
|
||||
// The turn that created each native message. A raw OpenCode frame carries
|
||||
// no turn identity of its own, so this map — not the mutable active-turn
|
||||
// pointer, which can already have moved on to a later turn by the time a
|
||||
// straggling frame for this message arrives — is the source of truth for
|
||||
// which turn a message's content belongs to.
|
||||
readonly #messageTurnIds = new Map<string, string>();
|
||||
readonly #messageRoles = new Map<string, string>();
|
||||
readonly #pendingMessageParts = new Map<
|
||||
string,
|
||||
@@ -467,8 +473,9 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
this.#resultFingerprint = restored?.fingerprint ?? null;
|
||||
this.#resultCallId = restored?.callId ?? null;
|
||||
this.#resultTurnId = restored?.turnId ?? null;
|
||||
for (const terminal of input.snapshot?.terminalTurns ?? [])
|
||||
for (const terminal of input.snapshot?.terminalTurns ?? []) {
|
||||
this.#terminalTurns.set(terminal.turnId, terminal.fingerprint);
|
||||
}
|
||||
if (this.#activeTurnId && this.#terminalTurns.has(this.#activeTurnId)) {
|
||||
this.#activeTurnId = null;
|
||||
}
|
||||
@@ -523,6 +530,10 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
this.#completedTextPartIds.clear();
|
||||
this.#completedReasoningPartIds.clear();
|
||||
this.#completedTextParts.length = 0;
|
||||
// `#terminalTurns` clears here for its own persisted-snapshot bookkeeping.
|
||||
// The late-frame gate in `#emit` does not depend on this map: it compares
|
||||
// against `#activeTurnId` directly, so a frame for the just-finished turn
|
||||
// stays blocked even after this new run attaches (see `#emit`).
|
||||
this.#terminalTurns.clear();
|
||||
this.#sendFullContext = false;
|
||||
this.#emit("run.attached", { runId: input.runId, sameSession: true });
|
||||
@@ -1375,7 +1386,7 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
"runtime_request.resolved",
|
||||
harnessRuntimeRequestOutcome(pending.request, { action }),
|
||||
{
|
||||
turnId,
|
||||
turnId: pending.request.turnId,
|
||||
itemId: pending.request.itemId,
|
||||
},
|
||||
);
|
||||
@@ -1402,16 +1413,21 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
? { action: "submit", response: pending.submittedResponse }
|
||||
: { reason: "provider_rejected" },
|
||||
),
|
||||
{ turnId, itemId: pending.request.itemId },
|
||||
{ turnId: pending.request.turnId, itemId: pending.request.itemId },
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (type === "message.part.updated" && turnId) {
|
||||
if (type === "message.part.updated") {
|
||||
const part = record(properties.part);
|
||||
const messageId = text(part.messageID, text(part.messageId));
|
||||
if (!messageId) return;
|
||||
// Resolve the turn this message actually belongs to, not whichever
|
||||
// turn is active right now. A straggling part for an earlier message
|
||||
// must stay attributed to the turn that created that message.
|
||||
const owningTurnId = this.#messageTurnIds.get(messageId) ?? turnId;
|
||||
if (!owningTurnId) return;
|
||||
const role = this.#messageRoles.get(messageId);
|
||||
if (role === "assistant") this.#emitAssistantPart(part, turnId);
|
||||
if (role === "assistant") this.#emitAssistantPart(part, owningTurnId);
|
||||
else if (role === undefined) {
|
||||
const pending = this.#pendingMessageParts.get(messageId) ?? [];
|
||||
if (pending.length < 100) pending.push(part);
|
||||
@@ -1419,19 +1435,29 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (type === "message.updated" && turnId) {
|
||||
if (type === "message.updated") {
|
||||
const info = record(properties.info);
|
||||
const messageId = text(
|
||||
info.id,
|
||||
text(info.messageID, text(info.messageId)),
|
||||
);
|
||||
const role = text(info.role);
|
||||
// Record the message's owning turn at the moment OpenCode first
|
||||
// reports it. A later turn that reuses the same native message id
|
||||
// legitimately reclaims ownership; a stale message never sees this
|
||||
// branch again, so its recorded owner never changes.
|
||||
if (messageId && role && turnId) this.#messageTurnIds.set(messageId, turnId);
|
||||
const owningTurnId = messageId
|
||||
? (this.#messageTurnIds.get(messageId) ?? turnId)
|
||||
: turnId;
|
||||
if (!owningTurnId) return;
|
||||
if (messageId && role) {
|
||||
this.#messageRoles.set(messageId, role);
|
||||
const pending = this.#pendingMessageParts.get(messageId) ?? [];
|
||||
this.#pendingMessageParts.delete(messageId);
|
||||
if (role === "assistant")
|
||||
for (const part of pending) this.#emitAssistantPart(part, turnId);
|
||||
for (const part of pending)
|
||||
this.#emitAssistantPart(part, owningTurnId);
|
||||
}
|
||||
const tokens = record(info.tokens);
|
||||
if (
|
||||
@@ -1457,7 +1483,7 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
this.#emit(
|
||||
"item.completed",
|
||||
{ kind: "usage", usage: this.#usage, usageMessageId: messageId },
|
||||
{ turnId, itemId: `${turnId}:usage` },
|
||||
{ turnId: owningTurnId, itemId: `${owningTurnId}:usage` },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1482,9 +1508,11 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
{ ...workspace, complete: true },
|
||||
{ turnId, itemId: `${turnId}:workspace` },
|
||||
);
|
||||
this.#activeTurnId = null;
|
||||
// Emit while this turn is still `#activeTurnId`; the gate in `#emit`
|
||||
// drops any frame whose turnId is not the active turn, so nulling it
|
||||
// first would make `#emit` drop this very event.
|
||||
this.#emit("turn.completed", { status: "completed" }, { turnId });
|
||||
this.#events.close();
|
||||
this.#activeTurnId = null;
|
||||
return;
|
||||
}
|
||||
if (type === "session.error" && turnId) {
|
||||
@@ -1502,7 +1530,6 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
// card. Preserve the provider fact as a cancelled terminal event; the
|
||||
// native session loop independently commits the authoritative yielded
|
||||
// result when this abort followed a governed wait.
|
||||
this.#activeTurnId = null;
|
||||
this.#emit(
|
||||
"turn.cancelled",
|
||||
{
|
||||
@@ -1512,7 +1539,7 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
{ turnId },
|
||||
);
|
||||
this.#terminalTurns.set(turnId, canonicalJson({ status: "cancelled" }));
|
||||
this.#events.close();
|
||||
this.#activeTurnId = null;
|
||||
return;
|
||||
}
|
||||
this.#emit(
|
||||
@@ -1532,14 +1559,13 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
},
|
||||
{ turnId, itemId: `${turnId}:session-error` },
|
||||
);
|
||||
this.#activeTurnId = null;
|
||||
this.#emit(
|
||||
"turn.failed",
|
||||
{ status: "failed", error: bounded(properties.error ?? properties) },
|
||||
{ turnId },
|
||||
);
|
||||
this.#terminalTurns.set(turnId, canonicalJson({ status: "failed" }));
|
||||
this.#events.close();
|
||||
this.#activeTurnId = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1804,6 +1830,29 @@ class OpenCodeHarnessSession implements HarnessSession {
|
||||
payload: Record<string, unknown>,
|
||||
refs: { turnId?: string; itemId?: string } = {},
|
||||
): void {
|
||||
if (
|
||||
eventType !== "harness.diagnostic" &&
|
||||
refs.turnId !== undefined &&
|
||||
refs.turnId !== this.#activeTurnId
|
||||
) {
|
||||
// The provider sent this frame for a turn that is not the current
|
||||
// active turn, so that turn already reached a terminal state: turns
|
||||
// run strictly one at a time (`startTurn` and `attachRun` both refuse
|
||||
// to proceed while `#activeTurnId` is set), and a turn id is never
|
||||
// reused. Comparing directly against `#activeTurnId` needs no history
|
||||
// of past turns, so the gate stays correct and its memory stays O(1)
|
||||
// no matter how many turns a long-lived session runs. The queue stays
|
||||
// open across turns, so a silent drop here would let a stale frame
|
||||
// reach the next turn's consumer. Report it instead of discarding it
|
||||
// without a trace.
|
||||
this.#emit("harness.diagnostic", {
|
||||
code: "opencode_late_terminal_turn_event_dropped",
|
||||
message: `OpenCode sent a ${eventType} event for a turn that already reached a terminal state.`,
|
||||
droppedEventType: eventType,
|
||||
turnId: refs.turnId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const sourceSeq = ++this.#sourceSequence;
|
||||
const event: PrpEvent = {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
|
||||
@@ -108,8 +108,27 @@ function json(response, status, value) {
|
||||
response.end(JSON.stringify(value));
|
||||
}
|
||||
|
||||
// Each simulated turn reuses the same short event ids ("event-1",
|
||||
// "event-3", and so on). OpenCode's real event ids are unique, and the
|
||||
// driver relies on that to drop a duplicate delivery of the same event.
|
||||
// Scope every event id to the turn that produced it so a second turn's
|
||||
// events do not look like duplicates of the first turn's events.
|
||||
let promptTurnSeq = 0;
|
||||
// Set by a "late-straggler-source" turn to simulate a distinct provider
|
||||
// frame for that turn's message arriving only after a later turn's prompt
|
||||
// has already been accepted. Counts down by one on each subsequent prompt
|
||||
// request and flushes at the start of the request that brings it to zero.
|
||||
// A plain "late-straggler-source" message flushes on the very next prompt
|
||||
// (delay 1); "late-straggler-source-delay-N" flushes N prompts later, so a
|
||||
// test can place the stale frame's arrival after several more turns have
|
||||
// sealed.
|
||||
let lateStragglerRemaining = 0;
|
||||
function emit(value) {
|
||||
const frame = `data: ${JSON.stringify(value)}\n\n`;
|
||||
const scoped =
|
||||
promptTurnSeq > 0 && typeof value.id === "string"
|
||||
? { ...value, id: `${value.id}#${promptTurnSeq}` }
|
||||
: value;
|
||||
const frame = `data: ${JSON.stringify(scoped)}\n\n`;
|
||||
for (const response of clients) response.write(frame);
|
||||
}
|
||||
|
||||
@@ -381,7 +400,27 @@ const server = createServer(async (request, response) => {
|
||||
error: "OpenCode 1.18 prompt model fields must be top-level",
|
||||
});
|
||||
}
|
||||
promptTurnSeq += 1;
|
||||
json(response, 204, null);
|
||||
if (lateStragglerRemaining > 0) {
|
||||
lateStragglerRemaining -= 1;
|
||||
if (lateStragglerRemaining === 0) {
|
||||
emit({
|
||||
type: "message.part.updated",
|
||||
id: "event-late-straggler-delivery",
|
||||
properties: {
|
||||
sessionID: session.id,
|
||||
part: {
|
||||
id: "part-late-straggler",
|
||||
messageID: "message-late-source",
|
||||
type: "text",
|
||||
text: "late straggler text must not reach the next turn",
|
||||
time: { start: 9, end: 10 },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
setTimeout(async () => {
|
||||
await callFirstPaperclipTool();
|
||||
const parsedPrompt = parsedPromptText(promptPayload);
|
||||
@@ -430,6 +469,77 @@ const server = createServer(async (request, response) => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (String(parsedPrompt.message ?? "").includes("session-failed")) {
|
||||
emit({
|
||||
type: "session.error",
|
||||
id: "event-session-failed",
|
||||
properties: {
|
||||
sessionID: session.id,
|
||||
error: {
|
||||
name: "ProviderError",
|
||||
message: "The fake provider failed on purpose.",
|
||||
},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
String(parsedPrompt.message ?? "").includes("late-straggler-source")
|
||||
) {
|
||||
emit({
|
||||
type: "message.updated",
|
||||
id: "event-late-source-message",
|
||||
properties: {
|
||||
sessionID: session.id,
|
||||
info: {
|
||||
id: "message-late-source",
|
||||
sessionID: session.id,
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
});
|
||||
await callTerminalTool(promptPayload);
|
||||
emit({
|
||||
type: "message.part.updated",
|
||||
id: "event-late-source-part",
|
||||
properties: {
|
||||
sessionID: session.id,
|
||||
part: {
|
||||
id: "part-late-source",
|
||||
messageID: "message-late-source",
|
||||
type: "text",
|
||||
text: "done",
|
||||
time: { start: 1, end: 2 },
|
||||
},
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "message.updated",
|
||||
id: "event-late-source-usage",
|
||||
properties: {
|
||||
info: {
|
||||
id: "message-late-source",
|
||||
sessionID: session.id,
|
||||
role: "assistant",
|
||||
tokens: { input: 3, output: 2 },
|
||||
cost: 0.001,
|
||||
},
|
||||
},
|
||||
});
|
||||
emit({
|
||||
type: "session.idle",
|
||||
id: "event-late-source-idle",
|
||||
properties: { sessionID: session.id },
|
||||
});
|
||||
// Deliver the straggling frame for this message only once a later
|
||||
// turn's own prompt has already been accepted. Defaults to the
|
||||
// very next prompt; "-delay-N" postpones it by N prompts.
|
||||
const delayMatch = String(parsedPrompt.message ?? "").match(
|
||||
/late-straggler-source-delay-(\d+)/,
|
||||
);
|
||||
lateStragglerRemaining = delayMatch ? Number(delayMatch[1]) : 1;
|
||||
return;
|
||||
}
|
||||
const textBeforeFinish = String(parsedPrompt.message ?? "").includes(
|
||||
"text-before-finish",
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user