TypeScript
fix(web): edit from here works after a previous rewind (#18982)
Lakshmi Tanmay35086ee087d0
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 32c83629c66..64435283024 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -2055,6 +2055,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {for (let ordinal = 1; ordinal <= 1_000; ordinal += 1) {const id = `turn-item:bounded-sql-history:${ordinal}`;const runId = `run:bounded-sql-history:${ordinal}`;+ const message = ordinal === 1 || ordinal === 1_000;yield* sql`INSERT INTO orchestration_v2_projection_runs (run_id, thread_id, ordinal, provider, provider_thread_id, status,@@ -2086,7 +2087,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {parent_item_id, ordinal, type, status, updated_at, payload_json) VALUES (${id}, ${threadId}, ${runId}, NULL, NULL, NULL, NULL, ${ordinal},- 'command_execution', 'completed', ${nowIso},+ ${message ? "user_message" : "command_execution"}, 'completed', ${nowIso},${encodeUnknownJsonString({id,threadId,@@ -2105,12 +2106,87 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {startedAt: nowIso,completedAt: nowIso,updatedAt: nowIso,- type: "command_execution",+ ...(message+ ? {+ type: "user_message",+ createdBy: "user",+ creationSource: "web",+ messageId: `message:bounded-sql-history:${ordinal}`,+ inputIntent: "turn_start",+ text: `Turn ${ordinal}`,+ attachments: [],+ }+ : { type: "command_execution" }),})})`;}+ for (const ordinal of [1, 1_000]) {+ yield* projectionStore.apply({+ id: EventId.make(`event:bounded-sql-history:message:${ordinal}`),+ type: "message.updated",+ threadId,+ occurredAt: now,+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: MessageId.make(`message:bounded-sql-history:${ordinal}`),+ threadId,+ runId: RunId.make(`run:bounded-sql-history:${ordinal}`),+ nodeId: NodeId.make(`node:bounded-sql-history:${ordinal}`),+ role: "user",+ text: `Turn ${ordinal}`,+ attachments: [],+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ });+ }+ const scopeId = CheckpointScopeId.make("scope:bounded-sql-history:root");+ const baselineId = CheckpointId.make("checkpoint:bounded-sql-history:baseline");+ yield* projectionStore.apply({+ id: EventId.make("event:bounded-sql-history:scope"),+ type: "checkpoint-scope.created",+ threadId,+ occurredAt: now,+ payload: {+ id: scopeId,+ threadId,+ runId: RunId.make("run:bounded-sql-history:1000"),+ nodeId: NodeId.make("node:bounded-sql-history:1000"),+ parentScopeId: null,+ providerThreadId: null,+ kind: "root_run",+ ordinalWithinParent: 0,+ advancesAppRunCount: true,+ cwd: "/repo/worktree",+ createdAt: now,+ },+ });+ // A reused root scope can retain its original baseline on a node outside the window.+ yield* projectionStore.apply({+ id: EventId.make("event:bounded-sql-history:baseline"),+ type: "checkpoint.captured",+ threadId,+ occurredAt: now,+ payload: {+ id: baselineId,+ threadId,+ scopeId,+ runId: null,+ nodeId: NodeId.make("node:bounded-sql-history:1"),+ parentCheckpointId: null,+ ordinalWithinScope: 0,+ appRunOrdinal: null,+ ref: CheckpointRef.make("refs/t3/bounded-sql-history/0"),+ status: "ready",+ files: [],+ capturedAt: now,+ },+ });+const snapshots = yield* Effect.all(Array.from({ length: 4 }, () =>projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 }),@@ -2123,6 +2199,18 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {assert.lengthOf(snapshot.projection.visibleTurnItems, 76);assert.strictEqual(snapshot.projection.turnItems[0]?.ordinal, 925);assert.strictEqual(snapshot.projection.turnItems.at(-1)?.ordinal, 1_000);+ assert.deepEqual(+ snapshot.projection.messages.map((message) => message.id),+ [MessageId.make("message:bounded-sql-history:1000")],+ );+ assert.deepEqual(+ snapshot.projection.checkpointScopes.map((scope) => scope.id),+ [scopeId],+ );+ assert.deepEqual(+ snapshot.projection.checkpoints.map((checkpoint) => checkpoint.id),+ [baselineId],+ );}const retainedRequestPlan = yield* sql<{ readonly detail: string }>`EXPLAIN QUERY PLANdiff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex b349ff667f5..1abad6204c8 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -3357,6 +3357,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =SELECT payload_json FROM orchestration_v2_projection_checkpointsWHERE thread_id = ${threadId}AND (status IN ('pending','capturing')+ OR (run_id IS NULL AND ordinal_within_scope = 0 AND status = 'ready')OR checkpoint_id IN (SELECT value FROM json_each(${cohortCheckpointIds}))OR run_id IN (SELECT value FROM json_each(${cohortRunIds}))OR node_id IN (SELECT value FROM json_each(${cohortNodeIds})))diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 8a38f9a102a..63d2fd1ca61 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -30,6 +30,8 @@ import {ProjectId,PROVIDER_SEND_TURN_MAX_ATTACHMENTS,ProviderInstanceId,+ ProviderSessionId,+ ProviderThreadId,ThreadId,RunId,type ScopedThreadRef,@@ -2243,8 +2245,46 @@ describe("waitForRevertedMessage", () => {function projectionAtom() {const base = makeThreadProjectionFixture();+ const providerThreadId = ProviderThreadId.make("provider-thread");const projection = {...base,+ thread: { ...base.thread, activeProviderThreadId: providerThreadId },+ providerThreads: [+ {+ id: providerThreadId,+ driver: "codex",+ providerInstanceId: base.thread.providerInstanceId,+ providerSessionId: ProviderSessionId.make("provider-session"),+ appThreadId: base.thread.id,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle",+ firstRunOrdinal: 1,+ lastRunOrdinal: 4,+ handoffIds: [],+ forkedFrom: null,+ createdAt: base.updatedAt,+ updatedAt: base.updatedAt,+ },+ ],+ runs: [1, 2, 3, 4].map((ordinal) => ({+ id: RunId.make(`run-${ordinal}`),+ threadId: base.thread.id,+ ordinal,+ providerInstanceId: base.thread.providerInstanceId,+ modelSelection: base.thread.modelSelection,+ providerThreadId,+ userMessageId: MessageId.make(`message-${ordinal}`),+ rootNodeId: null,+ activeAttemptId: null,+ status: "completed",+ requestedAt: base.updatedAt,+ startedAt: base.updatedAt,+ completedAt: base.updatedAt,+ checkpointId: null,+ contextHandoffId: null,+ })),messages: [{id: messageId,@@ -2269,7 +2309,7 @@ describe("waitForRevertedMessage", () => {it("rejects with the projected reason when the rollback fails for good", async () => {const { state, projection } = projectionAtom();- const waiting = waitForRevertedMessage(threadRef, messageId, 1, requestId, async () => {});+ const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {});await Promise.resolve();appAtomRegistry.set(state, {data: Option.some({@@ -2284,10 +2324,190 @@ describe("waitForRevertedMessage", () => {await expect(waiting).rejects.toThrow("The provider could not roll back.");});+ it.each([+ ["same", "streamed"],+ ["replacement", "streamed"],+ ["replacement", "refetched"],+ ] as const)(+ "waits for the retained rollback suffix when the edited message and run are paged out (%s provider, %s)",+ async (providerIdentity, projectionSource) => {+ vi.useFakeTimers();+ const { state, projection } = projectionAtom();+ const latestRunId = RunId.make("latest-run-9");+ const latestRun = {+ ...projection.runs[3]!,+ id: latestRunId,+ ordinal: 9,+ userMessageId: MessageId.make("latest-message-9"),+ status: "cancelled" as const,+ };+ const bounded = {+ ...projection,+ messages: [],+ providerThreads: projection.providerThreads.map((thread) => ({+ ...thread,+ lastRunOrdinal: 9,+ })),+ runs: [+ {+ ...latestRun,+ id: RunId.make("old-rewound-run-3"),+ userMessageId: MessageId.make("old-rewound-message-3"),+ ordinal: 3,+ status: "rolled_back" as const,+ },+ latestRun,+ ],+ };+ const oldProviderThread = bounded.providerThreads[0]!;+ const completedProviderThread = {+ ...oldProviderThread,+ ...(providerIdentity === "replacement"+ ? { id: ProviderThreadId.make("replacement-provider-thread"), firstRunOrdinal: null }+ : {}),+ lastRunOrdinal: null,+ };+ appAtomRegistry.set(state, { data: Option.some(bounded) });+ let outcome = "pending";+ const waiting = waitForRevertedMessage(threadRef, 0, requestId, async () => {}).then(+ () => {+ outcome = "reverted";+ },+ (error: Error) => {+ outcome = error.message;+ },+ );++ try {+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("pending");++ appAtomRegistry.set(state, {+ data: Option.some({+ ...bounded,+ thread: {+ ...bounded.thread,+ activeProviderThreadId:+ projectionSource === "refetched"+ ? completedProviderThread.id+ : oldProviderThread.id,+ },+ providerThreads:+ providerIdentity === "replacement"+ ? [oldProviderThread, completedProviderThread]+ : [completedProviderThread],+ runs: bounded.runs.map((run) =>+ run.id === latestRunId ? { ...run, status: "rolled_back" as const } : run,+ ),+ }),+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("reverted");+ await waiting;+ } finally {+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ },+ );++ it("waits for the requested target when another client finishes a shallower rewind", async () => {+ vi.useFakeTimers();+ const { state, projection } = projectionAtom();+ let outcome = "pending";+ const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}).then(+ () => {+ outcome = "reverted";+ },+ (error: Error) => {+ outcome = error.message;+ },+ );++ try {+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("pending");++ // Our command is accepted while the earlier target-3 effect is still running.+ const shallowerRewind = {+ ...projection,+ thread: { ...projection.thread, rollbackRequestId: requestId, rollbackFailure: null },+ providerThreads: projection.providerThreads.map((thread) => ({+ ...thread,+ lastRunOrdinal: 3,+ })),+ runs: projection.runs.map((run) =>+ run.ordinal > 3 ? { ...run, status: "rolled_back" as const } : run,+ ),+ };+ appAtomRegistry.set(state, { data: Option.some(shallowerRewind) });+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("pending");++ appAtomRegistry.set(state, {+ data: Option.some({+ ...shallowerRewind,+ providerThreads: shallowerRewind.providerThreads.map((thread) => ({+ ...thread,+ lastRunOrdinal: 1,+ })),+ runs: shallowerRewind.runs.map((run) =>+ run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,+ ),+ }),+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("reverted");+ await waiting;+ } finally {+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });++ it("rejects a stale edit already rewound by another client during attachment preparation", async () => {+ vi.useFakeTimers();+ const { state, projection } = projectionAtom();+ appAtomRegistry.set(state, {+ data: Option.some({+ ...projection,+ thread: { ...projection.thread, rollbackRequestId: CommandId.make("other-client-rewind") },+ messages: [],+ providerThreads: projection.providerThreads.map((thread) => ({+ ...thread,+ lastRunOrdinal: 1,+ })),+ runs: projection.runs.map((run) =>+ run.ordinal > 1 ? { ...run, status: "rolled_back" as const } : run,+ ),+ }),+ });+ const revert = vi.fn(async () => {});+ let outcome = "pending";+ const waiting = waitForRevertedMessage(threadRef, 1, requestId, revert).then(+ () => {+ outcome = "reverted";+ },+ () => {+ outcome = "rejected";+ },+ );++ try {+ await vi.advanceTimersByTimeAsync(0);+ expect(outcome).toBe("rejected");+ expect(revert).not.toHaveBeenCalled();+ await waiting;+ } finally {+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });+it("ignores a failure recorded for an earlier rollback", async () => {vi.useFakeTimers();const { state, projection } = projectionAtom();- const waiting = waitForRevertedMessage(threadRef, messageId, 1, requestId, async () => {}, 50);+ const waiting = waitForRevertedMessage(threadRef, 1, requestId, async () => {}, 50);const settled = expect(waiting).rejects.toThrow("Timed out waiting for the thread to rewind.");appAtomRegistry.set(state, {data: Option.some({diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 3e0f7a13e48..03a29ceb740 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -1068,7 +1068,6 @@ export async function waitForStartedServerThread(export async function waitForRevertedMessage(threadRef: ScopedThreadRef,- messageId: MessageId,turnCount: number,requestId: CommandId,revert: () => Promise<void>,@@ -1077,10 +1076,26 @@ export async function waitForRevertedMessage(const threadAtom = environmentThreadDetails.stateAtom(threadRef);const readProjection = () => Option.getOrNull(appAtomRegistry.get(threadAtom).data);const initial = readProjection();- if (!initial?.messages.some((message) => message.id === messageId)) {- throw new Error("The message to rewind is no longer available.");+ const providerThreadId = initial?.thread.activeProviderThreadId;+ const initialProviderThread = initial?.providerThreads.find(+ (providerThread) => providerThread.id === providerThreadId,+ );+ const initialProviderThreadIds = new Set(initial?.providerThreads.map((thread) => thread.id));+ // Paging can omit the source run. Rollback commits the entire settled suffix atomically.+ const witness = initial?.runs.reduce<(typeof initial.runs)[number] | undefined>((latest, run) => {+ if (+ run.ordinal <= turnCount ||+ (run.status !== "completed" &&+ run.status !== "interrupted" &&+ run.status !== "failed" &&+ run.status !== "cancelled")+ )+ return latest;+ return latest === undefined || run.ordinal > latest.ordinal ? run : latest;+ }, undefined);+ if (witness === undefined) {+ throw new Error("The thread has changed. Select a message to rewind again.");}- const messageRunId = initial.messages.find((message) => message.id === messageId)?.runId;return new Promise<void>((resolve, reject) => {let settled = false;let accepted = false;@@ -1104,10 +1119,18 @@ export async function waitForRevertedMessage(}if (accepted &&- thread.runs.some(- (run) =>- run.id === messageRunId && run.ordinal > turnCount && run.status === "rolled_back",- )+ thread.providerThreads.some(+ (providerThread) =>+ (providerThread.id === providerThreadId ||+ // Claude resets to a fresh root session when rewinding to thread start.+ (turnCount === 0 &&+ providerThread.ownerNodeId === null &&+ providerThread.appThreadId === initial?.thread.id &&+ providerThread.providerInstanceId === initialProviderThread?.providerInstanceId &&+ !initialProviderThreadIds.has(providerThread.id))) &&+ providerThread.lastRunOrdinal === (turnCount === 0 ? null : turnCount),+ ) &&+ thread.runs.some((run) => run.id === witness.id && run.status === "rolled_back"))finish();};diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 43fd030f8e1..7b14f8b1c54 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -8,7 +8,6 @@ import {resolveDraftHeroState,shouldDockDraftHeroForSubmission,} from "./ChatView.logic";-import * as DateTime from "effect/DateTime";import { restorePlanFollowUpComposer } from "./ChatView.logic";import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";import {@@ -65,6 +64,7 @@ import {type EnvironmentId,type MessageId,type ModelSelection,+ type OrchestrationV2ProviderTurn,type ProjectScript,type PreviewAnnotationPayload,ProviderInstanceId,@@ -72,6 +72,7 @@ import {type ScopedThreadRef,type ThreadId,type RunId,+ type RunAttemptId,type RuntimeRequestId,PROVIDER_SEND_TURN_MAX_ATTACHMENTS,ProviderInteractionMode,@@ -189,6 +190,7 @@ import {deriveActiveWorkStartedAt,deriveCanInterruptRunningThread,findLatestProposedPlan,+ findRevertCheckpoint,hasActionableProposedPlan,isLatestRunSettled,} from "../session-logic";@@ -760,6 +762,7 @@ async function rewindToMessage(input: {readonly threadId: ThreadId;readonly turnCount: number;readonly restoreFiles: boolean;+ readonly checkpoint: ReturnType<typeof findRevertCheckpoint>;readonly draftTarget: ScopedThreadRef | DraftId;readonly composerHasPendingAttachments: boolean;readonly createAssetUrl: Parameters<@@ -767,7 +770,14 @@ async function rewindToMessage(input: {>[0]["createAssetUrl"];readonly revertThreadCheckpoint: (value: {environmentId: EnvironmentId;- input: { commandId: CommandId; threadId: ThreadId; turnCount: number; restoreFiles: boolean };+ input: {+ commandId: CommandId;+ threadId: ThreadId;+ turnCount: number;+ restoreFiles: boolean;+ checkpointId?: string;+ scopeId?: string;+ };}) => Promise<AtomCommandResult<unknown, unknown>>;}): Promise<| { readonly error: string; readonly prompt?: never }@@ -795,24 +805,21 @@ async function rewindToMessage(input: {throw new Error("Make room for this message's attachments in the composer before rewinding.");}const commandId = CommandId.make(randomUUID());- await waitForRevertedMessage(- input.routeThreadRef,- message.id,- input.turnCount,- commandId,- async () => {- const result = await input.revertThreadCheckpoint({- environmentId,- input: {- commandId,- threadId: input.threadId,- turnCount: input.turnCount,- restoreFiles: input.restoreFiles,- },- });- if (result._tag === "Failure") throw squashAtomCommandFailure(result);- },- );+ await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => {+ const result = await input.revertThreadCheckpoint({+ environmentId,+ input: {+ commandId,+ threadId: input.threadId,+ turnCount: input.turnCount,+ restoreFiles: input.restoreFiles,+ ...(input.checkpoint === undefined+ ? {}+ : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }),+ },+ });+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);+ });const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";const restoredPrompt = recallableComposerPrompt(message.text);const nextPrompt =@@ -2929,6 +2936,48 @@ export default function ChatView(props: ChatViewProps) {panelAnimationDurationMs,);const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadDetailRef);+ const availableRevertTurnCounts = (() => {+ const available = new Set<number>();+ const providerThread = serverProjection?.providerThreads.find(+ (candidate) => candidate.id === serverProjection.thread.activeProviderThreadId,+ );+ if (+ !providerThread?.providerSessionId ||+ providerThread.providerInstanceId !== serverProjection?.thread.modelSelection.instanceId+ )+ return available;+ available.add(0);+ const attemptsById = new Map(serverProjection.attempts.map((attempt) => [attempt.id, attempt]));+ const providerTurnsById = new Map<+ OrchestrationV2ProviderTurn["id"],+ OrchestrationV2ProviderTurn+ >();+ const latestTurnByAttempt = new Map<RunAttemptId, OrchestrationV2ProviderTurn>();+ for (const turn of serverProjection.providerTurns) {+ providerTurnsById.set(turn.id, turn);+ if (turn.runAttemptId === null) continue;+ const latest = latestTurnByAttempt.get(turn.runAttemptId);+ if (latest === undefined || turn.ordinal > latest.ordinal) {+ latestTurnByAttempt.set(turn.runAttemptId, turn);+ }+ }+ for (const run of serverProjection.runs) {+ if (run.activeAttemptId === null) continue;+ const attempt = attemptsById.get(run.activeAttemptId);+ const providerTurn =+ latestTurnByAttempt.get(run.activeAttemptId) ??+ (attempt?.providerTurnId == null+ ? undefined+ : providerTurnsById.get(attempt.providerTurnId));+ // A ready file checkpoint alone cannot restore the provider conversation.+ if (providerTurn?.providerThreadId === providerThread.id) available.add(run.ordinal);+ }+ return available;+ })();+ // A paged history window cannot identify the first loaded run as the thread start.+ const threadStartCheckpointReady =+ !serverThreadHistory.hasMoreHistory &&+ findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined;/*** File tools are explicit; completed commands are included because a shell@@ -5875,20 +5924,7 @@ export default function ChatView(props: ChatViewProps) {!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))return;- const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId);- const message = sourceMessage- ? {- id: sourceMessage.id,- role: sourceMessage.role,- text: sourceMessage.text,- attachments: sourceMessage.attachments,- context: sourceMessage.context,- runId: sourceMessage.runId,- streaming: false,- createdAt: DateTime.formatIso(sourceMessage.createdAt),- updatedAt: DateTime.formatIso(sourceMessage.updatedAt),- }- : undefined;+ const message = timelineMessages.find((message) => message.id === messageId);if (!message || message.role !== "user") return;if (!supportsConversationRollback) {@@ -5925,6 +5961,8 @@ export default function ChatView(props: ChatViewProps) {threadId: activeThread.id,turnCount,restoreFiles,+ // Keep the live checkpoint identity when command context refetches a bounded window.+ checkpoint: findRevertCheckpoint(serverProjection?.checkpoints ?? [], turnCount),draftTarget: composerDraftTarget,composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,createAssetUrl: createAttachmentAssetUrl,@@ -8204,6 +8242,8 @@ export default function ChatView(props: ChatViewProps) {supportsConversationRollback={!paintOnlyDisplayedTimeline && supportsConversationRollback}+ threadStartCheckpointReady={threadStartCheckpointReady}+ availableRevertTurnCounts={availableRevertTurnCounts}onRevertToTurnCount={paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurnStable}diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex d55a621d875..b11a2c4b936 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -1281,7 +1281,7 @@ describe("deriveMessagesTimelineRows", () => {expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);});- it("projects assistant diff summaries and user revert counts onto the affected rows", () => {+ it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => {const assistantTurnDiffSummary = {runId: "turn-1" as never,completedAt: "2026-01-01T00:00:30Z",@@ -1328,6 +1328,7 @@ describe("deriveMessagesTimelineRows", () => {activeTurnStartedAt: null,turnDiffSummaries: [assistantTurnDiffSummary],supportsConversationRollback: true,+ threadStartCheckpointReady: true,});const userRow = rows.find(@@ -1339,7 +1340,7 @@ describe("deriveMessagesTimelineRows", () => {row.kind === "message" && row.message.role === "assistant",);- expect(userRow?.revertTurnCount).toBe(1);+ expect(userRow?.revertTurnCount).toBe(0);expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);});@@ -4423,7 +4424,10 @@ describe("streaming v2 row projection", () => {["Visible", "★ Insight\nKeep these line breaks"],])("keeps row parity and history identity from %j to %j", (before, after) => {const initial = fixture(before);- const previous = deriveMessagesTimelineRowsWithState(initial.input);+ const previous = deriveMessagesTimelineRowsWithState({+ ...initial.input,+ availableRevertTurnCounts: new Set([0]),+ });Object.freeze(previous.rows);for (const row of previous.rows) Object.freeze(row);const timelineInput = {@@ -4439,6 +4443,7 @@ describe("streaming v2 row projection", () => {timelineEntries: timeline.entries,latestRun: { ...initial.input.latestRun },turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ ...summary })),+ availableRevertTurnCounts: new Set([0]),};const next = deriveMessagesTimelineRowsWithState(input, previous);expect(next.rows).toEqual(diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex 1024f11a213..89a7971f548 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -1333,6 +1333,8 @@ export function deriveMessagesTimelineRows(input: {activeTurnStartedAt?: string | null;turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;supportsConversationRollback: boolean;+ threadStartCheckpointReady?: boolean;+ availableRevertTurnCounts?: ReadonlySet<number> | undefined;liveAgentTaskIds?: ReadonlySet<string> | undefined;worktreeSetup?: WorktreeSetupSnapshot | null;}): MessagesTimelineRow[] {@@ -1343,10 +1345,14 @@ export function deriveMessagesTimelineRows(input: {turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);}}+ const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);const revertTurnCountByUserMessageId = input.supportsConversationRollback? deriveRevertTurnCountByUserMessageId({timelineEntries: timelineEntries,checkpoints: input.turnDiffSummaries,+ threadStartCheckpointReady: input.threadStartCheckpointReady === true,+ unsettledRunId,+ availableRevertTurnCounts: input.availableRevertTurnCounts,}): new Map<MessageId, number>();const nextRows: MessagesTimelineRow[] = [];@@ -1354,7 +1360,6 @@ export function deriveMessagesTimelineRows(input: {timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),);const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries);- const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null);const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries);const completeSupersededReplyIds = completeSupersededReplyEntryIds(timelineEntries);@@ -2035,6 +2040,7 @@ function replaceStreamingMessageRows(expandedRunIds: previousExpandedRuns,expandedAttemptIds: previousExpandedAttempts,expandedWorkGroupIds: previousExpandedGroups,+ availableRevertTurnCounts: previousAvailableRevertTurnCounts,...previousContext} = previous.input;const {@@ -2044,6 +2050,7 @@ function replaceStreamingMessageRows(expandedRunIds,expandedAttemptIds,expandedWorkGroupIds,+ availableRevertTurnCounts,...context} = input;// V2 shell and checkpoint selectors produce fresh summaries for each event.@@ -2055,6 +2062,7 @@ function replaceStreamingMessageRows(!shallow(previousExpandedRuns, expandedRunIds) ||!shallow(previousExpandedAttempts, expandedAttemptIds) ||!shallow(previousExpandedGroups, expandedWorkGroupIds) ||+ !shallow(previousAvailableRevertTurnCounts, availableRevertTurnCounts) ||!sameCheckpointSummaries(previousCheckpoints, turnDiffSummaries)) {return null;diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex fc349b1a080..ac02feb76b1 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -484,6 +484,8 @@ interface MessagesTimelineProps {readonly scopeId: string;}) => void;supportsConversationRollback: boolean;+ threadStartCheckpointReady?: boolean;+ availableRevertTurnCounts?: ReadonlySet<number> | undefined;onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;onSendAppMessage?: (text: string) => Promise<void>;@@ -583,6 +585,8 @@ const ConversationTimeline = memo(function ConversationTimeline({onForkFromRun,onRollbackCheckpoint,supportsConversationRollback,+ threadStartCheckpointReady = false,+ availableRevertTurnCounts,onRevertToTurnCount,onUseArtifactTemplate = NOOP_USE_ARTIFACT_TEMPLATE,onSendAppMessage,@@ -857,6 +861,8 @@ const ConversationTimeline = memo(function ConversationTimeline({activeTurnStartedAt,turnDiffSummaries,supportsConversationRollback,+ threadStartCheckpointReady,+ availableRevertTurnCounts,worktreeSetup,});const rows = useStableRows(rawRows, listIdentityKey);diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex 6479438d2bb..9895998b137 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -277,6 +277,7 @@ describe("V2 session presentation", () => {const targets = deriveRevertTurnCountByUserMessageId({timelineEntries,+ threadStartCheckpointReady: true,checkpoints: [{runId,@@ -294,6 +295,173 @@ describe("V2 session presentation", () => {expect(targets.has(steerMessageId)).toBe(false);});+ describe("revert targets after a rewind", () => {+ const runId = (ordinal: number) => RunId.make(`run-${ordinal}`);+ const turn = (ordinal: number): TimelineEntry[] =>+ (["user", "assistant"] as const).map((role) => {+ const id = MessageId.make(`${role}-${ordinal}`);+ const createdAt = `2026-06-20T00:00:0${ordinal}.000Z`;+ return {+ id,+ kind: "message",+ createdAt,+ message: {+ id,+ role,+ text: role,+ runId: runId(ordinal),+ ...(role === "user" ? { inputIntent: "turn_start" as const } : {}),+ streaming: false,+ createdAt,+ updatedAt: createdAt,+ },+ };+ });+ const checkpoint = (ordinal: number, status: "ready" | "stale" = "ready") => ({+ runId: runId(ordinal),+ checkpointTurnCount: ordinal,+ checkpointRef: `checkpoint-${ordinal}` as never,+ status,+ files: [],+ assistantMessageId: MessageId.make(`assistant-${ordinal}`),+ completedAt: "2026-06-20T00:00:09.000Z",+ });+ const targets = (+ ordinals: ReadonlyArray<number>,+ checkpoints: ReadonlyArray<ReturnType<typeof checkpoint>>,+ options: { threadStartCheckpointReady?: boolean; unsettledRunId?: RunId } = {},+ ) =>+ Object.fromEntries(+ deriveRevertTurnCountByUserMessageId({+ timelineEntries: ordinals.flatMap(turn),+ checkpoints,+ threadStartCheckpointReady: options.threadStartCheckpointReady ?? true,+ unsettledRunId: options.unsettledRunId ?? null,+ }),+ );++ it("keeps rewound and stopped runs editable at the previous visible checkpoint", () => {+ // Runs 1 and 3 were rewound; run 5 stopped without capturing a checkpoint.+ expect(targets([2, 4, 5], [checkpoint(2), checkpoint(3, "stale"), checkpoint(4)])).toEqual({+ "user-2": 0,+ "user-4": 2,+ "user-5": 4,+ });+ expect(targets([2], [checkpoint(1, "stale")])).toEqual({ "user-2": 0 });+ });++ it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => {+ const fixture = makeStreamingTimelineFixture();+ const first = fixture.visibleTurnItems[0]!;+ if (first.item.type !== "user_message") throw new Error("Expected a user message fixture.");+ const notification = {+ ...first,+ item: {+ ...first.item,+ id: TurnItemId.make("wake-item"),+ runId: runId(2),+ type: "notification" as const,+ source: { kind: "delegated_task" as const, taskIds: [NodeId.make("task-1")] },+ outcome: "unknown" as const,+ summary: "Delegated task finished",+ },+ };+ const inherited = {+ ...notification,+ visibility: "inherited" as const,+ sourceThreadId: ThreadId.make("parent-thread"),+ sourceItemId: TurnItemId.make("inherited-wake"),+ item: {+ ...notification.item,+ id: TurnItemId.make("inherited-wake"),+ threadId: ThreadId.make("parent-thread"),+ runId: runId(7),+ },+ };+ const work: TimelineEntry = {+ id: "background-work",+ kind: "work",+ createdAt: "2026-06-20T00:00:02.000Z",+ entry: {+ id: "background-work",+ createdAt: "2026-06-20T00:00:02.000Z",+ runId: runId(8),+ itemType: "command_execution",+ label: "Background work",+ tone: "tool",+ },+ };++ expect(+ Object.fromEntries(+ deriveRevertTurnCountByUserMessageId({+ timelineEntries: [+ ...turn(1),+ ...deriveTimelineEntriesFromVisibleTurnItems({+ visibleTurnItems: [notification, inherited],+ optimisticMessages: [],+ }),+ work,+ ...turn(3),+ ],+ checkpoints: [+ checkpoint(1),+ checkpoint(2),+ checkpoint(3),+ checkpoint(7),+ checkpoint(8),+ ],+ threadStartCheckpointReady: true,+ }),+ ),+ ).toEqual({ "user-1": 0, "user-3": 2 });+ });++ it("hides edit when the predecessor is unavailable or the run is unsettled", () => {+ expect(targets([1, 2], [checkpoint(2)])).toEqual({ "user-1": 0 });+ expect(targets([1, 2], [checkpoint(1, "stale"), checkpoint(2)])).toEqual({ "user-1": 0 });+ // Earlier history is paged out, so the first loaded run's predecessor is unknown.+ expect(+ targets([4, 5], [checkpoint(4), checkpoint(5)], { threadStartCheckpointReady: false }),+ ).toEqual({ "user-5": 4 });+ expect(targets([1, 2], [checkpoint(1), checkpoint(2)], { unsettledRunId: runId(2) })).toEqual(+ { "user-1": 0 },+ );+ });++ it("can edit a cancelled run but cannot target its checkpoint without a provider turn", () => {+ expect(+ Object.fromEntries(+ deriveRevertTurnCountByUserMessageId({+ timelineEntries: [1, 2, 3].flatMap(turn),+ checkpoints: [checkpoint(1), checkpoint(2), checkpoint(3)],+ threadStartCheckpointReady: true,+ availableRevertTurnCounts: new Set([0, 1]),+ }),+ ),+ ).toEqual({ "user-1": 0, "user-2": 1 });+ });++ it("leaves inherited history uneditable and restores the first local run to thread start", () => {+ const fixture = makeStreamingTimelineFixture();+ const inheritedEntries = deriveTimelineEntriesFromVisibleTurnItems({+ visibleTurnItems: fixture.visibleTurnItems+ .filter(({ item }) => item.runId === fixture.historyRunId)+ .map((item) => ({ ...item, visibility: "inherited" as const })),+ optimisticMessages: [],+ });+ expect(+ Object.fromEntries(+ deriveRevertTurnCountByUserMessageId({+ timelineEntries: [...inheritedEntries, ...turn(2)],+ checkpoints: [{ ...checkpoint(7), runId: fixture.historyRunId }, checkpoint(2)],+ threadStartCheckpointReady: true,+ }),+ ),+ ).toEqual({ "user-2": 0 });+ });+ });+it("uses visible turn item order and keeps provider errors in the work log", () => {const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");const threadId = ThreadId.make("thread-visible");diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex 7c60d263c02..29bdad1be0b 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -1,6 +1,7 @@import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";import {type AssetResource,+ type OrchestrationV2Checkpoint,type OrchestrationV2ExecutionNode,type OrchestrationV2PlanArtifact,type OrchestrationV2ProjectedTurnItem,@@ -1011,30 +1012,74 @@ export function deriveTimelineEntriesFromVisibleTurnItemsWithState(};}+// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.export function deriveRevertTurnCountByUserMessageId(input: {readonly timelineEntries: ReadonlyArray<TimelineEntry>;readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;+ readonly threadStartCheckpointReady: boolean;+ readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;+ readonly unsettledRunId?: RunId | null;}): Map<ChatMessage["id"], number> {- const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();+ const readyTurnCountByRunId = new Map<RunId, number>();for (const checkpoint of input.checkpoints) {if (checkpoint.status === "ready") {- readyCheckpointByRunId.set(checkpoint.runId, checkpoint);+ readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);}}+ const targetByRunId = new Map<RunId, number | undefined>();const byUserMessageId = new Map<ChatMessage["id"], number>();+ let previousRunId: RunId | null = null;for (const entry of input.timelineEntries) {- if (entry.kind !== "message" || entry.message.role !== "user") continue;- if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {- continue;+ // Inherited history belongs to the source thread, not our checkpoint scope.+ if (entry.kind !== "message" && entry.kind !== "work") continue;+ const projectedItem =+ entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;+ if (projectedItem?.visibility === "inherited") continue;+ const runId =+ entry.kind === "message"+ ? entry.message.runId+ : entry.entry.itemType === "notification"+ ? entry.entry.runId+ : null;+ if (runId == null) continue;+ if (!targetByRunId.has(runId)) {+ targetByRunId.set(+ runId,+ previousRunId === null+ ? input.threadStartCheckpointReady+ ? 0+ : undefined+ : readyTurnCountByRunId.get(previousRunId),+ );+ previousRunId = runId;}- if (entry.message.runId === null) continue;- const checkpoint = readyCheckpointByRunId.get(entry.message.runId);- if (checkpoint === undefined) continue;- byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));+ if (entry.kind !== "message") continue;+ const { message } = entry;+ if (message.role !== "user" || message.runId === input.unsettledRunId) continue;+ if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;+ const target = targetByRunId.get(runId);+ if (+ target !== undefined &&+ (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))+ )+ byUserMessageId.set(message.id, target);}return byUserMessageId;}+export function findRevertCheckpoint(+ checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,+ turnCount: number,+): OrchestrationV2Checkpoint | undefined {+ return checkpoints.findLast(+ (checkpoint) =>+ checkpoint.status === "ready" &&+ (turnCount === 0+ ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null+ : checkpoint.appRunOrdinal === turnCount),+ );+}+export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {if (runtime === null) return "disconnected";if (