From 6cf6d7bc663943c9694141ba79644a151276fee8 Mon Sep 17 00:00:00 2001 From: Rishin Georgy Anil Date: Sun, 19 Jul 2026 17:23:49 +0100 Subject: [PATCH] fix: restore missing revert actions and resized timelines --- .../src/checkpointing/CheckpointStore.test.ts | 103 ++++++++ .../src/checkpointing/CheckpointStore.ts | 221 ++++++++++++++++-- .../Layers/CheckpointReactor.test.ts | 96 +++++++- .../orchestration/Layers/CheckpointReactor.ts | 96 ++++---- .../Layers/ProjectionPipeline.test.ts | 5 + .../Layers/ProjectionPipeline.ts | 89 +++---- .../src/orchestration/projector.test.ts | 8 +- apps/server/src/orchestration/projector.ts | 15 +- apps/server/src/vcs/GitVcsDriver.ts | 39 +++- .../web/src/components/ChatView.logic.test.ts | 70 ++++++ apps/web/src/components/ChatView.logic.ts | 60 ++++- apps/web/src/components/ChatView.tsx | 51 ++-- .../components/chat/MessagesTimeline.test.tsx | 15 ++ .../src/components/chat/MessagesTimeline.tsx | 98 ++++++-- .../src/state/threadReducer.test.ts | 151 ++++++++++++ .../client-runtime/src/state/threadReducer.ts | 68 +++++- 16 files changed, 979 insertions(+), 206 deletions(-) diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index bf332d20d0..5cae4f68ca 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -112,9 +112,112 @@ it.layer(TestLayer)("CheckpointStore.layer", (it) => { expect(yield* checkpointStore.isGitRepository(tmp)).toBe(true); }), ); + + it.effect("treats a standalone project nested under another repository as non-Git", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const fileSystem = yield* FileSystem.FileSystem; + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const project = NodePath.join(tmp, "project"); + yield* git(tmp, ["init"]); + yield* fileSystem.makeDirectory(project); + + expect(yield* checkpointStore.isGitRepository(project)).toBe(false); + }), + ); }); describe("diffCheckpoints", () => { + it.effect("captures and restores an initialized repository before its first commit", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir("checkpoint-store-unborn-git-test-"); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const threadId = ThreadId.make("thread-unborn-git-checkpoint-store"); + const baselineRef = checkpointRefForThreadTurn(threadId, 0); + const sourcePath = NodePath.join(tmp, "source.txt"); + + yield* git(tmp, ["init"]); + yield* writeTextFile(sourcePath, "before\n"); + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baselineRef }); + yield* writeTextFile(sourcePath, "after\n"); + + expect( + yield* checkpointStore.restoreCheckpoint({ + cwd: tmp, + checkpointRef: baselineRef, + }), + ).toBe(true); + const fileSystem = yield* FileSystem.FileSystem; + expect(yield* fileSystem.readFileString(sourcePath)).toBe("before\n"); + }), + ); + + it.effect("uses shadow checkpoints for a project nested under an unrelated repository", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir("checkpoint-store-nested-project-test-"); + const fileSystem = yield* FileSystem.FileSystem; + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const project = NodePath.join(tmp, "project"); + const threadId = ThreadId.make("thread-nested-project-checkpoint-store"); + const baselineRef = checkpointRefForThreadTurn(threadId, 0); + const changedRef = checkpointRefForThreadTurn(threadId, 1); + const createdPath = NodePath.join(project, "created.txt"); + + yield* git(tmp, ["init"]); + yield* fileSystem.makeDirectory(project); + yield* checkpointStore.captureCheckpoint({ cwd: project, checkpointRef: baselineRef }); + yield* writeTextFile(createdPath, "created\n"); + yield* checkpointStore.captureCheckpoint({ cwd: project, checkpointRef: changedRef }); + + expect( + yield* checkpointStore.restoreCheckpoint({ + cwd: project, + checkpointRef: baselineRef, + }), + ).toBe(true); + expect(yield* fileSystem.exists(createdPath)).toBe(false); + expect(yield* checkpointStore.isGitRepository(project)).toBe(false); + }), + ); + + it.effect("captures and restores files without initializing Git in the workspace", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir("checkpoint-store-shadow-test-"); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const threadId = ThreadId.make("thread-shadow-checkpoint-store"); + const baselineRef = checkpointRefForThreadTurn(threadId, 0); + const changedRef = checkpointRefForThreadTurn(threadId, 1); + const sourcePath = NodePath.join(tmp, "source.txt"); + const createdPath = NodePath.join(tmp, "created.txt"); + + yield* writeTextFile(sourcePath, "before\n"); + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: baselineRef }); + yield* writeTextFile(sourcePath, "after\n"); + yield* writeTextFile(createdPath, "new\n"); + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: changedRef }); + + const diff = yield* checkpointStore.diffCheckpoints({ + cwd: tmp, + fromCheckpointRef: baselineRef, + toCheckpointRef: changedRef, + ignoreWhitespace: false, + }); + expect(diff).toContain("+after"); + expect(diff).toContain("created.txt"); + + expect( + yield* checkpointStore.restoreCheckpoint({ + cwd: tmp, + checkpointRef: baselineRef, + }), + ).toBe(true); + const fileSystem = yield* FileSystem.FileSystem; + expect(yield* fileSystem.readFileString(sourcePath)).toBe("before\n"); + expect(yield* fileSystem.exists(createdPath)).toBe(false); + expect(yield* checkpointStore.isGitRepository(tmp)).toBe(false); + }), + ); + it.effect("returns full oversized checkpoint diffs without truncation", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index f13aa4572c..f1cb5c1346 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -1,9 +1,9 @@ /** * CheckpointStore - Repository interface for filesystem-backed workspace checkpoints. * - * Owns hidden Git-ref checkpoint capture/restore and diff computation for a - * workspace thread timeline. It does not store user-facing checkpoint metadata - * and does not coordinate provider conversation rollback. + * Owns hidden checkpoint capture/restore and diff computation for a workspace + * thread timeline. Git workspaces use their repository's hidden refs; other + * workspaces use a T3-managed shadow Git store outside the project directory. * * The live adapter resolves the active VCS driver once per checkpoint operation * and delegates to the driver's optional checkpoint capability. @@ -13,14 +13,21 @@ * * @module CheckpointStore */ -import { VcsUnsupportedOperationError, type CheckpointRef } from "@t3tools/contracts"; +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; +import * as NodePath from "node:path"; + +import { type CheckpointRef } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import type { CheckpointStoreError } from "./Errors.ts"; import type { VcsCheckpointOps } from "../vcs/VcsDriver.ts"; +import { ServerConfig } from "../config.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; export interface CaptureCheckpointInput { readonly cwd: string; @@ -50,7 +57,7 @@ export interface DeleteCheckpointRefsInput { export class CheckpointStore extends Context.Service< CheckpointStore, { - /** Check whether cwd is inside a Git worktree. */ + /** Check whether cwd is inside a user-managed Git worktree. */ readonly isGitRepository: (cwd: string) => Effect.Effect; /** @@ -98,26 +105,208 @@ export class CheckpointStore extends Context.Service< export const make = Effect.gen(function* () { const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry; + const vcsProcess = yield* VcsProcess.VcsProcess; + const fileSystem = yield* FileSystem.FileSystem; + const config = yield* ServerConfig; + + const shadowRepositoryPath = (cwd: string) => + NodePath.join( + config.stateDir, + "checkpoints", + NodeCrypto.createHash("sha256").update(NodePath.resolve(cwd)).digest("hex"), + ); + + const runShadowGit = Effect.fn("CheckpointStore.runShadowGit")(function* (input: { + readonly operation: string; + readonly cwd: string; + readonly args: ReadonlyArray; + readonly env?: NodeJS.ProcessEnv; + readonly allowNonZeroExit?: boolean; + readonly maxOutputBytes?: number; + }) { + const gitDir = shadowRepositoryPath(input.cwd); + yield* vcsProcess.run({ + operation: `${input.operation}.init`, + command: "git", + cwd: input.cwd, + args: ["init", "--bare", "--quiet", gitDir], + }); + return yield* vcsProcess.run({ + operation: input.operation, + command: "git", + cwd: input.cwd, + args: [`--git-dir=${gitDir}`, `--work-tree=${NodePath.resolve(input.cwd)}`, ...input.args], + ...(input.env ? { env: input.env } : {}), + ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}), + ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}), + }); + }); + + const resolveShadowCommit = Effect.fn("CheckpointStore.resolveShadowCommit")(function* (input: { + readonly cwd: string; + readonly checkpointRef: CheckpointRef; + }) { + const result = yield* runShadowGit({ + operation: "CheckpointStore.shadow.resolveCheckpointCommit", + cwd: input.cwd, + args: ["rev-parse", "--verify", "--quiet", `${input.checkpointRef}^{commit}`], + allowNonZeroExit: true, + }); + if (result.exitCode !== 0) { + return null; + } + const commit = result.stdout.trim(); + return commit.length > 0 ? commit : null; + }); + + const shadowCheckpoints: VcsCheckpointOps = { + captureCheckpoint: Effect.fn("CheckpointStore.shadow.captureCheckpoint")(function* (input) { + const gitDir = shadowRepositoryPath(input.cwd); + const tempIndexPath = NodePath.join(gitDir, `t3-checkpoint-index-${NodeCrypto.randomUUID()}`); + const env: NodeJS.ProcessEnv = { + ...process.env, + GIT_INDEX_FILE: tempIndexPath, + GIT_AUTHOR_NAME: "T3 Code", + GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com", + GIT_COMMITTER_NAME: "T3 Code", + GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com", + }; + const cleanup = fileSystem.remove(tempIndexPath, { force: true }).pipe(Effect.ignore); + + yield* Effect.gen(function* () { + yield* runShadowGit({ + operation: "CheckpointStore.shadow.captureCheckpoint.readTree", + cwd: input.cwd, + args: ["read-tree", "--empty"], + env, + }); + yield* runShadowGit({ + operation: "CheckpointStore.shadow.captureCheckpoint.add", + cwd: input.cwd, + args: ["add", "-A", "--", "."], + env, + }); + const tree = yield* runShadowGit({ + operation: "CheckpointStore.shadow.captureCheckpoint.writeTree", + cwd: input.cwd, + args: ["write-tree"], + env, + }); + const commit = yield* runShadowGit({ + operation: "CheckpointStore.shadow.captureCheckpoint.commitTree", + cwd: input.cwd, + args: [ + "commit-tree", + tree.stdout.trim(), + "-m", + `t3 checkpoint ref=${input.checkpointRef}`, + ], + env, + }); + yield* runShadowGit({ + operation: "CheckpointStore.shadow.captureCheckpoint.updateRef", + cwd: input.cwd, + args: ["update-ref", input.checkpointRef, commit.stdout.trim()], + }); + }).pipe(Effect.ensuring(cleanup)); + }), + + hasCheckpointRef: (input) => + resolveShadowCommit(input).pipe(Effect.map((commit) => commit !== null)), + + restoreCheckpoint: Effect.fn("CheckpointStore.shadow.restoreCheckpoint")(function* (input) { + const commit = yield* resolveShadowCommit(input); + if (!commit) { + return false; + } + const tempIndexPath = NodePath.join( + shadowRepositoryPath(input.cwd), + `t3-checkpoint-index-${NodeCrypto.randomUUID()}`, + ); + const env: NodeJS.ProcessEnv = { ...process.env, GIT_INDEX_FILE: tempIndexPath }; + const cleanup = fileSystem.remove(tempIndexPath, { force: true }).pipe(Effect.ignore); + yield* Effect.gen(function* () { + yield* runShadowGit({ + operation: "CheckpointStore.shadow.restoreCheckpoint.readTree", + cwd: input.cwd, + args: ["read-tree", commit], + env, + }); + yield* runShadowGit({ + operation: "CheckpointStore.shadow.restoreCheckpoint.checkout", + cwd: input.cwd, + args: ["checkout-index", "--all", "--force"], + env, + }); + yield* runShadowGit({ + operation: "CheckpointStore.shadow.restoreCheckpoint.clean", + cwd: input.cwd, + args: ["clean", "-fd", "--", "."], + env, + }); + }).pipe(Effect.ensuring(cleanup)); + return true; + }), + + diffCheckpoints: Effect.fn("CheckpointStore.shadow.diffCheckpoints")(function* (input) { + const result = yield* runShadowGit({ + operation: "CheckpointStore.shadow.diffCheckpoints", + cwd: input.cwd, + args: [ + "diff", + "--patch", + "--no-color", + "--no-ext-diff", + "--no-textconv", + ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), + `${input.fromCheckpointRef}^{commit}`, + `${input.toCheckpointRef}^{commit}`, + ], + allowNonZeroExit: true, + maxOutputBytes: 50 * 1024 * 1024, + }); + return result.stdout; + }), + + deleteCheckpointRefs: Effect.fn("CheckpointStore.shadow.deleteCheckpointRefs")( + function* (input) { + yield* Effect.forEach( + input.checkpointRefs, + (checkpointRef) => + runShadowGit({ + operation: "CheckpointStore.shadow.deleteCheckpointRefs", + cwd: input.cwd, + args: ["update-ref", "-d", checkpointRef], + allowNonZeroExit: true, + }), + { concurrency: 1, discard: true }, + ); + }, + ), + }; const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* ( - operation: string, + _operation: string, cwd: string, ) { - const handle = yield* vcsRegistry.resolve({ cwd }); - if (!handle.driver.checkpoints) { - return yield* new VcsUnsupportedOperationError({ - operation, - kind: handle.kind, - detail: `${handle.kind} driver does not implement checkpoint operations.`, - }); - } - return handle.driver.checkpoints satisfies VcsCheckpointOps; + const handle = yield* vcsRegistry.detect({ cwd }); + const workspaceOwnsRepository = + handle !== null && NodePath.resolve(handle.repository.rootPath) === NodePath.resolve(cwd); + return workspaceOwnsRepository + ? (handle.driver.checkpoints ?? shadowCheckpoints) + : shadowCheckpoints; }); const isGitRepository: CheckpointStore["Service"]["isGitRepository"] = (cwd) => vcsRegistry .detect({ cwd, requestedKind: "git" }) - .pipe(Effect.map((repository) => repository !== null)); + .pipe( + Effect.map( + (repository) => + repository !== null && + NodePath.resolve(repository.repository.rootPath) === NodePath.resolve(cwd), + ), + ); const captureCheckpoint: CheckpointStore["Service"]["captureCheckpoint"] = Effect.fn( "captureCheckpoint", diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 707c87c43c..cecb5335df 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -413,6 +413,7 @@ describe("CheckpointReactor", () => { return { engine, + runPromise: (effect: Effect.Effect) => runtime!.runPromise(effect), readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()), provider, cwd, @@ -424,7 +425,7 @@ describe("CheckpointReactor", () => { const harness = await createHarness({ seedFilesystemCheckpoints: false }); const createdAt = "2026-01-01T00:00:00.000Z"; - await Effect.runPromise( + await harness.runPromise( harness.engine.dispatch({ type: "thread.session.set", commandId: CommandId.make("cmd-session-set-capture"), @@ -828,7 +829,7 @@ describe("CheckpointReactor", () => { ); }); - it("continues processing runtime events after a single checkpoint runtime failure", async () => { + it("captures completed turns in a non-Git workspace and continues processing", async () => { const nonRepositorySessionCwd = NodeFS.mkdtempSync( NodePath.join(NodeOS.tmpdir(), "t3-checkpoint-runtime-non-repo-"), ); @@ -879,13 +880,13 @@ describe("CheckpointReactor", () => { turnId: asTurnId("turn-after-runtime-failure"), }); - await waitForGitRefExists( - harness.cwd, - checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0), + const thread = await waitForThread(harness.readModel, (entry) => + entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 1), ); + expect(thread.checkpoints).toHaveLength(1); expect( - gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)), - ).toBe(true); + thread.activities.some((activity) => activity.kind === "checkpoint.capture.failed"), + ).toBe(false); }); it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => { @@ -969,6 +970,87 @@ describe("CheckpointReactor", () => { ).toBe(false); }); + it("reverts legacy conversation turns that predate filesystem checkpoints", async () => { + const harness = await createHarness(); + const threadId = ThreadId.make("thread-1"); + const createdAt = "2026-01-01T00:00:00.000Z"; + + await harness.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-legacy-session-set"), + threadId, + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }), + ); + + for (const turnNumber of [1, 2]) { + const turnId = asTurnId(`legacy-turn-${turnNumber}`); + await harness.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-legacy-user-${turnNumber}`), + threadId, + message: { + messageId: MessageId.make(`legacy-user-${turnNumber}`), + role: "user", + text: `User ${turnNumber}`, + attachments: [], + }, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt, + }), + ); + await harness.runPromise( + harness.engine.dispatch({ + type: "thread.message.assistant.delta", + commandId: CommandId.make(`cmd-legacy-assistant-delta-${turnNumber}`), + threadId, + messageId: MessageId.make(`legacy-assistant-${turnNumber}`), + delta: `Assistant ${turnNumber}`, + turnId, + createdAt, + }), + ); + await harness.runPromise( + harness.engine.dispatch({ + type: "thread.message.assistant.complete", + commandId: CommandId.make(`cmd-legacy-assistant-complete-${turnNumber}`), + threadId, + messageId: MessageId.make(`legacy-assistant-${turnNumber}`), + turnId, + createdAt, + }), + ); + } + + await harness.runPromise( + harness.engine.dispatch({ + type: "thread.checkpoint.revert", + commandId: CommandId.make("cmd-legacy-revert-request"), + threadId, + turnCount: 1, + createdAt, + }), + ); + + await waitForEvent(harness.engine, (event) => event.type === "thread.reverted"); + expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({ + threadId, + numTurns: 1, + }); + }); + it("executes provider revert and emits thread.reverted for claude sessions", async () => { const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") }); const createdAt = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 3ba244ddf2..ffc1beb4d4 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -32,7 +32,6 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts" import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; import type { CheckpointStoreError } from "../../checkpointing/Errors.ts"; import type { OrchestrationDispatchError } from "../Errors.ts"; -import { isGitRepository } from "../../git/Utils.ts"; import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts"; import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts"; @@ -59,6 +58,10 @@ function sameId(left: string | null | undefined, right: string | null | undefine return left === right; } +export function countConversationTurns(messages: ReadonlyArray<{ readonly role: string }>): number { + return messages.reduce((count, message) => count + (message.role === "user" ? 1 : 0), 0); +} + function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" { switch (status) { case "failed": @@ -174,12 +177,10 @@ const make = Effect.gen(function* () { return project ? [project] : []; }); - const isGitWorkspace = (cwd: string) => isGitRepository(cwd); - // Resolves the workspace CWD for checkpoint operations, preferring the // active provider session CWD and falling back to the thread/project config. - // Returns undefined when no CWD can be determined or the workspace is not - // a git repository. + // CheckpointStore supports both user Git repositories and T3-managed shadow + // repositories, so a project does not need to initialize Git first. const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: { readonly threadId: ThreadId; readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null }; @@ -206,9 +207,6 @@ const make = Effect.gen(function* () { if (!cwd) { return undefined; } - if (!isGitWorkspace(cwd)) { - return undefined; - } return cwd; }); @@ -633,20 +631,12 @@ const make = Effect.gen(function* () { }).pipe(Effect.catch(() => Effect.void)); return; } - if (!isGitWorkspace(sessionRuntime.value.cwd)) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: "Checkpoints are unavailable because this project is not a git repository.", - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - const currentTurnCount = thread.checkpoints.reduce( + const checkpointTurnCount = thread.checkpoints.reduce( (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), 0, ); + const currentTurnCount = + checkpointTurnCount > 0 ? checkpointTurnCount : countConversationTurns(thread.messages); if (event.payload.turnCount > currentTurnCount) { yield* appendRevertFailureActivity({ @@ -658,42 +648,44 @@ const make = Effect.gen(function* () { return; } - const targetCheckpointRef = - event.payload.turnCount === 0 - ? checkpointRefForThreadTurn(event.payload.threadId, 0) - : thread.checkpoints.find( - (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount, - )?.checkpointRef; + if (checkpointTurnCount > 0) { + const targetCheckpointRef = + event.payload.turnCount === 0 + ? checkpointRefForThreadTurn(event.payload.threadId, 0) + : thread.checkpoints.find( + (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount, + )?.checkpointRef; - if (!targetCheckpointRef) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; + if (!targetCheckpointRef) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + const restored = yield* checkpointStore.restoreCheckpoint({ + cwd: sessionRuntime.value.cwd, + checkpointRef: targetCheckpointRef, + fallbackToHead: event.payload.turnCount === 0, + }); + if (!restored) { + yield* appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + return; + } + + // Refresh the workspace entry index so the @-mention file picker + // reflects the reverted filesystem state. + yield* workspaceEntries.refresh(sessionRuntime.value.cwd); } - const restored = yield* checkpointStore.restoreCheckpoint({ - cwd: sessionRuntime.value.cwd, - checkpointRef: targetCheckpointRef, - fallbackToHead: event.payload.turnCount === 0, - }); - if (!restored) { - yield* appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - return; - } - - // Refresh the workspace entry index so the @-mention file picker - // reflects the reverted filesystem state. - yield* workspaceEntries.refresh(sessionRuntime.value.cwd); - const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount); if (rolledBackTurns > 0) { yield* providerService.rollbackConversation({ diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 0999000ed4..da4ec1c614 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2395,6 +2395,11 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { turnId: "turn-1", role: "assistant", }, + { + messageId: "user-remove", + turnId: "turn-2", + role: "user", + }, ]); }), ); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index f12df85094..235725b726 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -210,12 +210,7 @@ function retainProjectionMessagesAfterRevert( ): ReadonlyArray { const retainedMessageIds = new Set(); const retainedTurnIds = new Set(); - const keptTurns = turns.filter( - (turn) => - turn.turnId !== null && - turn.checkpointTurnCount !== null && - turn.checkpointTurnCount <= turnCount, - ); + const keptTurns = retainProjectionTurnsAfterRevert(turns, turnCount); for (const turn of keptTurns) { if (turn.turnId !== null) { retainedTurnIds.add(turn.turnId); @@ -241,15 +236,12 @@ function retainProjectionMessagesAfterRevert( const retainedUserCount = messages.filter( (message) => message.role === "user" && retainedMessageIds.has(message.messageId), ).length; - const missingUserCount = Math.max(0, turnCount - retainedUserCount); + // Keep the selected user prompt (the message immediately after the retained turns), + // while pruning its response and every message that follows it. + const missingUserCount = Math.max(0, turnCount + 1 - retainedUserCount); if (missingUserCount > 0) { const fallbackUserMessages = messages - .filter( - (message) => - message.role === "user" && - !retainedMessageIds.has(message.messageId) && - (message.turnId === null || retainedTurnIds.has(message.turnId)), - ) + .filter((message) => message.role === "user" && !retainedMessageIds.has(message.messageId)) .toSorted( (left, right) => left.createdAt.localeCompare(right.createdAt) || @@ -287,20 +279,39 @@ function retainProjectionMessagesAfterRevert( return messages.filter((message) => retainedMessageIds.has(message.messageId)); } +function retainProjectionTurnsAfterRevert( + turns: ReadonlyArray, + turnCount: number, +): ReadonlyArray { + const checkpointedTurns = turns.filter( + (turn) => + turn.turnId !== null && + turn.checkpointTurnCount !== null && + turn.checkpointTurnCount <= turnCount, + ); + if (turns.some((turn) => turn.checkpointTurnCount !== null)) { + return checkpointedTurns; + } + + return turns + .filter((turn) => turn.turnId !== null) + .toSorted( + (left, right) => + left.requestedAt.localeCompare(right.requestedAt) || + (left.turnId ?? "").localeCompare(right.turnId ?? ""), + ) + .slice(0, turnCount); +} + function retainProjectionActivitiesAfterRevert( activities: ReadonlyArray, turns: ReadonlyArray, turnCount: number, ): ReadonlyArray { const retainedTurnIds = new Set( - turns - .filter( - (turn) => - turn.turnId !== null && - turn.checkpointTurnCount !== null && - turn.checkpointTurnCount <= turnCount, - ) - .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])), + retainProjectionTurnsAfterRevert(turns, turnCount).flatMap((turn) => + turn.turnId === null ? [] : [turn.turnId], + ), ); return activities.filter( (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), @@ -313,14 +324,9 @@ function retainProjectionProposedPlansAfterRevert( turnCount: number, ): ReadonlyArray { const retainedTurnIds = new Set( - turns - .filter( - (turn) => - turn.turnId !== null && - turn.checkpointTurnCount !== null && - turn.checkpointTurnCount <= turnCount, - ) - .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])), + retainProjectionTurnsAfterRevert(turns, turnCount).flatMap((turn) => + turn.turnId === null ? [] : [turn.turnId], + ), ); return proposedPlans.filter( (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId), @@ -772,19 +778,22 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } - const retainedTurns = yield* projectionTurnRepository.listByThreadId({ + const existingTurns = yield* projectionTurnRepository.listByThreadId({ threadId: event.payload.threadId, }); + const retainedTurns = retainProjectionTurnsAfterRevert( + existingTurns, + event.payload.turnCount, + ); let latestTurnId: ProjectionTurn["turnId"] = null; let latestCheckpointTurnCount = -1; for (let index = 0; index < retainedTurns.length; index += 1) { const turn = retainedTurns[index]; - if ( - !turn || - turn.turnId === null || - turn.checkpointTurnCount === null || - turn.checkpointTurnCount > event.payload.turnCount - ) { + if (!turn || turn.turnId === null) { + continue; + } + if (turn.checkpointTurnCount === null) { + latestTurnId = turn.turnId; continue; } if (turn.checkpointTurnCount > latestCheckpointTurnCount) { @@ -1305,11 +1314,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti const existingTurns = yield* projectionTurnRepository.listByThreadId({ threadId: event.payload.threadId, }); - const keptTurns = existingTurns.filter( - (turn) => - turn.turnId !== null && - turn.checkpointTurnCount !== null && - turn.checkpointTurnCount <= event.payload.turnCount, + const keptTurns = retainProjectionTurnsAfterRevert( + existingTurns, + event.payload.turnCount, ); yield* projectionTurnRepository.deleteByThreadId({ threadId: event.payload.threadId, diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts index fadd507802..a0d77329b4 100644 --- a/apps/server/src/orchestration/projector.test.ts +++ b/apps/server/src/orchestration/projector.test.ts @@ -690,6 +690,7 @@ describe("orchestration projector", () => { [ { role: "user", text: "First edit" }, { role: "assistant", text: "Updated README to v2.\n" }, + { role: "user", text: "Second edit" }, ], ); expect( @@ -699,7 +700,7 @@ describe("orchestration projector", () => { expect(thread?.latestTurn?.turnId).toBe("turn-1"); }); - it("does not fallback-retain messages tied to removed turn IDs", async () => { + it("retains the selected user prompt even when it is tied to the reverted turn", async () => { const createdAt = "2026-02-26T12:00:00.000Z"; const model = createEmptyReadModel(createdAt); @@ -849,7 +850,10 @@ describe("orchestration projector", () => { role: message.role, turnId: message.turnId, })), - ).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]); + ).toEqual([ + { id: "assistant-keep", role: "assistant", turnId: "turn-1" }, + { id: "user-remove", role: "user", turnId: "turn-2" }, + ]); }); it("caps message and checkpoint retention for long-lived threads", async () => { diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index fc6ab8f6fc..7736f64af4 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -99,15 +99,12 @@ function retainThreadMessagesAfterRevert( const retainedUserCount = messages.filter( (message) => message.role === "user" && retainedMessageIds.has(message.id), ).length; - const missingUserCount = Math.max(0, turnCount - retainedUserCount); + // Reverting "to" a user message keeps that selected prompt visible. The + // payload count represents completed turns before it, so retain one extra user message. + const missingUserCount = Math.max(0, turnCount + 1 - retainedUserCount); if (missingUserCount > 0) { const fallbackUserMessages = messages - .filter( - (message) => - message.role === "user" && - !retainedMessageIds.has(message.id) && - (message.turnId === null || retainedTurnIds.has(message.turnId)), - ) + .filter((message) => message.role === "user" && !retainedMessageIds.has(message.id)) .toSorted( (left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), @@ -128,7 +125,9 @@ function retainThreadMessagesAfterRevert( (message) => message.role === "assistant" && !retainedMessageIds.has(message.id) && - (message.turnId === null || retainedTurnIds.has(message.turnId)), + (retainedTurnIds.size === 0 || + message.turnId === null || + retainedTurnIds.has(message.turnId)), ) .toSorted( (left, right) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 55aa8f3883..652f4aeff7 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -747,19 +747,36 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( return false; } - yield* execute({ - operation, - cwd: input.cwd, - args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], - }); - yield* execute({ - operation, - cwd: input.cwd, - args: ["clean", "-fd", "--", "."], - }); - const headExists = yield* hasHeadCommit(input.cwd); + if (!headExists) { + // In an unborn repository every restored path is still untracked from + // Git's perspective. Clean first so we remove post-checkpoint files + // without immediately deleting the files restored from the snapshot. + yield* execute({ + operation, + cwd: input.cwd, + args: ["clean", "-fd", "--", "."], + }); + } + yield* execute({ + operation, + cwd: input.cwd, + args: [ + "restore", + "--source", + commitOid, + "--worktree", + ...(headExists ? ["--staged"] : []), + "--", + ".", + ], + }); if (headExists) { + yield* execute({ + operation, + cwd: input.cwd, + args: ["clean", "-fd", "--", "."], + }); yield* execute({ operation, cwd: input.cwd, diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index bc7487cee2..560a458372 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,4 +1,5 @@ import { + CheckpointRef, EnvironmentId, MessageId, ProjectId, @@ -16,6 +17,7 @@ import { buildThreadTurnInterruptInput, createLocalDispatchSnapshot, deriveComposerSendState, + deriveRevertTurnCountByUserMessageId, getStartedThreadModelChangeBlockReason, hasServerAcknowledgedLocalDispatch, reconcileMountedTerminalThreadIds, @@ -24,6 +26,74 @@ import { shouldWriteThreadErrorToCurrentServerThread, } from "./ChatView.logic"; +function timelineMessage( + id: string, + role: "user" | "assistant", + turnId: TurnId | null, + createdAt: string, +) { + return { + id: `entry-${id}`, + kind: "message" as const, + createdAt, + message: { + id: MessageId.make(id), + role, + text: id, + turnId, + createdAt, + updatedAt: createdAt, + streaming: false, + }, + }; +} + +describe("deriveRevertTurnCountByUserMessageId", () => { + const user = timelineMessage("user-1", "user", null, "2026-03-29T00:00:00.000Z"); + const assistant = timelineMessage( + "assistant-1", + "assistant", + TurnId.make("turn-1"), + "2026-03-29T00:00:01.000Z", + ); + + it("falls back to the stable turn id when the assistant message id is absent", () => { + const result = deriveRevertTurnCountByUserMessageId({ + timelineEntries: [user, assistant], + checkpoints: [ + { + turnId: TurnId.make("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-1/turn/1"), + status: "ready", + files: [], + assistantMessageId: null, + completedAt: assistant.createdAt, + }, + ], + }); + + expect(result.get(user.message.id)).toBe(0); + }); + + it("uses conversation order for completed legacy turns without checkpoints", () => { + const secondUser = timelineMessage("user-2", "user", null, "2026-03-29T00:00:02.000Z"); + const secondAssistant = timelineMessage( + "assistant-2", + "assistant", + TurnId.make("turn-2"), + "2026-03-29T00:00:03.000Z", + ); + const result = deriveRevertTurnCountByUserMessageId({ + timelineEntries: [user, assistant, secondUser, secondAssistant], + checkpoints: [], + }); + + expect(result.get(user.message.id)).toBe(0); + expect(result.get(secondUser.message.id)).toBe(1); + }); +}); + const environmentId = EnvironmentId.make("environment-local"); const projectId = ProjectId.make("project-1"); const threadId = ThreadId.make("thread-1"); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 325f9afa90..72f6731f5e 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -9,7 +9,8 @@ import { type ThreadId, type TurnId, } from "@t3tools/contracts"; -import { type ChatMessage, type SessionPhase, type Thread } from "../types"; +import { type ChatMessage, type SessionPhase, type Thread, type TurnDiffSummary } from "../types"; +import type { TimelineEntry } from "../session-logic"; import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; import * as Schema from "effect/Schema"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -27,6 +28,63 @@ export const MAX_HIDDEN_MOUNTED_PREVIEW_THREADS = 3; export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String); +export function deriveRevertTurnCountByUserMessageId(input: { + timelineEntries: ReadonlyArray; + checkpoints: ReadonlyArray; +}): Map { + const result = new Map(); + const checkpointByAssistantMessageId = new Map( + input.checkpoints.flatMap((checkpoint) => + checkpoint.assistantMessageId === null + ? [] + : ([[checkpoint.assistantMessageId, checkpoint]] as const), + ), + ); + const checkpointByTurnId = new Map( + input.checkpoints.map((checkpoint) => [checkpoint.turnId, checkpoint] as const), + ); + const useConversationOrderFallback = input.checkpoints.length === 0; + let userTurnIndex = 0; + + for (let index = 0; index < input.timelineEntries.length; index += 1) { + const entry = input.timelineEntries[index]; + if (!entry || entry.kind !== "message" || entry.message.role !== "user") { + continue; + } + + for (let nextIndex = index + 1; nextIndex < input.timelineEntries.length; nextIndex += 1) { + const nextEntry = input.timelineEntries[nextIndex]; + if (!nextEntry || nextEntry.kind !== "message") { + continue; + } + if (nextEntry.message.role === "user") { + break; + } + if (nextEntry.message.role !== "assistant") { + continue; + } + + const checkpoint = + checkpointByAssistantMessageId.get(nextEntry.message.id) ?? + (nextEntry.message.turnId === null + ? undefined + : checkpointByTurnId.get(nextEntry.message.turnId)); + if (checkpoint) { + result.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1)); + break; + } + if (useConversationOrderFallback && !nextEntry.message.streaming) { + result.set(entry.message.id, userTurnIndex); + break; + } + } + + userTurnIndex += 1; + } + + return result; +} + export function buildLocalDraftThread( threadId: ThreadId, draftThread: DraftThreadState, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c296c71706..e573090a2d 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -231,6 +231,7 @@ import { collectUserMessageBlobPreviewUrls, createLocalDispatchSnapshot, deriveComposerSendState, + deriveRevertTurnCountByUserMessageId, hasServerAcknowledgedLocalDispatch, getStartedThreadModelChangeBlockReason, LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, @@ -2208,8 +2209,7 @@ function ChatViewContent(props: ChatViewProps) { attachDraftHeroComposerAnchorRef, captureDraftHeroComposerRect, ] = useDraftHeroLayoutTransition(isDraftHeroState); - const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = - useTurnDiffSummaries(activeThread); + const { turnDiffSummaries } = useTurnDiffSummaries(activeThread); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); for (const summary of turnDiffSummaries) { @@ -2219,37 +2219,11 @@ function ChatViewContent(props: ChatViewProps) { return byMessageId; }, [turnDiffSummaries]); const revertTurnCountByUserMessageId = useMemo(() => { - const byUserMessageId = new Map(); - for (let index = 0; index < timelineEntries.length; index += 1) { - const entry = timelineEntries[index]; - if (!entry || entry.kind !== "message" || entry.message.role !== "user") { - continue; - } - - for (let nextIndex = index + 1; nextIndex < timelineEntries.length; nextIndex += 1) { - const nextEntry = timelineEntries[nextIndex]; - if (!nextEntry || nextEntry.kind !== "message") { - continue; - } - if (nextEntry.message.role === "user") { - break; - } - const summary = turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id); - if (!summary) { - continue; - } - const turnCount = - summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId]; - if (typeof turnCount !== "number") { - break; - } - byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1)); - break; - } - } - - return byUserMessageId; - }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); + return deriveRevertTurnCountByUserMessageId({ + timelineEntries, + checkpoints: turnDiffSummaries, + }); + }, [timelineEntries, turnDiffSummaries]); const gitCwd = activeProject ? projectScriptCwd({ @@ -3972,18 +3946,21 @@ function ChatViewContent(props: ChatViewProps) { if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { setThreadError( activeThread.id, - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting this conversation.`, ); return; } if (phase === "running" || isSendBusy || isConnecting) { - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); + setThreadError( + activeThread.id, + "Interrupt the current turn before reverting this conversation.", + ); return; } const confirmed = await localApi.dialogs.confirm( [ - `Revert this thread to checkpoint ${turnCount}?`, - "This will discard newer messages and turn diffs in this thread.", + "Revert this conversation to this message?", + "This will discard newer messages and restore workspace files when a snapshot is available.", "This action cannot be undone.", ].join("\n"), ); diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index b340a248fb..7f2bc52bcd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -271,6 +271,21 @@ describe("MessagesTimeline", () => { expect(markup).toContain("1 changed file"); }); + it("renders a disabled revert action while a user turn has no checkpoint yet", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('aria-label="Revert to this message"'); + expect(markup).toContain("disabled"); + }); + it("uses LegendList isNearEnd when deciding whether the live edge is visible", async () => { const { resolveTimelineIsAtEnd, diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index f759aa150b..87dee9f3a9 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -328,6 +328,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ const [timelineViewportElement, setTimelineViewportElement] = useState( null, ); + const timelineViewportWidthRef = useRef(null); + const [timelineLayoutGeneration, setTimelineLayoutGeneration] = useState(0); const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false); const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0); const handleAnchorReady = useCallback( @@ -395,25 +397,62 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return; } - const measure = () => { - const viewportWidth = timelineViewportElement.getBoundingClientRect().width; + let layoutRefreshTimeout: number | undefined; + + const measure = (forceLayoutRefresh = false) => { + const viewportWidth = Math.round(timelineViewportElement.getBoundingClientRect().width); const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(viewportWidth); setMinimapHasPersistentGutter((current) => current === nextHasPersistentGutter ? current : nextHasPersistentGutter, ); setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth)); + + if (viewportWidth <= 0) { + return; + } + if (timelineViewportWidthRef.current === null) { + timelineViewportWidthRef.current = + viewportWidth > 0 ? viewportWidth : timelineViewportWidthRef.current; + return; + } + if (!forceLayoutRefresh && viewportWidth === timelineViewportWidthRef.current) { + return; + } + + timelineViewportWidthRef.current = viewportWidth; + if (layoutRefreshTimeout !== undefined) { + window.clearTimeout(layoutRefreshTimeout); + } + layoutRefreshTimeout = window.setTimeout(() => { + // LegendList caches both row measurements and recycled container widths. A desktop + // window resize can briefly make the chat only a few pixels wide. Clearing sizes alone + // leaves some recycled rows one-character-wide, so remount the list after resize settles. + flushSync(() => { + setTimelineLayoutGeneration((generation) => generation + 1); + }); + }, 120); }; + const handleViewportResize = () => measure(true); - const frame = requestAnimationFrame(measure); + const frame = requestAnimationFrame(() => measure()); - const observer = new ResizeObserver(measure); + const observer = new ResizeObserver(() => measure()); observer.observe(timelineViewportElement); + window.addEventListener("resize", handleViewportResize); + window.visualViewport?.addEventListener("resize", handleViewportResize); + const pollId = window.setInterval(() => measure(), 250); return () => { cancelAnimationFrame(frame); + if (layoutRefreshTimeout !== undefined) { + window.clearTimeout(layoutRefreshTimeout); + } observer.disconnect(); + window.removeEventListener("resize", handleViewportResize); + window.visualViewport?.removeEventListener("resize", handleViewportResize); + window.clearInterval(pollId); }; - }, [timelineViewportElement, rows.length]); + }, [timelineViewportElement]); const sharedState = useMemo( () => ({ @@ -482,8 +521,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return ( -
+
+ key={timelineLayoutGeneration} ref={listRef} data={rows} keyExtractor={keyExtractor} @@ -955,7 +999,7 @@ function UserTimelineRow({ row }: { row: Extract
- {canRevertAgentWork && } + {displayedUserMessage.copyText && ( )} @@ -966,27 +1010,37 @@ function UserTimelineRow({ row }: { row: Extract - ctx.onRevertUserMessage(messageId)} - aria-label="Revert to this message" - /> - } - > - + }> + - Revert to this message + {tooltip} ); } diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts index 94eb1c6537..65332cceb0 100644 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ b/packages/client-runtime/src/state/threadReducer.test.ts @@ -599,6 +599,157 @@ describe("applyThreadDetailEvent", () => { }); describe("thread.reverted", () => { + it("retains earlier turns and the selected legacy user prompt", () => { + const legacyThread: OrchestrationThread = { + ...baseThread, + messages: [ + { + id: MessageId.make("legacy-user-1"), + role: "user", + text: "First", + turnId: null, + streaming: false, + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + { + id: MessageId.make("legacy-assistant-1"), + role: "assistant", + text: "Response 1", + turnId: TurnId.make("legacy-turn-1"), + streaming: false, + createdAt: "2026-04-01T02:00:00.000Z", + updatedAt: "2026-04-01T02:00:00.000Z", + }, + { + id: MessageId.make("legacy-user-2"), + role: "user", + text: "Second", + turnId: null, + streaming: false, + createdAt: "2026-04-01T03:00:00.000Z", + updatedAt: "2026-04-01T03:00:00.000Z", + }, + { + id: MessageId.make("legacy-assistant-2"), + role: "assistant", + text: "Response 2", + turnId: TurnId.make("legacy-turn-2"), + streaming: false, + createdAt: "2026-04-01T04:00:00.000Z", + updatedAt: "2026-04-01T04:00:00.000Z", + }, + ], + checkpoints: [], + }; + + const result = applyThreadDetailEvent(legacyThread, { + ...baseEventFields, + sequence: 14, + occurredAt: "2026-04-01T05:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.reverted", + payload: { + threadId: ThreadId.make("thread-1"), + turnCount: 1, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.messages.map((message) => message.id)).toEqual([ + MessageId.make("legacy-user-1"), + MessageId.make("legacy-assistant-1"), + MessageId.make("legacy-user-2"), + ]); + } + }); + + it("removes every message after the selected user prompt when checkpoints exist", () => { + const threadWithData: OrchestrationThread = { + ...baseThread, + messages: [ + { + id: MessageId.make("user-hello"), + role: "user", + text: "hello", + turnId: null, + streaming: false, + createdAt: "2026-04-01T01:00:00.000Z", + updatedAt: "2026-04-01T01:00:00.000Z", + }, + { + id: MessageId.make("assistant-hello"), + role: "assistant", + text: "Hello!", + turnId: TurnId.make("turn-1"), + streaming: false, + createdAt: "2026-04-01T02:00:00.000Z", + updatedAt: "2026-04-01T02:00:00.000Z", + }, + { + id: MessageId.make("user-create-file"), + role: "user", + text: "create a file", + turnId: null, + streaming: false, + createdAt: "2026-04-01T03:00:00.000Z", + updatedAt: "2026-04-01T03:00:00.000Z", + }, + { + id: MessageId.make("assistant-create-file"), + role: "assistant", + text: "Created it.", + turnId: TurnId.make("turn-2"), + streaming: false, + createdAt: "2026-04-01T04:00:00.000Z", + updatedAt: "2026-04-01T04:00:00.000Z", + }, + ], + checkpoints: [ + { + turnId: TurnId.make("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.make("ref-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("assistant-hello"), + completedAt: "2026-04-01T02:00:00.000Z", + }, + { + turnId: TurnId.make("turn-2"), + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.make("ref-2"), + status: "ready", + files: [], + assistantMessageId: MessageId.make("assistant-create-file"), + completedAt: "2026-04-01T04:00:00.000Z", + }, + ], + }; + + const result = applyThreadDetailEvent(threadWithData, { + ...baseEventFields, + sequence: 14, + occurredAt: "2026-04-01T05:00:00.000Z", + aggregateKind: "thread", + aggregateId: ThreadId.make("thread-1"), + type: "thread.reverted", + payload: { + threadId: ThreadId.make("thread-1"), + turnCount: 0, + }, + }); + + expect(result.kind).toBe("updated"); + if (result.kind === "updated") { + expect(result.thread.messages.map((message) => message.id)).toEqual([ + MessageId.make("user-hello"), + ]); + } + }); + it("filters entities to retained turns", () => { const threadWithData: OrchestrationThread = { ...baseThread, diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts index 670540fee7..cb009c2717 100644 --- a/packages/client-runtime/src/state/threadReducer.ts +++ b/packages/client-runtime/src/state/threadReducer.ts @@ -418,7 +418,11 @@ export function applyThreadDetailEvent( ); const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId)); - const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds); + const messages = retainMessagesAfterRevert( + thread.messages, + retainedTurnIds, + event.payload.turnCount, + ); const proposedPlans = pipe( thread.proposedPlans, Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)), @@ -532,16 +536,62 @@ function rebindCheckpointAssistantMessage( function retainMessagesAfterRevert( messages: ReadonlyArray, retainedTurnIds: ReadonlySet, + turnCount: number, ): OrchestrationMessage[] { - // Keep messages that belong to a retained turn, plus system messages and - // messages without a turn binding (pre-turn-0 user messages). - return Arr.filter(messages, (message) => { + const retainedMessageIds = new Set(); + for (const message of messages) { if (message.role === "system") { - return true; + retainedMessageIds.add(message.id); + continue; } - if (message.turnId === null) { - return true; + if (message.turnId !== null && retainedTurnIds.has(message.turnId)) { + retainedMessageIds.add(message.id); } - return retainedTurnIds.has(message.turnId); - }); + } + + // The revert target is the next user prompt after the retained completed turns. + // Keep that selected prompt visible, but discard its response and every later message. + const targetUserCount = turnCount + 1; + const retainedUserCount = messages.filter( + (message) => message.role === "user" && retainedMessageIds.has(message.id), + ).length; + const missingUserCount = Math.max(0, targetUserCount - retainedUserCount); + if (missingUserCount > 0) { + const fallbackUserMessages = messages + .filter((message) => message.role === "user" && !retainedMessageIds.has(message.id)) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingUserCount); + for (const message of fallbackUserMessages) { + retainedMessageIds.add(message.id); + } + } + + const retainedAssistantCount = messages.filter( + (message) => message.role === "assistant" && retainedMessageIds.has(message.id), + ).length; + const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount); + if (missingAssistantCount > 0) { + const fallbackAssistantMessages = messages + .filter( + (message) => + message.role === "assistant" && + !retainedMessageIds.has(message.id) && + (retainedTurnIds.size === 0 || + message.turnId === null || + retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingAssistantCount); + for (const message of fallbackAssistantMessages) { + retainedMessageIds.add(message.id); + } + } + + return Arr.filter(messages, (message) => retainedMessageIds.has(message.id)); }