fix(runner): retain provider sessions and send only new continuation events

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-18 22:05:48 -05:00
1 parent 4197c9f9c0
commit 3c66c65f9c
14 files changed
+251 -15

No files matched your search

+20 -3
View File
@@ -21642,6 +21642,11 @@ export function heartbeatService(
selectedEnvironmentForConfig?.driver === "sandbox" &&
selectedEnvironmentConfigForFingerprint.reuseLease === true &&
selectedEnvironmentConfigForFingerprint.runnerLifecycleMode === "warm";
// Native provider checkpoints bind to the workspace row, including ordinary
// local shared workspaces. Persist that binding independently of the opt-in
// isolated-workspace UI, just as warm sandbox continuity already does.
const nativeSharedWorkspace = agent.adapterType === "paperclip_runner" &&
requestedExecutionWorkspaceMode === "shared_workspace";
const bindIssueToPersistedExecutionWorkspace = async (
workspace: ExecutionWorkspace | null,
) => {
@@ -21655,7 +21660,7 @@ export function heartbeatService(
issueRef?.executionWorkspacePreference === "reuse_existing" ||
requestedExecutionWorkspaceMode === "isolated_workspace" ||
requestedExecutionWorkspaceMode === "operator_branch" ||
warmReusableExecutionWorkspace;
warmReusableExecutionWorkspace || nativeSharedWorkspace;
const nextIssuePatch: Record<string, unknown> = {};
if (issueExecutionWorkspaceIdForRun !== workspace.id) {
nextIssuePatch.executionWorkspaceId = workspace.id;
@@ -21684,7 +21689,7 @@ export function heartbeatService(
db,
undefined,
undefined,
{ bindRuntimeSharedWorkspace: warmReusableExecutionWorkspace && workspace.mode === "shared_workspace" },
{ bindRuntimeSharedWorkspace: (warmReusableExecutionWorkspace || nativeSharedWorkspace) && workspace.mode === "shared_workspace" },
);
issueExecutionWorkspaceIdForRun = workspace.id;
issueProjectWorkspaceIdForRun =
@@ -23294,7 +23299,7 @@ export function heartbeatService(
taskPrompt: [
nativeReviewRequest ?? readNonEmptyString(
selectPaperclipTaskMarkdown(context, {
resumedSession,
resumedSession: false,
}),
) ??
`# ${issueRef.identifier ?? issueRef.id}: ${issueRef.title}`,
@@ -23304,6 +23309,18 @@ export function heartbeatService(
].filter(Boolean).join("\n\n"),
wakePayload: context.paperclipWake,
resumedSession,
previousTurn: (() => {
if (!previousNativeRun || nativeReviewRequest) return null;
try {
return {
runId: previousNativeRun.id,
task: parseNativeExecutionInput(parseObject(previousNativeRun.runnerProfileJson).nativeExecutionInput).task,
};
} catch {
// An invalid prior snapshot must use the fresh bootstrap.
return null;
}
})(),
conversationMode: context.conversationMode === true,
agentId: agent.id,
workspace: {
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { buildNativeContinuationPrompt } from "./native-continuation.js";
const issue = { title: "Original task", description: "Retain my long task brief." };
const message = { id: "new", body: "Yes, please proceed.", authorType: "user", authorId: "board", sourceTrust: "user", createdByRunId: null };
const wake = {
reason: "issue_commented",
executionContinuation: {
version: 1,
objective: message.body,
messages: [{ ...message, id: "old", body: "OLD_HISTORY" }, message],
resumeDelta: { baseRunId: "prior", messages: [message] },
completedWork: { summary: "OLD_SUMMARY" },
humanResponses: [{ id: "old-question", result: { answer: "OLD_ANSWER" } }],
},
comments: [message], continuationSummary: { markdown: "OLD_SUMMARY" },
};
const build = (value: unknown = wake, previousIssue = issue) => buildNativeContinuationPrompt({ wakePayload: value, previousRunId: "prior", issue, previousIssue });
describe("native continuation event projection", () => {
it("sends a new comment once without the unchanged brief, objective, history or summary", () => {
const text = build()!;
expect(text.split(message.body)).toHaveLength(2);
for (const old of [issue.description, issue.title, "OLD_HISTORY", "OLD_SUMMARY", "OLD_ANSWER"]) expect(text).not.toContain(old);
expect(JSON.parse(text).messages[0]).toMatchObject({ authorType: "user", body: message.body });
expect(text.length).toBeLessThan(600);
});
it("only uses a delta whose base matches the actual previous run", () => {
expect(build({ ...wake, executionContinuation: { ...wake.executionContinuation, resumeDelta: { baseRunId: "different", messages: [message] } } })).toBeNull();
expect(build({ ...wake, executionContinuation: null })).toBeNull();
});
it("delivers the current authenticated answer once, not all prior answers", () => {
const text = build({ ...wake, interactionId: "new-question", executionContinuation: { ...wake.executionContinuation, resumeDelta: { baseRunId: "prior", messages: [] }, humanResponses: [...wake.executionContinuation.humanResponses, { id: "new-question", kind: "ask_user_questions", status: "answered", resolvedByUserId: "board", result: { answer: "NEW_ANSWER" } }] } })!;
expect(text.split("NEW_ANSWER")).toHaveLength(2);
expect(text).not.toContain("OLD_ANSWER");
expect(JSON.parse(text).humanResponses[0].resolvedByUserId).toBe("board");
});
it("includes external child completion and actual brief edits", () => {
const text = build({ ...wake, reason: "issue_children_completed", childIssueSummaries: [{ id: "child", status: "done", summary: "CHILD_RESULT" }] }, { ...issue, description: "old brief" })!;
expect(JSON.parse(text).taskChanges).toEqual({ description: issue.description });
expect(text).toContain("CHILD_RESULT");
});
it.each([{ fallbackFetchNeeded: true }, { recovery: { cause: "interrupted" } }, { externalChatExecutionBound: true }, { reason: "issue_assigned" }])("retains bootstrap framing for special wakes: %j", (extra) => {
expect(build({ ...wake, ...extra })).toBeNull();
});
});
@@ -0,0 +1,43 @@
import { normalizePaperclipWakePayload } from "@paperclipai/adapter-utils/server-utils";
/** Only new, authorized events belong in an already retained provider conversation.
* Full bootstrap input is kept separately for an actual provider resume failure.
*/
export function buildNativeContinuationPrompt(input: {
wakePayload: unknown;
previousRunId: string;
issue: { title: string; description: string | null };
previousIssue: { title: string; description: string | null };
}): string | null {
const wake = normalizePaperclipWakePayload(input.wakePayload);
const continuation = wake?.executionContinuation;
const delta = continuation?.resumeDelta;
if (!wake || !delta || delta.baseRunId !== input.previousRunId) return null;
// These paths have specialized delivery/recovery contracts. Preserve their
// existing framing until they have an event-specific continuation projection.
if (!['issue_commented', 'issue_children_completed'].includes(wake.reason ?? '') ||
wake.fallbackFetchNeeded || wake.truncated || wake.recovery || continuation?.interruptedRunId ||
wake.externalChatExecutionBound || wake.externalChatQuestionResponse ||
wake.taskWatchdog || wake.livenessContinuation || wake.activeTreeHold ||
wake.skillTest || wake.executionStage || wake.agentMessage ||
wake.documentReviewContext || wake.planReviewContext || wake.annotationDeltas.length > 0
) return null;
const taskChanges = Object.fromEntries(
(["title", "description"] as const)
.filter((key) => input.issue[key] !== input.previousIssue[key])
.map((key) => [key, input.issue[key]]),
);
const humanResponses = (continuation?.humanResponses ?? []).filter((answer) => answer.id === wake.interactionId);
// Do not substitute an unverified interaction outcome for an authorized answer.
if (wake.interactionId && humanResponses.length === 0) return null;
const events = {
messages: delta.messages,
...(humanResponses.length ? { humanResponses } : {}),
...(Object.keys(taskChanges).length ? { taskChanges } : {}),
...(wake.childIssueSummaries.length ? { childResults: wake.childIssueSummaries } : {}),
...(wake.childIssueSummaryTruncated ? { childResultsTruncated: true } : {}),
...(wake.unresolvedBlockerIssueIds.length ? { unresolvedBlockerIssueIds: wake.unresolvedBlockerIssueIds } : {}),
};
if (!events.messages.length && !humanResponses.length && !wake.childIssueSummaries.length && !Object.keys(taskChanges).length) return null;
return JSON.stringify(events);
}
@@ -1,3 +1,4 @@
import { buildNativeContinuationPrompt } from "./native-continuation.js";
import type {
NativeAcpxAgent,
NativeAcpxPermissionMode,
@@ -45,6 +46,7 @@ export function buildNativeExecutionInput(input: {
*/
wakePayload?: unknown;
resumedSession?: boolean;
previousTurn?: { runId: string; task: { title: string; description: string | null } } | null;
conversationMode?: boolean;
agentId: string;
workspace: {
@@ -146,7 +148,7 @@ export function buildNativeExecutionInput(input: {
}
: input.wakePayload;
const wakePrompt = renderPaperclipWakePrompt(wakePayload, {
resumedSession: input.resumedSession === true,
resumedSession: false,
conversationMode: input.conversationMode === true,
suppressIssueDescription: input.taskPrompt.trim().length > 0,
nativeWakeReaderAvailable: true,
@@ -168,6 +170,14 @@ export function buildNativeExecutionInput(input: {
.join("\n\n");
return parseNativeExecutionInput({
schema: "paperclip.native-execution-input.v4",
...(input.resumedSession && input.previousTurn && !input.conversationMode ? {
continuationPrompt: buildNativeContinuationPrompt({
wakePayload: input.wakePayload,
previousRunId: input.previousTurn.runId,
previousIssue: input.previousTurn.task,
issue: input.issue,
}),
} : {}),
executionMode,
planningContext: input.planningContext ?? null,
binding: {
@@ -2598,9 +2598,10 @@ describe("buildNativeExecutionInput wake projection", () => {
runtimeContext: nativeRuntimeContextFixture(),
});
expect(input.task.prompt.includes("Execution contract:")).toBe(!conversationMode);
expect(input.task.prompt.includes("Use child issues")).toBe(!conversationMode);
expect(input.task.prompt).toContain("## Paperclip Resume Delta");
expect(input.task.prompt).not.toContain("Execution contract:");
expect(input.task.prompt).not.toContain("Use child issues");
// Full bootstrap stays available if provider recovery fails after admission.
expect(input.task.prompt).toContain("## Paperclip Wake Payload");
expect(input.task.prompt).toContain("reason: issue_children_completed");
expect(input.task.prompt).toContain("DOT-147 Build utility (done)");
expect(input.task.prompt).toContain(