Compare commits

..
Author SHA1 Message Date
Julius Marminge b7bbcb2054 Ignore non-keydown terminal shortcuts
- guard terminal clear/navigation shortcut handlers to only process `keydown`
- add tests verifying `keyup` events are ignored
2026-02-15 17:02:38 -08:00
Julius Marminge 9547718175 Add terminal word and line navigation arrow shortcuts
- handle platform-specific modifier+arrow combos in terminal input
- reuse terminal write path for clear and navigation actions
- add shortcut tests for macOS and non-macOS mappings
2026-02-15 16:43:04 -08:00
29 changed files with 449 additions and 2289 deletions

No files matched your search

+2 -7
View File
@@ -22,10 +22,7 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
{ "key": "mod+j", "command": "terminal.toggle" }, { "key": "mod+j", "command": "terminal.toggle" },
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" }, { "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" }, { "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" }, { "key": "mod+shift+o", "command": "chat.new" },
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
{ "key": "mod+o", "command": "editor.openFavorite" } { "key": "mod+o", "command": "editor.openFavorite" }
] ]
``` ```
@@ -49,9 +46,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.toggle`: open/close terminal drawer - `terminal.toggle`: open/close terminal drawer
- `terminal.split`: split terminal (in focused terminal context by default) - `terminal.split`: split terminal (in focused terminal context by default)
- `terminal.new`: create new terminal (in focused terminal context by default) - `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default) - `chat.new`: create a new chat thread for the active project
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor - `editor.openFavorite`: open current project/worktree in the last-used editor
### Key Syntax ### Key Syntax
@@ -43,36 +43,6 @@ function createSendTurnHarness() {
return { manager, context, requireSession, sendRequest, updateSession }; 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", () => { describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => { it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull(); expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -228,62 +198,3 @@ describe("sendTurn", () => {
).rejects.toThrow("Turn input must include text or attachments."); ).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: [],
});
});
});
-80
View File
@@ -65,16 +65,6 @@ interface JsonRpcNotification {
params?: unknown; 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_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g"); const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
const CODEX_STDERR_LOG_REGEX = 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( async respondToRequest(
sessionId: string, sessionId: string,
requestId: string, requestId: string,
@@ -787,31 +742,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return undefined; 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 { private isServerRequest(value: unknown): value is JsonRpcRequest {
if (!value || typeof value !== "object") { if (!value || typeof value !== "object") {
return false; return false;
@@ -893,16 +823,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return target as Record<string, unknown>; 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 { private readString(value: unknown, key: string): string | undefined {
if (!value || typeof value !== "object") { if (!value || typeof value !== "object") {
return undefined; 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;
}
}
+1 -4
View File
@@ -28,10 +28,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" }, { key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" }, { key: "mod+d", command: "terminal.split", when: "terminalFocus" },
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" }, { key: "mod+n", command: "terminal.new", when: "terminalFocus" },
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" }, { key: "mod+shift+o", command: "chat.new" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+o", command: "editor.openFavorite" }, { key: "mod+o", command: "editor.openFavorite" },
]; ];
+1 -252
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it } from "vitest";
import { ProviderManager } from "./providerManager"; import { ProviderManager } from "./providerManager";
@@ -59,255 +59,4 @@ describe("ProviderManager", () => {
manager.dispose(); 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();
});
}); });
-312
View File
@@ -1,16 +1,10 @@
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { randomUUID } from "node:crypto";
import { import {
type ProviderCheckpoint,
type ProviderEvent, type ProviderEvent,
type ProviderInterruptTurnInput, type ProviderInterruptTurnInput,
type ProviderListCheckpointsInput,
type ProviderListCheckpointsResult,
type ProviderRevertToCheckpointInput,
type ProviderRevertToCheckpointResult,
type ProviderRespondToRequestInput, type ProviderRespondToRequestInput,
type ProviderSendTurnInput, type ProviderSendTurnInput,
type ProviderSession, type ProviderSession,
@@ -18,154 +12,23 @@ import {
type ProviderStopSessionInput, type ProviderStopSessionInput,
type ProviderTurnStartResult, type ProviderTurnStartResult,
providerInterruptTurnInputSchema, providerInterruptTurnInputSchema,
providerListCheckpointsInputSchema,
providerRevertToCheckpointInputSchema,
providerRespondToRequestInputSchema, providerRespondToRequestInputSchema,
providerSendTurnInputSchema, providerSendTurnInputSchema,
providerSessionStartInputSchema, providerSessionStartInputSchema,
providerStopSessionInputSchema, providerStopSessionInputSchema,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
import { CodexAppServerManager } from "./codexAppServerManager"; import { CodexAppServerManager } from "./codexAppServerManager";
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
export interface ProviderManagerEvents { export interface ProviderManagerEvents {
event: [event: ProviderEvent]; 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> { export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
private readonly codex = new CodexAppServerManager(); private readonly codex = new CodexAppServerManager();
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
private readonly threadLogsDir: string; private readonly threadLogsDir: string;
private readonly threadLogStreams = new Map<string, fs.WriteStream>(); private readonly threadLogStreams = new Map<string, fs.WriteStream>();
private readonly sessionThreadIds = new Map<string, string>(); private readonly sessionThreadIds = new Map<string, string>();
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>(); 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 disposed = false;
private readonly onCodexEvent = (event: ProviderEvent) => { private readonly onCodexEvent = (event: ProviderEvent) => {
if (this.disposed) { if (this.disposed) {
@@ -174,7 +37,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.routeEventToThreadLog(event); this.routeEventToThreadLog(event);
this.emit("event", event); this.emit("event", event);
this.maybeCaptureFilesystemCheckpoint(event);
}; };
constructor() { constructor() {
@@ -198,11 +60,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.sessionThreadIds.set(session.sessionId, session.threadId); this.sessionThreadIds.set(session.sessionId, session.threadId);
this.flushPendingSessionEvents(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; return session;
} }
@@ -238,99 +95,12 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.codex.stopSession(input.sessionId); this.codex.stopSession(input.sessionId);
this.sessionThreadIds.delete(input.sessionId); this.sessionThreadIds.delete(input.sessionId);
this.pendingEventsBySession.delete(input.sessionId); this.pendingEventsBySession.delete(input.sessionId);
this.sessionCheckpointCwds.delete(input.sessionId);
this.filesystemLocks.delete(input.sessionId);
} }
listSessions(): ProviderSession[] { listSessions(): ProviderSession[] {
return this.codex.listSessions(); 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 { stopAll(): void {
this.codex.stopAll(); this.codex.stopAll();
} }
@@ -348,88 +118,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
this.threadLogStreams.clear(); this.threadLogStreams.clear();
this.sessionThreadIds.clear(); this.sessionThreadIds.clear();
this.pendingEventsBySession.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 { private routeEventToThreadLog(event: ProviderEvent): void {
-24
View File
@@ -591,30 +591,6 @@ describe("WebSocket Server", () => {
expect(response.result).toEqual([]); 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 () => { it("routes terminal RPC methods and broadcasts terminal events", async () => {
const cwd = makeTempDir("t3code-ws-terminal-cwd-"); const cwd = makeTempDir("t3code-ws-terminal-cwd-");
const terminalManager = new MockTerminalManager(); const terminalManager = new MockTerminalManager();
-6
View File
@@ -309,12 +309,6 @@ export function createServer(options: ServerOptions) {
case WS_METHODS.providersListSessions: case WS_METHODS.providersListSessions:
return providerManager.listSessions(); 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: case WS_METHODS.projectsList:
return projectRegistry.list(); return projectRegistry.list();
+1 -4
View File
@@ -1,4 +1,3 @@
import { memo } from "react";
import type { Components } from "react-markdown"; import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown"; import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight"; import rehypeHighlight from "rehype-highlight";
@@ -14,7 +13,7 @@ const markdownComponents: Components = {
}, },
}; };
function ChatMarkdown({ text }: ChatMarkdownProps) { export default function ChatMarkdown({ text }: ChatMarkdownProps) {
return ( return (
<div className="chat-markdown text-sm leading-relaxed text-foreground/80"> <div className="chat-markdown text-sm leading-relaxed text-foreground/80">
<ReactMarkdown <ReactMarkdown
@@ -27,5 +26,3 @@ function ChatMarkdown({ text }: ChatMarkdownProps) {
</div> </div>
); );
} }
export default memo(ChatMarkdown);
File diff suppressed because it is too large. Load diff
@@ -312,10 +312,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
title: resultToast.title, title: resultToast.title,
description: resultToast.description, description: resultToast.description,
timeout: 0, timeout: 0,
data: { data: threadToastData,
...threadToastData,
dismissAfterVisibleMs: 10_000,
},
...(shouldOfferPushCta ...(shouldOfferPushCta
? { ? {
actionProps: { actionProps: {
+8 -23
View File
@@ -7,7 +7,7 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic"; import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic"; import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store"; import { useStore } from "../store";
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings"; import { isChatNewShortcut } from "../keybindings";
import { import {
DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID, DEFAULT_THREAD_TERMINAL_ID,
@@ -140,13 +140,7 @@ export default function Sidebar() {
}, [state.threads]); }, [state.threads]);
const handleNewThread = useCallback( const handleNewThread = useCallback(
( (projectId: string) => {
projectId: string,
options?: {
branch?: string | null;
worktreePath?: string | null;
},
) => {
dispatch({ dispatch({
type: "ADD_THREAD", type: "ADD_THREAD",
thread: { thread: {
@@ -172,8 +166,8 @@ export default function Sidebar() {
events: [], events: [],
error: null, error: null,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
branch: options?.branch ?? null, branch: null,
worktreePath: options?.worktreePath ?? null, worktreePath: null,
}, },
}); });
}, },
@@ -387,23 +381,14 @@ export default function Sidebar() {
useEffect(() => { useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => { const onWindowKeyDown = (event: KeyboardEvent) => {
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
handleNewThread(projectId);
return;
}
if (!isChatNewShortcut(event, keybindings)) return; if (!isChatNewShortcut(event, keybindings)) return;
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id; const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return; if (!projectId) return;
event.preventDefault(); event.preventDefault();
handleNewThread(projectId, { handleNewThread(projectId);
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
}; };
window.addEventListener("keydown", onWindowKeyDown); window.addEventListener("keydown", onWindowKeyDown);
@@ -1,5 +1,5 @@
import { FitAddon } from "@xterm/addon-fit"; import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react"; import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts"; import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm"; import { Terminal, type ITheme } from "@xterm/xterm";
import { import {
@@ -18,7 +18,10 @@ import {
preferredTerminalEditor, preferredTerminalEditor,
resolvePathLinkTarget, resolvePathLinkTarget,
} from "../terminal-links"; } from "../terminal-links";
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings"; import {
isTerminalClearShortcut,
terminalNavigationShortcutData,
} from "../keybindings";
import { import {
DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID, DEFAULT_THREAD_TERMINAL_ID,
@@ -158,7 +161,10 @@ function TerminalViewport({
try { try {
await api.terminal.write({ threadId, terminalId, data }); await api.terminal.write({ threadId, terminalId, data });
} catch (error) { } catch (error) {
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError); writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : fallbackError,
);
} }
}; };
@@ -423,7 +429,6 @@ interface ThreadTerminalDrawerProps {
onNewTerminal: () => void; onNewTerminal: () => void;
splitShortcutLabel?: string | undefined; splitShortcutLabel?: string | undefined;
newShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined;
closeShortcutLabel?: string | undefined;
onActiveTerminalChange: (terminalId: string) => void; onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void; onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void; onHeightChange: (height: number) => void;
@@ -439,9 +444,15 @@ interface TerminalActionButtonProps {
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) { function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
return ( return (
<Popover> <Popover>
<PopoverTrigger <PopoverTrigger openOnHover
openOnHover render={
render={<button type="button" className={className} onClick={onClick} aria-label={label} />} <button
type="button"
className={className}
onClick={onClick}
aria-label={label}
/>
}
> >
{children} {children}
</PopoverTrigger> </PopoverTrigger>
@@ -472,7 +483,6 @@ export default function ThreadTerminalDrawer({
onNewTerminal, onNewTerminal,
splitShortcutLabel, splitShortcutLabel,
newShortcutLabel, newShortcutLabel,
closeShortcutLabel,
onActiveTerminalChange, onActiveTerminalChange,
onCloseTerminal, onCloseTerminal,
onHeightChange, onHeightChange,
@@ -588,9 +598,6 @@ export default function ThreadTerminalDrawer({
), ),
[normalizedTerminalIds], [normalizedTerminalIds],
); );
const closeTerminalActionLabel = closeShortcutLabel
? `Close Terminal (${closeShortcutLabel})`
: "Close Terminal";
useEffect(() => { useEffect(() => {
onHeightChangeRef.current = onHeightChange; onHeightChangeRef.current = onHeightChange;
@@ -702,9 +709,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton <TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent" className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal} onClick={onSplitTerminal}
label={ label={splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"}
splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal"
}
> >
<SquareSplitHorizontal className="size-3.25" /> <SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton> </TerminalActionButton>
@@ -720,7 +725,7 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton <TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent" className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)} onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel} label="Close Terminal"
> >
<Trash2 className="size-3.25" /> <Trash2 className="size-3.25" />
</TerminalActionButton> </TerminalActionButton>
@@ -800,14 +805,16 @@ export default function ThreadTerminalDrawer({
<TerminalActionButton <TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70" className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal} onClick={onNewTerminal}
label={newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"} label={
newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal"
}
> >
<Plus className="size-3.25" /> <Plus className="size-3.25" />
</TerminalActionButton> </TerminalActionButton>
<TerminalActionButton <TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70" className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)} onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label={closeTerminalActionLabel} label="Close Terminal"
> >
<Trash2 className="size-3.25" /> <Trash2 className="size-3.25" />
</TerminalActionButton> </TerminalActionButton>
@@ -845,9 +852,6 @@ export default function ThreadTerminalDrawer({
> >
{terminalGroup.terminalIds.map((terminalId) => { {terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId; const isActive = terminalId === resolvedActiveTerminalId;
const closeTerminalLabel = `Close ${
terminalLabelById.get(terminalId) ?? "terminal"
}${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
return ( return (
<div <div
key={terminalId} key={terminalId}
@@ -871,30 +875,18 @@ export default function ThreadTerminalDrawer({
</span> </span>
</button> </button>
{normalizedTerminalIds.length > 1 && ( {normalizedTerminalIds.length > 1 && (
<Popover> <button
<PopoverTrigger type="button"
openOnHover className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
render={ onClick={(event) => {
<button event.stopPropagation();
type="button" onCloseTerminal(terminalId);
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100" }}
onClick={() => onCloseTerminal(terminalId)} aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
aria-label={closeTerminalLabel} title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
/> >
} ×
> </button>
<XIcon className="size-2.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="bottom"
sideOffset={6}
align="center"
className="pointer-events-none select-none"
>
{closeTerminalLabel}
</PopoverPopup>
</Popover>
)} )}
</div> </div>
); );
@@ -1,16 +0,0 @@
import { assert, describe, it } from "vitest";
import { shouldHideCollapsedToastContent } from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
assert.equal(shouldHideCollapsedToastContent(0, 1), false);
});
it("keeps the front-most toast readable in a visible stack", () => {
assert.equal(shouldHideCollapsedToastContent(0, 3), false);
});
it("hides non-front toasts until the stack is expanded", () => {
assert.equal(shouldHideCollapsedToastContent(1, 3), true);
});
});
@@ -1,9 +0,0 @@
export function shouldHideCollapsedToastContent(
visibleToastIndex: number,
visibleToastCount: number,
): boolean {
// Keep the front-most toast readable even if Base UI marks it as "behind"
// due to toasts hidden by thread filtering.
if (visibleToastCount <= 1) return false;
return visibleToastIndex > 0;
}
+84 -190
View File
@@ -1,7 +1,6 @@
"use client"; "use client";
import { Toast } from "@base-ui/react/toast"; import { Toast } from "@base-ui/react/toast";
import { useEffect } from "react";
import { import {
CircleAlertIcon, CircleAlertIcon,
CircleCheckIcon, CircleCheckIcon,
@@ -13,18 +12,14 @@ import {
import { cn } from "~/lib/utils"; import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button"; import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store"; import { useStore } from "~/store";
import { shouldHideCollapsedToastContent } from "./toast.logic";
type ThreadToastData = { type ThreadToastData = {
threadId?: string | null; threadId?: string | null;
tooltipStyle?: boolean; tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
}; };
const toastManager = Toast.createToastManager<ThreadToastData>(); const toastManager = Toast.createToastManager<ThreadToastData>();
const anchoredToastManager = Toast.createToastManager<ThreadToastData>(); const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
type ToastId = ReturnType<typeof toastManager.add>;
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
const TOAST_ICONS = { const TOAST_ICONS = {
error: CircleAlertIcon, error: CircleAlertIcon,
@@ -55,84 +50,6 @@ function shouldRenderForActiveThread(
return toastThreadId === activeThreadId; return toastThreadId === activeThreadId;
} }
function ThreadToastVisibleAutoDismiss({
toastId,
dismissAfterVisibleMs,
}: {
toastId: ToastId;
dismissAfterVisibleMs: number | undefined;
}) {
useEffect(() => {
if (!dismissAfterVisibleMs || dismissAfterVisibleMs <= 0) return;
if (typeof window === "undefined" || typeof document === "undefined") return;
let remainingMs = threadToastVisibleTimeoutRemainingMs.get(toastId) ?? dismissAfterVisibleMs;
let startedAtMs: number | null = null;
let timeoutId: number | null = null;
let closed = false;
const clearTimer = () => {
if (timeoutId === null) return;
window.clearTimeout(timeoutId);
timeoutId = null;
};
const closeToast = () => {
if (closed) return;
closed = true;
threadToastVisibleTimeoutRemainingMs.delete(toastId);
toastManager.close(toastId);
};
const pause = () => {
if (startedAtMs === null) return;
remainingMs = Math.max(0, remainingMs - (Date.now() - startedAtMs));
startedAtMs = null;
clearTimer();
threadToastVisibleTimeoutRemainingMs.set(toastId, remainingMs);
};
const start = () => {
if (closed || startedAtMs !== null) return;
if (remainingMs <= 0) {
closeToast();
return;
}
startedAtMs = Date.now();
clearTimer();
timeoutId = window.setTimeout(() => {
remainingMs = 0;
startedAtMs = null;
closeToast();
}, remainingMs);
};
const syncTimer = () => {
const shouldRun = document.visibilityState === "visible" && document.hasFocus();
if (shouldRun) {
start();
return;
}
pause();
};
syncTimer();
document.addEventListener("visibilitychange", syncTimer);
window.addEventListener("focus", syncTimer);
window.addEventListener("blur", syncTimer);
return () => {
document.removeEventListener("visibilitychange", syncTimer);
window.removeEventListener("focus", syncTimer);
window.removeEventListener("blur", syncTimer);
pause();
clearTimer();
};
}, [dismissAfterVisibleMs, toastId]);
return null;
}
function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) { function ToastProvider({ children, position = "top-right", ...props }: ToastProviderProps) {
return ( return (
<Toast.Provider toastManager={toastManager} {...props}> <Toast.Provider toastManager={toastManager} {...props}>
@@ -147,18 +64,6 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>(); const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = state.activeThreadId; const activeThreadId = state.activeThreadId;
const isTop = position.startsWith("top"); const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
);
useEffect(() => {
const activeToastIds = new Set(toasts.map((toast) => toast.id));
for (const toastId of threadToastVisibleTimeoutRemainingMs.keys()) {
if (!activeToastIds.has(toastId)) {
threadToastVisibleTimeoutRemainingMs.delete(toastId);
}
}
}, [toasts]);
return ( return (
<Toast.Portal data-slot="toast-portal"> <Toast.Portal data-slot="toast-portal">
@@ -176,107 +81,96 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
data-position={position} data-position={position}
data-slot="toast-viewport" data-slot="toast-viewport"
> >
{visibleToasts.map((toast, visibleIndex) => { {toasts
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null; .filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
const hideCollapsedContent = shouldHideCollapsedToastContent( .map((toast) => {
visibleIndex, const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
visibleToasts.length,
);
return ( return (
<Toast.Root <Toast.Root
className={cn(
"absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
// Base positioning using data-position
"data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-starting-style:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-[position*=top]:data-[position*=right]:data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateX(calc(100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<ThreadToastVisibleAutoDismiss
dismissAfterVisibleMs={toast.data?.dismissAfterVisibleMs}
toastId={toast.id}
/>
<Toast.Content
className={cn( className={cn(
"pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-expanded:opacity-100", "absolute z-[calc(9999-var(--toast-index))] h-(--toast-calc-height) w-full select-none rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 [transition:transform_.5s_cubic-bezier(.22,1,.36,1),opacity_.5s,height_.15s] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
hideCollapsedContent && // Base positioning using data-position
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0", "data-[position*=right]:right-0 data-[position*=right]:left-auto",
"data-[position*=left]:right-auto data-[position*=left]:left-0",
"data-[position*=center]:right-0 data-[position*=center]:left-0",
"data-[position*=top]:top-0 data-[position*=top]:bottom-auto data-[position*=top]:origin-top",
"data-[position*=bottom]:top-auto data-[position*=bottom]:bottom-0 data-[position*=bottom]:origin-bottom",
// Gap fill for hover
"after:absolute after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full",
"data-[position*=top]:after:top-full",
"data-[position*=bottom]:after:bottom-full",
// Define some variables
"[--toast-calc-height:var(--toast-frontmost-height,var(--toast-height))] [--toast-gap:--spacing(3)] [--toast-peek:--spacing(3)] [--toast-scale:calc(max(0,1-(var(--toast-index)*.1)))] [--toast-shrink:calc(1-var(--toast-scale))]",
// Define offset-y variable
"data-[position*=top]:[--toast-calc-offset-y:calc(var(--toast-offset-y)+var(--toast-index)*var(--toast-gap)+var(--toast-swipe-movement-y))]",
"data-[position*=bottom]:[--toast-calc-offset-y:calc(var(--toast-offset-y)*-1+var(--toast-index)*var(--toast-gap)*-1+var(--toast-swipe-movement-y))]",
// Default state transform
"data-[position*=top]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)+(var(--toast-index)*var(--toast-peek))+(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
"data-[position*=bottom]:transform-[translateX(var(--toast-swipe-movement-x))_translateY(calc(var(--toast-swipe-movement-y)-(var(--toast-index)*var(--toast-peek))-(var(--toast-shrink)*var(--toast-calc-height))))_scale(var(--toast-scale))]",
// Limited state
"data-limited:opacity-0",
// Expanded state
"data-expanded:h-(--toast-height)",
"data-position:data-expanded:transform-[translateX(var(--toast-swipe-movement-x))_translateY(var(--toast-calc-offset-y))]",
// Starting and ending animations
"data-[position*=top]:data-starting-style:transform-[translateY(calc(-100%-var(--toast-inset)))]",
"data-[position*=bottom]:data-starting-style:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)} )}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
> >
<div className="flex gap-2"> <Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
{Icon && ( <div className="flex gap-2">
<div {Icon && (
className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0" <div
data-slot="toast-icon" className="[&>svg]:h-lh [&>svg]:w-4 [&_svg]:pointer-events-none [&_svg]:shrink-0"
> data-slot="toast-icon"
<Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" /> >
</div> <Icon className="in-data-[type=loading]:animate-spin in-data-[type=error]:text-destructive in-data-[type=info]:text-info in-data-[type=success]:text-success in-data-[type=warning]:text-warning in-data-[type=loading]:opacity-80" />
)} </div>
)}
<div className="flex flex-col gap-0.5"> <div className="flex flex-col gap-0.5">
<Toast.Title className="font-medium" data-slot="toast-title" /> <Toast.Title className="font-medium" data-slot="toast-title" />
<Toast.Description <Toast.Description
className="text-muted-foreground" className="text-muted-foreground"
data-slot="toast-description" data-slot="toast-description"
/> />
</div>
</div> </div>
</div> {toast.actionProps && (
{toast.actionProps && ( <Toast.Action
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action"> className={buttonVariants({ size: "xs" })}
{toast.actionProps.children} data-slot="toast-action"
</Toast.Action> >
)} {toast.actionProps.children}
</Toast.Content> </Toast.Action>
</Toast.Root> )}
); </Toast.Content>
})} </Toast.Root>
);
})}
</Toast.Viewport> </Toast.Viewport>
</Toast.Portal> </Toast.Portal>
); );
+2 -43
View File
@@ -9,10 +9,8 @@ import {
import { import {
formatShortcutLabel, formatShortcutLabel,
isChatNewShortcut, isChatNewShortcut,
isChatNewLocalShortcut,
isOpenFavoriteEditorShortcut, isOpenFavoriteEditorShortcut,
isTerminalClearShortcut, isTerminalClearShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut, isTerminalNewShortcut,
isTerminalSplitShortcut, isTerminalSplitShortcut,
isTerminalToggleShortcut, isTerminalToggleShortcut,
@@ -85,13 +83,7 @@ const DEFAULT_BINDINGS = compile([
command: "terminal.new", command: "terminal.new",
whenAst: whenIdentifier("terminalFocus"), whenAst: whenIdentifier("terminalFocus"),
}, },
{
shortcut: modShortcut("w"),
command: "terminal.close",
whenAst: whenIdentifier("terminalFocus"),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" },
]); ]);
@@ -109,8 +101,8 @@ describe("isTerminalToggleShortcut", () => {
}); });
}); });
describe("split/new/close terminal shortcuts", () => { describe("split/new terminal shortcuts", () => {
it("requires terminalFocus for default split/new/close bindings", () => { it("requires terminalFocus for default split/new bindings", () => {
assert.isFalse( assert.isFalse(
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, { isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
platform: "MacIntel", platform: "MacIntel",
@@ -123,12 +115,6 @@ describe("split/new/close terminal shortcuts", () => {
context: { terminalFocus: false }, context: { terminalFocus: false },
}), }),
); );
assert.isFalse(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: false },
}),
);
}); });
it("matches split/new when terminalFocus is true", () => { it("matches split/new when terminalFocus is true", () => {
@@ -144,12 +130,6 @@ describe("split/new/close terminal shortcuts", () => {
context: { terminalFocus: true }, context: { terminalFocus: true },
}), }),
); );
assert.isTrue(
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
platform: "Linux",
context: { terminalFocus: true },
}),
);
}); });
it("supports when expressions", () => { it("supports when expressions", () => {
@@ -245,27 +225,6 @@ describe("chat/editor shortcuts", () => {
); );
}); });
it("matches chat.newLocal shortcut", () => {
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", metaKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "MacIntel",
},
),
);
assert.isTrue(
isChatNewLocalShortcut(
event({ key: "n", ctrlKey: true, shiftKey: true }),
DEFAULT_BINDINGS,
{
platform: "Linux",
},
),
);
});
it("matches editor.openFavorite shortcut", () => { it("matches editor.openFavorite shortcut", () => {
assert.isTrue( assert.isTrue(
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, { isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
-16
View File
@@ -190,14 +190,6 @@ export function isTerminalNewShortcut(
return matchesCommandShortcut(event, keybindings, "terminal.new", options); return matchesCommandShortcut(event, keybindings, "terminal.new", options);
} }
export function isTerminalCloseShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "terminal.close", options);
}
export function isChatNewShortcut( export function isChatNewShortcut(
event: ShortcutEventLike, event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig, keybindings: ResolvedKeybindingsConfig,
@@ -206,14 +198,6 @@ export function isChatNewShortcut(
return matchesCommandShortcut(event, keybindings, "chat.new", options); return matchesCommandShortcut(event, keybindings, "chat.new", options);
} }
export function isChatNewLocalShortcut(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): boolean {
return matchesCommandShortcut(event, keybindings, "chat.newLocal", options);
}
export function isOpenFavoriteEditorShortcut( export function isOpenFavoriteEditorShortcut(
event: ShortcutEventLike, event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig, keybindings: ResolvedKeybindingsConfig,
-62
View File
@@ -574,66 +574,4 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt); expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
expect(next.threads[0]?.lastVisitedAt).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();
});
}); });
-39
View File
@@ -56,13 +56,6 @@ type Action =
| { type: "SET_ERROR"; threadId: string; error: string | null } | { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string } | { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: 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"; type: "SET_THREAD_BRANCH";
threadId: string; threadId: string;
@@ -805,38 +798,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": { case "SET_THREAD_BRANCH": {
return { return {
...state, ...state,
-3
View File
@@ -91,9 +91,6 @@ export function createWsNativeApi(): NativeApi {
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input), respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input), stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
listSessions: () => transport.request(WS_METHODS.providersListSessions), listSessions: () => transport.request(WS_METHODS.providersListSessions),
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
revertToCheckpoint: (input) =>
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
onEvent: (callback) => onEvent: (callback) =>
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void), transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
}, },
-8
View File
@@ -18,10 +18,6 @@ import type {
import type { import type {
ProviderEvent, ProviderEvent,
ProviderInterruptTurnInput, ProviderInterruptTurnInput,
ProviderListCheckpointsInput,
ProviderListCheckpointsResult,
ProviderRevertToCheckpointInput,
ProviderRevertToCheckpointResult,
ProviderRespondToRequestInput, ProviderRespondToRequestInput,
ProviderSendTurnInput, ProviderSendTurnInput,
ProviderSession, ProviderSession,
@@ -88,10 +84,6 @@ export interface NativeApi {
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>; respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
stopSession: (input: ProviderStopSessionInput) => Promise<void>; stopSession: (input: ProviderStopSessionInput) => Promise<void>;
listSessions: () => Promise<ProviderSession[]>; listSessions: () => Promise<ProviderSession[]>;
listCheckpoints: (input: ProviderListCheckpointsInput) => Promise<ProviderListCheckpointsResult>;
revertToCheckpoint: (
input: ProviderRevertToCheckpointInput,
) => Promise<ProviderRevertToCheckpointResult>;
onEvent: (callback: (event: ProviderEvent) => void) => () => void; onEvent: (callback: (event: ProviderEvent) => void) => () => void;
}; };
projects: { projects: {
@@ -14,18 +14,6 @@ describe("keybindings contracts", () => {
command: "terminal.toggle", command: "terminal.toggle",
}); });
assert.strictEqual(parsed.command, "terminal.toggle"); assert.strictEqual(parsed.command, "terminal.toggle");
const parsedClose = keybindingRuleSchema.parse({
key: "mod+w",
command: "terminal.close",
});
assert.strictEqual(parsedClose.command, "terminal.close");
const parsedLocal = keybindingRuleSchema.parse({
key: "mod+shift+n",
command: "chat.newLocal",
});
assert.strictEqual(parsedLocal.command, "chat.newLocal");
}); });
it("rejects invalid command values", () => { it("rejects invalid command values", () => {
-2
View File
@@ -4,9 +4,7 @@ export const keybindingCommandSchema = z.enum([
"terminal.toggle", "terminal.toggle",
"terminal.split", "terminal.split",
"terminal.new", "terminal.new",
"terminal.close",
"chat.new", "chat.new",
"chat.newLocal",
"editor.openFavorite", "editor.openFavorite",
]); ]);
-73
View File
@@ -2,12 +2,7 @@ import { describe, expect, it } from "vitest";
import { import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
providerCheckpointSchema,
providerEventSchema, providerEventSchema,
providerListCheckpointsInputSchema,
providerListCheckpointsResultSchema,
providerRevertToCheckpointInputSchema,
providerRevertToCheckpointResultSchema,
providerRespondToRequestInputSchema, providerRespondToRequestInputSchema,
providerSendTurnInputSchema, providerSendTurnInputSchema,
providerSessionStartInputSchema, providerSessionStartInputSchema,
@@ -162,71 +157,3 @@ describe("providerRespondToRequestInputSchema", () => {
).toThrow(); ).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();
});
});
-38
View File
@@ -111,37 +111,6 @@ export const providerStopSessionInputSchema = z.object({
sessionId: z.string().min(1), 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({ export const providerRespondToRequestInputSchema = z.object({
sessionId: z.string().min(1), sessionId: z.string().min(1),
requestId: 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 ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>; export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
export type ProviderStopSessionInput = z.input<typeof providerStopSessionInputSchema>; 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 ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>; export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
export type ProviderEvent = z.infer<typeof providerEventSchema>; export type ProviderEvent = z.infer<typeof providerEventSchema>;
-2
View File
@@ -10,8 +10,6 @@ export const WS_METHODS = {
providersRespondToRequest: "providers.respondToRequest", providersRespondToRequest: "providers.respondToRequest",
providersStopSession: "providers.stopSession", providersStopSession: "providers.stopSession",
providersListSessions: "providers.listSessions", providersListSessions: "providers.listSessions",
providersListCheckpoints: "providers.listCheckpoints",
providersRevertToCheckpoint: "providers.revertToCheckpoint",
// Project registry methods // Project registry methods
projectsList: "projects.list", projectsList: "projects.list",