Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
707889950d | ||
|
|
4d976b8bf7 | ||
|
|
0c50a2d8e1 | ||
|
|
f64c26e708 | ||
|
|
6d8d39a5d1 | ||
|
|
afdfe16931 |
No files matched your search
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
declare module "bun:sqlite" {
|
||||
export class Database {
|
||||
constructor(filename?: string);
|
||||
exec(sql: string): void;
|
||||
run(sql: string, ...params: unknown[]): unknown;
|
||||
query(sql: string): {
|
||||
get(...params: unknown[]): unknown;
|
||||
};
|
||||
close(): void;
|
||||
}
|
||||
}
|
||||
@@ -43,36 +43,6 @@ 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();
|
||||
@@ -228,62 +198,3 @@ 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("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,16 +65,6 @@ 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 =
|
||||
@@ -341,41 +331,6 @@ 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,
|
||||
@@ -787,31 +742,6 @@ 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") ?? [];
|
||||
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;
|
||||
@@ -893,16 +823,6 @@ 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;
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
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("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("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 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
import { mkdtemp, rm, writeFile } 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> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0 && result.stdout.trim() === "true";
|
||||
}
|
||||
|
||||
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-"));
|
||||
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]",
|
||||
};
|
||||
|
||||
try {
|
||||
await writeFile(tempIndexPath, "");
|
||||
|
||||
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 restoreCheckpoint(input: { cwd: string; threadId: string; turnCount: number }): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."], { allowNonZeroExit: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
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;
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
refsToDelete.map((refName) =>
|
||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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 (!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;
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,7 @@ async function main() {
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
@@ -59,255 +59,4 @@ 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");
|
||||
|
||||
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 codex = (
|
||||
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[] }>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).codex;
|
||||
|
||||
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
|
||||
codex.hasSession = () => true;
|
||||
codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
{ id: "turn_3", items: [] },
|
||||
],
|
||||
});
|
||||
codex.rollbackThread = async (sessionId, numTurns) => {
|
||||
rollbackCalls.push({ sessionId, numTurns });
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => ({
|
||||
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(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,
|
||||
});
|
||||
|
||||
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,16 +1,10 @@
|
||||
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 ProviderInterruptTurnInput,
|
||||
type ProviderListCheckpointsInput,
|
||||
type ProviderListCheckpointsResult,
|
||||
type ProviderRevertToCheckpointInput,
|
||||
type ProviderRevertToCheckpointResult,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
@@ -18,154 +12,23 @@ import {
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
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) {
|
||||
@@ -174,7 +37,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
@@ -198,11 +60,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
}
|
||||
await this.initializeFilesystemCheckpointing(session).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -238,99 +95,12 @@ 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 revertToCheckpoint(
|
||||
raw: ProviderRevertToCheckpointInput,
|
||||
): Promise<ProviderRevertToCheckpointResult> {
|
||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
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}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(input.sessionId);
|
||||
if (checkpointCwd) {
|
||||
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 requestedRollbackTurns = currentTurnCount - input.turnCount;
|
||||
const afterSnapshot =
|
||||
requestedRollbackTurns > 0
|
||||
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
|
||||
: beforeSnapshot;
|
||||
|
||||
if (checkpointCwd) {
|
||||
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}.`,
|
||||
);
|
||||
}
|
||||
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();
|
||||
}
|
||||
@@ -348,88 +118,6 @@ 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): Promise<void> {
|
||||
const cwd = 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.captureCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
||||
});
|
||||
}
|
||||
|
||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { RendererStateStore } from "./rendererStateStore";
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
describe("RendererStateStore", () => {
|
||||
it("returns null when no renderer state has been saved", async () => {
|
||||
const stateDir = makeTempDir("t3code-renderer-state-empty-");
|
||||
const store = new RendererStateStore(stateDir);
|
||||
|
||||
await expect(store.get()).resolves.toBeNull();
|
||||
|
||||
await store.close();
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("persists and reloads renderer state from sqlite", async () => {
|
||||
const stateDir = makeTempDir("t3code-renderer-state-roundtrip-");
|
||||
const firstStore = new RendererStateStore(stateDir);
|
||||
const payload =
|
||||
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}';
|
||||
|
||||
await firstStore.set({ stateJson: payload });
|
||||
const firstRead = await firstStore.get();
|
||||
expect(firstRead).toMatchObject({
|
||||
stateJson: payload,
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
await firstStore.close();
|
||||
|
||||
const secondStore = new RendererStateStore(stateDir);
|
||||
const secondRead = await secondStore.get();
|
||||
expect(secondRead).toMatchObject({
|
||||
stateJson: payload,
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
await secondStore.close();
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
type RendererStateSetInput,
|
||||
type RendererStateSnapshot,
|
||||
rendererStateSetInputSchema,
|
||||
rendererStateSnapshotSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
interface RowShape {
|
||||
stateJson: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
interface SqliteAdapter {
|
||||
getState(): RowShape | null;
|
||||
setState(stateJson: string, updatedAt: string): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface BunSqliteDatabase {
|
||||
exec(sql: string): void;
|
||||
run(sql: string, ...params: unknown[]): unknown;
|
||||
query(sql: string): {
|
||||
get(...params: unknown[]): unknown;
|
||||
};
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface BunSqliteModule {
|
||||
Database: new (filename?: string) => BunSqliteDatabase;
|
||||
}
|
||||
|
||||
function defaultStateDir(): string {
|
||||
return path.join(os.homedir(), ".t3", "userdata");
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function parseRowShape(row: unknown): RowShape | null {
|
||||
if (!isObject(row)) return null;
|
||||
const stateJson = row.stateJson;
|
||||
const updatedAt = row.updatedAt;
|
||||
if (typeof stateJson !== "string" || typeof updatedAt !== "string") return null;
|
||||
return { stateJson, updatedAt };
|
||||
}
|
||||
|
||||
async function createNodeSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
const module = await import("node:sqlite");
|
||||
const db = new module.DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS renderer_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
state_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
const selectStatement = db.prepare(`
|
||||
SELECT state_json AS stateJson, updated_at AS updatedAt
|
||||
FROM renderer_state
|
||||
WHERE id = 1
|
||||
`);
|
||||
const upsertStatement = db.prepare(`
|
||||
INSERT INTO renderer_state (id, state_json, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
state_json = excluded.state_json,
|
||||
updated_at = excluded.updated_at
|
||||
`);
|
||||
|
||||
return {
|
||||
getState() {
|
||||
return parseRowShape(selectStatement.get());
|
||||
},
|
||||
setState(stateJson: string, updatedAt: string) {
|
||||
upsertStatement.run(stateJson, updatedAt);
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function createBunSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
const loadBunSqlite = new Function(
|
||||
"return import('bun:sqlite')",
|
||||
) as () => Promise<BunSqliteModule>;
|
||||
const module = await loadBunSqlite();
|
||||
const db = new module.Database(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS renderer_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
state_json TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
const selectQuery = db.query(`
|
||||
SELECT state_json AS stateJson, updated_at AS updatedAt
|
||||
FROM renderer_state
|
||||
WHERE id = 1
|
||||
`);
|
||||
const upsertSql = `
|
||||
INSERT INTO renderer_state (id, state_json, updated_at)
|
||||
VALUES (1, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
state_json = excluded.state_json,
|
||||
updated_at = excluded.updated_at
|
||||
`;
|
||||
|
||||
return {
|
||||
getState() {
|
||||
return parseRowShape(selectQuery.get());
|
||||
},
|
||||
setState(stateJson: string, updatedAt: string) {
|
||||
db.run(upsertSql, stateJson, updatedAt);
|
||||
},
|
||||
close() {
|
||||
db.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function createSqliteAdapter(dbPath: string): Promise<SqliteAdapter> {
|
||||
try {
|
||||
return await createNodeSqliteAdapter(dbPath);
|
||||
} catch {
|
||||
return createBunSqliteAdapter(dbPath);
|
||||
}
|
||||
}
|
||||
|
||||
export class RendererStateStore {
|
||||
private readonly stateDir: string;
|
||||
private readonly dbPath: string;
|
||||
private adapterPromise: Promise<SqliteAdapter> | null = null;
|
||||
|
||||
constructor(stateDir: string = defaultStateDir()) {
|
||||
this.stateDir = stateDir;
|
||||
this.dbPath = path.join(this.stateDir, "renderer-state.sqlite");
|
||||
fs.mkdirSync(this.stateDir, { recursive: true });
|
||||
}
|
||||
|
||||
async get(): Promise<RendererStateSnapshot | null> {
|
||||
const adapter = await this.getAdapter();
|
||||
const row = adapter.getState();
|
||||
if (!row) return null;
|
||||
const parsed = rendererStateSnapshotSchema.safeParse(row);
|
||||
if (!parsed.success) return null;
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async set(raw: RendererStateSetInput): Promise<void> {
|
||||
const input = rendererStateSetInputSchema.parse(raw);
|
||||
const adapter = await this.getAdapter();
|
||||
adapter.setState(input.stateJson, new Date().toISOString());
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (!this.adapterPromise) return;
|
||||
const adapter = await this.adapterPromise;
|
||||
adapter.close();
|
||||
this.adapterPromise = null;
|
||||
}
|
||||
|
||||
private async getAdapter(): Promise<SqliteAdapter> {
|
||||
if (!this.adapterPromise) {
|
||||
this.adapterPromise = createSqliteAdapter(this.dbPath);
|
||||
}
|
||||
return this.adapterPromise;
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,7 @@ describe("WebSocket Server", () => {
|
||||
return createServer({
|
||||
port: 0,
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
stateDir,
|
||||
...(options.devUrl ? { devUrl: options.devUrl } : {}),
|
||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||
projectRegistry: new ProjectRegistry(stateDir),
|
||||
@@ -342,6 +343,71 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads and writes renderer state over websocket", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-renderer-state-");
|
||||
server = createTestServer({ cwd: "/my/workspace", stateDir });
|
||||
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 empty = await sendRequest(ws, WS_METHODS.serverGetRendererState);
|
||||
expect(empty.error).toBeUndefined();
|
||||
expect(empty.result).toBeNull();
|
||||
|
||||
const setResponse = await sendRequest(ws, WS_METHODS.serverSetRendererState, {
|
||||
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
});
|
||||
expect(setResponse.error).toBeUndefined();
|
||||
|
||||
const loaded = await sendRequest(ws, WS_METHODS.serverGetRendererState);
|
||||
expect(loaded.error).toBeUndefined();
|
||||
expect(loaded.result).toMatchObject({
|
||||
stateJson:
|
||||
'{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("persists renderer state across server restarts", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-renderer-state-restart-");
|
||||
server = createTestServer({ cwd: "/workspace", stateDir });
|
||||
await server.start();
|
||||
const firstAddr = server.httpServer.address();
|
||||
const firstPort = typeof firstAddr === "object" && firstAddr !== null ? firstAddr.port : 0;
|
||||
|
||||
const firstWs = await connectWs(firstPort);
|
||||
connections.push(firstWs);
|
||||
await waitForMessage(firstWs);
|
||||
const setResponse = await sendRequest(firstWs, WS_METHODS.serverSetRendererState, {
|
||||
stateJson:
|
||||
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
});
|
||||
expect(setResponse.error).toBeUndefined();
|
||||
|
||||
await server.stop();
|
||||
server = createTestServer({ cwd: "/workspace", stateDir });
|
||||
await server.start();
|
||||
const secondAddr = server.httpServer.address();
|
||||
const secondPort =
|
||||
typeof secondAddr === "object" && secondAddr !== null ? secondAddr.port : 0;
|
||||
|
||||
const secondWs = await connectWs(secondPort);
|
||||
connections.push(secondWs);
|
||||
await waitForMessage(secondWs);
|
||||
|
||||
const loaded = await sendRequest(secondWs, WS_METHODS.serverGetRendererState);
|
||||
expect(loaded.error).toBeUndefined();
|
||||
expect(loaded.result).toMatchObject({
|
||||
stateJson:
|
||||
'{"version":8,"projects":[{"id":"project-1","name":"project","cwd":"/workspace","model":"gpt-5.3-codex","expanded":true}],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("reads keybindings from ~/.t3/keybindings.json", async () => {
|
||||
const fakeHome = makeTempDir("t3code-home-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
@@ -591,30 +657,6 @@ 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");
|
||||
});
|
||||
|
||||
it("routes terminal RPC methods and broadcasts terminal events", async () => {
|
||||
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
|
||||
const terminalManager = new MockTerminalManager();
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from "./git";
|
||||
import { TerminalManager } from "./terminalManager";
|
||||
import { loadResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { RendererStateStore } from "./rendererStateStore";
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
@@ -52,12 +53,14 @@ export interface ServerOptions {
|
||||
port: number;
|
||||
host?: string | undefined;
|
||||
cwd: string;
|
||||
stateDir?: string | undefined;
|
||||
staticDir?: string | undefined;
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
rendererStateStore?: RendererStateStore | undefined;
|
||||
authToken?: string | undefined;
|
||||
}
|
||||
|
||||
@@ -74,18 +77,21 @@ export function createServer(options: ServerOptions) {
|
||||
port,
|
||||
host,
|
||||
cwd,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
rendererStateStore: providedRendererStateStore,
|
||||
authToken,
|
||||
} = options;
|
||||
const providerManager = new ProviderManager();
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata");
|
||||
const projectRegistry = providedRegistry ?? new ProjectRegistry(resolvedStateDir);
|
||||
const rendererStateStore = providedRendererStateStore ?? new RendererStateStore(resolvedStateDir);
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
@@ -309,12 +315,6 @@ 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.providersRevertToCheckpoint:
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
@@ -423,6 +423,13 @@ export function createServer(options: ServerOptions) {
|
||||
keybindings: keybindingsConfig,
|
||||
};
|
||||
|
||||
case WS_METHODS.serverGetRendererState:
|
||||
return rendererStateStore.get();
|
||||
|
||||
case WS_METHODS.serverSetRendererState:
|
||||
await rendererStateStore.set(request.params as never);
|
||||
return undefined;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown method: ${request.method}`);
|
||||
}
|
||||
@@ -452,6 +459,7 @@ export function createServer(options: ServerOptions) {
|
||||
providerManager.stopAll();
|
||||
providerManager.dispose();
|
||||
terminalManager.dispose();
|
||||
await rendererStateStore.close();
|
||||
|
||||
for (const client of clients) {
|
||||
client.close();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
name: "main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
describe("deriveSyncedLocalBranch", () => {
|
||||
it("syncs to git current branch in local mode", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBe("main");
|
||||
});
|
||||
|
||||
it("does not sync when creating a new worktree", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: null,
|
||||
envMode: "worktree",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("does not sync when thread already targets a worktree path", () => {
|
||||
const result = deriveSyncedLocalBranch({
|
||||
activeThreadId: "thread-1",
|
||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
||||
envMode: "local",
|
||||
activeThreadBranch: "feature/demo",
|
||||
queryBranches: branches,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
|
||||
interface DeriveSyncedLocalBranchInput {
|
||||
activeThreadId: string | undefined;
|
||||
activeWorktreePath: string | null;
|
||||
envMode: "local" | "worktree";
|
||||
activeThreadBranch: string | null;
|
||||
queryBranches: GitBranch[] | undefined;
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
}: DeriveSyncedLocalBranchInput): string | null {
|
||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return currentBranch.name;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -86,17 +87,22 @@ export default function BranchToolbar({
|
||||
// Keep thread branch synced to git current branch for local threads.
|
||||
const queryBranches = branchesQuery.data?.branches;
|
||||
useEffect(() => {
|
||||
if (!activeThreadId || activeWorktreePath) return;
|
||||
const current = queryBranches?.find((branch) => branch.current);
|
||||
if (!current) return;
|
||||
if (current.name === activeThreadBranch) return;
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: current.name,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ProviderCheckpoint,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderSendTurnAttachmentInput,
|
||||
@@ -152,9 +151,6 @@ export default function ChatView() {
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isLoadingCheckpoints, setIsLoadingCheckpoints] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [checkpoints, setCheckpoints] = useState<ProviderCheckpoint[]>([]);
|
||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
|
||||
@@ -178,7 +174,7 @@ export default function ChatView() {
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||
const isWorking = phase === "running" || isSending || isConnecting;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
@@ -298,12 +294,6 @@ export default function ChatView() {
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const canCheckpoint =
|
||||
Boolean(api && activeThread && (activeThread.codexThreadId ?? activeThread.session?.threadId)) &&
|
||||
phase !== "running" &&
|
||||
!isSending &&
|
||||
!isConnecting &&
|
||||
!isRevertingCheckpoint;
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
@@ -446,12 +436,6 @@ export default function ChatView() {
|
||||
setExpandedWorkGroups({});
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
setCheckpoints([]);
|
||||
setIsLoadingCheckpoints(false);
|
||||
setIsRevertingCheckpoint(false);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || activeThread.terminalOpen) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -783,78 +767,6 @@ export default function ChatView() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadCheckpoints = async (): Promise<ProviderCheckpoint[] | null> => {
|
||||
if (!api || !activeThread) return null;
|
||||
if (phase === "running" || isSending || isConnecting || isRevertingCheckpoint) {
|
||||
return null;
|
||||
}
|
||||
const hasThreadIdentity = Boolean(activeThread.codexThreadId ?? activeThread.session?.threadId);
|
||||
if (!hasThreadIdentity) {
|
||||
setCheckpoints([]);
|
||||
return [];
|
||||
}
|
||||
|
||||
setIsLoadingCheckpoints(true);
|
||||
setThreadError(activeThread.id, null);
|
||||
try {
|
||||
const sessionInfo = await ensureSession();
|
||||
if (!sessionInfo) {
|
||||
return null;
|
||||
}
|
||||
const result = await api.providers.listCheckpoints({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
});
|
||||
setCheckpoints(result.checkpoints);
|
||||
return result.checkpoints;
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to load checkpoints.",
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setIsLoadingCheckpoints(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onRevertToCheckpoint = async (checkpoint: ProviderCheckpoint) => {
|
||||
if (!api || !activeThread || checkpoint.isCurrent || isRevertingCheckpoint) {
|
||||
return;
|
||||
}
|
||||
if (phase === "running" || isSending || isConnecting) {
|
||||
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||
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: checkpoint.turnCount,
|
||||
});
|
||||
dispatch({
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
threadRuntimeId: result.threadId,
|
||||
messageCount: result.messageCount,
|
||||
});
|
||||
setCheckpoints(result.checkpoints);
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to revert checkpoint.",
|
||||
);
|
||||
} finally {
|
||||
setIsRevertingCheckpoint(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSend = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!api || !activeThread || isSending || isConnecting) return;
|
||||
@@ -911,41 +823,48 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
setThreadError(activeThread.id, null);
|
||||
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
setIsSending(true);
|
||||
try {
|
||||
const turnAttachments = await Promise.all(
|
||||
composerImagesSnapshot.map(
|
||||
async (image): Promise<ProviderSendTurnAttachmentInput> => ({
|
||||
const preparedImages = await Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => {
|
||||
const attachment: ProviderSendTurnAttachmentInput = {
|
||||
type: "image",
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
}),
|
||||
),
|
||||
};
|
||||
return { image, attachment };
|
||||
}),
|
||||
);
|
||||
const turnAttachments = preparedImages.map(({ attachment }) => attachment);
|
||||
const messageAttachments: ChatImageAttachment[] = preparedImages.map(
|
||||
({ image, attachment }) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: attachment.dataUrl,
|
||||
}),
|
||||
);
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
setPrompt("");
|
||||
setComposerImages((existing) => {
|
||||
revokePreviewUrls(existing);
|
||||
return [];
|
||||
});
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
const shouldBootstrap =
|
||||
previousMessages.length > 0 &&
|
||||
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
|
||||
@@ -1086,14 +1005,6 @@ export default function ChatView() {
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={state.diffOpen}
|
||||
onToggleDiff={onToggleDiff}
|
||||
checkpoints={checkpoints}
|
||||
canCheckpoint={canCheckpoint}
|
||||
isLoadingCheckpoints={isLoadingCheckpoints}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onOpenCheckpoints={() => {
|
||||
void loadCheckpoints();
|
||||
}}
|
||||
onRevertToCheckpoint={onRevertToCheckpoint}
|
||||
/>
|
||||
</header>
|
||||
|
||||
@@ -1387,12 +1298,6 @@ interface ChatHeaderProps {
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
onToggleDiff: () => void;
|
||||
checkpoints: ProviderCheckpoint[];
|
||||
canCheckpoint: boolean;
|
||||
isLoadingCheckpoints: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
onOpenCheckpoints: () => void;
|
||||
onRevertToCheckpoint: (checkpoint: ProviderCheckpoint) => void;
|
||||
}
|
||||
|
||||
const ChatHeader = memo(function ChatHeader({
|
||||
@@ -1403,12 +1308,6 @@ const ChatHeader = memo(function ChatHeader({
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
onToggleDiff,
|
||||
checkpoints,
|
||||
canCheckpoint,
|
||||
isLoadingCheckpoints,
|
||||
isRevertingCheckpoint,
|
||||
onOpenCheckpoints,
|
||||
onRevertToCheckpoint,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
@@ -1419,46 +1318,6 @@ const ChatHeader = memo(function ChatHeader({
|
||||
<div className="flex items-center gap-3">
|
||||
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
|
||||
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={!canCheckpoint || isRevertingCheckpoint}
|
||||
onClick={onOpenCheckpoints}
|
||||
>
|
||||
{isRevertingCheckpoint
|
||||
? "Reverting..."
|
||||
: isLoadingCheckpoints
|
||||
? "Loading..."
|
||||
: "Checkpoints"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<MenuPopup align="end" className="w-72">
|
||||
{!canCheckpoint ? (
|
||||
<MenuItem disabled>Send at least one message to create checkpoints.</MenuItem>
|
||||
) : checkpoints.length === 0 ? (
|
||||
<MenuItem disabled>
|
||||
{isLoadingCheckpoints ? "Loading checkpoints..." : "No checkpoints available."}
|
||||
</MenuItem>
|
||||
) : (
|
||||
checkpoints.map((checkpoint) => (
|
||||
<MenuItem
|
||||
key={checkpoint.id}
|
||||
disabled={checkpoint.isCurrent || isRevertingCheckpoint}
|
||||
onClick={() => onRevertToCheckpoint(checkpoint)}
|
||||
>
|
||||
{checkpoint.label}
|
||||
{checkpoint.preview ? `: ${checkpoint.preview}` : ""}
|
||||
{checkpoint.isCurrent ? " (Current)" : ""}
|
||||
</MenuItem>
|
||||
))
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
|
||||
@@ -257,10 +257,65 @@ describe("hydratePersistedState", () => {
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("hydrates persisted image preview data urls", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 8,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Here",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.messages[0]?.attachments?.[0]?.previewUrl).toBe(
|
||||
"data:image/png;base64,AAAA",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v8 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
@@ -320,7 +375,7 @@ describe("toPersistedState", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.version).toBe(8);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
@@ -367,4 +422,69 @@ describe("toPersistedState", () => {
|
||||
expect("error" in persistedThread).toBe(false);
|
||||
expect("session" in persistedThread).toBe(false);
|
||||
});
|
||||
|
||||
it("persists preview data urls for image attachments", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Image",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
};
|
||||
|
||||
const persisted = toPersistedState({
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [thread],
|
||||
activeThreadId: "t-1",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.threads[0]?.messages[0]?.attachments?.[0]).toMatchObject({
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
previewUrl: "data:image/png;base64,AAAA",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -33,6 +33,7 @@ const persistedMessageSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
previewUrl: z.string().min(1).optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
@@ -103,12 +104,18 @@ export const persistedStateV7Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(7).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV8Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(8).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV5Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(5).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV8Schema,
|
||||
persistedStateV7Schema,
|
||||
persistedStateV6Schema,
|
||||
persistedStateV5Schema,
|
||||
@@ -252,7 +259,14 @@ function hydrateThread(
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
...(attachment.previewUrl ? { previewUrl: attachment.previewUrl } : {}),
|
||||
}));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
@@ -312,9 +326,9 @@ export function hydratePersistedState(
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
): z.infer<typeof persistedStateV8Schema> {
|
||||
return {
|
||||
version: 7,
|
||||
version: 8,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
@@ -340,6 +354,9 @@ export function toPersistedState(
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
...(attachment.previewUrl && /^data:image\//i.test(attachment.previewUrl)
|
||||
? { previewUrl: attachment.previewUrl }
|
||||
: {}),
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -574,66 +574,4 @@ 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",
|
||||
}),
|
||||
],
|
||||
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",
|
||||
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();
|
||||
});
|
||||
});
|
||||
+106
-58
@@ -5,13 +5,19 @@ import {
|
||||
createElement,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useReducer,
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
import {
|
||||
type PersistedStoreSnapshot,
|
||||
hydratePersistedState,
|
||||
toPersistedState,
|
||||
} from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession, readNativeApi } from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
@@ -25,6 +31,7 @@ import {
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
|
||||
type Action =
|
||||
| { type: "HYDRATE_PERSISTED_STATE"; snapshot: PersistedStoreSnapshot }
|
||||
| { type: "ADD_PROJECT"; project: Project }
|
||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||
@@ -56,13 +63,6 @@ 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;
|
||||
messageCount: number;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: string;
|
||||
@@ -82,8 +82,10 @@ export interface AppState {
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const LEGACY_PERSISTED_STATE_PRIMARY_KEY = "t3code:renderer-state:v8";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
LEGACY_PERSISTED_STATE_PRIMARY_KEY,
|
||||
"t3code:renderer-state:v7",
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
@@ -104,35 +106,30 @@ const initialState: AppState = {
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
function readLegacyPersistedStateFromLocalStorage(): PersistedStoreSnapshot | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
|
||||
try {
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawCurrent = window.localStorage.getItem(LEGACY_PERSISTED_STATE_PRIMARY_KEY);
|
||||
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
|
||||
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
if (!raw) return null;
|
||||
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
|
||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
if (!hydrated) return initialState;
|
||||
|
||||
return { ...hydrated, diffOpen: false };
|
||||
return hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||
} catch {
|
||||
return initialState;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistState(state: AppState): void {
|
||||
function clearLegacyPersistedStateFromLocalStorage(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
window.localStorage.setItem(PERSISTED_STATE_KEY, JSON.stringify(toPersistedState(state)));
|
||||
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
|
||||
window.localStorage.removeItem(legacyKey);
|
||||
}
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
// Ignore storage errors.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,6 +413,16 @@ function updateTurnFields(thread: Thread, event: ProviderEvent): Partial<Thread>
|
||||
|
||||
export function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "HYDRATE_PERSISTED_STATE":
|
||||
return {
|
||||
...state,
|
||||
projects: action.snapshot.projects,
|
||||
threads: action.snapshot.threads,
|
||||
activeThreadId: action.snapshot.activeThreadId,
|
||||
runtimeMode: action.snapshot.runtimeMode,
|
||||
diffOpen: false,
|
||||
};
|
||||
|
||||
case "ADD_PROJECT":
|
||||
if (state.projects.some((project) => project.cwd === action.project.cwd)) {
|
||||
return state;
|
||||
@@ -805,38 +812,6 @@ 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 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: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
lastVisitedAt: now,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
@@ -881,11 +856,84 @@ const StoreContext = createContext<{
|
||||
}>({ state: initialState, dispatch: () => {} });
|
||||
|
||||
export function StoreProvider({ children }: { children: ReactNode }) {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
const [persistenceReady, setPersistenceReady] = useState(false);
|
||||
const lastPersistedStateJsonRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
persistState(state);
|
||||
}, [state]);
|
||||
let disposed = false;
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
setPersistenceReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const serverSnapshot = await api.server.getRendererState();
|
||||
if (disposed) return;
|
||||
|
||||
const hydratedFromServer = serverSnapshot
|
||||
? hydratePersistedState(serverSnapshot.stateJson, false)
|
||||
: null;
|
||||
if (hydratedFromServer) {
|
||||
lastPersistedStateJsonRef.current = serverSnapshot?.stateJson ?? null;
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedFromServer });
|
||||
clearLegacyPersistedStateFromLocalStorage();
|
||||
return;
|
||||
}
|
||||
|
||||
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
|
||||
if (!hydratedLegacy) return;
|
||||
const migratedStateJson = JSON.stringify(toPersistedState(hydratedLegacy));
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
|
||||
try {
|
||||
await api.server.setRendererState({ stateJson: migratedStateJson });
|
||||
if (!disposed) {
|
||||
lastPersistedStateJsonRef.current = migratedStateJson;
|
||||
clearLegacyPersistedStateFromLocalStorage();
|
||||
}
|
||||
} catch {
|
||||
// Keep running with hydrated legacy state. Persist effect will retry.
|
||||
}
|
||||
} catch {
|
||||
if (disposed) return;
|
||||
const hydratedLegacy = readLegacyPersistedStateFromLocalStorage();
|
||||
if (hydratedLegacy) {
|
||||
dispatch({ type: "HYDRATE_PERSISTED_STATE", snapshot: hydratedLegacy });
|
||||
}
|
||||
} finally {
|
||||
if (!disposed) {
|
||||
setPersistenceReady(true);
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, [dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!persistenceReady) return;
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
|
||||
const stateJson = JSON.stringify(toPersistedState(state));
|
||||
if (lastPersistedStateJsonRef.current === stateJson) return;
|
||||
const persistTimer = window.setTimeout(() => {
|
||||
void api.server
|
||||
.setRendererState({ stateJson })
|
||||
.then(() => {
|
||||
lastPersistedStateJsonRef.current = stateJson;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, 150);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(persistTimer);
|
||||
};
|
||||
}, [persistenceReady, state]);
|
||||
|
||||
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
|
||||
}
|
||||
|
||||
@@ -91,9 +91,6 @@ 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),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
|
||||
},
|
||||
@@ -144,6 +141,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
getRendererState: () => transport.request(WS_METHODS.serverGetRendererState),
|
||||
setRendererState: (input) => transport.request(WS_METHODS.serverSetRendererState, input),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
+2
-1
@@ -19,7 +19,8 @@
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts"
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo"
|
||||
},
|
||||
"devDependencies": {
|
||||
"oxfmt": "^0.28.0",
|
||||
|
||||
@@ -7,5 +7,6 @@ export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./rendererState";
|
||||
export * from "./project";
|
||||
export * from "./git";
|
||||
@@ -18,10 +18,6 @@ import type {
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderListCheckpointsInput,
|
||||
ProviderListCheckpointsResult,
|
||||
ProviderRevertToCheckpointInput,
|
||||
ProviderRevertToCheckpointResult,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
@@ -36,6 +32,7 @@ import type {
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type { RendererStateSetInput, RendererStateSnapshot } from "./rendererState";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -88,10 +85,6 @@ export interface NativeApi {
|
||||
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
listCheckpoints: (input: ProviderListCheckpointsInput) => Promise<ProviderListCheckpointsResult>;
|
||||
revertToCheckpoint: (
|
||||
input: ProviderRevertToCheckpointInput,
|
||||
) => Promise<ProviderRevertToCheckpointResult>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
@@ -124,5 +117,7 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
getRendererState: () => Promise<RendererStateSnapshot | null>;
|
||||
setRendererState: (input: RendererStateSetInput) => Promise<void>;
|
||||
};
|
||||
}
|
||||
@@ -2,12 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
providerCheckpointSchema,
|
||||
providerEventSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerListCheckpointsResultSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRevertToCheckpointResultSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
@@ -162,71 +157,3 @@ 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();
|
||||
});
|
||||
});
|
||||
@@ -111,37 +111,6 @@ 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 providerRespondToRequestInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1),
|
||||
@@ -182,13 +151,6 @@ 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 ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { rendererStateSetInputSchema, rendererStateSnapshotSchema } from "./rendererState";
|
||||
|
||||
describe("rendererState contracts", () => {
|
||||
it("parses renderer state snapshot", () => {
|
||||
const parsed = rendererStateSnapshotSchema.parse({
|
||||
stateJson: '{"version":8,"projects":[],"threads":[],"activeThreadId":null,"runtimeMode":"full-access"}',
|
||||
updatedAt: "2026-02-18T10:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(parsed.updatedAt).toBe("2026-02-18T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("requires non-empty stateJson for set input", () => {
|
||||
expect(() => rendererStateSetInputSchema.parse({ stateJson: "" })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const RENDERER_STATE_MAX_JSON_CHARS = 25_000_000;
|
||||
|
||||
export const rendererStateSnapshotSchema = z.object({
|
||||
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
|
||||
updatedAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
export const rendererStateSetInputSchema = z.object({
|
||||
stateJson: z.string().min(1).max(RENDERER_STATE_MAX_JSON_CHARS),
|
||||
});
|
||||
|
||||
export type RendererStateSnapshot = z.infer<typeof rendererStateSnapshotSchema>;
|
||||
export type RendererStateSetInput = z.input<typeof rendererStateSetInputSchema>;
|
||||
@@ -10,8 +10,6 @@ export const WS_METHODS = {
|
||||
providersRespondToRequest: "providers.respondToRequest",
|
||||
providersStopSession: "providers.stopSession",
|
||||
providersListSessions: "providers.listSessions",
|
||||
providersListCheckpoints: "providers.listCheckpoints",
|
||||
providersRevertToCheckpoint: "providers.revertToCheckpoint",
|
||||
|
||||
// Project registry methods
|
||||
projectsList: "projects.list",
|
||||
@@ -42,6 +40,8 @@ export const WS_METHODS = {
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverGetRendererState: "server.getRendererState",
|
||||
serverSetRendererState: "server.setRendererState",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user