Merge turns: turn cursor, turn diffs, whole-file context, rewind, live command output

# Conflicts:
#	README.md
#	src/ui/App.tsx
#	src/ui/ThreadView.tsx
This commit is contained in:
Callum Alpass committed 2026-11-02 20:45:09 +11:00
commit 4fe103b657
16 files changed
+633 -40

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
import { expect, test } from "bun:test";
import { parsePatch } from "diff";
import { splitPatch, wholeFilePatch } from "../src/model/diffs.ts";
const changed = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -2 +2 @@\n-old\n+new\n";
test("diff files retain old paths and change types for contents requests", () => {
const files = splitPatch(changed + "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n" + "diff --git a/gone.ts b/gone.ts\ndeleted file mode 100644\n--- a/gone.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n" + "diff --git a/add.ts b/add.ts\nnew file mode 100644\n--- /dev/null\n+++ b/add.ts\n@@ -0,0 +1 @@\n+added\n");
expect(files.map(({ path, oldPath, changeType }) => ({ path, oldPath, changeType }))).toEqual([
{ path: "a.ts", oldPath: "a.ts", changeType: "change" }, { path: "new.ts", oldPath: "old.ts", changeType: "rename-pure" },
{ path: "gone.ts", oldPath: "gone.ts", changeType: "deleted" }, { path: "add.ts", oldPath: "add.ts", changeType: "new" },
]);
});
test("whole-file expansion preserves unchanged context on both sides of the hunk", () => {
const patch = wholeFilePatch(splitPatch(changed)[0]!, { oldContents: "before\nold\nafter\n", newContents: "before\nnew\nafter\n" });
expect(parsePatch(patch)[0]?.hunks[0]).toMatchObject({ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [" before", "-old", "+new", " after"] });
});
test("truncated patches keep their file identity without parsing an incomplete hunk", () => {
expect(splitPatch(changed.slice(0, -4))[0]?.path).toBe("a.ts");
expect(splitPatch("diff --git a/a.ts b/a.ts\n--- a/a.ts\n")[0]?.path).toBe("a.ts");
});
test("whole-file expansion can show a pure rename with identical contents", () => {
const file = splitPatch("diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n")[0]!;
const patch = wholeFilePatch(file, { oldContents: "unchanged\n", newContents: "unchanged\n" });
expect(parsePatch(patch)[0]?.hunks[0]?.lines).toEqual([" unchanged"]);
});
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, test } from "bun:test";
import { CheckpointId, CheckpointRef, CheckpointScopeId, MessageId, NodeId, ProviderSessionId, ProviderThreadId, ProviderTurnId, RunAttemptId, RunId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import type { TimelineEntriesProjection } from "../vendor/t3code/apps/web/src/session-logic.ts";
import { v2Now, v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
import { adjacentTurn, diffTurn, findRevertCheckpoint, turnTargets } from "../src/model/turns.ts";
const providerThreadId = ProviderThreadId.make("pt");
const scopeId = CheckpointScopeId.make("scope");
function checkpoint(ordinal: number, runOrdinal: number | null = ordinal) {
return { id: CheckpointId.make(`cp-${ordinal}`), threadId: v2Projection.thread.id, scopeId, runId: runOrdinal === null ? null : RunId.make(`run-${runOrdinal}`), nodeId: NodeId.make("node"), parentCheckpointId: null, ordinalWithinScope: ordinal, appRunOrdinal: runOrdinal, ref: CheckpointRef.make(`refs/checkpoints/${ordinal}`), status: "ready" as const,
files: ordinal === 2 ? [] : [{ path: "file.ts", kind: "modified", additions: 1, deletions: 0 }], capturedAt: v2Now };
}
function entries(): TimelineEntriesProjection["entries"] {
return [1, 2, 5].flatMap((ordinal) => [{ kind: "message" as const, id: `user-${ordinal}`, createdAt: "2026-06-20T00:00:00.000Z", message: { id: MessageId.make(`user-${ordinal}`), role: "user" as const, text: `prompt ${ordinal}`, runId: RunId.make(`run-${ordinal}`), streaming: false, inputIntent: "turn_start" as const, createdAt: "2026-06-20T00:00:00.000Z", updatedAt: "2026-06-20T00:00:00.000Z" } }]);
}
function projection(): OrchestrationV2ThreadProjection {
const runs = [1, 2, 5].map((ordinal) => ({ id: RunId.make(`run-${ordinal}`), ordinal, activeAttemptId: RunAttemptId.make(`attempt-${ordinal}`), status: "completed" }));
return { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, checkpoints: [checkpoint(0, null), checkpoint(1), checkpoint(2), checkpoint(3, 5)],
runs, attempts: [], providerThreads: [{ id: providerThreadId, providerSessionId: ProviderSessionId.make("session"), providerInstanceId: v2Projection.thread.modelSelection.instanceId }],
providerTurns: runs.map((run) => ({ id: ProviderTurnId.make(`pt-${run.ordinal}`), runAttemptId: run.activeAttemptId, ordinal: run.ordinal, providerThreadId })),
} as unknown as OrchestrationV2ThreadProjection;
}
describe("turn cursor and checkpoint targets", () => {
test("navigates by message identity after earlier turns load", () => {
const turns = turnTargets(projection(), entries(), null, true);
expect(adjacentTurn(turns, null, -1)?.messageId).toBe(MessageId.make("user-5"));
expect(adjacentTurn(turns, "user-5", -1)?.messageId).toBe(MessageId.make("user-2"));
expect(adjacentTurn(turns, "user-1", -1)?.messageId).toBe(MessageId.make("user-1"));
expect(adjacentTurn(turns, "user-5", 1)?.messageId).toBe(MessageId.make("user-5"));
expect(adjacentTurn([], null, -1)).toBeUndefined();
});
test("rewinds before the prompt, using visible predecessors across ordinal gaps", () => {
const turns = turnTargets(projection(), entries(), null, true);
expect(turns.map((turn) => turn.revertTurnCount)).toEqual([0, 1, 2]);
expect(findRevertCheckpoint(projection().checkpoints, turns[2]!.revertTurnCount!)?.id).toBe(CheckpointId.make("cp-2"));
});
test("does not mistake the first message in paged history for the thread start", () => {
const turns = turnTargets(projection(), entries().slice(1), null, false);
expect(turns.map((turn) => turn.revertTurnCount)).toEqual([undefined, 2]);
});
test("does not offer a running turn or a detached provider conversation for rollback", () => {
expect(turnTargets(projection(), entries(), RunId.make("run-5"), true)[2]?.revertTurnCount).toBeUndefined();
expect(turnTargets({ ...projection(), providerThreads: [] }, entries(), null, true).every((turn) => turn.revertTurnCount === undefined)).toBe(true);
});
test("defaults to the latest changed turn; a selection never falls back to another turn", () => {
const turns = turnTargets(projection(), entries(), null, true);
expect(diffTurn(turns, null)?.checkpointTurnCount).toBe(5);
expect(diffTurn(turns.slice(0, 2), null)?.checkpointTurnCount).toBe(1);
expect(diffTurn(turns, "user-2")?.checkpointTurnCount).toBe(2);
expect(diffTurn(turns, "missing")).toBeUndefined();
});
test("keeps only one anchor for a turn with steering messages", () => {
const all = entries();
const first = all[0]!;
expect(turnTargets(projection(), [first, first, ...all.slice(1)], null, true)).toHaveLength(3);
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, test } from "bun:test";
import { CheckpointId, CheckpointScopeId, OrchestrationGetFullThreadDiffInput, OrchestrationGetTurnDiffInput, OrchestrationV2Command, ProviderThreadId, ReviewDiffFileContentsInput, RunId, ThreadId, TurnItemId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { T3Session, type ThreadState } from "../src/client/session.ts";
import { v2Projection } from "../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
const threadId = ThreadId.make("thread-1");
const checkpoint = { id: CheckpointId.make("checkpoint-before-selected-prompt"), scopeId: CheckpointScopeId.make("root-scope") };
describe("turn RPCs without a server", () => {
test("both rollback choices dispatch the captured checkpoint and validate against the contract", async () => {
const session = new T3Session();
const sent: unknown[] = [];
Object.assign(session, { dispatch: async (command: unknown) => { sent.push(command); } });
await session.rollback(threadId, checkpoint, false);
await session.rollback(threadId, checkpoint, true);
expect(sent.every(Schema.is(OrchestrationV2Command))).toBe(true);
expect(sent[0]).toMatchObject({ type: "checkpoint.rollback", threadId, checkpointId: checkpoint.id, scopeId: checkpoint.scopeId, restoreFiles: false });
expect(sent[1]).toMatchObject({ restoreFiles: true });
expect(sent[0]).not.toHaveProperty("turnCount");
});
test("checkpoint ranges and file-contents requests match the RPC schemas", async () => {
const session = new T3Session();
const sent: { method: string; input: unknown }[] = [];
const rpc = Object.fromEntries(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"].map((method) => [method, (input: unknown) => { sent.push({ method, input }); return Effect.succeed({ diff: "", oldContents: "old", newContents: "new" }); }]));
Object.assign(session, { connection: { rpc } });
await session.turnDiff({ threadId, fromTurnCount: 4, toTurnCount: 5, ignoreWhitespace: true });
await session.fullThreadDiff({ threadId, toTurnCount: 5, ignoreWhitespace: false });
await session.diffFileContents({ cwd: "/workspace", sourceKind: "working-tree", baseRef: "HEAD", headRef: null, oldPath: "old.ts", newPath: "new.ts", changeType: "rename-changed" });
expect(Schema.is(OrchestrationGetTurnDiffInput)(sent[0]?.input)).toBe(true);
expect(Schema.is(OrchestrationGetFullThreadDiffInput)(sent[1]?.input)).toBe(true);
expect(Schema.is(ReviewDiffFileContentsInput)(sent[2]?.input)).toBe(true);
expect(sent.map((request) => request.method)).toEqual(["orchestration.getTurnDiff", "orchestration.getFullThreadDiff", "review.getDiffFileContents"]);
});
test("expanded output normalizes frames and unsubscribes immediately", async () => {
const session = new T3Session();
let finishStream!: () => void;
const finished = new Promise<void>((resolve) => { finishStream = resolve; });
let receive!: () => void;
const received = new Promise<void>((resolve) => { receive = resolve; });
const outputs: string[] = [];
const stream = Stream.concat(Stream.make(
{ kind: "replace" as const, text: "first\n", running: true, truncated: false },
{ kind: "append" as const, text: "second", running: true, truncated: false },
), Stream.never).pipe(Stream.ensuring(Effect.sync(finishStream)));
Object.assign(session, { connection: { rpc: { "orchestration.subscribeCommandOutput": (input: unknown) => {
expect(input).toEqual({ threadId, itemId: TurnItemId.make("command-1") });
return stream;
} } }, runInScope: Effect.runFork });
const close = session.watchCommandOutput(threadId, TurnItemId.make("command-1"), (view) => { outputs.push(view.output.text); if (outputs.length === 2) receive(); }, (error) => { throw new Error(error); });
await received;
close();
await finished;
expect(outputs).toEqual(["first\n", "first\nsecond"]);
});
});
function rewindSession() {
const session = new T3Session();
const providerThreadId = ProviderThreadId.make("provider-thread");
const initial = { ...v2Projection, thread: { ...v2Projection.thread, activeProviderThreadId: providerThreadId }, runs: [{ id: RunId.make("run-5"), ordinal: 5, status: "completed" }], providerThreads: [{ id: providerThreadId, lastRunOrdinal: 5 }] } as unknown as OrchestrationV2ThreadProjection;
let observe!: (state: ThreadState) => void;
let command: { commandId: string } | undefined;
let closed = false;
Object.assign(session, { watchThread: (_: unknown, listener: (state: ThreadState) => void) => { observe = listener; return () => { closed = true; }; }, dispatch: async (next: { commandId: string }) => { command = next; } });
const emit = (projection: OrchestrationV2ThreadProjection) => observe({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } });
return { session, initial, emit, command: () => command!, closed: () => closed };
}
test("rewind waits for the rolled-back suffix and the provider conversation, not just command acceptance", async () => {
const rig = rewindSession();
let resolved = false;
const pending = rig.session.rewind(rig.initial, checkpoint, 2, false).then(() => { resolved = true; });
await Promise.resolve();
rig.emit(rig.initial);
await Promise.resolve();
expect(resolved).toBe(false);
const next = { ...rig.initial, runs: rig.initial.runs.map((run) => ({ ...run, status: "rolled_back" as const })) };
rig.emit(next);
await Promise.resolve();
expect(resolved).toBe(false);
rig.emit({ ...next, providerThreads: next.providerThreads.map((thread) => ({ ...thread, lastRunOrdinal: 2 })) });
await pending;
expect(resolved).toBe(true);
expect(rig.closed()).toBe(true);
});
test("rewind reports the matching server failure and closes its listener", async () => {
const rig = rewindSession();
const pending = rig.session.rewind(rig.initial, checkpoint, 2, true);
rig.emit({ ...rig.initial, thread: { ...rig.initial.thread, rollbackFailure: { requestId: rig.command().commandId, message: "cannot restore" } } } as OrchestrationV2ThreadProjection);
await expect(pending).rejects.toThrow("cannot restore");
expect(rig.closed()).toBe(true);
});