@devries-cameron20 / t3code Mirror · read-only / commits / ccae953c46
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, 09:45 UTC

fix(server): ACP agents keep the kept conversation after Edit from here (#30188)

Julius Marminge committed Nov 16, 2026 at 19:23 UTC ccae953c46c09255038897b2872eb4952f8637e5
8 files changed +463 -68
apps/server/src/orchestration-v2/CommandPolicy.ts
+3 -1
@@ -322,9 +322,11 @@ const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
322 };
323
324 const ensureRollback: CommandPolicyV2Shape["ensureRollback"] = (input) => {
325 + // Without native truncation, the next turn replays the kept conversation as a handoff.
326 if (
327 !input.capabilities.threads.canRollbackThread ||
327 - !input.capabilities.checkpointing.providerCanRollbackConversation
328 + (!input.capabilities.checkpointing.providerCanRollbackConversation &&
329 + !input.capabilities.context.canConsumeHandoffSummaries)
330 ) {
331 return Effect.fail(
332 unsupported(input, "rollback", "providerInstanceId conversation rollback is unavailable"),
apps/server/src/orchestration-v2/Orchestrator.ts
+1 -36
@@ -82,6 +82,7 @@ import {
82 import * as KeyedLock from "@t3tools/shared/KeyedLock";
83 import { modelSelectionsEqual } from "@t3tools/shared/model";
84 import { modelSwitchSince } from "./modelSwitch.ts";
85 +import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts";
86 import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts";
87 import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
88 import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
@@ -1364,42 +1365,6 @@ function appendContextHandoffId(
1365 return handoffId === null ? handoffIds : Array.from(new Set([...handoffIds, handoffId]));
1366 }
1367
1367 -/** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */
1368 -function isScheduledFreshRun(
1369 - run: Pick<OrchestrationV2Run, "freshContext" | "userMessageId">,
1370 - turnItems: OrchestrationV2ThreadProjection["turnItems"],
1371 -): boolean {
1372 - // Turn items, unlike messages, are not narrowed to the runs since the latest compaction.
1373 - return (
1374 - run.freshContext === true &&
1375 - turnItems.some(
1376 - (item) =>
1377 - item.type === "user_message" &&
1378 - item.messageId === run.userMessageId &&
1379 - item.scheduledTaskId !== undefined,
1380 - )
1381 - );
1382 -}
1383 -
1384 -/** Ordinal of the latest started fresh-context run. Runs before it never reach a provider again. */
1385 -function contextBoundaryOrdinal(
1386 - projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
1387 -): number {
1388 - let boundary = 0;
1389 - for (const run of projection.runs) {
1390 - if (
1391 - run.freshContext === true &&
1392 - run.status !== "queued" &&
1393 - !cancelledBeforeStart(run) &&
1394 - run.ordinal > boundary &&
1395 - !isScheduledFreshRun(run, projection.turnItems)
1396 - ) {
1397 - boundary = run.ordinal;
1398 - }
1399 - }
1400 - return boundary;
1401 -}
1402 -
1368 /** The provider thread a message continues: the active one, unless a fresh-session schedule run started it. */
1369 function conversationProviderThread(
1370 projection: Pick<
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+14 -13
@@ -1028,19 +1028,6 @@ function makeLocalCommandHarness(input: {
1028 ),
1029 );
1030 const fallbackEnsureThread = vi.fn(() => Effect.succeed(providerThread));
1031 - const resumeFallbackSession = {
1032 - driver: providerThread.driver,
1033 - resumeThread: () =>
1034 - Effect.fail(
1035 - input.resumeFailure ??
1036 - new ProviderAdapter.ProviderAdapterEventStreamError({
1037 - driver: providerThread.driver,
1038 - providerSessionId,
1039 - cause: "native thread is gone",
1040 - }),
1041 - ),
1042 - ensureThread: fallbackEnsureThread,
1043 - };
1031 const providerSession = {
1032 id: providerSessionId,
1033 driver: providerThread.driver,
@@ -1059,6 +1046,20 @@ function makeLocalCommandHarness(input: {
1046 updatedAt: now,
1047 lastError: null,
1048 };
1049 + const resumeFallbackSession = {
1050 + driver: providerThread.driver,
1051 + providerSession,
1052 + resumeThread: () =>
1053 + Effect.fail(
1054 + input.resumeFailure ??
1055 + new ProviderAdapter.ProviderAdapterEventStreamError({
1056 + driver: providerThread.driver,
1057 + providerSessionId,
1058 + cause: "native thread is gone",
1059 + }),
1060 + ),
1061 + ensureThread: fallbackEnsureThread,
1062 + };
1063 const startTurn = vi.fn((_turn: ProviderAdapter.ProviderAdapterV2TurnInput) => Effect.void);
1064 const sideChatThread = {
1065 ...providerThread,
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+83 -12
@@ -9,6 +9,7 @@ import {
9 type OrchestrationV2ProviderThread,
10 type OrchestrationV2Run,
11 type OrchestrationV2RunAttempt,
12 + type OrchestrationV2ThreadProjection,
13 type OrchestrationV2TurnItem,
14 isCompactionCommandMessage,
15 parseGoalCommand,
@@ -43,6 +44,7 @@ import * as EventSink from "./EventSink.ts";
44 import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";
45 import * as ContextHandoffService from "./ContextHandoffService.ts";
46 import { isActiveRun } from "./CommandPolicy.ts";
47 +import { contextBoundaryOrdinal } from "./contextBoundary.ts";
48 import {
49 DEFAULT_HANDOFF_TOKEN_CAP,
50 handoffTokenCapConfig,
@@ -118,6 +120,53 @@ const refusedBeforePrompt = (error: unknown): boolean =>
120 error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) ||
121 (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause));
122
123 +/**
124 + * Whether a non-truncating provider's native session lost the conversation kept before `run`.
125 + * Rollback resets it: the newest accepted turn was rolled back (works without legacy-missing
126 + * native ids) or ran under another native id (rollback of runs the provider never accepted).
127 + */
128 +const nativeSessionMissesKeptTurns = (
129 + projection: Pick<
130 + OrchestrationV2ThreadProjection,
131 + "thread" | "runs" | "attempts" | "providerTurns" | "contextHandoffs"
132 + >,
133 + providerThread: OrchestrationV2ProviderThread,
134 + run: OrchestrationV2Run,
135 +): boolean => {
136 + const nativeId = providerThread.nativeThreadRef?.nativeId;
137 + if (nativeId === undefined) return false;
138 + const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId));
139 + const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id));
140 + const runsById = new Map(projection.runs.map((source) => [source.id, source]));
141 + const ordinalOf = (attempt: OrchestrationV2RunAttempt) =>
142 + runsById.get(attempt.runId)?.ordinal ?? 0;
143 + const newest = accepted
144 + .filter((attempt) => attempt.providerThreadId === providerThread.id)
145 + .toSorted((a, b) => ordinalOf(a) - ordinalOf(b) || a.attemptOrdinal - b.attemptOrdinal)
146 + .at(-1);
147 + if (newest === undefined) return false;
148 + // Inherited fork history is kept even when every local run was rolled back.
149 + const keepsHistory =
150 + (projection.thread.forkedFrom?.type === "run" && projection.thread.lineage.sideChat !== true) ||
151 + accepted.some((attempt) => {
152 + const source = runsById.get(attempt.runId);
153 + return (
154 + source !== undefined && source.ordinal < run.ordinal && source.status !== "rolled_back"
155 + );
156 + });
157 + return (
158 + keepsHistory &&
159 + (runsById.get(newest.runId)?.status === "rolled_back" ||
160 + (newest.nativeThreadId !== undefined && newest.nativeThreadId !== nativeId)) &&
161 + !projection.contextHandoffs.some(
162 + (handoff) =>
163 + handoff.toProviderThreadId === providerThread.id &&
164 + handoff.delivery?.nativeThreadId === nativeId &&
165 + handoff.delivery.status !== "pending",
166 + )
167 + );
168 +};
169 +
170 /** Missing execution records cannot be repaired by retrying a start. */
171 export class ProviderTurnStartRunStateMissingError extends Schema.TaggedError<ProviderTurnStartRunStateMissingError>()(
172 "ProviderTurnStartRunStateMissingError",
@@ -1084,6 +1133,8 @@ export const layer: Layer.Layer<
1133 type: "provider_resume_fallback",
1134 });
1135 const createdAt = yield* DateTime.now;
1136 + const history = yield* projectionStore.getTurnStartHistory(input.threadId);
1137 + const boundary = contextBoundaryOrdinal({ runs: projection.runs, turnItems: history });
1138 const handoff = yield* contextHandoffService.prepareProviderHandoff({
1139 threadId: projection.thread.id,
1140 targetRunId: run.id,
@@ -1095,13 +1146,25 @@ export const layer: Layer.Layer<
1146 coveredRunOrdinals: { from: 1, to: Math.max(1, run.ordinal - 1) },
1147 strategy: "full_thread_summary",
1148 runs: projection.runs,
1098 - items: (yield* projectionStore.getTurnStartHistory(input.threadId)).filter(
1099 - (item) =>
1100 - item.runId === null ||
1101 - projection.runs.some(
1102 - (source) => source.id === item.runId && source.ordinal < run.ordinal,
1103 - ),
1104 - ),
1149 + items: [
1150 + ...(boundary === 0
1151 + ? yield* ContextHandoffService.readInheritedHandoffItems(
1152 + projectionStore,
1153 + projection.thread,
1154 + )
1155 + : []),
1156 + ...history.filter((item) =>
1157 + item.runId === null
1158 + ? boundary === 0
1159 + : projection.runs.some(
1160 + (source) =>
1161 + source.id === item.runId &&
1162 + source.ordinal >= boundary &&
1163 + source.ordinal < run.ordinal &&
1164 + source.status !== "rolled_back",
1165 + ),
1166 + ),
1167 + ],
1168 createdAt,
1169 });
1170 return { handoff, transferId, createdAt };
@@ -1328,15 +1391,21 @@ export const layer: Layer.Layer<
1391 handoff.delivery?.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
1392 handoff.delivery?.status === "pending",
1393 );
1394 + // A provider that cannot truncate rolls back into a fresh native session holding none of the kept turns.
1395 + const nativeSessionLacksKeptTurns =
1396 + !session.providerSession.capabilities.checkpointing.providerCanRollbackConversation &&
1397 + nativeSessionMissesKeptTurns(projection, providerThread, run);
1398 const resumed = yield* Effect.result(
1332 - uncertainDelivery
1399 + uncertainDelivery || nativeSessionLacksKeptTurns
1400 ? Effect.fail(
1401 new ProviderAdapter.ProviderAdapterTurnStartError({
1402 driver: session.driver,
1403 threadId: projection.thread.id,
1404 providerThreadId: providerThread.id,
1405 runId,
1339 - cause: "Uncertain native history injection",
1406 + cause: uncertainDelivery
1407 + ? "Uncertain native history injection"
1408 + : "Native session holds none of the kept conversation",
1409 }),
1410 )
1411 : session.resumeThread({
@@ -1416,9 +1485,11 @@ export const layer: Layer.Layer<
1485 runId,
1486 reason: uncertainDelivery
1487 ? "uncertain_history_delivery"
1419 - : resumed._tag === "Success"
1420 - ? "handoff_budget_exhausted"
1421 - : "resume_failed",
1488 + : nativeSessionLacksKeptTurns
1489 + ? "native_session_lacks_kept_turns"
1490 + : resumed._tag === "Success"
1491 + ? "handoff_budget_exhausted"
1492 + : "resume_failed",
1493 errorTag: resumed._tag === "Failure" ? resumed.failure._tag : "ContextHandoffBudgetError",
1494 });
1495 const replacement = yield* loadFromProvider(
apps/server/src/orchestration-v2/contextBoundary.ts new
+39
@@ -0,0 +1,39 @@
1 +import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts";
2 +
3 +import { cancelledBeforeStart } from "./RestartBackgroundNote.ts";
4 +
5 +/** A fresh-session schedule run starts a side conversation; the thread's own one continues past it. */
6 +export function isScheduledFreshRun(
7 + run: Pick<OrchestrationV2Run, "freshContext" | "userMessageId">,
8 + turnItems: OrchestrationV2ThreadProjection["turnItems"],
9 +): boolean {
10 + // Turn items, unlike messages, are not narrowed to the runs since the latest compaction.
11 + return (
12 + run.freshContext === true &&
13 + turnItems.some(
14 + (item) =>
15 + item.type === "user_message" &&
16 + item.messageId === run.userMessageId &&
17 + item.scheduledTaskId !== undefined,
18 + )
19 + );
20 +}
21 +
22 +/** Ordinal of the latest started fresh-context run. Runs before it never reach a provider again. */
23 +export function contextBoundaryOrdinal(
24 + projection: Pick<OrchestrationV2ThreadProjection, "runs" | "turnItems">,
25 +): number {
26 + let boundary = 0;
27 + for (const run of projection.runs) {
28 + if (
29 + run.freshContext === true &&
30 + run.status !== "queued" &&
31 + !cancelledBeforeStart(run) &&
32 + run.ordinal > boundary &&
33 + !isScheduledFreshRun(run, projection.turnItems)
34 + ) {
35 + boundary = run.ordinal;
36 + }
37 + }
38 + return boundary;
39 +}
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+319 -2
@@ -131,6 +131,8 @@ function makeTestAdapter(input: {
131 readonly backgroundTasksEndWithProcess?: true;
132 readonly backgroundWork?: Ref.Ref<boolean>;
133 readonly closedSessions?: Ref.Ref<ReadonlyArray<string>>;
134 + // ACP cannot truncate, so its rollback answers with a fresh, empty native session.
135 + readonly rollback?: "truncates" | "replaces_native_thread";
136 }): ProviderAdapter.ProviderAdapterV2["Service"] {
137 return {
138 instanceId: input.instanceId,
@@ -448,8 +450,25 @@ function makeTestAdapter(input: {
450 respondToRuntimeRequest: () => Effect.void,
451 readThreadSnapshot: () =>
452 unimplemented(input.driver, "readThreadSnapshot unused in provider switch test"),
451 - rollbackThread: () =>
452 - unimplemented(input.driver, "rollbackThread unused in provider switch test"),
453 + rollbackThread: ({ providerThread }) =>
454 + input.rollback === undefined
455 + ? unimplemented(input.driver, "rollbackThread unused in provider switch test")
456 + : Effect.succeed({
457 + providerThread:
458 + input.rollback === "truncates" || providerThread.nativeThreadRef === null
459 + ? providerThread
460 + : {
461 + ...providerThread,
462 + nativeThreadRef: {
463 + ...providerThread.nativeThreadRef,
464 + nativeId: `${providerThread.nativeThreadRef.nativeId}:after-rollback`,
465 + },
466 + nativeConversationHeadRef: null,
467 + },
468 + providerTurns: [],
469 + messages: [],
470 + runtimeRequests: [],
471 + }),
472 forkThread: () =>
473 unimplemented(input.driver, "forkThread unused in provider switch test"),
474 };
@@ -1630,6 +1649,304 @@ describe("orchestration v2 provider switching", () => {
1649 }),
1650 );
1651
1652 + it.live.each([
1653 + {
1654 + name: "an ACP rollback that starts a fresh agent session",
1655 + instanceId: GROK_MODEL_SELECTION.instanceId,
1656 + driver: GROK_DRIVER,
1657 + capabilities: AcpProviderCapabilitiesV2,
1658 + modelSelection: GROK_MODEL_SELECTION,
1659 + rollback: "replaces_native_thread",
1660 + failResumeAfterRollback: false,
1661 + history: "plain",
1662 + delivers: ["favourite colour is teal"],
1663 + withholds: ["favourite animal is an otter"],
1664 + },
1665 + {
1666 + name: "a native rollback whose next resume fails",
1667 + instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1668 + driver: CLAUDE_DRIVER,
1669 + capabilities: ClaudeProviderCapabilitiesV2,
1670 + modelSelection: CLAUDE_MODEL_SELECTION,
1671 + rollback: "truncates",
1672 + failResumeAfterRollback: true,
1673 + history: "plain",
1674 + delivers: ["favourite colour is teal"],
1675 + withholds: ["favourite animal is an otter"],
1676 + },
1677 + {
1678 + // Pi forks into a new native thread that still holds the kept turns.
1679 + name: "a native rollback that forks a new native thread",
1680 + instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1681 + driver: CLAUDE_DRIVER,
1682 + capabilities: ClaudeProviderCapabilitiesV2,
1683 + modelSelection: CLAUDE_MODEL_SELECTION,
1684 + rollback: "replaces_native_thread",
1685 + failResumeAfterRollback: false,
1686 + history: "plain",
1687 + delivers: [],
1688 + withholds: ["favourite colour is teal", "favourite animal is an otter"],
1689 + },
1690 + {
1691 + name: "an ACP rollback where no attempt recorded its native session",
1692 + instanceId: GROK_MODEL_SELECTION.instanceId,
1693 + driver: GROK_DRIVER,
1694 + capabilities: AcpProviderCapabilitiesV2,
1695 + modelSelection: GROK_MODEL_SELECTION,
1696 + rollback: "replaces_native_thread",
1697 + failResumeAfterRollback: false,
1698 + history: "legacy_all_turns",
1699 + delivers: ["favourite colour is teal"],
1700 + withholds: ["favourite animal is an otter"],
1701 + },
1702 + {
1703 + name: "an ACP rollback of a forked thread to its baseline",
1704 + instanceId: GROK_MODEL_SELECTION.instanceId,
1705 + driver: GROK_DRIVER,
1706 + capabilities: AcpProviderCapabilitiesV2,
1707 + modelSelection: GROK_MODEL_SELECTION,
1708 + rollback: "replaces_native_thread",
1709 + failResumeAfterRollback: false,
1710 + history: "forked_to_baseline",
1711 + delivers: ["home town is Oslo"],
1712 + withholds: ["favourite colour is teal", "favourite animal is an otter"],
1713 + },
1714 + {
1715 + name: "an ACP rollback in a thread restarted with fresh context",
1716 + instanceId: GROK_MODEL_SELECTION.instanceId,
1717 + driver: GROK_DRIVER,
1718 + capabilities: AcpProviderCapabilitiesV2,
1719 + modelSelection: GROK_MODEL_SELECTION,
1720 + rollback: "replaces_native_thread",
1721 + failResumeAfterRollback: false,
1722 + history: "after_fresh_context",
1723 + delivers: ["favourite colour is teal"],
1724 + withholds: ["home town is Oslo", "favourite animal is an otter"],
1725 + },
1726 + ] as const)(
1727 + "gives the agent the kept conversation and not the rewound turn after $name",
1728 + (scenario) =>
1729 + Effect.scoped(
1730 + Effect.gen(function* () {
1731 + const name = `rollback-kept-context-${scenario.driver}-${scenario.history}`;
1732 + const cwd = yield* checkpointWorkspace(name);
1733 + const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1734 + const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1735 + const failResumeOnce = yield* Ref.make(false);
1736 + const nativeThreadGeneration = yield* Ref.make(0);
1737 + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1738 + makeTestAdapter({
1739 + instanceId: scenario.instanceId,
1740 + driver: scenario.driver,
1741 + capabilities: scenario.capabilities,
1742 + modelSelection: scenario.modelSelection,
1743 + responseByRunOrdinal: { 1: "noted", 2: "noted", 3: "noted" },
1744 + capturedTurns,
1745 + injectedHistory,
1746 + failResumeOnce,
1747 + nativeThreadGeneration,
1748 + rollback: scenario.rollback,
1749 + }),
1750 + ]);
1751 + yield* Effect.gen(function* () {
1752 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1753 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1754 + const runToCompletion = Effect.fn("runToCompletion")(function* (
1755 + ordinal: number,
1756 + text: string,
1757 + thread: ThreadId = threadId,
1758 + freshContext = false,
1759 + ) {
1760 + yield* orchestrator.dispatch({
1761 + type: "message.dispatch",
1762 + commandId: CommandId.make(`${thread}:${ordinal}`),
1763 + threadId: thread,
1764 + messageId: MessageId.make(`${thread}:${ordinal}`),
1765 + createdBy: "user",
1766 + creationSource: "web",
1767 + text,
1768 + attachments: [],
1769 + modelSelection: scenario.modelSelection,
1770 + ...(freshContext ? { freshContext: true } : {}),
1771 + dispatchMode: { type: "start_immediately" },
1772 + });
1773 + yield* orchestrator.streamStoredEvents.pipe(
1774 + Stream.filter(
1775 + ({ event }) =>
1776 + event.type === "run.updated" &&
1777 + event.threadId === thread &&
1778 + event.payload.ordinal === ordinal &&
1779 + (event.payload.status === "completed" || event.payload.status === "failed"),
1780 + ),
1781 + Stream.runHead,
1782 + );
1783 + yield* worker.drain();
1784 + });
1785 + const createThread = (thread: ThreadId) =>
1786 + orchestrator.dispatch({
1787 + type: "thread.create",
1788 + commandId: CommandId.make(`${thread}:create`),
1789 + threadId: thread,
1790 + projectId,
1791 + createdBy: "user",
1792 + creationSource: "web",
1793 + title: "Edit from here",
1794 + modelSelection: scenario.modelSelection,
1795 + runtimeMode: "full-access",
1796 + interactionMode: "default",
1797 + branch: null,
1798 + worktreePath: null,
1799 + });
1800 + if (scenario.history === "forked_to_baseline") {
1801 + const sourceThreadId = ThreadId.make(`${name}:source`);
1802 + yield* createThread(sourceThreadId);
1803 + yield* runToCompletion(
1804 + 1,
1805 + "My home town is Oslo. Reply with only the word: noted",
1806 + sourceThreadId,
1807 + );
1808 + yield* orchestrator.dispatch({
1809 + type: "thread.fork",
1810 + commandId: CommandId.make(`${name}:fork`),
1811 + sourceThreadId,
1812 + targetThreadId: threadId,
1813 + sourcePoint: {
1814 + type: "run",
1815 + runId: (yield* orchestrator.getThreadProjection(sourceThreadId)).runs[0]!.id,
1816 + },
1817 + createdBy: "user",
1818 + creationSource: "web",
1819 + });
1820 + } else {
1821 + yield* createThread(threadId);
1822 + }
1823 + // Runs before a fresh-context run never reach a provider again.
1824 + const first = scenario.history === "after_fresh_context" ? 2 : 1;
1825 + if (first === 2) {
1826 + yield* runToCompletion(1, "My home town is Oslo. Reply with only the word: noted");
1827 + }
1828 + yield* runToCompletion(
1829 + first,
1830 + "My favourite colour is teal. Reply with only the word: noted",
1831 + threadId,
1832 + first === 2,
1833 + );
1834 + yield* runToCompletion(
1835 + first + 1,
1836 + "My favourite animal is an otter. Reply with only the word: noted",
1837 + );
1838 + const beforeRollback = yield* orchestrator.getThreadProjection(threadId);
1839 + if (scenario.history === "legacy_all_turns") {
1840 + yield* (yield* EventSink.EventSinkV2).write({
1841 + events: beforeRollback.attempts.map(
1842 + ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
1843 + id: EventId.make(`${name}:legacy-attempt:${index}`),
1844 + type: "run-attempt.updated" as const,
1845 + threadId,
1846 + occurredAt: beforeRollback.thread.createdAt,
1847 + payload: legacy,
1848 + }),
1849 + ),
1850 + });
1851 + }
1852 + const keptOrdinal = scenario.history === "forked_to_baseline" ? 0 : first;
1853 + const keptCheckpoint = beforeRollback.checkpoints.find(
1854 + (checkpoint) =>
1855 + (checkpoint.appRunOrdinal ?? 0) === keptOrdinal && checkpoint.status === "ready",
1856 + );
1857 + if (keptCheckpoint === undefined) {
1858 + return yield* Effect.die("Expected a checkpoint after the first turn.");
1859 + }
1860 + yield* orchestrator.dispatch({
1861 + type: "checkpoint.rollback",
1862 + commandId: CommandId.make(`${name}:rollback`),
1863 + threadId,
1864 + scopeId: keptCheckpoint.scopeId,
1865 + checkpointId: keptCheckpoint.id,
1866 + restoreFiles: false,
1867 + });
1868 + yield* orchestrator.streamStoredEvents.pipe(
1869 + Stream.filter(
1870 + ({ event }) =>
1871 + (event.type === "run.updated" &&
1872 + event.payload.ordinal === first + 1 &&
1873 + event.payload.status === "rolled_back") ||
1874 + (event.type === "thread.metadata-updated" &&
1875 + event.payload.rollbackFailure != null),
1876 + ),
1877 + Stream.runHead,
1878 + );
1879 + yield* worker.drain();
1880 + assert.deepEqual(
1881 + (yield* orchestrator.getThreadProjection(threadId)).runs.map((run) => run.status),
1882 + scenario.history === "forked_to_baseline"
1883 + ? ["rolled_back", "rolled_back"]
1884 + : [...(first === 2 ? ["completed"] : []), "completed", "rolled_back"],
1885 + );
1886 + if (scenario.failResumeAfterRollback) {
1887 + const providerSessionId = (yield* orchestrator.getThreadProjection(threadId))
1888 + .providerThreads[0]?.providerSessionId;
1889 + if (providerSessionId == null) {
1890 + return yield* Effect.die("Expected a provider session after the rollback.");
1891 + }
1892 + yield* orchestrator.dispatch({
1893 + type: "provider-session.detach",
1894 + commandId: CommandId.make(`${name}:detach`),
1895 + threadId,
1896 + providerSessionId,
1897 + });
1898 + yield* worker.drain();
1899 + yield* Ref.set(failResumeOnce, true);
1900 + }
1901 + const historyBeforeRun3 = (yield* Ref.get(injectedHistory)).length;
1902 + yield* runToCompletion(first + 2, "What did I say first?");
1903 +
1904 + const run3 = (yield* Ref.get(capturedTurns)).at(-1);
1905 + const delivered =
1906 + (run3?.text ?? "") +
1907 + (yield* encodeJson((yield* Ref.get(injectedHistory)).slice(historyBeforeRun3)));
1908 + for (const kept of scenario.delivers) {
1909 + assert.include(delivered, kept, "the agent's session lacks this kept turn");
1910 + }
1911 + for (const withheld of scenario.withholds) {
1912 + assert.notInclude(delivered, withheld, "the session holds it or it was rewound");
1913 + }
1914 + if (scenario.name === "an ACP rollback that starts a fresh agent session") {
1915 + const recoveries = (projection: OrchestrationV2ThreadProjection) =>
1916 + projection.contextHandoffs.filter(
1917 + (handoff) => handoff.strategy === "full_thread_summary",
1918 + ).length;
1919 + const recoveriesBeforeRun4 = recoveries(
1920 + yield* orchestrator.getThreadProjection(threadId),
1921 + );
1922 + const sessionsBeforeRun4 = yield* Ref.get(nativeThreadGeneration);
1923 + yield* runToCompletion(4, "And what did I say second?");
1924 + assert.strictEqual(
1925 + recoveries(yield* orchestrator.getThreadProjection(threadId)),
1926 + recoveriesBeforeRun4,
1927 + "the recovered session holds the kept turns, so the next turn replays nothing",
1928 + );
1929 + assert.strictEqual(yield* Ref.get(nativeThreadGeneration), sessionsBeforeRun4);
1930 + }
1931 + }).pipe(
1932 + Effect.provide(
1933 + ProviderReplayHarness.layerWithRegistry(
1934 + {
1935 + name,
1936 + runtimePolicyOverride: {
1937 + cwd,
1938 + approvalPolicy: "never",
1939 + sandboxPolicy: { type: "readOnly" },
1940 + },
1941 + },
1942 + layerRegistry,
1943 + ),
1944 + ),
1945 + );
1946 + }),
1947 + ),
1948 + );
1949 +
1950 it.live.each([
1951 ["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()],
1952 ["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })],
docs/user/providers-acp.md
+2 -2
@@ -128,8 +128,8 @@ remain agent-specific.
128 ## Checkpoints
129
130 Checkpoint rollback restores your files as usual. ACP agents cannot rewind their own conversation,
131 -so the next turn after a rollback starts a fresh agent session that no longer remembers the
132 -conversation from before the checkpoint.
131 +so the next turn after a rollback starts a fresh agent session and T3 Code sends it the kept
132 +conversation, without the turns you rolled back.
133
134 Registry instances are not used for T3's app-owned text generation, such as thread titles, commit
135 messages, branch names, or pull request descriptions. Configure a text-generation-capable provider
packages/provider-acp/src/server/adapter.ts
+2 -2
@@ -802,8 +802,8 @@ export const AcpProviderCapabilitiesV2 = {
802 checkpointing: {
803 appCanCheckpointFilesystem: true,
804 supportsNestedCheckpointScopes: true,
805 - // ACP lacks truncation; rollback restores T3 checkpoints and starts a fresh agent session.
806 - providerCanRollbackConversation: true,
805 + // ACP lacks truncation; rollback starts a fresh agent session and turn start replays the kept history.
806 + providerCanRollbackConversation: false,
807 providerRollbackReturnsSnapshot: true,
808 providerCanReadConversationSnapshot: false,
809 },