Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e29a7705f9 | ||
|
|
4c98219c43 | ||
|
|
f748aa88bd | ||
|
|
ba46a1b9a6 | ||
|
|
a2e4c7198a | ||
|
|
832eb42ad6 | ||
|
|
b1f6e72b0b | ||
|
|
108513f246 | ||
|
|
8e3193c277 | ||
|
|
4768668637 | ||
|
|
46e540f52d | ||
|
|
8307207485 | ||
|
|
d35ca869ec | ||
|
|
72158ca943 | ||
|
|
3a5cd89ef2 | ||
|
|
ed25338f20 | ||
|
|
2d42cdea01 | ||
|
|
e5037981da | ||
|
|
4270716c68 |
No files matched your search
@@ -43,6 +43,36 @@ function createSendTurnHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const sendRequest = vi.spyOn(
|
||||
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
|
||||
"sendRequest",
|
||||
);
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -113,6 +143,40 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
provider: "codex",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toEqual({
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message: "cwd missing",
|
||||
});
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
it("sends text and image user input items to turn/start", async () => {
|
||||
const { manager, context, requireSession, sendRequest, updateSession } =
|
||||
@@ -198,3 +262,91 @@ describe("sendTurn", () => {
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread checkpoint control", () => {
|
||||
it("reads thread turns from thread/read", async () => {
|
||||
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads thread turns from flat thread/read responses", async () => {
|
||||
const { manager, context, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back turns via thread/rollback and resets session running state", async () => {
|
||||
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread("sess_1", 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
numTurns: 2,
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -65,6 +65,16 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexThreadTurnSnapshot {
|
||||
id: string;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface CodexThreadSnapshot {
|
||||
threadId: string;
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -138,40 +148,43 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
const context: CodexSessionContext = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
try {
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: resolvedCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
@@ -241,12 +254,24 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
if (context) {
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "session/startFailed",
|
||||
message,
|
||||
});
|
||||
}
|
||||
throw new Error(message, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -331,6 +356,41 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/read", {
|
||||
threadId,
|
||||
includeTurns: true,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
throw new Error("numTurns must be an integer >= 1.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/rollback", {
|
||||
threadId,
|
||||
numTurns,
|
||||
});
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/rollback", response);
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
@@ -742,6 +802,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
|
||||
const responseRecord = this.readObject(response);
|
||||
const thread = this.readObject(responseRecord, "thread");
|
||||
const threadId = this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
|
||||
if (!threadId) {
|
||||
throw new Error(`${method} response did not include a thread id.`);
|
||||
}
|
||||
|
||||
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
threadId,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -823,6 +908,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readArray(value: unknown, key?: string): unknown[] | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
return Array.isArray(target) ? target : undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runProcess("git", args, {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
function exists(filePath: string): boolean {
|
||||
return fs.existsSync(filePath);
|
||||
}
|
||||
|
||||
async function createRepo(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
await writeFile(path.join(cwd, "README.md"), "v1\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
|
||||
await runGit(cwd, ["add", "."]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function createRepoWithoutHead(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
describe("FilesystemCheckpointStore", () => {
|
||||
it("captures refs without mutating branch history and restores workspace state", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_1";
|
||||
|
||||
try {
|
||||
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
|
||||
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
|
||||
expect(rootCommit.length).toBeGreaterThan(0);
|
||||
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await rm(path.join(cwd, "tracked.txt"));
|
||||
await writeFile(path.join(cwd, "notes.md"), "notes\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
|
||||
|
||||
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
expect(restoredRoot).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
|
||||
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
|
||||
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
expect(restoredTurn1).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
|
||||
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when restoring a missing checkpoint", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId: "thr_2",
|
||||
turnCount: 999,
|
||||
});
|
||||
expect(restored).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_2b";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("prunes refs newer than the retained turn", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_3";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn1\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
|
||||
|
||||
await store.pruneAfterTurn({
|
||||
cwd,
|
||||
threadId,
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a unified patch between checkpoint turns", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_4";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_5";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("detects non-repo folders", async () => {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when repository path does not exist", async () => {
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
|
||||
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
});
|
||||
|
||||
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
|
||||
const cwd = await createRepoWithoutHead();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr-no-head";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "first\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "second\n");
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function checkpointRefThreadSegment(threadId: string): string {
|
||||
return Buffer.from(threadId, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
|
||||
if (!Number.isInteger(turnCount) || turnCount < 0) {
|
||||
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
|
||||
}
|
||||
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
|
||||
}
|
||||
|
||||
interface GitOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
stdin?: string;
|
||||
allowNonZeroExit?: boolean;
|
||||
}
|
||||
|
||||
export class FilesystemCheckpointStore {
|
||||
async isGitRepository(cwd: string): Promise<boolean> {
|
||||
try {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0 && result.stdout.trim() === "true";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async captureCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
|
||||
|
||||
try {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const hasHead = await this.hasHeadCommit(cwd);
|
||||
if (hasHead) {
|
||||
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
|
||||
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (!treeOid) {
|
||||
throw new Error("git write-tree returned an empty tree oid.");
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
|
||||
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
|
||||
env: commitEnv,
|
||||
stdin: `${message}\n`,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (!commitOid) {
|
||||
throw new Error("git commit-tree returned an empty commit oid.");
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", ref, commitOid]);
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async hasCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commit = await this.resolveCheckpointCommit(cwd, ref);
|
||||
return commit !== null;
|
||||
}
|
||||
|
||||
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
|
||||
const { cwd, threadId } = input;
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
|
||||
if (existing) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (!headCommit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
|
||||
return true;
|
||||
}
|
||||
|
||||
async restoreCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
||||
if (!commitOid && turnCount === 0) {
|
||||
commitOid = await this.resolveHeadCommit(cwd);
|
||||
}
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
||||
if (await this.hasHeadCommit(cwd)) {
|
||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async diffCheckpoints(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}): Promise<string> {
|
||||
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
|
||||
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
|
||||
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
|
||||
}
|
||||
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
|
||||
throw new Error(`Invalid to turn count: ${toTurnCount}`);
|
||||
}
|
||||
if (fromTurnCount > toTurnCount) {
|
||||
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
|
||||
}
|
||||
|
||||
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
|
||||
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
|
||||
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
|
||||
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
|
||||
if (!fromCommitOid && fromTurnCount === 0) {
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (headCommit) {
|
||||
fromCommitOid = headCommit;
|
||||
}
|
||||
}
|
||||
if (!fromCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
if (!toCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await this.runGit(cwd, [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
]);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
private async resolveHeadCommit(cwd: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
async pruneAfterTurn(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, maxTurnCount } = input;
|
||||
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
|
||||
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
|
||||
}
|
||||
|
||||
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
|
||||
const result = await this.runGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname)", threadRefPrefix],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refsToDelete = result.stdout
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.filter((refName) => {
|
||||
const turn = this.readRefTurnCount(refName);
|
||||
return turn !== null && turn > maxTurnCount;
|
||||
});
|
||||
|
||||
const batchSize = 32;
|
||||
const batches = Array.from(
|
||||
{ length: Math.ceil(refsToDelete.length / batchSize) },
|
||||
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
|
||||
);
|
||||
await batches.reduce<Promise<void>>((pending, batch) => {
|
||||
return pending.then(async () => {
|
||||
await Promise.all(
|
||||
batch.map((refName) =>
|
||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
||||
),
|
||||
);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
}
|
||||
|
||||
private async hasHeadCommit(cwd: string): Promise<boolean> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0;
|
||||
}
|
||||
|
||||
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
private readRefTurnCount(ref: string): number | null {
|
||||
const segments = ref.split("/");
|
||||
const rawTurn = segments.at(-1);
|
||||
if (!rawTurn) {
|
||||
return null;
|
||||
}
|
||||
const turn = Number.parseInt(rawTurn, 10);
|
||||
return Number.isInteger(turn) && turn >= 0 ? turn : null;
|
||||
}
|
||||
|
||||
private async runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: GitOptions = {},
|
||||
): Promise<Awaited<ReturnType<typeof runProcess>>> {
|
||||
let result: Awaited<ReturnType<typeof runProcess>>;
|
||||
try {
|
||||
result = await runProcess("git", args, {
|
||||
cwd,
|
||||
env: options.env,
|
||||
stdin: options.stdin,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new Error(`${quoteGitCommand(args)} timed out.`);
|
||||
}
|
||||
|
||||
if (result.stdoutTruncated || result.stderrTruncated) {
|
||||
throw new Error(
|
||||
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
throw new Error(
|
||||
stderr.length > 0
|
||||
? `${quoteGitCommand(args)} failed: ${stderr}`
|
||||
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
@@ -59,4 +59,745 @@ describe("ProviderManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects checkpoint operations for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.listCheckpoints({
|
||||
sessionId: "missing-session",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
await expect(
|
||||
manager.getCheckpointDiff({
|
||||
sessionId: "missing-session",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("derives checkpoints from thread turns", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const codex = (
|
||||
manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).codex;
|
||||
|
||||
codex.hasSession = () => true;
|
||||
codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [
|
||||
{
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: "Refactor the logger" }],
|
||||
},
|
||||
{
|
||||
type: "agentMessage",
|
||||
text: "I refactored it.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.listCheckpoints({
|
||||
sessionId: "sess_1",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thr_1",
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: false,
|
||||
},
|
||||
{
|
||||
id: "turn_1",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
label: "Turn 1",
|
||||
preview: "Refactor the logger",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rolls back from a selected checkpoint turn count", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
{ id: "turn_3", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async (sessionId, numTurns) => {
|
||||
rollbackCalls.push({ sessionId, numTurns });
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
const hasCheckpoint = vi.fn(async () => true);
|
||||
const restoreCheckpoint = vi.fn(async () => true);
|
||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
|
||||
expect(result.threadId).toBe("thr_1");
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(result.messageCount).toBe(0);
|
||||
expect(result.rolledBackTurns).toBe(2);
|
||||
expect(result.checkpoints).toHaveLength(2);
|
||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("returns diff text for a checkpoint range", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
diff: "diff --git a/a.ts b/a.ts",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
cwd: "/repo",
|
||||
},
|
||||
];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
const isGitRepository = vi.fn(async () => true);
|
||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
|
||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/repo");
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 2,
|
||||
});
|
||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/repo");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("falls back to process cwd for lazy checkpoint init when session cwd is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
||||
captureCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<void>;
|
||||
diffCheckpoints: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}) => Promise<string>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
||||
try {
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
});
|
||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
||||
const captureCheckpoint = vi.fn(async () => undefined);
|
||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
const result = await manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/fallback-repo");
|
||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
});
|
||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
||||
cwd: "/fallback-repo",
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/fallback-repo");
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not fall back to process cwd when a session cwd exists but is not a git repo", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
||||
try {
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
cwd: "/session-cwd",
|
||||
},
|
||||
];
|
||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
await expect(
|
||||
manager.getCheckpointDiff({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
||||
expect(isGitRepository).toHaveBeenCalledWith("/session-cwd");
|
||||
expect(isGitRepository).not.toHaveBeenCalledWith("/fallback-repo");
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails revert when filesystem checkpoints are unavailable for the session", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
listSessions: () => Array<{
|
||||
sessionId: string;
|
||||
provider: "codex";
|
||||
status: "ready";
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
cwd?: string;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.listSessions = () => [
|
||||
{
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
createdAt: "2026-02-18T00:00:00.000Z",
|
||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
||||
},
|
||||
];
|
||||
internals.filesystemCheckpointStore.isGitRepository = async () => false;
|
||||
internals.sessionCheckpointCwds.delete("sess_1");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
const callOrder: string[] = [];
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => {
|
||||
callOrder.push("rollback");
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
const hasCheckpoint = vi.fn(async () => true);
|
||||
const restoreCheckpoint = vi.fn(async () => {
|
||||
callOrder.push("restore");
|
||||
return true;
|
||||
});
|
||||
const pruneAfterTurn = vi.fn(async () => {
|
||||
callOrder.push("prune");
|
||||
return undefined;
|
||||
});
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
expect(callOrder).toEqual(["restore", "rollback", "prune"]);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("reverts to turn 0 without requiring an explicit turn 0 checkpoint ref", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [],
|
||||
});
|
||||
const hasCheckpoint = vi.fn(async () => false);
|
||||
const restoreCheckpoint = vi.fn(async () => true);
|
||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(result.turnCount).toBe(0);
|
||||
expect(hasCheckpoint).not.toHaveBeenCalled();
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 0,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("fails before rollback when filesystem checkpoint is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (
|
||||
sessionId: string,
|
||||
numTurns: number,
|
||||
) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const rollbackSpy = vi.fn(async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
}));
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = rollbackSpy;
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
|
||||
expect(rollbackSpy).not.toHaveBeenCalled();
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,18 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
type ProviderCheckpoint,
|
||||
type ProviderEvent,
|
||||
type ProviderGetCheckpointDiffInput,
|
||||
type ProviderGetCheckpointDiffResult,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderListCheckpointsInput,
|
||||
type ProviderListCheckpointsResult,
|
||||
type ProviderRevertToCheckpointInput,
|
||||
type ProviderRevertToCheckpointResult,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
@@ -12,23 +20,155 @@ import {
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerGetCheckpointDiffInputSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function trimToPreview(value: string): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
if (normalized.length <= 120) {
|
||||
return normalized;
|
||||
}
|
||||
return `${normalized.slice(0, 117)}...`;
|
||||
}
|
||||
|
||||
function summarizeUserMessageContent(content: unknown[]): string | undefined {
|
||||
const segments: string[] = [];
|
||||
|
||||
for (const part of content) {
|
||||
const record = asObject(part);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "text") {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
segments.push(text.trim());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "image") {
|
||||
segments.push("[Image attachment]");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "localImage") {
|
||||
segments.push("[Local image attachment]");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return trimToPreview(segments.join(" "));
|
||||
}
|
||||
|
||||
function summarizeTurn(turn: CodexThreadTurnSnapshot): {
|
||||
messageCountDelta: number;
|
||||
preview?: string;
|
||||
} {
|
||||
let messageCountDelta = 0;
|
||||
let preview: string | undefined;
|
||||
|
||||
for (const item of turn.items) {
|
||||
const record = asObject(item);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "userMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const content = asArray(record?.content);
|
||||
preview = summarizeUserMessageContent(content);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "agentMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
preview = trimToPreview(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messageCountDelta,
|
||||
...(preview ? { preview } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
|
||||
const checkpoints: ProviderCheckpoint[] = [];
|
||||
let messageCount = 0;
|
||||
const isEmpty = turns.length === 0;
|
||||
checkpoints.push({
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: isEmpty,
|
||||
});
|
||||
|
||||
for (let index = 0; index < turns.length; index += 1) {
|
||||
const turn = turns[index];
|
||||
if (!turn) continue;
|
||||
const turnSummary = summarizeTurn(turn);
|
||||
messageCount += turnSummary.messageCountDelta;
|
||||
checkpoints.push({
|
||||
id: turn.id,
|
||||
turnCount: index + 1,
|
||||
messageCount,
|
||||
label: `Turn ${index + 1}`,
|
||||
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
|
||||
isCurrent: index === turns.length - 1,
|
||||
});
|
||||
}
|
||||
|
||||
return checkpoints;
|
||||
}
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private readonly sessionCheckpointCwds = new Map<string, string>();
|
||||
private readonly filesystemLocks = new Map<string, Promise<void>>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
@@ -37,6 +177,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
@@ -60,6 +201,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
}
|
||||
await this.initializeFilesystemCheckpointing(session, input.cwd).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -95,12 +241,138 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.codex.stopSession(input.sessionId);
|
||||
this.sessionThreadIds.delete(input.sessionId);
|
||||
this.pendingEventsBySession.delete(input.sessionId);
|
||||
this.sessionCheckpointCwds.delete(input.sessionId);
|
||||
this.filesystemLocks.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
|
||||
const input = providerListCheckpointsInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(input.sessionId);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
checkpoints: buildCheckpoints(snapshot.turns),
|
||||
};
|
||||
}
|
||||
|
||||
async getCheckpointDiff(
|
||||
raw: ProviderGetCheckpointDiffInput,
|
||||
): Promise<ProviderGetCheckpointDiffResult> {
|
||||
const input = providerGetCheckpointDiffInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const snapshot = await this.codex.readThread(input.sessionId);
|
||||
if (input.toTurnCount > snapshot.turns.length) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async revertToCheckpoint(
|
||||
raw: ProviderRevertToCheckpointInput,
|
||||
): Promise<ProviderRevertToCheckpointResult> {
|
||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
||||
}
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const beforeSnapshot = await this.codex.readThread(input.sessionId);
|
||||
const currentTurnCount = beforeSnapshot.turns.length;
|
||||
if (input.turnCount > currentTurnCount) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (checkpointCwd && input.turnCount > 0) {
|
||||
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!hasCheckpoint) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!restored) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const requestedRollbackTurns = currentTurnCount - input.turnCount;
|
||||
const afterSnapshot =
|
||||
requestedRollbackTurns > 0
|
||||
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
|
||||
: beforeSnapshot;
|
||||
|
||||
await this.filesystemCheckpointStore.pruneAfterTurn({
|
||||
cwd: checkpointCwd,
|
||||
threadId: afterSnapshot.threadId,
|
||||
maxTurnCount: afterSnapshot.turns.length,
|
||||
});
|
||||
|
||||
const checkpoints = buildCheckpoints(afterSnapshot.turns);
|
||||
const currentCheckpoint =
|
||||
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
|
||||
checkpoints[checkpoints.length - 1] ??
|
||||
checkpoints[0];
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
|
||||
|
||||
return {
|
||||
threadId: afterSnapshot.threadId,
|
||||
turnCount: currentCheckpoint?.turnCount ?? 0,
|
||||
messageCount: currentCheckpoint?.messageCount ?? 0,
|
||||
rolledBackTurns,
|
||||
checkpoints,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
@@ -118,6 +390,149 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.threadLogStreams.clear();
|
||||
this.sessionThreadIds.clear();
|
||||
this.pendingEventsBySession.clear();
|
||||
this.sessionCheckpointCwds.clear();
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
private async initializeFilesystemCheckpointing(
|
||||
session: ProviderSession,
|
||||
preferredCwd?: string,
|
||||
): Promise<void> {
|
||||
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
|
||||
|
||||
await this.withFilesystemLock(session.sessionId, async () => {
|
||||
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
|
||||
if (!supportsGit) {
|
||||
this.sessionCheckpointCwds.delete(session.sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(session.sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
if (this.codex.hasSession(session.sessionId)) {
|
||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async getOrInitializeFilesystemCheckpointCwd(sessionId: string): Promise<string | null> {
|
||||
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (existingCwd) {
|
||||
return existingCwd;
|
||||
}
|
||||
|
||||
const session = this.codex
|
||||
.listSessions()
|
||||
.find((candidate) => candidate.sessionId === sessionId);
|
||||
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
|
||||
|
||||
await this.withFilesystemLock(sessionId, async () => {
|
||||
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
|
||||
if (currentCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cwdSupport = await Promise.all(
|
||||
candidateCwds.map(async (cwd) => ({
|
||||
cwd,
|
||||
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
|
||||
})),
|
||||
);
|
||||
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
|
||||
if (supportedCwd) {
|
||||
const snapshot = await this.codex.readThread(sessionId);
|
||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
});
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: supportedCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
if (this.codex.hasSession(sessionId)) {
|
||||
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.sessionCheckpointCwds.delete(sessionId);
|
||||
});
|
||||
|
||||
return this.sessionCheckpointCwds.get(sessionId) ?? null;
|
||||
}
|
||||
|
||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.withFilesystemLock(event.sessionId, async () => {
|
||||
if (!this.codex.hasSession(event.sessionId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
threadId?: string,
|
||||
): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/filesystemError",
|
||||
message,
|
||||
...(threadId ? { threadId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
||||
const next = previous.catch(() => undefined).then(fn);
|
||||
const completion = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.filesystemLocks.set(sessionId, completion);
|
||||
return next.finally(() => {
|
||||
const tracked = this.filesystemLocks.get(sessionId);
|
||||
if (tracked === completion) {
|
||||
this.filesystemLocks.delete(sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
|
||||
@@ -646,6 +646,38 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const listResponse = await sendRequest(ws, WS_METHODS.providersListCheckpoints, {
|
||||
sessionId: "missing-session",
|
||||
});
|
||||
expect(listResponse.result).toBeUndefined();
|
||||
expect(listResponse.error?.message).toContain("Unknown provider session");
|
||||
|
||||
const revertResponse = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(revertResponse.result).toBeUndefined();
|
||||
expect(revertResponse.error?.message).toContain("Unknown provider session");
|
||||
|
||||
const diffResponse = await sendRequest(ws, WS_METHODS.providersGetCheckpointDiff, {
|
||||
sessionId: "missing-session",
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
expect(diffResponse.result).toBeUndefined();
|
||||
expect(diffResponse.error?.message).toContain("Unknown provider session");
|
||||
});
|
||||
|
||||
it("routes terminal RPC methods and broadcasts terminal events", async () => {
|
||||
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
|
||||
const terminalManager = new MockTerminalManager();
|
||||
|
||||
@@ -310,6 +310,15 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
|
||||
case WS_METHODS.providersListCheckpoints:
|
||||
return providerManager.listCheckpoints(request.params as never);
|
||||
|
||||
case WS_METHODS.providersGetCheckpointDiff:
|
||||
return providerManager.getCheckpointDiff(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRevertToCheckpoint:
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
|
||||
+64
-3
@@ -1,8 +1,7 @@
|
||||
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Activity, Suspense, lazy, useEffect, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { isElectron } from "./env";
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
@@ -10,9 +9,50 @@ import { StoreProvider, useStore } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import { onServerWelcome } from "./wsNativeApi";
|
||||
import { useNativeApi } from "./hooks/useNativeApi";
|
||||
import { useMediaQuery } from "./hooks/useMediaQuery";
|
||||
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
|
||||
import { Sheet, SheetPopup } from "./components/ui/sheet";
|
||||
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
||||
|
||||
const DiffPanel = lazy(() => import("./components/DiffPanel"));
|
||||
const DiffWorkerPoolProvider = lazy(() =>
|
||||
import("./components/DiffPanel").then((module) => ({
|
||||
default: module.DiffWorkerPoolProvider,
|
||||
})),
|
||||
);
|
||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
||||
|
||||
const DiffPanelWrapper = (props: { children: React.ReactNode; sheet: boolean }) => {
|
||||
const { state, dispatch } = useStore();
|
||||
if (props.sheet) {
|
||||
return (
|
||||
<Sheet
|
||||
open={state.diffOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
dispatch({ type: "CLOSE_DIFF" });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SheetPopup
|
||||
side="right"
|
||||
showCloseButton={false}
|
||||
keepMounted
|
||||
className="w-[min(88vw,820px)] max-w-[820px] p-0"
|
||||
>
|
||||
{props.children}
|
||||
</SheetPopup>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
|
||||
{props.children}
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const { dispatch } = useStore();
|
||||
@@ -111,6 +151,7 @@ function AutoProjectBootstrap() {
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
branch: null,
|
||||
@@ -177,6 +218,18 @@ function DesktopProjectBootstrap() {
|
||||
function Layout() {
|
||||
const api = useNativeApi();
|
||||
const { state } = useStore();
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
|
||||
const diffLoadingFallback =
|
||||
!state.diffOpen || shouldUseDiffSheet ? (
|
||||
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</div>
|
||||
) : (
|
||||
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
|
||||
Loading diff viewer...
|
||||
</aside>
|
||||
);
|
||||
|
||||
if (!api) {
|
||||
return (
|
||||
@@ -195,7 +248,15 @@ function Layout() {
|
||||
<DesktopProjectBootstrap />
|
||||
<Sidebar />
|
||||
<ChatView />
|
||||
{state.diffOpen && <DiffPanel />}
|
||||
<Activity mode={state.diffOpen ? "visible" : "hidden"}>
|
||||
<DiffPanelWrapper sheet={shouldUseDiffSheet}>
|
||||
<Suspense fallback={diffLoadingFallback}>
|
||||
<DiffWorkerPoolProvider>
|
||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
||||
</DiffWorkerPoolProvider>
|
||||
</Suspense>
|
||||
</DiffPanelWrapper>
|
||||
</Activity>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,10 +27,11 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useDebouncedValue } from "@tanstack/react-pacer";
|
||||
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
|
||||
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
@@ -49,9 +50,11 @@ import {
|
||||
resolveModelSlug,
|
||||
} from "../model-logic";
|
||||
import {
|
||||
countDiffStat,
|
||||
derivePendingApprovals,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
type TurnDiffSummary,
|
||||
type PendingApproval,
|
||||
deriveWorkLogEntries,
|
||||
formatDuration,
|
||||
@@ -67,6 +70,7 @@ import {
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import {
|
||||
@@ -84,10 +88,12 @@ import {
|
||||
CircleAlertIcon,
|
||||
FileIcon,
|
||||
FolderIcon,
|
||||
DiffIcon,
|
||||
FolderClosedIcon,
|
||||
InfoIcon,
|
||||
LockIcon,
|
||||
LockOpenIcon,
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { Button } from "./ui/button";
|
||||
@@ -107,6 +113,7 @@ import {
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
} from "~/projectScripts";
|
||||
import { Toggle } from "./ui/toggle";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -345,6 +352,7 @@ export default function ChatView() {
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
|
||||
@@ -365,16 +373,19 @@ export default function ChatView() {
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const dragDepthRef = useRef(0);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
const checkpointHydrationSessionRequestRef = useRef(new Set<string>());
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeSessionId = activeThread?.session?.sessionId;
|
||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
||||
const activeThreadRuntimeId =
|
||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
||||
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting;
|
||||
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
@@ -402,6 +413,141 @@ export default function ChatView() {
|
||||
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
|
||||
[activeThread?.messages, workLogEntries],
|
||||
);
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
|
||||
const byMessageId = new Map<string, TurnDiffSummary>();
|
||||
for (const summary of turnDiffSummaries) {
|
||||
if (!summary.assistantMessageId) continue;
|
||||
byMessageId.set(summary.assistantMessageId, summary);
|
||||
}
|
||||
return byMessageId;
|
||||
}, [turnDiffSummaries]);
|
||||
const revertTurnCountByUserMessageId = useMemo(() => {
|
||||
const byUserMessageId = new Map<string, number>();
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || turnDiffSummaries.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const inferredMissingTurnCounts = turnDiffSummaries.reduce<Record<string, number>>(
|
||||
(acc, summary) => {
|
||||
if (typeof summary.checkpointTurnCount === "number") {
|
||||
return acc;
|
||||
}
|
||||
const inferredTurnCount = inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (typeof inferredTurnCount !== "number") {
|
||||
return acc;
|
||||
}
|
||||
acc[summary.turnId] = inferredTurnCount;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
if (Object.keys(inferredMissingTurnCounts).length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
|
||||
threadId: activeThreadId,
|
||||
checkpointTurnCountByTurnId: inferredMissingTurnCounts,
|
||||
});
|
||||
}, [activeThreadId, dispatch, inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
|
||||
|
||||
const checkpointDiffHydrationTargets = useMemo(() => {
|
||||
if (!api || !activeThreadId || !activeSessionId || turnDiffSummaries.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return turnDiffSummaries.flatMap((summary) => {
|
||||
const turnCount = inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (summary.checkpointDiffLoaded || typeof turnCount !== "number") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
turnId: summary.turnId,
|
||||
fromTurnCount: Math.max(0, turnCount - 1),
|
||||
toTurnCount: turnCount,
|
||||
},
|
||||
];
|
||||
});
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeThreadId,
|
||||
api,
|
||||
inferredCheckpointTurnCountByTurnId,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
|
||||
const checkpointDiffHydrationQueries = useQueries({
|
||||
queries: checkpointDiffHydrationTargets.map((target) =>
|
||||
checkpointDiffQueryOptions(api, {
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: target.fromTurnCount,
|
||||
toTurnCount: target.toTurnCount,
|
||||
cacheScope: `turn:${target.turnId}`,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || checkpointDiffHydrationTargets.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointDiffByTurnId: Record<string, string> = {};
|
||||
for (let index = 0; index < checkpointDiffHydrationTargets.length; index += 1) {
|
||||
const target = checkpointDiffHydrationTargets[index];
|
||||
const query = checkpointDiffHydrationQueries[index];
|
||||
const diff = query?.data?.diff;
|
||||
if (!target || !diff) {
|
||||
continue;
|
||||
}
|
||||
checkpointDiffByTurnId[target.turnId] = diff;
|
||||
}
|
||||
if (Object.keys(checkpointDiffByTurnId).length === 0) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: activeThreadId,
|
||||
checkpointDiffByTurnId,
|
||||
});
|
||||
}, [activeThreadId, checkpointDiffHydrationQueries, checkpointDiffHydrationTargets, dispatch]);
|
||||
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
@@ -457,16 +603,9 @@ export default function ChatView() {
|
||||
completionSummary,
|
||||
timelineEntries,
|
||||
]);
|
||||
const runtimeSessionConfig =
|
||||
state.runtimeMode === "full-access"
|
||||
? ({
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
} as const)
|
||||
: ({
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
} as const);
|
||||
const runtimeApprovalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
||||
const runtimeSandboxMode =
|
||||
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
const composerTrigger = useMemo(
|
||||
() => detectComposerTrigger(prompt, composerCursor),
|
||||
@@ -963,6 +1102,10 @@ export default function ChatView() {
|
||||
);
|
||||
}, [composerMenuItems, composerMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
setIsRevertingCheckpoint(false);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || activeThread.terminalOpen) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -1142,14 +1285,17 @@ export default function ChatView() {
|
||||
toggleTerminalVisibility,
|
||||
]);
|
||||
|
||||
const setThreadError = (threadId: string | null, error: string | null) => {
|
||||
if (!threadId) return;
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId,
|
||||
error,
|
||||
});
|
||||
};
|
||||
const setThreadError = useCallback(
|
||||
(threadId: string | null, error: string | null) => {
|
||||
if (!threadId) return;
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId,
|
||||
error,
|
||||
});
|
||||
},
|
||||
[dispatch],
|
||||
);
|
||||
|
||||
const addComposerImages = (files: File[]) => {
|
||||
if (!activeThreadId || files.length === 0) return;
|
||||
@@ -1254,62 +1400,196 @@ export default function ChatView() {
|
||||
focusComposer();
|
||||
};
|
||||
|
||||
const ensureSession = async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
const sessionThreadId = activeThread.session.threadId ?? null;
|
||||
const continuityState: SessionContinuityState =
|
||||
activeThread.codexThreadId === null
|
||||
? "new"
|
||||
: sessionThreadId === activeThread.codexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
return {
|
||||
sessionId: activeThread.session.sessionId,
|
||||
resolvedThreadId: sessionThreadId,
|
||||
continuityState,
|
||||
} satisfies EnsuredSessionInfo;
|
||||
}
|
||||
const ensureSession = useCallback(
|
||||
async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
const sessionThreadId = activeThread.session.threadId ?? null;
|
||||
const continuityState: SessionContinuityState =
|
||||
activeThread.codexThreadId === null
|
||||
? "new"
|
||||
: sessionThreadId === activeThread.codexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
return {
|
||||
sessionId: activeThread.session.sessionId,
|
||||
resolvedThreadId: sessionThreadId,
|
||||
continuityState,
|
||||
} satisfies EnsuredSessionInfo;
|
||||
}
|
||||
|
||||
const priorCodexThreadId = activeThread.codexThreadId;
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
provider: "codex",
|
||||
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
|
||||
model: selectedModel || undefined,
|
||||
resumeThreadId: priorCodexThreadId ?? undefined,
|
||||
approvalPolicy: runtimeSessionConfig.approvalPolicy,
|
||||
sandboxMode: runtimeSessionConfig.sandboxMode,
|
||||
});
|
||||
dispatch({
|
||||
type: "UPDATE_SESSION",
|
||||
threadId: activeThread.id,
|
||||
session,
|
||||
});
|
||||
const resolvedThreadId = session.threadId ?? null;
|
||||
const continuityState: SessionContinuityState =
|
||||
priorCodexThreadId === null
|
||||
? "new"
|
||||
: resolvedThreadId === priorCodexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
resolvedThreadId,
|
||||
continuityState,
|
||||
};
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: err instanceof Error ? err.message : "Failed to connect.",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
const priorCodexThreadId = activeThread.codexThreadId;
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const session = await api.providers.startSession({
|
||||
provider: "codex",
|
||||
cwd: cwdOverride ?? activeThread.worktreePath ?? activeProject.cwd,
|
||||
model: selectedModel || undefined,
|
||||
resumeThreadId: priorCodexThreadId ?? undefined,
|
||||
approvalPolicy: runtimeApprovalPolicy,
|
||||
sandboxMode: runtimeSandboxMode,
|
||||
});
|
||||
dispatch({
|
||||
type: "UPDATE_SESSION",
|
||||
threadId: activeThread.id,
|
||||
session,
|
||||
});
|
||||
const resolvedThreadId = session.threadId ?? null;
|
||||
const continuityState: SessionContinuityState =
|
||||
priorCodexThreadId === null
|
||||
? "new"
|
||||
: resolvedThreadId === priorCodexThreadId
|
||||
? "resumed"
|
||||
: "fallback_new";
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
resolvedThreadId,
|
||||
continuityState,
|
||||
};
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: err instanceof Error ? err.message : "Failed to connect.",
|
||||
});
|
||||
return null;
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
activeThread,
|
||||
api,
|
||||
dispatch,
|
||||
runtimeApprovalPolicy,
|
||||
runtimeSandboxMode,
|
||||
selectedModel,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !activeThreadId || activeSessionId) return;
|
||||
if (phase === "running" || isSending || isConnecting || isRevertingCheckpoint) return;
|
||||
const hasThreadIdentity = Boolean(activeThreadRuntimeId);
|
||||
if (!hasThreadIdentity) return;
|
||||
const selectedDiffTurnId =
|
||||
state.diffOpen && state.diffThreadId === activeThreadId ? state.diffTurnId : null;
|
||||
const selectedDiffTurn =
|
||||
selectedDiffTurnId === null
|
||||
? undefined
|
||||
: (turnDiffSummaries.find((summary) => summary.turnId === selectedDiffTurnId) ??
|
||||
turnDiffSummaries[0]);
|
||||
const selectedTurnMissingPatchBody = Boolean(
|
||||
selectedDiffTurn &&
|
||||
!selectedDiffTurn.unifiedDiff &&
|
||||
selectedDiffTurn.files.every((file) => !file.diff),
|
||||
);
|
||||
const hasPendingDiffHydration =
|
||||
turnDiffSummaries.some((summary) => !summary.checkpointDiffLoaded) ||
|
||||
selectedTurnMissingPatchBody;
|
||||
if (!hasPendingDiffHydration) return;
|
||||
|
||||
const requestKey = `${activeThreadId}:${activeThreadRuntimeId ?? "none"}`;
|
||||
if (checkpointHydrationSessionRequestRef.current.has(requestKey)) {
|
||||
return;
|
||||
}
|
||||
};
|
||||
checkpointHydrationSessionRequestRef.current.add(requestKey);
|
||||
setThreadError(activeThreadId, null);
|
||||
void ensureSession().then(
|
||||
() => {
|
||||
checkpointHydrationSessionRequestRef.current.delete(requestKey);
|
||||
},
|
||||
() => {
|
||||
// Keep the key on failure so this effect does not re-enter in a tight loop.
|
||||
},
|
||||
);
|
||||
}, [
|
||||
activeThreadId,
|
||||
activeThreadRuntimeId,
|
||||
activeSessionId,
|
||||
api,
|
||||
ensureSession,
|
||||
isConnecting,
|
||||
isRevertingCheckpoint,
|
||||
isSending,
|
||||
phase,
|
||||
setThreadError,
|
||||
state.diffOpen,
|
||||
state.diffThreadId,
|
||||
state.diffTurnId,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
|
||||
const onRevertToTurnCount = useCallback(
|
||||
async (turnCount: number) => {
|
||||
if (!api || !activeThread || isRevertingCheckpoint) {
|
||||
return;
|
||||
}
|
||||
if (phase === "running" || isSending || isConnecting) {
|
||||
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||
return;
|
||||
}
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[
|
||||
`Revert this thread to checkpoint ${turnCount}?`,
|
||||
"This will discard newer messages and turn diffs in this thread.",
|
||||
"This action cannot be undone.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRevertingCheckpoint(true);
|
||||
setThreadError(activeThread.id, null);
|
||||
try {
|
||||
const sessionInfo = await ensureSession();
|
||||
if (!sessionInfo) {
|
||||
return;
|
||||
}
|
||||
const result = await api.providers.revertToCheckpoint({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
turnCount,
|
||||
});
|
||||
dispatch({
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
threadRuntimeId: result.threadId,
|
||||
turnCount: result.turnCount,
|
||||
messageCount: result.messageCount,
|
||||
});
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS",
|
||||
threadId: activeThread.id,
|
||||
checkpointTurnCountByTurnId: Object.fromEntries(
|
||||
result.checkpoints
|
||||
.filter((entry) => entry.turnCount > 0)
|
||||
.map((entry) => [entry.id, entry.turnCount] as const),
|
||||
),
|
||||
});
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to revert thread state.",
|
||||
);
|
||||
} finally {
|
||||
setIsRevertingCheckpoint(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
api,
|
||||
dispatch,
|
||||
ensureSession,
|
||||
isConnecting,
|
||||
isRevertingCheckpoint,
|
||||
isSending,
|
||||
phase,
|
||||
setThreadError,
|
||||
],
|
||||
);
|
||||
|
||||
const onSend = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -1597,8 +1877,43 @@ export default function ChatView() {
|
||||
setExpandedImage(image);
|
||||
}, []);
|
||||
const onToggleDiff = useCallback(() => {
|
||||
dispatch({ type: "TOGGLE_DIFF" });
|
||||
}, [dispatch]);
|
||||
if (state.diffOpen) {
|
||||
dispatch({ type: "CLOSE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!activeThread) {
|
||||
dispatch({ type: "TOGGLE_DIFF" });
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
});
|
||||
}, [activeThread, dispatch, state.diffOpen]);
|
||||
const onOpenTurnDiff = useCallback(
|
||||
(turnId: string, filePath?: string) => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "OPEN_DIFF",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
...(filePath ? { filePath } : {}),
|
||||
});
|
||||
},
|
||||
[activeThread, dispatch],
|
||||
);
|
||||
const onRevertUserMessage = useCallback(
|
||||
(messageId: string) => {
|
||||
const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
|
||||
if (typeof targetTurnCount !== "number") {
|
||||
return;
|
||||
}
|
||||
void onRevertToTurnCount(targetTurnCount);
|
||||
},
|
||||
[onRevertToTurnCount, revertTurnCountByUserMessageId],
|
||||
);
|
||||
|
||||
// Empty state: no active thread
|
||||
if (!activeThread) {
|
||||
@@ -1665,9 +1980,14 @@ export default function ChatView() {
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
assistantCompletionByItemId={assistantCompletionByItemId}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
nowIso={nowIso}
|
||||
expandedWorkGroups={expandedWorkGroups}
|
||||
onToggleWorkGroup={onToggleWorkGroup}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}
|
||||
onRevertUserMessage={onRevertUserMessage}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
messagesEndRef={messagesEndRef}
|
||||
/>
|
||||
@@ -2011,17 +2331,15 @@ const ChatHeader = memo(function ChatHeader({
|
||||
)}
|
||||
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
|
||||
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
<Button
|
||||
<Toggle
|
||||
pressed={diffOpen}
|
||||
onPressedChange={onToggleDiff}
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"text-muted-foreground/70 hover:text-foreground/80",
|
||||
diffOpen && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
onClick={onToggleDiff}
|
||||
>
|
||||
Diff
|
||||
</Button>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
@@ -2120,9 +2438,14 @@ interface MessagesTimelineProps {
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary: string | null;
|
||||
assistantCompletionByItemId: Map<string, string>;
|
||||
turnDiffSummaryByAssistantMessageId: Map<string, TurnDiffSummary>;
|
||||
nowIso: string;
|
||||
expandedWorkGroups: Record<string, boolean>;
|
||||
onToggleWorkGroup: (groupId: string) => void;
|
||||
onOpenTurnDiff: (turnId: string, filePath?: string) => void;
|
||||
revertTurnCountByUserMessageId: Map<string, number>;
|
||||
onRevertUserMessage: (messageId: string) => void;
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (image: ExpandedImagePreview) => void;
|
||||
messagesEndRef: RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
@@ -2134,9 +2457,14 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
assistantCompletionByItemId,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
nowIso,
|
||||
expandedWorkGroups,
|
||||
onToggleWorkGroup,
|
||||
onOpenTurnDiff,
|
||||
revertTurnCountByUserMessageId,
|
||||
onRevertUserMessage,
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
messagesEndRef,
|
||||
}: MessagesTimelineProps) {
|
||||
@@ -2237,6 +2565,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
if (timelineEntry.message.role === "user") {
|
||||
const userImages = timelineEntry.message.attachments ?? [];
|
||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(timelineEntry.message.id);
|
||||
return (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
<div className="flex justify-end">
|
||||
@@ -2271,9 +2600,22 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isRevertingCheckpoint || isWorking}
|
||||
onClick={() => onRevertUserMessage(timelineEntry.message.id)}
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
<p className="text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Fragment>
|
||||
@@ -2298,6 +2640,107 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
(timelineEntry.message.streaming ? "" : "(empty response)")
|
||||
}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(
|
||||
timelineEntry.message.id,
|
||||
);
|
||||
if (!turnSummary) return null;
|
||||
const isCheckpointDiffLoading =
|
||||
!turnSummary.checkpointDiffLoaded && turnSummary.files.length === 0;
|
||||
const summaryStat = turnSummary.unifiedDiff
|
||||
? countDiffStat(turnSummary.unifiedDiff)
|
||||
: turnSummary.files.reduce(
|
||||
(acc, file) => {
|
||||
const next =
|
||||
typeof file.additions === "number" && typeof file.deletions === "number"
|
||||
? { additions: file.additions, deletions: file.deletions }
|
||||
: file.diff
|
||||
? countDiffStat(file.diff)
|
||||
: null;
|
||||
if (!next) {
|
||||
return acc;
|
||||
}
|
||||
return {
|
||||
additions: acc.additions + next.additions,
|
||||
deletions: acc.deletions + next.deletions,
|
||||
};
|
||||
},
|
||||
{ additions: 0, deletions: 0 },
|
||||
);
|
||||
const changedFileCountLabel = isCheckpointDiffLoading
|
||||
? "..."
|
||||
: String(turnSummary.files.length);
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{!isCheckpointDiffLoading &&
|
||||
(summaryStat.additions > 0 || summaryStat.deletions > 0) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<span className="text-success">+{summaryStat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{summaryStat.deletions}</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, turnSummary.files[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
{isCheckpointDiffLoading && (
|
||||
<p className="mb-1.5 text-[11px] text-muted-foreground/70">
|
||||
Loading checkpoint diff...
|
||||
</p>
|
||||
)}
|
||||
{turnSummary.files.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{turnSummary.files.map((file) => (
|
||||
<button
|
||||
key={`${turnSummary.turnId}:${file.path}`}
|
||||
type="button"
|
||||
className="rounded-md border border-border/70 bg-background/70 px-2 py-1 font-mono text-[11px] text-muted-foreground/80 transition-colors hover:border-border hover:text-foreground/90"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, file.path)}
|
||||
>
|
||||
{(() => {
|
||||
const stat =
|
||||
typeof file.additions === "number" &&
|
||||
typeof file.deletions === "number"
|
||||
? { additions: file.additions, deletions: file.deletions }
|
||||
: file.diff
|
||||
? countDiffStat(file.diff)
|
||||
: null;
|
||||
if (!stat) {
|
||||
return file.path;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<span>{file.path}</span>
|
||||
<span className="ml-1 text-muted-foreground/70">(</span>
|
||||
<span className="text-success">+{stat.additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{stat.deletions}</span>
|
||||
<span className="text-muted-foreground/70">)</span>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : !isCheckpointDiffLoading ? (
|
||||
<p className="text-[11px] text-muted-foreground/70">No changed files.</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
|
||||
@@ -1,58 +1,470 @@
|
||||
import { XIcon } from "lucide-react";
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
import {
|
||||
FileDiff,
|
||||
type FileDiffMetadata,
|
||||
Virtualizer,
|
||||
WorkerPoolContextProvider,
|
||||
} from "@pierre/diffs/react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { isElectron } from "../env";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { formatTimestamp } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
export default function DiffPanel() {
|
||||
const { dispatch } = useStore();
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark" | "system";
|
||||
|
||||
type RenderablePatch =
|
||||
| {
|
||||
kind: "files";
|
||||
files: FileDiffMetadata[];
|
||||
}
|
||||
| {
|
||||
kind: "raw";
|
||||
text: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
|
||||
if (!patch) return null;
|
||||
const normalizedPatch = patch.trim();
|
||||
if (normalizedPatch.length === 0) return null;
|
||||
|
||||
try {
|
||||
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
|
||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
||||
if (files.length > 0) {
|
||||
return { kind: "files", files };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Unsupported diff format. Showing raw patch.",
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
kind: "raw",
|
||||
text: normalizedPatch,
|
||||
reason: "Failed to parse patch. Showing raw patch.",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
|
||||
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
|
||||
if (raw.startsWith("a/") || raw.startsWith("b/")) {
|
||||
return raw.slice(2);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: "inline" | "sheet";
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
{/* Header */}
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{
|
||||
workerFactory: () =>
|
||||
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
|
||||
poolSize: workerPoolSize,
|
||||
totalASTLRUCacheSize: 240,
|
||||
}}
|
||||
highlighterOptions={{
|
||||
tokenizeMaxLineLength: 1_000,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const api = useNativeApi();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { state, dispatch } = useStore();
|
||||
const queryClient = useQueryClient();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
||||
const activeThreadRuntimeId =
|
||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
|
||||
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
|
||||
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
|
||||
const selectedFilePath =
|
||||
canApplyStoredTarget && selectedTurnId !== null ? state.diffFilePath : null;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
? undefined
|
||||
: (turnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
||||
turnDiffSummaries[0]);
|
||||
const selectedCheckpointTurnCount =
|
||||
selectedTurn &&
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
||||
const selectedCheckpointRange = useMemo(
|
||||
() =>
|
||||
typeof selectedCheckpointTurnCount === "number"
|
||||
? {
|
||||
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
|
||||
toTurnCount: selectedCheckpointTurnCount,
|
||||
}
|
||||
: null,
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const conversationCheckpointTurnCount = useMemo(() => {
|
||||
const turnCounts = turnDiffSummaries
|
||||
.map(
|
||||
(summary) =>
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
|
||||
)
|
||||
.filter((value): value is number => typeof value === "number");
|
||||
if (turnCounts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const latest = Math.max(...turnCounts);
|
||||
return latest > 0 ? latest : undefined;
|
||||
}, [inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
|
||||
const conversationCheckpointRange = useMemo(
|
||||
() =>
|
||||
!selectedTurn && typeof conversationCheckpointTurnCount === "number"
|
||||
? {
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: conversationCheckpointTurnCount,
|
||||
}
|
||||
: null,
|
||||
[conversationCheckpointTurnCount, selectedTurn],
|
||||
);
|
||||
const activeCheckpointRange = selectedTurn
|
||||
? selectedCheckpointRange
|
||||
: conversationCheckpointRange;
|
||||
const conversationCacheScope = useMemo(() => {
|
||||
if (selectedTurn || turnDiffSummaries.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return `conversation:${turnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
|
||||
}, [selectedTurn, turnDiffSummaries]);
|
||||
const activeCheckpointDiffQuery = useQuery(
|
||||
checkpointDiffQueryOptions(api, {
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
||||
}),
|
||||
);
|
||||
const selectedTurnCheckpointDiff = selectedTurn
|
||||
? activeCheckpointDiffQuery.data?.diff
|
||||
: undefined;
|
||||
const conversationCheckpointDiff = selectedTurn
|
||||
? undefined
|
||||
: activeCheckpointDiffQuery.data?.diff;
|
||||
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
|
||||
const checkpointDiffError =
|
||||
activeCheckpointDiffQuery.error instanceof Error
|
||||
? activeCheckpointDiffQuery.error.message
|
||||
: activeCheckpointDiffQuery.error
|
||||
? "Failed to load checkpoint diff."
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || !selectedTurn || !selectedTurnCheckpointDiff) {
|
||||
return;
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: activeThread.id,
|
||||
checkpointDiffByTurnId: {
|
||||
[selectedTurn.turnId]: selectedTurnCheckpointDiff,
|
||||
},
|
||||
});
|
||||
}, [activeThread?.id, dispatch, selectedTurn, selectedTurnCheckpointDiff]);
|
||||
|
||||
const selectedPatch = useMemo(() => {
|
||||
const patchForSummary = (summary: (typeof turnDiffSummaries)[number]): string | undefined => {
|
||||
const checkpointTurnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (activeSessionId && typeof checkpointTurnCount === "number") {
|
||||
const checkpointPatch = queryClient.getQueryData<{ diff: string }>(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
sessionId: activeSessionId,
|
||||
threadRuntimeId: activeThreadRuntimeId,
|
||||
fromTurnCount: Math.max(0, checkpointTurnCount - 1),
|
||||
toTurnCount: checkpointTurnCount,
|
||||
cacheScope: `turn:${summary.turnId}`,
|
||||
}),
|
||||
)?.diff;
|
||||
if (checkpointPatch) {
|
||||
return checkpointPatch;
|
||||
}
|
||||
}
|
||||
if (summary.unifiedDiff) {
|
||||
return summary.unifiedDiff;
|
||||
}
|
||||
const filePatches = summary.files
|
||||
.map((file) => file.diff?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (filePatches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return filePatches.join("\n\n");
|
||||
};
|
||||
|
||||
if (selectedTurn) {
|
||||
return selectedTurnCheckpointDiff ?? patchForSummary(selectedTurn);
|
||||
}
|
||||
|
||||
if (conversationCheckpointDiff) {
|
||||
return conversationCheckpointDiff;
|
||||
}
|
||||
|
||||
// Fallback when a conversation checkpoint diff isn't available yet:
|
||||
// keep one patch per file path (latest change wins) so files aren't duplicated.
|
||||
const latestPatchByPath = new Map<string, string>();
|
||||
for (const summary of turnDiffSummaries) {
|
||||
for (const file of summary.files) {
|
||||
if (latestPatchByPath.has(file.path)) {
|
||||
continue;
|
||||
}
|
||||
const patch = file.diff?.trim();
|
||||
if (!patch) {
|
||||
continue;
|
||||
}
|
||||
latestPatchByPath.set(file.path, patch);
|
||||
}
|
||||
}
|
||||
if (latestPatchByPath.size > 0) {
|
||||
return Array.from(latestPatchByPath.entries())
|
||||
.toSorted(([leftPath], [rightPath]) =>
|
||||
leftPath.localeCompare(rightPath, undefined, { numeric: true, sensitivity: "base" }),
|
||||
)
|
||||
.map(([, patch]) => patch)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
const patches = turnDiffSummaries
|
||||
.toReversed()
|
||||
.map((summary) => patchForSummary(summary)?.trim())
|
||||
.filter((patch): patch is string => Boolean(patch));
|
||||
if (patches.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return patches.join("\n\n");
|
||||
}, [
|
||||
activeSessionId,
|
||||
activeThreadRuntimeId,
|
||||
conversationCheckpointDiff,
|
||||
inferredCheckpointTurnCountByTurnId,
|
||||
queryClient,
|
||||
selectedTurn,
|
||||
selectedTurnCheckpointDiff,
|
||||
turnDiffSummaries,
|
||||
]);
|
||||
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
return [];
|
||||
}
|
||||
return renderablePatch.files.toSorted((left, right) =>
|
||||
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
|
||||
numeric: true,
|
||||
sensitivity: "base",
|
||||
}),
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
return;
|
||||
}
|
||||
const target = Array.from(
|
||||
patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
|
||||
).find((element) => element.dataset.diffFilePath === selectedFilePath);
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const selectTurn = (turnId: string) => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
turnId,
|
||||
});
|
||||
};
|
||||
const selectWholeConversation = () => {
|
||||
if (!activeThread) return;
|
||||
dispatch({
|
||||
type: "SET_DIFF_TARGET",
|
||||
threadId: activeThread.id,
|
||||
});
|
||||
};
|
||||
|
||||
const shouldUseDragRegion = isElectron && mode === "inline";
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={cn(
|
||||
"flex items-center justify-between border-b border-border px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
|
||||
)}
|
||||
>
|
||||
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Placeholder content */}
|
||||
<div className="flex-1 overflow-y-auto p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
|
||||
M
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
|
||||
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
|
||||
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
selectedTurnId === null
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="text-[10px] font-medium">All turns</div>
|
||||
<div className="text-[8px] opacity-70">Conversation</div>
|
||||
</div>
|
||||
<div className="space-y-0.5 font-mono text-[11px]">
|
||||
<div className="text-red-400/60">- const oldValue = "hello";</div>
|
||||
<div className="text-emerald-400/60">+ const newValue = "world";</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
|
||||
A
|
||||
</span>
|
||||
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
{turnDiffSummaries.map((summary, index) => (
|
||||
<button
|
||||
key={summary.turnId}
|
||||
type="button"
|
||||
className="shrink-0 rounded-md"
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
title={summary.turnId}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
||||
summary.turnId === selectedTurn?.turnId
|
||||
? "border-border bg-accent text-accent-foreground"
|
||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
||||
)}
|
||||
>
|
||||
<div className="text-[10px] font-medium">
|
||||
Turn {turnDiffSummaries.length - index}
|
||||
</div>
|
||||
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||
Diff integration coming soon
|
||||
</p>
|
||||
<ToggleGroup
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
{!activeThread ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
</div>
|
||||
) : turnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
{!canApplyStoredTarget && state.diffThreadId && (
|
||||
<div className="px-3 pt-2">
|
||||
<p className="mb-2 text-[11px] text-muted-foreground/65">
|
||||
Showing diffs for the active thread.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
</div>
|
||||
)}
|
||||
{!renderablePatch ? (
|
||||
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
|
||||
<p>
|
||||
{isLoadingCheckpointDiff
|
||||
? "Loading checkpoint diff..."
|
||||
: "No patch available for this selection."}
|
||||
</p>
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
}}
|
||||
>
|
||||
{renderableFiles.map((fileDiff) => {
|
||||
const filePath = resolveFileDiffPath(fileDiff);
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
return (
|
||||
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
{renderablePatch.text}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -170,6 +170,7 @@ export default function Sidebar() {
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
branch: options?.branch ?? null,
|
||||
|
||||
@@ -60,16 +60,18 @@ function SheetPopup({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
keepMounted = false,
|
||||
side = "right",
|
||||
variant = "default",
|
||||
...props
|
||||
}: SheetPrimitive.Popup.Props & {
|
||||
showCloseButton?: boolean;
|
||||
keepMounted?: boolean;
|
||||
side?: "right" | "left" | "top" | "bottom";
|
||||
variant?: "default" | "inset";
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetPortal keepMounted={keepMounted}>
|
||||
<SheetBackdrop />
|
||||
<SheetViewport side={side} variant={variant}>
|
||||
<SheetPrimitive.Popup
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
"use client";
|
||||
|
||||
import type { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { Toggle as ToggleComponent, type toggleVariants } from "~/components/ui/toggle";
|
||||
|
||||
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
...props
|
||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive
|
||||
className={cn(
|
||||
"flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input",
|
||||
orientation === "horizontal"
|
||||
? "*:pointer-coarse:after:min-w-auto"
|
||||
: "*:pointer-coarse:after:min-h-auto",
|
||||
variant === "default"
|
||||
? "gap-0.5"
|
||||
: orientation === "horizontal"
|
||||
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
|
||||
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
|
||||
className,
|
||||
)}
|
||||
data-size={size}
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ size, variant }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive>
|
||||
);
|
||||
}
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext);
|
||||
|
||||
const resolvedVariant = variant ?? context.variant;
|
||||
const resolvedSize = size ?? context.size;
|
||||
|
||||
return (
|
||||
<ToggleComponent
|
||||
className={className}
|
||||
data-size={resolvedSize}
|
||||
data-variant={resolvedVariant}
|
||||
size={resolvedSize}
|
||||
variant={resolvedVariant}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleComponent>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleGroupSeparator({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: {
|
||||
className?: string;
|
||||
} & React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
className={cn(
|
||||
"pointer-events-none relative bg-input before:absolute before:inset-0 dark:before:bg-input/32",
|
||||
className,
|
||||
)}
|
||||
orientation={orientation}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { ToggleGroup, Toggle, Toggle as ToggleGroupItem, ToggleGroupSeparator };
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const toggleVariants = cva(
|
||||
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base text-foreground outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-pressed:bg-input/64 data-pressed:text-accent-foreground sm:text-sm [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
variant: "default",
|
||||
},
|
||||
variants: {
|
||||
size: {
|
||||
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
|
||||
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
|
||||
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
|
||||
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
|
||||
},
|
||||
variant: {
|
||||
default: "border-transparent",
|
||||
outline:
|
||||
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive
|
||||
className={cn(toggleVariants({ className, size, variant }))}
|
||||
data-slot="toggle"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants };
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
function getMediaQueryMatch(query: string): boolean {
|
||||
if (typeof window === "undefined") {
|
||||
return false;
|
||||
}
|
||||
return window.matchMedia(query).matches;
|
||||
}
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => getMediaQueryMatch(query));
|
||||
|
||||
useEffect(() => {
|
||||
const mediaQueryList = window.matchMedia(query);
|
||||
const handleChange = () => {
|
||||
setMatches(mediaQueryList.matches);
|
||||
};
|
||||
|
||||
setMatches(mediaQueryList.matches);
|
||||
mediaQueryList.addEventListener("change", handleChange);
|
||||
return () => {
|
||||
mediaQueryList.removeEventListener("change", handleChange);
|
||||
};
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { ProviderEvent } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
import { deriveTurnDiffSummaries, inferCheckpointTurnCountByTurnId } from "../session-logic";
|
||||
import type { Thread, TurnDiffSummary } from "../types";
|
||||
|
||||
const derivedTurnDiffSummaryCache = new WeakMap<readonly ProviderEvent[], TurnDiffSummary[]>();
|
||||
|
||||
function deriveTurnDiffSummariesCached(events: ProviderEvent[]): TurnDiffSummary[] {
|
||||
const cached = derivedTurnDiffSummaryCache.get(events);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const derived = deriveTurnDiffSummaries(events);
|
||||
derivedTurnDiffSummaryCache.set(events, derived);
|
||||
return derived;
|
||||
}
|
||||
|
||||
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
|
||||
const turnDiffSummaries = useMemo(() => {
|
||||
if (!activeThread) {
|
||||
return [];
|
||||
}
|
||||
if (activeThread.turnDiffSummaries.length > 0) {
|
||||
return activeThread.turnDiffSummaries;
|
||||
}
|
||||
return deriveTurnDiffSummariesCached(activeThread.events);
|
||||
}, [activeThread]);
|
||||
|
||||
const inferredCheckpointTurnCountByTurnId = useMemo(
|
||||
() => inferCheckpointTurnCountByTurnId(turnDiffSummaries),
|
||||
[turnDiffSummaries],
|
||||
);
|
||||
|
||||
return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId };
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPatchCacheKey } from "./diffRendering";
|
||||
|
||||
describe("buildPatchCacheKey", () => {
|
||||
it("returns a stable cache key for identical content", () => {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
|
||||
expect(buildPatchCacheKey(patch)).toBe(buildPatchCacheKey(patch));
|
||||
});
|
||||
|
||||
it("normalizes outer whitespace before hashing", () => {
|
||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
|
||||
expect(buildPatchCacheKey(`\n${patch}\n`)).toBe(buildPatchCacheKey(patch));
|
||||
});
|
||||
|
||||
it("changes when diff content changes", () => {
|
||||
const before = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
||||
const after = "diff --git a/a.ts b/a.ts\n+console.log('hello world')";
|
||||
|
||||
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
hash = Math.imul(hash, multiplier) >>> 0;
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
|
||||
const normalizedPatch = patch.trim();
|
||||
const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
|
||||
const secondary = fnv1a32(
|
||||
normalizedPatch,
|
||||
SECONDARY_HASH_SEED,
|
||||
SECONDARY_HASH_MULTIPLIER,
|
||||
).toString(36);
|
||||
return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
|
||||
|
||||
describe("providerQueryKeys.checkpointDiff", () => {
|
||||
it("includes cacheScope so reused turn counts do not collide", () => {
|
||||
const baseInput = {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
} as const;
|
||||
|
||||
expect(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
cacheScope: "turn:old-turn",
|
||||
}),
|
||||
).not.toEqual(
|
||||
providerQueryKeys.checkpointDiff({
|
||||
...baseInput,
|
||||
cacheScope: "turn:new-turn",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkpointDiffQueryOptions", () => {
|
||||
it("forwards checkpoint range to the provider API", async () => {
|
||||
const getCheckpointDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
||||
const api = {
|
||||
providers: {
|
||||
getCheckpointDiff,
|
||||
},
|
||||
} as unknown as NativeApi;
|
||||
|
||||
const options = checkpointDiffQueryOptions(api, {
|
||||
sessionId: "session-id",
|
||||
threadRuntimeId: "thread-id",
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
cacheScope: "turn:abc",
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
await queryClient.fetchQuery(options);
|
||||
|
||||
expect(getCheckpointDiff).toHaveBeenCalledWith({
|
||||
sessionId: "session-id",
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { NativeApi } from "@t3tools/contracts";
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
|
||||
export interface CheckpointDiffQueryInput {
|
||||
sessionId: string | null;
|
||||
threadRuntimeId: string | null;
|
||||
fromTurnCount: number | null;
|
||||
toTurnCount: number | null;
|
||||
cacheScope?: string | null;
|
||||
}
|
||||
|
||||
export const providerQueryKeys = {
|
||||
all: ["providers"] as const,
|
||||
checkpointDiff: (input: CheckpointDiffQueryInput) =>
|
||||
[
|
||||
"providers",
|
||||
"checkpointDiff",
|
||||
input.sessionId,
|
||||
input.threadRuntimeId,
|
||||
input.fromTurnCount,
|
||||
input.toTurnCount,
|
||||
input.cacheScope ?? null,
|
||||
] as const,
|
||||
};
|
||||
|
||||
export function checkpointDiffQueryOptions(
|
||||
api: NativeApi | undefined,
|
||||
input: CheckpointDiffQueryInput,
|
||||
) {
|
||||
const hasValidRange =
|
||||
typeof input.fromTurnCount === "number" &&
|
||||
typeof input.toTurnCount === "number" &&
|
||||
Number.isInteger(input.fromTurnCount) &&
|
||||
Number.isInteger(input.toTurnCount) &&
|
||||
input.fromTurnCount >= 0 &&
|
||||
input.toTurnCount >= 0 &&
|
||||
input.fromTurnCount <= input.toTurnCount;
|
||||
|
||||
return queryOptions({
|
||||
queryKey: providerQueryKeys.checkpointDiff(input),
|
||||
queryFn: async () => {
|
||||
if (!api || !input.sessionId || !hasValidRange) {
|
||||
throw new Error("Checkpoint diff is unavailable.");
|
||||
}
|
||||
const { fromTurnCount, toTurnCount } = input;
|
||||
if (typeof fromTurnCount !== "number" || typeof toTurnCount !== "number") {
|
||||
throw new Error("Checkpoint diff range is invalid.");
|
||||
}
|
||||
return api.providers.getCheckpointDiff({
|
||||
sessionId: input.sessionId,
|
||||
fromTurnCount,
|
||||
toTurnCount,
|
||||
});
|
||||
},
|
||||
enabled: !!api && !!input.sessionId && hasValidRange,
|
||||
staleTime: Infinity,
|
||||
retry: 8,
|
||||
retryDelay: (attempt) => Math.min(2_000, 150 * 2 ** (attempt - 1)),
|
||||
});
|
||||
}
|
||||
@@ -263,6 +263,107 @@ describe("hydratePersistedState", () => {
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted turn diff summaries and clears persisted loaded flags", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
checkpointDiffLoaded: true,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 7,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
files: [{ path: 123 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated).not.toBeNull();
|
||||
expect(hydrated?.threads[0]?.id).toBe("t-1");
|
||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
@@ -309,6 +410,24 @@ describe("toPersistedState", () => {
|
||||
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
@@ -366,6 +485,22 @@ describe("toPersistedState", () => {
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-08T10:05:00.000Z",
|
||||
status: "completed",
|
||||
checkpointTurnCount: 1,
|
||||
files: [
|
||||
{
|
||||
path: "src/app.ts",
|
||||
kind: "modified",
|
||||
additions: 3,
|
||||
deletions: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const persistedThread = persisted.threads[0];
|
||||
expect(persistedThread).toBeDefined();
|
||||
|
||||
@@ -47,6 +47,23 @@ const persistedTerminalGroupSchema = z.object({
|
||||
terminalIds: z.array(z.string().trim().min(1)),
|
||||
});
|
||||
|
||||
const persistedTurnDiffFileChangeSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
kind: z.string().min(1).optional(),
|
||||
additions: z.number().int().min(0).optional(),
|
||||
deletions: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
const persistedTurnDiffSummarySchema = z.object({
|
||||
turnId: z.string().min(1),
|
||||
completedAt: z.string().min(1),
|
||||
status: z.string().min(1).optional(),
|
||||
files: z.array(persistedTurnDiffFileChangeSchema),
|
||||
assistantMessageId: z.string().min(1).optional(),
|
||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
||||
checkpointDiffLoaded: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const persistedThreadSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
codexThreadId: z.string().min(1).nullable().default(null),
|
||||
@@ -67,6 +84,7 @@ const persistedThreadSchema = z.object({
|
||||
lastVisitedAt: z.string().min(1).optional(),
|
||||
branch: z.string().min(1).nullable().optional(),
|
||||
worktreePath: z.string().min(1).nullable().optional(),
|
||||
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
|
||||
});
|
||||
|
||||
const persistedStateBodySchema = z.object({
|
||||
@@ -273,6 +291,21 @@ function hydrateThread(
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: thread.branch ?? null,
|
||||
worktreePath: thread.worktreePath ?? null,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -353,6 +386,21 @@ export function toPersistedState(
|
||||
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: summary.files.map((file) => ({
|
||||
path: file.path,
|
||||
...(file.kind ? { kind: file.kind } : {}),
|
||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
||||
})),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
||||
: {}),
|
||||
})),
|
||||
})),
|
||||
activeThreadId: state.activeThreadId,
|
||||
runtimeMode: state.runtimeMode,
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
derivePendingApprovals,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
@@ -393,6 +395,239 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffSummaries", () => {
|
||||
it("tracks completed turns and links them to assistant message completion", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/a.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-updated",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
threadId: "thr-1",
|
||||
turnId: "turn-1",
|
||||
diff: [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -0,0 +1 @@",
|
||||
"+created",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-msg",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "msg-1",
|
||||
type: "agentMessage",
|
||||
text: "Done",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-file-change",
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-file-change-2",
|
||||
type: "fileChange",
|
||||
status: "completed",
|
||||
changes: [
|
||||
{
|
||||
path: "src/unfinished.ts",
|
||||
kind: "modified",
|
||||
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
||||
expect(summaries[0]?.unifiedDiff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
it("includes completed turns even when no fileChange tool events were emitted", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
||||
expect(summaries[0]?.files).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps newest diff data when older events provide stale values", () => {
|
||||
const summaries = deriveTurnDiffSummaries([
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-old",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+older",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-diff-new",
|
||||
method: "turn/diff/updated",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: {
|
||||
diff: [
|
||||
"diff --git a/src/example.ts b/src/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+newest",
|
||||
].join("\n"),
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-completed",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
turn: {
|
||||
id: "turn-1",
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(summaries).toHaveLength(1);
|
||||
expect(summaries[0]?.unifiedDiff).toContain("+newest");
|
||||
expect(summaries[0]?.unifiedDiff).not.toContain("+older");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("splits a multi-file patch into sorted per-file entries", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
||||
expect(files[0]?.diff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
||||
expect(files[1]?.diff).toContain("diff --git a/src/b.ts b/src/b.ts");
|
||||
expect(files[0]?.additions).toBe(1);
|
||||
expect(files[0]?.deletions).toBe(1);
|
||||
});
|
||||
|
||||
it("parses git headers when file paths include ` b/`", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
|
||||
"--- a/subdir b/example.ts",
|
||||
"+++ b/subdir b/example.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old",
|
||||
"+new",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/example.ts");
|
||||
});
|
||||
|
||||
it("parses git header fallback for binary diffs with ` b/` in path", () => {
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
||||
[
|
||||
"diff --git a/subdir b/image.png b/subdir b/image.png",
|
||||
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(files).toHaveLength(1);
|
||||
expect(files[0]?.path).toBe("subdir b/image.png");
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
it("returns pending command/file-change approvals", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ChatMessage, SessionPhase } from "./types";
|
||||
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
|
||||
import { createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
@@ -33,10 +33,18 @@ export function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] | undefined {
|
||||
return Array.isArray(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
export function formatTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
@@ -99,6 +107,8 @@ export type TimelineEntry =
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
|
||||
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
@@ -438,6 +448,278 @@ export function deriveWorkLogEntries(
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface MutableTurnDiffSummary {
|
||||
turnId: string;
|
||||
completedAt: string | undefined;
|
||||
status: string | undefined;
|
||||
assistantMessageId: string | undefined;
|
||||
unifiedDiff: string | undefined;
|
||||
filesByPath: Map<string, TurnDiffFileChange>;
|
||||
}
|
||||
|
||||
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
|
||||
if (event.method !== "item/completed") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const item = asObject(asObject(event.payload)?.item);
|
||||
const itemType = normalizeItemType(asString(item?.type));
|
||||
if (itemType !== "file change") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const changes = asArray(item?.changes) ?? [];
|
||||
const parsed: TurnDiffFileChange[] = [];
|
||||
for (const rawChange of changes) {
|
||||
const change = asObject(rawChange);
|
||||
if (!change) continue;
|
||||
|
||||
const diff = normalizeDetail(asString(change.diff));
|
||||
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
|
||||
if (!path) continue;
|
||||
|
||||
const additions = asNumber(change.additions);
|
||||
const deletions = asNumber(change.deletions);
|
||||
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
|
||||
const kind = normalizeDetail(asString(change.kind));
|
||||
parsed.push({
|
||||
path,
|
||||
...(kind ? { kind } : {}),
|
||||
...(diff ? { diff } : {}),
|
||||
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
|
||||
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function mergeTurnDiffFileChange(
|
||||
byPath: Map<string, TurnDiffFileChange>,
|
||||
incoming: TurnDiffFileChange,
|
||||
): void {
|
||||
const existing = byPath.get(incoming.path);
|
||||
if (!existing) {
|
||||
byPath.set(incoming.path, incoming);
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.kind === undefined && incoming.kind !== undefined) {
|
||||
existing.kind = incoming.kind;
|
||||
}
|
||||
if (existing.diff === undefined && incoming.diff !== undefined) {
|
||||
existing.diff = incoming.diff;
|
||||
}
|
||||
if (existing.additions === undefined && incoming.additions !== undefined) {
|
||||
existing.additions = incoming.additions;
|
||||
}
|
||||
if (existing.deletions === undefined && incoming.deletions !== undefined) {
|
||||
existing.deletions = incoming.deletions;
|
||||
}
|
||||
}
|
||||
|
||||
function parsePathFromDiff(diff: string): string | undefined {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
|
||||
if (bPath && bPath[1]) return bPath[1];
|
||||
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
|
||||
if (gitHeader && gitHeader[1]) return gitHeader[1];
|
||||
const direct = normalized.match(/^\+\+\+ (.+)$/m);
|
||||
if (!direct || !direct[1] || direct[1] === "/dev/null") {
|
||||
return undefined;
|
||||
}
|
||||
return direct[1];
|
||||
}
|
||||
|
||||
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n");
|
||||
const byPath = new Map<string, string>();
|
||||
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
|
||||
|
||||
if (headerMatches.length === 0) {
|
||||
const path = parsePathFromDiff(normalized);
|
||||
if (path) {
|
||||
byPath.set(path, normalized.trim());
|
||||
}
|
||||
return byPath;
|
||||
}
|
||||
|
||||
for (let index = 0; index < headerMatches.length; index += 1) {
|
||||
const match = headerMatches[index];
|
||||
if (!match) continue;
|
||||
const start = match.index ?? 0;
|
||||
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
|
||||
const segment = normalized.slice(start, nextStart).trim();
|
||||
const path = parsePathFromDiff(segment);
|
||||
if (!path || segment.length === 0) continue;
|
||||
byPath.set(path, segment);
|
||||
}
|
||||
|
||||
return byPath;
|
||||
}
|
||||
|
||||
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
|
||||
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
|
||||
return Array.from(fileDiffsByPath.entries())
|
||||
.map(([path, fileDiff]) => {
|
||||
const stat = countDiffStat(fileDiff);
|
||||
return {
|
||||
path,
|
||||
diff: fileDiff,
|
||||
additions: stat.additions,
|
||||
deletions: stat.deletions,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
}
|
||||
|
||||
export function inferCheckpointTurnCountByTurnId(
|
||||
summaries: TurnDiffSummary[],
|
||||
): Record<string, number> {
|
||||
if (summaries.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const sorted = [...summaries].toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return a.completedAt.localeCompare(b.completedAt);
|
||||
}
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
const next: Record<string, number> = {};
|
||||
let fallbackTurnCount = 1;
|
||||
for (const summary of sorted) {
|
||||
if (typeof summary.checkpointTurnCount === "number") {
|
||||
next[summary.turnId] = summary.checkpointTurnCount;
|
||||
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
|
||||
continue;
|
||||
}
|
||||
next[summary.turnId] = fallbackTurnCount;
|
||||
fallbackTurnCount += 1;
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
|
||||
if (!patch) {
|
||||
return { additions: 0, deletions: 0 };
|
||||
}
|
||||
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
|
||||
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
||||
if (line.startsWith("+")) {
|
||||
additions += 1;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("-")) {
|
||||
deletions += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return { additions, deletions };
|
||||
}
|
||||
|
||||
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
|
||||
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
|
||||
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
|
||||
const ordered =
|
||||
events.length < 2 ||
|
||||
Number.isNaN(firstEventAt) ||
|
||||
Number.isNaN(lastEventAt) ||
|
||||
firstEventAt >= lastEventAt
|
||||
? events
|
||||
: [...events].toReversed();
|
||||
const byTurnId = new Map<string, MutableTurnDiffSummary>();
|
||||
|
||||
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
|
||||
const existing = byTurnId.get(turnId);
|
||||
if (existing) return existing;
|
||||
const next: MutableTurnDiffSummary = {
|
||||
turnId,
|
||||
completedAt: undefined,
|
||||
status: undefined,
|
||||
assistantMessageId: undefined,
|
||||
unifiedDiff: undefined,
|
||||
filesByPath: new Map<string, TurnDiffFileChange>(),
|
||||
};
|
||||
byTurnId.set(turnId, next);
|
||||
return next;
|
||||
};
|
||||
|
||||
for (const event of ordered) {
|
||||
const turnId = eventTurnId(event);
|
||||
if (!turnId) continue;
|
||||
const summary = ensureSummary(turnId);
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
if (summary.completedAt === undefined) {
|
||||
summary.completedAt = event.createdAt;
|
||||
}
|
||||
const turn = asObject(asObject(event.payload)?.turn);
|
||||
if (summary.status === undefined) {
|
||||
summary.status = normalizeDetail(asString(turn?.status));
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(asObject(event.payload)?.item);
|
||||
if (asString(item?.type) === "agentMessage") {
|
||||
const itemId = normalizeDetail(asString(item?.id));
|
||||
if (itemId && summary.assistantMessageId === undefined) {
|
||||
summary.assistantMessageId = itemId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "turn/diff/updated" && summary.unifiedDiff === undefined) {
|
||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
||||
if (diff) {
|
||||
summary.unifiedDiff = diff;
|
||||
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of parseFileChangeEntriesFromEvent(event)) {
|
||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
||||
}
|
||||
}
|
||||
|
||||
const summaries: TurnDiffSummary[] = [];
|
||||
for (const summary of byTurnId.values()) {
|
||||
if (!summary.completedAt) continue;
|
||||
|
||||
summaries.push({
|
||||
turnId: summary.turnId,
|
||||
completedAt: summary.completedAt,
|
||||
...(summary.status ? { status: summary.status } : {}),
|
||||
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
|
||||
a.path.localeCompare(b.path),
|
||||
),
|
||||
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
summaries.sort((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
return summaries;
|
||||
}
|
||||
|
||||
function toTimestamp(isoDate: string): number {
|
||||
const parsed = Date.parse(isoDate);
|
||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||
|
||||
+260
-2
@@ -57,6 +57,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: makeSession(),
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
branch: null,
|
||||
@@ -81,6 +82,9 @@ function makeState(thread: Thread): AppState {
|
||||
activeThreadId: thread.id,
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -145,6 +149,21 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.terminalOpen).toBe(true);
|
||||
});
|
||||
|
||||
it("opens diff panel with an explicit turn/file target", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "OPEN_DIFF",
|
||||
threadId: "thread-local-1",
|
||||
turnId: "turn-1",
|
||||
filePath: "src/app.ts",
|
||||
});
|
||||
|
||||
expect(next.diffOpen).toBe(true);
|
||||
expect(next.diffThreadId).toBe("thread-local-1");
|
||||
expect(next.diffTurnId).toBe("turn-1");
|
||||
expect(next.diffFilePath).toBe("src/app.ts");
|
||||
});
|
||||
|
||||
it("sets terminal open state per thread", () => {
|
||||
const state = makeState(makeThread({ terminalOpen: true }));
|
||||
const next = reducer(state, {
|
||||
@@ -499,6 +518,74 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
|
||||
});
|
||||
|
||||
it("preserves persisted turn diffs when events were reset and appends new completed turn diffs", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
events: [],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:01.000Z",
|
||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const withFileChange = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "item/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
type: "fileChange",
|
||||
changes: [{ path: "src/new.ts", kind: "added" }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(withFileChange.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-1",
|
||||
]);
|
||||
|
||||
const completed = reducer(withFileChange, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-2", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(completed.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
||||
"turn-2",
|
||||
"turn-1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:03.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(1);
|
||||
});
|
||||
|
||||
it("reconciles project ids by cwd when syncing backend projects", () => {
|
||||
const state: AppState = {
|
||||
projects: [
|
||||
@@ -531,7 +618,10 @@ describe("store reducer thread continuity", () => {
|
||||
],
|
||||
activeThreadId: "thread-b",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-b",
|
||||
diffTurnId: "turn-b",
|
||||
diffFilePath: "src/removed.ts",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -556,6 +646,10 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.id).toBe("thread-a");
|
||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||
expect(next.activeThreadId).toBe("thread-a");
|
||||
expect(next.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
it("treats empty scripts from sync as authoritative", () => {
|
||||
@@ -582,6 +676,9 @@ describe("store reducer thread continuity", () => {
|
||||
activeThreadId: "thread-a",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -660,7 +757,10 @@ describe("store reducer thread continuity", () => {
|
||||
],
|
||||
activeThreadId: "thread-a",
|
||||
runtimeMode: "full-access",
|
||||
diffOpen: false,
|
||||
diffOpen: true,
|
||||
diffThreadId: "thread-a",
|
||||
diffTurnId: "turn-a",
|
||||
diffFilePath: "src/a.ts",
|
||||
};
|
||||
|
||||
const next = reducer(state, {
|
||||
@@ -673,6 +773,10 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-b");
|
||||
expect(next.activeThreadId).toBe("thread-b");
|
||||
expect(next.diffOpen).toBe(false);
|
||||
expect(next.diffThreadId).toBeNull();
|
||||
expect(next.diffTurnId).toBeNull();
|
||||
expect(next.diffFilePath).toBeNull();
|
||||
});
|
||||
|
||||
it("marks the active thread as visited when selected", () => {
|
||||
@@ -718,4 +822,158 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
|
||||
it("reverts thread state to a checkpoint snapshot", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_before",
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
threadId: "thr_before",
|
||||
activeTurnId: "turn-live",
|
||||
}),
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "First",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-2",
|
||||
role: "assistant",
|
||||
text: "First reply",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-3",
|
||||
role: "user",
|
||||
text: "Second",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-live",
|
||||
}),
|
||||
],
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn_1",
|
||||
completedAt: "2026-02-08T10:00:01.000Z",
|
||||
files: [{ path: "src/first.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
{
|
||||
turnId: "turn_2",
|
||||
completedAt: "2026-02-08T10:00:03.000Z",
|
||||
files: [{ path: "src/second.ts", kind: "modified" }],
|
||||
checkpointTurnCount: 2,
|
||||
},
|
||||
],
|
||||
error: "temporary failure",
|
||||
latestTurnId: "turn-live",
|
||||
latestTurnStartedAt: "2026-02-08T10:00:03.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: "thread-local-1",
|
||||
sessionId: "sess-1",
|
||||
threadRuntimeId: "thr_after",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual(["m-1", "m-2"]);
|
||||
expect(next.threads[0]?.events).toEqual([]);
|
||||
expect(next.threads[0]?.error).toBeNull();
|
||||
expect(next.threads[0]?.session?.status).toBe("ready");
|
||||
expect(next.threads[0]?.session?.activeTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.latestTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn_1"]);
|
||||
});
|
||||
|
||||
it("keeps checkpoint-derived turn files when later events for the same turn arrive", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [
|
||||
{
|
||||
path: "src/from-checkpoint.ts",
|
||||
diff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
},
|
||||
],
|
||||
unifiedDiff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
||||
checkpointDiffLoaded: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-09T00:00:04.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/from-checkpoint.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.unifiedDiff).toContain("from-checkpoint.ts");
|
||||
});
|
||||
|
||||
it("updates turn summaries from checkpoint diffs and marks them as loaded", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
turnDiffSummaries: [
|
||||
{
|
||||
turnId: "turn-1",
|
||||
completedAt: "2026-02-09T00:00:03.000Z",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
||||
threadId: "thread-local-1",
|
||||
checkpointDiffByTurnId: {
|
||||
"turn-1": [
|
||||
"diff --git a/src/a.ts b/src/a.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-a",
|
||||
"+new-a",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"@@ -1 +1 @@",
|
||||
"-old-b",
|
||||
"+new-b",
|
||||
].join("\n"),
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
||||
"src/a.ts",
|
||||
"src/b.ts",
|
||||
]);
|
||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
||||
});
|
||||
});
|
||||
+340
-24
@@ -11,7 +11,15 @@ import {
|
||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
deriveTurnDiffFilesFromUnifiedDiff,
|
||||
deriveTurnDiffSummaries,
|
||||
inferCheckpointTurnCountByTurnId,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -42,6 +50,19 @@ type Action =
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "OPEN_DIFF";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| {
|
||||
type: "SET_DIFF_TARGET";
|
||||
threadId: string;
|
||||
turnId?: string;
|
||||
filePath?: string;
|
||||
}
|
||||
| { type: "CLOSE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
event: ProviderEvent;
|
||||
@@ -59,6 +80,24 @@ type Action =
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
|
||||
| {
|
||||
type: "REVERT_TO_CHECKPOINT";
|
||||
threadId: string;
|
||||
sessionId: string;
|
||||
threadRuntimeId: string;
|
||||
turnCount: number;
|
||||
messageCount: number;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS";
|
||||
threadId: string;
|
||||
checkpointTurnCountByTurnId: Record<string, number>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS";
|
||||
threadId: string;
|
||||
checkpointDiffByTurnId: Record<string, string>;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: string;
|
||||
@@ -76,6 +115,9 @@ export interface AppState {
|
||||
activeThreadId: string | null;
|
||||
runtimeMode: RuntimeMode;
|
||||
diffOpen: boolean;
|
||||
diffThreadId: string | null;
|
||||
diffTurnId: string | null;
|
||||
diffFilePath: string | null;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
@@ -96,6 +138,9 @@ const initialState: AppState = {
|
||||
activeThreadId: null,
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
@@ -118,7 +163,15 @@ function readPersistedState(): AppState {
|
||||
? hydrated.activeThreadId
|
||||
: (threads[0]?.id ?? null);
|
||||
|
||||
return { ...hydrated, threads, activeThreadId, diffOpen: false };
|
||||
return {
|
||||
...hydrated,
|
||||
threads,
|
||||
activeThreadId,
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
} catch {
|
||||
return initialState;
|
||||
}
|
||||
@@ -145,6 +198,102 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function resetDiffTargetIfMissing(state: AppState, threads: Thread[]) {
|
||||
if (!state.diffThreadId) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
const hasThread = threads.some((thread) => thread.id === state.diffThreadId);
|
||||
if (hasThread) {
|
||||
return {
|
||||
diffOpen: state.diffOpen,
|
||||
diffThreadId: state.diffThreadId,
|
||||
diffTurnId: state.diffTurnId,
|
||||
diffFilePath: state.diffFilePath,
|
||||
};
|
||||
}
|
||||
return {
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeTurnDiffSummaries(
|
||||
existing: Thread["turnDiffSummaries"],
|
||||
next: Thread["turnDiffSummaries"],
|
||||
): Thread["turnDiffSummaries"] {
|
||||
if (next.length === 0) return existing;
|
||||
|
||||
const existingByTurnId = new Map(existing.map((summary) => [summary.turnId, summary] as const));
|
||||
const merged = next.map((summary) => {
|
||||
const previous = existingByTurnId.get(summary.turnId);
|
||||
if (!previous) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const prefersCheckpointDiff = previous.checkpointDiffLoaded || summary.checkpointDiffLoaded;
|
||||
const files =
|
||||
prefersCheckpointDiff ||
|
||||
(summary.files.length === 0 && previous.files.length > 0 && summary.unifiedDiff === undefined)
|
||||
? previous.files
|
||||
: summary.files;
|
||||
const unifiedDiff =
|
||||
prefersCheckpointDiff || summary.unifiedDiff === undefined
|
||||
? (previous.unifiedDiff ?? summary.unifiedDiff)
|
||||
: summary.unifiedDiff;
|
||||
|
||||
return {
|
||||
...summary,
|
||||
files,
|
||||
...(unifiedDiff !== undefined ? { unifiedDiff } : {}),
|
||||
...(summary.assistantMessageId
|
||||
? {}
|
||||
: previous.assistantMessageId
|
||||
? { assistantMessageId: previous.assistantMessageId }
|
||||
: {}),
|
||||
...(typeof summary.checkpointTurnCount === "number"
|
||||
? {}
|
||||
: typeof previous.checkpointTurnCount === "number"
|
||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
||||
: {}),
|
||||
...(summary.checkpointDiffLoaded || previous.checkpointDiffLoaded
|
||||
? { checkpointDiffLoaded: true }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const mergedTurnIds = new Set(merged.map((summary) => summary.turnId));
|
||||
for (const summary of existing) {
|
||||
if (!mergedTurnIds.has(summary.turnId)) {
|
||||
merged.push(summary);
|
||||
}
|
||||
}
|
||||
|
||||
const sorted = merged.toSorted((a, b) => {
|
||||
const aTime = Date.parse(a.completedAt);
|
||||
const bTime = Date.parse(b.completedAt);
|
||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
||||
return b.completedAt.localeCompare(a.completedAt);
|
||||
}
|
||||
return bTime - aTime;
|
||||
});
|
||||
|
||||
const inferredTurnCountByTurnId = inferCheckpointTurnCountByTurnId(sorted);
|
||||
return sorted.map((summary) =>
|
||||
typeof summary.checkpointTurnCount === "number"
|
||||
? summary
|
||||
: Object.assign({}, summary, {
|
||||
checkpointTurnCount: inferredTurnCountByTurnId[summary.turnId],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -479,12 +628,14 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
|
||||
? state.activeThreadId
|
||||
: (nextThreads[0]?.id ?? null);
|
||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects: nextProjects,
|
||||
threads: nextThreads,
|
||||
activeThreadId,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -506,12 +657,14 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
const activeThreadId = threads.some((thread) => thread.id === state.activeThreadId)
|
||||
? state.activeThreadId
|
||||
: (threads[0]?.id ?? null);
|
||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
||||
|
||||
return {
|
||||
...state,
|
||||
projects,
|
||||
threads,
|
||||
activeThreadId,
|
||||
...diffState,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -520,6 +673,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
||||
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
@@ -710,6 +864,26 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "OPEN_DIFF":
|
||||
return {
|
||||
...state,
|
||||
diffOpen: true,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "SET_DIFF_TARGET":
|
||||
return {
|
||||
...state,
|
||||
diffThreadId: action.threadId,
|
||||
diffTurnId: action.turnId ?? null,
|
||||
diffFilePath: action.filePath ?? null,
|
||||
};
|
||||
|
||||
case "CLOSE_DIFF":
|
||||
return { ...state, diffOpen: false };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
@@ -746,27 +920,37 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, target.id, (t) => ({
|
||||
...t,
|
||||
...(() => {
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
const shouldRebindIdentity =
|
||||
event.method === "thread/started" && t.session?.status === "connecting";
|
||||
return {
|
||||
codexThreadId: shouldRebindIdentity
|
||||
? (eventThreadId ?? t.codexThreadId)
|
||||
: (t.codexThreadId ?? eventThreadId ?? null),
|
||||
error: event.kind === "error" && event.message ? event.message : t.error,
|
||||
};
|
||||
})(),
|
||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||
events: [event, ...t.events],
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === state.activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
})),
|
||||
threads: updateThread(state.threads, target.id, (t) => {
|
||||
const nextEvents = [event, ...t.events];
|
||||
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
|
||||
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
|
||||
const shouldRederiveDiffs =
|
||||
event.method === "turn/completed" ||
|
||||
event.method === "turn/diff/updated" ||
|
||||
(event.method === "item/completed" &&
|
||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange"));
|
||||
const turnDiffSummaries = shouldRederiveDiffs
|
||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
||||
: t.turnDiffSummaries;
|
||||
const eventThreadId = getEventThreadId(event);
|
||||
const shouldRebindIdentity =
|
||||
event.method === "thread/started" && t.session?.status === "connecting";
|
||||
return {
|
||||
...t,
|
||||
codexThreadId: shouldRebindIdentity
|
||||
? (eventThreadId ?? t.codexThreadId)
|
||||
: (t.codexThreadId ?? eventThreadId ?? null),
|
||||
error: event.kind === "error" && event.message ? event.message : t.error,
|
||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||
events: nextEvents,
|
||||
turnDiffSummaries,
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === state.activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -834,6 +1018,125 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
})),
|
||||
};
|
||||
|
||||
case "REVERT_TO_CHECKPOINT":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
const nextMessageCount = Math.max(0, Math.floor(action.messageCount));
|
||||
const nextTurnCount = Math.max(0, Math.floor(action.turnCount));
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
...t,
|
||||
codexThreadId: action.threadRuntimeId,
|
||||
session:
|
||||
t.session?.sessionId === action.sessionId
|
||||
? {
|
||||
...t.session,
|
||||
status: "ready",
|
||||
threadId: action.threadRuntimeId,
|
||||
activeTurnId: undefined,
|
||||
updatedAt: now,
|
||||
lastError: undefined,
|
||||
}
|
||||
: t.session,
|
||||
messages: t.messages.slice(0, nextMessageCount),
|
||||
events: [],
|
||||
turnDiffSummaries: t.turnDiffSummaries.filter(
|
||||
(summary) =>
|
||||
typeof summary.checkpointTurnCount === "number" &&
|
||||
summary.checkpointTurnCount <= nextTurnCount,
|
||||
),
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
lastVisitedAt: now,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TURN_CHECKPOINT_COUNTS":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
const hasUpdates = t.turnDiffSummaries.some(
|
||||
(summary) =>
|
||||
action.checkpointTurnCountByTurnId[summary.turnId] !== undefined &&
|
||||
action.checkpointTurnCountByTurnId[summary.turnId] !== summary.checkpointTurnCount,
|
||||
);
|
||||
if (!hasUpdates) {
|
||||
return t;
|
||||
}
|
||||
return {
|
||||
...t,
|
||||
turnDiffSummaries: t.turnDiffSummaries.map((summary) => {
|
||||
const turnCount = action.checkpointTurnCountByTurnId[summary.turnId];
|
||||
if (turnCount === undefined) {
|
||||
return summary;
|
||||
}
|
||||
return {
|
||||
...summary,
|
||||
checkpointTurnCount: turnCount,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_TURN_CHECKPOINT_DIFFS":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
let hasUpdates = false;
|
||||
const updatedSummaries = t.turnDiffSummaries.map((summary) => {
|
||||
const checkpointDiff = action.checkpointDiffByTurnId[summary.turnId];
|
||||
if (checkpointDiff === undefined) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
const files = deriveTurnDiffFilesFromUnifiedDiff(checkpointDiff);
|
||||
const filesUnchanged =
|
||||
files.length === summary.files.length &&
|
||||
files.every((file, index) => {
|
||||
const existing = summary.files[index];
|
||||
return (
|
||||
existing !== undefined &&
|
||||
existing.path === file.path &&
|
||||
existing.diff === file.diff &&
|
||||
existing.kind === file.kind &&
|
||||
existing.additions === file.additions &&
|
||||
existing.deletions === file.deletions
|
||||
);
|
||||
});
|
||||
if (
|
||||
summary.unifiedDiff === checkpointDiff &&
|
||||
filesUnchanged &&
|
||||
summary.checkpointDiffLoaded
|
||||
) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
hasUpdates = true;
|
||||
return {
|
||||
...summary,
|
||||
unifiedDiff: checkpointDiff,
|
||||
files,
|
||||
checkpointDiffLoaded: true,
|
||||
};
|
||||
});
|
||||
|
||||
if (!hasUpdates) {
|
||||
return t;
|
||||
}
|
||||
|
||||
return {
|
||||
...t,
|
||||
turnDiffSummaries: updatedSummaries,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
@@ -862,7 +1165,20 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
||||
const activeThreadId =
|
||||
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
|
||||
return { ...state, threads, activeThreadId };
|
||||
const shouldClearDiffTarget = state.diffThreadId === action.threadId;
|
||||
return {
|
||||
...state,
|
||||
threads,
|
||||
activeThreadId,
|
||||
...(shouldClearDiffTarget
|
||||
? {
|
||||
diffOpen: false,
|
||||
diffThreadId: null,
|
||||
diffTurnId: null,
|
||||
diffFilePath: null,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
|
||||
@@ -37,6 +37,25 @@ export interface ChatMessage {
|
||||
streaming: boolean;
|
||||
}
|
||||
|
||||
export interface TurnDiffFileChange {
|
||||
path: string;
|
||||
kind?: string | undefined;
|
||||
diff?: string | undefined;
|
||||
additions?: number | undefined;
|
||||
deletions?: number | undefined;
|
||||
}
|
||||
|
||||
export interface TurnDiffSummary {
|
||||
turnId: string;
|
||||
completedAt: string;
|
||||
status?: string | undefined;
|
||||
files: TurnDiffFileChange[];
|
||||
unifiedDiff?: string | undefined;
|
||||
assistantMessageId?: string | undefined;
|
||||
checkpointTurnCount?: number | undefined;
|
||||
checkpointDiffLoaded?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -71,4 +90,5 @@ export interface Thread {
|
||||
lastVisitedAt?: string | undefined;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
turnDiffSummaries: TurnDiffSummary[];
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
import "@pierre/diffs/worker/worker.js";
|
||||
@@ -25,6 +25,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
turnDiffSummaries: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
branch: null,
|
||||
|
||||
@@ -91,6 +91,10 @@ export function createWsNativeApi(): NativeApi {
|
||||
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
|
||||
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
|
||||
listSessions: () => transport.request(WS_METHODS.providersListSessions),
|
||||
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
|
||||
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, input),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
|
||||
},
|
||||
|
||||
@@ -37,6 +37,9 @@ export class WsTransport {
|
||||
}
|
||||
|
||||
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
||||
if (typeof method !== "string" || method.length === 0) {
|
||||
throw new Error("Request method is required");
|
||||
}
|
||||
const id = String(this.nextId++);
|
||||
const message: WsRequest = { id, method, ...(params !== undefined ? { params } : {}) };
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-pacer": "^0.19.4",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
@@ -304,6 +305,8 @@
|
||||
|
||||
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DJbQsSJUr4KSi9uU0QqOgI7PX2C+fKGZX+YDprt3vM2sC0dWZsgVTLoN2vtkNyEWJSY2mnvRFUshWXT3bmo0Ug=="],
|
||||
|
||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
|
||||
|
||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||
|
||||
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
|
||||
@@ -384,6 +387,22 @@
|
||||
|
||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="],
|
||||
|
||||
"@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-iAlTtSDDbJiRpvgL5ugKEATDtHdUVkqgHDm/gbD2ZS9c88mx7G1zSYjjOxp5Qa0eaW0MAQosFRmJSk354PRoQA=="],
|
||||
|
||||
"@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-jdKhfgW9CRtj3Tor0L7+yPwdG3CgP7W+ZEqSsojrMzCjD1e0IxIbwUMDDpYlVBlC08TACg4puwFGkZfLS+56Tw=="],
|
||||
|
||||
"@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-DyXsOG0vGtNtl7ygvabHd7Mt5EY8gCNqR9Y7Lpbbd/PbJvgWrqaKzH1JW6H6qFkuUa8aCxoiYVv8/YfFljiQxA=="],
|
||||
|
||||
"@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-x/42TfhWmp6H00T6uwVrdTJGKgNdFbrEdhaDwSR5fd5zhQ1Q46bHq9EO61SCEWJR0HY7z2HNDMaBZp8JRmKiIA=="],
|
||||
|
||||
"@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-o+tlOKqsr6FE4+mYJG08tfCFDS+3CG20HbldXeVoyP+cYSUxDhrFf3GPjE60U55iOkkjbpY2uC3It/eeja35/g=="],
|
||||
|
||||
"@shikijs/transformers": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/types": "3.22.0" } }, "sha512-E7eRV7mwDBjueLF6852n2oYeJYxBq3NSsDk+uyruYAXONv4U8holGmIrT+mPRJQ1J1SNOH6L8G19KRzmBawrFw=="],
|
||||
|
||||
"@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-491iAekgKDBFE67z70Ok5a8KBMsQ2IJwOWw3us/7ffQkIBCyOQfm/aNwVMBUriP02QshIfgHCBSIYAl3u2eWjg=="],
|
||||
|
||||
"@shikijs/vscode-textmate": ["@shikijs/[email protected]", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
|
||||
|
||||
"@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
|
||||
|
||||
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||
@@ -622,6 +641,8 @@
|
||||
|
||||
"devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
|
||||
|
||||
"diff": ["[email protected]", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
|
||||
|
||||
"dts-resolver": ["[email protected]", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="],
|
||||
|
||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||
@@ -722,6 +743,8 @@
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
@@ -736,6 +759,8 @@
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
|
||||
"html-void-elements": ["[email protected]", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],
|
||||
|
||||
"http-cache-semantics": ["[email protected]", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
|
||||
|
||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||
@@ -822,6 +847,8 @@
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
|
||||
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-JJ8GVTQqFwuliifD48U6+h7DXEHdkhJ/E87kksGByII3qHxtPciVb8T8woQONHBQgHVOl7rSMrrip3SeVNy7Fg=="],
|
||||
|
||||
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
@@ -952,6 +979,10 @@
|
||||
|
||||
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||
|
||||
"oniguruma-parser": ["[email protected]", "", {}, "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w=="],
|
||||
|
||||
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.0.1", "regex-recursion": "^6.0.2" } }, "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA=="],
|
||||
|
||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||
|
||||
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
||||
@@ -998,6 +1029,12 @@
|
||||
|
||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||
|
||||
"regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
|
||||
|
||||
"regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
@@ -1046,6 +1083,8 @@
|
||||
|
||||
"serialize-error": ["[email protected]", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
|
||||
|
||||
"shiki": ["[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/engine-javascript": "3.22.0", "@shikijs/engine-oniguruma": "3.22.0", "@shikijs/langs": "3.22.0", "@shikijs/themes": "3.22.0", "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-LBnhsoYEe0Eou4e1VgJACes+O6S6QC0w71fCSp5Oya79inkwkm15gQ1UF6VtQ8j/taMDh79hAB49WUk8ALQW3g=="],
|
||||
|
||||
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||
|
||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"import": "./src/index.ts",
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -17,7 +17,13 @@ import type {
|
||||
} from "./git";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderGetCheckpointDiffInput,
|
||||
ProviderGetCheckpointDiffResult,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderListCheckpointsInput,
|
||||
ProviderListCheckpointsResult,
|
||||
ProviderRevertToCheckpointInput,
|
||||
ProviderRevertToCheckpointResult,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
@@ -89,6 +95,15 @@ export interface NativeApi {
|
||||
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
listCheckpoints: (
|
||||
input: ProviderListCheckpointsInput,
|
||||
) => Promise<ProviderListCheckpointsResult>;
|
||||
getCheckpointDiff: (
|
||||
input: ProviderGetCheckpointDiffInput,
|
||||
) => Promise<ProviderGetCheckpointDiffResult>;
|
||||
revertToCheckpoint: (
|
||||
input: ProviderRevertToCheckpointInput,
|
||||
) => Promise<ProviderRevertToCheckpointResult>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
|
||||
@@ -2,7 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
providerCheckpointSchema,
|
||||
providerEventSchema,
|
||||
providerGetCheckpointDiffInputSchema,
|
||||
providerGetCheckpointDiffResultSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerListCheckpointsResultSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRevertToCheckpointResultSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
@@ -157,3 +164,98 @@ describe("providerRespondToRequestInputSchema", () => {
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider checkpoint schemas", () => {
|
||||
it("accepts list checkpoint inputs", () => {
|
||||
const parsed = providerListCheckpointsInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
});
|
||||
expect(parsed.sessionId).toBe("sess_1");
|
||||
});
|
||||
|
||||
it("accepts checkpoint records and list results", () => {
|
||||
const checkpoint = providerCheckpointSchema.parse({
|
||||
id: "turn_1",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
label: "Turn 1",
|
||||
preview: "Summarize this file",
|
||||
isCurrent: true,
|
||||
});
|
||||
expect(checkpoint.turnCount).toBe(1);
|
||||
|
||||
const listResult = providerListCheckpointsResultSchema.parse({
|
||||
threadId: "thr_1",
|
||||
checkpoints: [checkpoint],
|
||||
});
|
||||
expect(listResult.checkpoints).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts revert checkpoint input/result", () => {
|
||||
const input = providerRevertToCheckpointInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 2,
|
||||
});
|
||||
expect(input.turnCount).toBe(2);
|
||||
|
||||
const result = providerRevertToCheckpointResultSchema.parse({
|
||||
threadId: "thr_1",
|
||||
turnCount: 2,
|
||||
messageCount: 4,
|
||||
rolledBackTurns: 1,
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: false,
|
||||
},
|
||||
{
|
||||
id: "turn_2",
|
||||
turnCount: 2,
|
||||
messageCount: 4,
|
||||
label: "Turn 2",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.rolledBackTurns).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects negative turn counts", () => {
|
||||
expect(() =>
|
||||
providerRevertToCheckpointInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
turnCount: -1,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("accepts checkpoint diff input/result", () => {
|
||||
const input = providerGetCheckpointDiffInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
});
|
||||
expect(input.fromTurnCount).toBe(1);
|
||||
|
||||
const result = providerGetCheckpointDiffResultSchema.parse({
|
||||
threadId: "thr_1",
|
||||
fromTurnCount: 1,
|
||||
toTurnCount: 2,
|
||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
||||
});
|
||||
expect(result.toTurnCount).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects checkpoint diff ranges where start is after end", () => {
|
||||
expect(() =>
|
||||
providerGetCheckpointDiffInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
fromTurnCount: 3,
|
||||
toTurnCount: 2,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -111,6 +111,60 @@ export const providerStopSessionInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerListCheckpointsInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerCheckpointSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
messageCount: z.number().int().min(0),
|
||||
label: z.string().min(1),
|
||||
preview: z.string().min(1).optional(),
|
||||
isCurrent: z.boolean(),
|
||||
});
|
||||
|
||||
export const providerListCheckpointsResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
checkpoints: z.array(providerCheckpointSchema),
|
||||
});
|
||||
|
||||
export const providerRevertToCheckpointInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export const providerRevertToCheckpointResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
messageCount: z.number().int().min(0),
|
||||
rolledBackTurns: z.number().int().min(0),
|
||||
checkpoints: z.array(providerCheckpointSchema),
|
||||
});
|
||||
|
||||
export const providerGetCheckpointDiffInputSchema = z
|
||||
.object({
|
||||
sessionId: z.string().min(1),
|
||||
fromTurnCount: z.number().int().min(0),
|
||||
toTurnCount: z.number().int().min(0),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.fromTurnCount > value.toTurnCount) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "fromTurnCount must be less than or equal to toTurnCount",
|
||||
path: ["fromTurnCount"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const providerGetCheckpointDiffResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
fromTurnCount: z.number().int().min(0),
|
||||
toTurnCount: z.number().int().min(0),
|
||||
diff: z.string(),
|
||||
});
|
||||
|
||||
export const providerRespondToRequestInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1),
|
||||
@@ -151,6 +205,15 @@ export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
|
||||
export type ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
|
||||
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
|
||||
export type ProviderStopSessionInput = z.input<typeof providerStopSessionInputSchema>;
|
||||
export type ProviderListCheckpointsInput = z.input<typeof providerListCheckpointsInputSchema>;
|
||||
export type ProviderCheckpoint = z.infer<typeof providerCheckpointSchema>;
|
||||
export type ProviderListCheckpointsResult = z.infer<typeof providerListCheckpointsResultSchema>;
|
||||
export type ProviderRevertToCheckpointInput = z.input<typeof providerRevertToCheckpointInputSchema>;
|
||||
export type ProviderRevertToCheckpointResult = z.infer<
|
||||
typeof providerRevertToCheckpointResultSchema
|
||||
>;
|
||||
export type ProviderGetCheckpointDiffInput = z.input<typeof providerGetCheckpointDiffInputSchema>;
|
||||
export type ProviderGetCheckpointDiffResult = z.infer<typeof providerGetCheckpointDiffResultSchema>;
|
||||
export type ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
@@ -10,6 +10,9 @@ export const WS_METHODS = {
|
||||
providersRespondToRequest: "providers.respondToRequest",
|
||||
providersStopSession: "providers.stopSession",
|
||||
providersListSessions: "providers.listSessions",
|
||||
providersListCheckpoints: "providers.listCheckpoints",
|
||||
providersGetCheckpointDiff: "providers.getCheckpointDiff",
|
||||
providersRevertToCheckpoint: "providers.revertToCheckpoint",
|
||||
|
||||
// Project registry methods
|
||||
projectsList: "projects.list",
|
||||
|
||||
Reference in new issue
Block a user