@devries-cameron20 / t3code Mirror · read-only / commits / 9e19b7f7e1
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 16:00 UTC

feat(server): resume stopped provider threads natively (#36526)

Yash Singh committed Nov 14, 2026 at 03:24 UTC 9e19b7f7e1ab504e05ee73df51c7fc7700f246af
22 files changed +806 -108
apps/mobile/src/features/threads/resume-thread.ts
+1 -1
@@ -69,7 +69,7 @@ export async function resumeThread<E>(input: {
69 message: {
70 messageId: input.messageId,
71 role: "user",
72 - text: "Continue where you left off.",
72 + text: "",
73 attachments: [],
74 },
75 runtimeMode,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+129
@@ -281,6 +281,69 @@ function makeClaudeTestTurnInput(input: {
281 };
282 }
283
284 +describe("ClaudeAdapterV2 native resume history", () => {
285 + const entry = (uuid: string, type: string, content: unknown) => ({
286 + uuid,
287 + type,
288 + message: { content },
289 + });
290 + const prompt = entry("prompt", "user", "Run the task");
291 + const completed = entry("completed-tool", "user", [
292 + { type: "tool_result", tool_use_id: "done", content: "Saved", is_error: false },
293 + ]);
294 + const call = entry("call", "assistant", [
295 + { type: "tool_use", id: "pending", name: "Bash", input: {} },
296 + ]);
297 + const interrupted = entry("stopped-tool", "user", [
298 + {
299 + type: "tool_result",
300 + tool_use_id: "pending",
301 + content: "The user doesn't want to proceed with this tool use. STOP",
302 + is_error: true,
303 + },
304 + ]);
305 + it.each([
306 + {
307 + name: "an interrupted reply",
308 + messages: [
309 + prompt,
310 + entry("reply", "assistant", "Partial response"),
311 + entry("stop", "user", [{ type: "text", text: "[Request interrupted by user]" }]),
312 + ],
313 + head: "reply",
314 + },
315 + {
316 + name: "an interrupted tool after completed work",
317 + messages: [
318 + prompt,
319 + completed,
320 + call,
321 + interrupted,
322 + entry("stop", "user", "[Request interrupted by user for tool use]"),
323 + ],
324 + head: "call",
325 + },
326 + {
327 + name: "an interrupted request before any reply",
328 + messages: [prompt, entry("stop", "user", "[Request interrupted by user]")],
329 + head: "prompt",
330 + },
331 + {
332 + name: "completed tool results",
333 + messages: [prompt, completed, entry("stop", "user", "[Request interrupted by user]")],
334 + head: "completed-tool",
335 + },
336 + { name: "an explicit refusal", messages: [prompt, call, interrupted], head: undefined },
337 + {
338 + name: "ordinary conversation text",
339 + messages: [prompt, entry("reply", "assistant", "Continue where you left off.")],
340 + head: undefined,
341 + },
342 + ])("selects the native history head for $name", ({ messages, head }) => {
343 + assert.equal(ClaudeAdapterV2.claudeResumeSessionAt(messages), head);
344 + });
345 +});
346 +
347 describe("ClaudeAdapterV2 runtime query policy", () => {
348 it.each([
349 "-- --thinking-display omitted",
@@ -3661,6 +3724,72 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3724 });
3725 const makeWakeHarness = makeWakeHarnessWithOptions();
3726
3727 + it.effect.each([false, true])(
3728 + "resumes a stopped query with empty SDK content and a fresh native process, buffered: %s",
3729 + (buffered) =>
3730 + Effect.gen(function* () {
3731 + const harness = yield* makeWakeHarnessWithOptions({
3732 + freshQueueOnReopen: true,
3733 + close: (queue) => Queue.shutdown(queue),
3734 + });
3735 + const input = makeClaudeTestTurnInput({
3736 + threadId: harness.threadId,
3737 + providerThread: harness.providerThread,
3738 + now: DateTime.makeUnsafe(0),
3739 + attemptId: RunAttemptId.make("native-resume"),
3740 + text: "Initial task",
3741 + attachments: [],
3742 + providerTurnOrdinal: 1,
3743 + });
3744 + yield* harness.runtime.startTurn(input);
3745 + yield* harness.offerAndWait(turnOneResult);
3746 + yield* Queue.take(harness.terminalReceipts);
3747 + if (buffered) {
3748 + yield* harness.offerAndWait(wakeAssistant);
3749 + yield* harness.offerAndWait(wakeResult);
3750 + }
3751 + const { message, ...turn } = input;
3752 + yield* harness.runtime.resumeTurn!({
3753 + ...turn,
3754 + providerTurnOrdinal: 2,
3755 + messageId: message.messageId,
3756 + });
3757 + assert.equal(harness.processQueues.length, 2);
3758 + assert.equal(
3759 + harness.getOpenedOptions()?.resume,
3760 + harness.providerThread.nativeThreadRef?.nativeId,
3761 + );
3762 + if (buffered) {
3763 + assert.equal(harness.offeredMessages.length, 1);
3764 + } else {
3765 + assert.deepEqual(harness.offeredMessages.at(-1)?.message.content, []);
3766 + yield* harness.offerAndWait(turnOneResult);
3767 + }
3768 + yield* Queue.take(harness.terminalReceipts);
3769 + assert.equal(harness.terminalEvents().length, 2);
3770 + if (buffered) {
3771 + assert.isTrue(
3772 + harness.events.some(
3773 + (event) =>
3774 + event.type === "turn_item.updated" &&
3775 + event.turnItem.type === "assistant_message" &&
3776 + event.turnItem.text === WAKE_ASSISTANT_TEXT,
3777 + ),
3778 + );
3779 + }
3780 + }).pipe(
3781 + Effect.scoped,
3782 + Effect.provide(
3783 + Layer.mergeAll(
3784 + IdAllocator.layer,
3785 + McpProviderSessions.layer,
3786 + NodeServices.layer,
3787 + NodeCrypto.layer,
3788 + ),
3789 + ),
3790 + ),
3791 + );
3792 +
3793 it.effect("resumes the session a /clear selected after the Claude process is replaced", () =>
3794 Effect.gen(function* () {
3795 const harness = yield* makeWakeHarnessWithOptions({
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+150 -39
@@ -647,6 +647,7 @@ export type ClaudeAgentSdkQueryOptions = Omit<
647 } & ClaudeAgentSdkThreadIdentity;
648
649 export interface ClaudeAgentSdkQueryOpenInput {
650 + readonly resume?: true;
651 readonly options: ClaudeAgentSdkQueryOptions;
652 readonly threadId: ThreadId;
653 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
@@ -1220,6 +1221,67 @@ const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
1221 ),
1222 );
1223
1224 +const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect(
1225 + Schema.fromJsonString(
1226 + Schema.Array(
1227 + Schema.Struct({
1228 + type: Schema.String,
1229 + uuid: Schema.String,
1230 + message: Schema.Struct({ content: Schema.Unknown }),
1231 + }),
1232 + ),
1233 + ),
1234 +);
1235 +
1236 +// Claude's interactive reply-on-resume removes native abort rows before querying the saved history.
1237 +export function claudeResumeSessionAt(
1238 + messages: ReadonlyArray<{
1239 + readonly type: string;
1240 + readonly uuid: string;
1241 + readonly message: { readonly content: unknown };
1242 + }>,
1243 +): string | undefined {
1244 + let end = messages.length;
1245 + let toolInterrupted = false;
1246 + while (end > 0) {
1247 + const message = messages[end - 1]!;
1248 + const content = message.message.content;
1249 + const blocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
1250 + if (message.type !== "user" || !Array.isArray(blocks) || blocks.length === 0) break;
1251 + const stop = blocks.every(
1252 + (block: unknown) =>
1253 + Predicate.isObject(block) &&
1254 + block.type === "text" &&
1255 + (block.text === "[Request interrupted by user]" ||
1256 + block.text === "[Request interrupted by user for tool use]"),
1257 + );
1258 + if (stop) {
1259 + toolInterrupted ||= blocks.some(
1260 + (block: unknown) =>
1261 + Predicate.isObject(block) && block.text === "[Request interrupted by user for tool use]",
1262 + );
1263 + end--;
1264 + continue;
1265 + }
1266 + if (
1267 + toolInterrupted &&
1268 + blocks.every(
1269 + (block: unknown) =>
1270 + Predicate.isObject(block) &&
1271 + block.type === "tool_result" &&
1272 + block.is_error === true &&
1273 + typeof block.content === "string" &&
1274 + block.content.startsWith("The user doesn't want to proceed with this tool use."),
1275 + )
1276 + ) {
1277 + end--;
1278 + continue;
1279 + }
1280 + break;
1281 + }
1282 + return end === messages.length ? undefined : messages[end - 1]?.uuid;
1283 +}
1284 +
1285 const claudeConfigDirOf = (
1286 path: Path.Path,
1287 environment: NodeJS.ProcessEnv,
@@ -1229,7 +1291,7 @@ const claudeConfigDirOf = (
1291 // The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
1292 // worker so concurrent providers keep the server's environment.
1293 const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
1232 - readonly method: "forkSession";
1294 + readonly method: "forkSession" | "getSessionMessages";
1295 readonly sessionId: string;
1296 readonly options?: ForkSessionOptions;
1297 readonly environment: NodeJS.ProcessEnv;
@@ -1358,10 +1420,36 @@ export const layerQueryRunner: Layer.Layer<
1420 // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments.
1421 const { mcpServers, ...sdkOptions } = input.options;
1422 // Jobs the agent starts inherit the thread, so port discovery can attribute their servers.
1423 + let resumeSessionAt = sdkOptions.resumeSessionAt;
1424 + if (input.resume && sdkOptions.resume !== undefined) {
1425 + const messages = yield* runClaudeWorker({
1426 + method: "getSessionMessages",
1427 + sessionId: sdkOptions.resume,
1428 + options: sdkOptions.cwd === undefined ? {} : { dir: sdkOptions.cwd },
1429 + environment: sdkOptions.env ?? hostEnvironment,
1430 + }).pipe(
1431 + Effect.flatMap(decodeClaudeHistoryMessages),
1432 + Effect.mapError((cause) => queryRunnerError(cause, "getSessionMessages")),
1433 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1434 + Effect.provideService(Path.Path, path),
1435 + );
1436 + const boundary =
1437 + resumeSessionAt === undefined
1438 + ? messages.length
1439 + : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1;
1440 + resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt;
1441 + }
1442 const queryOptions = {
1443 ...sdkOptions,
1444 + ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
1445 env: {
1446 ...(sdkOptions.env ?? hostEnvironment),
1447 + ...(input.resume
1448 + ? {
1449 + CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1",
1450 + CLAUDE_CODE_RESUME_REASON: "user_resume",
1451 + }
1452 + : {}),
1453 [PortScanner.AGENT_THREAD_ENV]: input.threadId,
1454 },
1455 };
@@ -12160,6 +12248,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12248 );
12249 let compiledSelection = compileClaudeModelSelection(turnInput.modelSelection, catalog);
12250 if (
12251 + !turnInput.resume &&
12252 existing !== null &&
12253 existing.nativeThreadId === nativeThreadId &&
12254 existing.queryPolicyKey === queryPolicyKey &&
@@ -12172,6 +12261,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12261 yield* applySelectionLive(existing, compiledSelection);
12262 }
12263 if (
12264 + !turnInput.resume &&
12265 existing !== null &&
12266 existing.nativeThreadId === nativeThreadId &&
12267 existing.queryPolicyKey === queryPolicyKey &&
@@ -12302,6 +12392,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12392 threadId: turnInput.threadId,
12393 providerSessionId: input.providerSessionId,
12394 options: queryOptions,
12395 + ...(turnInput.resume ? { resume: true } : {}),
12396 });
12397 // The SDK spawns the CLI per turn, so only the open waits for a provider update.
12398 const querySession = yield* (
@@ -12548,27 +12639,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12639 const userMessage =
12640 promptUuid === null
12641 ? null
12551 - : yield* makeClaudeUserMessageWithAttachments({
12552 - text: promptText,
12553 - // Mentions in inline handoff history are history, not this turn's skill.
12554 - ...(turnInput.inlineContextLength === undefined
12555 - ? {}
12556 - : {
12557 - skillMentionsFrom:
12558 - promptText.length -
12559 - turnInput.message.text.slice(turnInput.inlineContextLength).trimEnd()
12560 - .length,
12561 - }),
12562 - attachments: turnInput.message.attachments,
12563 - attachmentsDir,
12564 - fileSystem,
12565 - pdfReservation,
12566 - ...(skills === undefined ? {} : { skills }),
12567 - uuid: promptUuid,
12568 - }).pipe(
12569 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
12570 - Effect.provideService(Path.Path, path),
12571 - );
12642 + : turnInput.resume
12643 + ? {
12644 + type: "user" as const,
12645 + message: { role: "user" as const, content: [] },
12646 + parent_tool_use_id: null,
12647 + uuid: promptUuid,
12648 + }
12649 + : yield* makeClaudeUserMessageWithAttachments({
12650 + text: promptText,
12651 + // Mentions in inline handoff history are history, not this turn's skill.
12652 + ...(turnInput.inlineContextLength === undefined
12653 + ? {}
12654 + : {
12655 + skillMentionsFrom:
12656 + promptText.length -
12657 + turnInput.message.text.slice(turnInput.inlineContextLength).trimEnd()
12658 + .length,
12659 + }),
12660 + attachments: turnInput.message.attachments,
12661 + attachmentsDir,
12662 + fileSystem,
12663 + pdfReservation,
12664 + ...(skills === undefined ? {} : { skills }),
12665 + uuid: promptUuid,
12666 + }).pipe(
12667 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
12668 + Effect.provideService(Path.Path, path),
12669 + );
12670 const querySession = yield* openQuery(turnInput, nativeThreadId, queryPolicy);
12671 const autoCompactWindow = yield* resolveAutoCompactWindow(
12672 querySession.settingsCwd,
@@ -12624,7 +12722,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12722 subagentsByTaskId: new Map(),
12723 subagentsByToolUseId: new Map(),
12724 promptUuid,
12627 - promptEcho: isClaudeProviderContinuationTurn(turnInput) ? "confirmed" : "pending",
12725 + promptEcho:
12726 + isClaudeProviderContinuationTurn(turnInput) || turnInput.resume
12727 + ? "confirmed"
12728 + : "pending",
12729 promptStarted: false,
12730 nativeWakeStarted: false,
12731 gatedFramesBeforeEcho: 0,
@@ -12705,22 +12806,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12806 }),
12807 });
12808 });
12708 - if (userMessage !== null) {
12809 + const offerUserMessage =
12810 + userMessage === null
12811 + ? Effect.void
12812 + : startUserTurnForWakeReports(nativeThreadId).pipe(
12813 + Effect.andThen(
12814 + Effect.uninterruptibleMask((restore) =>
12815 + restore(
12816 + querySession.query.offer(userMessage, () => {
12817 + pdfReservation.commit();
12818 + }),
12819 + ).pipe(Effect.tap(() => Effect.sync(() => pdfReservation.commit()))),
12820 + ),
12821 + ),
12822 + );
12823 + if (userMessage !== null && !turnInput.resume) {
12824 yield* attachTurn;
12710 - yield* startUserTurnForWakeReports(nativeThreadId);
12711 - yield* Effect.uninterruptibleMask((restore) =>
12712 - restore(
12713 - querySession.query.offer(userMessage, () => {
12714 - pdfReservation.commit();
12715 - }),
12716 - ).pipe(
12717 - Effect.tap(() =>
12718 - Effect.sync(() => {
12719 - pdfReservation.commit();
12720 - }),
12721 - ),
12722 - ),
12723 - );
12825 + yield* offerUserMessage;
12826 return;
12827 }
12828 // Transcript reads suspend replay; hold SDK frames until the buffer is applied to preserve order.
@@ -12751,6 +12853,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12853 : (yield* Ref.get(absorbedWakes)).has(nativeThreadId);
12854 if (!leavesLaterWake) yield* forgetAbsorbedWake(nativeThreadId);
12855 if (drained.length === 0) {
12856 + if (turnInput.resume) return;
12857 const completedAt = yield* DateTime.now;
12858 yield* finalizeActiveTurn({ context, status: "completed", completedAt });
12859 return;
@@ -12817,7 +12920,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12920 const completedAt = yield* DateTime.now;
12921 yield* finalizeActiveTurn({ context, status: "completed", completedAt });
12922 if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId);
12820 - } else if (!context.nativeWakeStarted) {
12923 + } else if (!context.nativeWakeStarted && !turnInput.resume) {
12924 yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe(
12925 Effect.andThen(
12926 sdkMessageLock.withPermits(1)(
@@ -12847,6 +12950,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12950 }
12951 }),
12952 );
12953 + if (userMessage !== null) {
12954 + yield* sdkMessageLock.withPermits(1)(
12955 + Effect.gen(function* () {
12956 + if ((yield* Ref.get(activeTurn)) === context) yield* offerUserMessage;
12957 + }),
12958 + );
12959 + }
12960 },
12961 (effect, turnInput) =>
12962 effect.pipe(
@@ -13390,6 +13500,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13500 ),
13501 ),
13502 ),
13503 + resumeTurn: (input) => startTurn(ProviderAdapter.resumeTurnInput(input)),
13504 startTurn,
13505 compactThread: (turnInput) =>
13506 startTurn({
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+75
@@ -1519,6 +1519,81 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1519 };
1520 });
1521
1522 + it.effect.each(["native", "ordinary"] as const)(
1523 + "resumes Codex without a prompt only for an existing conversation (%s)",
1524 + (mode) =>
1525 + Effect.gen(function* () {
1526 + const nativeThreadId = `resume-${mode}`;
1527 + const nativeTurnId = `resume-turn-${mode}`;
1528 + const preamble = codexReplayPreamble({
1529 + nativeThreadId,
1530 + nativeTurnId,
1531 + prompt: "Hello",
1532 + });
1533 + const harness = yield* makeCodexReplayHarness(
1534 + makeCodexReplayTranscript({
1535 + scenario: `manual-resume-${mode}`,
1536 + entries: [
1537 + ...preamble.map((entry) =>
1538 + mode === "native" &&
1539 + entry.type === "expect_outbound" &&
1540 + Predicate.isObject(entry.frame) &&
1541 + Predicate.isObject(entry.frame.params) &&
1542 + entry.frame.method === "turn/start"
1543 + ? {
1544 + ...entry,
1545 + frame: {
1546 + ...entry.frame,
1547 + params: {
1548 + ...entry.frame.params,
1549 + input: [],
1550 + },
1551 + },
1552 + }
1553 + : entry,
1554 + ),
1555 + {
1556 + type: "emit_inbound",
1557 + frame: {
1558 + method: "turn/completed",
1559 + params: {
1560 + threadId: nativeThreadId,
1561 + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1562 + },
1563 + },
1564 + },
1565 + ],
1566 + }),
1567 + );
1568 + const input = {
1569 + ...makeCodexTestTurnInput({
1570 + threadId: harness.threadId,
1571 + providerThread: harness.providerThread,
1572 + now: yield* DateTime.now,
1573 + attemptId: RunAttemptId.make(`resume-${mode}`),
1574 + text: "Hello",
1575 + }),
1576 + nativeThreadHasTurns: true,
1577 + };
1578 + const { message, ...resumeInput } = input;
1579 + if (mode === "native")
1580 + yield* harness.runtime.resumeTurn!({ ...resumeInput, messageId: message.messageId });
1581 + else yield* harness.runtime.startTurn(input);
1582 + yield* harness.firstTerminal;
1583 + assert.equal(harness.terminalEvents()[0]?.status, "completed");
1584 + }).pipe(
1585 + Effect.scoped,
1586 + Effect.provide(
1587 + Layer.mergeAll(
1588 + IdAllocator.layer,
1589 + McpProviderSessions.layer,
1590 + NodeServices.layer,
1591 + NodeCrypto.layer,
1592 + ),
1593 + ),
1594 + ),
1595 + );
1596 +
1597 it.effect("keeps native image views available to the clients", () =>
1598 Effect.gen(function* () {
1599 const nativeThreadId = "image-view-thread";
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+6 -8
@@ -7844,16 +7844,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7844 }),
7845 ),
7846 ),
7847 + resumeTurn: (input) => runtime.startTurn(ProviderAdapter.resumeTurnInput(input)),
7848 startTurn: (turnInput) => {
7848 - const goalCommand =
7849 - turnInput.restartContinuationOfRunId === undefined
7850 - ? parseGoalCommand(turnInput.message)
7851 - : null;
7849 + const continuation =
7850 + turnInput.restartContinuationOfRunId !== undefined || turnInput.resume === true;
7851 + const goalCommand = !continuation ? parseGoalCommand(turnInput.message) : null;
7852 if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand);
7853 const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId;
7854 return Effect.gen(function* () {
7855 if (
7856 - turnInput.restartContinuationOfRunId === undefined &&
7856 + !continuation &&
7857 nativeThreadId != null &&
7858 goalsPausedForWake.has(nativeThreadId) &&
7859 goalsByNativeThread.get(nativeThreadId)?.status === "paused"
@@ -7862,9 +7862,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7862 }
7863 yield* startNativeTurn(
7864 turnInput,
7865 - turnInput.restartContinuationOfRunId === undefined
7866 - ? yield* toCodexInput(turnInput)
7867 - : [],
7865 + !continuation ? yield* toCodexInput(turnInput) : [],
7866 );
7867 }).pipe(
7868 Effect.mapError(
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+14
@@ -523,6 +523,20 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
523 }),
524 );
525
526 + it.effect("resumes through OpenCode with an empty native prompt", () =>
527 + Effect.gen(function* () {
528 + const { runtime, thread } = yield* resumed([
529 + out("session.prompt", { sessionID: SESSION, text: "" }),
530 + promptAccepted,
531 + event("session.execution.succeeded", { sessionID: SESSION }),
532 + ]);
533 + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
534 + const { message, ...input } = turnInput(thread);
535 + yield* runtime.resumeTurn!({ ...input, messageId: message.messageId });
536 + assert.equal((yield* Fiber.join(terminal))?.status, "completed");
537 + }).pipe(Effect.scoped),
538 + );
539 +
540 it.effect("renames the session before the first turn after the thread was renamed", () =>
541 Effect.gen(function* () {
542 const { runtime, thread } = yield* resumed([
apps/server/src/orchestration-v2/Orchestrator.ts
+27 -8
@@ -7134,10 +7134,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7134 }
7135 }
7136 }
7137 + const notification =
7138 + command.manualContinuationOfRunId === undefined
7139 + ? command.notification
7140 + : {
7141 + source: { kind: "system" as const },
7142 + outcome: "updated" as const,
7143 + summary: "Resumed thread",
7144 + };
7145 const dispatchText =
7138 - delegatedCompletion === undefined
7139 - ? command.text
7140 - : delegatedCompletionWakeDetail(delegatedCompletion.taskIds, projection.subagents);
7146 + command.manualContinuationOfRunId !== undefined
7147 + ? ""
7148 + : delegatedCompletion === undefined
7149 + ? command.text
7150 + : delegatedCompletionWakeDetail(delegatedCompletion.taskIds, projection.subagents);
7151 const sourcePlanProjection =
7152 command.sourcePlanRef === undefined
7153 ? null
@@ -7226,12 +7236,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7236 effects,
7237 projection,
7238 modelSelection:
7229 - delegatedCompletion === undefined && command.notification === undefined
7239 + delegatedCompletion === undefined && notification === undefined
7240 ? modelSelection
7241 : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)?.modelSelection ??
7242 modelSelection),
7243 delegatedCompletion,
7234 - ...(command.notification === undefined ? {} : { notification: command.notification }),
7244 + ...(notification === undefined ? {} : { notification }),
7245 targetRunId: dispatchMode.targetRunId,
7246 messageId: command.messageId,
7247 text: dispatchText,
@@ -7492,6 +7502,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7502 ...(command.restartContinuationOfRunId === undefined
7503 ? {}
7504 : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
7505 + ...(command.manualContinuationOfRunId === undefined
7506 + ? {}
7507 + : { manualContinuationOfRunId: command.manualContinuationOfRunId }),
7508 ...(command.usageLimitContinuationOfRunId === undefined
7509 ? {}
7510 : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
@@ -7552,7 +7565,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7565 createdAt: now,
7566 updatedAt: now,
7567 ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
7555 - ...(command.notification === undefined ? {} : { notification: command.notification }),
7568 + ...(notification === undefined ? {} : { notification }),
7569 };
7570 const emitEvent = emit(events, command);
7571 if (targetProviderThread === undefined) {
@@ -7903,6 +7916,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7916 ...(command.restartContinuationOfRunId === undefined
7917 ? {}
7918 : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
7919 + ...(command.manualContinuationOfRunId === undefined
7920 + ? {}
7921 + : { manualContinuationOfRunId: command.manualContinuationOfRunId }),
7922 ...(command.usageLimitContinuationOfRunId === undefined
7923 ? {}
7924 : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
@@ -7967,7 +7983,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7983 createdAt: now,
7984 updatedAt: now,
7985 ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
7970 - ...(command.notification === undefined ? {} : { notification: command.notification }),
7986 + ...(notification === undefined ? {} : { notification }),
7987 };
7988 const turnItem: OrchestrationV2TurnItem = {
7989 createdBy: command.createdBy,
@@ -8698,6 +8714,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8714 ...(command.restartContinuationOfRunId === undefined
8715 ? {}
8716 : { restartContinuationOfRunId: command.restartContinuationOfRunId }),
8717 + ...(command.manualContinuationOfRunId === undefined
8718 + ? {}
8719 + : { manualContinuationOfRunId: command.manualContinuationOfRunId }),
8720 ...(command.usageLimitContinuationOfRunId === undefined
8721 ? {}
8722 : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
@@ -8755,7 +8774,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8774 createdAt: now,
8775 updatedAt: now,
8776 ...(delegatedCompletion === undefined ? {} : { delegatedCompletion }),
8758 - ...(command.notification === undefined ? {} : { notification: command.notification }),
8777 + ...(notification === undefined ? {} : { notification }),
8778 };
8779 const turnItem: OrchestrationV2TurnItem = {
8780 createdBy: command.createdBy,
apps/server/src/orchestration-v2/ProjectionStore.ts
+11 -2
@@ -5,6 +5,7 @@ import { projectTurnItemForWire } from "./WireProjection.ts";
5 import * as Stream from "effect/Stream";
6 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
7 import { makeThreadFind } from "./ThreadFind.ts";
8 +import { unsentManualContinuationSource } from "./manualContinuation.ts";
9 import type {
10 OrchestrationV2ThreadLinkMetadata,
11 OrchestrationV2SearchThreadInput,
@@ -5128,11 +5129,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5129 WHERE bindings.thread_id = ${threadId}
5130 ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC
5131 `.pipe(Effect.flatMap(decodeRows(decodeProviderSessionPayload, threadId)));
5132 + const run = runs.find((source) => source.id === runId);
5133 + const unsentSource = unsentManualContinuationSource(run, {
5134 + runs,
5135 + attempts,
5136 + providerTurns,
5137 + });
5138 + const messageIds = [run, unsentSource].flatMap((source) =>
5139 + source === undefined ? [] : [source.userMessageId],
5140 + );
5141 const messages = yield* sql<PayloadRow>`
5142 SELECT payload_json FROM orchestration_v2_projection_messages
5143 WHERE thread_id = ${threadId} AND (
5134 - message_id IN (SELECT json_extract(payload_json, '$.userMessageId') FROM orchestration_v2_projection_runs
5135 - WHERE thread_id = ${threadId} AND run_id = ${runId})
5144 + message_id IN ${sql.in(messageIds)}
5145 OR (role = 'user' AND lower(trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace})) = '/compact')
5146 -- Earlier /goal turns defer context too; parseGoalCommand narrows this prefix match.
5147 OR (role = 'user' AND trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace}) GLOB '/goal*')
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+180 -14
@@ -373,6 +373,9 @@ it.each([
373
374 function makeLocalCommandHarness(input: {
375 readonly text: string;
376 + readonly manualContinuation?: boolean;
377 + readonly nativeResumeUnsupported?: boolean;
378 + readonly steeringRestart?: boolean;
379 readonly nativeGoals?: boolean;
380 readonly goalDriver?: "opencode" | "antigravity";
381 readonly worktreePath?: string;
@@ -407,6 +410,9 @@ function makeLocalCommandHarness(input: {
410 */
411 readonly sideChat?: {
412 readonly contextRun: "current" | "failed" | "cancelled" | "delivered";
413 + readonly unsentResume?: boolean;
414 + readonly repeatedResume?: boolean;
415 + readonly acceptedResume?: boolean;
416 readonly nativeForkFrom?: "idle" | "busy";
417 readonly switchedProvider?: boolean;
418 readonly threadRuntimeMode?: OrchestrationV2ThreadProjection["thread"]["runtimeMode"];
@@ -426,6 +432,7 @@ function makeLocalCommandHarness(input: {
432 const checkpointScopeId = CheckpointScopeId.make("scope-native-account-command");
433 const messageId = MessageId.make("message-native-account-command");
434 const run: OrchestrationV2ThreadProjection["runs"][number] = {
435 + ...(input.manualContinuation ? { manualContinuationOfRunId: RunId.make("stopped-run") } : {}),
436 id: runId,
437 threadId,
438 ordinal: 2,
@@ -508,7 +515,7 @@ function makeLocalCommandHarness(input: {
515 providerInstanceId: newInstanceId,
516 providerThreadId,
517 providerTurnId: null,
511 - reason: "initial",
518 + reason: input.steeringRestart ? "steering_restart" : "initial",
519 status: "pending",
520 startedAt: null,
521 completedAt: null,
@@ -759,6 +766,71 @@ function makeLocalCommandHarness(input: {
766 ],
767 };
768 }
769 + if (input.sideChat?.unsentResume) {
770 + const originalMessageId = MessageId.make("original-unsent-message");
771 + projection = {
772 + ...projection,
773 + runs: [
774 + {
775 + ...run,
776 + id: RunId.make("stopped-run"),
777 + manualContinuationOfRunId: undefined,
778 + userMessageId: originalMessageId,
779 + status: "interrupted",
780 + ordinal: 1,
781 + },
782 + ...projection.runs,
783 + ],
784 + messages: [
785 + { ...message, id: originalMessageId, text: "Original request" },
786 + ...projection.messages,
787 + ],
788 + };
789 + }
790 + if (input.sideChat?.repeatedResume) {
791 + const retry = RunId.make("stopped-resume");
792 + projection = {
793 + ...projection,
794 + runs: projection.runs
795 + .map((r) => (r.id === runId ? { ...r, manualContinuationOfRunId: retry } : r))
796 + .concat({
797 + ...run,
798 + id: retry,
799 + manualContinuationOfRunId: RunId.make("stopped-run"),
800 + status: "interrupted",
801 + }),
802 + };
803 + }
804 + if (input.sideChat?.acceptedResume) {
805 + const acceptedId = RunAttemptId.make("accepted-original");
806 + projection = {
807 + ...projection,
808 + attempts: [
809 + ...projection.attempts,
810 + {
811 + ...projection.attempts[0]!,
812 + id: acceptedId,
813 + runId: RunId.make("stopped-run"),
814 + providerThreadId: oldProviderThreadId,
815 + status: "interrupted",
816 + },
817 + ],
818 + providerTurns: [
819 + ...projection.providerTurns,
820 + {
821 + id: ProviderTurnId.make("accepted-original-turn"),
822 + runAttemptId: acceptedId,
823 + providerThreadId: oldProviderThreadId,
824 + nodeId: rootNodeId,
825 + ordinal: 1,
826 + nativeTurnRef: null,
827 + status: "interrupted",
828 + startedAt: now,
829 + completedAt: now,
830 + },
831 + ],
832 + };
833 + }
834 if ("historyReadFailureAfterFallback" in input || "resumeFailure" in input) {
835 const nativeThreadRef = {
836 driver: providerThread.driver,
@@ -917,6 +989,10 @@ function makeLocalCommandHarness(input: {
989 resumeThread: () => Effect.succeed(sideChatThread),
990 forkThread,
991 startTurn,
992 + resumeTurn: input.nativeResumeUnsupported
993 + ? undefined
994 + : (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) =>
995 + startTurn(ProviderAdapter.resumeTurnInput(input)),
996 };
997 const open = vi.fn(() =>
998 input.sideChat !== undefined
@@ -954,7 +1030,13 @@ function makeLocalCommandHarness(input: {
1030 (input: RunExecutionService.RunExecutionServiceV2StartRootRunInput) => Effect.Effect<void>
1031 >((runInput) =>
1032 input.sideChat !== undefined
957 - ? runInput.session.startTurn(runInput as never).pipe(Effect.orDie)
1033 + ? (runInput.resume
1034 + ? runInput.session.resumeTurn!({
1035 + ...runInput,
1036 + messageId: runInput.message.messageId,
1037 + } as never)
1038 + : runInput.session.startTurn(runInput as never)
1039 + ).pipe(Effect.orDie)
1040 : input.failReadsAfterRunning === true || input.previousTurn !== undefined
1041 ? Effect.suspend(() =>
1042 providerBusy ? Effect.die("The previous provider turn is still running.") : Effect.void,
@@ -1434,6 +1516,47 @@ effectIt.effect("recovers an abandoned failed turn before continuing its native
1516 }),
1517 );
1518
1519 +effectIt.effect("sends new steering text when restarting a manual continuation", () =>
1520 + Effect.gen(function* () {
1521 + const harness = makeLocalCommandHarness({
1522 + text: "New steering instruction",
1523 + manualContinuation: true,
1524 + steeringRestart: true,
1525 + nativeResumeUnsupported: true,
1526 + sideChat: { contextRun: "delivered" },
1527 + });
1528 + yield* harness.start;
1529 + expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("New steering instruction");
1530 + expect(harness.startRootRun.mock.calls[0]?.[0].resume).toBe(false);
1531 + }),
1532 +);
1533 +
1534 +effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () =>
1535 + Effect.gen(function* () {
1536 + const harness = makeLocalCommandHarness({
1537 + text: "",
1538 + manualContinuation: true,
1539 + nativeResumeUnsupported: true,
1540 + sideChat: { contextRun: "delivered" },
1541 + });
1542 + yield* harness.start;
1543 + expect(harness.startTurn).not.toHaveBeenCalled();
1544 + expect(harness.startRootRun).not.toHaveBeenCalled();
1545 + expect(harness.settledRuns).toEqual(["failed"]);
1546 + expect(harness.projection().turnItems).toEqual(
1547 + expect.arrayContaining([
1548 + expect.objectContaining({
1549 + type: "error",
1550 + failure: expect.objectContaining({
1551 + message:
1552 + "This provider cannot resume without a new message. Send a message to continue.",
1553 + }),
1554 + }),
1555 + ]),
1556 + );
1557 + }),
1558 +);
1559 +
1560 effectIt.effect.each([
1561 { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" },
1562 { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" },
@@ -1445,6 +1568,21 @@ effectIt.effect.each([
1568 context: "SIDE_CHAT_CONTEXT",
1569 },
1570 { contextRun: "delivered", runtimeMode: "full-access", context: "" },
1571 + { contextRun: "delivered", runtimeMode: "full-access", context: "", unsentResume: true },
1572 + {
1573 + contextRun: "delivered",
1574 + runtimeMode: "full-access",
1575 + context: "",
1576 + unsentResume: true,
1577 + repeatedResume: true,
1578 + },
1579 + {
1580 + contextRun: "delivered",
1581 + runtimeMode: "full-access",
1582 + context: "",
1583 + unsentResume: true,
1584 + acceptedResume: true,
1585 + },
1586 {
1587 contextRun: "current",
1588 threadRuntimeMode: "approval-required",
@@ -1456,7 +1594,8 @@ effectIt.effect.each([
1594 ({ runtimeMode, context, ...sideChat }) =>
1595 Effect.gen(function* () {
1596 const harness = makeLocalCommandHarness({
1459 - text: "What is the main thread doing?",
1597 + text: "",
1598 + manualContinuation: true,
1599 sideChat,
1600 });
1601
@@ -1466,8 +1605,14 @@ effectIt.effect.each([
1605 expect.objectContaining({ runtimePolicy: expect.objectContaining({ runtimeMode }) }),
1606 );
1607 expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([
1469 - withInlineContext(context, "What is the main thread doing?"),
1608 + withInlineContext(
1609 + context,
1610 + "unsentResume" in sideChat && !("acceptedResume" in sideChat) ? "Original request" : "",
1611 + ),
1612 ]);
1613 + expect(harness.startTurn.mock.calls[0]?.[0].resume === true).toBe(
1614 + context === "" && (!("unsentResume" in sideChat) || "acceptedResume" in sideChat),
1615 + );
1616 expect(harness.projection().contextHandoffs).toMatchObject([
1617 {
1618 id: "side-chat-context",
@@ -1512,26 +1657,47 @@ effectIt.effect.each([
1657 }),
1658 );
1659
1515 -effectIt.effect.each([
1516 - { goalDriver: "opencode", nativeGoals: false },
1517 - { goalDriver: "opencode", nativeGoals: true },
1518 - { goalDriver: "antigravity", nativeGoals: false },
1519 - { goalDriver: "antigravity", nativeGoals: true },
1520 -] as const)(
1521 - "$goalDriver goal prompts defer switched-provider history only with native support: $nativeGoals",
1522 - ({ goalDriver, nativeGoals }) =>
1660 +effectIt.effect.each(
1661 + (
1662 + [
1663 + { goalDriver: "opencode", nativeGoals: false },
1664 + { goalDriver: "opencode", nativeGoals: true },
1665 + { goalDriver: "antigravity", nativeGoals: false },
1666 + { goalDriver: "antigravity", nativeGoals: true },
1667 + ] as const
1668 + ).flatMap((choice) => [
1669 + { ...choice, resuming: false },
1670 + { ...choice, resuming: true },
1671 + ]),
1672 +)(
1673 + "$goalDriver goal prompts defer switched-provider history only with native support: $nativeGoals, resuming: $resuming",
1674 + ({ goalDriver, nativeGoals, resuming }) =>
1675 Effect.gen(function* () {
1676 const harness = makeLocalCommandHarness({
1525 - text: "/goal all tests pass",
1677 + text: resuming ? "" : "/goal all tests pass",
1678 + manualContinuation: resuming,
1679 goalDriver,
1680 nativeGoals,
1528 - sideChat: { contextRun: "failed", switchedProvider: true },
1681 + sideChat: { contextRun: "failed", switchedProvider: true, unsentResume: resuming },
1682 });
1683 + if (resuming) {
1684 + const projection = harness.projection();
1685 + harness.setProjection({
1686 + ...projection,
1687 + messages: projection.messages.map((message) =>
1688 + message.id === "original-unsent-message"
1689 + ? { ...message, text: "/goal all tests pass" }
1690 + : message,
1691 + ),
1692 + });
1693 + }
1694 harness.tryHandlePromptCommand.mockReturnValue(Effect.succeed(false));
1695 yield* harness.start;
1696 expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("SIDE_CHAT_CONTEXT")).toBe(
1697 !nativeGoals,
1698 );
1699 + if (nativeGoals)
1700 + expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("/goal all tests pass");
1701 }),
1702 );
1703
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+60 -16
@@ -54,6 +54,7 @@ import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDeliv
54 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
55 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
56 import * as ProjectionStore from "./ProjectionStore.ts";
57 +import { unsentManualContinuationSource } from "./manualContinuation.ts";
58 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
59 import {
60 ContextHandoffBackgroundWorkError,
@@ -266,6 +267,12 @@ export const layer: Layer.Layer<
267 return {
268 ...session,
269 startTurn: (input: Parameters<typeof session.startTurn>[0]) => start(input),
270 + ...(session.resumeTurn === undefined
271 + ? {}
272 + : {
273 + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) =>
274 + start(ProviderAdapter.resumeTurnInput(input)),
275 + }),
276 ...(session.compactThread === undefined
277 ? {}
278 : {
@@ -360,6 +367,16 @@ export const layer: Layer.Layer<
367 cause: `Run ${runId} is missing its execution projection state.`,
368 });
369 }
370 + const manualResume =
371 + run.manualContinuationOfRunId !== undefined && attempt.reason !== "steering_restart";
372 + const resumeSource = manualResume
373 + ? unsentManualContinuationSource(run, projection)
374 + : undefined;
375 + const unsentResumeMessage =
376 + resumeSource !== undefined
377 + ? projection.messages.find((source) => source.id === resumeSource.userMessageId)
378 + : undefined;
379 + const providerMessage = unsentResumeMessage ?? message;
380 const settleRunBeforeStart = Effect.fn("orchestrationV2.providerTurnStart.settleBeforeStart")(
381 function* (input: {
382 readonly signal: string;
@@ -479,9 +496,12 @@ export const layer: Layer.Layer<
496 });
497 },
498 );
482 - if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) {
499 + if (
500 + providerMessage.attachments.length === 0 &&
501 + providerMessage.text.trimStart().startsWith("/")
502 + ) {
503 const isEmptyCompaction =
484 - message.text.trim().toLowerCase() === "/compact" && !projection.hasConversation;
504 + providerMessage.text.trim().toLowerCase() === "/compact" && !projection.hasConversation;
505 // Preparation may select a new provider; account commands still target the last native session.
506 const nativeThreads = new Map(
507 projection.providerThreads
@@ -512,8 +532,8 @@ export const layer: Layer.Layer<
532 providerAuth.tryHandlePromptCommand({
533 instanceId: authInstanceId,
534 text: projectComposerContextForProvider({
515 - text: message.text,
516 - records: message.context?.records ?? [],
535 + text: providerMessage.text,
536 + records: providerMessage.context?.records ?? [],
537 }),
538 hasAttachments: false,
539 }),
@@ -551,7 +571,7 @@ export const layer: Layer.Layer<
571 : {
572 type: "command_execution",
573 title: "Provider signed out",
554 - input: message.text.trim(),
574 + input: providerMessage.text.trim(),
575 output: "Provider signed out",
576 exitCode: 0,
577 },
@@ -755,15 +775,15 @@ export const layer: Layer.Layer<
775 let effectiveHandoffs = handoffs;
776 let resumeFellBack = false;
777 const userText = projectComposerContextForProvider({
758 - text: message.text,
759 - records: message.context?.records ?? [],
778 + text: providerMessage.text,
779 + records: providerMessage.context?.records ?? [],
780 });
781 // Native goal commands go verbatim; handoff history waits a turn.
782 const goalDriver =
783 session.driver === "codex" ||
784 session.driver === "claudeAgent" ||
785 session.providerSession.capabilities.turns.supportsNativeGoals === true;
766 - const goalCommand = goalDriver && parseGoalCommand(message) !== null;
786 + const goalCommand = goalDriver && parseGoalCommand(providerMessage) !== null;
787 // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively.
788 const noteContinuation = isRestartNoteContinuation(
789 run,
@@ -936,7 +956,7 @@ export const layer: Layer.Layer<
956 tokenCap,
957 modelContextWindow,
958 userText: restartNote === "" ? userText : `${restartNote}\n\n${userText}`,
939 - attachments: message.attachments,
959 + attachments: providerMessage.attachments,
960 providerThread: budgetProviderThread,
961 nativeContextEstimate:
962 budgetProviderThread.contextUsage?.usedTokens === undefined
@@ -1265,7 +1285,7 @@ export const layer: Layer.Layer<
1285 handoffs: [...handoffs, ...resumedRetryHandoff],
1286 providerThread: { ...resumed.success, id: providerThread.id },
1287 budget: context.budget,
1268 - deferInline: isCompactionCommandMessage(message) || goalCommand,
1288 + deferInline: isCompactionCommandMessage(providerMessage) || goalCommand,
1289 alreadyDeliveredItemIds: context.deliveredItemIds,
1290 persist: () => Effect.void,
1291 }).pipe(
@@ -1448,6 +1468,17 @@ export const layer: Layer.Layer<
1468 legacyInputRunIds,
1469 budget,
1470 } = handoffContext;
1471 + if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) {
1472 + yield* settleStartFailure({
1473 + signal: "resume-unsupported",
1474 + title: "Native resume is unavailable",
1475 + error: new ProviderAdapter.ProviderResumeUnsupportedError({
1476 + driver: session.driver,
1477 + providerThreadId: providerThread.id,
1478 + }),
1479 + });
1480 + return;
1481 + }
1482 const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext));
1483 const runningProviderThread: OrchestrationV2ProviderThread = {
1484 ...loadedProviderThread,
@@ -1649,11 +1680,23 @@ export const layer: Layer.Layer<
1680 .join("\n\n");
1681 const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput;
1682 const text = goalCommand ? userText : withInlineContext(context, userText);
1652 - yield* start({
1653 - ...(noteContinuation ? promptedInput : turnInput),
1654 - message: { ...turnInput.message, text },
1655 - ...(text === userText ? {} : { inlineContextLength: text.length - userText.length }),
1656 - }).pipe(
1683 + const startInput = noteContinuation ? promptedInput : turnInput;
1684 + const { resume: _resume, ...contextInput } = startInput;
1685 + const { message: resumeMessage, resume: _resumeIntent, ...resumeInput } = startInput;
1686 + const operation =
1687 + turnInput.resume && context === "" && session.resumeTurn !== undefined
1688 + ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId })
1689 + : start({
1690 + ...(context === "" ? startInput : contextInput),
1691 + message: {
1692 + ...turnInput.message,
1693 + text,
1694 + },
1695 + ...(text === userText
1696 + ? {}
1697 + : { inlineContextLength: text.length - userText.length }),
1698 + });
1699 + yield* operation.pipe(
1700 // Clear pending handoff markers for refused prompts so the next turn retains the native session.
1701 Effect.tapError((error) =>
1702 refusedBeforePrompt(error)
@@ -1740,6 +1783,7 @@ export const layer: Layer.Layer<
1783 .filter((turn) => turn.providerThreadId === providerThread.id)
1784 .map((turn) => turn.ordinal),
1785 ) + 1,
1786 + resume: manualResume && unsentResumeMessage === undefined,
1787 nativeThreadHasTurns:
1788 nativeInputRunIds.size > 0 ||
1789 (legacyInputRunIds.size > 0 &&
@@ -1753,7 +1797,7 @@ export const layer: Layer.Layer<
1797 message: {
1798 messageId: message.id,
1799 text: userText,
1756 - attachments: message.attachments,
1800 + attachments: providerMessage.attachments,
1801 createdBy: message.createdBy,
1802 creationSource: message.creationSource,
1803 ...(message.scheduledTaskId === undefined
apps/server/src/orchestration-v2/RunExecutionService.ts
+29 -12
@@ -582,6 +582,7 @@ export interface RunExecutionServiceV2StartRootRunInput {
582 readonly baseline?: Effect.Effect<void>;
583 readonly providerTurnOrdinal: number;
584 readonly nativeThreadHasTurns?: boolean;
585 + readonly resume?: boolean;
586 readonly loadInheritedBackgroundTurnItems?: () => Effect.Effect<
587 ReadonlyArray<InheritedBackgroundTurnItemRoute>,
588 unknown
@@ -1962,21 +1963,37 @@ export const layer: Layer.Layer<
1963 const compact =
1964 input.message.attachments.length === 0 &&
1965 input.message.text.trim().toLowerCase() === "/compact";
1965 - const startTurn = compact
1966 - ? (input.session.compactThread?.(turnInput) ??
1967 - Effect.fail(
1968 - new ProviderAdapter.ProviderAdapterTurnStartError({
1969 - driver: input.session.driver,
1970 - threadId: input.run.threadId,
1971 - providerThreadId: input.providerThread.id,
1972 - runId: input.run.id,
1973 - cause: new ProviderAdapter.ProviderCompactionUnsupportedError({
1966 + const { message: _message, ...resumeInput } = turnInput;
1967 + const startTurn =
1968 + input.resume === true
1969 + ? (input.session.resumeTurn?.({ ...resumeInput, messageId: input.message.messageId }) ??
1970 + Effect.fail(
1971 + new ProviderAdapter.ProviderAdapterTurnStartError({
1972 driver: input.session.driver,
1973 + threadId: input.run.threadId,
1974 providerThreadId: input.providerThread.id,
1975 + runId: input.run.id,
1976 + cause: new ProviderAdapter.ProviderResumeUnsupportedError({
1977 + driver: input.session.driver,
1978 + providerThreadId: input.providerThread.id,
1979 + }),
1980 }),
1977 - }),
1978 - ))
1979 - : input.session.startTurn(turnInput);
1981 + ))
1982 + : compact
1983 + ? (input.session.compactThread?.(turnInput) ??
1984 + Effect.fail(
1985 + new ProviderAdapter.ProviderAdapterTurnStartError({
1986 + driver: input.session.driver,
1987 + threadId: input.run.threadId,
1988 + providerThreadId: input.providerThread.id,
1989 + runId: input.run.id,
1990 + cause: new ProviderAdapter.ProviderCompactionUnsupportedError({
1991 + driver: input.session.driver,
1992 + providerThreadId: input.providerThread.id,
1993 + }),
1994 + }),
1995 + ))
1996 + : input.session.startTurn(turnInput);
1997 yield* Effect.andThen(shouldStart, startTurn).pipe(
1998 // Wait for acceptance so abandoned startup cannot leave a refresher
1999 // on the already-detached ingestion fiber.
apps/server/src/orchestration-v2/TurnStartReads.test.ts
+31
@@ -352,6 +352,37 @@ it.effect.each(["sqlite"] as const)(
352 (yield* store.getTurnStartContext(threadId, runId)).messages.map((m) => m.id),
353 marker.id,
354 );
355 + const originalId = MessageId.make("unsent-original");
356 + yield* store.apply({
357 + id: EventId.make("unsent-original-event"),
358 + type: "message.updated",
359 + threadId,
360 + runId: oldRunId,
361 + occurredAt: now,
362 + payload: { ...message, id: originalId, runId: oldRunId, text: "Original request" },
363 + });
364 + yield* putRun({
365 + ...run,
366 + id: oldRunId,
367 + ordinal: 1,
368 + status: "interrupted",
369 + userMessageId: originalId,
370 + });
371 + const retryId = RunId.make("unsent-retry");
372 + yield* putRun({ ...run, ordinal: 3, manualContinuationOfRunId: retryId });
373 + yield* putRun({
374 + ...run,
375 + id: retryId,
376 + ordinal: 2,
377 + status: "interrupted",
378 + manualContinuationOfRunId: oldRunId,
379 + });
380 + assert.equal(
381 + (yield* store.getTurnStartContext(threadId, runId)).messages.find(
382 + (m) => m.id === originalId,
383 + )?.text,
384 + "Original request",
385 + );
386 const other = ThreadId.make("other");
387 yield* putThread({ ...thread, id: other });
388 assert.deepEqual((yield* store.getTurnStartContext(other, runId)).messages, []);
apps/server/src/orchestration-v2/manualContinuation.ts new
+25
@@ -0,0 +1,25 @@
1 +import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2 +
3 +export function unsentManualContinuationSource(
4 + run: OrchestrationV2Run | undefined,
5 + projection: Pick<OrchestrationV2ThreadProjection, "runs" | "attempts" | "providerTurns">,
6 +) {
7 + let sourceId = run?.manualContinuationOfRunId;
8 + if (sourceId === undefined) return undefined;
9 + const runs = new Map(projection.runs.map((source) => [source.id, source]));
10 + const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId));
11 + const acceptedRuns = new Set(
12 + projection.attempts
13 + .filter((attempt) => acceptedAttempts.has(attempt.id))
14 + .map((attempt) => attempt.runId),
15 + );
16 + const visited = new Set<OrchestrationV2Run["id"]>();
17 + while (sourceId !== undefined && !visited.has(sourceId)) {
18 + visited.add(sourceId);
19 + const source = runs.get(sourceId);
20 + if (source === undefined || acceptedRuns.has(sourceId)) return undefined;
21 + if (source.manualContinuationOfRunId === undefined) return source;
22 + sourceId = source.manualContinuationOfRunId;
23 + }
24 + return undefined;
25 +}
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+11
@@ -10832,6 +10832,17 @@ it.layer(layerTest)("usage-limit recovery", (it) => {
10832 assert.lengthOf(after.runs, 3);
10833 assert.equal(after.runs[1]?.status, "queued");
10834 assert.equal(after.runs[2]?.status, "starting");
10835 + assert.equal(after.runs[2]?.manualContinuationOfRunId, source.id);
10836 + const resumeMessage = after.messages.find(
10837 + (message) => message.id === resume("first").messageId,
10838 + );
10839 + assert.equal(resumeMessage?.text, "");
10840 + assert.equal(resumeMessage?.notification?.summary, "Resumed thread");
10841 + assert.isFalse(
10842 + after.turnItems.some(
10843 + (item) => item.runId === after.runs[2]?.id && item.type === "user_message",
10844 + ),
10845 + );
10846 assert.equal(
10847 (yield* orchestrator.dispatch(resume("second")).pipe(Effect.exit))._tag,
10848 "Failure",
apps/web/src/components/chat/useComposerResume.ts
+2 -2
@@ -49,7 +49,7 @@ interface ComposerResumeInput {
49 }
50
51 /**
52 - * Resumes an interrupted run ("Continue where you left off.") and/or releases the turns held
52 + * Resumes an interrupted run and/or releases the turns held
53 * in its queue. Shares the per-route send lock with the composer's send paths.
54 */
55 export function useComposerResume(input: ComposerResumeInput) {
@@ -130,7 +130,7 @@ export function useComposerResume(input: ComposerResumeInput) {
130 message: {
131 messageId: newMessageId(),
132 role: "user",
133 - text: "Continue where you left off.",
133 + text: "",
134 attachments: [],
135 },
136 runtimeMode,
docs/user/composer.md
+6 -2
@@ -258,8 +258,12 @@ images. **Send now** sends a message right away, into the running turn if there
258 also edit or remove it.
259
260 If you stop the agent or the server restarts, queued messages keep their order and are held.
261 -Press **Resume** in an empty composer to continue. **Resume** also continues a stopped
262 -run or one that hit a usage limit, even with nothing queued. Sending a new message also resumes the queue, unless it steers a turn that is already
261 +Press **Resume** in an empty composer to continue. For stopped runs and usage limits,
262 +this uses the provider's native continuation without sending a new prompt. If the provider
263 +does not support it, send a message to continue instead. If the original request never reached
264 +the provider, Resume sends that request again.
265 +
266 +Sending a new message also resumes the queue, unless it steers a turn that is already
267 running. You can edit or remove held messages without starting them.
268
269 The pencil on a queued message opens it in the composer for editing. The original message
docs/user/thread-sidebar.md
+2 -2
@@ -250,8 +250,8 @@ thread** from its long-press menu on mobile.
250 keeps the provider's explanation. Retry after the limit resets, or switch to
251 another provider instance.
252 Press **Resume** in an empty composer to continue a limited or interrupted turn
253 -manually. Do this when the provider reports no reset time, because nothing
254 -continues the turn on its own.
253 +manually when the provider supports native continuation, or send a message to continue.
254 +Do this when the provider reports no reset time, because nothing continues the turn on its own.
255 Queued messages stay saved while the limit blocks the thread. They run after
256 the continuation finishes. If the queue was held by a restart, resume it then.
257
packages/contracts/src/orchestrationV2.ts
+1
@@ -741,6 +741,7 @@ export const OrchestrationV2Run = Schema.Struct({
741 checkpointId: Schema.NullOr(CheckpointId),
742 contextHandoffId: Schema.NullOr(ContextHandoffId),
743 restartContinuationOfRunId: Schema.optional(RunId),
744 + manualContinuationOfRunId: Schema.optional(RunId),
745 usageLimitContinuationOfRunId: Schema.optional(RunId),
746 delegatedTaskId: Schema.optional(NodeId),
747 workStartedAt: Schema.optional(Schema.DateTimeUtc),
packages/provider-core/src/server/ProviderAdapter.ts
+32
@@ -277,6 +277,15 @@ export class ProviderAdapterThreadInUseError extends Schema.TaggedError<Provider
277 /**
278 * The user sent `/compact` to a driver whose session has no native compaction.
279 */
280 +export class ProviderResumeUnsupportedError extends Schema.TaggedError<ProviderResumeUnsupportedError>()(
281 + "ProviderResumeUnsupportedError",
282 + { driver: ProviderDriverKind, providerThreadId: ProviderThreadId },
283 +) {
284 + override get message(): string {
285 + return "This provider cannot resume without a new message. Send a message to continue.";
286 + }
287 +}
288 +
289 export class ProviderCompactionUnsupportedError extends Schema.TaggedError<ProviderCompactionUnsupportedError>()(
290 "ProviderCompactionUnsupportedError",
291 {
@@ -491,6 +500,7 @@ export const ProviderAdapterV2Error = Schema.Union([
500 ProviderAdapterRollbackThreadError,
501 ProviderAdapterForkThreadError,
502 ProviderAdapterTurnStartError,
503 + ProviderResumeUnsupportedError,
504 ProviderAdapterSteerRunUnsupportedError,
505 ProviderAdapterSteerRunError,
506 ProviderAdapterSteerDeclinedError,
@@ -533,6 +543,7 @@ export interface ProviderAdapterV2TurnInput {
543 readonly nativeThreadHasTurns?: boolean;
544 readonly providerTurnOrdinal: number;
545 readonly restartContinuationOfRunId?: RunId;
546 + readonly resume?: true;
547 readonly attemptId: RunAttemptId;
548 readonly rootNodeId: NodeId;
549 readonly providerThread: OrchestrationV2ProviderThread;
@@ -544,6 +555,24 @@ export interface ProviderAdapterV2TurnInput {
555 readonly appContext?: ReadonlyArray<{ readonly key: string; readonly text: string }>;
556 }
557
558 +export type ProviderAdapterV2ResumeTurnInput = Omit<
559 + ProviderAdapterV2TurnInput,
560 + "message" | "resume"
561 +> & {
562 + readonly messageId: MessageId;
563 +};
564 +
565 +export function resumeTurnInput(
566 + input: ProviderAdapterV2ResumeTurnInput,
567 +): ProviderAdapterV2TurnInput {
568 + const { messageId, ...turn } = input;
569 + return {
570 + ...turn,
571 + resume: true,
572 + message: { messageId, text: "", attachments: [], createdBy: "user", creationSource: "server" },
573 + };
574 +}
575 +
576 export interface ProviderAdapterV2SteerInput {
577 readonly threadId: ThreadId;
578 readonly runId: RunId;
@@ -707,6 +736,9 @@ export interface ProviderAdapterV2SessionRuntime {
736 readonly startTurn: (
737 input: ProviderAdapterV2TurnInput,
738 ) => Effect.Effect<void, ProviderAdapterV2Error>;
739 + readonly resumeTurn?: (
740 + input: ProviderAdapterV2ResumeTurnInput,
741 + ) => Effect.Effect<void, ProviderAdapterV2Error>;
742 readonly compactThread?: (
743 input: ProviderAdapterV2TurnInput,
744 ) => Effect.Effect<void, ProviderAdapterV2Error>;
packages/provider-opencode/src/server/adapter.test.ts
+10 -1
@@ -202,6 +202,7 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
202 text = "hello",
203 startProviderThread: OrchestrationV2ProviderThread = providerThread,
204 turnPolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy = policy,
205 + resume = false,
206 ) =>
207 runtime.startTurn({
208 appThread: {
@@ -234,6 +235,7 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
235 attemptId: RunAttemptId.make(`attempt-opencode-${suffix}`),
236 rootNodeId: NodeId.make(`node-opencode-${suffix}`),
237 providerThread: startProviderThread,
238 + ...(resume ? { resume: true as const } : {}),
239 message: {
240 createdBy: "user",
241 creationSource: "web",
@@ -264,6 +266,7 @@ describe("OpenCodeAdapterV2", () => {
266 ["unknown", "prompt"],
267 ["failure", "prompt"],
268 ["unset", "prompt"],
269 + ["unset", "resume"],
270 ] as const)("normalizes reasoning variants for %s inventory at %s dispatch", ([kind, request]) =>
271 Effect.gen(function* () {
272 const suffix = `variant-${kind}-${request}`;
@@ -329,10 +332,16 @@ describe("OpenCodeAdapterV2", () => {
332 ],
333 },
334 );
332 - yield* harness.startTurn(request === "command" ? "/review staged changes" : "hello");
335 + yield* harness.startTurn(
336 + request === "command" ? "/review staged changes" : request === "resume" ? "" : "hello",
337 + harness.providerThread,
338 + harness.policy,
339 + request === "resume",
340 + );
341 assert.equal(inputs.length, 1);
342 const payload = inputs[0]!;
343 assert.equal(payload.agent, "plan");
344 + if (request === "resume") assert.deepEqual(payload.parts, []);
345 if (kind === "supported" || kind === "unknown" || kind === "failure") {
346 assert.equal(payload.variant, "medium");
347 } else {
packages/provider-opencode/src/server/adapter.ts
+2
@@ -3090,6 +3090,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3090 const resolvePromptParts = Effect.fnUntraced(function* (
3091 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
3092 ) {
3093 + if (turnInput.resume) return [];
3094 const text = (yield* providerMessageTextWithAttachmentPaths({
3095 text: turnInput.message.text,
3096 attachments: turnInput.message.attachments,
@@ -3394,6 +3395,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3395 ...turnInput,
3396 message: { ...turnInput.message, text: "/compact" },
3397 }),
3398 + resumeTurn: (input) => runtimeSession.startTurn(ProviderAdapter.resumeTurnInput(input)),
3399 startTurn: Effect.fn("OpencodeAdapter.startTurn")(
3400 function* (turnInput) {
3401 if (nativeStreamFailure !== null) {
packages/provider-opencode/src/server/v2/adapter.ts
+2 -1
@@ -4540,7 +4540,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4540 const mentions = skillMentions(text);
4541 const skills = mentions.length === 0 ? [] : yield* skillsMentioned(location, mentions);
4542 const files = yield* promptFiles(turnInput.message.attachments);
4543 - const messageText = yield* promptText(turnInput);
4543 + const messageText = turnInput.resume ? "" : yield* promptText(turnInput);
4544 if (!sending()) return;
4545 return yield* client.session
4546 .prompt({
@@ -4704,6 +4704,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4704 ),
4705 compactThread: (turnInput) =>
4706 runtime.startTurn({ ...turnInput, message: { ...turnInput.message, text: "/compact" } }),
4707 + resumeTurn: (input) => runtime.startTurn(ProviderAdapter.resumeTurnInput(input)),
4708 startTurn: Effect.fn("OpenCode2Adapter.startTurn")(
4709 function* (turnInput) {
4710 // Waited out before the session's gate, so a rollback or fork is not