:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(agent): defer prewarmed resume until user message (#85443)
Georgiy Tarasove143611db0f1
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.tsindex 0d8b6ee3cf38..c2c0818f1ffb 100644--- a/products/desktop/packages/agent/src/server/agent-server.test.ts+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts@@ -29,6 +29,7 @@ import {import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";import { getSessionJsonlPath } from "../adapters/claude/session/jsonl-hydration";import type { PermissionMode } from "../execution-mode";+import { HandoffCheckpointTracker } from "../handoff-checkpoint";import type { PostHogAPIClient } from "../posthog-api";import type { ResumeState } from "../resume";import {@@ -42,6 +43,7 @@ import type { StoredEntry, TaskRun } from "../types";import {AgentServer,isTurnCompleteNotification,+ PREWARMED_RESUME_IDLE_CAPABILITY,SSE_KEEPALIVE_INTERVAL_MS,} from "./agent-server";import { type JwtPayload, SANDBOX_CONNECTION_AUDIENCE } from "./jwt";@@ -555,6 +557,7 @@ describe("AgentServer HTTP Mode", () => {totalMs: expect.any(Number),phasesMs: expect.any(Object),}),+ capabilities: [PREWARMED_RESUME_IDLE_CAPABILITY],});}, 30000);@@ -3526,6 +3529,449 @@ describe("AgentServer HTTP Mode", () => {});describe("resume prompt display", () => {+ it.each(["native", "summary"] as const)(+ "keeps a prewarmed %s resume idle until the forwarded user message arrives",+ async (resumeKind) => {+ const s = createServer();+ await s.start();++ const prompt = vi.fn(async () => ({ stopReason: "cancelled" }));+ const payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const taskRun = createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: {+ prewarmed: true,+ await_user_message: true,+ resume_from_run_id: "previous-run",+ },+ });+ const internals = s as unknown as {+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };+ session: { clientConnection: { prompt: typeof prompt } };+ resumeState: ResumeState | null;+ nativeResume: { sessionId: string; warm: boolean } | null;+ prewarmedRun: boolean;+ prewarmedStartupTurnPending: boolean;+ sendInitialTaskMessage(+ payload: JwtPayload,+ taskRun: TaskRun | null,+ ): Promise<void>;+ };+ internals.session.clientConnection.prompt = prompt;+ internals.prewarmedRun = true;+ internals.prewarmedStartupTurnPending = true;+ internals.resumeState = {+ conversation: [+ {+ role: "user",+ content: [{ type: "text", text: "original request" }],+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "work completed so far" }],+ },+ ],+ latestGitCheckpoint: null,+ interrupted: false,+ logEntryCount: 2,+ sessionId: "prior-session",+ };+ internals.nativeResume =+ resumeKind === "native"+ ? { sessionId: "prior-session", warm: true }+ : null;+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);++ await internals.sendInitialTaskMessage(payload, taskRun);++ expect(prompt).not.toHaveBeenCalled();+ expect(internals.resumeState).not.toBeNull();++ const response = await fetch(`http://localhost:${port}/command`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${createToken()}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: `deferred-${resumeKind}`,+ method: "user_message",+ params: { content: "continue with this change" },+ }),+ });++ expect(response.status).toBe(200);+ expect(prompt).toHaveBeenCalledOnce();+ const [{ prompt: promptBlocks }] = prompt.mock.calls[0] as unknown as [+ { prompt: ContentBlock[] },+ ];+ const visibleText = promptBlocks+ .filter(+ (block) =>+ block.type === "text" &&+ !(+ (block as { _meta?: { ui?: { hidden?: boolean } } })._meta?.ui+ ?.hidden === true+ ),+ )+ .map((block) => (block as { text: string }).text);+ expect(visibleText).toEqual(["continue with this change"]);+ if (resumeKind === "summary") {+ expect(promptBlocks).toHaveLength(3);+ expect((promptBlocks[0] as { text: string }).text).toContain(+ "work completed so far",+ );+ } else {+ expect(promptBlocks).toHaveLength(1);+ }+ expect(internals.resumeState).toBeNull();+ expect(internals.nativeResume).toBeNull();+ },+ 30000,+ );++ it("resumes instead of idling once the run is no longer awaiting its first message", async () => {+ // `prewarmed` outlives activation; `await_user_message` is what the backend clears. Idling on+ // provenance alone strands every reinitialization of an activated run, waiting for a first+ // message that was already delivered.+ const s = createServer();+ await s.start();++ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));+ const payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const taskRun = createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: { prewarmed: true, resume_from_run_id: "previous-run" },+ });+ const internals = s as unknown as {+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };+ session: { clientConnection: { prompt: typeof prompt } };+ resumeState: ResumeState | null;+ nativeResume: { sessionId: string; warm: boolean } | null;+ prewarmedRun: boolean;+ sendInitialTaskMessage(+ payload: JwtPayload,+ taskRun: TaskRun | null,+ ): Promise<void>;+ };+ internals.session.clientConnection.prompt = prompt;+ internals.nativeResume = null;+ internals.resumeState = {+ conversation: [+ {+ role: "user",+ content: [{ type: "text", text: "original request" }],+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "work completed so far" }],+ },+ ],+ latestGitCheckpoint: null,+ interrupted: false,+ logEntryCount: 2,+ sessionId: "prior-session",+ };+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);++ await internals.sendInitialTaskMessage(payload, taskRun);++ expect(internals.prewarmedRun).toBe(false);+ expect(prompt).toHaveBeenCalledOnce();+ }, 30000);++ it("loads the summary fallback before a prewarmed run idles", async () => {+ // Initialization may fail to fetch the run `prepareNativeResume` needed. If the fallback load+ // is skipped on the way to idling, the forwarded first message starts the resumed task with+ // none of its prior conversation, and nothing reports an error.+ const s = createServer();+ await s.start();++ const payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const taskRun = createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: {+ prewarmed: true,+ await_user_message: true,+ resume_from_run_id: "previous-run",+ },+ });+ const internals = s as unknown as {+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };+ resumeState: ResumeState | null;+ nativeResume: { sessionId: string; warm: boolean } | null;+ prewarmedRun: boolean;+ loadResumeState(+ taskId: string,+ resumeRunId: string,+ currentRunId: string,+ ): Promise<void>;+ sendInitialTaskMessage(+ payload: JwtPayload,+ taskRun: TaskRun | null,+ ): Promise<void>;+ };+ internals.nativeResume = null;+ internals.resumeState = null;+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);+ const loadResumeState = vi+ .spyOn(internals, "loadResumeState")+ .mockImplementation(async () => {+ internals.resumeState = {+ conversation: [+ {+ role: "assistant",+ content: [{ type: "text", text: "work completed so far" }],+ },+ ],+ latestGitCheckpoint: null,+ interrupted: false,+ logEntryCount: 1,+ sessionId: "prior-session",+ };+ });++ await internals.sendInitialTaskMessage(payload, taskRun);++ expect(loadResumeState).toHaveBeenCalledWith(+ "test-task-id",+ "previous-run",+ "test-run-id",+ );+ expect(internals.prewarmedRun).toBe(true);+ expect(internals.resumeState).not.toBeNull();+ }, 30000);++ it("applies the resume git checkpoint at most once", async () => {+ // The checkpoint resets the workspace to the resumed run's snapshot. Applying it again after+ // a turn has written files discards that work — including a turn that failed and is retried.+ const s = createServer();+ await s.start();++ const applyFromHandoff = vi+ .spyOn(HandoffCheckpointTracker.prototype, "applyFromHandoff")+ .mockResolvedValue({ packBytes: 1, indexBytes: 1, totalBytes: 2 });+ const payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const internals = s as unknown as {+ resumeState: ResumeState | null;+ resumeGitCheckpointApplied: boolean | null;+ config: { repositoryPath?: string };+ applyResumeGitCheckpoint(payload: JwtPayload): Promise<boolean>;+ };+ internals.config.repositoryPath = "/tmp/workspace";+ internals.resumeGitCheckpointApplied = null;+ internals.resumeState = {+ conversation: [],+ latestGitCheckpoint: { branch: "main", head: "abc123" },+ interrupted: false,+ logEntryCount: 0,+ sessionId: "prior-session",+ } as unknown as ResumeState;++ const first = await internals.applyResumeGitCheckpoint(payload);+ const second = await internals.applyResumeGitCheckpoint(payload);++ expect(first).toBe(true);+ expect(second).toBe(true);+ expect(applyFromHandoff).toHaveBeenCalledOnce();+ applyFromHandoff.mockRestore();+ }, 30000);++ it("still continues after /compact sent as the first forwarded message", async () => {+ // A summary resume prepends a hidden history block. Reading the slash command off the wrapped+ // prompt stops recognizing `/compact`, so the run reports complete instead of carrying on with+ // the user's compact instruction.+ const s = createServer();+ await s.start();++ const prompt = vi.fn(async () => ({ stopReason: "end_turn" }));+ const _payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const taskRun = createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: {+ prewarmed: true,+ await_user_message: true,+ resume_from_run_id: "previous-run",+ },+ });+ const internals = s as unknown as {+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };+ session: { clientConnection: { prompt: typeof prompt } };+ resumeState: ResumeState | null;+ nativeResume: { sessionId: string; warm: boolean } | null;+ prewarmedRun: boolean;+ };+ internals.session.clientConnection.prompt = prompt;+ internals.prewarmedRun = true;+ internals.nativeResume = null;+ internals.resumeState = {+ conversation: [+ {+ role: "assistant",+ content: [{ type: "text", text: "work completed so far" }],+ },+ ],+ latestGitCheckpoint: null,+ interrupted: false,+ logEntryCount: 1,+ sessionId: "prior-session",+ };+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);++ const response = await fetch(`http://localhost:${port}/command`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${createToken()}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: "deferred-compact",+ method: "user_message",+ params: { content: "/compact keep the auth work" },+ }),+ });++ expect(response.status).toBe(200);+ expect(prompt).toHaveBeenCalledTimes(2);+ const [, secondCall] = prompt.mock.calls as unknown as [+ unknown,+ [{ prompt: ContentBlock[] }],+ ];+ expect((secondCall[0].prompt[0] as { text: string }).text).toContain(+ "Compaction is complete",+ );+ }, 30000);++ it("retries an oversized deferred native resume on a fresh session", async () => {+ // `sendResumeContinuation` gets this through `runResumeTurn`'s retryOnOversizedPrompt, but a+ // prewarmed run defers its resume onto the first forwarded message and never takes that path.+ // Without a fallback the run just fails when the replayed transcript overflows the window.+ const s = createServer();+ await s.start();++ const prompt = vi+ .fn()+ .mockRejectedValueOnce(new Error("API Error: 413 prompt is too long"))+ .mockResolvedValue({ stopReason: "end_turn" });+ const newSession = vi.fn(async () => ({ sessionId: "fresh-session" }));+ const _payload: JwtPayload = {+ run_id: "test-run-id",+ task_id: "test-task-id",+ team_id: 1,+ user_id: 1,+ distinct_id: "test-distinct-id",+ mode: "interactive",+ };+ const taskRun = createTaskRun({+ id: "test-run-id",+ task: "test-task-id",+ state: {+ prewarmed: true,+ await_user_message: true,+ resume_from_run_id: "previous-run",+ },+ });+ const internals = s as unknown as {+ posthogAPI: { getTaskRun: ReturnType<typeof vi.fn> };+ session: {+ clientConnection: {+ prompt: typeof prompt;+ newSession: typeof newSession;+ };+ };+ resumeState: ResumeState | null;+ nativeResume: { sessionId: string; warm: boolean } | null;+ prewarmedRun: boolean;+ };+ internals.session.clientConnection.prompt = prompt;+ internals.session.clientConnection.newSession = newSession;+ internals.prewarmedRun = true;+ internals.nativeResume = { sessionId: "prior-session", warm: true };+ internals.resumeState = {+ conversation: [+ {+ role: "user",+ content: [{ type: "text", text: "original request" }],+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "work completed so far" }],+ },+ ],+ latestGitCheckpoint: null,+ interrupted: false,+ logEntryCount: 2,+ sessionId: "prior-session",+ };+ vi.spyOn(internals.posthogAPI, "getTaskRun").mockResolvedValue(taskRun);++ const response = await fetch(`http://localhost:${port}/command`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${createToken()}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: "deferred-oversized",+ method: "user_message",+ params: { content: "continue with this change" },+ }),+ });++ expect(response.status).toBe(200);+ expect(newSession).toHaveBeenCalledOnce();+ expect(prompt).toHaveBeenCalledTimes(2);+ const [, secondCall] = prompt.mock.calls as unknown as [+ unknown,+ [{ prompt: ContentBlock[] }],+ ];+ expect((secondCall[0].prompt[0] as { text: string }).text).toContain(+ "work completed so far",+ );+ }, 30000);+it("hides synthetic resume context while keeping the pending user message visible", async () => {const s = createServer() as unknown as {resumeState: ResumeState | null;diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.tsindex ccbc768b00a6..f20e2fe1dfdf 100644--- a/products/desktop/packages/agent/src/server/agent-server.ts+++ b/products/desktop/packages/agent/src/server/agent-server.ts@@ -339,6 +339,8 @@ interface BuiltPrompt {messageId?: string;}+export const PREWARMED_RESUME_IDLE_CAPABILITY = "prewarmedResumeIdle";+function hiddenTextBlock(text: string): ContentBlock {return {type: "text",@@ -541,6 +543,8 @@ export class AgentServer {// CLI flags can't carry the user's choice. Those settings are read from the// run's state when the first message arrives (see resolveActivationSettings).private prewarmedRun = false;+ /** Whether the resume git checkpoint has been attempted, and what it answered. See `applyResumeGitCheckpoint`. */+ private resumeGitCheckpointApplied: boolean | null = null;private prewarmedStartupTurnPending = false;private autoPublishStateResolved = false;private warmReasoningEffortResolved = false;@@ -766,6 +770,7 @@ export class AgentServer {bootMs: this.sessionReadyBootMs,sessionInitMs: this.sessionInitMs,boot,+ capabilities: [PREWARMED_RESUME_IDLE_CAPABILITY],});});@@ -1279,7 +1284,7 @@ export class AgentServer {taskId: commandSession.payload.task_id,runId: commandSession.payload.run_id,});- const prompt = builtPrompt.prompt;+ let prompt = builtPrompt.prompt;if (prompt.length === 0) {throw new Error("User message cannot be empty");}@@ -1340,11 +1345,22 @@ export class AgentServer {return outcome;}+ // Read the slash command off what the user actually typed. A deferred summary resume+ // prepends a hidden history block, and `isManualCompactPrompt` matches on the whole+ // prompt text, so checking afterwards would stop recognizing `/compact` as the first+ // message of a resumed session.+ const manualCompactPrompt = isManualCompactPrompt(prompt);++ const deferredResume = await this.preparePrewarmedResumePrompt(+ commandSession.payload,+ prompt,+ );+ prompt = deferredResume.prompt;+commandSession.logWriter.resetTurnMessages(commandSession.payload.run_id,);- const manualCompactPrompt = isManualCompactPrompt(prompt);const acpSessionId = commandSession.acpSessionId;const continueAfterCompaction = (): Promise<PromptResponse> =>this.promptWithUpstreamRetry({@@ -1379,11 +1395,31 @@ export class AgentServer {}return promptResult;};- if (this.prewarmedStartupTurnPending) {- this.prewarmedStartupTurnPending = false;- result = await this.runStartupTurn(runPrompt);- } else {- result = await this.runOwnedTurn(runPrompt);+ const runTurn = () => {+ if (this.prewarmedStartupTurnPending) {+ this.prewarmedStartupTurnPending = false;+ return this.runStartupTurn(runPrompt);+ }+ return this.runOwnedTurn(runPrompt);+ };+ try {+ result = await runTurn();+ } catch (error) {+ // A deferred native resume replays the whole prior transcript, which can overflow+ // the context window. Fall back the way `sendResumeContinuation` does — a fresh+ // session carrying summarized history — instead of failing the run.+ const retryPrompt =+ deferredResume.consumed && isPromptTooLongError(error)+ ? await this.retryOversizedDeferredResume(+ commandSession.payload,+ builtPrompt.prompt,+ )+ : null;+ if (!retryPrompt) {+ throw error;+ }+ prompt = retryPrompt;+ result = await runTurn();}if (result.stopReason === "end_turn" && manualCompactPrompt) {@@ -1411,6 +1447,10 @@ export class AgentServer {throw error;}commitDelivery();+ if (deferredResume.consumed) {+ this.resumeState = null;+ this.nativeResume = null;+ }const outcome = { stopReason: "error_recoverable" };resolveDelivery(outcome);return outcome;@@ -1418,6 +1458,10 @@ export class AgentServer {this.suppressAdapterTurnComplete = false;}commitDelivery();+ if (deferredResume.consumed) {+ this.resumeState = null;+ this.nativeResume = null;+ }this.logger.debug("User message completed", {stopReason: result.stopReason,@@ -1743,6 +1787,7 @@ export class AgentServer {this.resumeState = null;this.nativeResume = null;+ this.resumeGitCheckpointApplied = null;this.preSessionEvents = [];this.prewarmedRun = false;this.prewarmedStartupTurnPending = false;@@ -2414,13 +2459,19 @@ export class AgentServer {});}- if (this.nativeResume) {- if (await this.settleIdleResume(payload, taskRun)) return;- await this.sendResumeContinuation(payload, taskRun);- return;- }+ const taskRunState = taskRun?.state as Record<string, unknown> | undefined;+ const prewarmed = taskRunState?.prewarmed === true;+ const hasPendingUserPrompt =+ (typeof taskRunState?.pending_user_message === "string" &&+ taskRunState.pending_user_message.trim().length > 0) ||+ (Array.isArray(taskRunState?.pending_user_artifact_ids) &&+ taskRunState.pending_user_artifact_ids.length > 0);- if (!this.resumeState) {+ // Load the summary fallback before deciding to idle. A prewarmed run that idles here reads+ // this state when its first message arrives, and initialization may have failed to fetch the+ // run that `prepareNativeResume` needed — leaving both resume fields empty and starting the+ // resumed task with none of its prior conversation.+ if (!this.nativeResume && !this.resumeState) {const resumeRunId = this.getResumeRunId(taskRun);if (resumeRunId) {await this.loadResumeState(@@ -2431,6 +2482,24 @@ export class AgentServer {}}+ // `await_user_message` is the marker the backend clears on activation. `prewarmed` is permanent+ // provenance that outlives it, so idling on that alone would strand a run whose first message+ // was already delivered — every later reinitialization would wait for a message nobody sends.+ const awaitsFirstMessage = taskRunState?.await_user_message === true;+ if (prewarmed && awaitsFirstMessage && !hasPendingUserPrompt) {+ this.prewarmedRun = true;+ this.logger.debug(+ "Prewarmed run awaits its forwarded first message, skipping initial message",+ );+ return;+ }++ if (this.nativeResume) {+ if (await this.settleIdleResume(payload, taskRun)) return;+ await this.sendResumeContinuation(payload, taskRun);+ return;+ }+if (this.resumeState && this.resumeState.conversation.length > 0) {await this.sendResumeMessage(payload, taskRun);return;@@ -2448,9 +2517,6 @@ export class AgentServer {// A prewarmed run gets its first message forwarded as a user_message// signal on activation; building one from task.description here too// would deliver it twice (and without the forwarded artifacts).- const prewarmed = !!(- taskRun?.state as Record<string, unknown> | undefined- )?.prewarmed;let initialPrompt: ContentBlock[] = [];let initialPromptMeta: Record<string, unknown> | undefined;let initialPromptMessageId: string | undefined;@@ -2638,6 +2704,140 @@ export class AgentServer {return true;}+ private async preparePrewarmedResumePrompt(+ payload: JwtPayload,+ prompt: ContentBlock[],+ ): Promise<{ prompt: ContentBlock[]; consumed: boolean }> {+ if (!this.prewarmedRun) {+ return { prompt, consumed: false };+ }++ if (this.nativeResume) {+ const checkpointApplied = this.nativeResume.warm+ ? false+ : await this.applyResumeGitCheckpoint(payload);+ this.logger.debug("Applying deferred native resume to user message", {+ taskId: payload.task_id,+ sessionId: this.nativeResume.sessionId,+ warm: this.nativeResume.warm,+ checkpointApplied,+ });+ return { prompt, consumed: true };+ }++ if (!this.resumeState?.conversation.length) {+ return { prompt, consumed: false };+ }++ const resumeState = this.resumeState;+ const checkpointApplied = await this.applyResumeGitCheckpoint(payload);++ this.logger.debug("Applying deferred summary resume to user message", {+ taskId: payload.task_id,+ conversationTurns: resumeState.conversation.length,+ checkpointApplied,+ hasGitCheckpoint: !!resumeState.latestGitCheckpoint,+ });++ return {+ prompt: this.wrapPromptWithSummaryResume(+ resumeState,+ checkpointApplied,+ prompt,+ ),+ consumed: true,+ };+ }++ /** Wrap the user's message in the previous session's conversation, hidden from the transcript. */+ private wrapPromptWithSummaryResume(+ resumeState: ResumeState,+ checkpointApplied: boolean,+ prompt: ContentBlock[],+ ): ContentBlock[] {+ const checkpointContext = checkpointApplied+ ? "The workspace environment (all files, packages, and code changes) has been fully restored from the latest checkpoint."+ : "No additional git checkpoint was applied before resuming. Use the current workspace contents together with the preserved conversation history below.";+ const conversationSummary = formatConversationForResume(+ resumeState.conversation,+ );+ return [+ hiddenTextBlock(+ `You are resuming a previous conversation. ${checkpointContext}\n\n` ++ `Here is the conversation history from the previous session:\n\n` ++ `${conversationSummary}\n\n` ++ "The user has sent a new message:\n\n",+ ),+ ...prompt,+ hiddenTextBlock(+ "\n\nRespond to the user's new message above. You have full context from the previous session.",+ ),+ ];+ }++ /**+ * Recover a deferred native resume whose transcript overflowed the context window: open a fresh+ * session and rebuild the prompt around summarized history instead. Returns the replacement+ * prompt, or null when there is nothing to fall back to.+ *+ * `sendResumeContinuation` gets this through `runResumeTurn`'s `retryOnOversizedPrompt`, but a+ * prewarmed run defers its resume onto the first forwarded `user_message` and never goes through+ * that path — without this it would fail the run instead of retrying.+ */+ private async retryOversizedDeferredResume(+ payload: JwtPayload,+ prompt: ContentBlock[],+ ): Promise<ContentBlock[] | null> {+ if (this.oversizedResumeRetried || !this.session) {+ return null;+ }+ this.oversizedResumeRetried = true;++ const taskRun = await this.refreshTaskRunForResume(payload, null);+ const resumeRunId = this.getResumeRunId(taskRun);+ if (!resumeRunId) return null;+ if (!this.resumeState) {+ try {+ await this.loadResumeState(+ payload.task_id,+ resumeRunId,+ payload.run_id,+ );+ } catch (error) {+ this.logger.warn("Failed to reload resume state for retry", {+ error: getErrorMessage(error),+ });+ return null;+ }+ }+ const resumeState = this.resumeState;+ if (!resumeState?.conversation.length) return null;++ try {+ const response = await this.session.clientConnection.newSession({+ cwd: this.config.repositoryPath ?? "/tmp/workspace",+ mcpServers: this.config.mcpServers ?? [],+ _meta: this.session.sessionMeta,+ });+ this.session.acpSessionId = response.sessionId;+ } catch (error) {+ this.logger.warn("Failed to start fresh session for oversized resume", {+ error: getErrorMessage(error),+ });+ return null;+ }++ this.logger.warn(+ "Deferred resume prompt exceeded the context window; retrying on a fresh session with summarized history",+ { taskId: payload.task_id, runId: payload.run_id },+ );+ return this.wrapPromptWithSummaryResume(+ resumeState,+ await this.applyResumeGitCheckpoint(payload),+ prompt,+ );+ }+private async sendResumeContinuation(payload: JwtPayload,taskRun: TaskRun | null,@@ -2837,6 +3037,13 @@ export class AgentServer {private async applyResumeGitCheckpoint(payload: JwtPayload,): Promise<boolean> {+ // At most once per process, and the answer is replayed afterwards. The checkpoint resets the+ // workspace to the resumed run's snapshot, so a second application discards everything the+ // session has written since — including the work of a turn that failed and is being retried.+ // A failed attempt counts as an attempt: it may have partially applied.+ if (this.resumeGitCheckpointApplied !== null) {+ return this.resumeGitCheckpointApplied;+ }if (!this.resumeState?.latestGitCheckpoint ||!this.config.repositoryPath ||@@ -2862,12 +3069,14 @@ export class AgentServer {indexBytes: metrics.indexBytes,totalBytes: metrics.totalBytes,});+ this.resumeGitCheckpointApplied = true;return true;} catch (error) {this.logger.warn("Failed to apply git checkpoint", {error: error instanceof Error ? error.message : String(error),branch: this.resumeState.latestGitCheckpoint.branch,});+ this.resumeGitCheckpointApplied = false;return false;}}