@devries-cameron20 / t3code Mirror · read-only / commits / 35086ee087
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 22, 22:00 UTC

fix(web): edit from here works after a previous rewind (#18982)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Lakshmi Tanmay committed Oct 20, 2026 at 10:59 UTC 35086ee087d01af5c1c248bb80b1c9fb88544dd9
10 files changed +663 -59
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+90 -2
@@ -2055,6 +2055,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2055 for (let ordinal = 1; ordinal <= 1_000; ordinal += 1) {
2056 const id = `turn-item:bounded-sql-history:${ordinal}`;
2057 const runId = `run:bounded-sql-history:${ordinal}`;
2058 + const message = ordinal === 1 || ordinal === 1_000;
2059 yield* sql`
2060 INSERT INTO orchestration_v2_projection_runs (
2061 run_id, thread_id, ordinal, provider, provider_thread_id, status,
@@ -2086,7 +2087,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2087 parent_item_id, ordinal, type, status, updated_at, payload_json
2088 ) VALUES (
2089 ${id}, ${threadId}, ${runId}, NULL, NULL, NULL, NULL, ${ordinal},
2089 - 'command_execution', 'completed', ${nowIso},
2090 + ${message ? "user_message" : "command_execution"}, 'completed', ${nowIso},
2091 ${encodeUnknownJsonString({
2092 id,
2093 threadId,
@@ -2105,12 +2106,87 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2106 startedAt: nowIso,
2107 completedAt: nowIso,
2108 updatedAt: nowIso,
2108 - type: "command_execution",
2109 + ...(message
2110 + ? {
2111 + type: "user_message",
2112 + createdBy: "user",
2113 + creationSource: "web",
2114 + messageId: `message:bounded-sql-history:${ordinal}`,
2115 + inputIntent: "turn_start",
2116 + text: `Turn ${ordinal}`,
2117 + attachments: [],
2118 + }
2119 + : { type: "command_execution" }),
2120 })}
2121 )
2122 `;
2123 }
2124
2125 + for (const ordinal of [1, 1_000]) {
2126 + yield* projectionStore.apply({
2127 + id: EventId.make(`event:bounded-sql-history:message:${ordinal}`),
2128 + type: "message.updated",
2129 + threadId,
2130 + occurredAt: now,
2131 + payload: {
2132 + createdBy: "user",
2133 + creationSource: "web",
2134 + id: MessageId.make(`message:bounded-sql-history:${ordinal}`),
2135 + threadId,
2136 + runId: RunId.make(`run:bounded-sql-history:${ordinal}`),
2137 + nodeId: NodeId.make(`node:bounded-sql-history:${ordinal}`),
2138 + role: "user",
2139 + text: `Turn ${ordinal}`,
2140 + attachments: [],
2141 + streaming: false,
2142 + createdAt: now,
2143 + updatedAt: now,
2144 + },
2145 + });
2146 + }
2147 + const scopeId = CheckpointScopeId.make("scope:bounded-sql-history:root");
2148 + const baselineId = CheckpointId.make("checkpoint:bounded-sql-history:baseline");
2149 + yield* projectionStore.apply({
2150 + id: EventId.make("event:bounded-sql-history:scope"),
2151 + type: "checkpoint-scope.created",
2152 + threadId,
2153 + occurredAt: now,
2154 + payload: {
2155 + id: scopeId,
2156 + threadId,
2157 + runId: RunId.make("run:bounded-sql-history:1000"),
2158 + nodeId: NodeId.make("node:bounded-sql-history:1000"),
2159 + parentScopeId: null,
2160 + providerThreadId: null,
2161 + kind: "root_run",
2162 + ordinalWithinParent: 0,
2163 + advancesAppRunCount: true,
2164 + cwd: "/repo/worktree",
2165 + createdAt: now,
2166 + },
2167 + });
2168 + // A reused root scope can retain its original baseline on a node outside the window.
2169 + yield* projectionStore.apply({
2170 + id: EventId.make("event:bounded-sql-history:baseline"),
2171 + type: "checkpoint.captured",
2172 + threadId,
2173 + occurredAt: now,
2174 + payload: {
2175 + id: baselineId,
2176 + threadId,
2177 + scopeId,
2178 + runId: null,
2179 + nodeId: NodeId.make("node:bounded-sql-history:1"),
2180 + parentCheckpointId: null,
2181 + ordinalWithinScope: 0,
2182 + appRunOrdinal: null,
2183 + ref: CheckpointRef.make("refs/t3/bounded-sql-history/0"),
2184 + status: "ready",
2185 + files: [],
2186 + capturedAt: now,
2187 + },
2188 + });
2189 +
2190 const snapshots = yield* Effect.all(
2191 Array.from({ length: 4 }, () =>
2192 projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 }),
@@ -2123,6 +2199,18 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
2199 assert.lengthOf(snapshot.projection.visibleTurnItems, 76);
2200 assert.strictEqual(snapshot.projection.turnItems[0]?.ordinal, 925);
2201 assert.strictEqual(snapshot.projection.turnItems.at(-1)?.ordinal, 1_000);
2202 + assert.deepEqual(
2203 + snapshot.projection.messages.map((message) => message.id),
2204 + [MessageId.make("message:bounded-sql-history:1000")],
2205 + );
2206 + assert.deepEqual(
2207 + snapshot.projection.checkpointScopes.map((scope) => scope.id),
2208 + [scopeId],
2209 + );
2210 + assert.deepEqual(
2211 + snapshot.projection.checkpoints.map((checkpoint) => checkpoint.id),
2212 + [baselineId],
2213 + );
2214 }
2215 const retainedRequestPlan = yield* sql<{ readonly detail: string }>`
2216 EXPLAIN QUERY PLAN
apps/server/src/orchestration-v2/ProjectionStore.ts
+1
@@ -3357,6 +3357,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
3357 SELECT payload_json FROM orchestration_v2_projection_checkpoints
3358 WHERE thread_id = ${threadId}
3359 AND (status IN ('pending','capturing')
3360 + OR (run_id IS NULL AND ordinal_within_scope = 0 AND status = 'ready')
3361 OR checkpoint_id IN (SELECT value FROM json_each(${cohortCheckpointIds}))
3362 OR run_id IN (SELECT value FROM json_each(${cohortRunIds}))
3363 OR node_id IN (SELECT value FROM json_each(${cohortNodeIds})))
apps/web/src/components/ChatView.logic.test.ts
+222 -2
@@ -30,6 +30,8 @@ import {
30 ProjectId,
31 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
32 ProviderInstanceId,
33 + ProviderSessionId,
34 + ProviderThreadId,
35 ThreadId,
36 RunId,
37 type ScopedThreadRef,
@@ -2243,8 +2245,46 @@ describe("waitForRevertedMessage", () => {
2245
2246 function projectionAtom() {
2247 const base = makeThreadProjectionFixture();
2248 + const providerThreadId = ProviderThreadId.make("provider-thread");
2249 const projection = {
2250 ...base,
2251 + thread: { ...base.thread, activeProviderThreadId: providerThreadId },
2252 + providerThreads: [
2253 + {
2254 + id: providerThreadId,
2255 + driver: "codex",
2256 + providerInstanceId: base.thread.providerInstanceId,
2257 + providerSessionId: ProviderSessionId.make("provider-session"),
2258 + appThreadId: base.thread.id,
2259 + ownerNodeId: null,
2260 + nativeThreadRef: null,
2261 + nativeConversationHeadRef: null,
2262 + status: "idle",
2263 + firstRunOrdinal: 1,
2264 + lastRunOrdinal: 4,
2265 + handoffIds: [],
2266 + forkedFrom: null,
2267 + createdAt: base.updatedAt,
2268 + updatedAt: base.updatedAt,
2269 + },
2270 + ],
2271 + runs: [1, 2, 3, 4].map((ordinal) => ({
2272 + id: RunId.make(`run-${ordinal}`),
2273 + threadId: base.thread.id,
2274 + ordinal,
2275 + providerInstanceId: base.thread.providerInstanceId,
2276 + modelSelection: base.thread.modelSelection,
2277 + providerThreadId,
2278 + userMessageId: MessageId.make(`message-${ordinal}`),
2279 + rootNodeId: null,
2280 + activeAttemptId: null,
2281 + status: "completed",
2282 + requestedAt: base.updatedAt,
2283 + startedAt: base.updatedAt,
2284 + completedAt: base.updatedAt,
2285 + checkpointId: null,
2286 + contextHandoffId: null,
2287 + })),
2288 messages: [
2289 {
2290 id: messageId,
@@ -2269,7 +2309,7 @@ describe("waitForRevertedMessage", () => {
2309
2310 it("rejects with the projected reason when the rollback fails for good", async () => {
2311 const { state, projection } = projectionAtom();
2272 - const waiting = waitForRevertedMessage(threadRef, messageId, 1, requestId, async () => {});
2312 + const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {});
2313 await Promise.resolve();
2314 appAtomRegistry.set(state, {
2315 data: Option.some({
@@ -2284,10 +2324,190 @@ describe("waitForRevertedMessage", () => {
2324 await expect(waiting).rejects.toThrow("The provider could not roll back.");
2325 });
2326
2327 + it.each([
2328 + ["same", "streamed"],
2329 + ["replacement", "streamed"],
2330 + ["replacement", "refetched"],
2331 + ] as const)(
2332 + "waits for the retained rollback suffix when the edited message and run are paged out (%s provider, %s)",
2333 + async (providerIdentity, projectionSource) => {
2334 + vi.useFakeTimers();
2335 + const { state, projection } = projectionAtom();
2336 + const latestRunId = RunId.make("latest-run-9");
2337 + const latestRun = {
2338 + ...projection.runs[3]!,
2339 + id: latestRunId,
2340 + ordinal: 9,
2341 + userMessageId: MessageId.make("latest-message-9"),
2342 + status: "cancelled" as const,
2343 + };
2344 + const bounded = {
2345 + ...projection,
2346 + messages: [],
2347 + providerThreads: projection.providerThreads.map((thread) => ({
2348 + ...thread,
2349 + lastRunOrdinal: 9,
2350 + })),
2351 + runs: [
2352 + {
2353 + ...latestRun,
2354 + id: RunId.make("old-rewound-run-3"),
2355 + userMessageId: MessageId.make("old-rewound-message-3"),
2356 + ordinal: 3,
2357 + status: "rolled_back" as const,
2358 + },
2359 + latestRun,
2360 + ],
2361 + };
2362 + const oldProviderThread = bounded.providerThreads[0]!;
2363 + const completedProviderThread = {
2364 + ...oldProviderThread,
2365 + ...(providerIdentity === "replacement"
2366 + ? { id: ProviderThreadId.make("replacement-provider-thread"), firstRunOrdinal: null }
2367 + : {}),
2368 + lastRunOrdinal: null,
2369 + };
2370 + appAtomRegistry.set(state, { data: Option.some(bounded) });
2371 + let outcome = "pending";
2372 + const waiting = waitForRevertedMessage(threadRef, 0, requestId, async () => {}).then(
2373 + () => {
2374 + outcome = "reverted";
2375 + },
2376 + (error: Error) => {
2377 + outcome = error.message;
2378 + },
2379 + );
2380 +
2381 + try {
2382 + await vi.advanceTimersByTimeAsync(0);
2383 + expect(outcome).toBe("pending");
2384 +
2385 + appAtomRegistry.set(state, {
2386 + data: Option.some({
2387 + ...bounded,
2388 + thread: {
2389 + ...bounded.thread,
2390 + activeProviderThreadId:
2391 + projectionSource === "refetched"
2392 + ? completedProviderThread.id
2393 + : oldProviderThread.id,
2394 + },
2395 + providerThreads:
2396 + providerIdentity === "replacement"
2397 + ? [oldProviderThread, completedProviderThread]
2398 + : [completedProviderThread],
2399 + runs: bounded.runs.map((run) =>
2400 + run.id === latestRunId ? { ...run, status: "rolled_back" as const } : run,
2401 + ),
2402 + }),
2403 + });
2404 + await vi.advanceTimersByTimeAsync(0);
2405 + expect(outcome).toBe("reverted");
2406 + await waiting;
2407 + } finally {
2408 + vi.clearAllTimers();
2409 + vi.useRealTimers();
2410 + }
2411 + },
2412 + );
2413 +
2414 + it("waits for the requested target when another client finishes a shallower rewind", async () => {
2415 + vi.useFakeTimers();
2416 + const { state, projection } = projectionAtom();
2417 + let outcome = "pending";
2418 + const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}).then(
2419 + () => {
2420 + outcome = "reverted";
2421 + },
2422 + (error: Error) => {
2423 + outcome = error.message;
2424 + },
2425 + );
2426 +
2427 + try {
2428 + await vi.advanceTimersByTimeAsync(0);
2429 + expect(outcome).toBe("pending");
2430 +
2431 + // Our command is accepted while the earlier target-3 effect is still running.
2432 + const shallowerRewind = {
2433 + ...projection,
2434 + thread: { ...projection.thread, rollbackRequestId: requestId, rollbackFailure: null },
2435 + providerThreads: projection.providerThreads.map((thread) => ({
2436 + ...thread,
2437 + lastRunOrdinal: 3,
2438 + })),
2439 + runs: projection.runs.map((run) =>
2440 + run.ordinal > 3 ? { ...run, status: "rolled_back" as const } : run,
2441 + ),
2442 + };
2443 + appAtomRegistry.set(state, { data: Option.some(shallowerRewind) });
2444 + await vi.advanceTimersByTimeAsync(0);
2445 + expect(outcome).toBe("pending");
2446 +
2447 + appAtomRegistry.set(state, {
2448 + data: Option.some({
2449 + ...shallowerRewind,
2450 + providerThreads: shallowerRewind.providerThreads.map((thread) => ({
2451 + ...thread,
2452 + lastRunOrdinal: 1,
2453 + })),
2454 + runs: shallowerRewind.runs.map((run) =>
2455 + run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,
2456 + ),
2457 + }),
2458 + });
2459 + await vi.advanceTimersByTimeAsync(0);
2460 + expect(outcome).toBe("reverted");
2461 + await waiting;
2462 + } finally {
2463 + vi.clearAllTimers();
2464 + vi.useRealTimers();
2465 + }
2466 + });
2467 +
2468 + it("rejects a stale edit already rewound by another client during attachment preparation", async () => {
2469 + vi.useFakeTimers();
2470 + const { state, projection } = projectionAtom();
2471 + appAtomRegistry.set(state, {
2472 + data: Option.some({
2473 + ...projection,
2474 + thread: { ...projection.thread, rollbackRequestId: CommandId.make("other-client-rewind") },
2475 + messages: [],
2476 + providerThreads: projection.providerThreads.map((thread) => ({
2477 + ...thread,
2478 + lastRunOrdinal: 1,
2479 + })),
2480 + runs: projection.runs.map((run) =>
2481 + run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,
2482 + ),
2483 + }),
2484 + });
2485 + const revert = vi.fn(async () => {});
2486 + let outcome = "pending";
2487 + const waiting = waitForRevertedMessage(threadRef, 1, requestId, revert).then(
2488 + () => {
2489 + outcome = "reverted";
2490 + },
2491 + () => {
2492 + outcome = "rejected";
2493 + },
2494 + );
2495 +
2496 + try {
2497 + await vi.advanceTimersByTimeAsync(0);
2498 + expect(outcome).toBe("rejected");
2499 + expect(revert).not.toHaveBeenCalled();
2500 + await waiting;
2501 + } finally {
2502 + vi.clearAllTimers();
2503 + vi.useRealTimers();
2504 + }
2505 + });
2506 +
2507 it("ignores a failure recorded for an earlier rollback", async () => {
2508 vi.useFakeTimers();
2509 const { state, projection } = projectionAtom();
2290 - const waiting = waitForRevertedMessage(threadRef, messageId, 1, requestId, async () => {}, 50);
2510 + const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}, 50);
2511 const settled = expect(waiting).rejects.toThrow("Timed out waiting for the thread to rewind.");
2512 appAtomRegistry.set(state, {
2513 data: Option.some({
apps/web/src/components/ChatView.logic.ts
+31 -8
@@ -1068,7 +1068,6 @@ export async function waitForStartedServerThread(
1068
1069 export async function waitForRevertedMessage(
1070 threadRef: ScopedThreadRef,
1071 - messageId: MessageId,
1071 turnCount: number,
1072 requestId: CommandId,
1073 revert: () => Promise<void>,
@@ -1077,10 +1076,26 @@ export async function waitForRevertedMessage(
1076 const threadAtom = environmentThreadDetails.stateAtom(threadRef);
1077 const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);
1078 const initial = readProjection();
1080 - if (!initial?.messages.some((message) => message.id === messageId)) {
1081 - throw new Error("The message to rewind is no longer available.");
1079 + const providerThreadId = initial?.thread.activeProviderThreadId;
1080 + const initialProviderThread = initial?.providerThreads.find(
1081 + (providerThread) => providerThread.id === providerThreadId,
1082 + );
1083 + const initialProviderThreadIds = new Set(initial?.providerThreads.map((thread) => thread.id));
1084 + // Paging can omit the source run. Rollback commits the entire settled suffix atomically.
1085 + const witness = initial?.runs.reduce<(typeof initial.runs)[number] | undefined>((latest, run) => {
1086 + if (
1087 + run.ordinal <= turnCount ||
1088 + (run.status !== "completed" &&
1089 + run.status !== "interrupted" &&
1090 + run.status !== "failed" &&
1091 + run.status !== "cancelled")
1092 + )
1093 + return latest;
1094 + return latest === undefined || run.ordinal > latest.ordinal ? run : latest;
1095 + }, undefined);
1096 + if (witness === undefined) {
1097 + throw new Error("The thread has changed. Select a message to rewind again.");
1098 }
1083 - const messageRunId = initial.messages.find((message) => message.id === messageId)?.runId;
1099 return new Promise<void>((resolve, reject) => {
1100 let settled = false;
1101 let accepted = false;
@@ -1104,10 +1119,18 @@ export async function waitForRevertedMessage(
1119 }
1120 if (
1121 accepted &&
1107 - thread.runs.some(
1108 - (run) =>
1109 - run.id === messageRunId && run.ordinal > turnCount && run.status === "rolled_back",
1110 - )
1122 + thread.providerThreads.some(
1123 + (providerThread) =>
1124 + (providerThread.id === providerThreadId ||
1125 + // Claude resets to a fresh root session when rewinding to thread start.
1126 + (turnCount === 0 &&
1127 + providerThread.ownerNodeId === null &&
1128 + providerThread.appThreadId === initial?.thread.id &&
1129 + providerThread.providerInstanceId === initialProviderThread?.providerInstanceId &&
1130 + !initialProviderThreadIds.has(providerThread.id))) &&
1131 + providerThread.lastRunOrdinal === (turnCount === 0 ? null : turnCount),
1132 + ) &&
1133 + thread.runs.some((run) => run.id === witness.id && run.status === "rolled_back")
1134 )
1135 finish();
1136 };
apps/web/src/components/ChatView.tsx
+74 -34
@@ -8,7 +8,6 @@ import {
8 resolveDraftHeroState,
9 shouldDockDraftHeroForSubmission,
10 } from "./ChatView.logic";
11 -import * as DateTime from "effect/DateTime";
11 import { restorePlanFollowUpComposer } from "./ChatView.logic";
12 import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";
13 import {
@@ -65,6 +64,7 @@ import {
64 type EnvironmentId,
65 type MessageId,
66 type ModelSelection,
67 + type OrchestrationV2ProviderTurn,
68 type ProjectScript,
69 type PreviewAnnotationPayload,
70 ProviderInstanceId,
@@ -72,6 +72,7 @@ import {
72 type ScopedThreadRef,
73 type ThreadId,
74 type RunId,
75 + type RunAttemptId,
76 type RuntimeRequestId,
77 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
78 ProviderInteractionMode,
@@ -189,6 +190,7 @@ import {
190 deriveActiveWorkStartedAt,
191 deriveCanInterruptRunningThread,
192 findLatestProposedPlan,
193 + findRevertCheckpoint,
194 hasActionableProposedPlan,
195 isLatestRunSettled,
196 } from "../session-logic";
@@ -760,6 +762,7 @@ async function rewindToMessage(input: {
762 readonly threadId: ThreadId;
763 readonly turnCount: number;
764 readonly restoreFiles: boolean;
765 + readonly checkpoint: ReturnType<typeof findRevertCheckpoint>;
766 readonly draftTarget: ScopedThreadRef | DraftId;
767 readonly composerHasPendingAttachments: boolean;
768 readonly createAssetUrl: Parameters<
@@ -767,7 +770,14 @@ async function rewindToMessage(input: {
770 >[0]["createAssetUrl"];
771 readonly revertThreadCheckpoint: (value: {
772 environmentId: EnvironmentId;
770 - input: { commandId: CommandId; threadId: ThreadId; turnCount: number; restoreFiles: boolean };
773 + input: {
774 + commandId: CommandId;
775 + threadId: ThreadId;
776 + turnCount: number;
777 + restoreFiles: boolean;
778 + checkpointId?: string;
779 + scopeId?: string;
780 + };
781 }) => Promise<AtomCommandResult<unknown, unknown>>;
782 }): Promise<
783 | { readonly error: string; readonly prompt?: never }
@@ -795,24 +805,21 @@ async function rewindToMessage(input: {
805 throw new Error("Make room for this message's attachments in the composer before rewinding.");
806 }
807 const commandId = CommandId.make(randomUUID());
798 - await waitForRevertedMessage(
799 - input.routeThreadRef,
800 - message.id,
801 - input.turnCount,
802 - commandId,
803 - async () => {
804 - const result = await input.revertThreadCheckpoint({
805 - environmentId,
806 - input: {
807 - commandId,
808 - threadId: input.threadId,
809 - turnCount: input.turnCount,
810 - restoreFiles: input.restoreFiles,
811 - },
812 - });
813 - if (result._tag === "Failure") throw squashAtomCommandFailure(result);
814 - },
815 - );
808 + await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => {
809 + const result = await input.revertThreadCheckpoint({
810 + environmentId,
811 + input: {
812 + commandId,
813 + threadId: input.threadId,
814 + turnCount: input.turnCount,
815 + restoreFiles: input.restoreFiles,
816 + ...(input.checkpoint === undefined
817 + ? {}
818 + : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }),
819 + },
820 + });
821 + if (result._tag === "Failure") throw squashAtomCommandFailure(result);
822 + });
823 const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
824 const restoredPrompt = recallableComposerPrompt(message.text);
825 const nextPrompt =
@@ -2929,6 +2936,48 @@ export default function ChatView(props: ChatViewProps) {
2936 panelAnimationDurationMs,
2937 );
2938 const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadDetailRef);
2939 + const availableRevertTurnCounts = (() => {
2940 + const available = new Set<number>();
2941 + const providerThread = serverProjection?.providerThreads.find(
2942 + (candidate) => candidate.id === serverProjection.thread.activeProviderThreadId,
2943 + );
2944 + if (
2945 + !providerThread?.providerSessionId ||
2946 + providerThread.providerInstanceId !== serverProjection?.thread.modelSelection.instanceId
2947 + )
2948 + return available;
2949 + available.add(0);
2950 + const attemptsById = new Map(serverProjection.attempts.map((attempt) => [attempt.id, attempt]));
2951 + const providerTurnsById = new Map<
2952 + OrchestrationV2ProviderTurn["id"],
2953 + OrchestrationV2ProviderTurn
2954 + >();
2955 + const latestTurnByAttempt = new Map<RunAttemptId, OrchestrationV2ProviderTurn>();
2956 + for (const turn of serverProjection.providerTurns) {
2957 + providerTurnsById.set(turn.id, turn);
2958 + if (turn.runAttemptId === null) continue;
2959 + const latest = latestTurnByAttempt.get(turn.runAttemptId);
2960 + if (latest === undefined || turn.ordinal > latest.ordinal) {
2961 + latestTurnByAttempt.set(turn.runAttemptId, turn);
2962 + }
2963 + }
2964 + for (const run of serverProjection.runs) {
2965 + if (run.activeAttemptId === null) continue;
2966 + const attempt = attemptsById.get(run.activeAttemptId);
2967 + const providerTurn =
2968 + latestTurnByAttempt.get(run.activeAttemptId) ??
2969 + (attempt?.providerTurnId == null
2970 + ? undefined
2971 + : providerTurnsById.get(attempt.providerTurnId));
2972 + // A ready file checkpoint alone cannot restore the provider conversation.
2973 + if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal);
2974 + }
2975 + return available;
2976 + })();
2977 + // A paged history window cannot identify the first loaded run as the thread start.
2978 + const threadStartCheckpointReady =
2979 + !serverThreadHistory.hasMoreHistory &&
2980 + findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined;
2981
2982 /**
2983 * File tools are explicit; completed commands are included because a shell
@@ -5875,20 +5924,7 @@ export default function ChatView(props: ChatViewProps) {
5924 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
5925 )
5926 return;
5878 - const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId);
5879 - const message = sourceMessage
5880 - ? {
5881 - id: sourceMessage.id,
5882 - role: sourceMessage.role,
5883 - text: sourceMessage.text,
5884 - attachments: sourceMessage.attachments,
5885 - context: sourceMessage.context,
5886 - runId: sourceMessage.runId,
5887 - streaming: false,
5888 - createdAt: DateTime.formatIso(sourceMessage.createdAt),
5889 - updatedAt: DateTime.formatIso(sourceMessage.updatedAt),
5890 - }
5891 - : undefined;
5927 + const message = timelineMessages.find((message) => message.id === messageId);
5928 if (!message || message.role !== "user") return;
5929
5930 if (!supportsConversationRollback) {
@@ -5925,6 +5961,8 @@ export default function ChatView(props: ChatViewProps) {
5961 threadId: activeThread.id,
5962 turnCount,
5963 restoreFiles,
5964 + // Keep the live checkpoint identity when command context refetches a bounded window.
5965 + checkpoint: findRevertCheckpoint(serverProjection?.checkpoints ?? [], turnCount),
5966 draftTarget: composerDraftTarget,
5967 composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,
5968 createAssetUrl: createAttachmentAssetUrl,
@@ -8204,6 +8242,8 @@ export default function ChatView(props: ChatViewProps) {
8242 supportsConversationRollback={
8243 !paintOnlyDisplayedTimeline && supportsConversationRollback
8244 }
8245 + threadStartCheckpointReady={threadStartCheckpointReady}
8246 + availableRevertTurnCounts={availableRevertTurnCounts}
8247 onRevertToTurnCount={
8248 paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurnStable
8249 }
apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+8 -3
@@ -1281,7 +1281,7 @@ describe("deriveMessagesTimelineRows", () => {
1281 expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
1282 });
1283
1284 - it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
1284 + it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => {
1285 const assistantTurnDiffSummary = {
1286 runId: "turn-1" as never,
1287 completedAt: "2026-01-01T00:00:30Z",
@@ -1328,6 +1328,7 @@ describe("deriveMessagesTimelineRows", () => {
1328 activeTurnStartedAt: null,
1329 turnDiffSummaries: [assistantTurnDiffSummary],
1330 supportsConversationRollback: true,
1331 + threadStartCheckpointReady: true,
1332 });
1333
1334 const userRow = rows.find(
@@ -1339,7 +1340,7 @@ describe("deriveMessagesTimelineRows", () => {
1340 row.kind === "message" && row.message.role === "assistant",
1341 );
1342
1342 - expect(userRow?.revertTurnCount).toBe(1);
1343 + expect(userRow?.revertTurnCount).toBe(0);
1344 expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
1345 });
1346
@@ -4423,7 +4424,10 @@ describe("streaming v2 row projection", () => {
4424 ["Visible", "★ Insight\nKeep these line breaks"],
4425 ])("keeps row parity and history identity from %j to %j", (before, after) => {
4426 const initial = fixture(before);
4426 - const previous = deriveMessagesTimelineRowsWithState(initial.input);
4427 + const previous = deriveMessagesTimelineRowsWithState({
4428 + ...initial.input,
4429 + availableRevertTurnCounts: new Set([0]),
4430 + });
4431 Object.freeze(previous.rows);
4432 for (const row of previous.rows) Object.freeze(row);
4433 const timelineInput = {
@@ -4439,6 +4443,7 @@ describe("streaming v2 row projection", () => {
4443 timelineEntries: timeline.entries,
4444 latestRun: { ...initial.input.latestRun },
4445 turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ ...summary })),
4446 + availableRevertTurnCounts: new Set([0]),
4447 };
4448 const next = deriveMessagesTimelineRowsWithState(input, previous);
4449 expect(next.rows).toEqual(
apps/web/src/components/chat/MessagesTimeline.logic.ts
+9 -1
@@ -1333,6 +1333,8 @@ export function deriveMessagesTimelineRows(input: {
1333 activeTurnStartedAt?: string | null;
1334 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
1335 supportsConversationRollback: boolean;
1336 + threadStartCheckpointReady?: boolean;
1337 + availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1338 liveAgentTaskIds?: ReadonlySet<string> | undefined;
1339 worktreeSetup?: WorktreeSetupSnapshot | null;
1340 }): MessagesTimelineRow[] {
@@ -1343,10 +1345,14 @@ export function deriveMessagesTimelineRows(input: {
1345 turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);
1346 }
1347 }
1348 + const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);
1349 const revertTurnCountByUserMessageId = input.supportsConversationRollback
1350 ? deriveRevertTurnCountByUserMessageId({
1351 timelineEntries: timelineEntries,
1352 checkpoints: input.turnDiffSummaries,
1353 + threadStartCheckpointReady: input.threadStartCheckpointReady === true,
1354 + unsettledRunId,
1355 + availableRevertTurnCounts: input.availableRevertTurnCounts,
1356 })
1357 : new Map<MessageId, number>();
1358 const nextRows: MessagesTimelineRow[] = [];
@@ -1354,7 +1360,6 @@ export function deriveMessagesTimelineRows(input: {
1360 timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
1361 );
1362 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries);
1357 - const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);
1363 const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null);
1364 const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries);
1365 const completeSupersededReplyIds = completeSupersededReplyEntryIds(timelineEntries);
@@ -2035,6 +2040,7 @@ function replaceStreamingMessageRows(
2040 expandedRunIds: previousExpandedRuns,
2041 expandedAttemptIds: previousExpandedAttempts,
2042 expandedWorkGroupIds: previousExpandedGroups,
2043 + availableRevertTurnCounts: previousAvailableRevertTurnCounts,
2044 ...previousContext
2045 } = previous.input;
2046 const {
@@ -2044,6 +2050,7 @@ function replaceStreamingMessageRows(
2050 expandedRunIds,
2051 expandedAttemptIds,
2052 expandedWorkGroupIds,
2053 + availableRevertTurnCounts,
2054 ...context
2055 } = input;
2056 // V2 shell and checkpoint selectors produce fresh summaries for each event.
@@ -2055,6 +2062,7 @@ function replaceStreamingMessageRows(
2062 !shallow(previousExpandedRuns, expandedRunIds) ||
2063 !shallow(previousExpandedAttempts, expandedAttemptIds) ||
2064 !shallow(previousExpandedGroups, expandedWorkGroupIds) ||
2065 + !shallow(previousAvailableRevertTurnCounts, availableRevertTurnCounts) ||
2066 !sameCheckpointSummaries(previousCheckpoints, turnDiffSummaries)
2067 ) {
2068 return null;
apps/web/src/components/chat/MessagesTimeline.tsx
+6
@@ -484,6 +484,8 @@ interface MessagesTimelineProps {
484 readonly scopeId: string;
485 }) => void;
486 supportsConversationRollback: boolean;
487 + threadStartCheckpointReady?: boolean;
488 + availableRevertTurnCounts?: ReadonlySet<number> | undefined;
489 onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
490 onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
491 onSendAppMessage?: (text: string) => Promise<void>;
@@ -583,6 +585,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
585 onForkFromRun,
586 onRollbackCheckpoint,
587 supportsConversationRollback,
588 + threadStartCheckpointReady = false,
589 + availableRevertTurnCounts,
590 onRevertToTurnCount,
591 onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,
592 onSendAppMessage,
@@ -857,6 +861,8 @@ const ConversationTimeline = memo(function ConversationTimeline({
861 activeTurnStartedAt,
862 turnDiffSummaries,
863 supportsConversationRollback,
864 + threadStartCheckpointReady,
865 + availableRevertTurnCounts,
866 worktreeSetup,
867 });
868 const rows = useStableRows(rawRows, listIdentityKey);
apps/web/src/session-logic.test.ts
+168
@@ -277,6 +277,7 @@ describe("V2 session presentation", () => {
277
278 const targets = deriveRevertTurnCountByUserMessageId({
279 timelineEntries,
280 + threadStartCheckpointReady: true,
281 checkpoints: [
282 {
283 runId,
@@ -294,6 +295,173 @@ describe("V2 session presentation", () => {
295 expect(targets.has(steerMessageId)).toBe(false);
296 });
297
298 + describe("revert targets after a rewind", () => {
299 + const runId = (ordinal: number) => RunId.make(`run-${ordinal}`);
300 + const turn = (ordinal: number): TimelineEntry[] =>
301 + (["user", "assistant"] as const).map((role) => {
302 + const id = MessageId.make(`${role}-${ordinal}`);
303 + const createdAt = `2026-06-20T00:00:0${ordinal}.000Z`;
304 + return {
305 + id,
306 + kind: "message",
307 + createdAt,
308 + message: {
309 + id,
310 + role,
311 + text: role,
312 + runId: runId(ordinal),
313 + ...(role === "user" ? { inputIntent: "turn_start" as const } : {}),
314 + streaming: false,
315 + createdAt,
316 + updatedAt: createdAt,
317 + },
318 + };
319 + });
320 + const checkpoint = (ordinal: number, status: "ready" | "stale" = "ready") => ({
321 + runId: runId(ordinal),
322 + checkpointTurnCount: ordinal,
323 + checkpointRef: `checkpoint-${ordinal}` as never,
324 + status,
325 + files: [],
326 + assistantMessageId: MessageId.make(`assistant-${ordinal}`),
327 + completedAt: "2026-06-20T00:00:09.000Z",
328 + });
329 + const targets = (
330 + ordinals: ReadonlyArray<number>,
331 + checkpoints: ReadonlyArray<ReturnType<typeof checkpoint>>,
332 + options: { threadStartCheckpointReady?: boolean; unsettledRunId?: RunId } = {},
333 + ) =>
334 + Object.fromEntries(
335 + deriveRevertTurnCountByUserMessageId({
336 + timelineEntries: ordinals.flatMap(turn),
337 + checkpoints,
338 + threadStartCheckpointReady: options.threadStartCheckpointReady ?? true,
339 + unsettledRunId: options.unsettledRunId ?? null,
340 + }),
341 + );
342 +
343 + it("keeps rewound and stopped runs editable at the previous visible checkpoint", () => {
344 + // Runs 1 and 3 were rewound; run 5 stopped without capturing a checkpoint.
345 + expect(targets([2, 4, 5], [checkpoint(2), checkpoint(3, "stale"), checkpoint(4)])).toEqual({
346 + "user-2": 0,
347 + "user-4": 2,
348 + "user-5": 4,
349 + });
350 + expect(targets([2], [checkpoint(1, "stale")])).toEqual({ "user-2": 0 });
351 + });
352 +
353 + it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => {
354 + const fixture = makeStreamingTimelineFixture();
355 + const first = fixture.visibleTurnItems[0]!;
356 + if (first.item.type !== "user_message") throw new Error("Expected a user message fixture.");
357 + const notification = {
358 + ...first,
359 + item: {
360 + ...first.item,
361 + id: TurnItemId.make("wake-item"),
362 + runId: runId(2),
363 + type: "notification" as const,
364 + source: { kind: "delegated_task" as const, taskIds: [NodeId.make("task-1")] },
365 + outcome: "unknown" as const,
366 + summary: "Delegated task finished",
367 + },
368 + };
369 + const inherited = {
370 + ...notification,
371 + visibility: "inherited" as const,
372 + sourceThreadId: ThreadId.make("parent-thread"),
373 + sourceItemId: TurnItemId.make("inherited-wake"),
374 + item: {
375 + ...notification.item,
376 + id: TurnItemId.make("inherited-wake"),
377 + threadId: ThreadId.make("parent-thread"),
378 + runId: runId(7),
379 + },
380 + };
381 + const work: TimelineEntry = {
382 + id: "background-work",
383 + kind: "work",
384 + createdAt: "2026-06-20T00:00:02.000Z",
385 + entry: {
386 + id: "background-work",
387 + createdAt: "2026-06-20T00:00:02.000Z",
388 + runId: runId(8),
389 + itemType: "command_execution",
390 + label: "Background work",
391 + tone: "tool",
392 + },
393 + };
394 +
395 + expect(
396 + Object.fromEntries(
397 + deriveRevertTurnCountByUserMessageId({
398 + timelineEntries: [
399 + ...turn(1),
400 + ...deriveTimelineEntriesFromVisibleTurnItems({
401 + visibleTurnItems: [notification, inherited],
402 + optimisticMessages: [],
403 + }),
404 + work,
405 + ...turn(3),
406 + ],
407 + checkpoints: [
408 + checkpoint(1),
409 + checkpoint(2),
410 + checkpoint(3),
411 + checkpoint(7),
412 + checkpoint(8),
413 + ],
414 + threadStartCheckpointReady: true,
415 + }),
416 + ),
417 + ).toEqual({ "user-1": 0, "user-3": 2 });
418 + });
419 +
420 + it("hides edit when the predecessor is unavailable or the run is unsettled", () => {
421 + expect(targets([1, 2], [checkpoint(2)])).toEqual({ "user-1": 0 });
422 + expect(targets([1, 2], [checkpoint(1, "stale"), checkpoint(2)])).toEqual({ "user-1": 0 });
423 + // Earlier history is paged out, so the first loaded run's predecessor is unknown.
424 + expect(
425 + targets([4, 5], [checkpoint(4), checkpoint(5)], { threadStartCheckpointReady: false }),
426 + ).toEqual({ "user-5": 4 });
427 + expect(targets([1, 2], [checkpoint(1), checkpoint(2)], { unsettledRunId: runId(2) })).toEqual(
428 + { "user-1": 0 },
429 + );
430 + });
431 +
432 + it("can edit a cancelled run but cannot target its checkpoint without a provider turn", () => {
433 + expect(
434 + Object.fromEntries(
435 + deriveRevertTurnCountByUserMessageId({
436 + timelineEntries: [1, 2, 3].flatMap(turn),
437 + checkpoints: [checkpoint(1), checkpoint(2), checkpoint(3)],
438 + threadStartCheckpointReady: true,
439 + availableRevertTurnCounts: new Set([0, 1]),
440 + }),
441 + ),
442 + ).toEqual({ "user-1": 0, "user-2": 1 });
443 + });
444 +
445 + it("leaves inherited history uneditable and restores the first local run to thread start", () => {
446 + const fixture = makeStreamingTimelineFixture();
447 + const inheritedEntries = deriveTimelineEntriesFromVisibleTurnItems({
448 + visibleTurnItems: fixture.visibleTurnItems
449 + .filter(({ item }) => item.runId === fixture.historyRunId)
450 + .map((item) => ({ ...item, visibility: "inherited" as const })),
451 + optimisticMessages: [],
452 + });
453 + expect(
454 + Object.fromEntries(
455 + deriveRevertTurnCountByUserMessageId({
456 + timelineEntries: [...inheritedEntries, ...turn(2)],
457 + checkpoints: [{ ...checkpoint(7), runId: fixture.historyRunId }, checkpoint(2)],
458 + threadStartCheckpointReady: true,
459 + }),
460 + ),
461 + ).toEqual({ "user-2": 0 });
462 + });
463 + });
464 +
465 it("uses visible turn item order and keeps provider errors in the work log", () => {
466 const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
467 const threadId = ThreadId.make("thread-visible");
apps/web/src/session-logic.ts
+54 -9
@@ -1,6 +1,7 @@
1 import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2 import {
3 type AssetResource,
4 + type OrchestrationV2Checkpoint,
5 type OrchestrationV2ExecutionNode,
6 type OrchestrationV2PlanArtifact,
7 type OrchestrationV2ProjectedTurnItem,
@@ -1011,30 +1012,74 @@ export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1012 };
1013 }
1014
1015 +// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1016 export function deriveRevertTurnCountByUserMessageId(input: {
1017 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1018 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1019 + readonly threadStartCheckpointReady: boolean;
1020 + readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1021 + readonly unsettledRunId?: RunId | null;
1022 }): Map<ChatMessage["id"], number> {
1018 - const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
1023 + const readyTurnCountByRunId = new Map<RunId, number>();
1024 for (const checkpoint of input.checkpoints) {
1025 if (checkpoint.status === "ready") {
1021 - readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
1026 + readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1027 }
1028 }
1029 + const targetByRunId = new Map<RunId, number | undefined>();
1030 const byUserMessageId = new Map<ChatMessage["id"], number>();
1031 + let previousRunId: RunId | null = null;
1032 for (const entry of input.timelineEntries) {
1026 - if (entry.kind !== "message" || entry.message.role !== "user") continue;
1027 - if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
1028 - continue;
1033 + // Inherited history belongs to the source thread, not our checkpoint scope.
1034 + if (entry.kind !== "message" && entry.kind !== "work") continue;
1035 + const projectedItem =
1036 + entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1037 + if (projectedItem?.visibility === "inherited") continue;
1038 + const runId =
1039 + entry.kind === "message"
1040 + ? entry.message.runId
1041 + : entry.entry.itemType === "notification"
1042 + ? entry.entry.runId
1043 + : null;
1044 + if (runId == null) continue;
1045 + if (!targetByRunId.has(runId)) {
1046 + targetByRunId.set(
1047 + runId,
1048 + previousRunId === null
1049 + ? input.threadStartCheckpointReady
1050 + ? 0
1051 + : undefined
1052 + : readyTurnCountByRunId.get(previousRunId),
1053 + );
1054 + previousRunId = runId;
1055 }
1030 - if (entry.message.runId === null) continue;
1031 - const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
1032 - if (checkpoint === undefined) continue;
1033 - byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
1056 + if (entry.kind !== "message") continue;
1057 + const { message } = entry;
1058 + if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1059 + if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1060 + const target = targetByRunId.get(runId);
1061 + if (
1062 + target !== undefined &&
1063 + (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1064 + )
1065 + byUserMessageId.set(message.id, target);
1066 }
1067 return byUserMessageId;
1068 }
1069
1070 +export function findRevertCheckpoint(
1071 + checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1072 + turnCount: number,
1073 +): OrchestrationV2Checkpoint | undefined {
1074 + return checkpoints.findLast(
1075 + (checkpoint) =>
1076 + checkpoint.status === "ready" &&
1077 + (turnCount === 0
1078 + ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1079 + : checkpoint.appRunOrdinal === turnCount),
1080 + );
1081 +}
1082 +
1083 export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
1084 if (runtime === null) return "disconnected";
1085 if (