Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c9fae23efe | ||
|
|
4d2f16be47 | ||
|
|
c6047688a1 |
No files matched your search
-101
@@ -1,101 +0,0 @@
|
|||||||
# Keybindings
|
|
||||||
|
|
||||||
T3 Code reads keybindings from:
|
|
||||||
|
|
||||||
- `~/.t3/keybindings.json`
|
|
||||||
|
|
||||||
The file must be a JSON array of rules:
|
|
||||||
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{ "key": "mod+g", "command": "terminal.toggle" },
|
|
||||||
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
|
||||||
|
|
||||||
## Defaults
|
|
||||||
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{ "key": "mod+j", "command": "terminal.toggle" },
|
|
||||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
|
||||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
|
||||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
|
||||||
{ "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" }
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
### Rule Shape
|
|
||||||
|
|
||||||
Each entry supports:
|
|
||||||
|
|
||||||
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
|
|
||||||
- `command` (required): action ID
|
|
||||||
- `when` (optional): boolean expression controlling when the shortcut is active
|
|
||||||
|
|
||||||
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
|
|
||||||
|
|
||||||
### Available Commands
|
|
||||||
|
|
||||||
- `terminal.toggle`: open/close terminal drawer
|
|
||||||
- `terminal.split`: split 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 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
|
|
||||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
|
||||||
|
|
||||||
### Key Syntax
|
|
||||||
|
|
||||||
Supported modifiers:
|
|
||||||
|
|
||||||
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
|
|
||||||
- `cmd` / `meta`
|
|
||||||
- `ctrl` / `control`
|
|
||||||
- `shift`
|
|
||||||
- `alt` / `option`
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- `mod+j`
|
|
||||||
- `mod+shift+d`
|
|
||||||
- `ctrl+l`
|
|
||||||
- `cmd+k`
|
|
||||||
|
|
||||||
### `when` Conditions
|
|
||||||
|
|
||||||
Currently available context keys:
|
|
||||||
|
|
||||||
- `terminalFocus`
|
|
||||||
- `terminalOpen`
|
|
||||||
|
|
||||||
Supported operators:
|
|
||||||
|
|
||||||
- `!` (not)
|
|
||||||
- `&&` (and)
|
|
||||||
- `||` (or)
|
|
||||||
- parentheses: `(` `)`
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
- `"when": "terminalFocus"`
|
|
||||||
- `"when": "terminalOpen && !terminalFocus"`
|
|
||||||
- `"when": "terminalFocus || terminalOpen"`
|
|
||||||
|
|
||||||
Unknown condition keys evaluate to `false`.
|
|
||||||
|
|
||||||
### Precedence
|
|
||||||
|
|
||||||
- Rules are evaluated in array order.
|
|
||||||
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
|
|
||||||
- That means precedence is across commands, not only within the same command.
|
|
||||||
@@ -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();
|
||||||
@@ -143,40 +113,6 @@ describe("isRecoverableThreadResumeError", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("startSession", () => {
|
|
||||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
|
||||||
const manager = new CodexAppServerManager();
|
|
||||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
|
||||||
manager.on("event", (event) => {
|
|
||||||
events.push({
|
|
||||||
method: event.method,
|
|
||||||
kind: event.kind,
|
|
||||||
...(event.message ? { message: event.message } : {}),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
|
||||||
throw new Error("cwd missing");
|
|
||||||
});
|
|
||||||
try {
|
|
||||||
await expect(
|
|
||||||
manager.startSession({
|
|
||||||
provider: "codex",
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("cwd missing");
|
|
||||||
expect(events).toHaveLength(1);
|
|
||||||
expect(events[0]).toEqual({
|
|
||||||
method: "session/startFailed",
|
|
||||||
kind: "error",
|
|
||||||
message: "cwd missing",
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
processCwd.mockRestore();
|
|
||||||
manager.stopAll();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("sendTurn", () => {
|
describe("sendTurn", () => {
|
||||||
it("sends text and image user input items to turn/start", async () => {
|
it("sends text and image user input items to turn/start", async () => {
|
||||||
const { manager, context, requireSession, sendRequest, updateSession } =
|
const { manager, context, requireSession, sendRequest, updateSession } =
|
||||||
@@ -262,91 +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("reads thread turns from flat thread/read responses", async () => {
|
|
||||||
const { manager, context, sendRequest } = createThreadControlHarness();
|
|
||||||
sendRequest.mockResolvedValue({
|
|
||||||
threadId: "thread_1",
|
|
||||||
turns: [
|
|
||||||
{
|
|
||||||
id: "turn_1",
|
|
||||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await manager.readThread("sess_1");
|
|
||||||
|
|
||||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
|
||||||
threadId: "thread_1",
|
|
||||||
includeTurns: true,
|
|
||||||
});
|
|
||||||
expect(result).toEqual({
|
|
||||||
threadId: "thread_1",
|
|
||||||
turns: [
|
|
||||||
{
|
|
||||||
id: "turn_1",
|
|
||||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rolls back turns via thread/rollback and resets session running state", async () => {
|
|
||||||
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
|
|
||||||
sendRequest.mockResolvedValue({
|
|
||||||
thread: {
|
|
||||||
id: "thread_1",
|
|
||||||
turns: [],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await manager.rollbackThread("sess_1", 2);
|
|
||||||
|
|
||||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
|
||||||
threadId: "thread_1",
|
|
||||||
numTurns: 2,
|
|
||||||
});
|
|
||||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
|
||||||
status: "ready",
|
|
||||||
activeTurnId: undefined,
|
|
||||||
});
|
|
||||||
expect(result).toEqual({
|
|
||||||
threadId: "thread_1",
|
|
||||||
turns: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -65,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 =
|
||||||
@@ -148,43 +138,40 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||||
const sessionId = randomUUID();
|
const sessionId = randomUUID();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
let context: CodexSessionContext | undefined;
|
|
||||||
|
const session: ProviderSession = {
|
||||||
|
sessionId,
|
||||||
|
provider: "codex",
|
||||||
|
status: "connecting",
|
||||||
|
model: normalizeCodexModelSlug(input.model),
|
||||||
|
cwd: input.cwd,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
const child = spawn("codex", ["app-server"], {
|
||||||
|
cwd: input.cwd,
|
||||||
|
env: process.env,
|
||||||
|
stdio: ["pipe", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
const output = readline.createInterface({ input: child.stdout });
|
||||||
|
|
||||||
|
const context: CodexSessionContext = {
|
||||||
|
session,
|
||||||
|
child,
|
||||||
|
output,
|
||||||
|
pending: new Map(),
|
||||||
|
pendingApprovals: new Map(),
|
||||||
|
nextRequestId: 1,
|
||||||
|
stopping: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.sessions.set(sessionId, context);
|
||||||
|
this.attachProcessListeners(context);
|
||||||
|
|
||||||
|
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resolvedCwd = input.cwd ?? process.cwd();
|
|
||||||
|
|
||||||
const session: ProviderSession = {
|
|
||||||
sessionId,
|
|
||||||
provider: "codex",
|
|
||||||
status: "connecting",
|
|
||||||
model: normalizeCodexModelSlug(input.model),
|
|
||||||
cwd: resolvedCwd,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
const child = spawn("codex", ["app-server"], {
|
|
||||||
cwd: resolvedCwd,
|
|
||||||
env: process.env,
|
|
||||||
stdio: ["pipe", "pipe", "pipe"],
|
|
||||||
});
|
|
||||||
const output = readline.createInterface({ input: child.stdout });
|
|
||||||
|
|
||||||
context = {
|
|
||||||
session,
|
|
||||||
child,
|
|
||||||
output,
|
|
||||||
pending: new Map(),
|
|
||||||
pendingApprovals: new Map(),
|
|
||||||
nextRequestId: 1,
|
|
||||||
stopping: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
this.sessions.set(sessionId, context);
|
|
||||||
this.attachProcessListeners(context);
|
|
||||||
|
|
||||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
|
||||||
|
|
||||||
await this.sendRequest(context, "initialize", {
|
await this.sendRequest(context, "initialize", {
|
||||||
clientInfo: {
|
clientInfo: {
|
||||||
name: "t3code_desktop",
|
name: "t3code_desktop",
|
||||||
@@ -254,24 +241,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
return { ...context.session };
|
return { ...context.session };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||||
if (context) {
|
this.updateSession(context, {
|
||||||
this.updateSession(context, {
|
status: "error",
|
||||||
status: "error",
|
lastError: message,
|
||||||
lastError: message,
|
});
|
||||||
});
|
this.emitErrorEvent(context, "session/startFailed", message);
|
||||||
this.emitErrorEvent(context, "session/startFailed", message);
|
this.stopSession(sessionId);
|
||||||
this.stopSession(sessionId);
|
|
||||||
} else {
|
|
||||||
this.emitEvent({
|
|
||||||
id: randomUUID(),
|
|
||||||
kind: "error",
|
|
||||||
provider: "codex",
|
|
||||||
sessionId,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
method: "session/startFailed",
|
|
||||||
message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
throw new Error(message, { cause: error });
|
throw new Error(message, { cause: error });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -356,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,
|
||||||
@@ -802,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") ?? this.readArray(responseRecord, "turns") ?? [];
|
|
||||||
const turns = turnsRaw.map((turnValue, index) => {
|
|
||||||
const turn = this.readObject(turnValue);
|
|
||||||
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
|
|
||||||
const items = this.readArray(turn, "items") ?? [];
|
|
||||||
return {
|
|
||||||
id: turnId,
|
|
||||||
items,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
threadId,
|
|
||||||
turns,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||||
if (!value || typeof value !== "object") {
|
if (!value || typeof value !== "object") {
|
||||||
return false;
|
return false;
|
||||||
@@ -908,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,243 +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;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function createRepoWithoutHead(): Promise<string> {
|
|
||||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
|
|
||||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
|
||||||
return cwd;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("FilesystemCheckpointStore", () => {
|
|
||||||
it("captures refs without mutating branch history and restores workspace state", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr_1";
|
|
||||||
|
|
||||||
try {
|
|
||||||
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
|
|
||||||
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
|
||||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
|
||||||
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
|
|
||||||
expect(rootCommit.length).toBeGreaterThan(0);
|
|
||||||
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
|
|
||||||
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
|
||||||
await rm(path.join(cwd, "tracked.txt"));
|
|
||||||
await writeFile(path.join(cwd, "notes.md"), "notes\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
|
||||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
|
||||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
|
|
||||||
|
|
||||||
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
|
|
||||||
expect(restoredRoot).toBe(true);
|
|
||||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
|
||||||
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
|
|
||||||
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
|
|
||||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
|
||||||
|
|
||||||
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
expect(restoredTurn1).toBe(true);
|
|
||||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
|
|
||||||
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
|
|
||||||
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
|
|
||||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false when restoring a missing checkpoint", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const restored = await store.restoreCheckpoint({
|
|
||||||
cwd,
|
|
||||||
threadId: "thr_2",
|
|
||||||
turnCount: 999,
|
|
||||||
});
|
|
||||||
expect(restored).toBe(false);
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr_2b";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
|
||||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
|
||||||
|
|
||||||
const restored = await store.restoreCheckpoint({
|
|
||||||
cwd,
|
|
||||||
threadId,
|
|
||||||
turnCount: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(restored).toBe(true);
|
|
||||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
|
||||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("prunes refs newer than the retained turn", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr_3";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "turn1\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "turn2\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
|
|
||||||
|
|
||||||
await store.pruneAfterTurn({
|
|
||||||
cwd,
|
|
||||||
threadId,
|
|
||||||
maxTurnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
|
|
||||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
|
|
||||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns a unified patch between checkpoint turns", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr_4";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
|
||||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
|
|
||||||
const diff = await store.diffCheckpoints({
|
|
||||||
cwd,
|
|
||||||
threadId,
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
|
||||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
|
|
||||||
const cwd = await createRepo();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr_5";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
|
||||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
|
||||||
|
|
||||||
const diff = await store.diffCheckpoints({
|
|
||||||
cwd,
|
|
||||||
threadId,
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
|
||||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("detects non-repo folders", async () => {
|
|
||||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
|
|
||||||
try {
|
|
||||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false when repository path does not exist", async () => {
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
|
|
||||||
|
|
||||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
|
|
||||||
const cwd = await createRepoWithoutHead();
|
|
||||||
const store = new FilesystemCheckpointStore();
|
|
||||||
const threadId = "thr-no-head";
|
|
||||||
|
|
||||||
try {
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "first\n");
|
|
||||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
|
||||||
|
|
||||||
await writeFile(path.join(cwd, "README.md"), "second\n");
|
|
||||||
const restored = await store.restoreCheckpoint({
|
|
||||||
cwd,
|
|
||||||
threadId,
|
|
||||||
turnCount: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(restored).toBe(true);
|
|
||||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
|
|
||||||
} finally {
|
|
||||||
await rm(cwd, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,322 +0,0 @@
|
|||||||
import { mkdtemp, rm } from "node:fs/promises";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import { randomUUID } from "node:crypto";
|
|
||||||
|
|
||||||
import { runProcess } from "./processRunner";
|
|
||||||
|
|
||||||
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
|
||||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
||||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
|
||||||
|
|
||||||
function quoteGitCommand(args: readonly string[]): string {
|
|
||||||
return `git ${args.join(" ")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function checkpointRefThreadSegment(threadId: string): string {
|
|
||||||
return Buffer.from(threadId, "utf8").toString("base64url");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
|
|
||||||
if (!Number.isInteger(turnCount) || turnCount < 0) {
|
|
||||||
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
|
|
||||||
}
|
|
||||||
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GitOptions {
|
|
||||||
env?: NodeJS.ProcessEnv;
|
|
||||||
stdin?: string;
|
|
||||||
allowNonZeroExit?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class FilesystemCheckpointStore {
|
|
||||||
async isGitRepository(cwd: string): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
});
|
|
||||||
return result.code === 0 && result.stdout.trim() === "true";
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async captureCheckpoint(input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}): Promise<void> {
|
|
||||||
const { cwd, threadId, turnCount } = input;
|
|
||||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
|
||||||
|
|
||||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
|
|
||||||
|
|
||||||
try {
|
|
||||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
|
||||||
const commitEnv: NodeJS.ProcessEnv = {
|
|
||||||
...process.env,
|
|
||||||
GIT_INDEX_FILE: tempIndexPath,
|
|
||||||
GIT_AUTHOR_NAME: "T3 Code",
|
|
||||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
|
||||||
GIT_COMMITTER_NAME: "T3 Code",
|
|
||||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
|
||||||
};
|
|
||||||
|
|
||||||
const hasHead = await this.hasHeadCommit(cwd);
|
|
||||||
if (hasHead) {
|
|
||||||
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
|
|
||||||
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
|
|
||||||
const treeOid = writeTreeResult.stdout.trim();
|
|
||||||
if (!treeOid) {
|
|
||||||
throw new Error("git write-tree returned an empty tree oid.");
|
|
||||||
}
|
|
||||||
|
|
||||||
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
|
|
||||||
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
|
|
||||||
env: commitEnv,
|
|
||||||
stdin: `${message}\n`,
|
|
||||||
});
|
|
||||||
const commitOid = commitTreeResult.stdout.trim();
|
|
||||||
if (!commitOid) {
|
|
||||||
throw new Error("git commit-tree returned an empty commit oid.");
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.runGit(cwd, ["update-ref", ref, commitOid]);
|
|
||||||
} finally {
|
|
||||||
await rm(tempDir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async hasCheckpoint(input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
const { cwd, threadId, turnCount } = input;
|
|
||||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
|
||||||
const commit = await this.resolveCheckpointCommit(cwd, ref);
|
|
||||||
return commit !== null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
|
|
||||||
const { cwd, threadId } = input;
|
|
||||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
|
||||||
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
|
|
||||||
if (existing) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const headCommit = await this.resolveHeadCommit(cwd);
|
|
||||||
if (!headCommit) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
async restoreCheckpoint(input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}): Promise<boolean> {
|
|
||||||
const { cwd, threadId, turnCount } = input;
|
|
||||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
|
||||||
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
|
||||||
if (!commitOid && turnCount === 0) {
|
|
||||||
commitOid = await this.resolveHeadCommit(cwd);
|
|
||||||
}
|
|
||||||
if (!commitOid) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
|
||||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
|
||||||
if (await this.hasHeadCommit(cwd)) {
|
|
||||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
async diffCheckpoints(input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
fromTurnCount: number;
|
|
||||||
toTurnCount: number;
|
|
||||||
}): Promise<string> {
|
|
||||||
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
|
|
||||||
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
|
|
||||||
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
|
|
||||||
}
|
|
||||||
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
|
|
||||||
throw new Error(`Invalid to turn count: ${toTurnCount}`);
|
|
||||||
}
|
|
||||||
if (fromTurnCount > toTurnCount) {
|
|
||||||
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
|
|
||||||
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
|
|
||||||
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
|
|
||||||
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
|
|
||||||
if (!fromCommitOid && fromTurnCount === 0) {
|
|
||||||
const headCommit = await this.resolveHeadCommit(cwd);
|
|
||||||
if (headCommit) {
|
|
||||||
fromCommitOid = headCommit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!fromCommitOid) {
|
|
||||||
throw new Error(
|
|
||||||
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!toCommitOid) {
|
|
||||||
throw new Error(
|
|
||||||
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await this.runGit(cwd, [
|
|
||||||
"diff",
|
|
||||||
"--patch",
|
|
||||||
"--minimal",
|
|
||||||
"--no-color",
|
|
||||||
fromCommitOid,
|
|
||||||
toCommitOid,
|
|
||||||
]);
|
|
||||||
return result.stdout;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async resolveHeadCommit(cwd: string): Promise<string | null> {
|
|
||||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
});
|
|
||||||
if (result.code !== 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const commit = result.stdout.trim();
|
|
||||||
return commit.length > 0 ? commit : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async pruneAfterTurn(input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
maxTurnCount: number;
|
|
||||||
}): Promise<void> {
|
|
||||||
const { cwd, threadId, maxTurnCount } = input;
|
|
||||||
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
|
|
||||||
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
|
|
||||||
const result = await this.runGit(
|
|
||||||
cwd,
|
|
||||||
["for-each-ref", "--format=%(refname)", threadRefPrefix],
|
|
||||||
{
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (result.code !== 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const refsToDelete = result.stdout
|
|
||||||
.split(/\r?\n/g)
|
|
||||||
.map((line) => line.trim())
|
|
||||||
.filter((line) => line.length > 0)
|
|
||||||
.filter((refName) => {
|
|
||||||
const turn = this.readRefTurnCount(refName);
|
|
||||||
return turn !== null && turn > maxTurnCount;
|
|
||||||
});
|
|
||||||
|
|
||||||
const batchSize = 32;
|
|
||||||
const batches = Array.from(
|
|
||||||
{ length: Math.ceil(refsToDelete.length / batchSize) },
|
|
||||||
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
|
|
||||||
);
|
|
||||||
await batches.reduce<Promise<void>>((pending, batch) => {
|
|
||||||
return pending.then(async () => {
|
|
||||||
await Promise.all(
|
|
||||||
batch.map((refName) =>
|
|
||||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}, Promise.resolve());
|
|
||||||
}
|
|
||||||
|
|
||||||
private async hasHeadCommit(cwd: string): Promise<boolean> {
|
|
||||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
});
|
|
||||||
return result.code === 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
|
|
||||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
});
|
|
||||||
if (result.code !== 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const commit = result.stdout.trim();
|
|
||||||
return commit.length > 0 ? commit : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private readRefTurnCount(ref: string): number | null {
|
|
||||||
const segments = ref.split("/");
|
|
||||||
const rawTurn = segments.at(-1);
|
|
||||||
if (!rawTurn) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const turn = Number.parseInt(rawTurn, 10);
|
|
||||||
return Number.isInteger(turn) && turn >= 0 ? turn : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async runGit(
|
|
||||||
cwd: string,
|
|
||||||
args: readonly string[],
|
|
||||||
options: GitOptions = {},
|
|
||||||
): Promise<Awaited<ReturnType<typeof runProcess>>> {
|
|
||||||
let result: Awaited<ReturnType<typeof runProcess>>;
|
|
||||||
try {
|
|
||||||
result = await runProcess("git", args, {
|
|
||||||
cwd,
|
|
||||||
env: options.env,
|
|
||||||
stdin: options.stdin,
|
|
||||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
|
||||||
outputMode: "truncate",
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.timedOut) {
|
|
||||||
throw new Error(`${quoteGitCommand(args)} timed out.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.stdoutTruncated || result.stderrTruncated) {
|
|
||||||
throw new Error(
|
|
||||||
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
|
||||||
const stderr = result.stderr.trim();
|
|
||||||
throw new Error(
|
|
||||||
stderr.length > 0
|
|
||||||
? `${quoteGitCommand(args)} failed: ${stderr}`
|
|
||||||
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -760,35 +760,6 @@ describe("git integration", () => {
|
|||||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", async () => {
|
|
||||||
await using remote = await makeTmpDir();
|
|
||||||
await using source = await makeTmpDir();
|
|
||||||
await using clone = await makeTmpDir();
|
|
||||||
await git(remote.path, "init --bare");
|
|
||||||
|
|
||||||
await initRepoWithCommit(source.path);
|
|
||||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
|
||||||
(branch) => branch.current,
|
|
||||||
)!.name;
|
|
||||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
|
||||||
await git(source.path, `push -u origin ${initialBranch}`);
|
|
||||||
|
|
||||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
|
||||||
await git(clone.path, "config user.email '[email protected]'");
|
|
||||||
await git(clone.path, "config user.name 'Test'");
|
|
||||||
await git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
|
||||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
|
||||||
await git(clone.path, "add CHANGELOG.md");
|
|
||||||
await git(clone.path, "commit -m 'remote update'");
|
|
||||||
await git(clone.path, `push origin ${initialBranch}`);
|
|
||||||
|
|
||||||
const core = new GitCoreService();
|
|
||||||
const details = await core.statusDetails(source.path);
|
|
||||||
expect(details.branch).toBe(initialBranch);
|
|
||||||
expect(details.aheadCount).toBe(0);
|
|
||||||
expect(details.behindCount).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||||
await using tmp = await makeTmpDir();
|
await using tmp = await makeTmpDir();
|
||||||
await initRepoWithCommit(tmp.path);
|
await initRepoWithCommit(tmp.path);
|
||||||
|
|||||||
+6
-62
@@ -65,8 +65,6 @@ interface ExecuteGitOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
|
||||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_000;
|
|
||||||
|
|
||||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||||
function runGit(
|
function runGit(
|
||||||
@@ -218,8 +216,6 @@ async function executeGit(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class GitCoreService {
|
export class GitCoreService {
|
||||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
|
||||||
|
|
||||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||||
const input = gitStatusInputSchema.parse(raw);
|
const input = gitStatusInputSchema.parse(raw);
|
||||||
const details = await this.statusDetails(input.cwd);
|
const details = await this.statusDetails(input.cwd);
|
||||||
@@ -235,8 +231,6 @@ export class GitCoreService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
|
||||||
|
|
||||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||||
@@ -559,9 +553,7 @@ export class GitCoreService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveCurrentUpstream(
|
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||||
cwd: string,
|
|
||||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
|
||||||
const upstreamRef = trimStdout(
|
const upstreamRef = trimStdout(
|
||||||
await this.gitStdout(
|
await this.gitStdout(
|
||||||
cwd,
|
cwd,
|
||||||
@@ -570,72 +562,24 @@ export class GitCoreService {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||||
return null;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const separatorIndex = upstreamRef.indexOf("/");
|
const separatorIndex = upstreamRef.indexOf("/");
|
||||||
if (separatorIndex <= 0) {
|
if (separatorIndex <= 0) {
|
||||||
return null;
|
return;
|
||||||
}
|
}
|
||||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||||
if (remoteName.length === 0) {
|
if (remoteName.length === 0) {
|
||||||
return null;
|
return;
|
||||||
}
|
}
|
||||||
if (upstreamBranch.length === 0) {
|
if (upstreamBranch.length === 0) {
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
upstreamRef,
|
|
||||||
remoteName,
|
|
||||||
upstreamBranch,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async fetchUpstreamRef(
|
|
||||||
cwd: string,
|
|
||||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
|
||||||
): Promise<void> {
|
|
||||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
|
||||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async fetchUpstreamRefForStatus(
|
|
||||||
cwd: string,
|
|
||||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
|
||||||
): Promise<void> {
|
|
||||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
|
||||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
|
||||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
|
||||||
if (!upstream) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
|
||||||
const now = Date.now();
|
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
|
||||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
|
||||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
|
||||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
|
||||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
|
||||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
|
||||||
if (!upstream) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await this.fetchUpstreamRef(cwd, upstream);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||||
|
|||||||
@@ -1,225 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import { assert, afterEach, describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
compileResolvedKeybindingRule,
|
|
||||||
parseKeybindingShortcut,
|
|
||||||
upsertKeybindingRule,
|
|
||||||
} from "./keybindings";
|
|
||||||
|
|
||||||
describe("server keybindings", () => {
|
|
||||||
const tempDirs: string[] = [];
|
|
||||||
const logger = {
|
|
||||||
warn: vi.fn(),
|
|
||||||
};
|
|
||||||
|
|
||||||
function makeTempDir(prefix: string): string {
|
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
||||||
tempDirs.push(dir);
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
logger.warn.mockReset();
|
|
||||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses shortcuts including plus key", () => {
|
|
||||||
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
|
|
||||||
key: "j",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
});
|
|
||||||
assert.deepEqual(parseKeybindingShortcut("mod++"), {
|
|
||||||
key: "+",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("compiles valid rule with parsed when AST", () => {
|
|
||||||
const compiled = compileResolvedKeybindingRule({
|
|
||||||
key: "mod+d",
|
|
||||||
command: "terminal.split",
|
|
||||||
when: "terminalOpen && !terminalFocus",
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(compiled, {
|
|
||||||
command: "terminal.split",
|
|
||||||
shortcut: {
|
|
||||||
key: "d",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
},
|
|
||||||
whenAst: {
|
|
||||||
type: "and",
|
|
||||||
left: { type: "identifier", name: "terminalOpen" },
|
|
||||||
right: {
|
|
||||||
type: "not",
|
|
||||||
node: { type: "identifier", name: "terminalFocus" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects invalid rules", () => {
|
|
||||||
assert.isNull(
|
|
||||||
compileResolvedKeybindingRule({
|
|
||||||
key: "mod+shift+d+o",
|
|
||||||
command: "terminal.new",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.isNull(
|
|
||||||
compileResolvedKeybindingRule({
|
|
||||||
key: "mod+d",
|
|
||||||
command: "terminal.split",
|
|
||||||
when: "terminalFocus && (",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.isNull(
|
|
||||||
compileResolvedKeybindingRule({
|
|
||||||
key: "mod+d",
|
|
||||||
command: "terminal.split",
|
|
||||||
when: `${"!".repeat(300)}terminalFocus`,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const configPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(
|
|
||||||
configPath,
|
|
||||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
const resolved = upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
});
|
|
||||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
|
||||||
key: string;
|
|
||||||
command: string;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
expect(persisted).toEqual([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("replaces existing custom keybinding for the same command", () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const configPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(
|
|
||||||
configPath,
|
|
||||||
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
});
|
|
||||||
|
|
||||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
|
||||||
key: string;
|
|
||||||
command: string;
|
|
||||||
}>;
|
|
||||||
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refuses to overwrite malformed keybindings config", () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const configPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(configPath, "{ not-json", "utf8");
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
}),
|
|
||||||
).toThrow(/Unable to parse keybindings config/);
|
|
||||||
|
|
||||||
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reports non-array config parse errors without duplicate prefix", () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const configPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
}),
|
|
||||||
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
}),
|
|
||||||
).not.toThrow(
|
|
||||||
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("cleans up temp files when atomic keybinding write fails", () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const configPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
vi.spyOn(fs, "renameSync").mockImplementation(() => {
|
|
||||||
throw new Error("rename failed");
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
upsertKeybindingRule(logger, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
}),
|
|
||||||
).toThrow(/rename failed/);
|
|
||||||
|
|
||||||
expect(fs.readFileSync(configPath, "utf8")).toBe(
|
|
||||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
|
||||||
);
|
|
||||||
const tempFiles = fs
|
|
||||||
.readdirSync(configDir)
|
|
||||||
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
|
|
||||||
expect(tempFiles).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,447 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import type {
|
|
||||||
KeybindingRule,
|
|
||||||
KeybindingsConfig,
|
|
||||||
KeybindingShortcut,
|
|
||||||
KeybindingWhenNode,
|
|
||||||
ResolvedKeybindingRule,
|
|
||||||
ResolvedKeybindingsConfig,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { keybindingRuleSchema } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
interface KeybindingsLogger {
|
|
||||||
warn(message: string, context?: Record<string, unknown>): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
type WhenToken =
|
|
||||||
| { type: "identifier"; value: string }
|
|
||||||
| { type: "not" }
|
|
||||||
| { type: "and" }
|
|
||||||
| { type: "or" }
|
|
||||||
| { type: "lparen" }
|
|
||||||
| { type: "rparen" };
|
|
||||||
|
|
||||||
const MAX_WHEN_EXPRESSION_DEPTH = 256;
|
|
||||||
|
|
||||||
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
|
||||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
|
||||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
|
||||||
{ 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" },
|
|
||||||
];
|
|
||||||
|
|
||||||
function normalizeKeyToken(token: string): string {
|
|
||||||
if (token === "space") return " ";
|
|
||||||
if (token === "esc") return "escape";
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
|
||||||
const rawTokens = value
|
|
||||||
.toLowerCase()
|
|
||||||
.split("+")
|
|
||||||
.map((token) => token.trim());
|
|
||||||
const tokens = [...rawTokens];
|
|
||||||
let trailingEmptyCount = 0;
|
|
||||||
while (tokens[tokens.length - 1] === "") {
|
|
||||||
trailingEmptyCount += 1;
|
|
||||||
tokens.pop();
|
|
||||||
}
|
|
||||||
if (trailingEmptyCount > 0) {
|
|
||||||
tokens.push("+");
|
|
||||||
}
|
|
||||||
if (tokens.some((token) => token.length === 0)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (tokens.length === 0) return null;
|
|
||||||
|
|
||||||
let key: string | null = null;
|
|
||||||
let metaKey = false;
|
|
||||||
let ctrlKey = false;
|
|
||||||
let shiftKey = false;
|
|
||||||
let altKey = false;
|
|
||||||
let modKey = false;
|
|
||||||
|
|
||||||
for (const token of tokens) {
|
|
||||||
switch (token) {
|
|
||||||
case "cmd":
|
|
||||||
case "meta":
|
|
||||||
metaKey = true;
|
|
||||||
break;
|
|
||||||
case "ctrl":
|
|
||||||
case "control":
|
|
||||||
ctrlKey = true;
|
|
||||||
break;
|
|
||||||
case "shift":
|
|
||||||
shiftKey = true;
|
|
||||||
break;
|
|
||||||
case "alt":
|
|
||||||
case "option":
|
|
||||||
altKey = true;
|
|
||||||
break;
|
|
||||||
case "mod":
|
|
||||||
modKey = true;
|
|
||||||
break;
|
|
||||||
default: {
|
|
||||||
if (key !== null) return null;
|
|
||||||
key = normalizeKeyToken(token);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === null) return null;
|
|
||||||
return {
|
|
||||||
key,
|
|
||||||
metaKey,
|
|
||||||
ctrlKey,
|
|
||||||
shiftKey,
|
|
||||||
altKey,
|
|
||||||
modKey,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
|
||||||
const tokens: WhenToken[] = [];
|
|
||||||
let index = 0;
|
|
||||||
|
|
||||||
while (index < expression.length) {
|
|
||||||
const current = expression[index];
|
|
||||||
if (!current) break;
|
|
||||||
|
|
||||||
if (/\s/.test(current)) {
|
|
||||||
index += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (expression.startsWith("&&", index)) {
|
|
||||||
tokens.push({ type: "and" });
|
|
||||||
index += 2;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (expression.startsWith("||", index)) {
|
|
||||||
tokens.push({ type: "or" });
|
|
||||||
index += 2;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (current === "!") {
|
|
||||||
tokens.push({ type: "not" });
|
|
||||||
index += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (current === "(") {
|
|
||||||
tokens.push({ type: "lparen" });
|
|
||||||
index += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (current === ")") {
|
|
||||||
tokens.push({ type: "rparen" });
|
|
||||||
index += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
|
|
||||||
if (!identifier) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
tokens.push({ type: "identifier", value: identifier[0] });
|
|
||||||
index += identifier[0].length;
|
|
||||||
}
|
|
||||||
|
|
||||||
return tokens;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
|
||||||
const tokens = tokenizeWhenExpression(expression);
|
|
||||||
if (!tokens || tokens.length === 0) return null;
|
|
||||||
let index = 0;
|
|
||||||
|
|
||||||
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
|
|
||||||
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const token = tokens[index];
|
|
||||||
if (!token) return null;
|
|
||||||
|
|
||||||
if (token.type === "identifier") {
|
|
||||||
index += 1;
|
|
||||||
return { type: "identifier", name: token.value };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.type === "lparen") {
|
|
||||||
index += 1;
|
|
||||||
const expressionNode = parseOr(depth + 1);
|
|
||||||
const closeToken = tokens[index];
|
|
||||||
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
index += 1;
|
|
||||||
return expressionNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseUnary = (depth: number): KeybindingWhenNode | null => {
|
|
||||||
let notCount = 0;
|
|
||||||
while (tokens[index]?.type === "not") {
|
|
||||||
index += 1;
|
|
||||||
notCount += 1;
|
|
||||||
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let node = parsePrimary(depth);
|
|
||||||
if (!node) return null;
|
|
||||||
|
|
||||||
while (notCount > 0) {
|
|
||||||
node = { type: "not", node };
|
|
||||||
notCount -= 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return node;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseAnd = (depth: number): KeybindingWhenNode | null => {
|
|
||||||
let left = parseUnary(depth);
|
|
||||||
if (!left) return null;
|
|
||||||
|
|
||||||
while (tokens[index]?.type === "and") {
|
|
||||||
index += 1;
|
|
||||||
const right = parseUnary(depth);
|
|
||||||
if (!right) return null;
|
|
||||||
left = { type: "and", left, right };
|
|
||||||
}
|
|
||||||
|
|
||||||
return left;
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseOr = (depth: number): KeybindingWhenNode | null => {
|
|
||||||
let left = parseAnd(depth);
|
|
||||||
if (!left) return null;
|
|
||||||
|
|
||||||
while (tokens[index]?.type === "or") {
|
|
||||||
index += 1;
|
|
||||||
const right = parseAnd(depth);
|
|
||||||
if (!right) return null;
|
|
||||||
left = { type: "or", left, right };
|
|
||||||
}
|
|
||||||
|
|
||||||
return left;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ast = parseOr(0);
|
|
||||||
if (!ast || index !== tokens.length) return null;
|
|
||||||
return ast;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
|
||||||
const key = rule.key.trim();
|
|
||||||
if (key.length === 0) return null;
|
|
||||||
const shortcut = parseKeybindingShortcut(key);
|
|
||||||
if (!shortcut) return null;
|
|
||||||
|
|
||||||
const when = rule.when?.trim();
|
|
||||||
if (when && when.length > 0) {
|
|
||||||
const whenAst = parseKeybindingWhenExpression(when);
|
|
||||||
if (!whenAst) return null;
|
|
||||||
return {
|
|
||||||
command: rule.command,
|
|
||||||
shortcut,
|
|
||||||
whenAst,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
command: rule.command,
|
|
||||||
shortcut,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function compileResolvedKeybindingsConfig(
|
|
||||||
config: KeybindingsConfig,
|
|
||||||
): ResolvedKeybindingsConfig {
|
|
||||||
const compiled: ResolvedKeybindingsConfig = [];
|
|
||||||
for (const rule of config) {
|
|
||||||
const resolved = compileResolvedKeybindingRule(rule);
|
|
||||||
if (!resolved) continue;
|
|
||||||
compiled.push(resolved);
|
|
||||||
}
|
|
||||||
return compiled;
|
|
||||||
}
|
|
||||||
|
|
||||||
function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
|
|
||||||
const resolved: ResolvedKeybindingsConfig = [];
|
|
||||||
for (const rule of DEFAULT_KEYBINDINGS) {
|
|
||||||
const compiled = compileResolvedKeybindingRule(rule);
|
|
||||||
if (!compiled) {
|
|
||||||
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
|
|
||||||
}
|
|
||||||
resolved.push(compiled);
|
|
||||||
}
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
|
|
||||||
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
|
|
||||||
const MAX_KEYBINDINGS = 256;
|
|
||||||
|
|
||||||
class KeybindingsConfigParseError extends Error {
|
|
||||||
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
|
|
||||||
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveKeybindingsConfigPath(): string {
|
|
||||||
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadCustomKeybindingsConfig(
|
|
||||||
logger: KeybindingsLogger,
|
|
||||||
options?: {
|
|
||||||
throwOnUnreadableConfig?: boolean;
|
|
||||||
},
|
|
||||||
): KeybindingsConfig {
|
|
||||||
const configPath = resolveKeybindingsConfigPath();
|
|
||||||
try {
|
|
||||||
const raw = fs.readFileSync(configPath, "utf8");
|
|
||||||
const parsed = JSON.parse(raw) as unknown;
|
|
||||||
if (!Array.isArray(parsed)) {
|
|
||||||
if (options?.throwOnUnreadableConfig) {
|
|
||||||
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
|
|
||||||
}
|
|
||||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
|
||||||
path: configPath,
|
|
||||||
});
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const sanitized: KeybindingsConfig = [];
|
|
||||||
let invalidEntries = 0;
|
|
||||||
for (const entry of parsed) {
|
|
||||||
const result = keybindingRuleSchema.safeParse(entry);
|
|
||||||
if (result.success) {
|
|
||||||
if (!compileResolvedKeybindingRule(result.data)) {
|
|
||||||
invalidEntries += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
sanitized.push(result.data);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
invalidEntries += 1;
|
|
||||||
}
|
|
||||||
if (invalidEntries > 0) {
|
|
||||||
logger.warn("ignoring invalid keybinding entries", {
|
|
||||||
path: configPath,
|
|
||||||
invalidEntries,
|
|
||||||
totalEntries: parsed.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return sanitized;
|
|
||||||
} catch (error) {
|
|
||||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
if (options?.throwOnUnreadableConfig) {
|
|
||||||
if (error instanceof KeybindingsConfigParseError) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
throw new KeybindingsConfigParseError(
|
|
||||||
configPath,
|
|
||||||
error instanceof Error ? error.message : String(error),
|
|
||||||
{ cause: error },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
logger.warn("ignoring malformed keybindings config", {
|
|
||||||
path: configPath,
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
});
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
|
|
||||||
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
|
||||||
try {
|
|
||||||
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
|
||||||
fs.renameSync(tempPath, configPath);
|
|
||||||
} catch (error) {
|
|
||||||
fs.rmSync(tempPath, { force: true });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
|
||||||
if (custom.length === 0) {
|
|
||||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
|
||||||
}
|
|
||||||
|
|
||||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
|
||||||
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
|
|
||||||
(binding) => !overriddenCommands.has(binding.command),
|
|
||||||
);
|
|
||||||
const merged = [...retainedDefaults, ...custom];
|
|
||||||
|
|
||||||
if (merged.length <= MAX_KEYBINDINGS) {
|
|
||||||
return merged;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
|
||||||
return merged.slice(-MAX_KEYBINDINGS);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function loadResolvedKeybindingsConfig(
|
|
||||||
logger: KeybindingsLogger,
|
|
||||||
): ResolvedKeybindingsConfig {
|
|
||||||
const customConfig = loadCustomKeybindingsConfig(logger);
|
|
||||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
|
|
||||||
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
|
|
||||||
const mergedBeforeCapLength =
|
|
||||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
|
||||||
.length + compiledCustomConfig.length;
|
|
||||||
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
|
|
||||||
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
|
|
||||||
logger.warn("truncating merged keybindings config to max entries", {
|
|
||||||
path: resolveKeybindingsConfigPath(),
|
|
||||||
maxEntries: MAX_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return merged;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function upsertKeybindingRule(
|
|
||||||
logger: KeybindingsLogger,
|
|
||||||
rawRule: unknown,
|
|
||||||
): ResolvedKeybindingsConfig {
|
|
||||||
const rule = keybindingRuleSchema.parse(rawRule);
|
|
||||||
if (!compileResolvedKeybindingRule(rule)) {
|
|
||||||
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const configPath = resolveKeybindingsConfigPath();
|
|
||||||
const customConfig = loadCustomKeybindingsConfig(logger, {
|
|
||||||
throwOnUnreadableConfig: true,
|
|
||||||
});
|
|
||||||
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
|
|
||||||
const cappedConfig =
|
|
||||||
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
|
|
||||||
|
|
||||||
if (nextConfig.length > MAX_KEYBINDINGS) {
|
|
||||||
logger.warn("truncating keybindings config to max entries", {
|
|
||||||
path: configPath,
|
|
||||||
maxEntries: MAX_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
||||||
writeConfigAtomically(configPath, cappedConfig);
|
|
||||||
|
|
||||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
|
|
||||||
return mergeWithDefaultKeybindings(compiledCustomConfig);
|
|
||||||
}
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { ProjectRegistry } from "./projectRegistry";
|
|
||||||
|
|
||||||
const tempDirs: string[] = [];
|
|
||||||
|
|
||||||
function makeTempDir(prefix: string): string {
|
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
||||||
tempDirs.push(dir);
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("ProjectRegistry scripts", () => {
|
|
||||||
it("stores and reloads project scripts", () => {
|
|
||||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
|
||||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
|
||||||
const registry = new ProjectRegistry(stateDir);
|
|
||||||
|
|
||||||
const created = registry.add({ cwd: projectDir }).project;
|
|
||||||
const updated = registry.updateScripts({
|
|
||||||
id: created.id,
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "run",
|
|
||||||
name: "Run",
|
|
||||||
command: "bun run dev",
|
|
||||||
icon: "play",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "bun install",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(updated.project.scripts).toHaveLength(2);
|
|
||||||
expect(updated.project.scripts[1]?.id).toBe("setup");
|
|
||||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
|
|
||||||
|
|
||||||
const reloaded = new ProjectRegistry(stateDir);
|
|
||||||
const listed = reloaded.list();
|
|
||||||
expect(listed).toHaveLength(1);
|
|
||||||
expect(listed[0]?.scripts).toHaveLength(2);
|
|
||||||
expect(listed[0]?.scripts[0]?.id).toBe("run");
|
|
||||||
expect(listed[0]?.scripts[1]?.id).toBe("setup");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("deduplicates script ids and allows only one setup script", () => {
|
|
||||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
|
||||||
const projectDir = makeTempDir("t3code-project-registry-project-");
|
|
||||||
const registry = new ProjectRegistry(stateDir);
|
|
||||||
const created = registry.add({ cwd: projectDir }).project;
|
|
||||||
|
|
||||||
const updated = registry.updateScripts({
|
|
||||||
id: created.id,
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "echo setup",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup Duplicate",
|
|
||||||
command: "echo duplicate",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "another",
|
|
||||||
name: "Another Setup",
|
|
||||||
command: "echo another",
|
|
||||||
icon: "play",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(updated.project.scripts).toHaveLength(2);
|
|
||||||
expect(updated.project.scripts[0]?.id).toBe("setup");
|
|
||||||
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
|
|
||||||
expect(updated.project.scripts[1]?.id).toBe("another");
|
|
||||||
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("throws when updating scripts for an unknown project id", () => {
|
|
||||||
const stateDir = makeTempDir("t3code-project-registry-state-");
|
|
||||||
const registry = new ProjectRegistry(stateDir);
|
|
||||||
|
|
||||||
expect(() =>
|
|
||||||
registry.updateScripts({
|
|
||||||
id: "missing-project",
|
|
||||||
scripts: [],
|
|
||||||
}),
|
|
||||||
).toThrowError("Project not found");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -8,31 +8,11 @@ import {
|
|||||||
type ProjectListResult,
|
type ProjectListResult,
|
||||||
type ProjectRecord,
|
type ProjectRecord,
|
||||||
type ProjectRemoveInput,
|
type ProjectRemoveInput,
|
||||||
type ProjectScript,
|
|
||||||
type ProjectUpdateScriptsInput,
|
|
||||||
type ProjectUpdateScriptsResult,
|
|
||||||
normalizeProjectScripts,
|
|
||||||
projectAddInputSchema,
|
projectAddInputSchema,
|
||||||
projectRecordSchema,
|
projectRecordSchema,
|
||||||
projectRemoveInputSchema,
|
projectRemoveInputSchema,
|
||||||
projectScriptsSchema,
|
|
||||||
projectUpdateScriptsInputSchema,
|
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
|
||||||
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
|
||||||
const cloned: ProjectScript[] = [];
|
|
||||||
for (const script of scripts) {
|
|
||||||
cloned.push({
|
|
||||||
id: script.id,
|
|
||||||
name: script.name,
|
|
||||||
command: script.command,
|
|
||||||
icon: script.icon,
|
|
||||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return cloned;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeCwd(rawCwd: string): string {
|
function normalizeCwd(rawCwd: string): string {
|
||||||
const resolved = path.resolve(rawCwd.trim());
|
const resolved = path.resolve(rawCwd.trim());
|
||||||
const normalized = path.normalize(resolved);
|
const normalized = path.normalize(resolved);
|
||||||
@@ -68,10 +48,7 @@ export class ProjectRegistry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
list(): ProjectListResult {
|
list(): ProjectListResult {
|
||||||
return this.projects.map((project) => ({
|
return this.projects.map((project) => ({ ...project }));
|
||||||
...project,
|
|
||||||
scripts: cloneScripts(project.scripts),
|
|
||||||
}));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
add(raw: ProjectAddInput): ProjectAddResult {
|
add(raw: ProjectAddInput): ProjectAddResult {
|
||||||
@@ -83,13 +60,7 @@ export class ProjectRegistry {
|
|||||||
|
|
||||||
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
return {
|
return { project: { ...existing }, created: false };
|
||||||
project: {
|
|
||||||
...existing,
|
|
||||||
scripts: cloneScripts(existing.scripts),
|
|
||||||
},
|
|
||||||
created: false,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -97,20 +68,13 @@ export class ProjectRegistry {
|
|||||||
id: randomUUID(),
|
id: randomUUID(),
|
||||||
cwd: normalizedCwd,
|
cwd: normalizedCwd,
|
||||||
name: inferProjectName(normalizedCwd),
|
name: inferProjectName(normalizedCwd),
|
||||||
scripts: [],
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
};
|
};
|
||||||
|
|
||||||
this.projects = [project, ...this.projects];
|
this.projects = [project, ...this.projects];
|
||||||
this.persist();
|
this.persist();
|
||||||
return {
|
return { project: { ...project }, created: true };
|
||||||
project: {
|
|
||||||
...project,
|
|
||||||
scripts: cloneScripts(project.scripts),
|
|
||||||
},
|
|
||||||
created: true,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
remove(raw: ProjectRemoveInput): void {
|
remove(raw: ProjectRemoveInput): void {
|
||||||
@@ -124,31 +88,6 @@ export class ProjectRegistry {
|
|||||||
this.persist();
|
this.persist();
|
||||||
}
|
}
|
||||||
|
|
||||||
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
|
|
||||||
const input = projectUpdateScriptsInputSchema.parse(raw);
|
|
||||||
const index = this.projects.findIndex((project) => project.id === input.id);
|
|
||||||
if (index < 0) {
|
|
||||||
throw new Error(`Project not found: ${input.id}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
|
|
||||||
const nextUpdatedAt = new Date().toISOString();
|
|
||||||
const nextProject: ProjectRecord = {
|
|
||||||
...this.projects[index]!,
|
|
||||||
scripts: nextScripts,
|
|
||||||
updatedAt: nextUpdatedAt,
|
|
||||||
};
|
|
||||||
|
|
||||||
const nextProjects = [...this.projects];
|
|
||||||
nextProjects[index] = nextProject;
|
|
||||||
this.projects = nextProjects;
|
|
||||||
this.persist();
|
|
||||||
|
|
||||||
return {
|
|
||||||
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private loadFromDisk(): ProjectRecord[] {
|
private loadFromDisk(): ProjectRecord[] {
|
||||||
const loaded = this.readPersistedProjects();
|
const loaded = this.readPersistedProjects();
|
||||||
const deduped = new Map<string, ProjectRecord>();
|
const deduped = new Map<string, ProjectRecord>();
|
||||||
@@ -168,7 +107,6 @@ export class ProjectRegistry {
|
|||||||
cwd: normalizedCwd,
|
cwd: normalizedCwd,
|
||||||
name:
|
name:
|
||||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||||
scripts: normalizeProjectScripts(project.scripts),
|
|
||||||
};
|
};
|
||||||
deduped.set(normalizedCwd, normalizedProject);
|
deduped.set(normalizedCwd, normalizedProject);
|
||||||
normalizedProjects.push(normalizedProject);
|
normalizedProjects.push(normalizedProject);
|
||||||
@@ -183,7 +121,6 @@ export class ProjectRegistry {
|
|||||||
source.id !== project.id ||
|
source.id !== project.id ||
|
||||||
source.cwd !== project.cwd ||
|
source.cwd !== project.cwd ||
|
||||||
source.name !== project.name ||
|
source.name !== project.name ||
|
||||||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
|
|
||||||
source.createdAt !== project.createdAt ||
|
source.createdAt !== project.createdAt ||
|
||||||
source.updatedAt !== project.updatedAt
|
source.updatedAt !== project.updatedAt
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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,745 +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");
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
manager.getCheckpointDiff({
|
|
||||||
sessionId: "missing-session",
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("Unknown provider session: missing-session");
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("derives checkpoints from thread turns", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const codex = (
|
|
||||||
manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
).codex;
|
|
||||||
|
|
||||||
codex.hasSession = () => true;
|
|
||||||
codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{
|
|
||||||
id: "turn_1",
|
|
||||||
items: [
|
|
||||||
{
|
|
||||||
type: "userMessage",
|
|
||||||
content: [{ type: "text", text: "Refactor the logger" }],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: "agentMessage",
|
|
||||||
text: "I refactored it.",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await manager.listCheckpoints({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
threadId: "thr_1",
|
|
||||||
checkpoints: [
|
|
||||||
{
|
|
||||||
id: "root",
|
|
||||||
turnCount: 0,
|
|
||||||
messageCount: 0,
|
|
||||||
label: "Start of conversation",
|
|
||||||
isCurrent: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "turn_1",
|
|
||||||
turnCount: 1,
|
|
||||||
messageCount: 2,
|
|
||||||
label: "Turn 1",
|
|
||||||
preview: "Refactor the logger",
|
|
||||||
isCurrent: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rolls back from a selected checkpoint turn count", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
rollbackThread: (
|
|
||||||
sessionId: string,
|
|
||||||
numTurns: number,
|
|
||||||
) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
hasCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
restoreCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
pruneAfterTurn: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
maxTurnCount: number;
|
|
||||||
}) => Promise<void>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
{ id: "turn_3", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
internals.codex.rollbackThread = async (sessionId, numTurns) => {
|
|
||||||
rollbackCalls.push({ sessionId, numTurns });
|
|
||||||
return {
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [{ id: "turn_1", items: [] }],
|
|
||||||
};
|
|
||||||
};
|
|
||||||
const hasCheckpoint = vi.fn(async () => true);
|
|
||||||
const restoreCheckpoint = vi.fn(async () => true);
|
|
||||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
|
||||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
|
||||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
|
||||||
|
|
||||||
const result = await manager.revertToCheckpoint({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
|
|
||||||
expect(result.threadId).toBe("thr_1");
|
|
||||||
expect(result.turnCount).toBe(1);
|
|
||||||
expect(result.messageCount).toBe(0);
|
|
||||||
expect(result.rolledBackTurns).toBe(2);
|
|
||||||
expect(result.checkpoints).toHaveLength(2);
|
|
||||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
maxTurnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns diff text for a checkpoint range", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
diffCheckpoints: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
fromTurnCount: number;
|
|
||||||
toTurnCount: number;
|
|
||||||
}) => Promise<string>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
|
||||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
|
||||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
|
||||||
|
|
||||||
const result = await manager.getCheckpointDiff({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toEqual({
|
|
||||||
threadId: "thr_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
diff: "diff --git a/a.ts b/a.ts",
|
|
||||||
});
|
|
||||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("lazily initializes filesystem checkpoints before diffing when cache is missing", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
listSessions: () => Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: "codex";
|
|
||||||
status: "ready";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
cwd?: string;
|
|
||||||
}>;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
|
||||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
|
||||||
captureCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<void>;
|
|
||||||
diffCheckpoints: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
fromTurnCount: number;
|
|
||||||
toTurnCount: number;
|
|
||||||
}) => Promise<string>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.listSessions = () => [
|
|
||||||
{
|
|
||||||
sessionId: "sess_1",
|
|
||||||
provider: "codex",
|
|
||||||
status: "ready",
|
|
||||||
createdAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
cwd: "/repo",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
const isGitRepository = vi.fn(async () => true);
|
|
||||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
|
||||||
const captureCheckpoint = vi.fn(async () => undefined);
|
|
||||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
|
||||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
|
||||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
|
||||||
internals.sessionCheckpointCwds.delete("sess_1");
|
|
||||||
|
|
||||||
const result = await manager.getCheckpointDiff({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
|
||||||
expect(isGitRepository).toHaveBeenCalledWith("/repo");
|
|
||||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 2,
|
|
||||||
});
|
|
||||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
});
|
|
||||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
});
|
|
||||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/repo");
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to process cwd for lazy checkpoint init when session cwd is missing", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
listSessions: () => Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: "codex";
|
|
||||||
status: "ready";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
cwd?: string;
|
|
||||||
}>;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
|
||||||
ensureRootCheckpoint: (input: { cwd: string; threadId: string }) => Promise<boolean>;
|
|
||||||
captureCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<void>;
|
|
||||||
diffCheckpoints: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
fromTurnCount: number;
|
|
||||||
toTurnCount: number;
|
|
||||||
}) => Promise<string>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
|
||||||
try {
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.listSessions = () => [
|
|
||||||
{
|
|
||||||
sessionId: "sess_1",
|
|
||||||
provider: "codex",
|
|
||||||
status: "ready",
|
|
||||||
createdAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [{ id: "turn_1", items: [] }],
|
|
||||||
});
|
|
||||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
|
||||||
const ensureRootCheckpoint = vi.fn(async () => true);
|
|
||||||
const captureCheckpoint = vi.fn(async () => undefined);
|
|
||||||
const diffCheckpoints = vi.fn(async () => "diff --git a/a.ts b/a.ts");
|
|
||||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
|
||||||
internals.filesystemCheckpointStore.ensureRootCheckpoint = ensureRootCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.captureCheckpoint = captureCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.diffCheckpoints = diffCheckpoints;
|
|
||||||
internals.sessionCheckpointCwds.delete("sess_1");
|
|
||||||
|
|
||||||
const result = await manager.getCheckpointDiff({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.diff).toBe("diff --git a/a.ts b/a.ts");
|
|
||||||
expect(isGitRepository).toHaveBeenCalledWith("/fallback-repo");
|
|
||||||
expect(captureCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/fallback-repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
expect(ensureRootCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/fallback-repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
});
|
|
||||||
expect(diffCheckpoints).toHaveBeenCalledWith({
|
|
||||||
cwd: "/fallback-repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
expect(internals.sessionCheckpointCwds.get("sess_1")).toBe("/fallback-repo");
|
|
||||||
} finally {
|
|
||||||
processCwd.mockRestore();
|
|
||||||
manager.dispose();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not fall back to process cwd when a session cwd exists but is not a git repo", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
listSessions: () => Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: "codex";
|
|
||||||
status: "ready";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
cwd?: string;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const processCwd = vi.spyOn(process, "cwd").mockReturnValue("/fallback-repo");
|
|
||||||
try {
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.listSessions = () => [
|
|
||||||
{
|
|
||||||
sessionId: "sess_1",
|
|
||||||
provider: "codex",
|
|
||||||
status: "ready",
|
|
||||||
createdAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
cwd: "/session-cwd",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
const isGitRepository = vi.fn(async (cwd: string) => cwd === "/fallback-repo");
|
|
||||||
internals.filesystemCheckpointStore.isGitRepository = isGitRepository;
|
|
||||||
internals.sessionCheckpointCwds.delete("sess_1");
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
manager.getCheckpointDiff({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
|
||||||
expect(isGitRepository).toHaveBeenCalledWith("/session-cwd");
|
|
||||||
expect(isGitRepository).not.toHaveBeenCalledWith("/fallback-repo");
|
|
||||||
} finally {
|
|
||||||
processCwd.mockRestore();
|
|
||||||
manager.dispose();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fails revert when filesystem checkpoints are unavailable for the session", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
listSessions: () => Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: "codex";
|
|
||||||
status: "ready";
|
|
||||||
createdAt: string;
|
|
||||||
updatedAt: string;
|
|
||||||
cwd?: string;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
isGitRepository: (cwd: string) => Promise<boolean>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.listSessions = () => [
|
|
||||||
{
|
|
||||||
sessionId: "sess_1",
|
|
||||||
provider: "codex",
|
|
||||||
status: "ready",
|
|
||||||
createdAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-18T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
internals.filesystemCheckpointStore.isGitRepository = async () => false;
|
|
||||||
internals.sessionCheckpointCwds.delete("sess_1");
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
manager.revertToCheckpoint({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
turnCount: 1,
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("Filesystem checkpoints are unavailable for this session.");
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
rollbackThread: (
|
|
||||||
sessionId: string,
|
|
||||||
numTurns: number,
|
|
||||||
) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
hasCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
restoreCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
pruneAfterTurn: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
maxTurnCount: number;
|
|
||||||
}) => Promise<void>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
const callOrder: string[] = [];
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
internals.codex.rollbackThread = async () => {
|
|
||||||
callOrder.push("rollback");
|
|
||||||
return {
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [{ id: "turn_1", items: [] }],
|
|
||||||
};
|
|
||||||
};
|
|
||||||
const hasCheckpoint = vi.fn(async () => true);
|
|
||||||
const restoreCheckpoint = vi.fn(async () => {
|
|
||||||
callOrder.push("restore");
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
const pruneAfterTurn = vi.fn(async () => {
|
|
||||||
callOrder.push("prune");
|
|
||||||
return undefined;
|
|
||||||
});
|
|
||||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
|
||||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
|
||||||
|
|
||||||
const result = await manager.revertToCheckpoint({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.turnCount).toBe(1);
|
|
||||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 1,
|
|
||||||
});
|
|
||||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
maxTurnCount: 1,
|
|
||||||
});
|
|
||||||
expect(callOrder).toEqual(["restore", "rollback", "prune"]);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reverts to turn 0 without requiring an explicit turn 0 checkpoint ref", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
rollbackThread: (
|
|
||||||
sessionId: string,
|
|
||||||
numTurns: number,
|
|
||||||
) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
hasCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
restoreCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
pruneAfterTurn: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
maxTurnCount: number;
|
|
||||||
}) => Promise<void>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
internals.codex.rollbackThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [],
|
|
||||||
});
|
|
||||||
const hasCheckpoint = vi.fn(async () => false);
|
|
||||||
const restoreCheckpoint = vi.fn(async () => true);
|
|
||||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
|
||||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
|
||||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
|
||||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
|
||||||
|
|
||||||
const result = await manager.revertToCheckpoint({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
turnCount: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.turnCount).toBe(0);
|
|
||||||
expect(hasCheckpoint).not.toHaveBeenCalled();
|
|
||||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
turnCount: 0,
|
|
||||||
});
|
|
||||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
|
||||||
cwd: "/repo",
|
|
||||||
threadId: "thr_1",
|
|
||||||
maxTurnCount: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("fails before rollback when filesystem checkpoint is missing", async () => {
|
|
||||||
const manager = new ProviderManager();
|
|
||||||
const internals = manager as unknown as {
|
|
||||||
codex: {
|
|
||||||
hasSession: (sessionId: string) => boolean;
|
|
||||||
readThread: (sessionId: string) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
rollbackThread: (
|
|
||||||
sessionId: string,
|
|
||||||
numTurns: number,
|
|
||||||
) => Promise<{
|
|
||||||
threadId: string;
|
|
||||||
turns: Array<{ id: string; items: unknown[] }>;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
filesystemCheckpointStore: {
|
|
||||||
hasCheckpoint: (input: {
|
|
||||||
cwd: string;
|
|
||||||
threadId: string;
|
|
||||||
turnCount: number;
|
|
||||||
}) => Promise<boolean>;
|
|
||||||
};
|
|
||||||
sessionCheckpointCwds: Map<string, string>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const rollbackSpy = vi.fn(async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [{ id: "turn_1", items: [] }],
|
|
||||||
}));
|
|
||||||
|
|
||||||
internals.codex.hasSession = () => true;
|
|
||||||
internals.codex.readThread = async () => ({
|
|
||||||
threadId: "thr_1",
|
|
||||||
turns: [
|
|
||||||
{ id: "turn_1", items: [] },
|
|
||||||
{ id: "turn_2", items: [] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
internals.codex.rollbackThread = rollbackSpy;
|
|
||||||
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
|
|
||||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
manager.revertToCheckpoint({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
turnCount: 1,
|
|
||||||
}),
|
|
||||||
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
|
|
||||||
expect(rollbackSpy).not.toHaveBeenCalled();
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -1,18 +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 ProviderGetCheckpointDiffInput,
|
|
||||||
type ProviderGetCheckpointDiffResult,
|
|
||||||
type ProviderInterruptTurnInput,
|
type ProviderInterruptTurnInput,
|
||||||
type ProviderListCheckpointsInput,
|
|
||||||
type ProviderListCheckpointsResult,
|
|
||||||
type ProviderRevertToCheckpointInput,
|
|
||||||
type ProviderRevertToCheckpointResult,
|
|
||||||
type ProviderRespondToRequestInput,
|
type ProviderRespondToRequestInput,
|
||||||
type ProviderSendTurnInput,
|
type ProviderSendTurnInput,
|
||||||
type ProviderSession,
|
type ProviderSession,
|
||||||
@@ -20,155 +12,23 @@ import {
|
|||||||
type ProviderStopSessionInput,
|
type ProviderStopSessionInput,
|
||||||
type ProviderTurnStartResult,
|
type ProviderTurnStartResult,
|
||||||
providerInterruptTurnInputSchema,
|
providerInterruptTurnInputSchema,
|
||||||
providerGetCheckpointDiffInputSchema,
|
|
||||||
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) {
|
||||||
@@ -177,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() {
|
||||||
@@ -201,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, input.cwd).catch((error) => {
|
|
||||||
const message =
|
|
||||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
|
||||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
|
||||||
});
|
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,138 +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 getCheckpointDiff(
|
|
||||||
raw: ProviderGetCheckpointDiffInput,
|
|
||||||
): Promise<ProviderGetCheckpointDiffResult> {
|
|
||||||
const input = providerGetCheckpointDiffInputSchema.parse(raw);
|
|
||||||
if (!this.codex.hasSession(input.sessionId)) {
|
|
||||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
|
||||||
if (!checkpointCwd) {
|
|
||||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
|
||||||
}
|
|
||||||
|
|
||||||
return this.withFilesystemLock(input.sessionId, async () => {
|
|
||||||
const snapshot = await this.codex.readThread(input.sessionId);
|
|
||||||
if (input.toTurnCount > snapshot.turns.length) {
|
|
||||||
throw new Error(
|
|
||||||
`Checkpoint turn count ${input.toTurnCount} exceeds current turn count ${snapshot.turns.length}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const diff = await this.filesystemCheckpointStore.diffCheckpoints({
|
|
||||||
cwd: checkpointCwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
fromTurnCount: input.fromTurnCount,
|
|
||||||
toTurnCount: input.toTurnCount,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
fromTurnCount: input.fromTurnCount,
|
|
||||||
toTurnCount: input.toTurnCount,
|
|
||||||
diff,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async revertToCheckpoint(
|
|
||||||
raw: ProviderRevertToCheckpointInput,
|
|
||||||
): Promise<ProviderRevertToCheckpointResult> {
|
|
||||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
|
||||||
if (!this.codex.hasSession(input.sessionId)) {
|
|
||||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkpointCwd = await this.getOrInitializeFilesystemCheckpointCwd(input.sessionId);
|
|
||||||
if (!checkpointCwd) {
|
|
||||||
throw new Error("Filesystem checkpoints are unavailable for this session.");
|
|
||||||
}
|
|
||||||
return this.withFilesystemLock(input.sessionId, async () => {
|
|
||||||
const beforeSnapshot = await this.codex.readThread(input.sessionId);
|
|
||||||
const currentTurnCount = beforeSnapshot.turns.length;
|
|
||||||
if (input.turnCount > currentTurnCount) {
|
|
||||||
throw new Error(
|
|
||||||
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (checkpointCwd && input.turnCount > 0) {
|
|
||||||
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
|
|
||||||
cwd: checkpointCwd,
|
|
||||||
threadId: beforeSnapshot.threadId,
|
|
||||||
turnCount: input.turnCount,
|
|
||||||
});
|
|
||||||
if (!hasCheckpoint) {
|
|
||||||
throw new Error(
|
|
||||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
|
|
||||||
cwd: checkpointCwd,
|
|
||||||
threadId: beforeSnapshot.threadId,
|
|
||||||
turnCount: input.turnCount,
|
|
||||||
});
|
|
||||||
if (!restored) {
|
|
||||||
throw new Error(
|
|
||||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestedRollbackTurns = currentTurnCount - input.turnCount;
|
|
||||||
const afterSnapshot =
|
|
||||||
requestedRollbackTurns > 0
|
|
||||||
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
|
|
||||||
: beforeSnapshot;
|
|
||||||
|
|
||||||
await this.filesystemCheckpointStore.pruneAfterTurn({
|
|
||||||
cwd: checkpointCwd,
|
|
||||||
threadId: afterSnapshot.threadId,
|
|
||||||
maxTurnCount: afterSnapshot.turns.length,
|
|
||||||
});
|
|
||||||
|
|
||||||
const checkpoints = buildCheckpoints(afterSnapshot.turns);
|
|
||||||
const currentCheckpoint =
|
|
||||||
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
|
|
||||||
checkpoints[checkpoints.length - 1] ??
|
|
||||||
checkpoints[0];
|
|
||||||
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
|
|
||||||
|
|
||||||
return {
|
|
||||||
threadId: afterSnapshot.threadId,
|
|
||||||
turnCount: currentCheckpoint?.turnCount ?? 0,
|
|
||||||
messageCount: currentCheckpoint?.messageCount ?? 0,
|
|
||||||
rolledBackTurns,
|
|
||||||
checkpoints,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
stopAll(): void {
|
stopAll(): void {
|
||||||
this.codex.stopAll();
|
this.codex.stopAll();
|
||||||
}
|
}
|
||||||
@@ -390,149 +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,
|
|
||||||
preferredCwd?: string,
|
|
||||||
): Promise<void> {
|
|
||||||
const cwd = preferredCwd ?? session.cwd ?? process.cwd();
|
|
||||||
|
|
||||||
await this.withFilesystemLock(session.sessionId, async () => {
|
|
||||||
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
|
|
||||||
if (!supportsGit) {
|
|
||||||
this.sessionCheckpointCwds.delete(session.sessionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const snapshot = await this.codex.readThread(session.sessionId);
|
|
||||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
|
||||||
cwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
});
|
|
||||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
|
||||||
cwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
turnCount: snapshot.turns.length,
|
|
||||||
});
|
|
||||||
if (this.codex.hasSession(session.sessionId)) {
|
|
||||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getOrInitializeFilesystemCheckpointCwd(sessionId: string): Promise<string | null> {
|
|
||||||
const existingCwd = this.sessionCheckpointCwds.get(sessionId);
|
|
||||||
if (existingCwd) {
|
|
||||||
return existingCwd;
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = this.codex
|
|
||||||
.listSessions()
|
|
||||||
.find((candidate) => candidate.sessionId === sessionId);
|
|
||||||
const candidateCwds = session?.cwd ? [session.cwd] : [process.cwd()];
|
|
||||||
|
|
||||||
await this.withFilesystemLock(sessionId, async () => {
|
|
||||||
const currentCwd = this.sessionCheckpointCwds.get(sessionId);
|
|
||||||
if (currentCwd) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cwdSupport = await Promise.all(
|
|
||||||
candidateCwds.map(async (cwd) => ({
|
|
||||||
cwd,
|
|
||||||
supportsGit: await this.filesystemCheckpointStore.isGitRepository(cwd),
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
const supportedCwd = cwdSupport.find((entry) => entry.supportsGit)?.cwd;
|
|
||||||
if (supportedCwd) {
|
|
||||||
const snapshot = await this.codex.readThread(sessionId);
|
|
||||||
await this.filesystemCheckpointStore.ensureRootCheckpoint({
|
|
||||||
cwd: supportedCwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
});
|
|
||||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
|
||||||
cwd: supportedCwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
turnCount: snapshot.turns.length,
|
|
||||||
});
|
|
||||||
if (this.codex.hasSession(sessionId)) {
|
|
||||||
this.sessionCheckpointCwds.set(sessionId, supportedCwd);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.sessionCheckpointCwds.delete(sessionId);
|
|
||||||
});
|
|
||||||
|
|
||||||
return this.sessionCheckpointCwds.get(sessionId) ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
|
||||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
|
||||||
if (!checkpointCwd) {
|
|
||||||
void this.getOrInitializeFilesystemCheckpointCwd(event.sessionId).catch((error) => {
|
|
||||||
const message =
|
|
||||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
|
||||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
void this.withFilesystemLock(event.sessionId, async () => {
|
|
||||||
if (!this.codex.hasSession(event.sessionId)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const snapshot = await this.codex.readThread(event.sessionId);
|
|
||||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
|
||||||
cwd: checkpointCwd,
|
|
||||||
threadId: snapshot.threadId,
|
|
||||||
turnCount: snapshot.turns.length,
|
|
||||||
});
|
|
||||||
}).catch((error) => {
|
|
||||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
|
||||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private emitFilesystemCheckpointError(
|
|
||||||
sessionId: string,
|
|
||||||
message: string,
|
|
||||||
threadId?: string,
|
|
||||||
): void {
|
|
||||||
this.emit("event", {
|
|
||||||
id: randomUUID(),
|
|
||||||
kind: "error",
|
|
||||||
provider: "codex",
|
|
||||||
sessionId,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
method: "checkpoint/filesystemError",
|
|
||||||
message,
|
|
||||||
...(threadId ? { threadId } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
|
||||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
|
||||||
const next = previous.catch(() => undefined).then(fn);
|
|
||||||
const completion = next.then(
|
|
||||||
() => undefined,
|
|
||||||
() => undefined,
|
|
||||||
);
|
|
||||||
this.filesystemLocks.set(sessionId, completion);
|
|
||||||
return next.finally(() => {
|
|
||||||
const tracked = this.filesystemLocks.get(sessionId);
|
|
||||||
if (tracked === completion) {
|
|
||||||
this.filesystemLocks.delete(sessionId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ export interface PtyProcess {
|
|||||||
|
|
||||||
export interface PtySpawnInput {
|
export interface PtySpawnInput {
|
||||||
shell: string;
|
shell: string;
|
||||||
args?: string[];
|
|
||||||
cwd: string;
|
cwd: string;
|
||||||
cols: number;
|
cols: number;
|
||||||
rows: number;
|
rows: number;
|
||||||
@@ -119,7 +118,7 @@ class NodePtyProcess implements PtyProcess {
|
|||||||
export class NodePtyAdapter implements PtyAdapter {
|
export class NodePtyAdapter implements PtyAdapter {
|
||||||
spawn(input: PtySpawnInput): PtyProcess {
|
spawn(input: PtySpawnInput): PtyProcess {
|
||||||
ensureNodePtySpawnHelperExecutable();
|
ensureNodePtySpawnHelperExecutable();
|
||||||
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
|
const ptyProcess = nodePty.spawn(input.shell, [], {
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
cols: input.cols,
|
cols: input.cols,
|
||||||
rows: input.rows,
|
rows: input.rows,
|
||||||
|
|||||||
@@ -196,65 +196,6 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resizes running terminal on open when a different size is requested", async () => {
|
|
||||||
const { manager, ptyAdapter } = makeManager();
|
|
||||||
await manager.open(openInput({ cols: 100, rows: 24 }));
|
|
||||||
const process = ptyAdapter.processes[0];
|
|
||||||
expect(process).toBeDefined();
|
|
||||||
if (!process) return;
|
|
||||||
|
|
||||||
await manager.open(openInput({ cols: 140, rows: 40 }));
|
|
||||||
|
|
||||||
expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("preserves existing terminal size on open when size is omitted", async () => {
|
|
||||||
const { manager, ptyAdapter } = makeManager();
|
|
||||||
await manager.open(openInput({ cols: 100, rows: 24 }));
|
|
||||||
const ptyProcess = ptyAdapter.processes[0];
|
|
||||||
expect(ptyProcess).toBeDefined();
|
|
||||||
if (!ptyProcess) return;
|
|
||||||
|
|
||||||
await manager.open({
|
|
||||||
threadId: "thread-1",
|
|
||||||
cwd: globalThis.process.cwd(),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(ptyProcess.resizeCalls).toEqual([]);
|
|
||||||
|
|
||||||
ptyProcess.emitExit({ exitCode: 0, signal: 0 });
|
|
||||||
await manager.open({
|
|
||||||
threadId: "thread-1",
|
|
||||||
cwd: globalThis.process.cwd(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const resumedSpawn = ptyAdapter.spawnInputs[1];
|
|
||||||
expect(resumedSpawn).toBeDefined();
|
|
||||||
if (!resumedSpawn) return;
|
|
||||||
expect(resumedSpawn.cols).toBe(100);
|
|
||||||
expect(resumedSpawn.rows).toBe(24);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses default dimensions when opening a new terminal without size hints", async () => {
|
|
||||||
const { manager, ptyAdapter } = makeManager();
|
|
||||||
await manager.open({
|
|
||||||
threadId: "thread-1",
|
|
||||||
cwd: process.cwd(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const spawned = ptyAdapter.spawnInputs[0];
|
|
||||||
expect(spawned).toBeDefined();
|
|
||||||
if (!spawned) return;
|
|
||||||
expect(spawned.cols).toBe(120);
|
|
||||||
expect(spawned.rows).toBe(30);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("supports multiple terminals per thread with isolated sessions", async () => {
|
it("supports multiple terminals per thread with isolated sessions", async () => {
|
||||||
const { manager, ptyAdapter } = makeManager();
|
const { manager, ptyAdapter } = makeManager();
|
||||||
await manager.open(openInput({ terminalId: "default" }));
|
await manager.open(openInput({ terminalId: "default" }));
|
||||||
@@ -525,42 +466,4 @@ describe("TerminalManager", () => {
|
|||||||
restoreEnv();
|
restoreEnv();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it("injects runtime env overrides into spawned terminals", async () => {
|
|
||||||
const { manager, ptyAdapter } = makeManager();
|
|
||||||
await manager.open(
|
|
||||||
openInput({
|
|
||||||
env: {
|
|
||||||
T3CODE_PROJECT_ROOT: "/repo",
|
|
||||||
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
|
|
||||||
CUSTOM_FLAG: "1",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
|
||||||
expect(spawnInput).toBeDefined();
|
|
||||||
if (!spawnInput) return;
|
|
||||||
|
|
||||||
expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo");
|
|
||||||
expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a");
|
|
||||||
expect(spawnInput.env.CUSTOM_FLAG).toBe("1");
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => {
|
|
||||||
if (process.platform === "win32") return;
|
|
||||||
const { manager, ptyAdapter } = makeManager(5, {
|
|
||||||
shellResolver: () => "/bin/zsh",
|
|
||||||
});
|
|
||||||
await manager.open(openInput());
|
|
||||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
|
||||||
expect(spawnInput).toBeDefined();
|
|
||||||
if (!spawnInput) return;
|
|
||||||
|
|
||||||
expect(spawnInput.shell).toBe("/bin/zsh");
|
|
||||||
expect(spawnInput.args).toEqual(["-o", "nopromptsp"]);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -26,8 +26,6 @@ import { runProcess } from "./processRunner";
|
|||||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||||
const DEFAULT_OPEN_COLS = 120;
|
|
||||||
const DEFAULT_OPEN_ROWS = 30;
|
|
||||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||||
|
|
||||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||||
@@ -61,16 +59,8 @@ interface TerminalSessionState {
|
|||||||
unsubscribeData: (() => void) | null;
|
unsubscribeData: (() => void) | null;
|
||||||
unsubscribeExit: (() => void) | null;
|
unsubscribeExit: (() => void) | null;
|
||||||
hasRunningSubprocess: boolean;
|
hasRunningSubprocess: boolean;
|
||||||
runtimeEnv: Record<string, string> | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ShellCandidate {
|
|
||||||
shell: string;
|
|
||||||
args?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
type TerminalStartInput = TerminalOpenInput & { cols: number; rows: number };
|
|
||||||
|
|
||||||
function defaultShellResolver(): string {
|
function defaultShellResolver(): string {
|
||||||
if (process.platform === "win32") {
|
if (process.platform === "win32") {
|
||||||
return process.env.ComSpec ?? "cmd.exe";
|
return process.env.ComSpec ?? "cmd.exe";
|
||||||
@@ -92,54 +82,34 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
|||||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
function uniqueShells(shells: Array<string | null>): string[] {
|
||||||
if (!command || command.length === 0) return null;
|
|
||||||
const shellName = path.basename(command).toLowerCase();
|
|
||||||
if (process.platform !== "win32" && shellName === "zsh") {
|
|
||||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
|
||||||
}
|
|
||||||
return { shell: command };
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatShellCandidate(candidate: ShellCandidate): string {
|
|
||||||
if (!candidate.args || candidate.args.length === 0) return candidate.shell;
|
|
||||||
return `${candidate.shell} ${candidate.args.join(" ")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
|
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const ordered: ShellCandidate[] = [];
|
const ordered: string[] = [];
|
||||||
for (const candidate of candidates) {
|
for (const shell of shells) {
|
||||||
if (!candidate) continue;
|
if (!shell || shell.length === 0) continue;
|
||||||
const key = formatShellCandidate(candidate);
|
if (seen.has(shell)) continue;
|
||||||
if (seen.has(key)) continue;
|
seen.add(shell);
|
||||||
seen.add(key);
|
ordered.push(shell);
|
||||||
ordered.push(candidate);
|
|
||||||
}
|
}
|
||||||
return ordered;
|
return ordered;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
function resolveShellCandidates(shellResolver: () => string): string[] {
|
||||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
const requested = normalizeShellCommand(shellResolver());
|
||||||
|
|
||||||
if (process.platform === "win32") {
|
if (process.platform === "win32") {
|
||||||
return uniqueShellCandidates([
|
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
|
||||||
requested,
|
|
||||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
|
||||||
shellCandidateFromCommand("powershell.exe"),
|
|
||||||
shellCandidateFromCommand("cmd.exe"),
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return uniqueShellCandidates([
|
return uniqueShells([
|
||||||
requested,
|
requested,
|
||||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
normalizeShellCommand(process.env.SHELL),
|
||||||
shellCandidateFromCommand("/bin/zsh"),
|
"/bin/zsh",
|
||||||
shellCandidateFromCommand("/bin/bash"),
|
"/bin/bash",
|
||||||
shellCandidateFromCommand("/bin/sh"),
|
"/bin/sh",
|
||||||
shellCandidateFromCommand("zsh"),
|
"zsh",
|
||||||
shellCandidateFromCommand("bash"),
|
"bash",
|
||||||
shellCandidateFromCommand("sh"),
|
"sh",
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -271,33 +241,16 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
|
|||||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createTerminalSpawnEnv(
|
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||||
baseEnv: NodeJS.ProcessEnv,
|
|
||||||
runtimeEnv?: Record<string, string> | null,
|
|
||||||
): NodeJS.ProcessEnv {
|
|
||||||
const spawnEnv: NodeJS.ProcessEnv = {};
|
const spawnEnv: NodeJS.ProcessEnv = {};
|
||||||
for (const [key, value] of Object.entries(baseEnv)) {
|
for (const [key, value] of Object.entries(baseEnv)) {
|
||||||
if (value === undefined) continue;
|
if (value === undefined) continue;
|
||||||
if (shouldExcludeTerminalEnvKey(key)) continue;
|
if (shouldExcludeTerminalEnvKey(key)) continue;
|
||||||
spawnEnv[key] = value;
|
spawnEnv[key] = value;
|
||||||
}
|
}
|
||||||
if (runtimeEnv) {
|
|
||||||
for (const [key, value] of Object.entries(runtimeEnv)) {
|
|
||||||
spawnEnv[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return spawnEnv;
|
return spawnEnv;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizedRuntimeEnv(
|
|
||||||
env: Record<string, string> | undefined,
|
|
||||||
): Record<string, string> | null {
|
|
||||||
if (!env) return null;
|
|
||||||
const entries = Object.entries(env);
|
|
||||||
if (entries.length === 0) return null;
|
|
||||||
return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right)));
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||||
private readonly sessions = new Map<string, TerminalSessionState>();
|
private readonly sessions = new Map<string, TerminalSessionState>();
|
||||||
private readonly logsDir: string;
|
private readonly logsDir: string;
|
||||||
@@ -338,8 +291,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
if (!existing) {
|
if (!existing) {
|
||||||
await this.flushPersistQueue(input.threadId, input.terminalId);
|
await this.flushPersistQueue(input.threadId, input.terminalId);
|
||||||
const history = await this.readHistory(input.threadId, input.terminalId);
|
const history = await this.readHistory(input.threadId, input.terminalId);
|
||||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
|
||||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
|
||||||
const session: TerminalSessionState = {
|
const session: TerminalSessionState = {
|
||||||
threadId: input.threadId,
|
threadId: input.threadId,
|
||||||
terminalId: input.terminalId,
|
terminalId: input.terminalId,
|
||||||
@@ -350,49 +301,37 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
exitCode: null,
|
exitCode: null,
|
||||||
exitSignal: null,
|
exitSignal: null,
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
cols,
|
cols: input.cols,
|
||||||
rows,
|
rows: input.rows,
|
||||||
process: null,
|
process: null,
|
||||||
unsubscribeData: null,
|
unsubscribeData: null,
|
||||||
unsubscribeExit: null,
|
unsubscribeExit: null,
|
||||||
hasRunningSubprocess: false,
|
hasRunningSubprocess: false,
|
||||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
|
||||||
};
|
};
|
||||||
this.sessions.set(sessionKey, session);
|
this.sessions.set(sessionKey, session);
|
||||||
this.startSession(session, { ...input, cols, rows }, "started");
|
this.startSession(session, input, "started");
|
||||||
return this.snapshot(session);
|
return this.snapshot(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
|
if (existing.cwd !== input.cwd) {
|
||||||
const currentRuntimeEnv = existing.runtimeEnv;
|
|
||||||
const targetCols = input.cols ?? existing.cols;
|
|
||||||
const targetRows = input.rows ?? existing.rows;
|
|
||||||
const runtimeEnvChanged =
|
|
||||||
JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv);
|
|
||||||
|
|
||||||
if (existing.cwd !== input.cwd || runtimeEnvChanged) {
|
|
||||||
this.stopProcess(existing);
|
this.stopProcess(existing);
|
||||||
existing.cwd = input.cwd;
|
existing.cwd = input.cwd;
|
||||||
existing.runtimeEnv = nextRuntimeEnv;
|
|
||||||
existing.history = "";
|
existing.history = "";
|
||||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||||
} else if (existing.status === "exited" || existing.status === "error") {
|
} else if (existing.status === "exited" || existing.status === "error") {
|
||||||
existing.runtimeEnv = nextRuntimeEnv;
|
|
||||||
existing.history = "";
|
existing.history = "";
|
||||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||||
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
|
|
||||||
existing.runtimeEnv = nextRuntimeEnv;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!existing.process) {
|
if (!existing.process) {
|
||||||
this.startSession(existing, { ...input, cols: targetCols, rows: targetRows }, "started");
|
this.startSession(existing, input, "started");
|
||||||
return this.snapshot(existing);
|
return this.snapshot(existing);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existing.cols !== targetCols || existing.rows !== targetRows) {
|
if (existing.cols !== input.cols || existing.rows !== input.rows) {
|
||||||
existing.cols = targetCols;
|
existing.cols = input.cols;
|
||||||
existing.rows = targetRows;
|
existing.rows = input.rows;
|
||||||
existing.process.resize(targetCols, targetRows);
|
existing.process.resize(input.cols, input.rows);
|
||||||
existing.updatedAt = new Date().toISOString();
|
existing.updatedAt = new Date().toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,8 +388,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
const sessionKey = toSessionKey(input.threadId, input.terminalId);
|
const sessionKey = toSessionKey(input.threadId, input.terminalId);
|
||||||
let session = this.sessions.get(sessionKey);
|
let session = this.sessions.get(sessionKey);
|
||||||
if (!session) {
|
if (!session) {
|
||||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
|
||||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
|
||||||
session = {
|
session = {
|
||||||
threadId: input.threadId,
|
threadId: input.threadId,
|
||||||
terminalId: input.terminalId,
|
terminalId: input.terminalId,
|
||||||
@@ -461,27 +398,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
exitCode: null,
|
exitCode: null,
|
||||||
exitSignal: null,
|
exitSignal: null,
|
||||||
updatedAt: new Date().toISOString(),
|
updatedAt: new Date().toISOString(),
|
||||||
cols,
|
cols: input.cols,
|
||||||
rows,
|
rows: input.rows,
|
||||||
process: null,
|
process: null,
|
||||||
unsubscribeData: null,
|
unsubscribeData: null,
|
||||||
unsubscribeExit: null,
|
unsubscribeExit: null,
|
||||||
hasRunningSubprocess: false,
|
hasRunningSubprocess: false,
|
||||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
|
||||||
};
|
};
|
||||||
this.sessions.set(sessionKey, session);
|
this.sessions.set(sessionKey, session);
|
||||||
} else {
|
} else {
|
||||||
this.stopProcess(session);
|
this.stopProcess(session);
|
||||||
session.cwd = input.cwd;
|
session.cwd = input.cwd;
|
||||||
session.runtimeEnv = normalizedRuntimeEnv(input.env);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const cols = input.cols ?? session.cols;
|
|
||||||
const rows = input.rows ?? session.rows;
|
|
||||||
|
|
||||||
session.history = "";
|
session.history = "";
|
||||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||||
this.startSession(session, { ...input, cols, rows }, "restarted");
|
this.startSession(session, input, "restarted");
|
||||||
return this.snapshot(session);
|
return this.snapshot(session);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -530,7 +462,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
|
|
||||||
private startSession(
|
private startSession(
|
||||||
session: TerminalSessionState,
|
session: TerminalSessionState,
|
||||||
input: TerminalStartInput,
|
input: TerminalOpenInput,
|
||||||
eventType: "started" | "restarted",
|
eventType: "started" | "restarted",
|
||||||
): void {
|
): void {
|
||||||
this.stopProcess(session);
|
this.stopProcess(session);
|
||||||
@@ -548,20 +480,19 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
let startedShell: string | null = null;
|
let startedShell: string | null = null;
|
||||||
try {
|
try {
|
||||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
const terminalEnv = createTerminalSpawnEnv(process.env);
|
||||||
let lastSpawnError: unknown = null;
|
let lastSpawnError: unknown = null;
|
||||||
|
|
||||||
for (const candidate of shellCandidates) {
|
for (const shell of shellCandidates) {
|
||||||
try {
|
try {
|
||||||
ptyProcess = this.ptyAdapter.spawn({
|
ptyProcess = this.ptyAdapter.spawn({
|
||||||
shell: candidate.shell,
|
shell,
|
||||||
...(candidate.args ? { args: candidate.args } : {}),
|
|
||||||
cwd: session.cwd,
|
cwd: session.cwd,
|
||||||
cols: session.cols,
|
cols: session.cols,
|
||||||
rows: session.rows,
|
rows: session.rows,
|
||||||
env: terminalEnv,
|
env: terminalEnv,
|
||||||
});
|
});
|
||||||
startedShell = formatShellCandidate(candidate);
|
startedShell = shell;
|
||||||
break;
|
break;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastSpawnError = error;
|
lastSpawnError = error;
|
||||||
@@ -575,9 +506,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
const detail =
|
const detail =
|
||||||
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
|
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
|
||||||
const tried =
|
const tried =
|
||||||
shellCandidates.length > 0
|
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
|
||||||
? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
|
|
||||||
: "";
|
|
||||||
throw new Error(`${detail}.${tried}`.trim());
|
throw new Error(`${detail}.${tried}`.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
|
||||||
import type { ProcessRunOptions, ProcessRunResult } from "./processRunner";
|
|
||||||
|
|
||||||
const { runProcessMock } = vi.hoisted(() => ({
|
|
||||||
runProcessMock: vi.fn<
|
|
||||||
(
|
|
||||||
command: string,
|
|
||||||
args: readonly string[],
|
|
||||||
options?: ProcessRunOptions,
|
|
||||||
) => Promise<ProcessRunResult>
|
|
||||||
>(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("./processRunner", () => ({
|
|
||||||
runProcess: runProcessMock,
|
|
||||||
}));
|
|
||||||
|
|
||||||
function processResult(
|
|
||||||
overrides: Partial<ProcessRunResult> & Pick<ProcessRunResult, "stdout" | "code">,
|
|
||||||
): ProcessRunResult {
|
|
||||||
return {
|
|
||||||
stdout: overrides.stdout,
|
|
||||||
code: overrides.code,
|
|
||||||
stderr: overrides.stderr ?? "",
|
|
||||||
signal: overrides.signal ?? null,
|
|
||||||
timedOut: overrides.timedOut ?? false,
|
|
||||||
stdoutTruncated: overrides.stdoutTruncated ?? false,
|
|
||||||
stderrTruncated: overrides.stderrTruncated ?? false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("searchWorkspaceEntries git-ignore chunking", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
runProcessMock.mockReset();
|
|
||||||
vi.resetModules();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("chunks git check-ignore stdin to avoid building giant strings", async () => {
|
|
||||||
const ignoredPaths = Array.from(
|
|
||||||
{ length: 5000 },
|
|
||||||
(_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`,
|
|
||||||
);
|
|
||||||
const keptPaths = ["src/keep.ts", "docs/readme.md"];
|
|
||||||
const listedPaths = [...ignoredPaths, ...keptPaths];
|
|
||||||
let checkIgnoreCalls = 0;
|
|
||||||
|
|
||||||
runProcessMock.mockImplementation(async (_command, args, options) => {
|
|
||||||
if (args[0] === "rev-parse") {
|
|
||||||
return processResult({ code: 0, stdout: "true\n" });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (args[0] === "ls-files") {
|
|
||||||
return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (args[0] === "check-ignore") {
|
|
||||||
checkIgnoreCalls += 1;
|
|
||||||
const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0);
|
|
||||||
const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/"));
|
|
||||||
return processResult({
|
|
||||||
code: chunkIgnored.length > 0 ? 0 : 1,
|
|
||||||
stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(`Unexpected command: git ${args.join(" ")}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
const { searchWorkspaceEntries } = await import("./workspaceEntries");
|
|
||||||
const result = await searchWorkspaceEntries({
|
|
||||||
cwd: "/virtual/workspace",
|
|
||||||
query: "",
|
|
||||||
limit: 100,
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.isAbove(checkIgnoreCalls, 1);
|
|
||||||
assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/")));
|
|
||||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,176 +0,0 @@
|
|||||||
import fs from "node:fs";
|
|
||||||
import fsPromises from "node:fs/promises";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import { spawnSync } from "node:child_process";
|
|
||||||
|
|
||||||
import { afterEach, assert, describe, it, vi } from "vitest";
|
|
||||||
|
|
||||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
|
||||||
|
|
||||||
const tempDirs: string[] = [];
|
|
||||||
|
|
||||||
function makeTempDir(prefix: string): string {
|
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
|
||||||
tempDirs.push(dir);
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
|
|
||||||
function writeFile(cwd: string, relativePath: string, contents = ""): void {
|
|
||||||
const absolutePath = path.join(cwd, relativePath);
|
|
||||||
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
|
||||||
fs.writeFileSync(absolutePath, contents, "utf8");
|
|
||||||
}
|
|
||||||
|
|
||||||
function runGit(cwd: string, args: string[]): void {
|
|
||||||
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
|
|
||||||
if (result.status !== 0) {
|
|
||||||
throw new Error(result.stderr || `git ${args.join(" ")} failed`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("searchWorkspaceEntries", () => {
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns files and directories relative to cwd", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-entries-");
|
|
||||||
writeFile(cwd, "src/components/Composer.tsx");
|
|
||||||
writeFile(cwd, "src/index.ts");
|
|
||||||
writeFile(cwd, "README.md");
|
|
||||||
writeFile(cwd, ".git/HEAD");
|
|
||||||
writeFile(cwd, "node_modules/pkg/index.js");
|
|
||||||
|
|
||||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
|
||||||
const paths = result.entries.map((entry) => entry.path);
|
|
||||||
|
|
||||||
assert.include(paths, "src");
|
|
||||||
assert.include(paths, "src/components");
|
|
||||||
assert.include(paths, "src/components/Composer.tsx");
|
|
||||||
assert.include(paths, "README.md");
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git")));
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules")));
|
|
||||||
assert.isFalse(result.truncated);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("filters and ranks entries by query", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-query-");
|
|
||||||
writeFile(cwd, "src/components/Composer.tsx");
|
|
||||||
writeFile(cwd, "src/components/composePrompt.ts");
|
|
||||||
writeFile(cwd, "docs/composition.md");
|
|
||||||
|
|
||||||
const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 });
|
|
||||||
|
|
||||||
assert.isAbove(result.entries.length, 0);
|
|
||||||
assert.isTrue(result.entries.some((entry) => entry.path === "src/components"));
|
|
||||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("excludes gitignored paths for git repositories", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
|
||||||
runGit(cwd, ["init"]);
|
|
||||||
writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n");
|
|
||||||
writeFile(cwd, "src/keep.ts", "export {};");
|
|
||||||
writeFile(cwd, "ignored.txt", "ignore me");
|
|
||||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
|
||||||
writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}");
|
|
||||||
|
|
||||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
|
||||||
const paths = result.entries.map((entry) => entry.path);
|
|
||||||
|
|
||||||
assert.include(paths, "src");
|
|
||||||
assert.include(paths, "src/keep.ts");
|
|
||||||
assert.notInclude(paths, "ignored.txt");
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/")));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("excludes tracked paths that match ignore rules", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-tracked-gitignore-");
|
|
||||||
runGit(cwd, ["init"]);
|
|
||||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
|
||||||
writeFile(cwd, "src/keep.ts", "export {};");
|
|
||||||
runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]);
|
|
||||||
writeFile(cwd, ".gitignore", ".convex/\n");
|
|
||||||
|
|
||||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
|
||||||
const paths = result.entries.map((entry) => entry.path);
|
|
||||||
|
|
||||||
assert.include(paths, "src");
|
|
||||||
assert.include(paths, "src/keep.ts");
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("excludes .convex in non-git workspaces", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-non-git-convex-");
|
|
||||||
writeFile(cwd, ".convex/local-storage/data.json", "{}");
|
|
||||||
writeFile(cwd, "src/keep.ts", "export {};");
|
|
||||||
|
|
||||||
const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 });
|
|
||||||
const paths = result.entries.map((entry) => entry.path);
|
|
||||||
|
|
||||||
assert.include(paths, "src");
|
|
||||||
assert.include(paths, "src/keep.ts");
|
|
||||||
assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/")));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("deduplicates concurrent index builds for the same cwd", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-concurrent-build-");
|
|
||||||
writeFile(cwd, "src/components/Composer.tsx");
|
|
||||||
|
|
||||||
let rootReadCount = 0;
|
|
||||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
|
||||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
|
||||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
|
||||||
if (args[0] === cwd) {
|
|
||||||
rootReadCount += 1;
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
||||||
}
|
|
||||||
return originalReaddir(...args);
|
|
||||||
}) as typeof fsPromises.readdir,
|
|
||||||
);
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
|
|
||||||
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
|
|
||||||
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.equal(rootReadCount, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("limits concurrent directory reads while walking the filesystem", async () => {
|
|
||||||
const cwd = makeTempDir("t3code-workspace-read-concurrency-");
|
|
||||||
for (let index = 0; index < 80; index += 1) {
|
|
||||||
writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};");
|
|
||||||
}
|
|
||||||
|
|
||||||
let activeReads = 0;
|
|
||||||
let peakReads = 0;
|
|
||||||
const originalReaddir = fsPromises.readdir.bind(fsPromises);
|
|
||||||
vi.spyOn(fsPromises, "readdir").mockImplementation(
|
|
||||||
(async (...args: Parameters<typeof fsPromises.readdir>) => {
|
|
||||||
const target = args[0];
|
|
||||||
if (typeof target === "string" && target.startsWith(cwd)) {
|
|
||||||
activeReads += 1;
|
|
||||||
peakReads = Math.max(peakReads, activeReads);
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 4));
|
|
||||||
try {
|
|
||||||
return await originalReaddir(...args);
|
|
||||||
} finally {
|
|
||||||
activeReads -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return originalReaddir(...args);
|
|
||||||
}) as typeof fsPromises.readdir,
|
|
||||||
);
|
|
||||||
|
|
||||||
await searchWorkspaceEntries({ cwd, query: "", limit: 200 });
|
|
||||||
|
|
||||||
assert.isAtMost(peakReads, 32);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,433 +0,0 @@
|
|||||||
import fs from "node:fs/promises";
|
|
||||||
import type { Dirent } from "node:fs";
|
|
||||||
import path from "node:path";
|
|
||||||
import { runProcess } from "./processRunner";
|
|
||||||
|
|
||||||
import {
|
|
||||||
projectSearchEntriesInputSchema,
|
|
||||||
type ProjectEntry,
|
|
||||||
type ProjectSearchEntriesInput,
|
|
||||||
type ProjectSearchEntriesResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const WORKSPACE_CACHE_TTL_MS = 15_000;
|
|
||||||
const WORKSPACE_CACHE_MAX_KEYS = 4;
|
|
||||||
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
|
|
||||||
const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
|
|
||||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
|
||||||
const IGNORED_DIRECTORY_NAMES = new Set([
|
|
||||||
".git",
|
|
||||||
".convex",
|
|
||||||
"node_modules",
|
|
||||||
".next",
|
|
||||||
".turbo",
|
|
||||||
"dist",
|
|
||||||
"build",
|
|
||||||
"out",
|
|
||||||
".cache",
|
|
||||||
]);
|
|
||||||
|
|
||||||
interface WorkspaceIndex {
|
|
||||||
scannedAt: number;
|
|
||||||
entries: ProjectEntry[];
|
|
||||||
truncated: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
|
||||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
|
||||||
|
|
||||||
function toPosixPath(input: string): string {
|
|
||||||
return input.split(path.sep).join("/");
|
|
||||||
}
|
|
||||||
|
|
||||||
function parentPathOf(input: string): string | undefined {
|
|
||||||
const separatorIndex = input.lastIndexOf("/");
|
|
||||||
if (separatorIndex === -1) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return input.slice(0, separatorIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
function basenameOf(input: string): string {
|
|
||||||
const separatorIndex = input.lastIndexOf("/");
|
|
||||||
if (separatorIndex === -1) {
|
|
||||||
return input;
|
|
||||||
}
|
|
||||||
return input.slice(separatorIndex + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeQuery(input: string): string {
|
|
||||||
return input
|
|
||||||
.trim()
|
|
||||||
.replace(/^[@./]+/, "")
|
|
||||||
.toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
|
||||||
if (!query) {
|
|
||||||
return entry.kind === "directory" ? 0 : 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const normalizedPath = entry.path.toLowerCase();
|
|
||||||
const normalizedName = basenameOf(normalizedPath);
|
|
||||||
|
|
||||||
if (normalizedName === query) return 0;
|
|
||||||
if (normalizedPath === query) return 1;
|
|
||||||
if (normalizedName.startsWith(query)) return 2;
|
|
||||||
if (normalizedPath.startsWith(query)) return 3;
|
|
||||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
|
||||||
return 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
|
||||||
const firstSegment = relativePath.split("/")[0];
|
|
||||||
if (!firstSegment) return false;
|
|
||||||
return IGNORED_DIRECTORY_NAMES.has(firstSegment);
|
|
||||||
}
|
|
||||||
|
|
||||||
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
|
|
||||||
const parts = input.split("\0");
|
|
||||||
if (parts.length === 0) return [];
|
|
||||||
|
|
||||||
// If output was truncated, the final token can be partial.
|
|
||||||
if (truncated && parts[parts.length - 1]?.length) {
|
|
||||||
parts.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
return parts.filter((value) => value.length > 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
function directoryAncestorsOf(relativePath: string): string[] {
|
|
||||||
const segments = relativePath.split("/").filter((segment) => segment.length > 0);
|
|
||||||
if (segments.length <= 1) return [];
|
|
||||||
const directories: string[] = [];
|
|
||||||
for (let index = 1; index < segments.length; index += 1) {
|
|
||||||
directories.push(segments.slice(0, index).join("/"));
|
|
||||||
}
|
|
||||||
return directories;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function mapWithConcurrency<TInput, TOutput>(
|
|
||||||
items: readonly TInput[],
|
|
||||||
concurrency: number,
|
|
||||||
mapper: (item: TInput, index: number) => Promise<TOutput>,
|
|
||||||
): Promise<TOutput[]> {
|
|
||||||
if (items.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
|
|
||||||
const results = Array.from({ length: items.length }) as TOutput[];
|
|
||||||
let nextIndex = 0;
|
|
||||||
|
|
||||||
const workers = Array.from({ length: boundedConcurrency }, async () => {
|
|
||||||
while (nextIndex < items.length) {
|
|
||||||
const currentIndex = nextIndex;
|
|
||||||
nextIndex += 1;
|
|
||||||
results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
await Promise.all(workers);
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
|
|
||||||
const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
|
|
||||||
cwd,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
timeoutMs: 5_000,
|
|
||||||
maxBufferBytes: 4_096,
|
|
||||||
}).catch(() => null);
|
|
||||||
return Boolean(
|
|
||||||
insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
|
|
||||||
if (relativePaths.length === 0) {
|
|
||||||
return relativePaths;
|
|
||||||
}
|
|
||||||
|
|
||||||
const ignoredPaths = new Set<string>();
|
|
||||||
let chunk: string[] = [];
|
|
||||||
let chunkBytes = 0;
|
|
||||||
|
|
||||||
const flushChunk = async (): Promise<boolean> => {
|
|
||||||
if (chunk.length === 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
|
|
||||||
cwd,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
timeoutMs: 20_000,
|
|
||||||
maxBufferBytes: 16 * 1024 * 1024,
|
|
||||||
outputMode: "truncate",
|
|
||||||
stdin: `${chunk.join("\0")}\0`,
|
|
||||||
}).catch(() => null);
|
|
||||||
chunk = [];
|
|
||||||
chunkBytes = 0;
|
|
||||||
|
|
||||||
if (!checkIgnore) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// git-check-ignore exits with 1 when no paths match.
|
|
||||||
if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const matchedIgnoredPaths = splitNullSeparatedPaths(
|
|
||||||
checkIgnore.stdout,
|
|
||||||
Boolean(checkIgnore.stdoutTruncated),
|
|
||||||
);
|
|
||||||
for (const ignoredPath of matchedIgnoredPaths) {
|
|
||||||
ignoredPaths.add(ignoredPath);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const relativePath of relativePaths) {
|
|
||||||
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
|
|
||||||
if (
|
|
||||||
chunk.length > 0 &&
|
|
||||||
chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
|
|
||||||
!(await flushChunk())
|
|
||||||
) {
|
|
||||||
return relativePaths;
|
|
||||||
}
|
|
||||||
|
|
||||||
chunk.push(relativePath);
|
|
||||||
chunkBytes += relativePathBytes;
|
|
||||||
|
|
||||||
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
|
|
||||||
return relativePaths;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(await flushChunk())) {
|
|
||||||
return relativePaths;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ignoredPaths.size === 0) {
|
|
||||||
return relativePaths;
|
|
||||||
}
|
|
||||||
|
|
||||||
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
|
|
||||||
}
|
|
||||||
|
|
||||||
async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
|
|
||||||
if (!(await isInsideGitWorkTree(cwd))) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const listedFiles = await runProcess(
|
|
||||||
"git",
|
|
||||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
|
||||||
{
|
|
||||||
cwd,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
timeoutMs: 20_000,
|
|
||||||
maxBufferBytes: 16 * 1024 * 1024,
|
|
||||||
outputMode: "truncate",
|
|
||||||
},
|
|
||||||
).catch(() => null);
|
|
||||||
if (!listedFiles || listedFiles.code !== 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const listedPaths = splitNullSeparatedPaths(
|
|
||||||
listedFiles.stdout,
|
|
||||||
Boolean(listedFiles.stdoutTruncated),
|
|
||||||
)
|
|
||||||
.map((entry) => toPosixPath(entry))
|
|
||||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
|
||||||
const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
|
|
||||||
|
|
||||||
const directorySet = new Set<string>();
|
|
||||||
for (const filePath of filePaths) {
|
|
||||||
for (const directoryPath of directoryAncestorsOf(filePath)) {
|
|
||||||
if (!isPathInIgnoredDirectory(directoryPath)) {
|
|
||||||
directorySet.add(directoryPath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
|
||||||
.toSorted((left, right) => left.localeCompare(right))
|
|
||||||
.map((directoryPath) => ({
|
|
||||||
path: directoryPath,
|
|
||||||
kind: "directory",
|
|
||||||
parentPath: parentPathOf(directoryPath),
|
|
||||||
}));
|
|
||||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
|
||||||
.toSorted((left, right) => left.localeCompare(right))
|
|
||||||
.map((filePath) => ({
|
|
||||||
path: filePath,
|
|
||||||
kind: "file",
|
|
||||||
parentPath: parentPathOf(filePath),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const entries = [...directoryEntries, ...fileEntries];
|
|
||||||
return {
|
|
||||||
scannedAt: Date.now(),
|
|
||||||
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
|
|
||||||
truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
|
||||||
const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
|
|
||||||
if (gitIndexed) {
|
|
||||||
return gitIndexed;
|
|
||||||
}
|
|
||||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
|
||||||
|
|
||||||
let pendingDirectories: string[] = [""];
|
|
||||||
const entries: ProjectEntry[] = [];
|
|
||||||
let truncated = false;
|
|
||||||
|
|
||||||
while (pendingDirectories.length > 0 && !truncated) {
|
|
||||||
const currentDirectories = pendingDirectories;
|
|
||||||
pendingDirectories = [];
|
|
||||||
const directoryEntries = await mapWithConcurrency(
|
|
||||||
currentDirectories,
|
|
||||||
WORKSPACE_SCAN_READDIR_CONCURRENCY,
|
|
||||||
async (relativeDir) => {
|
|
||||||
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
|
|
||||||
try {
|
|
||||||
const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
|
|
||||||
return { relativeDir, dirents };
|
|
||||||
} catch (error) {
|
|
||||||
if (!relativeDir) {
|
|
||||||
throw new Error(
|
|
||||||
`Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
|
|
||||||
{ cause: error },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return { relativeDir, dirents: null };
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
|
|
||||||
const { relativeDir, dirents } = directoryEntry;
|
|
||||||
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
|
|
||||||
|
|
||||||
dirents.sort((left, right) => left.name.localeCompare(right.name));
|
|
||||||
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
|
|
||||||
for (const dirent of dirents) {
|
|
||||||
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!dirent.isDirectory() && !dirent.isFile()) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const relativePath = toPosixPath(
|
|
||||||
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
|
|
||||||
);
|
|
||||||
if (isPathInIgnoredDirectory(relativePath)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
candidates.push({ dirent, relativePath });
|
|
||||||
}
|
|
||||||
return candidates;
|
|
||||||
});
|
|
||||||
|
|
||||||
const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
|
|
||||||
candidateEntries.map((entry) => entry.relativePath),
|
|
||||||
);
|
|
||||||
const allowedPathSet = shouldFilterWithGitIgnore
|
|
||||||
? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
|
|
||||||
: null;
|
|
||||||
|
|
||||||
for (const candidateEntries of candidateEntriesByDirectory) {
|
|
||||||
for (const candidate of candidateEntries) {
|
|
||||||
if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const entry: ProjectEntry = {
|
|
||||||
path: candidate.relativePath,
|
|
||||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
|
||||||
parentPath: parentPathOf(candidate.relativePath),
|
|
||||||
};
|
|
||||||
entries.push(entry);
|
|
||||||
|
|
||||||
if (candidate.dirent.isDirectory()) {
|
|
||||||
pendingDirectories.push(candidate.relativePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
|
|
||||||
truncated = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (truncated) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
scannedAt: Date.now(),
|
|
||||||
entries,
|
|
||||||
truncated,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
|
||||||
const cached = workspaceIndexCache.get(cwd);
|
|
||||||
if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
|
|
||||||
return cached;
|
|
||||||
}
|
|
||||||
|
|
||||||
const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
|
|
||||||
if (inFlight) {
|
|
||||||
return inFlight;
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextPromise = buildWorkspaceIndex(cwd)
|
|
||||||
.then((next) => {
|
|
||||||
workspaceIndexCache.set(cwd, next);
|
|
||||||
while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
|
|
||||||
const oldestKey = workspaceIndexCache.keys().next().value;
|
|
||||||
if (!oldestKey) break;
|
|
||||||
workspaceIndexCache.delete(oldestKey);
|
|
||||||
}
|
|
||||||
return next;
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
inFlightWorkspaceIndexBuilds.delete(cwd);
|
|
||||||
});
|
|
||||||
inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
|
|
||||||
return nextPromise;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function searchWorkspaceEntries(
|
|
||||||
input: ProjectSearchEntriesInput,
|
|
||||||
): Promise<ProjectSearchEntriesResult> {
|
|
||||||
const parsed = projectSearchEntriesInputSchema.parse(input);
|
|
||||||
const index = await getWorkspaceIndex(parsed.cwd);
|
|
||||||
const normalizedQuery = normalizeQuery(parsed.query);
|
|
||||||
const candidates = normalizedQuery
|
|
||||||
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
|
|
||||||
: index.entries;
|
|
||||||
|
|
||||||
const ranked = candidates.toSorted((left, right) => {
|
|
||||||
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
|
|
||||||
if (scoreDelta !== 0) return scoreDelta;
|
|
||||||
return left.path.localeCompare(right.path);
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
entries: ranked.slice(0, parsed.limit),
|
|
||||||
truncated: index.truncated || ranked.length > parsed.limit,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -11,13 +11,10 @@ import {
|
|||||||
DEFAULT_TERMINAL_ID,
|
DEFAULT_TERMINAL_ID,
|
||||||
WS_CHANNELS,
|
WS_CHANNELS,
|
||||||
WS_METHODS,
|
WS_METHODS,
|
||||||
type KeybindingsConfig,
|
|
||||||
type ResolvedKeybindingsConfig,
|
|
||||||
type WsPush,
|
type WsPush,
|
||||||
type WsResponse,
|
type WsResponse,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { ProjectRegistry } from "./projectRegistry";
|
import { ProjectRegistry } from "./projectRegistry";
|
||||||
import { compileResolvedKeybindingRule, DEFAULT_KEYBINDINGS } from "./keybindings";
|
|
||||||
import type {
|
import type {
|
||||||
TerminalClearInput,
|
TerminalClearInput,
|
||||||
TerminalCloseInput,
|
TerminalCloseInput,
|
||||||
@@ -195,32 +192,6 @@ async function sendRequest(ws: WebSocket, method: string, params?: unknown): Pro
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsConfig {
|
|
||||||
const resolved: ResolvedKeybindingsConfig = [];
|
|
||||||
for (const binding of bindings) {
|
|
||||||
const compiled = compileResolvedKeybindingRule(binding);
|
|
||||||
if (!compiled) {
|
|
||||||
throw new Error(`Unexpected invalid keybinding in test setup: ${binding.command}`);
|
|
||||||
}
|
|
||||||
resolved.push(compiled);
|
|
||||||
}
|
|
||||||
return resolved;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
|
||||||
|
|
||||||
function mergeWithDefaultsForTest(custom: KeybindingsConfig): ResolvedKeybindingsConfig {
|
|
||||||
if (custom.length === 0) {
|
|
||||||
return DEFAULT_RESOLVED_KEYBINDINGS;
|
|
||||||
}
|
|
||||||
|
|
||||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
|
||||||
const retainedDefaults = DEFAULT_KEYBINDINGS.filter(
|
|
||||||
(binding) => !overriddenCommands.has(binding.command),
|
|
||||||
);
|
|
||||||
return compileKeybindings([...retainedDefaults, ...custom].slice(-256));
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("WebSocket Server", () => {
|
describe("WebSocket Server", () => {
|
||||||
let server: ReturnType<typeof createServer> | null = null;
|
let server: ReturnType<typeof createServer> | null = null;
|
||||||
const connections: WebSocket[] = [];
|
const connections: WebSocket[] = [];
|
||||||
@@ -323,8 +294,6 @@ describe("WebSocket Server", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("responds to server.getConfig", async () => {
|
it("responds to server.getConfig", async () => {
|
||||||
const fakeHome = makeTempDir("t3code-home-");
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
server = createTestServer({ cwd: "/my/workspace" });
|
||||||
await server.start();
|
await server.start();
|
||||||
const addr = server.httpServer.address();
|
const addr = server.httpServer.address();
|
||||||
@@ -338,278 +307,7 @@ describe("WebSocket Server", () => {
|
|||||||
|
|
||||||
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
const response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
||||||
expect(response.error).toBeUndefined();
|
expect(response.error).toBeUndefined();
|
||||||
expect(response.result).toEqual({
|
expect(response.result).toEqual({ cwd: "/my/workspace" });
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reads keybindings from ~/.t3/keybindings.json", async () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-home-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(configDir, "keybindings.json"),
|
|
||||||
JSON.stringify([
|
|
||||||
{ key: "cmd+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
|
||||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
|
||||||
]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: mergeWithDefaultsForTest([
|
|
||||||
{ key: "cmd+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
|
||||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
|
||||||
]),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("warns and ignores invalid keybinding entries", async () => {
|
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
||||||
const fakeHome = makeTempDir("t3code-home-invalid-entry-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(configDir, "keybindings.json"),
|
|
||||||
JSON.stringify([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+z", command: "invalid.command", when: "terminalFocus" },
|
|
||||||
]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: mergeWithDefaultsForTest([{ key: "mod+j", command: "terminal.toggle" }]),
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
warnSpy.mock.calls.some(([message]) =>
|
|
||||||
String(message).includes("ignoring invalid keybinding entries"),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("warns and ignores keybindings with malformed when expressions", async () => {
|
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
||||||
const fakeHome = makeTempDir("t3code-home-invalid-when-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(configDir, "keybindings.json"),
|
|
||||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle", when: "terminalFocus && (" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
warnSpy.mock.calls.some(([message]) =>
|
|
||||||
String(message).includes("ignoring invalid keybinding entries"),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reads keybindings once at startup and caches the resolved config", async () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-home-cached-config-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(
|
|
||||||
keybindingsPath,
|
|
||||||
JSON.stringify([{ key: "cmd+j", command: "terminal.toggle" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 firstResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(firstResponse.error).toBeUndefined();
|
|
||||||
expect(firstResponse.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: mergeWithDefaultsForTest([{ key: "cmd+j", command: "terminal.toggle" }]),
|
|
||||||
});
|
|
||||||
|
|
||||||
fs.writeFileSync(
|
|
||||||
keybindingsPath,
|
|
||||||
JSON.stringify([{ key: "cmd+k", command: "terminal.toggle" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
|
|
||||||
const secondResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(secondResponse.error).toBeUndefined();
|
|
||||||
expect(secondResponse.result).toEqual(firstResponse.result);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("upserts keybinding rules and updates cached server config", async () => {
|
|
||||||
const fakeHome = makeTempDir("t3code-home-upsert-keybinding-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
const keybindingsPath = path.join(configDir, "keybindings.json");
|
|
||||||
fs.writeFileSync(
|
|
||||||
keybindingsPath,
|
|
||||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, {
|
|
||||||
key: "mod+shift+r",
|
|
||||||
command: "script.run-tests.run",
|
|
||||||
});
|
|
||||||
expect(upsertResponse.error).toBeUndefined();
|
|
||||||
expect(upsertResponse.result).toEqual({
|
|
||||||
keybindings: mergeWithDefaultsForTest([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]),
|
|
||||||
});
|
|
||||||
|
|
||||||
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as Array<{
|
|
||||||
key: string;
|
|
||||||
command: string;
|
|
||||||
}>;
|
|
||||||
expect(persistedConfig).toEqual([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]);
|
|
||||||
|
|
||||||
const configResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(configResponse.error).toBeUndefined();
|
|
||||||
expect(configResponse.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: mergeWithDefaultsForTest([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
|
||||||
]),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("warns and ignores unsupported keybindings config format", async () => {
|
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
||||||
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(
|
|
||||||
path.join(configDir, "keybindings.json"),
|
|
||||||
JSON.stringify({ "terminal.toggle": "mod+j" }),
|
|
||||||
"utf8",
|
|
||||||
);
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
warnSpy.mock.calls.some(([message]) =>
|
|
||||||
String(message).includes("unsupported format; expected array"),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("warns and ignores malformed keybindings config files", async () => {
|
|
||||||
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
||||||
const fakeHome = makeTempDir("t3code-home-invalid-");
|
|
||||||
const configDir = path.join(fakeHome, ".t3");
|
|
||||||
fs.mkdirSync(configDir, { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(configDir, "keybindings.json"), "{not-json", "utf8");
|
|
||||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/my/workspace" });
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.serverGetConfig);
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
cwd: "/my/workspace",
|
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
warnSpy.mock.calls.some(([message]) =>
|
|
||||||
String(message).includes("ignoring malformed keybindings config"),
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns error for unknown methods", async () => {
|
it("returns error for unknown methods", async () => {
|
||||||
@@ -646,38 +344,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");
|
|
||||||
|
|
||||||
const diffResponse = await sendRequest(ws, WS_METHODS.providersGetCheckpointDiff, {
|
|
||||||
sessionId: "missing-session",
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: 1,
|
|
||||||
});
|
|
||||||
expect(diffResponse.result).toBeUndefined();
|
|
||||||
expect(diffResponse.error?.message).toContain("Unknown provider session");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("routes terminal RPC methods and broadcasts terminal events", async () => {
|
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();
|
||||||
@@ -843,42 +509,6 @@ describe("WebSocket Server", () => {
|
|||||||
expect(projectId).toBeTruthy();
|
expect(projectId).toBeTruthy();
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
|
|
||||||
const updatedScripts = await sendRequest(ws, WS_METHODS.projectsUpdateScripts, {
|
|
||||||
id: projectId,
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "bun install",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
expect(updatedScripts.error).toBeUndefined();
|
|
||||||
const scriptPayload = (
|
|
||||||
updatedScripts.result as {
|
|
||||||
project: {
|
|
||||||
scripts: Array<{
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
command: string;
|
|
||||||
icon: string;
|
|
||||||
runOnWorktreeCreate: boolean;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
).project.scripts;
|
|
||||||
expect(scriptPayload).toEqual([
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "bun install",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
|
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
|
||||||
id: projectId,
|
id: projectId,
|
||||||
});
|
});
|
||||||
@@ -889,38 +519,6 @@ describe("WebSocket Server", () => {
|
|||||||
expect(afterRemove.result).toEqual([]);
|
expect(afterRemove.result).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("supports projects.searchEntries", async () => {
|
|
||||||
const workspace = makeTempDir("t3code-ws-workspace-entries-");
|
|
||||||
fs.mkdirSync(path.join(workspace, "src", "components"), { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(workspace, "src", "components", "Composer.tsx"), "export {};", "utf8");
|
|
||||||
fs.writeFileSync(path.join(workspace, "README.md"), "# test", "utf8");
|
|
||||||
fs.mkdirSync(path.join(workspace, ".git"), { recursive: true });
|
|
||||||
fs.writeFileSync(path.join(workspace, ".git", "HEAD"), "ref: refs/heads/main\n", "utf8");
|
|
||||||
|
|
||||||
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 response = await sendRequest(ws, WS_METHODS.projectsSearchEntries, {
|
|
||||||
cwd: workspace,
|
|
||||||
query: "comp",
|
|
||||||
limit: 10,
|
|
||||||
});
|
|
||||||
expect(response.error).toBeUndefined();
|
|
||||||
expect(response.result).toEqual({
|
|
||||||
entries: expect.arrayContaining([
|
|
||||||
expect.objectContaining({ path: "src/components", kind: "directory" }),
|
|
||||||
expect.objectContaining({ path: "src/components/Composer.tsx", kind: "file" }),
|
|
||||||
]),
|
|
||||||
truncated: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("supports git methods over websocket", async () => {
|
it("supports git methods over websocket", async () => {
|
||||||
const repoCwd = makeTempDir("t3code-ws-git-project-");
|
const repoCwd = makeTempDir("t3code-ws-git-project-");
|
||||||
|
|
||||||
|
|||||||
@@ -31,8 +31,6 @@ import {
|
|||||||
removeGitWorktree,
|
removeGitWorktree,
|
||||||
} from "./git";
|
} from "./git";
|
||||||
import { TerminalManager } from "./terminalManager";
|
import { TerminalManager } from "./terminalManager";
|
||||||
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
|
|
||||||
import { searchWorkspaceEntries } from "./workspaceEntries";
|
|
||||||
|
|
||||||
const MIME_TYPES: Record<string, string> = {
|
const MIME_TYPES: Record<string, string> = {
|
||||||
".html": "text/html; charset=utf-8",
|
".html": "text/html; charset=utf-8",
|
||||||
@@ -92,7 +90,6 @@ export function createServer(options: ServerOptions) {
|
|||||||
const logger = createLogger("ws");
|
const logger = createLogger("ws");
|
||||||
const logWebSocketEvents =
|
const logWebSocketEvents =
|
||||||
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
|
||||||
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
|
|
||||||
|
|
||||||
function logOutgoingPush(push: WsPush, recipients: number) {
|
function logOutgoingPush(push: WsPush, recipients: number) {
|
||||||
if (!logWebSocketEvents) return;
|
if (!logWebSocketEvents) return;
|
||||||
@@ -310,15 +307,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.providersGetCheckpointDiff:
|
|
||||||
return providerManager.getCheckpointDiff(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();
|
||||||
|
|
||||||
@@ -329,11 +317,6 @@ export function createServer(options: ServerOptions) {
|
|||||||
projectRegistry.remove(request.params as never);
|
projectRegistry.remove(request.params as never);
|
||||||
return undefined;
|
return undefined;
|
||||||
|
|
||||||
case WS_METHODS.projectsSearchEntries:
|
|
||||||
return searchWorkspaceEntries(request.params as never);
|
|
||||||
case WS_METHODS.projectsUpdateScripts:
|
|
||||||
return projectRegistry.updateScripts(request.params as never);
|
|
||||||
|
|
||||||
case WS_METHODS.shellOpenInEditor: {
|
case WS_METHODS.shellOpenInEditor: {
|
||||||
const params = request.params as {
|
const params = request.params as {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
@@ -427,16 +410,7 @@ export function createServer(options: ServerOptions) {
|
|||||||
return undefined;
|
return undefined;
|
||||||
|
|
||||||
case WS_METHODS.serverGetConfig:
|
case WS_METHODS.serverGetConfig:
|
||||||
return {
|
return { cwd };
|
||||||
cwd,
|
|
||||||
keybindings: keybindingsConfig,
|
|
||||||
};
|
|
||||||
|
|
||||||
case WS_METHODS.serverUpsertKeybinding:
|
|
||||||
keybindingsConfig = upsertKeybindingRule(logger, request.params);
|
|
||||||
return {
|
|
||||||
keybindings: keybindingsConfig,
|
|
||||||
};
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new Error(`Unknown method: ${request.method}`);
|
throw new Error(`Unknown method: ${request.method}`);
|
||||||
|
|||||||
@@ -12,9 +12,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.2.0",
|
"@base-ui/react": "^1.2.0",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
"@tanstack/react-pacer": "^0.19.4",
|
|
||||||
"@tanstack/react-query": "^5.90.0",
|
"@tanstack/react-query": "^5.90.0",
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
|
|||||||
+3
-66
@@ -1,7 +1,8 @@
|
|||||||
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Activity, Suspense, lazy, useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
import ChatView from "./components/ChatView";
|
import ChatView from "./components/ChatView";
|
||||||
|
import DiffPanel from "./components/DiffPanel";
|
||||||
import Sidebar from "./components/Sidebar";
|
import Sidebar from "./components/Sidebar";
|
||||||
import { isElectron } from "./env";
|
import { isElectron } from "./env";
|
||||||
import { DEFAULT_MODEL } from "./model-logic";
|
import { DEFAULT_MODEL } from "./model-logic";
|
||||||
@@ -9,50 +10,9 @@ import { StoreProvider, useStore } from "./store";
|
|||||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||||
import { onServerWelcome } from "./wsNativeApi";
|
import { onServerWelcome } from "./wsNativeApi";
|
||||||
import { useNativeApi } from "./hooks/useNativeApi";
|
import { useNativeApi } from "./hooks/useNativeApi";
|
||||||
import { useMediaQuery } from "./hooks/useMediaQuery";
|
|
||||||
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
|
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
|
||||||
import { Sheet, SheetPopup } from "./components/ui/sheet";
|
|
||||||
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
||||||
|
|
||||||
const DiffPanel = lazy(() => import("./components/DiffPanel"));
|
|
||||||
const DiffWorkerPoolProvider = lazy(() =>
|
|
||||||
import("./components/DiffPanel").then((module) => ({
|
|
||||||
default: module.DiffWorkerPoolProvider,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
|
||||||
|
|
||||||
const DiffPanelWrapper = (props: { children: React.ReactNode; sheet: boolean }) => {
|
|
||||||
const { state, dispatch } = useStore();
|
|
||||||
if (props.sheet) {
|
|
||||||
return (
|
|
||||||
<Sheet
|
|
||||||
open={state.diffOpen}
|
|
||||||
onOpenChange={(open) => {
|
|
||||||
if (!open) {
|
|
||||||
dispatch({ type: "CLOSE_DIFF" });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<SheetPopup
|
|
||||||
side="right"
|
|
||||||
showCloseButton={false}
|
|
||||||
keepMounted
|
|
||||||
className="w-[min(88vw,820px)] max-w-[820px] p-0"
|
|
||||||
>
|
|
||||||
{props.children}
|
|
||||||
</SheetPopup>
|
|
||||||
</Sheet>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
|
|
||||||
{props.children}
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
function EventRouter() {
|
function EventRouter() {
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
const { dispatch } = useStore();
|
const { dispatch } = useStore();
|
||||||
@@ -125,7 +85,6 @@ function AutoProjectBootstrap() {
|
|||||||
cwd: payload.cwd,
|
cwd: payload.cwd,
|
||||||
model: DEFAULT_MODEL,
|
model: DEFAULT_MODEL,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
dispatch({
|
dispatch({
|
||||||
@@ -151,7 +110,6 @@ function AutoProjectBootstrap() {
|
|||||||
session: null,
|
session: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
events: [],
|
events: [],
|
||||||
turnDiffSummaries: [],
|
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -188,7 +146,6 @@ function DesktopProjectBootstrap() {
|
|||||||
cwd: project.cwd,
|
cwd: project.cwd,
|
||||||
model: DEFAULT_MODEL,
|
model: DEFAULT_MODEL,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: project.scripts,
|
|
||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
bootstrappedRef.current = true;
|
bootstrappedRef.current = true;
|
||||||
@@ -218,18 +175,6 @@ function DesktopProjectBootstrap() {
|
|||||||
function Layout() {
|
function Layout() {
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
const { state } = useStore();
|
const { state } = useStore();
|
||||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
|
||||||
|
|
||||||
const diffLoadingFallback =
|
|
||||||
!state.diffOpen || shouldUseDiffSheet ? (
|
|
||||||
<div className="flex h-full min-h-0 items-center justify-center px-4 text-center text-xs text-muted-foreground/70">
|
|
||||||
Loading diff viewer...
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<aside className="flex h-full w-[560px] shrink-0 items-center justify-center border-l border-border bg-card px-4 text-center text-xs text-muted-foreground/70">
|
|
||||||
Loading diff viewer...
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!api) {
|
if (!api) {
|
||||||
return (
|
return (
|
||||||
@@ -248,15 +193,7 @@ function Layout() {
|
|||||||
<DesktopProjectBootstrap />
|
<DesktopProjectBootstrap />
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
<ChatView />
|
<ChatView />
|
||||||
<Activity mode={state.diffOpen ? "visible" : "hidden"}>
|
{state.diffOpen && <DiffPanel />}
|
||||||
<DiffPanelWrapper sheet={shouldUseDiffSheet}>
|
|
||||||
<Suspense fallback={diffLoadingFallback}>
|
|
||||||
<DiffWorkerPoolProvider>
|
|
||||||
<DiffPanel mode={shouldUseDiffSheet ? "sheet" : "inline"} />
|
|
||||||
</DiffWorkerPoolProvider>
|
|
||||||
</Suspense>
|
|
||||||
</DiffPanelWrapper>
|
|
||||||
</Activity>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
|
|
||||||
|
|
||||||
describe("isScrollContainerNearBottom", () => {
|
|
||||||
it("returns true when already at bottom", () => {
|
|
||||||
expect(
|
|
||||||
isScrollContainerNearBottom({
|
|
||||||
scrollTop: 600,
|
|
||||||
clientHeight: 400,
|
|
||||||
scrollHeight: 1_000,
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns true when within the auto-scroll threshold", () => {
|
|
||||||
expect(
|
|
||||||
isScrollContainerNearBottom({
|
|
||||||
scrollTop: 540,
|
|
||||||
clientHeight: 400,
|
|
||||||
scrollHeight: 1_000,
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false when the user is meaningfully above the bottom", () => {
|
|
||||||
expect(
|
|
||||||
isScrollContainerNearBottom({
|
|
||||||
scrollTop: 520,
|
|
||||||
clientHeight: 400,
|
|
||||||
scrollHeight: 1_000,
|
|
||||||
}),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("clamps negative thresholds to zero", () => {
|
|
||||||
expect(
|
|
||||||
isScrollContainerNearBottom(
|
|
||||||
{
|
|
||||||
scrollTop: 539,
|
|
||||||
clientHeight: 400,
|
|
||||||
scrollHeight: 1_000,
|
|
||||||
},
|
|
||||||
-1,
|
|
||||||
),
|
|
||||||
).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to the default threshold for non-finite values", () => {
|
|
||||||
expect(
|
|
||||||
isScrollContainerNearBottom(
|
|
||||||
{
|
|
||||||
scrollTop: 540,
|
|
||||||
clientHeight: 400,
|
|
||||||
scrollHeight: 1_000,
|
|
||||||
},
|
|
||||||
Number.NaN,
|
|
||||||
),
|
|
||||||
).toBe(true);
|
|
||||||
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
|
|
||||||
|
|
||||||
interface ScrollPosition {
|
|
||||||
scrollTop: number;
|
|
||||||
clientHeight: number;
|
|
||||||
scrollHeight: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isScrollContainerNearBottom(
|
|
||||||
position: ScrollPosition,
|
|
||||||
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
|
|
||||||
): boolean {
|
|
||||||
const threshold = Number.isFinite(thresholdPx)
|
|
||||||
? Math.max(0, thresholdPx)
|
|
||||||
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
|
||||||
|
|
||||||
const { scrollTop, clientHeight, scrollHeight } = position;
|
|
||||||
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
|
|
||||||
return distanceFromBottom <= threshold;
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
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();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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,7 +9,6 @@ import {
|
|||||||
gitCreateBranchAndCheckoutMutationOptions,
|
gitCreateBranchAndCheckoutMutationOptions,
|
||||||
} from "../lib/gitReactQuery";
|
} from "../lib/gitReactQuery";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import {
|
import {
|
||||||
Combobox,
|
Combobox,
|
||||||
@@ -68,35 +67,36 @@ export default function BranchToolbar({
|
|||||||
: branchNames;
|
: branchNames;
|
||||||
// ── Mutations ─────────────────────────────────────────────────────────
|
// ── Mutations ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const checkoutMutation = useMutation(
|
const checkoutMutation = useMutation({
|
||||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||||
);
|
onError: (error) => {
|
||||||
|
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
||||||
|
setIsBranchMenuOpen(true);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const createBranchMutation = useMutation(
|
const createBranchMutation = useMutation({
|
||||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
...gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
||||||
);
|
onError: (error) =>
|
||||||
|
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||||
|
});
|
||||||
|
|
||||||
// ── Effects ───────────────────────────────────────────────────────────
|
// ── Effects ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
// Keep thread branch synced to git current branch for local threads.
|
// Keep thread branch synced to git current branch for local threads.
|
||||||
const queryBranches = branchesQuery.data?.branches;
|
const queryBranches = branchesQuery.data?.branches;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const syncedBranch = deriveSyncedLocalBranch({
|
if (!activeThreadId || activeWorktreePath) return;
|
||||||
activeThreadId,
|
const current = queryBranches?.find((branch) => branch.current);
|
||||||
activeWorktreePath,
|
if (!current) return;
|
||||||
envMode,
|
if (current.name === activeThreadBranch) return;
|
||||||
activeThreadBranch,
|
|
||||||
queryBranches,
|
|
||||||
});
|
|
||||||
if (!activeThreadId || !syncedBranch) return;
|
|
||||||
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: "SET_THREAD_BRANCH",
|
type: "SET_THREAD_BRANCH",
|
||||||
threadId: activeThreadId,
|
threadId: activeThreadId,
|
||||||
branch: syncedBranch,
|
branch: current.name,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
});
|
});
|
||||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isBranchMenuOpen) return;
|
if (isBranchMenuOpen) return;
|
||||||
@@ -153,10 +153,6 @@ export default function BranchToolbar({
|
|||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
onComposerFocusRequest?.();
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
|
||||||
setIsBranchMenuOpen(true);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -171,9 +167,6 @@ export default function BranchToolbar({
|
|||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
onComposerFocusRequest?.();
|
||||||
},
|
},
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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);
|
|
||||||
+434
-1803
File diff suppressed because it is too large.
Load diff
@@ -1,470 +1,58 @@
|
|||||||
import { parsePatchFiles } from "@pierre/diffs";
|
import { XIcon } from "lucide-react";
|
||||||
import {
|
|
||||||
FileDiff,
|
|
||||||
type FileDiffMetadata,
|
|
||||||
Virtualizer,
|
|
||||||
WorkerPoolContextProvider,
|
|
||||||
} from "@pierre/diffs/react";
|
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { Columns2Icon, Rows3Icon } from "lucide-react";
|
|
||||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "~/lib/providerReactQuery";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useNativeApi } from "../hooks/useNativeApi";
|
|
||||||
import { useTheme } from "../hooks/useTheme";
|
|
||||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
|
||||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
|
||||||
import { formatTimestamp } from "../session-logic";
|
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
import { Button } from "./ui/button";
|
||||||
|
|
||||||
type DiffRenderMode = "stacked" | "split";
|
export default function DiffPanel() {
|
||||||
type DiffThemeType = "light" | "dark" | "system";
|
const { dispatch } = useStore();
|
||||||
|
|
||||||
type RenderablePatch =
|
|
||||||
| {
|
|
||||||
kind: "files";
|
|
||||||
files: FileDiffMetadata[];
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
kind: "raw";
|
|
||||||
text: string;
|
|
||||||
reason: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
function getRenderablePatch(patch: string | undefined): RenderablePatch | null {
|
|
||||||
if (!patch) return null;
|
|
||||||
const normalizedPatch = patch.trim();
|
|
||||||
if (normalizedPatch.length === 0) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const parsedPatches = parsePatchFiles(normalizedPatch, buildPatchCacheKey(normalizedPatch));
|
|
||||||
const files = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
|
|
||||||
if (files.length > 0) {
|
|
||||||
return { kind: "files", files };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
kind: "raw",
|
|
||||||
text: normalizedPatch,
|
|
||||||
reason: "Unsupported diff format. Showing raw patch.",
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return {
|
|
||||||
kind: "raw",
|
|
||||||
text: normalizedPatch,
|
|
||||||
reason: "Failed to parse patch. Showing raw patch.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
|
|
||||||
const raw = fileDiff.name ?? fileDiff.prevName ?? "";
|
|
||||||
if (raw.startsWith("a/") || raw.startsWith("b/")) {
|
|
||||||
return raw.slice(2);
|
|
||||||
}
|
|
||||||
return raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
|
||||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DiffPanelProps {
|
|
||||||
mode?: "inline" | "sheet";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
|
||||||
const workerPoolSize = useMemo(() => {
|
|
||||||
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
|
|
||||||
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<WorkerPoolContextProvider
|
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||||
poolOptions={{
|
{/* Header */}
|
||||||
workerFactory: () =>
|
|
||||||
new Worker(new URL("../workers/diffs.worker.ts", import.meta.url), { type: "module" }),
|
|
||||||
poolSize: workerPoolSize,
|
|
||||||
totalASTLRUCacheSize: 240,
|
|
||||||
}}
|
|
||||||
highlighterOptions={{
|
|
||||||
tokenizeMaxLineLength: 1_000,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</WorkerPoolContextProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|
||||||
const api = useNativeApi();
|
|
||||||
const { resolvedTheme } = useTheme();
|
|
||||||
const { state, dispatch } = useStore();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
|
||||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
|
||||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
|
||||||
const activeThreadRuntimeId =
|
|
||||||
activeThread?.codexThreadId ?? activeThread?.session?.threadId ?? null;
|
|
||||||
const activeSessionId = activeThread?.session?.sessionId ?? null;
|
|
||||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
|
||||||
useTurnDiffSummaries(activeThread);
|
|
||||||
|
|
||||||
const canApplyStoredTarget = Boolean(activeThread && state.diffThreadId === activeThread.id);
|
|
||||||
const selectedTurnId = canApplyStoredTarget ? state.diffTurnId : null;
|
|
||||||
const selectedFilePath =
|
|
||||||
canApplyStoredTarget && selectedTurnId !== null ? state.diffFilePath : null;
|
|
||||||
const selectedTurn =
|
|
||||||
selectedTurnId === null
|
|
||||||
? undefined
|
|
||||||
: (turnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
|
||||||
turnDiffSummaries[0]);
|
|
||||||
const selectedCheckpointTurnCount =
|
|
||||||
selectedTurn &&
|
|
||||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
|
||||||
const selectedCheckpointRange = useMemo(
|
|
||||||
() =>
|
|
||||||
typeof selectedCheckpointTurnCount === "number"
|
|
||||||
? {
|
|
||||||
fromTurnCount: Math.max(0, selectedCheckpointTurnCount - 1),
|
|
||||||
toTurnCount: selectedCheckpointTurnCount,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
[selectedCheckpointTurnCount],
|
|
||||||
);
|
|
||||||
const conversationCheckpointTurnCount = useMemo(() => {
|
|
||||||
const turnCounts = turnDiffSummaries
|
|
||||||
.map(
|
|
||||||
(summary) =>
|
|
||||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
|
|
||||||
)
|
|
||||||
.filter((value): value is number => typeof value === "number");
|
|
||||||
if (turnCounts.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
const latest = Math.max(...turnCounts);
|
|
||||||
return latest > 0 ? latest : undefined;
|
|
||||||
}, [inferredCheckpointTurnCountByTurnId, turnDiffSummaries]);
|
|
||||||
const conversationCheckpointRange = useMemo(
|
|
||||||
() =>
|
|
||||||
!selectedTurn && typeof conversationCheckpointTurnCount === "number"
|
|
||||||
? {
|
|
||||||
fromTurnCount: 0,
|
|
||||||
toTurnCount: conversationCheckpointTurnCount,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
[conversationCheckpointTurnCount, selectedTurn],
|
|
||||||
);
|
|
||||||
const activeCheckpointRange = selectedTurn
|
|
||||||
? selectedCheckpointRange
|
|
||||||
: conversationCheckpointRange;
|
|
||||||
const conversationCacheScope = useMemo(() => {
|
|
||||||
if (selectedTurn || turnDiffSummaries.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return `conversation:${turnDiffSummaries.map((summary) => summary.turnId).join(",")}`;
|
|
||||||
}, [selectedTurn, turnDiffSummaries]);
|
|
||||||
const activeCheckpointDiffQuery = useQuery(
|
|
||||||
checkpointDiffQueryOptions(api, {
|
|
||||||
sessionId: activeSessionId,
|
|
||||||
threadRuntimeId: activeThreadRuntimeId,
|
|
||||||
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
|
|
||||||
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
|
|
||||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const selectedTurnCheckpointDiff = selectedTurn
|
|
||||||
? activeCheckpointDiffQuery.data?.diff
|
|
||||||
: undefined;
|
|
||||||
const conversationCheckpointDiff = selectedTurn
|
|
||||||
? undefined
|
|
||||||
: activeCheckpointDiffQuery.data?.diff;
|
|
||||||
const isLoadingCheckpointDiff = activeCheckpointDiffQuery.isLoading;
|
|
||||||
const checkpointDiffError =
|
|
||||||
activeCheckpointDiffQuery.error instanceof Error
|
|
||||||
? activeCheckpointDiffQuery.error.message
|
|
||||||
: activeCheckpointDiffQuery.error
|
|
||||||
? "Failed to load checkpoint diff."
|
|
||||||
: null;
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!activeThread?.id || !selectedTurn || !selectedTurnCheckpointDiff) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
dispatch({
|
|
||||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
|
||||||
threadId: activeThread.id,
|
|
||||||
checkpointDiffByTurnId: {
|
|
||||||
[selectedTurn.turnId]: selectedTurnCheckpointDiff,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}, [activeThread?.id, dispatch, selectedTurn, selectedTurnCheckpointDiff]);
|
|
||||||
|
|
||||||
const selectedPatch = useMemo(() => {
|
|
||||||
const patchForSummary = (summary: (typeof turnDiffSummaries)[number]): string | undefined => {
|
|
||||||
const checkpointTurnCount =
|
|
||||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
|
||||||
if (activeSessionId && typeof checkpointTurnCount === "number") {
|
|
||||||
const checkpointPatch = queryClient.getQueryData<{ diff: string }>(
|
|
||||||
providerQueryKeys.checkpointDiff({
|
|
||||||
sessionId: activeSessionId,
|
|
||||||
threadRuntimeId: activeThreadRuntimeId,
|
|
||||||
fromTurnCount: Math.max(0, checkpointTurnCount - 1),
|
|
||||||
toTurnCount: checkpointTurnCount,
|
|
||||||
cacheScope: `turn:${summary.turnId}`,
|
|
||||||
}),
|
|
||||||
)?.diff;
|
|
||||||
if (checkpointPatch) {
|
|
||||||
return checkpointPatch;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (summary.unifiedDiff) {
|
|
||||||
return summary.unifiedDiff;
|
|
||||||
}
|
|
||||||
const filePatches = summary.files
|
|
||||||
.map((file) => file.diff?.trim())
|
|
||||||
.filter((patch): patch is string => Boolean(patch));
|
|
||||||
if (filePatches.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return filePatches.join("\n\n");
|
|
||||||
};
|
|
||||||
|
|
||||||
if (selectedTurn) {
|
|
||||||
return selectedTurnCheckpointDiff ?? patchForSummary(selectedTurn);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (conversationCheckpointDiff) {
|
|
||||||
return conversationCheckpointDiff;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback when a conversation checkpoint diff isn't available yet:
|
|
||||||
// keep one patch per file path (latest change wins) so files aren't duplicated.
|
|
||||||
const latestPatchByPath = new Map<string, string>();
|
|
||||||
for (const summary of turnDiffSummaries) {
|
|
||||||
for (const file of summary.files) {
|
|
||||||
if (latestPatchByPath.has(file.path)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const patch = file.diff?.trim();
|
|
||||||
if (!patch) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
latestPatchByPath.set(file.path, patch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (latestPatchByPath.size > 0) {
|
|
||||||
return Array.from(latestPatchByPath.entries())
|
|
||||||
.toSorted(([leftPath], [rightPath]) =>
|
|
||||||
leftPath.localeCompare(rightPath, undefined, { numeric: true, sensitivity: "base" }),
|
|
||||||
)
|
|
||||||
.map(([, patch]) => patch)
|
|
||||||
.join("\n\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
const patches = turnDiffSummaries
|
|
||||||
.toReversed()
|
|
||||||
.map((summary) => patchForSummary(summary)?.trim())
|
|
||||||
.filter((patch): patch is string => Boolean(patch));
|
|
||||||
if (patches.length === 0) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return patches.join("\n\n");
|
|
||||||
}, [
|
|
||||||
activeSessionId,
|
|
||||||
activeThreadRuntimeId,
|
|
||||||
conversationCheckpointDiff,
|
|
||||||
inferredCheckpointTurnCountByTurnId,
|
|
||||||
queryClient,
|
|
||||||
selectedTurn,
|
|
||||||
selectedTurnCheckpointDiff,
|
|
||||||
turnDiffSummaries,
|
|
||||||
]);
|
|
||||||
const renderablePatch = useMemo(() => getRenderablePatch(selectedPatch), [selectedPatch]);
|
|
||||||
const renderableFiles = useMemo(() => {
|
|
||||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
return renderablePatch.files.toSorted((left, right) =>
|
|
||||||
resolveFileDiffPath(left).localeCompare(resolveFileDiffPath(right), undefined, {
|
|
||||||
numeric: true,
|
|
||||||
sensitivity: "base",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}, [renderablePatch]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!selectedFilePath || !patchViewportRef.current) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const target = Array.from(
|
|
||||||
patchViewportRef.current.querySelectorAll<HTMLElement>("[data-diff-file-path]"),
|
|
||||||
).find((element) => element.dataset.diffFilePath === selectedFilePath);
|
|
||||||
target?.scrollIntoView({ block: "nearest" });
|
|
||||||
}, [selectedFilePath, renderableFiles]);
|
|
||||||
|
|
||||||
const selectTurn = (turnId: string) => {
|
|
||||||
if (!activeThread) return;
|
|
||||||
dispatch({
|
|
||||||
type: "SET_DIFF_TARGET",
|
|
||||||
threadId: activeThread.id,
|
|
||||||
turnId,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
const selectWholeConversation = () => {
|
|
||||||
if (!activeThread) return;
|
|
||||||
dispatch({
|
|
||||||
type: "SET_DIFF_TARGET",
|
|
||||||
threadId: activeThread.id,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const shouldUseDragRegion = isElectron && mode === "inline";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<aside
|
|
||||||
className={cn(
|
|
||||||
"flex h-full min-w-0 flex-col bg-card",
|
|
||||||
mode === "inline"
|
|
||||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
|
||||||
: "w-full",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||||
"flex items-center justify-between border-b border-border px-4",
|
|
||||||
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
|
|
||||||
)}
|
|
||||||
>
|
>
|
||||||
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
|
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||||
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
|
<Button
|
||||||
<div
|
type="button"
|
||||||
className={cn(
|
size="icon-xs"
|
||||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
variant="ghost"
|
||||||
selectedTurnId === null
|
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||||
? "border-border bg-accent text-accent-foreground"
|
|
||||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="text-[10px] font-medium">All turns</div>
|
|
||||||
<div className="text-[8px] opacity-70">Conversation</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
{turnDiffSummaries.map((summary, index) => (
|
|
||||||
<button
|
|
||||||
key={summary.turnId}
|
|
||||||
type="button"
|
|
||||||
className="shrink-0 rounded-md"
|
|
||||||
onClick={() => selectTurn(summary.turnId)}
|
|
||||||
title={summary.turnId}
|
|
||||||
>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
|
||||||
summary.turnId === selectedTurn?.turnId
|
|
||||||
? "border-border bg-accent text-accent-foreground"
|
|
||||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="text-[10px] font-medium">
|
|
||||||
Turn {turnDiffSummaries.length - index}
|
|
||||||
</div>
|
|
||||||
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<ToggleGroup
|
|
||||||
variant="outline"
|
|
||||||
size="xs"
|
|
||||||
value={[diffRenderMode]}
|
|
||||||
onValueChange={(value) => {
|
|
||||||
const next = value[0];
|
|
||||||
if (next === "stacked" || next === "split") {
|
|
||||||
setDiffRenderMode(next);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
<XIcon />
|
||||||
<Rows3Icon className="size-3" />
|
</Button>
|
||||||
</Toggle>
|
|
||||||
<Toggle aria-label="Split diff view" value="split">
|
|
||||||
<Columns2Icon className="size-3" />
|
|
||||||
</Toggle>
|
|
||||||
</ToggleGroup>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!activeThread ? (
|
{/* Placeholder content */}
|
||||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
<div className="flex-1 overflow-y-auto p-4">
|
||||||
Select a thread to inspect turn diffs.
|
<div className="space-y-3">
|
||||||
</div>
|
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||||
) : turnDiffSummaries.length === 0 ? (
|
<div className="mb-2 flex items-center gap-2">
|
||||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
<span className="rounded bg-emerald-500/20 px-1.5 py-0.5 text-[9px] font-medium text-emerald-400">
|
||||||
No completed turns yet.
|
M
|
||||||
</div>
|
</span>
|
||||||
) : (
|
<span className="font-mono text-xs text-muted-foreground/80">src/App.tsx</span>
|
||||||
<>
|
</div>
|
||||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
<div className="space-y-0.5 font-mono text-[11px]">
|
||||||
{!canApplyStoredTarget && state.diffThreadId && (
|
<div className="text-red-400/60">- const oldValue = "hello";</div>
|
||||||
<div className="px-3 pt-2">
|
<div className="text-emerald-400/60">+ const newValue = "world";</div>
|
||||||
<p className="mb-2 text-[11px] text-muted-foreground/65">
|
</div>
|
||||||
Showing diffs for the active thread.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{checkpointDiffError && !renderablePatch && (
|
|
||||||
<div className="px-3">
|
|
||||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!renderablePatch ? (
|
|
||||||
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
|
|
||||||
<p>
|
|
||||||
{isLoadingCheckpointDiff
|
|
||||||
? "Loading checkpoint diff..."
|
|
||||||
: "No patch available for this selection."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : renderablePatch.kind === "files" ? (
|
|
||||||
<Virtualizer
|
|
||||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
|
||||||
config={{
|
|
||||||
overscrollSize: 600,
|
|
||||||
intersectionObserverMargin: 1200,
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{renderableFiles.map((fileDiff) => {
|
|
||||||
const filePath = resolveFileDiffPath(fileDiff);
|
|
||||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
|
||||||
return (
|
|
||||||
<div key={fileKey} data-diff-file-path={filePath} className="rounded-md">
|
|
||||||
<FileDiff
|
|
||||||
fileDiff={fileDiff}
|
|
||||||
options={{
|
|
||||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
|
||||||
lineDiffType: "none",
|
|
||||||
themeType: resolvedTheme as DiffThemeType,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Virtualizer>
|
|
||||||
) : (
|
|
||||||
<div className="h-full overflow-auto px-3 py-2">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
|
||||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
|
||||||
{renderablePatch.text}
|
|
||||||
</pre>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
|
||||||
)}
|
<div className="rounded-lg border border-border/80 bg-muted p-3">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="rounded bg-blue-500/20 px-1.5 py-0.5 text-[9px] font-medium text-blue-400">
|
||||||
|
A
|
||||||
|
</span>
|
||||||
|
<span className="font-mono text-xs text-muted-foreground/80">src/utils.ts</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="mt-6 text-center text-[10px] text-muted-foreground/30">
|
||||||
|
Diff integration coming soon
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -226,14 +226,17 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
void api.shell.openExternal(prUrl).catch((err) => {
|
const promise = api.shell.openExternal(prUrl);
|
||||||
toastManager.add({
|
toastManager.promise(promise, {
|
||||||
type: "error",
|
loading: { title: "Opening PR...", data: threadToastData },
|
||||||
|
success: { title: "PR opened", data: threadToastData },
|
||||||
|
error: (err) => ({
|
||||||
title: "Unable to open PR link",
|
title: "Unable to open PR link",
|
||||||
description: err instanceof Error ? err.message : "An error occurred.",
|
description: err instanceof Error ? err.message : "An error occurred.",
|
||||||
data: threadToastData,
|
data: threadToastData,
|
||||||
});
|
}),
|
||||||
});
|
});
|
||||||
|
void promise.catch(() => undefined);
|
||||||
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
|
||||||
|
|
||||||
const runGitActionWithToast = useCallback(
|
const runGitActionWithToast = useCallback(
|
||||||
@@ -309,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: {
|
||||||
@@ -627,8 +627,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
|||||||
: gitStatusForActions.aheadCount === 0 &&
|
: gitStatusForActions.aheadCount === 0 &&
|
||||||
gitStatusForActions.behindCount === 0
|
gitStatusForActions.behindCount === 0
|
||||||
? "Up to date"
|
? "Up to date"
|
||||||
: gitStatusForActions.aheadCount > 0 &&
|
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
|
||||||
gitStatusForActions.behindCount > 0
|
|
||||||
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
|
||||||
: gitStatusForActions.aheadCount > 0
|
: gitStatusForActions.aheadCount > 0
|
||||||
? `Ahead by ${gitStatusForActions.aheadCount}`
|
? `Ahead by ${gitStatusForActions.aheadCount}`
|
||||||
|
|||||||
@@ -1,464 +0,0 @@
|
|||||||
import type {
|
|
||||||
ProjectScript,
|
|
||||||
ProjectScriptIcon,
|
|
||||||
ResolvedKeybindingsConfig,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import {
|
|
||||||
BugIcon,
|
|
||||||
ChevronDownIcon,
|
|
||||||
FlaskConicalIcon,
|
|
||||||
HammerIcon,
|
|
||||||
ListChecksIcon,
|
|
||||||
PlayIcon,
|
|
||||||
PlusIcon,
|
|
||||||
SettingsIcon,
|
|
||||||
WrenchIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
|
|
||||||
|
|
||||||
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
|
|
||||||
import { shortcutLabelForCommand } from "~/keybindings";
|
|
||||||
import { isMacPlatform } from "~/lib/utils";
|
|
||||||
import { Button } from "./ui/button";
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogPanel,
|
|
||||||
DialogPopup,
|
|
||||||
DialogTitle,
|
|
||||||
} from "./ui/dialog";
|
|
||||||
import { Group, GroupSeparator } from "./ui/group";
|
|
||||||
import { Input } from "./ui/input";
|
|
||||||
import { Label } from "./ui/label";
|
|
||||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
|
|
||||||
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
|
|
||||||
import { Switch } from "./ui/switch";
|
|
||||||
import { Textarea } from "./ui/textarea";
|
|
||||||
|
|
||||||
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
|
|
||||||
{ id: "play", label: "Play" },
|
|
||||||
{ id: "test", label: "Test" },
|
|
||||||
{ id: "lint", label: "Lint" },
|
|
||||||
{ id: "configure", label: "Configure" },
|
|
||||||
{ id: "build", label: "Build" },
|
|
||||||
{ id: "debug", label: "Debug" },
|
|
||||||
];
|
|
||||||
|
|
||||||
function ScriptIcon({
|
|
||||||
icon,
|
|
||||||
className = "size-3.5",
|
|
||||||
}: {
|
|
||||||
icon: ProjectScriptIcon;
|
|
||||||
className?: string;
|
|
||||||
}) {
|
|
||||||
if (icon === "test") return <FlaskConicalIcon className={className} />;
|
|
||||||
if (icon === "lint") return <ListChecksIcon className={className} />;
|
|
||||||
if (icon === "configure") return <WrenchIcon className={className} />;
|
|
||||||
if (icon === "build") return <HammerIcon className={className} />;
|
|
||||||
if (icon === "debug") return <BugIcon className={className} />;
|
|
||||||
return <PlayIcon className={className} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface NewProjectScriptInput {
|
|
||||||
name: string;
|
|
||||||
command: string;
|
|
||||||
icon: ProjectScriptIcon;
|
|
||||||
runOnWorktreeCreate: boolean;
|
|
||||||
keybinding: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProjectScriptsControlProps {
|
|
||||||
scripts: ProjectScript[];
|
|
||||||
keybindings: ResolvedKeybindingsConfig;
|
|
||||||
preferredScriptId?: string | null;
|
|
||||||
onRunScript: (script: ProjectScript) => void;
|
|
||||||
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
|
|
||||||
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeShortcutKeyToken(key: string): string | null {
|
|
||||||
const normalized = key.toLowerCase();
|
|
||||||
if (
|
|
||||||
normalized === "meta" ||
|
|
||||||
normalized === "control" ||
|
|
||||||
normalized === "ctrl" ||
|
|
||||||
normalized === "shift" ||
|
|
||||||
normalized === "alt" ||
|
|
||||||
normalized === "option"
|
|
||||||
) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (normalized === " ") return "space";
|
|
||||||
if (normalized === "escape") return "esc";
|
|
||||||
if (normalized === "arrowup") return "arrowup";
|
|
||||||
if (normalized === "arrowdown") return "arrowdown";
|
|
||||||
if (normalized === "arrowleft") return "arrowleft";
|
|
||||||
if (normalized === "arrowright") return "arrowright";
|
|
||||||
if (normalized.length === 1) return normalized;
|
|
||||||
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
|
|
||||||
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
if (normalized === "delete" || normalized === "home" || normalized === "end") {
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
if (normalized === "pageup" || normalized === "pagedown") return normalized;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
|
|
||||||
const keyToken = normalizeShortcutKeyToken(event.key);
|
|
||||||
if (!keyToken) return null;
|
|
||||||
|
|
||||||
const parts: string[] = [];
|
|
||||||
if (isMacPlatform(navigator.platform)) {
|
|
||||||
if (event.metaKey) parts.push("mod");
|
|
||||||
if (event.ctrlKey) parts.push("ctrl");
|
|
||||||
} else {
|
|
||||||
if (event.ctrlKey) parts.push("mod");
|
|
||||||
if (event.metaKey) parts.push("meta");
|
|
||||||
}
|
|
||||||
if (event.altKey) parts.push("alt");
|
|
||||||
if (event.shiftKey) parts.push("shift");
|
|
||||||
if (parts.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
parts.push(keyToken);
|
|
||||||
return parts.join("+");
|
|
||||||
}
|
|
||||||
|
|
||||||
function keybindingValueForCommand(
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
command: string,
|
|
||||||
): string | null {
|
|
||||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
|
||||||
const binding = keybindings[index];
|
|
||||||
if (!binding || binding.command !== command) continue;
|
|
||||||
|
|
||||||
const parts: string[] = [];
|
|
||||||
if (binding.shortcut.modKey) parts.push("mod");
|
|
||||||
if (binding.shortcut.ctrlKey) parts.push("ctrl");
|
|
||||||
if (binding.shortcut.metaKey) parts.push("meta");
|
|
||||||
if (binding.shortcut.altKey) parts.push("alt");
|
|
||||||
if (binding.shortcut.shiftKey) parts.push("shift");
|
|
||||||
const keyToken =
|
|
||||||
binding.shortcut.key === " "
|
|
||||||
? "space"
|
|
||||||
: binding.shortcut.key === "escape"
|
|
||||||
? "esc"
|
|
||||||
: binding.shortcut.key;
|
|
||||||
parts.push(keyToken);
|
|
||||||
return parts.join("+");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ProjectScriptsControl({
|
|
||||||
scripts,
|
|
||||||
keybindings,
|
|
||||||
preferredScriptId = null,
|
|
||||||
onRunScript,
|
|
||||||
onAddScript,
|
|
||||||
onUpdateScript,
|
|
||||||
}: ProjectScriptsControlProps) {
|
|
||||||
const addScriptFormId = React.useId();
|
|
||||||
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
|
|
||||||
const [dialogOpen, setDialogOpen] = useState(false);
|
|
||||||
const [name, setName] = useState("");
|
|
||||||
const [command, setCommand] = useState("");
|
|
||||||
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
|
|
||||||
const [iconPickerOpen, setIconPickerOpen] = useState(false);
|
|
||||||
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
|
|
||||||
const [keybinding, setKeybinding] = useState("");
|
|
||||||
const [validationError, setValidationError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
const primaryScript = useMemo(() => {
|
|
||||||
if (preferredScriptId) {
|
|
||||||
const preferred = scripts.find((script) => script.id === preferredScriptId);
|
|
||||||
if (preferred) return preferred;
|
|
||||||
}
|
|
||||||
return primaryProjectScript(scripts);
|
|
||||||
}, [preferredScriptId, scripts]);
|
|
||||||
const isEditing = editingScriptId !== null;
|
|
||||||
const dropdownItemClassName =
|
|
||||||
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
|
|
||||||
|
|
||||||
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
|
|
||||||
if (event.key === "Tab") return;
|
|
||||||
event.preventDefault();
|
|
||||||
if (event.key === "Backspace" || event.key === "Delete") {
|
|
||||||
setKeybinding("");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const next = keybindingFromEvent(event);
|
|
||||||
if (!next) return;
|
|
||||||
setKeybinding(next);
|
|
||||||
};
|
|
||||||
|
|
||||||
const submitAddScript = async (event: FormEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
const trimmedName = name.trim();
|
|
||||||
const trimmedCommand = command.trim();
|
|
||||||
if (trimmedName.length === 0) {
|
|
||||||
setValidationError("Name is required.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (trimmedCommand.length === 0) {
|
|
||||||
setValidationError("Command is required.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setValidationError(null);
|
|
||||||
try {
|
|
||||||
const payload = {
|
|
||||||
name: trimmedName,
|
|
||||||
command: trimmedCommand,
|
|
||||||
icon,
|
|
||||||
runOnWorktreeCreate,
|
|
||||||
keybinding: keybinding.trim() || null,
|
|
||||||
} satisfies NewProjectScriptInput;
|
|
||||||
if (editingScriptId) {
|
|
||||||
await onUpdateScript(editingScriptId, payload);
|
|
||||||
} else {
|
|
||||||
await onAddScript(payload);
|
|
||||||
}
|
|
||||||
setDialogOpen(false);
|
|
||||||
setIconPickerOpen(false);
|
|
||||||
} catch (error) {
|
|
||||||
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const openAddDialog = () => {
|
|
||||||
setEditingScriptId(null);
|
|
||||||
setName("");
|
|
||||||
setCommand("");
|
|
||||||
setIcon("play");
|
|
||||||
setIconPickerOpen(false);
|
|
||||||
setRunOnWorktreeCreate(false);
|
|
||||||
setKeybinding("");
|
|
||||||
setValidationError(null);
|
|
||||||
setDialogOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
const openEditDialog = (script: ProjectScript) => {
|
|
||||||
setEditingScriptId(script.id);
|
|
||||||
setName(script.name);
|
|
||||||
setCommand(script.command);
|
|
||||||
setIcon(script.icon);
|
|
||||||
setIconPickerOpen(false);
|
|
||||||
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
|
|
||||||
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
|
|
||||||
setValidationError(null);
|
|
||||||
setDialogOpen(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
{primaryScript ? (
|
|
||||||
<Group aria-label="Project scripts">
|
|
||||||
<Button
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => onRunScript(primaryScript)}
|
|
||||||
title={`Run ${primaryScript.name}`}
|
|
||||||
>
|
|
||||||
<ScriptIcon icon={primaryScript.icon} />
|
|
||||||
<span className="ml-0.5">{primaryScript.name}</span>
|
|
||||||
</Button>
|
|
||||||
<GroupSeparator />
|
|
||||||
<Menu highlightItemOnHover={false}>
|
|
||||||
<MenuTrigger
|
|
||||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
|
||||||
>
|
|
||||||
<ChevronDownIcon className="size-4" />
|
|
||||||
</MenuTrigger>
|
|
||||||
<MenuPopup align="end">
|
|
||||||
{scripts.map((script) => {
|
|
||||||
const shortcutLabel = shortcutLabelForCommand(
|
|
||||||
keybindings,
|
|
||||||
commandForProjectScript(script.id),
|
|
||||||
);
|
|
||||||
return (
|
|
||||||
<MenuItem
|
|
||||||
key={script.id}
|
|
||||||
className={`group ${dropdownItemClassName}`}
|
|
||||||
onClick={() => onRunScript(script)}
|
|
||||||
>
|
|
||||||
<ScriptIcon icon={script.icon} className="size-4" />
|
|
||||||
<span className="truncate">
|
|
||||||
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
|
|
||||||
</span>
|
|
||||||
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
|
|
||||||
{shortcutLabel && (
|
|
||||||
<MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
|
|
||||||
{shortcutLabel}
|
|
||||||
</MenuShortcut>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
size="icon-xs"
|
|
||||||
className="absolute right-0 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"
|
|
||||||
aria-label={`Edit ${script.name}`}
|
|
||||||
onPointerDown={(event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
}}
|
|
||||||
onClick={(event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
openEditDialog(script);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<SettingsIcon className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
</span>
|
|
||||||
</MenuItem>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
|
|
||||||
<PlusIcon className="size-4" />
|
|
||||||
Add action
|
|
||||||
</MenuItem>
|
|
||||||
</MenuPopup>
|
|
||||||
</Menu>
|
|
||||||
</Group>
|
|
||||||
) : (
|
|
||||||
<Button size="xs" variant="outline" onClick={openAddDialog}>
|
|
||||||
<PlusIcon className="size-3.5" />
|
|
||||||
Add action
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Dialog
|
|
||||||
onOpenChange={(open) => {
|
|
||||||
setDialogOpen(open);
|
|
||||||
if (!open) {
|
|
||||||
setIconPickerOpen(false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onOpenChangeComplete={(open) => {
|
|
||||||
if (open) return;
|
|
||||||
setEditingScriptId(null);
|
|
||||||
setName("");
|
|
||||||
setCommand("");
|
|
||||||
setIcon("play");
|
|
||||||
setRunOnWorktreeCreate(false);
|
|
||||||
setKeybinding("");
|
|
||||||
setValidationError(null);
|
|
||||||
}}
|
|
||||||
open={dialogOpen}
|
|
||||||
>
|
|
||||||
<DialogPopup>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Actions are project-scoped commands you can run from the top bar or keybindings.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
<DialogPanel>
|
|
||||||
<form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label htmlFor="script-name">Name</Label>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
|
|
||||||
<PopoverTrigger
|
|
||||||
render={
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
|
|
||||||
aria-label="Choose icon"
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<ScriptIcon icon={icon} className="size-4.5" />
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverPopup align="start">
|
|
||||||
<div className="grid grid-cols-3 gap-2">
|
|
||||||
{SCRIPT_ICONS.map((entry) => {
|
|
||||||
const isSelected = entry.id === icon;
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={entry.id}
|
|
||||||
type="button"
|
|
||||||
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
|
|
||||||
isSelected
|
|
||||||
? "border-primary/70 bg-primary/10"
|
|
||||||
: "border-border/70 hover:bg-accent/60"
|
|
||||||
}`}
|
|
||||||
onClick={() => {
|
|
||||||
setIcon(entry.id);
|
|
||||||
setIconPickerOpen(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<ScriptIcon icon={entry.id} className="size-4" />
|
|
||||||
<span>{entry.label}</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
</PopoverPopup>
|
|
||||||
</Popover>
|
|
||||||
<Input
|
|
||||||
id="script-name"
|
|
||||||
placeholder="Test"
|
|
||||||
value={name}
|
|
||||||
onChange={(event) => setName(event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label htmlFor="script-keybinding">Keybinding</Label>
|
|
||||||
<Input
|
|
||||||
id="script-keybinding"
|
|
||||||
placeholder="Press shortcut"
|
|
||||||
value={keybinding}
|
|
||||||
readOnly
|
|
||||||
onKeyDown={captureKeybinding}
|
|
||||||
/>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Press a shortcut. Use <code>Backspace</code> to clear.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Label htmlFor="script-command">Command</Label>
|
|
||||||
<Textarea
|
|
||||||
id="script-command"
|
|
||||||
placeholder="bun test"
|
|
||||||
value={command}
|
|
||||||
onChange={(event) => setCommand(event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
|
|
||||||
<span>Run automatically on worktree creation</span>
|
|
||||||
<Switch
|
|
||||||
checked={runOnWorktreeCreate}
|
|
||||||
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
|
|
||||||
</form>
|
|
||||||
</DialogPanel>
|
|
||||||
<DialogFooter>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
onClick={() => {
|
|
||||||
setDialogOpen(false);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button form={addScriptFormId} type="submit">
|
|
||||||
{isEditing ? "Save changes" : "Save action"}
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogPopup>
|
|
||||||
</Dialog>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,11 @@
|
|||||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { isElectron } from "../env";
|
import { isElectron } from "../env";
|
||||||
import { useTheme } from "../hooks/useTheme";
|
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 {
|
import {
|
||||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
DEFAULT_THREAD_TERMINAL_ID,
|
||||||
@@ -16,13 +14,9 @@ import {
|
|||||||
} from "../types";
|
} from "../types";
|
||||||
import { useNativeApi } from "../hooks/useNativeApi";
|
import { useNativeApi } from "../hooks/useNativeApi";
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
|
||||||
import { toastManager } from "./ui/toast";
|
|
||||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||||
|
|
||||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
|
||||||
|
|
||||||
function formatRelativeTime(iso: string): string {
|
function formatRelativeTime(iso: string): string {
|
||||||
const diff = Date.now() - new Date(iso).getTime();
|
const diff = Date.now() - new Date(iso).getTime();
|
||||||
const minutes = Math.floor(diff / 60_000);
|
const minutes = Math.floor(diff / 60_000);
|
||||||
@@ -118,14 +112,8 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
|||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
const { data: keybindings = EMPTY_KEYBINDINGS } = useQuery({
|
|
||||||
...serverConfigQueryOptions(api),
|
|
||||||
select: (config) => config.keybindings,
|
|
||||||
});
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const removeWorktreeMutation = useMutation(
|
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ api, queryClient }));
|
||||||
gitRemoveWorktreeMutationOptions({ api, queryClient }),
|
|
||||||
);
|
|
||||||
const { theme, setTheme } = useTheme();
|
const { theme, setTheme } = useTheme();
|
||||||
const [addingProject, setAddingProject] = useState(false);
|
const [addingProject, setAddingProject] = useState(false);
|
||||||
const [newCwd, setNewCwd] = useState("");
|
const [newCwd, setNewCwd] = useState("");
|
||||||
@@ -140,13 +128,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: {
|
||||||
@@ -170,11 +152,10 @@ export default function Sidebar() {
|
|||||||
session: null,
|
session: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
events: [],
|
events: [],
|
||||||
turnDiffSummaries: [],
|
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
branch: options?.branch ?? null,
|
branch: null,
|
||||||
worktreePath: options?.worktreePath ?? null,
|
worktreePath: null,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
@@ -215,7 +196,6 @@ export default function Sidebar() {
|
|||||||
cwd: result.project.cwd,
|
cwd: result.project.cwd,
|
||||||
model: DEFAULT_MODEL,
|
model: DEFAULT_MODEL,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: result.project.scripts,
|
|
||||||
};
|
};
|
||||||
const existingById = state.projects.find((p) => p.id === project.id);
|
const existingById = state.projects.find((p) => p.id === project.id);
|
||||||
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
|
||||||
@@ -243,7 +223,6 @@ export default function Sidebar() {
|
|||||||
cwd,
|
cwd,
|
||||||
model: DEFAULT_MODEL,
|
model: DEFAULT_MODEL,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
};
|
};
|
||||||
dispatch({ type: "ADD_PROJECT", project });
|
dispatch({ type: "ADD_PROJECT", project });
|
||||||
handleNewThread(project.id);
|
handleNewThread(project.id);
|
||||||
@@ -343,77 +322,29 @@ export default function Sidebar() {
|
|||||||
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
|
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleProjectContextMenu = useCallback(
|
|
||||||
async (projectId: string, position: { x: number; y: number }) => {
|
|
||||||
if (!api) return;
|
|
||||||
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
|
|
||||||
if (clicked !== "delete") return;
|
|
||||||
|
|
||||||
const project = state.projects.find((entry) => entry.id === projectId);
|
|
||||||
if (!project) return;
|
|
||||||
|
|
||||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
|
||||||
if (projectThreads.length > 0) {
|
|
||||||
toastManager.add({
|
|
||||||
type: "warning",
|
|
||||||
title: "Project is not empty",
|
|
||||||
description: "Delete all threads in this project before deleting it.",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const confirmed = await api.dialogs.confirm(
|
|
||||||
[`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
|
|
||||||
);
|
|
||||||
if (!confirmed) return;
|
|
||||||
|
|
||||||
if (isElectron) {
|
|
||||||
try {
|
|
||||||
await api.projects.remove({ id: projectId });
|
|
||||||
} catch (error) {
|
|
||||||
const message =
|
|
||||||
error instanceof Error ? error.message : "Unknown error deleting project.";
|
|
||||||
console.error("Failed to remove project", { projectId, error });
|
|
||||||
toastManager.add({
|
|
||||||
type: "error",
|
|
||||||
title: `Failed to delete "${project.name}"`,
|
|
||||||
description: message,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatch({ type: "DELETE_PROJECT", projectId });
|
|
||||||
},
|
|
||||||
[api, dispatch, state.projects, state.threads],
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||||
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
|
const isNewThreadShortcut =
|
||||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
event.metaKey &&
|
||||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
event.shiftKey &&
|
||||||
if (!projectId) return;
|
!event.ctrlKey &&
|
||||||
event.preventDefault();
|
!event.altKey &&
|
||||||
handleNewThread(projectId);
|
event.key.toLowerCase() === "o";
|
||||||
return;
|
if (!isNewThreadShortcut) 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);
|
||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("keydown", onWindowKeyDown);
|
window.removeEventListener("keydown", onWindowKeyDown);
|
||||||
};
|
};
|
||||||
}, [handleNewThread, keybindings, state.activeThreadId, state.projects, state.threads]);
|
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||||
@@ -477,13 +408,6 @@ export default function Sidebar() {
|
|||||||
type="button"
|
type="button"
|
||||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
|
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-accent"
|
||||||
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
|
onClick={() => dispatch({ type: "TOGGLE_PROJECT", projectId: project.id })}
|
||||||
onContextMenu={(e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
void handleProjectContextMenu(project.id, {
|
|
||||||
x: e.clientX,
|
|
||||||
y: e.clientY,
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<span className="text-[10px] text-muted-foreground/70">
|
<span className="text-[10px] text-muted-foreground/70">
|
||||||
{project.expanded ? "▼" : "▶"}
|
{project.expanded ? "▼" : "▶"}
|
||||||
|
|||||||
@@ -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,11 +18,10 @@ import {
|
|||||||
preferredTerminalEditor,
|
preferredTerminalEditor,
|
||||||
resolvePathLinkTarget,
|
resolvePathLinkTarget,
|
||||||
} from "../terminal-links";
|
} from "../terminal-links";
|
||||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
import { isTerminalClearShortcut } from "../terminal-shortcuts";
|
||||||
import {
|
import {
|
||||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
DEFAULT_THREAD_TERMINAL_ID,
|
||||||
MAX_THREAD_TERMINAL_COUNT,
|
|
||||||
type ThreadTerminalGroup,
|
type ThreadTerminalGroup,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
|
|
||||||
@@ -111,7 +110,6 @@ interface TerminalViewportProps {
|
|||||||
threadId: string;
|
threadId: string;
|
||||||
terminalId: string;
|
terminalId: string;
|
||||||
cwd: string;
|
cwd: string;
|
||||||
runtimeEnv?: Record<string, string>;
|
|
||||||
focusRequestId: number;
|
focusRequestId: number;
|
||||||
autoFocus: boolean;
|
autoFocus: boolean;
|
||||||
resizeEpoch: number;
|
resizeEpoch: number;
|
||||||
@@ -123,7 +121,6 @@ function TerminalViewport({
|
|||||||
threadId,
|
threadId,
|
||||||
terminalId,
|
terminalId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
|
||||||
focusRequestId,
|
focusRequestId,
|
||||||
autoFocus,
|
autoFocus,
|
||||||
resizeEpoch,
|
resizeEpoch,
|
||||||
@@ -155,29 +152,24 @@ function TerminalViewport({
|
|||||||
terminalRef.current = terminal;
|
terminalRef.current = terminal;
|
||||||
fitAddonRef.current = fitAddon;
|
fitAddonRef.current = fitAddon;
|
||||||
|
|
||||||
const sendTerminalInput = async (data: string, fallbackError: string) => {
|
const sendClearShortcut = async () => {
|
||||||
const activeTerminal = terminalRef.current;
|
const activeTerminal = terminalRef.current;
|
||||||
if (!activeTerminal) return;
|
if (!activeTerminal) return;
|
||||||
try {
|
try {
|
||||||
await api.terminal.write({ threadId, terminalId, data });
|
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
|
writeSystemMessage(
|
||||||
|
activeTerminal,
|
||||||
|
error instanceof Error ? error.message : "Failed to clear terminal",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
terminal.attachCustomKeyEventHandler((event) => {
|
terminal.attachCustomKeyEventHandler((event) => {
|
||||||
const navigationData = terminalNavigationShortcutData(event);
|
|
||||||
if (navigationData !== null) {
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
void sendTerminalInput(navigationData, "Failed to move cursor");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isTerminalClearShortcut(event)) return true;
|
if (!isTerminalClearShortcut(event)) return true;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
void sendTerminalInput("\u000c", "Failed to clear terminal");
|
void sendClearShortcut();
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -276,7 +268,6 @@ function TerminalViewport({
|
|||||||
cwd,
|
cwd,
|
||||||
cols: activeTerminal.cols,
|
cols: activeTerminal.cols,
|
||||||
rows: activeTerminal.rows,
|
rows: activeTerminal.rows,
|
||||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
|
||||||
});
|
});
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
activeTerminal.write("\u001bc");
|
activeTerminal.write("\u001bc");
|
||||||
@@ -372,7 +363,7 @@ function TerminalViewport({
|
|||||||
fitAddonRef.current = null;
|
fitAddonRef.current = null;
|
||||||
terminal.dispose();
|
terminal.dispose();
|
||||||
};
|
};
|
||||||
}, [api, cwd, runtimeEnv, terminalId, threadId]);
|
}, [api, cwd, terminalId, threadId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!autoFocus) return;
|
if (!autoFocus) return;
|
||||||
@@ -417,7 +408,6 @@ interface ThreadTerminalDrawerProps {
|
|||||||
api: NativeApi;
|
api: NativeApi;
|
||||||
threadId: string;
|
threadId: string;
|
||||||
cwd: string;
|
cwd: string;
|
||||||
runtimeEnv?: Record<string, string>;
|
|
||||||
height: number;
|
height: number;
|
||||||
terminalIds: string[];
|
terminalIds: string[];
|
||||||
activeTerminalId: string;
|
activeTerminalId: string;
|
||||||
@@ -426,9 +416,6 @@ interface ThreadTerminalDrawerProps {
|
|||||||
focusRequestId: number;
|
focusRequestId: number;
|
||||||
onSplitTerminal: () => void;
|
onSplitTerminal: () => void;
|
||||||
onNewTerminal: () => void;
|
onNewTerminal: () => void;
|
||||||
splitShortcutLabel?: 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;
|
||||||
@@ -444,9 +431,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>
|
||||||
@@ -467,7 +460,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
api,
|
api,
|
||||||
threadId,
|
threadId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
|
||||||
height,
|
height,
|
||||||
terminalIds,
|
terminalIds,
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
@@ -476,9 +468,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
focusRequestId,
|
focusRequestId,
|
||||||
onSplitTerminal,
|
onSplitTerminal,
|
||||||
onNewTerminal,
|
onNewTerminal,
|
||||||
splitShortcutLabel,
|
|
||||||
newShortcutLabel,
|
|
||||||
closeShortcutLabel,
|
|
||||||
onActiveTerminalChange,
|
onActiveTerminalChange,
|
||||||
onCloseTerminal,
|
onCloseTerminal,
|
||||||
onHeightChange,
|
onHeightChange,
|
||||||
@@ -587,7 +576,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
const showGroupHeaders =
|
const showGroupHeaders =
|
||||||
resolvedTerminalGroups.length > 1 ||
|
resolvedTerminalGroups.length > 1 ||
|
||||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
|
||||||
const terminalLabelById = useMemo(
|
const terminalLabelById = useMemo(
|
||||||
() =>
|
() =>
|
||||||
new Map(
|
new Map(
|
||||||
@@ -595,23 +583,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
),
|
),
|
||||||
[normalizedTerminalIds],
|
[normalizedTerminalIds],
|
||||||
);
|
);
|
||||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
|
||||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
|
||||||
: (splitShortcutLabel ? `Split Terminal (${splitShortcutLabel})` : "Split Terminal");
|
|
||||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
|
||||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
|
||||||
: (newShortcutLabel ? `New Terminal (${newShortcutLabel})` : "New Terminal");
|
|
||||||
const closeTerminalActionLabel = closeShortcutLabel
|
|
||||||
? `Close Terminal (${closeShortcutLabel})`
|
|
||||||
: "Close Terminal";
|
|
||||||
const onSplitTerminalAction = useCallback(() => {
|
|
||||||
if (hasReachedTerminalLimit) return;
|
|
||||||
onSplitTerminal();
|
|
||||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
|
||||||
const onNewTerminalAction = useCallback(() => {
|
|
||||||
if (hasReachedTerminalLimit) return;
|
|
||||||
onNewTerminal();
|
|
||||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
onHeightChangeRef.current = onHeightChange;
|
onHeightChangeRef.current = onHeightChange;
|
||||||
@@ -706,7 +677,7 @@ export default function ThreadTerminalDrawer({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<aside
|
<aside
|
||||||
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
|
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||||
style={{ height: `${drawerHeight}px` }}
|
style={{ height: `${drawerHeight}px` }}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
@@ -721,25 +692,17 @@ export default function ThreadTerminalDrawer({
|
|||||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||||
<TerminalActionButton
|
<TerminalActionButton
|
||||||
className={`p-1 text-foreground/90 transition-colors ${
|
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||||
hasReachedTerminalLimit
|
onClick={onSplitTerminal}
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
label="Split Terminal"
|
||||||
: "hover:bg-accent"
|
|
||||||
}`}
|
|
||||||
onClick={onSplitTerminalAction}
|
|
||||||
label={splitTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<SquareSplitHorizontal className="size-3.25" />
|
<SquareSplitHorizontal className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</TerminalActionButton>
|
||||||
<div className="h-4 w-px bg-border/80" />
|
<div className="h-4 w-px bg-border/80" />
|
||||||
<TerminalActionButton
|
<TerminalActionButton
|
||||||
className={`p-1 text-foreground/90 transition-colors ${
|
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||||
hasReachedTerminalLimit
|
onClick={onNewTerminal}
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
label="New Terminal"
|
||||||
: "hover:bg-accent"
|
|
||||||
}`}
|
|
||||||
onClick={onNewTerminalAction}
|
|
||||||
label={newTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<Plus className="size-3.25" />
|
<Plus className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</TerminalActionButton>
|
||||||
@@ -747,7 +710,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>
|
||||||
@@ -760,9 +723,9 @@ export default function ThreadTerminalDrawer({
|
|||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
{isSplitView ? (
|
{isSplitView ? (
|
||||||
<div
|
<div
|
||||||
className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
|
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||||
style={{
|
style={{
|
||||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
|
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{visibleTerminalIds.map((terminalId) => (
|
{visibleTerminalIds.map((terminalId) => (
|
||||||
@@ -783,7 +746,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
threadId={threadId}
|
threadId={threadId}
|
||||||
terminalId={terminalId}
|
terminalId={terminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
@@ -801,7 +763,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
threadId={threadId}
|
threadId={threadId}
|
||||||
terminalId={resolvedActiveTerminalId}
|
terminalId={resolvedActiveTerminalId}
|
||||||
cwd={cwd}
|
cwd={cwd}
|
||||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
|
||||||
focusRequestId={focusRequestId}
|
focusRequestId={focusRequestId}
|
||||||
autoFocus
|
autoFocus
|
||||||
resizeEpoch={resizeEpoch}
|
resizeEpoch={resizeEpoch}
|
||||||
@@ -816,31 +777,23 @@ export default function ThreadTerminalDrawer({
|
|||||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||||
<div className="inline-flex h-full items-stretch">
|
<div className="inline-flex h-full items-stretch">
|
||||||
<TerminalActionButton
|
<TerminalActionButton
|
||||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||||
hasReachedTerminalLimit
|
onClick={onSplitTerminal}
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
label="Split Terminal"
|
||||||
: "hover:bg-accent/70"
|
|
||||||
}`}
|
|
||||||
onClick={onSplitTerminalAction}
|
|
||||||
label={splitTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<SquareSplitHorizontal className="size-3.25" />
|
<SquareSplitHorizontal 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 ${
|
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||||
hasReachedTerminalLimit
|
onClick={onNewTerminal}
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
label="New Terminal"
|
||||||
: "hover:bg-accent/70"
|
|
||||||
}`}
|
|
||||||
onClick={onNewTerminalAction}
|
|
||||||
label={newTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<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>
|
||||||
@@ -878,9 +831,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}
|
||||||
@@ -904,30 +854,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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -60,18 +60,16 @@ function SheetPopup({
|
|||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
showCloseButton = true,
|
showCloseButton = true,
|
||||||
keepMounted = false,
|
|
||||||
side = "right",
|
side = "right",
|
||||||
variant = "default",
|
variant = "default",
|
||||||
...props
|
...props
|
||||||
}: SheetPrimitive.Popup.Props & {
|
}: SheetPrimitive.Popup.Props & {
|
||||||
showCloseButton?: boolean;
|
showCloseButton?: boolean;
|
||||||
keepMounted?: boolean;
|
|
||||||
side?: "right" | "left" | "top" | "bottom";
|
side?: "right" | "left" | "top" | "bottom";
|
||||||
variant?: "default" | "inset";
|
variant?: "default" | "inset";
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SheetPortal keepMounted={keepMounted}>
|
<SheetPortal>
|
||||||
<SheetBackdrop />
|
<SheetBackdrop />
|
||||||
<SheetViewport side={side} variant={variant}>
|
<SheetViewport side={side} variant={variant}>
|
||||||
<SheetPrimitive.Popup
|
<SheetPrimitive.Popup
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -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>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,97 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import type { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
|
||||||
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
|
|
||||||
import type { VariantProps } from "class-variance-authority";
|
|
||||||
import * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Separator } from "~/components/ui/separator";
|
|
||||||
import { Toggle as ToggleComponent, type toggleVariants } from "~/components/ui/toggle";
|
|
||||||
|
|
||||||
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
|
|
||||||
size: "default",
|
|
||||||
variant: "default",
|
|
||||||
});
|
|
||||||
|
|
||||||
function ToggleGroup({
|
|
||||||
className,
|
|
||||||
variant = "default",
|
|
||||||
size = "default",
|
|
||||||
orientation = "horizontal",
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
|
||||||
return (
|
|
||||||
<ToggleGroupPrimitive
|
|
||||||
className={cn(
|
|
||||||
"flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input",
|
|
||||||
orientation === "horizontal"
|
|
||||||
? "*:pointer-coarse:after:min-w-auto"
|
|
||||||
: "*:pointer-coarse:after:min-h-auto",
|
|
||||||
variant === "default"
|
|
||||||
? "gap-0.5"
|
|
||||||
: orientation === "horizontal"
|
|
||||||
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
|
|
||||||
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-size={size}
|
|
||||||
data-slot="toggle-group"
|
|
||||||
data-variant={variant}
|
|
||||||
orientation={orientation}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ToggleGroupContext.Provider value={{ size, variant }}>
|
|
||||||
{children}
|
|
||||||
</ToggleGroupContext.Provider>
|
|
||||||
</ToggleGroupPrimitive>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Toggle({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
variant,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
|
||||||
const context = React.useContext(ToggleGroupContext);
|
|
||||||
|
|
||||||
const resolvedVariant = variant ?? context.variant;
|
|
||||||
const resolvedSize = size ?? context.size;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ToggleComponent
|
|
||||||
className={className}
|
|
||||||
data-size={resolvedSize}
|
|
||||||
data-variant={resolvedVariant}
|
|
||||||
size={resolvedSize}
|
|
||||||
variant={resolvedVariant}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</ToggleComponent>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ToggleGroupSeparator({
|
|
||||||
className,
|
|
||||||
orientation = "vertical",
|
|
||||||
...props
|
|
||||||
}: {
|
|
||||||
className?: string;
|
|
||||||
} & React.ComponentProps<typeof Separator>) {
|
|
||||||
return (
|
|
||||||
<Separator
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none relative bg-input before:absolute before:inset-0 dark:before:bg-input/32",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
orientation={orientation}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { ToggleGroup, Toggle, Toggle as ToggleGroupItem, ToggleGroupSeparator };
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const toggleVariants = cva(
|
|
||||||
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer select-none items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base text-foreground outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-pressed:bg-input/64 data-pressed:text-accent-foreground sm:text-sm [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
size: "default",
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
size: {
|
|
||||||
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
|
|
||||||
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
|
|
||||||
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
|
|
||||||
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
|
|
||||||
},
|
|
||||||
variant: {
|
|
||||||
default: "border-transparent",
|
|
||||||
outline:
|
|
||||||
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function Toggle({
|
|
||||||
className,
|
|
||||||
variant,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
|
|
||||||
return (
|
|
||||||
<TogglePrimitive
|
|
||||||
className={cn(toggleVariants({ className, size, variant }))}
|
|
||||||
data-slot="toggle"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Toggle, toggleVariants };
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
|
||||||
|
|
||||||
describe("detectComposerTrigger", () => {
|
|
||||||
it("detects @path trigger at cursor", () => {
|
|
||||||
const text = "Please check @src/com";
|
|
||||||
const trigger = detectComposerTrigger(text, text.length);
|
|
||||||
|
|
||||||
expect(trigger).toEqual({
|
|
||||||
kind: "path",
|
|
||||||
query: "src/com",
|
|
||||||
rangeStart: "Please check ".length,
|
|
||||||
rangeEnd: text.length,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("detects slash command token while typing command name", () => {
|
|
||||||
const text = "/mo";
|
|
||||||
const trigger = detectComposerTrigger(text, text.length);
|
|
||||||
|
|
||||||
expect(trigger).toEqual({
|
|
||||||
kind: "slash-command",
|
|
||||||
query: "mo",
|
|
||||||
rangeStart: 0,
|
|
||||||
rangeEnd: text.length,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("detects slash model query after /model", () => {
|
|
||||||
const text = "/model spark";
|
|
||||||
const trigger = detectComposerTrigger(text, text.length);
|
|
||||||
|
|
||||||
expect(trigger).toEqual({
|
|
||||||
kind: "slash-model",
|
|
||||||
query: "spark",
|
|
||||||
rangeStart: 0,
|
|
||||||
rangeEnd: text.length,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("replaceTextRange", () => {
|
|
||||||
it("replaces a text range and returns new cursor", () => {
|
|
||||||
const replaced = replaceTextRange("hello @src", 6, 10, "");
|
|
||||||
expect(replaced).toEqual({
|
|
||||||
text: "hello ",
|
|
||||||
cursor: 6,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
|
||||||
|
|
||||||
export interface ComposerTrigger {
|
|
||||||
kind: ComposerTriggerKind;
|
|
||||||
query: string;
|
|
||||||
rangeStart: number;
|
|
||||||
rangeEnd: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
function clampCursor(text: string, cursor: number): number {
|
|
||||||
if (!Number.isFinite(cursor)) return text.length;
|
|
||||||
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
|
|
||||||
}
|
|
||||||
|
|
||||||
function isWhitespace(char: string): boolean {
|
|
||||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
|
||||||
}
|
|
||||||
|
|
||||||
function tokenStartForCursor(text: string, cursor: number): number {
|
|
||||||
let index = cursor - 1;
|
|
||||||
while (index >= 0 && !isWhitespace(text[index] ?? "")) {
|
|
||||||
index -= 1;
|
|
||||||
}
|
|
||||||
return index + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
|
||||||
const cursor = clampCursor(text, cursorInput);
|
|
||||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
|
||||||
const linePrefix = text.slice(lineStart, cursor);
|
|
||||||
|
|
||||||
if (linePrefix.startsWith("/")) {
|
|
||||||
const commandMatch = /^\/(\S*)$/.exec(linePrefix);
|
|
||||||
if (commandMatch) {
|
|
||||||
const commandQuery = commandMatch[1] ?? "";
|
|
||||||
if (commandQuery.toLowerCase() === "model") {
|
|
||||||
return {
|
|
||||||
kind: "slash-model",
|
|
||||||
query: "",
|
|
||||||
rangeStart: lineStart,
|
|
||||||
rangeEnd: cursor,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if ("model".startsWith(commandQuery.toLowerCase())) {
|
|
||||||
return {
|
|
||||||
kind: "slash-command",
|
|
||||||
query: commandQuery,
|
|
||||||
rangeStart: lineStart,
|
|
||||||
rangeEnd: cursor,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
|
|
||||||
if (modelMatch) {
|
|
||||||
return {
|
|
||||||
kind: "slash-model",
|
|
||||||
query: (modelMatch[1] ?? "").trim(),
|
|
||||||
rangeStart: lineStart,
|
|
||||||
rangeEnd: cursor,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const tokenStart = tokenStartForCursor(text, cursor);
|
|
||||||
const token = text.slice(tokenStart, cursor);
|
|
||||||
if (!token.startsWith("@")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
kind: "path",
|
|
||||||
query: token.slice(1),
|
|
||||||
rangeStart: tokenStart,
|
|
||||||
rangeEnd: cursor,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function replaceTextRange(
|
|
||||||
text: string,
|
|
||||||
rangeStart: number,
|
|
||||||
rangeEnd: number,
|
|
||||||
replacement: string,
|
|
||||||
): { text: string; cursor: number } {
|
|
||||||
const safeStart = Math.max(0, Math.min(text.length, rangeStart));
|
|
||||||
const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
|
|
||||||
const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
|
|
||||||
return { text: nextText, cursor: safeStart + replacement.length };
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
function getMediaQueryMatch(query: string): boolean {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return window.matchMedia(query).matches;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useMediaQuery(query: string): boolean {
|
|
||||||
const [matches, setMatches] = useState(() => getMediaQueryMatch(query));
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const mediaQueryList = window.matchMedia(query);
|
|
||||||
const handleChange = () => {
|
|
||||||
setMatches(mediaQueryList.matches);
|
|
||||||
};
|
|
||||||
|
|
||||||
setMatches(mediaQueryList.matches);
|
|
||||||
mediaQueryList.addEventListener("change", handleChange);
|
|
||||||
return () => {
|
|
||||||
mediaQueryList.removeEventListener("change", handleChange);
|
|
||||||
};
|
|
||||||
}, [query]);
|
|
||||||
|
|
||||||
return matches;
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import type { ProviderEvent } from "@t3tools/contracts";
|
|
||||||
import { useMemo } from "react";
|
|
||||||
import { deriveTurnDiffSummaries, inferCheckpointTurnCountByTurnId } from "../session-logic";
|
|
||||||
import type { Thread, TurnDiffSummary } from "../types";
|
|
||||||
|
|
||||||
const derivedTurnDiffSummaryCache = new WeakMap<readonly ProviderEvent[], TurnDiffSummary[]>();
|
|
||||||
|
|
||||||
function deriveTurnDiffSummariesCached(events: ProviderEvent[]): TurnDiffSummary[] {
|
|
||||||
const cached = derivedTurnDiffSummaryCache.get(events);
|
|
||||||
if (cached) {
|
|
||||||
return cached;
|
|
||||||
}
|
|
||||||
const derived = deriveTurnDiffSummaries(events);
|
|
||||||
derivedTurnDiffSummaryCache.set(events, derived);
|
|
||||||
return derived;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useTurnDiffSummaries(activeThread: Thread | undefined) {
|
|
||||||
const turnDiffSummaries = useMemo(() => {
|
|
||||||
if (!activeThread) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
if (activeThread.turnDiffSummaries.length > 0) {
|
|
||||||
return activeThread.turnDiffSummaries;
|
|
||||||
}
|
|
||||||
return deriveTurnDiffSummariesCached(activeThread.events);
|
|
||||||
}, [activeThread]);
|
|
||||||
|
|
||||||
const inferredCheckpointTurnCountByTurnId = useMemo(
|
|
||||||
() => inferCheckpointTurnCountByTurnId(turnDiffSummaries),
|
|
||||||
[turnDiffSummaries],
|
|
||||||
);
|
|
||||||
|
|
||||||
return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId };
|
|
||||||
}
|
|
||||||
@@ -1,467 +0,0 @@
|
|||||||
import { assert, describe, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
type KeybindingCommand,
|
|
||||||
type KeybindingShortcut,
|
|
||||||
type KeybindingWhenNode,
|
|
||||||
type ResolvedKeybindingsConfig,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import {
|
|
||||||
formatShortcutLabel,
|
|
||||||
isChatNewShortcut,
|
|
||||||
isChatNewLocalShortcut,
|
|
||||||
isOpenFavoriteEditorShortcut,
|
|
||||||
isTerminalClearShortcut,
|
|
||||||
isTerminalCloseShortcut,
|
|
||||||
isTerminalNewShortcut,
|
|
||||||
isTerminalSplitShortcut,
|
|
||||||
isTerminalToggleShortcut,
|
|
||||||
resolveShortcutCommand,
|
|
||||||
shortcutLabelForCommand,
|
|
||||||
terminalNavigationShortcutData,
|
|
||||||
type ShortcutEventLike,
|
|
||||||
} from "./keybindings";
|
|
||||||
|
|
||||||
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
|
|
||||||
return {
|
|
||||||
key: "j",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function modShortcut(
|
|
||||||
key: string,
|
|
||||||
overrides: Partial<Omit<KeybindingShortcut, "key">> = {},
|
|
||||||
): KeybindingShortcut {
|
|
||||||
return {
|
|
||||||
key,
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function whenIdentifier(name: string): KeybindingWhenNode {
|
|
||||||
return { type: "identifier", name };
|
|
||||||
}
|
|
||||||
|
|
||||||
function whenNot(node: KeybindingWhenNode): KeybindingWhenNode {
|
|
||||||
return { type: "not", node };
|
|
||||||
}
|
|
||||||
|
|
||||||
function whenAnd(left: KeybindingWhenNode, right: KeybindingWhenNode): KeybindingWhenNode {
|
|
||||||
return { type: "and", left, right };
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TestBinding {
|
|
||||||
shortcut: KeybindingShortcut;
|
|
||||||
command: KeybindingCommand;
|
|
||||||
whenAst?: KeybindingWhenNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
|
|
||||||
return bindings.map((binding) => ({
|
|
||||||
command: binding.command,
|
|
||||||
shortcut: binding.shortcut,
|
|
||||||
...(binding.whenAst ? { whenAst: binding.whenAst } : {}),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
const DEFAULT_BINDINGS = compile([
|
|
||||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("d"),
|
|
||||||
command: "terminal.split",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("d", { shiftKey: true }),
|
|
||||||
command: "terminal.new",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("w"),
|
|
||||||
command: "terminal.close",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
|
|
||||||
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
|
|
||||||
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
|
|
||||||
]);
|
|
||||||
|
|
||||||
describe("isTerminalToggleShortcut", () => {
|
|
||||||
it("matches Cmd+J on macOS", () => {
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalToggleShortcut(event({ metaKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("matches Ctrl+J on non-macOS", () => {
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalToggleShortcut(event({ ctrlKey: true }), DEFAULT_BINDINGS, { platform: "Win32" }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("split/new/close terminal shortcuts", () => {
|
|
||||||
it("requires terminalFocus for default split/new/close bindings", () => {
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "Linux",
|
|
||||||
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", () => {
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalSplitShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalNewShortcut(event({ key: "d", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "Linux",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalCloseShortcut(event({ key: "w", ctrlKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "Linux",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("supports when expressions", () => {
|
|
||||||
const keybindings = compile([
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("\\"),
|
|
||||||
command: "terminal.split",
|
|
||||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("n", { shiftKey: true }),
|
|
||||||
command: "terminal.new",
|
|
||||||
whenAst: whenAnd(whenIdentifier("terminalOpen"), whenNot(whenIdentifier("terminalFocus"))),
|
|
||||||
},
|
|
||||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
|
||||||
]);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Win32",
|
|
||||||
context: { terminalOpen: true, terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalSplitShortcut(event({ key: "\\", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Win32",
|
|
||||||
context: { terminalOpen: false, terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true, shiftKey: true }), keybindings, {
|
|
||||||
platform: "Win32",
|
|
||||||
context: { terminalOpen: true, terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("supports when boolean literals", () => {
|
|
||||||
const keybindings = compile([
|
|
||||||
{ shortcut: modShortcut("n"), command: "terminal.new", whenAst: whenIdentifier("true") },
|
|
||||||
{ shortcut: modShortcut("m"), command: "terminal.new", whenAst: whenIdentifier("false") },
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalNewShortcut(event({ key: "m", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("shortcutLabelForCommand", () => {
|
|
||||||
it("returns the most recent binding label", () => {
|
|
||||||
const bindings = compile([
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("\\"),
|
|
||||||
command: "terminal.split",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("\\", { shiftKey: true }),
|
|
||||||
command: "terminal.split",
|
|
||||||
whenAst: whenNot(whenIdentifier("terminalFocus")),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
assert.strictEqual(
|
|
||||||
shortcutLabelForCommand(bindings, "terminal.split", "Linux"),
|
|
||||||
"Ctrl+Shift+\\",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns labels for non-terminal commands", () => {
|
|
||||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
|
||||||
assert.strictEqual(
|
|
||||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"),
|
|
||||||
"Ctrl+O",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("chat/editor shortcuts", () => {
|
|
||||||
it("matches chat.new shortcut", () => {
|
|
||||||
assert.isTrue(
|
|
||||||
isChatNewShortcut(event({ key: "o", metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isChatNewShortcut(event({ key: "o", ctrlKey: true, shiftKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
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", () => {
|
|
||||||
assert.isTrue(
|
|
||||||
isOpenFavoriteEditorShortcut(event({ key: "o", metaKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isOpenFavoriteEditorShortcut(event({ key: "o", ctrlKey: true }), DEFAULT_BINDINGS, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("cross-command precedence", () => {
|
|
||||||
it("uses when + order so a later focused rule overrides a global rule", () => {
|
|
||||||
const keybindings = compile([
|
|
||||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("n"),
|
|
||||||
command: "terminal.new",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isFalse(
|
|
||||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isChatNewShortcut(event({ key: "n", metaKey: true }), keybindings, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
context: { terminalFocus: false },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("still lets a later global rule win when both rules match", () => {
|
|
||||||
const keybindings = compile([
|
|
||||||
{
|
|
||||||
shortcut: modShortcut("n"),
|
|
||||||
command: "terminal.new",
|
|
||||||
whenAst: whenIdentifier("terminalFocus"),
|
|
||||||
},
|
|
||||||
{ shortcut: modShortcut("n"), command: "chat.new" },
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isChatNewShortcut(event({ key: "n", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
context: { terminalFocus: true },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("resolveShortcutCommand", () => {
|
|
||||||
it("returns dynamic script commands", () => {
|
|
||||||
const keybindings = compile([
|
|
||||||
{ shortcut: modShortcut("r"), command: "script.setup.run" },
|
|
||||||
]);
|
|
||||||
|
|
||||||
assert.strictEqual(
|
|
||||||
resolveShortcutCommand(event({ key: "r", ctrlKey: true }), keybindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
"script.setup.run",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("formatShortcutLabel", () => {
|
|
||||||
it("formats labels for macOS", () => {
|
|
||||||
assert.strictEqual(
|
|
||||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "MacIntel"),
|
|
||||||
"⇧⌘D",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats labels for non-macOS", () => {
|
|
||||||
assert.strictEqual(
|
|
||||||
formatShortcutLabel(modShortcut("d", { shiftKey: true }), "Linux"),
|
|
||||||
"Ctrl+Shift+D",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("formats labels for plus key", () => {
|
|
||||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "MacIntel"), "⌘+");
|
|
||||||
assert.strictEqual(formatShortcutLabel(modShortcut("+"), "Linux"), "Ctrl++");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("isTerminalClearShortcut", () => {
|
|
||||||
it("matches Ctrl+L on all platforms", () => {
|
|
||||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"));
|
|
||||||
assert.isTrue(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("matches Cmd+K on macOS", () => {
|
|
||||||
assert.isTrue(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores non-keydown events", () => {
|
|
||||||
assert.isFalse(
|
|
||||||
isTerminalClearShortcut(event({ type: "keyup", key: "l", ctrlKey: true }), "Linux"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("terminalNavigationShortcutData", () => {
|
|
||||||
it("maps Option+Arrow on macOS to word movement", () => {
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", altKey: true }), "MacIntel"),
|
|
||||||
"\u001bb",
|
|
||||||
);
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowRight", altKey: true }), "MacIntel"),
|
|
||||||
"\u001bf",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps Cmd+Arrow on macOS to line movement", () => {
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "MacIntel"),
|
|
||||||
"\u0001",
|
|
||||||
);
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowRight", metaKey: true }), "MacIntel"),
|
|
||||||
"\u0005",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("maps Ctrl+Arrow on non-macOS to word movement", () => {
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", ctrlKey: true }), "Win32"),
|
|
||||||
"\u001bb",
|
|
||||||
);
|
|
||||||
assert.strictEqual(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowRight", ctrlKey: true }), "Linux"),
|
|
||||||
"\u001bf",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects unsupported combinations", () => {
|
|
||||||
assert.isNull(
|
|
||||||
terminalNavigationShortcutData(
|
|
||||||
event({ key: "ArrowLeft", shiftKey: true, altKey: true }),
|
|
||||||
"MacIntel",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
assert.isNull(
|
|
||||||
terminalNavigationShortcutData(event({ key: "ArrowLeft", metaKey: true }), "Linux"),
|
|
||||||
);
|
|
||||||
assert.isNull(terminalNavigationShortcutData(event({ key: "a", altKey: true }), "MacIntel"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores non-keydown events", () => {
|
|
||||||
assert.isNull(
|
|
||||||
terminalNavigationShortcutData(
|
|
||||||
event({ type: "keyup", key: "ArrowLeft", altKey: true }),
|
|
||||||
"MacIntel",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("plus key parsing", () => {
|
|
||||||
it("matches the plus key shortcut", () => {
|
|
||||||
const plusBindings = compile([{ shortcut: modShortcut("+"), command: "terminal.toggle" }]);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalToggleShortcut(event({ key: "+", metaKey: true }), plusBindings, {
|
|
||||||
platform: "MacIntel",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
assert.isTrue(
|
|
||||||
isTerminalToggleShortcut(event({ key: "+", ctrlKey: true }), plusBindings, {
|
|
||||||
platform: "Linux",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
import {
|
|
||||||
type KeybindingCommand,
|
|
||||||
type KeybindingShortcut,
|
|
||||||
type KeybindingWhenNode,
|
|
||||||
type ResolvedKeybindingsConfig,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { isMacPlatform } from "./lib/utils";
|
|
||||||
|
|
||||||
export interface ShortcutEventLike {
|
|
||||||
type?: string;
|
|
||||||
key: string;
|
|
||||||
metaKey: boolean;
|
|
||||||
ctrlKey: boolean;
|
|
||||||
shiftKey: boolean;
|
|
||||||
altKey: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ShortcutMatchContext {
|
|
||||||
terminalFocus: boolean;
|
|
||||||
terminalOpen: boolean;
|
|
||||||
[key: string]: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ShortcutMatchOptions {
|
|
||||||
platform?: string;
|
|
||||||
context?: Partial<ShortcutMatchContext>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const TERMINAL_WORD_BACKWARD = "\u001bb";
|
|
||||||
const TERMINAL_WORD_FORWARD = "\u001bf";
|
|
||||||
const TERMINAL_LINE_START = "\u0001";
|
|
||||||
const TERMINAL_LINE_END = "\u0005";
|
|
||||||
|
|
||||||
function normalizeEventKey(key: string): string {
|
|
||||||
const normalized = key.toLowerCase();
|
|
||||||
if (normalized === "esc") return "escape";
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
shortcut: KeybindingShortcut,
|
|
||||||
platform = navigator.platform,
|
|
||||||
): boolean {
|
|
||||||
const key = normalizeEventKey(event.key);
|
|
||||||
if (key !== shortcut.key) return false;
|
|
||||||
|
|
||||||
const useMetaForMod = isMacPlatform(platform);
|
|
||||||
const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
|
||||||
const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
|
||||||
return (
|
|
||||||
event.metaKey === expectedMeta &&
|
|
||||||
event.ctrlKey === expectedCtrl &&
|
|
||||||
event.shiftKey === shortcut.shiftKey &&
|
|
||||||
event.altKey === shortcut.altKey
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePlatform(options: ShortcutMatchOptions | undefined): string {
|
|
||||||
return options?.platform ?? navigator.platform;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatchContext {
|
|
||||||
return {
|
|
||||||
terminalFocus: false,
|
|
||||||
terminalOpen: false,
|
|
||||||
...options?.context,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function evaluateWhenNode(node: KeybindingWhenNode, context: ShortcutMatchContext): boolean {
|
|
||||||
switch (node.type) {
|
|
||||||
case "identifier":
|
|
||||||
if (node.name === "true") return true;
|
|
||||||
if (node.name === "false") return false;
|
|
||||||
return Boolean(context[node.name]);
|
|
||||||
case "not":
|
|
||||||
return !evaluateWhenNode(node.node, context);
|
|
||||||
case "and":
|
|
||||||
return evaluateWhenNode(node.left, context) && evaluateWhenNode(node.right, context);
|
|
||||||
case "or":
|
|
||||||
return evaluateWhenNode(node.left, context) || evaluateWhenNode(node.right, context);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesWhenClause(
|
|
||||||
whenAst: KeybindingWhenNode | undefined,
|
|
||||||
context: ShortcutMatchContext,
|
|
||||||
): boolean {
|
|
||||||
if (!whenAst) return true;
|
|
||||||
return evaluateWhenNode(whenAst, context);
|
|
||||||
}
|
|
||||||
|
|
||||||
function matchesCommandShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
command: KeybindingCommand,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
return resolveShortcutCommand(event, keybindings, options) === command;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveShortcutCommand(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): string | null {
|
|
||||||
const platform = resolvePlatform(options);
|
|
||||||
const context = resolveContext(options);
|
|
||||||
|
|
||||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
|
||||||
const binding = keybindings[index];
|
|
||||||
if (!binding) continue;
|
|
||||||
if (!matchesWhenClause(binding.whenAst, context)) continue;
|
|
||||||
if (!matchesShortcut(event, binding.shortcut, platform)) continue;
|
|
||||||
return binding.command;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatShortcutKeyLabel(key: string): string {
|
|
||||||
if (key === " ") return "Space";
|
|
||||||
if (key.length === 1) return key.toUpperCase();
|
|
||||||
if (key === "escape") return "Esc";
|
|
||||||
if (key === "arrowup") return "Up";
|
|
||||||
if (key === "arrowdown") return "Down";
|
|
||||||
if (key === "arrowleft") return "Left";
|
|
||||||
if (key === "arrowright") return "Right";
|
|
||||||
return key.slice(0, 1).toUpperCase() + key.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatShortcutLabel(
|
|
||||||
shortcut: KeybindingShortcut,
|
|
||||||
platform = navigator.platform,
|
|
||||||
): string {
|
|
||||||
const keyLabel = formatShortcutKeyLabel(shortcut.key);
|
|
||||||
const useMetaForMod = isMacPlatform(platform);
|
|
||||||
const showMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod);
|
|
||||||
const showCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod);
|
|
||||||
const showAlt = shortcut.altKey;
|
|
||||||
const showShift = shortcut.shiftKey;
|
|
||||||
|
|
||||||
if (useMetaForMod) {
|
|
||||||
return `${showCtrl ? "\u2303" : ""}${showAlt ? "\u2325" : ""}${showShift ? "\u21e7" : ""}${showMeta ? "\u2318" : ""}${keyLabel}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts: string[] = [];
|
|
||||||
if (showCtrl) parts.push("Ctrl");
|
|
||||||
if (showAlt) parts.push("Alt");
|
|
||||||
if (showShift) parts.push("Shift");
|
|
||||||
if (showMeta) parts.push("Meta");
|
|
||||||
parts.push(keyLabel);
|
|
||||||
return parts.join("+");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function shortcutLabelForCommand(
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
command: KeybindingCommand,
|
|
||||||
platform = navigator.platform,
|
|
||||||
): string | null {
|
|
||||||
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
|
|
||||||
const binding = keybindings[index];
|
|
||||||
if (!binding || binding.command !== command) continue;
|
|
||||||
return formatShortcutLabel(binding.shortcut, platform);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isTerminalToggleShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
return matchesCommandShortcut(event, keybindings, "terminal.toggle", options);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isTerminalSplitShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
return matchesCommandShortcut(event, keybindings, "terminal.split", options);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isTerminalNewShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
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(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
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(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
keybindings: ResolvedKeybindingsConfig,
|
|
||||||
options?: ShortcutMatchOptions,
|
|
||||||
): boolean {
|
|
||||||
return matchesCommandShortcut(event, keybindings, "editor.openFavorite", options);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isTerminalClearShortcut(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
platform = navigator.platform,
|
|
||||||
): boolean {
|
|
||||||
if (event.type !== undefined && event.type !== "keydown") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const key = event.key.toLowerCase();
|
|
||||||
|
|
||||||
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
isMacPlatform(platform) &&
|
|
||||||
key === "k" &&
|
|
||||||
event.metaKey &&
|
|
||||||
!event.ctrlKey &&
|
|
||||||
!event.altKey &&
|
|
||||||
!event.shiftKey
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function terminalNavigationShortcutData(
|
|
||||||
event: ShortcutEventLike,
|
|
||||||
platform = navigator.platform,
|
|
||||||
): string | null {
|
|
||||||
if (event.type !== undefined && event.type !== "keydown") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.shiftKey) return null;
|
|
||||||
|
|
||||||
const key = normalizeEventKey(event.key);
|
|
||||||
if (key !== "arrowleft" && key !== "arrowright") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const moveWord = key === "arrowleft" ? TERMINAL_WORD_BACKWARD : TERMINAL_WORD_FORWARD;
|
|
||||||
const moveLine = key === "arrowleft" ? TERMINAL_LINE_START : TERMINAL_LINE_END;
|
|
||||||
|
|
||||||
if (isMacPlatform(platform)) {
|
|
||||||
if (event.altKey && !event.metaKey && !event.ctrlKey) {
|
|
||||||
return moveWord;
|
|
||||||
}
|
|
||||||
if (event.metaKey && !event.altKey && !event.ctrlKey) {
|
|
||||||
return moveLine;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.ctrlKey && !event.metaKey && !event.altKey) {
|
|
||||||
return moveWord;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.altKey && !event.metaKey && !event.ctrlKey) {
|
|
||||||
return moveWord;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
import { buildPatchCacheKey } from "./diffRendering";
|
|
||||||
|
|
||||||
describe("buildPatchCacheKey", () => {
|
|
||||||
it("returns a stable cache key for identical content", () => {
|
|
||||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
|
||||||
|
|
||||||
expect(buildPatchCacheKey(patch)).toBe(buildPatchCacheKey(patch));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("normalizes outer whitespace before hashing", () => {
|
|
||||||
const patch = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
|
||||||
|
|
||||||
expect(buildPatchCacheKey(`\n${patch}\n`)).toBe(buildPatchCacheKey(patch));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("changes when diff content changes", () => {
|
|
||||||
const before = "diff --git a/a.ts b/a.ts\n+console.log('hello')";
|
|
||||||
const after = "diff --git a/a.ts b/a.ts\n+console.log('hello world')";
|
|
||||||
|
|
||||||
expect(buildPatchCacheKey(before)).not.toBe(buildPatchCacheKey(after));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
|
||||||
const FNV_PRIME_32 = 0x01000193;
|
|
||||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
|
||||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
|
||||||
|
|
||||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
|
||||||
let hash = seed >>> 0;
|
|
||||||
for (let index = 0; index < input.length; index += 1) {
|
|
||||||
hash ^= input.charCodeAt(index);
|
|
||||||
hash = Math.imul(hash, multiplier) >>> 0;
|
|
||||||
}
|
|
||||||
return hash >>> 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
|
|
||||||
const normalizedPatch = patch.trim();
|
|
||||||
const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
|
|
||||||
const secondary = fnv1a32(
|
|
||||||
normalizedPatch,
|
|
||||||
SECONDARY_HASH_SEED,
|
|
||||||
SECONDARY_HASH_MULTIPLIER,
|
|
||||||
).toString(36);
|
|
||||||
return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,6 @@
|
|||||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
||||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
const GIT_STATUS_STALE_TIME_MS = 5_000;
|
|
||||||
const GIT_STATUS_REFETCH_INTERVAL_MS = 15_000;
|
|
||||||
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
|
|
||||||
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
|
|
||||||
|
|
||||||
export const gitQueryKeys = {
|
export const gitQueryKeys = {
|
||||||
all: ["git"] as const,
|
all: ["git"] as const,
|
||||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
||||||
@@ -26,10 +21,6 @@ export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string |
|
|||||||
return api.git.status({ cwd });
|
return api.git.status({ cwd });
|
||||||
},
|
},
|
||||||
enabled: !!api && !!cwd,
|
enabled: !!api && !!cwd,
|
||||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: "always",
|
|
||||||
refetchOnReconnect: "always",
|
|
||||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,10 +34,6 @@ export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string
|
|||||||
return api.git.listBranches({ cwd });
|
return api.git.listBranches({ cwd });
|
||||||
},
|
},
|
||||||
enabled: !!api && !!cwd,
|
enabled: !!api && !!cwd,
|
||||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: true,
|
|
||||||
refetchOnReconnect: true,
|
|
||||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,42 +0,0 @@
|
|||||||
import type { NativeApi, ProjectSearchEntriesResult } from "@t3tools/contracts";
|
|
||||||
import { queryOptions } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export const projectQueryKeys = {
|
|
||||||
all: ["projects"] as const,
|
|
||||||
searchEntries: (cwd: string | null, query: string, limit: number) =>
|
|
||||||
["projects", "search-entries", cwd, query, limit] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_SEARCH_ENTRIES_LIMIT = 80;
|
|
||||||
const DEFAULT_SEARCH_ENTRIES_STALE_TIME = 15_000;
|
|
||||||
const EMPTY_SEARCH_ENTRIES_RESULT: ProjectSearchEntriesResult = {
|
|
||||||
entries: [],
|
|
||||||
truncated: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function projectSearchEntriesQueryOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
query: string;
|
|
||||||
enabled?: boolean;
|
|
||||||
limit?: number;
|
|
||||||
staleTime?: number;
|
|
||||||
}) {
|
|
||||||
const limit = input.limit ?? DEFAULT_SEARCH_ENTRIES_LIMIT;
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: projectQueryKeys.searchEntries(input.cwd, input.query, limit),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!input.api || !input.cwd) {
|
|
||||||
throw new Error("Workspace entry search is unavailable.");
|
|
||||||
}
|
|
||||||
return input.api.projects.searchEntries({
|
|
||||||
cwd: input.cwd,
|
|
||||||
query: input.query,
|
|
||||||
limit,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
enabled: (input.enabled ?? true) && Boolean(input.api && input.cwd),
|
|
||||||
staleTime: input.staleTime ?? DEFAULT_SEARCH_ENTRIES_STALE_TIME,
|
|
||||||
placeholderData: (previous) => previous ?? EMPTY_SEARCH_ENTRIES_RESULT,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import type { NativeApi } from "@t3tools/contracts";
|
|
||||||
import { QueryClient } from "@tanstack/react-query";
|
|
||||||
import { describe, expect, it, vi } from "vitest";
|
|
||||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "./providerReactQuery";
|
|
||||||
|
|
||||||
describe("providerQueryKeys.checkpointDiff", () => {
|
|
||||||
it("includes cacheScope so reused turn counts do not collide", () => {
|
|
||||||
const baseInput = {
|
|
||||||
sessionId: "session-id",
|
|
||||||
threadRuntimeId: "thread-id",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
expect(
|
|
||||||
providerQueryKeys.checkpointDiff({
|
|
||||||
...baseInput,
|
|
||||||
cacheScope: "turn:old-turn",
|
|
||||||
}),
|
|
||||||
).not.toEqual(
|
|
||||||
providerQueryKeys.checkpointDiff({
|
|
||||||
...baseInput,
|
|
||||||
cacheScope: "turn:new-turn",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("checkpointDiffQueryOptions", () => {
|
|
||||||
it("forwards checkpoint range to the provider API", async () => {
|
|
||||||
const getCheckpointDiff = vi.fn().mockResolvedValue({ diff: "patch" });
|
|
||||||
const api = {
|
|
||||||
providers: {
|
|
||||||
getCheckpointDiff,
|
|
||||||
},
|
|
||||||
} as unknown as NativeApi;
|
|
||||||
|
|
||||||
const options = checkpointDiffQueryOptions(api, {
|
|
||||||
sessionId: "session-id",
|
|
||||||
threadRuntimeId: "thread-id",
|
|
||||||
fromTurnCount: 3,
|
|
||||||
toTurnCount: 4,
|
|
||||||
cacheScope: "turn:abc",
|
|
||||||
});
|
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
|
||||||
await queryClient.fetchQuery(options);
|
|
||||||
|
|
||||||
expect(getCheckpointDiff).toHaveBeenCalledWith({
|
|
||||||
sessionId: "session-id",
|
|
||||||
fromTurnCount: 3,
|
|
||||||
toTurnCount: 4,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
import type { NativeApi } from "@t3tools/contracts";
|
|
||||||
import { queryOptions } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export interface CheckpointDiffQueryInput {
|
|
||||||
sessionId: string | null;
|
|
||||||
threadRuntimeId: string | null;
|
|
||||||
fromTurnCount: number | null;
|
|
||||||
toTurnCount: number | null;
|
|
||||||
cacheScope?: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const providerQueryKeys = {
|
|
||||||
all: ["providers"] as const,
|
|
||||||
checkpointDiff: (input: CheckpointDiffQueryInput) =>
|
|
||||||
[
|
|
||||||
"providers",
|
|
||||||
"checkpointDiff",
|
|
||||||
input.sessionId,
|
|
||||||
input.threadRuntimeId,
|
|
||||||
input.fromTurnCount,
|
|
||||||
input.toTurnCount,
|
|
||||||
input.cacheScope ?? null,
|
|
||||||
] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function checkpointDiffQueryOptions(
|
|
||||||
api: NativeApi | undefined,
|
|
||||||
input: CheckpointDiffQueryInput,
|
|
||||||
) {
|
|
||||||
const hasValidRange =
|
|
||||||
typeof input.fromTurnCount === "number" &&
|
|
||||||
typeof input.toTurnCount === "number" &&
|
|
||||||
Number.isInteger(input.fromTurnCount) &&
|
|
||||||
Number.isInteger(input.toTurnCount) &&
|
|
||||||
input.fromTurnCount >= 0 &&
|
|
||||||
input.toTurnCount >= 0 &&
|
|
||||||
input.fromTurnCount <= input.toTurnCount;
|
|
||||||
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: providerQueryKeys.checkpointDiff(input),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!api || !input.sessionId || !hasValidRange) {
|
|
||||||
throw new Error("Checkpoint diff is unavailable.");
|
|
||||||
}
|
|
||||||
const { fromTurnCount, toTurnCount } = input;
|
|
||||||
if (typeof fromTurnCount !== "number" || typeof toTurnCount !== "number") {
|
|
||||||
throw new Error("Checkpoint diff range is invalid.");
|
|
||||||
}
|
|
||||||
return api.providers.getCheckpointDiff({
|
|
||||||
sessionId: input.sessionId,
|
|
||||||
fromTurnCount,
|
|
||||||
toTurnCount,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
enabled: !!api && !!input.sessionId && hasValidRange,
|
|
||||||
staleTime: Infinity,
|
|
||||||
retry: 8,
|
|
||||||
retryDelay: (attempt) => Math.min(2_000, 150 * 2 ** (attempt - 1)),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import type { NativeApi } from "@t3tools/contracts";
|
|
||||||
import { queryOptions } from "@tanstack/react-query";
|
|
||||||
|
|
||||||
export const serverQueryKeys = {
|
|
||||||
all: ["server"] as const,
|
|
||||||
config: () => ["server", "config"] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function serverConfigQueryOptions(api: NativeApi | undefined) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: serverQueryKeys.config(),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!api || !api.server || typeof api.server.getConfig !== "function") {
|
|
||||||
throw new Error("Server config is unavailable.");
|
|
||||||
}
|
|
||||||
return api.server.getConfig();
|
|
||||||
},
|
|
||||||
enabled: !!api && !!api.server && typeof api.server.getConfig === "function",
|
|
||||||
staleTime: Infinity,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { assert, describe, it } from "vitest";
|
|
||||||
|
|
||||||
import { isWindowsPlatform } from "./utils";
|
|
||||||
|
|
||||||
describe("isWindowsPlatform", () => {
|
|
||||||
it("matches Windows platform identifiers", () => {
|
|
||||||
assert.isTrue(isWindowsPlatform("Win32"));
|
|
||||||
assert.isTrue(isWindowsPlatform("Windows"));
|
|
||||||
assert.isTrue(isWindowsPlatform("windows_nt"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not match darwin", () => {
|
|
||||||
assert.isFalse(isWindowsPlatform("darwin"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -4,11 +4,3 @@ import { twMerge } from "tailwind-merge";
|
|||||||
export function cn(...inputs: CxOptions) {
|
export function cn(...inputs: CxOptions) {
|
||||||
return twMerge(cx(inputs));
|
return twMerge(cx(inputs));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isMacPlatform(platform: string): boolean {
|
|
||||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function isWindowsPlatform(platform: string): boolean {
|
|
||||||
return /^win(dows)?/i.test(platform);
|
|
||||||
}
|
|
||||||
@@ -20,7 +20,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.2-codex",
|
model: "gpt-5.2-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -70,7 +69,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: false,
|
expanded: false,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -121,7 +119,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: false,
|
expanded: false,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [],
|
threads: [],
|
||||||
@@ -143,7 +140,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -191,7 +187,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -236,7 +231,6 @@ describe("hydratePersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -263,107 +257,6 @@ describe("hydratePersistedState", () => {
|
|||||||
]);
|
]);
|
||||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("hydrates persisted turn diff summaries and clears persisted loaded flags", () => {
|
|
||||||
const payload = JSON.stringify({
|
|
||||||
version: 7,
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: "p-1",
|
|
||||||
name: "Project",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [
|
|
||||||
{
|
|
||||||
id: "t-1",
|
|
||||||
codexThreadId: "thr_1",
|
|
||||||
projectId: "p-1",
|
|
||||||
title: "Thread",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
messages: [],
|
|
||||||
createdAt: "2026-02-08T10:00:00.000Z",
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-08T10:05:00.000Z",
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
checkpointDiffLoaded: true,
|
|
||||||
files: [
|
|
||||||
{
|
|
||||||
path: "src/app.ts",
|
|
||||||
kind: "modified",
|
|
||||||
additions: 3,
|
|
||||||
deletions: 1,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activeThreadId: "t-1",
|
|
||||||
});
|
|
||||||
|
|
||||||
const hydrated = hydratePersistedState(payload, false);
|
|
||||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-08T10:05:00.000Z",
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
files: [
|
|
||||||
{
|
|
||||||
path: "src/app.ts",
|
|
||||||
kind: "modified",
|
|
||||||
additions: 3,
|
|
||||||
deletions: 1,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("drops malformed persisted turn diff summaries instead of rejecting the whole snapshot", () => {
|
|
||||||
const payload = JSON.stringify({
|
|
||||||
version: 7,
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: "p-1",
|
|
||||||
name: "Project",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [
|
|
||||||
{
|
|
||||||
id: "t-1",
|
|
||||||
codexThreadId: "thr_1",
|
|
||||||
projectId: "p-1",
|
|
||||||
title: "Thread",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
messages: [],
|
|
||||||
createdAt: "2026-02-08T10:00:00.000Z",
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-08T10:05:00.000Z",
|
|
||||||
files: [{ path: 123 }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activeThreadId: "t-1",
|
|
||||||
});
|
|
||||||
|
|
||||||
const hydrated = hydratePersistedState(payload, false);
|
|
||||||
expect(hydrated).not.toBeNull();
|
|
||||||
expect(hydrated?.threads[0]?.id).toBe("t-1");
|
|
||||||
expect(hydrated?.threads[0]?.turnDiffSummaries).toEqual([]);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("toPersistedState", () => {
|
describe("toPersistedState", () => {
|
||||||
@@ -410,24 +303,6 @@ describe("toPersistedState", () => {
|
|||||||
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-08T10:05:00.000Z",
|
|
||||||
status: "completed",
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
files: [
|
|
||||||
{
|
|
||||||
path: "src/app.ts",
|
|
||||||
kind: "modified",
|
|
||||||
additions: 3,
|
|
||||||
deletions: 1,
|
|
||||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
unifiedDiff: "diff --git a/src/app.ts b/src/app.ts",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const persisted = toPersistedState({
|
const persisted = toPersistedState({
|
||||||
@@ -438,7 +313,6 @@ describe("toPersistedState", () => {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [thread],
|
threads: [thread],
|
||||||
@@ -485,22 +359,6 @@ describe("toPersistedState", () => {
|
|||||||
lastVisitedAt: thread.lastVisitedAt,
|
lastVisitedAt: thread.lastVisitedAt,
|
||||||
branch: null,
|
branch: null,
|
||||||
worktreePath: null,
|
worktreePath: null,
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-08T10:05:00.000Z",
|
|
||||||
status: "completed",
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
files: [
|
|
||||||
{
|
|
||||||
path: "src/app.ts",
|
|
||||||
kind: "modified",
|
|
||||||
additions: 3,
|
|
||||||
deletions: 1,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
});
|
||||||
const persistedThread = persisted.threads[0];
|
const persistedThread = persisted.threads[0];
|
||||||
expect(persistedThread).toBeDefined();
|
expect(persistedThread).toBeDefined();
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { projectScriptSchema } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||||
import {
|
import {
|
||||||
@@ -20,7 +19,6 @@ const persistedProjectSchema = z.object({
|
|||||||
cwd: z.string().min(1),
|
cwd: z.string().min(1),
|
||||||
model: z.string().min(1),
|
model: z.string().min(1),
|
||||||
expanded: z.boolean(),
|
expanded: z.boolean(),
|
||||||
scripts: z.array(projectScriptSchema).default([]),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const persistedMessageSchema = z.object({
|
const persistedMessageSchema = z.object({
|
||||||
@@ -47,23 +45,6 @@ const persistedTerminalGroupSchema = z.object({
|
|||||||
terminalIds: z.array(z.string().trim().min(1)),
|
terminalIds: z.array(z.string().trim().min(1)),
|
||||||
});
|
});
|
||||||
|
|
||||||
const persistedTurnDiffFileChangeSchema = z.object({
|
|
||||||
path: z.string().min(1),
|
|
||||||
kind: z.string().min(1).optional(),
|
|
||||||
additions: z.number().int().min(0).optional(),
|
|
||||||
deletions: z.number().int().min(0).optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const persistedTurnDiffSummarySchema = z.object({
|
|
||||||
turnId: z.string().min(1),
|
|
||||||
completedAt: z.string().min(1),
|
|
||||||
status: z.string().min(1).optional(),
|
|
||||||
files: z.array(persistedTurnDiffFileChangeSchema),
|
|
||||||
assistantMessageId: z.string().min(1).optional(),
|
|
||||||
checkpointTurnCount: z.number().int().min(0).optional(),
|
|
||||||
checkpointDiffLoaded: z.boolean().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
const persistedThreadSchema = z.object({
|
const persistedThreadSchema = z.object({
|
||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
codexThreadId: z.string().min(1).nullable().default(null),
|
codexThreadId: z.string().min(1).nullable().default(null),
|
||||||
@@ -84,7 +65,6 @@ const persistedThreadSchema = z.object({
|
|||||||
lastVisitedAt: z.string().min(1).optional(),
|
lastVisitedAt: z.string().min(1).optional(),
|
||||||
branch: z.string().min(1).nullable().optional(),
|
branch: z.string().min(1).nullable().optional(),
|
||||||
worktreePath: z.string().min(1).nullable().optional(),
|
worktreePath: z.string().min(1).nullable().optional(),
|
||||||
turnDiffSummaries: z.array(persistedTurnDiffSummarySchema).catch([]).default([]),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const persistedStateBodySchema = z.object({
|
const persistedStateBodySchema = z.object({
|
||||||
@@ -160,7 +140,6 @@ function hydrateProject(
|
|||||||
return {
|
return {
|
||||||
...project,
|
...project,
|
||||||
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
|
||||||
scripts: project.scripts,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,21 +270,6 @@ function hydrateThread(
|
|||||||
lastVisitedAt: thread.lastVisitedAt,
|
lastVisitedAt: thread.lastVisitedAt,
|
||||||
branch: thread.branch ?? null,
|
branch: thread.branch ?? null,
|
||||||
worktreePath: thread.worktreePath ?? null,
|
worktreePath: thread.worktreePath ?? null,
|
||||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
|
||||||
turnId: summary.turnId,
|
|
||||||
completedAt: summary.completedAt,
|
|
||||||
...(summary.status ? { status: summary.status } : {}),
|
|
||||||
files: summary.files.map((file) => ({
|
|
||||||
path: file.path,
|
|
||||||
...(file.kind ? { kind: file.kind } : {}),
|
|
||||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
|
||||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
|
||||||
})),
|
|
||||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
|
||||||
...(typeof summary.checkpointTurnCount === "number"
|
|
||||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
|
||||||
: {}),
|
|
||||||
})),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -386,21 +350,6 @@ export function toPersistedState(
|
|||||||
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
||||||
branch: thread.branch,
|
branch: thread.branch,
|
||||||
worktreePath: thread.worktreePath,
|
worktreePath: thread.worktreePath,
|
||||||
turnDiffSummaries: thread.turnDiffSummaries.map((summary) => ({
|
|
||||||
turnId: summary.turnId,
|
|
||||||
completedAt: summary.completedAt,
|
|
||||||
...(summary.status ? { status: summary.status } : {}),
|
|
||||||
files: summary.files.map((file) => ({
|
|
||||||
path: file.path,
|
|
||||||
...(file.kind ? { kind: file.kind } : {}),
|
|
||||||
...(typeof file.additions === "number" ? { additions: file.additions } : {}),
|
|
||||||
...(typeof file.deletions === "number" ? { deletions: file.deletions } : {}),
|
|
||||||
})),
|
|
||||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
|
||||||
...(typeof summary.checkpointTurnCount === "number"
|
|
||||||
? { checkpointTurnCount: summary.checkpointTurnCount }
|
|
||||||
: {}),
|
|
||||||
})),
|
|
||||||
})),
|
})),
|
||||||
activeThreadId: state.activeThreadId,
|
activeThreadId: state.activeThreadId,
|
||||||
runtimeMode: state.runtimeMode,
|
runtimeMode: state.runtimeMode,
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
commandForProjectScript,
|
|
||||||
nextProjectScriptId,
|
|
||||||
primaryProjectScript,
|
|
||||||
projectScriptRuntimeEnv,
|
|
||||||
projectScriptIdFromCommand,
|
|
||||||
setupProjectScript,
|
|
||||||
} from "./projectScripts";
|
|
||||||
|
|
||||||
describe("projectScripts helpers", () => {
|
|
||||||
it("builds and parses script run commands", () => {
|
|
||||||
const command = commandForProjectScript("lint");
|
|
||||||
expect(command).toBe("script.lint.run");
|
|
||||||
expect(projectScriptIdFromCommand(command)).toBe("lint");
|
|
||||||
expect(projectScriptIdFromCommand("terminal.toggle")).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("slugifies and dedupes project script ids", () => {
|
|
||||||
expect(nextProjectScriptId("Run Tests", [])).toBe("run-tests");
|
|
||||||
expect(nextProjectScriptId("Run Tests", ["run-tests"])).toBe("run-tests-2");
|
|
||||||
expect(nextProjectScriptId("!!!", [])).toBe("script");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves primary and setup scripts", () => {
|
|
||||||
const scripts = [
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "bun install",
|
|
||||||
icon: "configure" as const,
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
name: "Test",
|
|
||||||
command: "bun test",
|
|
||||||
icon: "test" as const,
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
expect(primaryProjectScript(scripts)?.id).toBe("test");
|
|
||||||
expect(setupProjectScript(scripts)?.id).toBe("setup");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("builds default runtime env for scripts", () => {
|
|
||||||
const env = projectScriptRuntimeEnv({
|
|
||||||
project: { cwd: "/repo" },
|
|
||||||
worktreePath: "/repo/worktree-a",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(env).toMatchObject({
|
|
||||||
T3CODE_PROJECT_ROOT: "/repo",
|
|
||||||
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("allows overriding runtime env values", () => {
|
|
||||||
const env = projectScriptRuntimeEnv({
|
|
||||||
project: { cwd: "/repo" },
|
|
||||||
extraEnv: {
|
|
||||||
T3CODE_PROJECT_ROOT: "/custom-root",
|
|
||||||
CUSTOM_FLAG: "1",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(env.T3CODE_PROJECT_ROOT).toBe("/custom-root");
|
|
||||||
expect(env.CUSTOM_FLAG).toBe("1");
|
|
||||||
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
import type { ProjectScript } from "@t3tools/contracts";
|
|
||||||
|
|
||||||
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
|
|
||||||
const MAX_SCRIPT_ID_LENGTH = 64;
|
|
||||||
|
|
||||||
function normalizeScriptId(value: string): string {
|
|
||||||
const cleaned = value
|
|
||||||
.trim()
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/[^a-z0-9]+/g, "-")
|
|
||||||
.replace(/^-+|-+$/g, "");
|
|
||||||
if (cleaned.length === 0) {
|
|
||||||
return "script";
|
|
||||||
}
|
|
||||||
if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
|
|
||||||
return cleaned;
|
|
||||||
}
|
|
||||||
return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function commandForProjectScript(scriptId: string): string {
|
|
||||||
return `script.${scriptId}.run`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function projectScriptIdFromCommand(command: string): string | null {
|
|
||||||
const match = SCRIPT_RUN_COMMAND_PATTERN.exec(command.trim());
|
|
||||||
return match?.[1] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
|
|
||||||
const taken = new Set(Array.from(existingIds));
|
|
||||||
const baseId = normalizeScriptId(name);
|
|
||||||
if (!taken.has(baseId)) return baseId;
|
|
||||||
|
|
||||||
let suffix = 2;
|
|
||||||
while (suffix < 10_000) {
|
|
||||||
const candidate = `${baseId}-${suffix}`;
|
|
||||||
const safeCandidate =
|
|
||||||
candidate.length <= MAX_SCRIPT_ID_LENGTH
|
|
||||||
? candidate
|
|
||||||
: `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
|
|
||||||
if (!taken.has(safeCandidate)) {
|
|
||||||
return safeCandidate;
|
|
||||||
}
|
|
||||||
suffix += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// This last-resort fallback only triggers after exhausting thousands of suffixes.
|
|
||||||
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ProjectScriptRuntimeEnvInput {
|
|
||||||
project: {
|
|
||||||
cwd: string;
|
|
||||||
};
|
|
||||||
worktreePath?: string | null;
|
|
||||||
extraEnv?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
|
|
||||||
const env: Record<string, string> = {
|
|
||||||
T3CODE_PROJECT_ROOT: input.project.cwd,
|
|
||||||
};
|
|
||||||
if (input.worktreePath) {
|
|
||||||
env.T3CODE_WORKTREE_PATH = input.worktreePath;
|
|
||||||
}
|
|
||||||
if (input.extraEnv) {
|
|
||||||
return { ...env, ...input.extraEnv };
|
|
||||||
}
|
|
||||||
return env;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
|
||||||
const regular = scripts.find((script) => !script.runOnWorktreeCreate);
|
|
||||||
return regular ?? scripts[0] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
|
|
||||||
return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
|
|
||||||
}
|
|
||||||
@@ -5,8 +5,6 @@ import {
|
|||||||
type WorkLogEntry,
|
type WorkLogEntry,
|
||||||
applyEventToMessages,
|
applyEventToMessages,
|
||||||
derivePendingApprovals,
|
derivePendingApprovals,
|
||||||
deriveTurnDiffFilesFromUnifiedDiff,
|
|
||||||
deriveTurnDiffSummaries,
|
|
||||||
deriveTimelineEntries,
|
deriveTimelineEntries,
|
||||||
deriveWorkLogEntries,
|
deriveWorkLogEntries,
|
||||||
evolveSession,
|
evolveSession,
|
||||||
@@ -395,239 +393,6 @@ describe("deriveWorkLogEntries", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("deriveTurnDiffSummaries", () => {
|
|
||||||
it("tracks completed turns and links them to assistant message completion", () => {
|
|
||||||
const summaries = deriveTurnDiffSummaries([
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-start",
|
|
||||||
method: "turn/started",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:00.000Z",
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-file-change",
|
|
||||||
method: "item/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:01.000Z",
|
|
||||||
payload: {
|
|
||||||
item: {
|
|
||||||
id: "item-file-change",
|
|
||||||
type: "fileChange",
|
|
||||||
status: "completed",
|
|
||||||
changes: [
|
|
||||||
{
|
|
||||||
path: "src/a.ts",
|
|
||||||
kind: "modified",
|
|
||||||
diff: "diff --git a/src/a.ts b/src/a.ts\n@@ -1 +1 @@\n-old\n+new\n",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-diff-updated",
|
|
||||||
method: "turn/diff/updated",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:02.000Z",
|
|
||||||
payload: {
|
|
||||||
threadId: "thr-1",
|
|
||||||
turnId: "turn-1",
|
|
||||||
diff: [
|
|
||||||
"diff --git a/src/a.ts b/src/a.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old",
|
|
||||||
"+new",
|
|
||||||
"diff --git a/src/b.ts b/src/b.ts",
|
|
||||||
"@@ -0,0 +1 @@",
|
|
||||||
"+created",
|
|
||||||
].join("\n"),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-agent-msg",
|
|
||||||
method: "item/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:03.000Z",
|
|
||||||
payload: {
|
|
||||||
item: {
|
|
||||||
id: "msg-1",
|
|
||||||
type: "agentMessage",
|
|
||||||
text: "Done",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-completed",
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:04.000Z",
|
|
||||||
payload: {
|
|
||||||
turn: {
|
|
||||||
id: "turn-1",
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-2-file-change",
|
|
||||||
method: "item/completed",
|
|
||||||
turnId: "turn-2",
|
|
||||||
createdAt: "2026-02-08T10:00:05.000Z",
|
|
||||||
payload: {
|
|
||||||
item: {
|
|
||||||
id: "item-file-change-2",
|
|
||||||
type: "fileChange",
|
|
||||||
status: "completed",
|
|
||||||
changes: [
|
|
||||||
{
|
|
||||||
path: "src/unfinished.ts",
|
|
||||||
kind: "modified",
|
|
||||||
diff: "diff --git a/src/unfinished.ts b/src/unfinished.ts",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(summaries).toHaveLength(1);
|
|
||||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
|
||||||
expect(summaries[0]?.assistantMessageId).toBe("msg-1");
|
|
||||||
expect(summaries[0]?.unifiedDiff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
|
||||||
expect(summaries[0]?.files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
|
||||||
expect(summaries[0]?.files[0]?.kind).toBe("modified");
|
|
||||||
expect(summaries[0]?.files[0]?.additions).toBe(1);
|
|
||||||
expect(summaries[0]?.files[0]?.deletions).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes completed turns even when no fileChange tool events were emitted", () => {
|
|
||||||
const summaries = deriveTurnDiffSummaries([
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-start",
|
|
||||||
method: "turn/started",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:00.000Z",
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-completed",
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:01.000Z",
|
|
||||||
payload: {
|
|
||||||
turn: {
|
|
||||||
id: "turn-1",
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(summaries).toHaveLength(1);
|
|
||||||
expect(summaries[0]?.turnId).toBe("turn-1");
|
|
||||||
expect(summaries[0]?.files).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps newest diff data when older events provide stale values", () => {
|
|
||||||
const summaries = deriveTurnDiffSummaries([
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-diff-old",
|
|
||||||
method: "turn/diff/updated",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:01.000Z",
|
|
||||||
payload: {
|
|
||||||
diff: [
|
|
||||||
"diff --git a/src/example.ts b/src/example.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old",
|
|
||||||
"+older",
|
|
||||||
].join("\n"),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-diff-new",
|
|
||||||
method: "turn/diff/updated",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:02.000Z",
|
|
||||||
payload: {
|
|
||||||
diff: [
|
|
||||||
"diff --git a/src/example.ts b/src/example.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old",
|
|
||||||
"+newest",
|
|
||||||
].join("\n"),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
makeEvent({
|
|
||||||
id: "evt-turn-completed",
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-08T10:00:03.000Z",
|
|
||||||
payload: {
|
|
||||||
turn: {
|
|
||||||
id: "turn-1",
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(summaries).toHaveLength(1);
|
|
||||||
expect(summaries[0]?.unifiedDiff).toContain("+newest");
|
|
||||||
expect(summaries[0]?.unifiedDiff).not.toContain("+older");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("deriveTurnDiffFilesFromUnifiedDiff", () => {
|
|
||||||
it("splits a multi-file patch into sorted per-file entries", () => {
|
|
||||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
|
||||||
[
|
|
||||||
"diff --git a/src/b.ts b/src/b.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old-b",
|
|
||||||
"+new-b",
|
|
||||||
"diff --git a/src/a.ts b/src/a.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old-a",
|
|
||||||
"+new-a",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(files.map((file) => file.path)).toEqual(["src/a.ts", "src/b.ts"]);
|
|
||||||
expect(files[0]?.diff).toContain("diff --git a/src/a.ts b/src/a.ts");
|
|
||||||
expect(files[1]?.diff).toContain("diff --git a/src/b.ts b/src/b.ts");
|
|
||||||
expect(files[0]?.additions).toBe(1);
|
|
||||||
expect(files[0]?.deletions).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses git headers when file paths include ` b/`", () => {
|
|
||||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
|
||||||
[
|
|
||||||
"diff --git a/subdir b/example.ts b/subdir b/example.ts",
|
|
||||||
"--- a/subdir b/example.ts",
|
|
||||||
"+++ b/subdir b/example.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old",
|
|
||||||
"+new",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(files).toHaveLength(1);
|
|
||||||
expect(files[0]?.path).toBe("subdir b/example.ts");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses git header fallback for binary diffs with ` b/` in path", () => {
|
|
||||||
const files = deriveTurnDiffFilesFromUnifiedDiff(
|
|
||||||
[
|
|
||||||
"diff --git a/subdir b/image.png b/subdir b/image.png",
|
|
||||||
"Binary files a/subdir b/image.png and b/subdir b/image.png differ",
|
|
||||||
].join("\n"),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(files).toHaveLength(1);
|
|
||||||
expect(files[0]?.path).toBe("subdir b/image.png");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("derivePendingApprovals", () => {
|
describe("derivePendingApprovals", () => {
|
||||||
it("returns pending command/file-change approvals", () => {
|
it("returns pending command/file-change approvals", () => {
|
||||||
const approvals = derivePendingApprovals([
|
const approvals = derivePendingApprovals([
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
|
import type { NativeApi, ProviderEvent, ProviderKind, ProviderSession } from "@t3tools/contracts";
|
||||||
import type { ChatMessage, SessionPhase, TurnDiffFileChange, TurnDiffSummary } from "./types";
|
import type { ChatMessage, SessionPhase } from "./types";
|
||||||
import { createWsNativeApi } from "./wsNativeApi";
|
import { createWsNativeApi } from "./wsNativeApi";
|
||||||
|
|
||||||
export const PROVIDER_OPTIONS: Array<{
|
export const PROVIDER_OPTIONS: Array<{
|
||||||
@@ -33,18 +33,10 @@ export function asObject(value: unknown): Record<string, unknown> | undefined {
|
|||||||
return value as Record<string, unknown>;
|
return value as Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function asArray(value: unknown): unknown[] | undefined {
|
|
||||||
return Array.isArray(value) ? value : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function asString(value: unknown): string | undefined {
|
export function asString(value: unknown): string | undefined {
|
||||||
return typeof value === "string" ? value : undefined;
|
return typeof value === "string" ? value : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function asNumber(value: unknown): number | undefined {
|
|
||||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatTimestamp(isoDate: string): string {
|
export function formatTimestamp(isoDate: string): string {
|
||||||
return new Intl.DateTimeFormat(undefined, {
|
return new Intl.DateTimeFormat(undefined, {
|
||||||
hour: "numeric",
|
hour: "numeric",
|
||||||
@@ -107,8 +99,6 @@ export type TimelineEntry =
|
|||||||
entry: WorkLogEntry;
|
entry: WorkLogEntry;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type { TurnDiffFileChange, TurnDiffSummary } from "./types";
|
|
||||||
|
|
||||||
function normalizeDetail(value: string | undefined): string | undefined {
|
function normalizeDetail(value: string | undefined): string | undefined {
|
||||||
if (!value) return undefined;
|
if (!value) return undefined;
|
||||||
const trimmed = value.trim();
|
const trimmed = value.trim();
|
||||||
@@ -448,278 +438,6 @@ export function deriveWorkLogEntries(
|
|||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MutableTurnDiffSummary {
|
|
||||||
turnId: string;
|
|
||||||
completedAt: string | undefined;
|
|
||||||
status: string | undefined;
|
|
||||||
assistantMessageId: string | undefined;
|
|
||||||
unifiedDiff: string | undefined;
|
|
||||||
filesByPath: Map<string, TurnDiffFileChange>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseFileChangeEntriesFromEvent(event: ProviderEvent): TurnDiffFileChange[] {
|
|
||||||
if (event.method !== "item/completed") {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const item = asObject(asObject(event.payload)?.item);
|
|
||||||
const itemType = normalizeItemType(asString(item?.type));
|
|
||||||
if (itemType !== "file change") {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const changes = asArray(item?.changes) ?? [];
|
|
||||||
const parsed: TurnDiffFileChange[] = [];
|
|
||||||
for (const rawChange of changes) {
|
|
||||||
const change = asObject(rawChange);
|
|
||||||
if (!change) continue;
|
|
||||||
|
|
||||||
const diff = normalizeDetail(asString(change.diff));
|
|
||||||
const path = normalizeDetail(asString(change.path)) ?? (diff ? parsePathFromDiff(diff) : undefined);
|
|
||||||
if (!path) continue;
|
|
||||||
|
|
||||||
const additions = asNumber(change.additions);
|
|
||||||
const deletions = asNumber(change.deletions);
|
|
||||||
const stat = additions !== undefined && deletions !== undefined ? null : diff ? countDiffStat(diff) : null;
|
|
||||||
const kind = normalizeDetail(asString(change.kind));
|
|
||||||
parsed.push({
|
|
||||||
path,
|
|
||||||
...(kind ? { kind } : {}),
|
|
||||||
...(diff ? { diff } : {}),
|
|
||||||
...(additions !== undefined ? { additions } : stat ? { additions: stat.additions } : {}),
|
|
||||||
...(deletions !== undefined ? { deletions } : stat ? { deletions: stat.deletions } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeTurnDiffFileChange(
|
|
||||||
byPath: Map<string, TurnDiffFileChange>,
|
|
||||||
incoming: TurnDiffFileChange,
|
|
||||||
): void {
|
|
||||||
const existing = byPath.get(incoming.path);
|
|
||||||
if (!existing) {
|
|
||||||
byPath.set(incoming.path, incoming);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existing.kind === undefined && incoming.kind !== undefined) {
|
|
||||||
existing.kind = incoming.kind;
|
|
||||||
}
|
|
||||||
if (existing.diff === undefined && incoming.diff !== undefined) {
|
|
||||||
existing.diff = incoming.diff;
|
|
||||||
}
|
|
||||||
if (existing.additions === undefined && incoming.additions !== undefined) {
|
|
||||||
existing.additions = incoming.additions;
|
|
||||||
}
|
|
||||||
if (existing.deletions === undefined && incoming.deletions !== undefined) {
|
|
||||||
existing.deletions = incoming.deletions;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePathFromDiff(diff: string): string | undefined {
|
|
||||||
const normalized = diff.replace(/\r\n/g, "\n");
|
|
||||||
const bPath = normalized.match(/^\+\+\+ b\/(.+)$/m);
|
|
||||||
if (bPath && bPath[1]) return bPath[1];
|
|
||||||
const gitHeader = normalized.match(/^diff --git a\/(.+) b\/\1$/m);
|
|
||||||
if (gitHeader && gitHeader[1]) return gitHeader[1];
|
|
||||||
const direct = normalized.match(/^\+\+\+ (.+)$/m);
|
|
||||||
if (!direct || !direct[1] || direct[1] === "/dev/null") {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
return direct[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function splitUnifiedDiffByFile(diff: string): Map<string, string> {
|
|
||||||
const normalized = diff.replace(/\r\n/g, "\n");
|
|
||||||
const byPath = new Map<string, string>();
|
|
||||||
const headerMatches = [...normalized.matchAll(/^diff --git .+$/gm)];
|
|
||||||
|
|
||||||
if (headerMatches.length === 0) {
|
|
||||||
const path = parsePathFromDiff(normalized);
|
|
||||||
if (path) {
|
|
||||||
byPath.set(path, normalized.trim());
|
|
||||||
}
|
|
||||||
return byPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let index = 0; index < headerMatches.length; index += 1) {
|
|
||||||
const match = headerMatches[index];
|
|
||||||
if (!match) continue;
|
|
||||||
const start = match.index ?? 0;
|
|
||||||
const nextStart = headerMatches[index + 1]?.index ?? normalized.length;
|
|
||||||
const segment = normalized.slice(start, nextStart).trim();
|
|
||||||
const path = parsePathFromDiff(segment);
|
|
||||||
if (!path || segment.length === 0) continue;
|
|
||||||
byPath.set(path, segment);
|
|
||||||
}
|
|
||||||
|
|
||||||
return byPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deriveTurnDiffFilesFromUnifiedDiff(diff: string): TurnDiffFileChange[] {
|
|
||||||
const fileDiffsByPath = splitUnifiedDiffByFile(diff);
|
|
||||||
return Array.from(fileDiffsByPath.entries())
|
|
||||||
.map(([path, fileDiff]) => {
|
|
||||||
const stat = countDiffStat(fileDiff);
|
|
||||||
return {
|
|
||||||
path,
|
|
||||||
diff: fileDiff,
|
|
||||||
additions: stat.additions,
|
|
||||||
deletions: stat.deletions,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function inferCheckpointTurnCountByTurnId(
|
|
||||||
summaries: TurnDiffSummary[],
|
|
||||||
): Record<string, number> {
|
|
||||||
if (summaries.length === 0) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
const sorted = [...summaries].toSorted((a, b) => {
|
|
||||||
const aTime = Date.parse(a.completedAt);
|
|
||||||
const bTime = Date.parse(b.completedAt);
|
|
||||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
|
||||||
return a.completedAt.localeCompare(b.completedAt);
|
|
||||||
}
|
|
||||||
return aTime - bTime;
|
|
||||||
});
|
|
||||||
|
|
||||||
const next: Record<string, number> = {};
|
|
||||||
let fallbackTurnCount = 1;
|
|
||||||
for (const summary of sorted) {
|
|
||||||
if (typeof summary.checkpointTurnCount === "number") {
|
|
||||||
next[summary.turnId] = summary.checkpointTurnCount;
|
|
||||||
fallbackTurnCount = Math.max(fallbackTurnCount, summary.checkpointTurnCount + 1);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
next[summary.turnId] = fallbackTurnCount;
|
|
||||||
fallbackTurnCount += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return next;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function countDiffStat(patch: string | undefined): { additions: number; deletions: number } {
|
|
||||||
if (!patch) {
|
|
||||||
return { additions: 0, deletions: 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
let additions = 0;
|
|
||||||
let deletions = 0;
|
|
||||||
for (const line of patch.replace(/\r\n/g, "\n").split("\n")) {
|
|
||||||
if (line.startsWith("+++ ") || line.startsWith("--- ")) continue;
|
|
||||||
if (line.startsWith("+")) {
|
|
||||||
additions += 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (line.startsWith("-")) {
|
|
||||||
deletions += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { additions, deletions };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function deriveTurnDiffSummaries(events: ProviderEvent[]): TurnDiffSummary[] {
|
|
||||||
const firstEventAt = Date.parse(events[0]?.createdAt ?? "");
|
|
||||||
const lastEventAt = Date.parse(events.at(-1)?.createdAt ?? "");
|
|
||||||
const ordered =
|
|
||||||
events.length < 2 ||
|
|
||||||
Number.isNaN(firstEventAt) ||
|
|
||||||
Number.isNaN(lastEventAt) ||
|
|
||||||
firstEventAt >= lastEventAt
|
|
||||||
? events
|
|
||||||
: [...events].toReversed();
|
|
||||||
const byTurnId = new Map<string, MutableTurnDiffSummary>();
|
|
||||||
|
|
||||||
const ensureSummary = (turnId: string): MutableTurnDiffSummary => {
|
|
||||||
const existing = byTurnId.get(turnId);
|
|
||||||
if (existing) return existing;
|
|
||||||
const next: MutableTurnDiffSummary = {
|
|
||||||
turnId,
|
|
||||||
completedAt: undefined,
|
|
||||||
status: undefined,
|
|
||||||
assistantMessageId: undefined,
|
|
||||||
unifiedDiff: undefined,
|
|
||||||
filesByPath: new Map<string, TurnDiffFileChange>(),
|
|
||||||
};
|
|
||||||
byTurnId.set(turnId, next);
|
|
||||||
return next;
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const event of ordered) {
|
|
||||||
const turnId = eventTurnId(event);
|
|
||||||
if (!turnId) continue;
|
|
||||||
const summary = ensureSummary(turnId);
|
|
||||||
|
|
||||||
if (event.method === "turn/completed") {
|
|
||||||
if (summary.completedAt === undefined) {
|
|
||||||
summary.completedAt = event.createdAt;
|
|
||||||
}
|
|
||||||
const turn = asObject(asObject(event.payload)?.turn);
|
|
||||||
if (summary.status === undefined) {
|
|
||||||
summary.status = normalizeDetail(asString(turn?.status));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.method === "item/completed") {
|
|
||||||
const item = asObject(asObject(event.payload)?.item);
|
|
||||||
if (asString(item?.type) === "agentMessage") {
|
|
||||||
const itemId = normalizeDetail(asString(item?.id));
|
|
||||||
if (itemId && summary.assistantMessageId === undefined) {
|
|
||||||
summary.assistantMessageId = itemId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.method === "turn/diff/updated" && summary.unifiedDiff === undefined) {
|
|
||||||
const diff = normalizeDetail(asString(asObject(event.payload)?.diff));
|
|
||||||
if (diff) {
|
|
||||||
summary.unifiedDiff = diff;
|
|
||||||
for (const file of deriveTurnDiffFilesFromUnifiedDiff(diff)) {
|
|
||||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const file of parseFileChangeEntriesFromEvent(event)) {
|
|
||||||
mergeTurnDiffFileChange(summary.filesByPath, file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const summaries: TurnDiffSummary[] = [];
|
|
||||||
for (const summary of byTurnId.values()) {
|
|
||||||
if (!summary.completedAt) continue;
|
|
||||||
|
|
||||||
summaries.push({
|
|
||||||
turnId: summary.turnId,
|
|
||||||
completedAt: summary.completedAt,
|
|
||||||
...(summary.status ? { status: summary.status } : {}),
|
|
||||||
files: Array.from(summary.filesByPath.values()).toSorted((a, b) =>
|
|
||||||
a.path.localeCompare(b.path),
|
|
||||||
),
|
|
||||||
...(summary.unifiedDiff ? { unifiedDiff: summary.unifiedDiff } : {}),
|
|
||||||
...(summary.assistantMessageId ? { assistantMessageId: summary.assistantMessageId } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
summaries.sort((a, b) => {
|
|
||||||
const aTime = Date.parse(a.completedAt);
|
|
||||||
const bTime = Date.parse(b.completedAt);
|
|
||||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
|
||||||
return b.completedAt.localeCompare(a.completedAt);
|
|
||||||
}
|
|
||||||
return bTime - aTime;
|
|
||||||
});
|
|
||||||
|
|
||||||
return summaries;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toTimestamp(isoDate: string): number {
|
function toTimestamp(isoDate: string): number {
|
||||||
const parsed = Date.parse(isoDate);
|
const parsed = Date.parse(isoDate);
|
||||||
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
|
||||||
|
|||||||
+2
-449
@@ -2,11 +2,7 @@ import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/con
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { type AppState, reducer } from "./store";
|
import { type AppState, reducer } from "./store";
|
||||||
import {
|
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
|
||||||
MAX_THREAD_TERMINAL_COUNT,
|
|
||||||
} from "./types";
|
|
||||||
import type { Thread } from "./types";
|
import type { Thread } from "./types";
|
||||||
|
|
||||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||||
@@ -57,7 +53,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
session: makeSession(),
|
session: makeSession(),
|
||||||
messages: [],
|
messages: [],
|
||||||
events: [],
|
events: [],
|
||||||
turnDiffSummaries: [],
|
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: "2026-02-09T00:00:00.000Z",
|
createdAt: "2026-02-09T00:00:00.000Z",
|
||||||
branch: null,
|
branch: null,
|
||||||
@@ -75,16 +70,12 @@ function makeState(thread: Thread): AppState {
|
|||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [thread],
|
threads: [thread],
|
||||||
activeThreadId: thread.id,
|
activeThreadId: thread.id,
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
diffOpen: false,
|
diffOpen: false,
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,21 +140,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
expect(next.threads[0]?.terminalOpen).toBe(true);
|
expect(next.threads[0]?.terminalOpen).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("opens diff panel with an explicit turn/file target", () => {
|
|
||||||
const state = makeState(makeThread());
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "OPEN_DIFF",
|
|
||||||
threadId: "thread-local-1",
|
|
||||||
turnId: "turn-1",
|
|
||||||
filePath: "src/app.ts",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.diffOpen).toBe(true);
|
|
||||||
expect(next.diffThreadId).toBe("thread-local-1");
|
|
||||||
expect(next.diffTurnId).toBe("turn-1");
|
|
||||||
expect(next.diffFilePath).toBe("src/app.ts");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("sets terminal open state per thread", () => {
|
it("sets terminal open state per thread", () => {
|
||||||
const state = makeState(makeThread({ terminalOpen: true }));
|
const state = makeState(makeThread({ terminalOpen: true }));
|
||||||
const next = reducer(state, {
|
const next = reducer(state, {
|
||||||
@@ -279,70 +255,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("caps split terminals at four per thread", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
|
||||||
activeTerminalId: "term-4",
|
|
||||||
terminalGroups: [
|
|
||||||
{
|
|
||||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SPLIT_THREAD_TERMINAL",
|
|
||||||
threadId: "thread-local-1",
|
|
||||||
terminalId: "term-5",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
|
||||||
expect(next.threads[0]?.terminalIds).toEqual([
|
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
|
||||||
"term-2",
|
|
||||||
"term-3",
|
|
||||||
"term-4",
|
|
||||||
]);
|
|
||||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("caps new terminals at four per thread", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3", "term-4"],
|
|
||||||
activeTerminalId: "term-4",
|
|
||||||
terminalGroups: [
|
|
||||||
{
|
|
||||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
|
||||||
},
|
|
||||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
|
||||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
|
||||||
{ id: "group-term-4", terminalIds: ["term-4"] },
|
|
||||||
],
|
|
||||||
activeTerminalGroupId: "group-term-4",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "NEW_THREAD_TERMINAL",
|
|
||||||
threadId: "thread-local-1",
|
|
||||||
terminalId: "term-5",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.terminalIds).toHaveLength(MAX_THREAD_TERMINAL_COUNT);
|
|
||||||
expect(next.threads[0]?.terminalIds).toEqual([
|
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
|
||||||
"term-2",
|
|
||||||
"term-3",
|
|
||||||
"term-4",
|
|
||||||
]);
|
|
||||||
expect(next.threads[0]?.activeTerminalId).toBe("term-4");
|
|
||||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-4");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||||
const state = makeState(
|
const state = makeState(
|
||||||
makeThread({
|
makeThread({
|
||||||
@@ -518,74 +430,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
|
expect(next.threads[0]?.session?.threadId).toBe("thr_new");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves persisted turn diffs when events were reset and appends new completed turn diffs", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
events: [],
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-09T00:00:01.000Z",
|
|
||||||
files: [{ path: "src/existing.ts", kind: "modified" }],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const withFileChange = reducer(state, {
|
|
||||||
type: "APPLY_EVENT",
|
|
||||||
event: makeEvent({
|
|
||||||
method: "item/completed",
|
|
||||||
turnId: "turn-2",
|
|
||||||
createdAt: "2026-02-09T00:00:02.000Z",
|
|
||||||
payload: {
|
|
||||||
item: {
|
|
||||||
type: "fileChange",
|
|
||||||
changes: [{ path: "src/new.ts", kind: "added" }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
activeAssistantItemRef: { current: null },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(withFileChange.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
|
||||||
"turn-1",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const completed = reducer(withFileChange, {
|
|
||||||
type: "APPLY_EVENT",
|
|
||||||
event: makeEvent({
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-2",
|
|
||||||
createdAt: "2026-02-09T00:00:03.000Z",
|
|
||||||
payload: { turn: { id: "turn-2", status: "completed" } },
|
|
||||||
}),
|
|
||||||
activeAssistantItemRef: { current: null },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(completed.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
|
|
||||||
"turn-2",
|
|
||||||
"turn-1",
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("infers checkpoint turn counts when deriving turn summaries from an empty baseline", () => {
|
|
||||||
const state = makeState(makeThread({ turnDiffSummaries: [] }));
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "APPLY_EVENT",
|
|
||||||
event: makeEvent({
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-09T00:00:03.000Z",
|
|
||||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
|
||||||
}),
|
|
||||||
activeAssistantItemRef: { current: null },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.turnId).toBe("turn-1");
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointTurnCount).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("reconciles project ids by cwd when syncing backend projects", () => {
|
it("reconciles project ids by cwd when syncing backend projects", () => {
|
||||||
const state: AppState = {
|
const state: AppState = {
|
||||||
projects: [
|
projects: [
|
||||||
@@ -595,7 +439,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
cwd: "/tmp/a",
|
cwd: "/tmp/a",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: false,
|
expanded: false,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "project-old-b",
|
id: "project-old-b",
|
||||||
@@ -603,7 +446,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
cwd: "/tmp/b",
|
cwd: "/tmp/b",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
threads: [
|
threads: [
|
||||||
@@ -618,10 +460,7 @@ describe("store reducer thread continuity", () => {
|
|||||||
],
|
],
|
||||||
activeThreadId: "thread-b",
|
activeThreadId: "thread-b",
|
||||||
runtimeMode: "full-access",
|
runtimeMode: "full-access",
|
||||||
diffOpen: true,
|
diffOpen: false,
|
||||||
diffThreadId: "thread-b",
|
|
||||||
diffTurnId: "turn-b",
|
|
||||||
diffFilePath: "src/removed.ts",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const next = reducer(state, {
|
const next = reducer(state, {
|
||||||
@@ -633,7 +472,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
cwd: "/tmp/a",
|
cwd: "/tmp/a",
|
||||||
model: "gpt-5.3-codex",
|
model: "gpt-5.3-codex",
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -646,137 +484,6 @@ describe("store reducer thread continuity", () => {
|
|||||||
expect(next.threads[0]?.id).toBe("thread-a");
|
expect(next.threads[0]?.id).toBe("thread-a");
|
||||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||||
expect(next.activeThreadId).toBe("thread-a");
|
expect(next.activeThreadId).toBe("thread-a");
|
||||||
expect(next.diffOpen).toBe(false);
|
|
||||||
expect(next.diffThreadId).toBeNull();
|
|
||||||
expect(next.diffTurnId).toBeNull();
|
|
||||||
expect(next.diffFilePath).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("treats empty scripts from sync as authoritative", () => {
|
|
||||||
const state: AppState = {
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: "project-old-a",
|
|
||||||
name: "A",
|
|
||||||
cwd: "/tmp/a",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: true,
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
name: "Test",
|
|
||||||
command: "bun test",
|
|
||||||
icon: "test",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
|
|
||||||
activeThreadId: "thread-a",
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
diffOpen: false,
|
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SYNC_PROJECTS",
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: "project-new-a",
|
|
||||||
name: "A",
|
|
||||||
cwd: "/tmp/a",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: false,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.projects[0]?.scripts).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("updates project scripts", () => {
|
|
||||||
const state = makeState(makeThread());
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SET_PROJECT_SCRIPTS",
|
|
||||||
projectId: "project-1",
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
name: "Test",
|
|
||||||
command: "bun test",
|
|
||||||
icon: "test",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.projects[0]?.scripts).toEqual([
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
name: "Test",
|
|
||||||
command: "bun test",
|
|
||||||
icon: "test",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("deletes a project and all of its threads", () => {
|
|
||||||
const state: AppState = {
|
|
||||||
projects: [
|
|
||||||
{
|
|
||||||
id: "project-1",
|
|
||||||
name: "One",
|
|
||||||
cwd: "/tmp/one",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: true,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "project-2",
|
|
||||||
name: "Two",
|
|
||||||
cwd: "/tmp/two",
|
|
||||||
model: "gpt-5.3-codex",
|
|
||||||
expanded: true,
|
|
||||||
scripts: [],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
threads: [
|
|
||||||
makeThread({
|
|
||||||
id: "thread-a",
|
|
||||||
projectId: "project-1",
|
|
||||||
}),
|
|
||||||
makeThread({
|
|
||||||
id: "thread-b",
|
|
||||||
projectId: "project-2",
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
activeThreadId: "thread-a",
|
|
||||||
runtimeMode: "full-access",
|
|
||||||
diffOpen: true,
|
|
||||||
diffThreadId: "thread-a",
|
|
||||||
diffTurnId: "turn-a",
|
|
||||||
diffFilePath: "src/a.ts",
|
|
||||||
};
|
|
||||||
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "DELETE_PROJECT",
|
|
||||||
projectId: "project-1",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.projects).toHaveLength(1);
|
|
||||||
expect(next.projects[0]?.id).toBe("project-2");
|
|
||||||
expect(next.threads).toHaveLength(1);
|
|
||||||
expect(next.threads[0]?.id).toBe("thread-b");
|
|
||||||
expect(next.activeThreadId).toBe("thread-b");
|
|
||||||
expect(next.diffOpen).toBe(false);
|
|
||||||
expect(next.diffThreadId).toBeNull();
|
|
||||||
expect(next.diffTurnId).toBeNull();
|
|
||||||
expect(next.diffFilePath).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("marks the active thread as visited when selected", () => {
|
it("marks the active thread as visited when selected", () => {
|
||||||
@@ -822,158 +529,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",
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn_1",
|
|
||||||
completedAt: "2026-02-08T10:00:01.000Z",
|
|
||||||
files: [{ path: "src/first.ts", kind: "modified" }],
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
turnId: "turn_2",
|
|
||||||
completedAt: "2026-02-08T10:00:03.000Z",
|
|
||||||
files: [{ path: "src/second.ts", kind: "modified" }],
|
|
||||||
checkpointTurnCount: 2,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
error: "temporary failure",
|
|
||||||
latestTurnId: "turn-live",
|
|
||||||
latestTurnStartedAt: "2026-02-08T10:00:03.000Z",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "REVERT_TO_CHECKPOINT",
|
|
||||||
threadId: "thread-local-1",
|
|
||||||
sessionId: "sess-1",
|
|
||||||
threadRuntimeId: "thr_after",
|
|
||||||
turnCount: 1,
|
|
||||||
messageCount: 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.codexThreadId).toBe("thr_after");
|
|
||||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual(["m-1", "m-2"]);
|
|
||||||
expect(next.threads[0]?.events).toEqual([]);
|
|
||||||
expect(next.threads[0]?.error).toBeNull();
|
|
||||||
expect(next.threads[0]?.session?.status).toBe("ready");
|
|
||||||
expect(next.threads[0]?.session?.activeTurnId).toBeUndefined();
|
|
||||||
expect(next.threads[0]?.session?.threadId).toBe("thr_after");
|
|
||||||
expect(next.threads[0]?.latestTurnId).toBeUndefined();
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual(["turn_1"]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps checkpoint-derived turn files when later events for the same turn arrive", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-09T00:00:03.000Z",
|
|
||||||
files: [
|
|
||||||
{
|
|
||||||
path: "src/from-checkpoint.ts",
|
|
||||||
diff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
unifiedDiff: "diff --git a/src/from-checkpoint.ts b/src/from-checkpoint.ts",
|
|
||||||
checkpointDiffLoaded: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "APPLY_EVENT",
|
|
||||||
event: makeEvent({
|
|
||||||
method: "turn/completed",
|
|
||||||
turnId: "turn-1",
|
|
||||||
createdAt: "2026-02-09T00:00:04.000Z",
|
|
||||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
|
||||||
}),
|
|
||||||
activeAssistantItemRef: { current: null },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
|
||||||
"src/from-checkpoint.ts",
|
|
||||||
]);
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.unifiedDiff).toContain("from-checkpoint.ts");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("updates turn summaries from checkpoint diffs and marks them as loaded", () => {
|
|
||||||
const state = makeState(
|
|
||||||
makeThread({
|
|
||||||
turnDiffSummaries: [
|
|
||||||
{
|
|
||||||
turnId: "turn-1",
|
|
||||||
completedAt: "2026-02-09T00:00:03.000Z",
|
|
||||||
files: [],
|
|
||||||
checkpointTurnCount: 1,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
const next = reducer(state, {
|
|
||||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS",
|
|
||||||
threadId: "thread-local-1",
|
|
||||||
checkpointDiffByTurnId: {
|
|
||||||
"turn-1": [
|
|
||||||
"diff --git a/src/a.ts b/src/a.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old-a",
|
|
||||||
"+new-a",
|
|
||||||
"diff --git a/src/b.ts b/src/b.ts",
|
|
||||||
"@@ -1 +1 @@",
|
|
||||||
"-old-b",
|
|
||||||
"+new-b",
|
|
||||||
].join("\n"),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.files.map((file) => file.path)).toEqual([
|
|
||||||
"src/a.ts",
|
|
||||||
"src/b.ts",
|
|
||||||
]);
|
|
||||||
expect(next.threads[0]?.turnDiffSummaries[0]?.checkpointDiffLoaded).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
+26
-398
@@ -8,24 +8,14 @@ import {
|
|||||||
useReducer,
|
useReducer,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
|
||||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||||
import { resolveModelSlug } from "./model-logic";
|
import { resolveModelSlug } from "./model-logic";
|
||||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||||
import {
|
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||||
applyEventToMessages,
|
|
||||||
asObject,
|
|
||||||
asString,
|
|
||||||
deriveTurnDiffFilesFromUnifiedDiff,
|
|
||||||
deriveTurnDiffSummaries,
|
|
||||||
inferCheckpointTurnCountByTurnId,
|
|
||||||
evolveSession,
|
|
||||||
} from "./session-logic";
|
|
||||||
import {
|
import {
|
||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
DEFAULT_THREAD_TERMINAL_ID,
|
DEFAULT_THREAD_TERMINAL_ID,
|
||||||
DEFAULT_RUNTIME_MODE,
|
DEFAULT_RUNTIME_MODE,
|
||||||
MAX_THREAD_TERMINAL_COUNT,
|
|
||||||
type ProjectScript,
|
|
||||||
type Project,
|
type Project,
|
||||||
type RuntimeMode,
|
type RuntimeMode,
|
||||||
type Thread,
|
type Thread,
|
||||||
@@ -36,10 +26,8 @@ import {
|
|||||||
|
|
||||||
type Action =
|
type Action =
|
||||||
| { type: "ADD_PROJECT"; project: Project }
|
| { type: "ADD_PROJECT"; project: Project }
|
||||||
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
|
|
||||||
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
| { type: "SYNC_PROJECTS"; projects: Project[] }
|
||||||
| { type: "TOGGLE_PROJECT"; projectId: string }
|
| { type: "TOGGLE_PROJECT"; projectId: string }
|
||||||
| { type: "DELETE_PROJECT"; projectId: string }
|
|
||||||
| { type: "ADD_THREAD"; thread: Thread }
|
| { type: "ADD_THREAD"; thread: Thread }
|
||||||
| { type: "SET_ACTIVE_THREAD"; threadId: string }
|
| { type: "SET_ACTIVE_THREAD"; threadId: string }
|
||||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
|
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
|
||||||
@@ -50,19 +38,6 @@ type Action =
|
|||||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||||
| { type: "TOGGLE_DIFF" }
|
| { type: "TOGGLE_DIFF" }
|
||||||
| {
|
|
||||||
type: "OPEN_DIFF";
|
|
||||||
threadId: string;
|
|
||||||
turnId?: string;
|
|
||||||
filePath?: string;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
type: "SET_DIFF_TARGET";
|
|
||||||
threadId: string;
|
|
||||||
turnId?: string;
|
|
||||||
filePath?: string;
|
|
||||||
}
|
|
||||||
| { type: "CLOSE_DIFF" }
|
|
||||||
| {
|
| {
|
||||||
type: "APPLY_EVENT";
|
type: "APPLY_EVENT";
|
||||||
event: ProviderEvent;
|
event: ProviderEvent;
|
||||||
@@ -80,24 +55,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;
|
|
||||||
turnCount: number;
|
|
||||||
messageCount: number;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
type: "SET_THREAD_TURN_CHECKPOINT_COUNTS";
|
|
||||||
threadId: string;
|
|
||||||
checkpointTurnCountByTurnId: Record<string, number>;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
type: "SET_THREAD_TURN_CHECKPOINT_DIFFS";
|
|
||||||
threadId: string;
|
|
||||||
checkpointDiffByTurnId: Record<string, string>;
|
|
||||||
}
|
|
||||||
| {
|
| {
|
||||||
type: "SET_THREAD_BRANCH";
|
type: "SET_THREAD_BRANCH";
|
||||||
threadId: string;
|
threadId: string;
|
||||||
@@ -115,9 +72,6 @@ export interface AppState {
|
|||||||
activeThreadId: string | null;
|
activeThreadId: string | null;
|
||||||
runtimeMode: RuntimeMode;
|
runtimeMode: RuntimeMode;
|
||||||
diffOpen: boolean;
|
diffOpen: boolean;
|
||||||
diffThreadId: string | null;
|
|
||||||
diffTurnId: string | null;
|
|
||||||
diffFilePath: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||||
@@ -138,9 +92,6 @@ const initialState: AppState = {
|
|||||||
activeThreadId: null,
|
activeThreadId: null,
|
||||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||||
diffOpen: false,
|
diffOpen: false,
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Helpers ──────────────────────────────────────────────────────────
|
// ── Helpers ──────────────────────────────────────────────────────────
|
||||||
@@ -158,20 +109,7 @@ function readPersistedState(): AppState {
|
|||||||
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
|
||||||
if (!hydrated) return initialState;
|
if (!hydrated) return initialState;
|
||||||
|
|
||||||
const threads = hydrated.threads.map((thread) => normalizeThreadTerminals(thread));
|
return { ...hydrated, diffOpen: false };
|
||||||
const activeThreadId = threads.some((thread) => thread.id === hydrated.activeThreadId)
|
|
||||||
? hydrated.activeThreadId
|
|
||||||
: (threads[0]?.id ?? null);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...hydrated,
|
|
||||||
threads,
|
|
||||||
activeThreadId,
|
|
||||||
diffOpen: false,
|
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
};
|
|
||||||
} catch {
|
} catch {
|
||||||
return initialState;
|
return initialState;
|
||||||
}
|
}
|
||||||
@@ -198,105 +136,9 @@ function updateThread(
|
|||||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetDiffTargetIfMissing(state: AppState, threads: Thread[]) {
|
|
||||||
if (!state.diffThreadId) {
|
|
||||||
return {
|
|
||||||
diffOpen: state.diffOpen,
|
|
||||||
diffThreadId: state.diffThreadId,
|
|
||||||
diffTurnId: state.diffTurnId,
|
|
||||||
diffFilePath: state.diffFilePath,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const hasThread = threads.some((thread) => thread.id === state.diffThreadId);
|
|
||||||
if (hasThread) {
|
|
||||||
return {
|
|
||||||
diffOpen: state.diffOpen,
|
|
||||||
diffThreadId: state.diffThreadId,
|
|
||||||
diffTurnId: state.diffTurnId,
|
|
||||||
diffFilePath: state.diffFilePath,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
diffOpen: false,
|
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeTurnDiffSummaries(
|
|
||||||
existing: Thread["turnDiffSummaries"],
|
|
||||||
next: Thread["turnDiffSummaries"],
|
|
||||||
): Thread["turnDiffSummaries"] {
|
|
||||||
if (next.length === 0) return existing;
|
|
||||||
|
|
||||||
const existingByTurnId = new Map(existing.map((summary) => [summary.turnId, summary] as const));
|
|
||||||
const merged = next.map((summary) => {
|
|
||||||
const previous = existingByTurnId.get(summary.turnId);
|
|
||||||
if (!previous) {
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
|
|
||||||
const prefersCheckpointDiff = previous.checkpointDiffLoaded || summary.checkpointDiffLoaded;
|
|
||||||
const files =
|
|
||||||
prefersCheckpointDiff ||
|
|
||||||
(summary.files.length === 0 && previous.files.length > 0 && summary.unifiedDiff === undefined)
|
|
||||||
? previous.files
|
|
||||||
: summary.files;
|
|
||||||
const unifiedDiff =
|
|
||||||
prefersCheckpointDiff || summary.unifiedDiff === undefined
|
|
||||||
? (previous.unifiedDiff ?? summary.unifiedDiff)
|
|
||||||
: summary.unifiedDiff;
|
|
||||||
|
|
||||||
return {
|
|
||||||
...summary,
|
|
||||||
files,
|
|
||||||
...(unifiedDiff !== undefined ? { unifiedDiff } : {}),
|
|
||||||
...(summary.assistantMessageId
|
|
||||||
? {}
|
|
||||||
: previous.assistantMessageId
|
|
||||||
? { assistantMessageId: previous.assistantMessageId }
|
|
||||||
: {}),
|
|
||||||
...(typeof summary.checkpointTurnCount === "number"
|
|
||||||
? {}
|
|
||||||
: typeof previous.checkpointTurnCount === "number"
|
|
||||||
? { checkpointTurnCount: previous.checkpointTurnCount }
|
|
||||||
: {}),
|
|
||||||
...(summary.checkpointDiffLoaded || previous.checkpointDiffLoaded
|
|
||||||
? { checkpointDiffLoaded: true }
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const mergedTurnIds = new Set(merged.map((summary) => summary.turnId));
|
|
||||||
for (const summary of existing) {
|
|
||||||
if (!mergedTurnIds.has(summary.turnId)) {
|
|
||||||
merged.push(summary);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const sorted = merged.toSorted((a, b) => {
|
|
||||||
const aTime = Date.parse(a.completedAt);
|
|
||||||
const bTime = Date.parse(b.completedAt);
|
|
||||||
if (Number.isNaN(aTime) || Number.isNaN(bTime)) {
|
|
||||||
return b.completedAt.localeCompare(a.completedAt);
|
|
||||||
}
|
|
||||||
return bTime - aTime;
|
|
||||||
});
|
|
||||||
|
|
||||||
const inferredTurnCountByTurnId = inferCheckpointTurnCountByTurnId(sorted);
|
|
||||||
return sorted.map((summary) =>
|
|
||||||
typeof summary.checkpointTurnCount === "number"
|
|
||||||
? summary
|
|
||||||
: Object.assign({}, summary, {
|
|
||||||
checkpointTurnCount: inferredTurnCountByTurnId[summary.turnId],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
const unique = [...new Set(ids)];
|
||||||
if (unique.length > 0) {
|
if (unique.length > 0) {
|
||||||
return unique;
|
return unique;
|
||||||
}
|
}
|
||||||
@@ -314,7 +156,6 @@ function normalizeRunningTerminalIds(
|
|||||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||||
}
|
}
|
||||||
@@ -578,33 +419,20 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
{
|
{
|
||||||
...action.project,
|
...action.project,
|
||||||
model: resolveModelSlug(action.project.model),
|
model: resolveModelSlug(action.project.model),
|
||||||
scripts: normalizeProjectScripts(action.project.scripts),
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
case "SET_PROJECT_SCRIPTS":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
projects: state.projects.map((project) =>
|
|
||||||
project.id === action.projectId
|
|
||||||
? { ...project, scripts: normalizeProjectScripts(action.scripts) }
|
|
||||||
: project,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SYNC_PROJECTS": {
|
case "SYNC_PROJECTS": {
|
||||||
const previousByCwd = new Map(
|
const previousByCwd = new Map(
|
||||||
state.projects.map((project) => [project.cwd, project] as const),
|
state.projects.map((project) => [project.cwd, project] as const),
|
||||||
);
|
);
|
||||||
const nextProjects = action.projects.map((project) => {
|
const nextProjects = action.projects.map((project) => {
|
||||||
const previous = previousByCwd.get(project.cwd);
|
const previous = previousByCwd.get(project.cwd);
|
||||||
const scripts = normalizeProjectScripts(project.scripts);
|
|
||||||
return {
|
return {
|
||||||
...project,
|
...project,
|
||||||
model: resolveModelSlug(previous?.model ?? project.model),
|
model: resolveModelSlug(previous?.model ?? project.model),
|
||||||
expanded: previous?.expanded ?? project.expanded,
|
expanded: previous?.expanded ?? project.expanded,
|
||||||
scripts,
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
const previousProjectById = new Map(
|
const previousProjectById = new Map(
|
||||||
@@ -628,14 +456,12 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
|
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
|
||||||
? state.activeThreadId
|
? state.activeThreadId
|
||||||
: (nextThreads[0]?.id ?? null);
|
: (nextThreads[0]?.id ?? null);
|
||||||
const diffState = resetDiffTargetIfMissing(state, nextThreads);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
projects: nextProjects,
|
projects: nextProjects,
|
||||||
threads: nextThreads,
|
threads: nextThreads,
|
||||||
activeThreadId,
|
activeThreadId,
|
||||||
...diffState,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -647,33 +473,11 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
case "DELETE_PROJECT": {
|
|
||||||
const projects = state.projects.filter((project) => project.id !== action.projectId);
|
|
||||||
if (projects.length === state.projects.length) {
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
|
|
||||||
const threads = state.threads.filter((thread) => thread.projectId !== action.projectId);
|
|
||||||
const activeThreadId = threads.some((thread) => thread.id === state.activeThreadId)
|
|
||||||
? state.activeThreadId
|
|
||||||
: (threads[0]?.id ?? null);
|
|
||||||
const diffState = resetDiffTargetIfMissing(state, threads);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
projects,
|
|
||||||
threads,
|
|
||||||
activeThreadId,
|
|
||||||
...diffState,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
case "ADD_THREAD": {
|
case "ADD_THREAD": {
|
||||||
const nextThread = normalizeThreadTerminals({
|
const nextThread = normalizeThreadTerminals({
|
||||||
...action.thread,
|
...action.thread,
|
||||||
model: resolveModelSlug(action.thread.model),
|
model: resolveModelSlug(action.thread.model),
|
||||||
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
||||||
turnDiffSummaries: action.thread.turnDiffSummaries ?? [],
|
|
||||||
});
|
});
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
@@ -726,13 +530,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
...state,
|
...state,
|
||||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||||
const normalizedThread = normalizeThreadTerminals(thread);
|
const normalizedThread = normalizeThreadTerminals(thread);
|
||||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
|
||||||
if (
|
|
||||||
isNewTerminal &&
|
|
||||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
|
||||||
) {
|
|
||||||
return normalizedThread;
|
|
||||||
}
|
|
||||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||||
? normalizedThread.terminalIds
|
? normalizedThread.terminalIds
|
||||||
: [...normalizedThread.terminalIds, action.terminalId];
|
: [...normalizedThread.terminalIds, action.terminalId];
|
||||||
@@ -799,13 +596,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
...state,
|
...state,
|
||||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||||
const normalizedThread = normalizeThreadTerminals(thread);
|
const normalizedThread = normalizeThreadTerminals(thread);
|
||||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
|
||||||
if (
|
|
||||||
isNewTerminal &&
|
|
||||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
|
||||||
) {
|
|
||||||
return normalizedThread;
|
|
||||||
}
|
|
||||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||||
? normalizedThread.terminalIds
|
? normalizedThread.terminalIds
|
||||||
: [...normalizedThread.terminalIds, action.terminalId];
|
: [...normalizedThread.terminalIds, action.terminalId];
|
||||||
@@ -864,26 +654,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
case "TOGGLE_DIFF":
|
case "TOGGLE_DIFF":
|
||||||
return { ...state, diffOpen: !state.diffOpen };
|
return { ...state, diffOpen: !state.diffOpen };
|
||||||
|
|
||||||
case "OPEN_DIFF":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
diffOpen: true,
|
|
||||||
diffThreadId: action.threadId,
|
|
||||||
diffTurnId: action.turnId ?? null,
|
|
||||||
diffFilePath: action.filePath ?? null,
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SET_DIFF_TARGET":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
diffThreadId: action.threadId,
|
|
||||||
diffTurnId: action.turnId ?? null,
|
|
||||||
diffFilePath: action.filePath ?? null,
|
|
||||||
};
|
|
||||||
|
|
||||||
case "CLOSE_DIFF":
|
|
||||||
return { ...state, diffOpen: false };
|
|
||||||
|
|
||||||
case "APPLY_TERMINAL_EVENT":
|
case "APPLY_TERMINAL_EVENT":
|
||||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||||
return state;
|
return state;
|
||||||
@@ -920,37 +690,27 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
threads: updateThread(state.threads, target.id, (t) => {
|
threads: updateThread(state.threads, target.id, (t) => ({
|
||||||
const nextEvents = [event, ...t.events];
|
...t,
|
||||||
const itemType = asString(asObject(asObject(event.payload)?.item)?.type);
|
...(() => {
|
||||||
const normalizedItemType = itemType?.replace(/[_-]/g, "").toLowerCase();
|
const eventThreadId = getEventThreadId(event);
|
||||||
const shouldRederiveDiffs =
|
const shouldRebindIdentity =
|
||||||
event.method === "turn/completed" ||
|
event.method === "thread/started" && t.session?.status === "connecting";
|
||||||
event.method === "turn/diff/updated" ||
|
return {
|
||||||
(event.method === "item/completed" &&
|
codexThreadId: shouldRebindIdentity
|
||||||
(normalizedItemType === "agentmessage" || normalizedItemType === "filechange"));
|
? (eventThreadId ?? t.codexThreadId)
|
||||||
const turnDiffSummaries = shouldRederiveDiffs
|
: (t.codexThreadId ?? eventThreadId ?? null),
|
||||||
? mergeTurnDiffSummaries(t.turnDiffSummaries, deriveTurnDiffSummaries(nextEvents))
|
error: event.kind === "error" && event.message ? event.message : t.error,
|
||||||
: t.turnDiffSummaries;
|
};
|
||||||
const eventThreadId = getEventThreadId(event);
|
})(),
|
||||||
const shouldRebindIdentity =
|
session: t.session ? evolveSession(t.session, event) : t.session,
|
||||||
event.method === "thread/started" && t.session?.status === "connecting";
|
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||||
return {
|
events: [event, ...t.events],
|
||||||
...t,
|
...updateTurnFields(t, event),
|
||||||
codexThreadId: shouldRebindIdentity
|
...(event.method === "turn/completed" && t.id === state.activeThreadId
|
||||||
? (eventThreadId ?? t.codexThreadId)
|
? { lastVisitedAt: event.createdAt }
|
||||||
: (t.codexThreadId ?? eventThreadId ?? null),
|
: {}),
|
||||||
error: event.kind === "error" && event.message ? event.message : t.error,
|
})),
|
||||||
session: t.session ? evolveSession(t.session, event) : t.session,
|
|
||||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
|
||||||
events: nextEvents,
|
|
||||||
turnDiffSummaries,
|
|
||||||
...updateTurnFields(t, event),
|
|
||||||
...(event.method === "turn/completed" && t.id === state.activeThreadId
|
|
||||||
? { lastVisitedAt: event.createdAt }
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1018,125 +778,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 nextTurnCount = Math.max(0, Math.floor(action.turnCount));
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
return {
|
|
||||||
...t,
|
|
||||||
codexThreadId: action.threadRuntimeId,
|
|
||||||
session:
|
|
||||||
t.session?.sessionId === action.sessionId
|
|
||||||
? {
|
|
||||||
...t.session,
|
|
||||||
status: "ready",
|
|
||||||
threadId: action.threadRuntimeId,
|
|
||||||
activeTurnId: undefined,
|
|
||||||
updatedAt: now,
|
|
||||||
lastError: undefined,
|
|
||||||
}
|
|
||||||
: t.session,
|
|
||||||
messages: t.messages.slice(0, nextMessageCount),
|
|
||||||
events: [],
|
|
||||||
turnDiffSummaries: t.turnDiffSummaries.filter(
|
|
||||||
(summary) =>
|
|
||||||
typeof summary.checkpointTurnCount === "number" &&
|
|
||||||
summary.checkpointTurnCount <= nextTurnCount,
|
|
||||||
),
|
|
||||||
error: null,
|
|
||||||
latestTurnId: undefined,
|
|
||||||
latestTurnStartedAt: undefined,
|
|
||||||
latestTurnCompletedAt: undefined,
|
|
||||||
latestTurnDurationMs: undefined,
|
|
||||||
lastVisitedAt: now,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SET_THREAD_TURN_CHECKPOINT_COUNTS":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
|
||||||
const hasUpdates = t.turnDiffSummaries.some(
|
|
||||||
(summary) =>
|
|
||||||
action.checkpointTurnCountByTurnId[summary.turnId] !== undefined &&
|
|
||||||
action.checkpointTurnCountByTurnId[summary.turnId] !== summary.checkpointTurnCount,
|
|
||||||
);
|
|
||||||
if (!hasUpdates) {
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...t,
|
|
||||||
turnDiffSummaries: t.turnDiffSummaries.map((summary) => {
|
|
||||||
const turnCount = action.checkpointTurnCountByTurnId[summary.turnId];
|
|
||||||
if (turnCount === undefined) {
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
...summary,
|
|
||||||
checkpointTurnCount: turnCount,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SET_THREAD_TURN_CHECKPOINT_DIFFS":
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
|
||||||
let hasUpdates = false;
|
|
||||||
const updatedSummaries = t.turnDiffSummaries.map((summary) => {
|
|
||||||
const checkpointDiff = action.checkpointDiffByTurnId[summary.turnId];
|
|
||||||
if (checkpointDiff === undefined) {
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
|
|
||||||
const files = deriveTurnDiffFilesFromUnifiedDiff(checkpointDiff);
|
|
||||||
const filesUnchanged =
|
|
||||||
files.length === summary.files.length &&
|
|
||||||
files.every((file, index) => {
|
|
||||||
const existing = summary.files[index];
|
|
||||||
return (
|
|
||||||
existing !== undefined &&
|
|
||||||
existing.path === file.path &&
|
|
||||||
existing.diff === file.diff &&
|
|
||||||
existing.kind === file.kind &&
|
|
||||||
existing.additions === file.additions &&
|
|
||||||
existing.deletions === file.deletions
|
|
||||||
);
|
|
||||||
});
|
|
||||||
if (
|
|
||||||
summary.unifiedDiff === checkpointDiff &&
|
|
||||||
filesUnchanged &&
|
|
||||||
summary.checkpointDiffLoaded
|
|
||||||
) {
|
|
||||||
return summary;
|
|
||||||
}
|
|
||||||
|
|
||||||
hasUpdates = true;
|
|
||||||
return {
|
|
||||||
...summary,
|
|
||||||
unifiedDiff: checkpointDiff,
|
|
||||||
files,
|
|
||||||
checkpointDiffLoaded: true,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!hasUpdates) {
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...t,
|
|
||||||
turnDiffSummaries: updatedSummaries,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
|
|
||||||
case "SET_THREAD_BRANCH": {
|
case "SET_THREAD_BRANCH": {
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
@@ -1165,20 +806,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
|||||||
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
const threads = state.threads.filter((t) => t.id !== action.threadId);
|
||||||
const activeThreadId =
|
const activeThreadId =
|
||||||
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
|
state.activeThreadId === action.threadId ? (threads[0]?.id ?? null) : state.activeThreadId;
|
||||||
const shouldClearDiffTarget = state.diffThreadId === action.threadId;
|
return { ...state, threads, activeThreadId };
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
threads,
|
|
||||||
activeThreadId,
|
|
||||||
...(shouldClearDiffTarget
|
|
||||||
? {
|
|
||||||
diffOpen: false,
|
|
||||||
diffThreadId: null,
|
|
||||||
diffTurnId: null,
|
|
||||||
diffFilePath: null,
|
|
||||||
}
|
|
||||||
: {}),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||||
import { isMacPlatform } from "./lib/utils";
|
|
||||||
|
|
||||||
export type TerminalLinkKind = "url" | "path";
|
export type TerminalLinkKind = "url" | "path";
|
||||||
|
|
||||||
@@ -16,6 +15,10 @@ const FILE_PATH_PATTERN =
|
|||||||
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
|
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
|
||||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||||
|
|
||||||
|
function isMacPlatform(platform: string): boolean {
|
||||||
|
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||||
|
}
|
||||||
|
|
||||||
function trimClosingDelimiters(value: string): string {
|
function trimClosingDelimiters(value: string): string {
|
||||||
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
|
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
|
||||||
if (output.length === 0) return output;
|
if (output.length === 0) return output;
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
isTerminalClearShortcut,
|
||||||
|
isTerminalToggleShortcut,
|
||||||
|
type ShortcutEventLike,
|
||||||
|
} from "./terminal-shortcuts";
|
||||||
|
|
||||||
|
function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
|
||||||
|
return {
|
||||||
|
key: "j",
|
||||||
|
metaKey: false,
|
||||||
|
ctrlKey: false,
|
||||||
|
shiftKey: false,
|
||||||
|
altKey: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("isTerminalToggleShortcut", () => {
|
||||||
|
it("matches Cmd+J on macOS", () => {
|
||||||
|
expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches Ctrl+J on non-macOS", () => {
|
||||||
|
expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects wrong modifiers", () => {
|
||||||
|
expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
|
||||||
|
expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-j keys", () => {
|
||||||
|
expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("isTerminalClearShortcut", () => {
|
||||||
|
it("matches Ctrl+L on all platforms", () => {
|
||||||
|
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
|
||||||
|
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches Cmd+K on macOS", () => {
|
||||||
|
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects Cmd+K on non-macOS", () => {
|
||||||
|
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects wrong modifiers", () => {
|
||||||
|
expect(
|
||||||
|
isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
export interface ShortcutEventLike {
|
||||||
|
key: string;
|
||||||
|
metaKey: boolean;
|
||||||
|
ctrlKey: boolean;
|
||||||
|
shiftKey: boolean;
|
||||||
|
altKey: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMacPlatform(platform: string): boolean {
|
||||||
|
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTerminalToggleShortcut(
|
||||||
|
event: ShortcutEventLike,
|
||||||
|
platform = navigator.platform,
|
||||||
|
): boolean {
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
if (key !== "j") return false;
|
||||||
|
if (event.shiftKey || event.altKey) return false;
|
||||||
|
|
||||||
|
if (isMacPlatform(platform)) {
|
||||||
|
return event.metaKey && !event.ctrlKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
return event.ctrlKey && !event.metaKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTerminalClearShortcut(
|
||||||
|
event: ShortcutEventLike,
|
||||||
|
platform = navigator.platform,
|
||||||
|
): boolean {
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
|
||||||
|
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
isMacPlatform(platform) &&
|
||||||
|
key === "k" &&
|
||||||
|
event.metaKey &&
|
||||||
|
!event.ctrlKey &&
|
||||||
|
!event.altKey &&
|
||||||
|
!event.shiftKey
|
||||||
|
);
|
||||||
|
}
|
||||||
+1
-28
@@ -1,16 +1,10 @@
|
|||||||
import type {
|
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||||
ProjectScript as ContractProjectScript,
|
|
||||||
ProviderEvent,
|
|
||||||
ProviderSession,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||||
export type RuntimeMode = "approval-required" | "full-access";
|
export type RuntimeMode = "approval-required" | "full-access";
|
||||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||||
export const MAX_THREAD_TERMINAL_COUNT = 4;
|
|
||||||
export type ProjectScript = ContractProjectScript;
|
|
||||||
|
|
||||||
export interface ThreadTerminalGroup {
|
export interface ThreadTerminalGroup {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -37,32 +31,12 @@ export interface ChatMessage {
|
|||||||
streaming: boolean;
|
streaming: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TurnDiffFileChange {
|
|
||||||
path: string;
|
|
||||||
kind?: string | undefined;
|
|
||||||
diff?: string | undefined;
|
|
||||||
additions?: number | undefined;
|
|
||||||
deletions?: number | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TurnDiffSummary {
|
|
||||||
turnId: string;
|
|
||||||
completedAt: string;
|
|
||||||
status?: string | undefined;
|
|
||||||
files: TurnDiffFileChange[];
|
|
||||||
unifiedDiff?: string | undefined;
|
|
||||||
assistantMessageId?: string | undefined;
|
|
||||||
checkpointTurnCount?: number | undefined;
|
|
||||||
checkpointDiffLoaded?: boolean | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Project {
|
export interface Project {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
cwd: string;
|
cwd: string;
|
||||||
model: string;
|
model: string;
|
||||||
expanded: boolean;
|
expanded: boolean;
|
||||||
scripts: ProjectScript[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Thread {
|
export interface Thread {
|
||||||
@@ -90,5 +64,4 @@ export interface Thread {
|
|||||||
lastVisitedAt?: string | undefined;
|
lastVisitedAt?: string | undefined;
|
||||||
branch: string | null;
|
branch: string | null;
|
||||||
worktreePath: string | null;
|
worktreePath: string | null;
|
||||||
turnDiffSummaries: TurnDiffSummary[];
|
|
||||||
}
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"version":"12.17.0","source":"https://raw.githubusercontent.com/vscode-icons/vscode-icons/v12.17.0/src/iconsManifest/languages.ts","generatedAt":"2026-02-17T20:03:11.362Z","extensionToLanguageId":{"as":"actionscript","ada":"ada","prw":"advpl","affect":"affectscript","agda":"agda","al":"al","alloy":"alloy","ansible":"ansible","g4":"antlr","any":"anyscript","htaccess":"apacheconf","cls":"apex","apib":"apiblueprint","apl":"apl","applescript":"applescript","adoc":"asciidoc","asp":"asp","asm":"arm","astro":"astro","ats":"ats","ahk":"ahk","au3":"autoit","am":"automake","avcs":"avro","azcli":"azcli","azure-pipelines.yml":"azure-pipelines","bal":"ballerina","bat":"bat","bats":"bats","bzl":"bazel","bf":"befunge","bicep":"bicep","bib":"bibtex","biml":"biml","bin":"code-text-binary","rast":"biome_syntax_tree","blade.php":"blade","blitzbasic":"blitzbasic","bolt":"bolt","bsq":"bosque","bru":"bruno","buf.yaml":"buf","lockb":"bun.lockb","c":"c","c3":"c3","cal":"c-al","cabal":"cabal","capnp":"capnp","casc":"casc","cddl":"cddl","ceylon":"ceylon","cfc":"cfc","cfm":"cfmhtml","circom":"circom","clojure":"clojure","clojurescript":"clojurescript","yml":"manifest-yaml","cmake":"cmake","cbl":"cobol","ql":"ql","coffee":"coffeescript","cfml":"cfml","confluence":"confluence","ckbk":"cookbook","instructions.md":"instructions","cpp":"cpp","cr":"crystal","cs":"csharp","css":"css","wxss":"css","acss":"css","mcss":"css","pcss":"css","postcss":"css","nss":"css","ccss":"css","less":"css","scss":"css","sass":"css","csv":"csv","feature":"cucumber","cu":"cuda","cypher":"cypher","pyx":"cython","dal":"dal","dart":"dart","dhall":"dhall","html":"django-html","diff":"diff","d":"d","hcl":"dockerbake","dtx":"doctex","env":"dotenv","dot":"dotjs","dox":"doxygen","drawio":"drawio","drl":"drools","dtd":"dtd","dust":"dustjs","dylan":"dylan","earthfile":"earthfile","edge":"edge","eex":"eex","es":"es","ex":"elixir","elm":"elm","erb":"erb","erl":"erlang","yaml":"esphome","xlsx":"excel","falcon":"falcon","fql":"fql","f":"fortran","ftl":"ftl","fs":"fsharp","fthtml":"fthtml","gspec":"galen","gml":"gml-gms","gcode":"gcode","gen":"genstat","git":"git-commit","gleam":"gleam","gjs":"glimmer-js","glsl":"glsl","glyphs":"glyphs","gp":"gnuplot","go":"go","mod":"go.mod","work":"go.work","api":"goctl","gd":"gdscript","gradle.kts":"gradle-kotlin-dsl","gr":"grain","gql":"graphql","gv":"dot","grit":"grit","groovy":"groovy","haml":"haml","hbs":"handlebars","prg":"harbour","hs":"haskell","haxe":"haxe","helm.tpl":"helm","hjson":"hjson","hlsl":"hlsl","hosts":"hosts","http":"http","aff":"hunspell.aff","hy":"hy","hypr":"hypr","icl":"icl","imba":"imba","4gl":"4GL","ini":"ini","ink":"ink","iss":"innosetup","io":"io","janet":"janet","java":"java","js":"javascript","mjs":"javascript","cjs":"javascript","es6":"javascript","jake":"javascript","jsm":"javascript","jsx":"javascript","njs":"javascript","pac":"javascript","sjs":"javascript","ssjs":"javascript","xsjs":"javascript","xsjslib":"javascript","jekyll":"jekyll","jenkins":"jenkins","jest-snap":"jest-snapshot","jinja":"jinja","json":"json","jsonc":"jsonc","jsonl":"jsonl","jsonnet":"jsonnet","json5":"json5","jl":"julia","id":"iodine","k":"k","kv":"kivy","ks":"kos","kt":"kotlin","kusto":"kusto","tex":"latex","lark":"lark","lat":"latino","lean":"lean4","flex":"lex","ly":"lilypond","lisp":"lisp","lhs":"literate haskell","log":"log","lol":"lolcode","lsl":"lsl","lua":"lua","m4":"m4","mk":"makefile","md":"markdown","markdown":"markdown","mdown":"markdown","mkd":"markdown","marko":"marko","mat":"matlab","ms":"maxscript","mdx":"mdx","mediawiki":"mediawiki","mel":"mel","mmd":"mermaid","metal":"metal","mcfunction":"bc-mcfunction","mjml":"mjml","pq":"powerquery","mojo":"mojo","ep":"mojolicious","mongo":"mongo","mson":"mson","mv":"mv","mvt":"mvt","ne":"nearley","nginx":"nginx","nim":"nim","nimble":"nimble","nix":"nix","nsi":"nsis","nunjucks":"nunjucks","nu":"nushell","m":"objective-c","mm":"objective-cpp","ml":"ocaml","o3":"ogone","w":"abl","things":"openhab","org":"org","pas":"pascal","pddl":"pddl","plan":"plan","happenings":"happenings","pl":"perl","pl6":"perl6","pgsql":"pgsql","php":"php","php4":"php","php5":"php","php7":"php","phtml":"php","phps":"php","phpt":"php","phar":"php","aw":"php","ctp":"php","inc":"php","php3":"php","php8":"php","module":"php","theme":"php","tpl":"php","pine":"pine","txt":"plaintext","dbgasm":"platformio-debug.disassembly","ddl":"plsql","po":"po","dib":"polyglot-notebook","polymer":"polymer","pony":"pony","ps":"postscript","ps1":"powershell","prisma":"prisma","pde":"pde","pro":"prolog","rules":"prometheus","properties":"java-properties","proto":"proto3","pug":"jade","pp":"puppet","purs":"purescript","arr":"pyret","pyscript":"pyscript","py":"python","pyi":"python","pyw":"python","pyc":"python","pyd":"python","pyo":"python","pxd":"python","pxi":"python","rpy":"python","cpy":"python","ipy":"python","pyowo":"pythowo","qvs":"qlik","qml":"qml","qs":"qsharp","r":"r","rkt":"racket","raku":"raku","cshtml":"razor","raml":"raLine truncated
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"iconDefinitions":{"_file":{"iconPath":"../../icons/default_file.svg"},"_folder":{"iconPath":"../../icons/default_folder.svg"},"_folder_open":{"iconPath":"../../icons/default_folder_opened.svg"},"_root_folder":{"iconPath":"../../icons/default_root_folder.svg"},"_root_folder_open":{"iconPath":"../../icons/default_root_folder_opened.svg"},"_file_light":{"iconPath":""},"_folder_light":{"iconPath":""},"_folder_light_open":{"iconPath":""},"_root_folder_light":{"iconPath":""},"_root_folder_light_open":{"iconPath":""},"_fd_android":{"iconPath":"../../icons/folder_type_android.svg"},"_fd_android_open":{"iconPath":"../../icons/folder_type_android_opened.svg"},"_fd_angular":{"iconPath":"../../icons/folder_type_angular.svg"},"_fd_angular_open":{"iconPath":"../../icons/folder_type_angular_opened.svg"},"_fd_apache":{"iconPath":"../../icons/folder_type_apache.svg"},"_fd_apache_open":{"iconPath":"../../icons/folder_type_apache_opened.svg"},"_fd_api":{"iconPath":"../../icons/folder_type_api.svg"},"_fd_api_open":{"iconPath":"../../icons/folder_type_api_opened.svg"},"_fd_app":{"iconPath":"../../icons/folder_type_app.svg"},"_fd_app_open":{"iconPath":"../../icons/folder_type_app_opened.svg"},"_fd_arangodb":{"iconPath":"../../icons/folder_type_arangodb.svg"},"_fd_arangodb_open":{"iconPath":"../../icons/folder_type_arangodb_opened.svg"},"_fd_asset":{"iconPath":"../../icons/folder_type_asset.svg"},"_fd_asset_open":{"iconPath":"../../icons/folder_type_asset_opened.svg"},"_fd_astro":{"iconPath":"../../icons/folder_type_astro.svg"},"_fd_astro_open":{"iconPath":"../../icons/folder_type_astro_opened.svg"},"_fd_audio":{"iconPath":"../../icons/folder_type_audio.svg"},"_fd_audio_open":{"iconPath":"../../icons/folder_type_audio_opened.svg"},"_fd_aurelia":{"iconPath":"../../icons/folder_type_aurelia.svg"},"_fd_aurelia_open":{"iconPath":"../../icons/folder_type_aurelia_opened.svg"},"_fd_aws":{"iconPath":"../../icons/folder_type_aws.svg"},"_fd_aws_open":{"iconPath":"../../icons/folder_type_aws_opened.svg"},"_fd_azure":{"iconPath":"../../icons/folder_type_azure.svg"},"_fd_azure_open":{"iconPath":"../../icons/folder_type_azure_opened.svg"},"_fd_azurepipelines":{"iconPath":"../../icons/folder_type_azurepipelines.svg"},"_fd_azurepipelines_open":{"iconPath":"../../icons/folder_type_azurepipelines_opened.svg"},"_fd_binary":{"iconPath":"../../icons/folder_type_binary.svg"},"_fd_binary_open":{"iconPath":"../../icons/folder_type_binary_opened.svg"},"_fd_bloc":{"iconPath":"../../icons/folder_type_bloc.svg"},"_fd_bloc_open":{"iconPath":"../../icons/folder_type_bloc_opened.svg"},"_fd_blueprint":{"iconPath":"../../icons/folder_type_blueprint.svg"},"_fd_blueprint_open":{"iconPath":"../../icons/folder_type_blueprint_opened.svg"},"_fd_bot":{"iconPath":"../../icons/folder_type_bot.svg"},"_fd_bot_open":{"iconPath":"../../icons/folder_type_bot_opened.svg"},"_fd_bower":{"iconPath":"../../icons/folder_type_bower.svg"},"_fd_bower_open":{"iconPath":"../../icons/folder_type_bower_opened.svg"},"_fd_buildkite":{"iconPath":"../../icons/folder_type_buildkite.svg"},"_fd_buildkite_open":{"iconPath":"../../icons/folder_type_buildkite_opened.svg"},"_fd_cake":{"iconPath":"../../icons/folder_type_cake.svg"},"_fd_cake_open":{"iconPath":"../../icons/folder_type_cake_opened.svg"},"_fd_cargo":{"iconPath":"../../icons/folder_type_cargo.svg"},"_fd_cargo_open":{"iconPath":"../../icons/folder_type_cargo_opened.svg"},"_fd_certificate":{"iconPath":"../../icons/folder_type_certificate.svg"},"_fd_certificate_open":{"iconPath":"../../icons/folder_type_certificate_opened.svg"},"_fd_changesets":{"iconPath":"../../icons/folder_type_changesets.svg"},"_fd_changesets_open":{"iconPath":"../../icons/folder_type_changesets_opened.svg"},"_fd_chef":{"iconPath":"../../icons/folder_type_chef.svg"},"_fd_chef_open":{"iconPath":"../../icons/folder_type_chef_opened.svg"},"_fd_circleci":{"iconPath":"../../icons/folder_type_circleci.svg"},"_fd_circleci_open":{"iconPath":"../../icons/folder_type_circleci_opened.svg"},"_fd_claude":{"iconPath":"../../icons/folder_type_claude.svg"},"_fd_claude_open":{"iconPath":"../../icons/folder_type_claude_opened.svg"},"_fd_cli":{"iconPath":"../../icons/folder_type_cli.svg"},"_fd_cli_open":{"iconPath":"../../icons/folder_type_cli_opened.svg"},"_fd_client":{"iconPath":"../../icons/folder_type_client.svg"},"_fd_client_open":{"iconPath":"../../icons/folder_type_client_opened.svg"},"_fd_cloudflare":{"iconPath":"../../icons/folder_type_cloudflare.svg"},"_fd_cloudflare_open":{"iconPath":"../../icons/folder_type_cloudflare_opened.svg"},"_fd_cmake":{"iconPath":"../../icons/folder_type_cmake.svg"},"_fd_cmake_open":{"iconPath":"../../icons/folder_type_cmake_opened.svg"},"_fd_common":{"iconPath":"../../icons/folder_type_common.svg"},"_fd_common_open":{"iconPath":"../../icons/folder_type_common_opened.svg"},"_fd_component":{"iconPath":"../../icons/folder_type_component.svg"},"_fd_component_open":{"iconPath":"../../icons/folder_type_component_opened.svg"},"_fd_composer":{"iconPath":".Line truncated
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
import { assert, describe, it } from "vitest";
|
|
||||||
|
|
||||||
import { getVscodeIconUrlForEntry } from "./vscode-icons";
|
|
||||||
|
|
||||||
describe("getVscodeIconUrlForEntry", () => {
|
|
||||||
it("uses exact filename matches from the vscode-icons manifest", () => {
|
|
||||||
const darkUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "dark");
|
|
||||||
const lightUrl = getVscodeIconUrlForEntry("pnpm-workspace.yaml", "file", "light");
|
|
||||||
|
|
||||||
assert.isTrue(darkUrl.endsWith("/file_type_pnpm.svg"));
|
|
||||||
assert.isTrue(lightUrl.endsWith("/file_type_light_pnpm.svg"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses longest extension match for compound extensions", () => {
|
|
||||||
const iconUrl = getVscodeIconUrlForEntry("tsconfig.tsbuildinfo", "file", "dark");
|
|
||||||
const manifestStyleUrl = getVscodeIconUrlForEntry("buf.yaml", "file", "dark");
|
|
||||||
assert.isTrue(iconUrl.endsWith("/file_type_tsbuildinfo.svg"));
|
|
||||||
assert.isTrue(manifestStyleUrl.endsWith("/file_type_buf.svg"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("uses folder mappings and light-aware filename mappings", () => {
|
|
||||||
const folderUrl = getVscodeIconUrlForEntry("packages/src", "directory", "light");
|
|
||||||
const fileUrl = getVscodeIconUrlForEntry("AGENTS.md", "file", "light");
|
|
||||||
|
|
||||||
assert.isTrue(folderUrl.endsWith("/folder_type_src.svg"));
|
|
||||||
assert.isTrue(fileUrl.endsWith("/file_type_light_agents.svg"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to language-based mappings for path-only cases", () => {
|
|
||||||
const tsxUrl = getVscodeIconUrlForEntry("checkbox.tsx", "file", "light");
|
|
||||||
const dockerfileUrl = getVscodeIconUrlForEntry("Dockerfile", "file", "dark");
|
|
||||||
const shellUrl = getVscodeIconUrlForEntry("entrypoint.sh", "file", "dark");
|
|
||||||
const cursorRulesUrl = getVscodeIconUrlForEntry("general.mdc", "file", "dark");
|
|
||||||
const githubWorkflowUrl = getVscodeIconUrlForEntry(".github/workflows/ci.yml", "file", "light");
|
|
||||||
|
|
||||||
assert.isTrue(tsxUrl.endsWith("/file_type_reactts.svg"));
|
|
||||||
assert.isTrue(dockerfileUrl.endsWith("/file_type_docker.svg"));
|
|
||||||
assert.isTrue(shellUrl.endsWith("/file_type_shell.svg"));
|
|
||||||
assert.isTrue(cursorRulesUrl.endsWith("/file_type_markdown.svg"));
|
|
||||||
assert.isTrue(githubWorkflowUrl.endsWith("/file_type_light_yaml.svg"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("falls back to defaults when there is no match", () => {
|
|
||||||
const fileUrl = getVscodeIconUrlForEntry("foo.unknown-ext", "file", "dark");
|
|
||||||
const folderUrl = getVscodeIconUrlForEntry("totally-unknown-folder", "directory", "dark");
|
|
||||||
|
|
||||||
assert.isTrue(fileUrl.endsWith("/default_file.svg"));
|
|
||||||
assert.isTrue(folderUrl.endsWith("/default_folder.svg"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
import vscodeIconsManifest from "./vscode-icons-manifest.json";
|
|
||||||
import languageAssociationsData from "./vscode-icons-language-associations.json";
|
|
||||||
|
|
||||||
const VSCODE_ICONS_VERSION = "v12.17.0";
|
|
||||||
const VSCODE_ICONS_BASE_URL = `https://cdn.jsdelivr.net/gh/vscode-icons/vscode-icons@${VSCODE_ICONS_VERSION}/icons`;
|
|
||||||
|
|
||||||
interface IconDefinition {
|
|
||||||
iconPath: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IconLookupSection {
|
|
||||||
file?: string;
|
|
||||||
folder?: string;
|
|
||||||
fileNames: Record<string, string>;
|
|
||||||
fileExtensions: Record<string, string>;
|
|
||||||
folderNames: Record<string, string>;
|
|
||||||
languageIds?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface VscodeIconsManifest extends IconLookupSection {
|
|
||||||
iconDefinitions: Record<string, IconDefinition>;
|
|
||||||
light: IconLookupSection;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface LanguageAssociations {
|
|
||||||
version: string;
|
|
||||||
extensionToLanguageId: Record<string, string>;
|
|
||||||
fileNameToLanguageId: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
const manifest = vscodeIconsManifest as VscodeIconsManifest;
|
|
||||||
const languageAssociations = languageAssociationsData as LanguageAssociations;
|
|
||||||
const iconDefinitions = manifest.iconDefinitions;
|
|
||||||
|
|
||||||
const darkFileNames = toLowercaseLookup(manifest.fileNames);
|
|
||||||
const lightFileNames = toLowercaseLookup(manifest.light.fileNames);
|
|
||||||
const darkFileExtensions = toLowercaseLookup(manifest.fileExtensions);
|
|
||||||
const lightFileExtensions = toLowercaseLookup(manifest.light.fileExtensions);
|
|
||||||
const darkFolderNames = toLowercaseLookup(manifest.folderNames);
|
|
||||||
const lightFolderNames = toLowercaseLookup(manifest.light.folderNames);
|
|
||||||
const darkLanguageIds = toLowercaseLookup(manifest.languageIds ?? {});
|
|
||||||
const lightLanguageIds = toLowercaseLookup(manifest.light.languageIds ?? {});
|
|
||||||
const languageIdByExtension = toLowercaseLookup(languageAssociations.extensionToLanguageId);
|
|
||||||
const languageIdByFileName = toLowercaseLookup(languageAssociations.fileNameToLanguageId);
|
|
||||||
const localLanguageIdByExtensionOverrides = {
|
|
||||||
// Cursor rules files (*.mdc) are commonly treated as markdown in VSCode/Cursor.
|
|
||||||
mdc: "markdown",
|
|
||||||
// Upstream languages.ts maps yml/yaml to specialized language ids that can produce
|
|
||||||
// non-generic YAML icons (for example cloudfoundry/esphome). Prefer the base YAML icon
|
|
||||||
// unless a more specific basename/extension match (e.g. azure-pipelines.yml) is found.
|
|
||||||
yml: "yaml",
|
|
||||||
yaml: "yaml",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const defaultDarkFileIconDefinition = manifest.file ?? "_file";
|
|
||||||
const defaultLightFileIconDefinition = manifest.light.file ?? defaultDarkFileIconDefinition;
|
|
||||||
const defaultDarkFolderIconDefinition = manifest.folder ?? "_folder";
|
|
||||||
const defaultLightFolderIconDefinition = manifest.light.folder ?? defaultDarkFolderIconDefinition;
|
|
||||||
|
|
||||||
function toLowercaseLookup(source: Record<string, string>): Record<string, string> {
|
|
||||||
const entries = Object.entries(source);
|
|
||||||
const lookup: Record<string, string> = {};
|
|
||||||
for (const [key, value] of entries) {
|
|
||||||
lookup[key.toLowerCase()] = value;
|
|
||||||
}
|
|
||||||
return lookup;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function basenameOfPath(pathValue: string): string {
|
|
||||||
const slashIndex = pathValue.lastIndexOf("/");
|
|
||||||
if (slashIndex === -1) return pathValue;
|
|
||||||
return pathValue.slice(slashIndex + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function extensionCandidates(fileName: string): string[] {
|
|
||||||
const candidates = new Set<string>();
|
|
||||||
if (fileName.includes(".")) {
|
|
||||||
candidates.add(fileName);
|
|
||||||
}
|
|
||||||
let dotIndex = fileName.indexOf(".");
|
|
||||||
while (dotIndex !== -1 && dotIndex < fileName.length - 1) {
|
|
||||||
const candidate = fileName.slice(dotIndex + 1);
|
|
||||||
if (candidate.length > 0) {
|
|
||||||
candidates.add(candidate);
|
|
||||||
}
|
|
||||||
dotIndex = fileName.indexOf(".", dotIndex + 1);
|
|
||||||
}
|
|
||||||
return [...candidates];
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveLanguageFallbackDefinition(
|
|
||||||
pathValue: string,
|
|
||||||
theme: "light" | "dark",
|
|
||||||
): string | null {
|
|
||||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
|
||||||
const languageIds = theme === "light" ? lightLanguageIds : darkLanguageIds;
|
|
||||||
|
|
||||||
const fromBasenameLanguage = languageIdByFileName[basename];
|
|
||||||
if (fromBasenameLanguage) {
|
|
||||||
return languageIds[fromBasenameLanguage] ?? darkLanguageIds[fromBasenameLanguage] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const candidate of extensionCandidates(basename)) {
|
|
||||||
const languageId =
|
|
||||||
localLanguageIdByExtensionOverrides[
|
|
||||||
candidate as keyof typeof localLanguageIdByExtensionOverrides
|
|
||||||
] ?? languageIdByExtension[candidate];
|
|
||||||
if (!languageId) continue;
|
|
||||||
return languageIds[languageId] ?? darkLanguageIds[languageId] ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function iconFilenameForDefinitionKey(definitionKey: string | undefined): string | null {
|
|
||||||
if (!definitionKey) return null;
|
|
||||||
const iconPath = iconDefinitions[definitionKey]?.iconPath;
|
|
||||||
if (!iconPath) return null;
|
|
||||||
const slashIndex = iconPath.lastIndexOf("/");
|
|
||||||
if (slashIndex === -1) {
|
|
||||||
return iconPath;
|
|
||||||
}
|
|
||||||
return iconPath.slice(slashIndex + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveFileDefinition(pathValue: string, theme: "light" | "dark"): string {
|
|
||||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
|
||||||
const fileNames = theme === "light" ? lightFileNames : darkFileNames;
|
|
||||||
const fileExtensions = theme === "light" ? lightFileExtensions : darkFileExtensions;
|
|
||||||
|
|
||||||
const fromFileName = fileNames[basename] ?? darkFileNames[basename];
|
|
||||||
if (fromFileName) return fromFileName;
|
|
||||||
|
|
||||||
for (const candidate of extensionCandidates(basename)) {
|
|
||||||
const fromExtension = fileExtensions[candidate] ?? darkFileExtensions[candidate];
|
|
||||||
if (fromExtension) return fromExtension;
|
|
||||||
}
|
|
||||||
|
|
||||||
const fromLanguage = resolveLanguageFallbackDefinition(pathValue, theme);
|
|
||||||
if (fromLanguage) return fromLanguage;
|
|
||||||
|
|
||||||
return theme === "light" ? defaultLightFileIconDefinition : defaultDarkFileIconDefinition;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveFolderDefinition(pathValue: string, theme: "light" | "dark"): string {
|
|
||||||
const basename = basenameOfPath(pathValue).toLowerCase();
|
|
||||||
const folderNames = theme === "light" ? lightFolderNames : darkFolderNames;
|
|
||||||
return (
|
|
||||||
folderNames[basename] ??
|
|
||||||
darkFolderNames[basename] ??
|
|
||||||
(theme === "light" ? defaultLightFolderIconDefinition : defaultDarkFolderIconDefinition)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getVscodeIconUrlForEntry(
|
|
||||||
pathValue: string,
|
|
||||||
kind: "file" | "directory",
|
|
||||||
theme: "light" | "dark",
|
|
||||||
): string {
|
|
||||||
const definitionKey =
|
|
||||||
kind === "directory"
|
|
||||||
? resolveFolderDefinition(pathValue, theme)
|
|
||||||
: resolveFileDefinition(pathValue, theme);
|
|
||||||
const iconFilename =
|
|
||||||
iconFilenameForDefinitionKey(definitionKey) ??
|
|
||||||
(kind === "directory" ? "default_folder.svg" : "default_file.svg");
|
|
||||||
return `${VSCODE_ICONS_BASE_URL}/${iconFilename}`;
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
import "@pierre/diffs/worker/worker.js";
|
|
||||||
@@ -25,7 +25,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
|||||||
session: null,
|
session: null,
|
||||||
messages: [],
|
messages: [],
|
||||||
events: [],
|
events: [],
|
||||||
turnDiffSummaries: [],
|
|
||||||
error: null,
|
error: null,
|
||||||
createdAt: "2026-02-13T00:00:00.000Z",
|
createdAt: "2026-02-13T00:00:00.000Z",
|
||||||
branch: null,
|
branch: null,
|
||||||
|
|||||||
@@ -91,10 +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),
|
|
||||||
getCheckpointDiff: (input) => transport.request(WS_METHODS.providersGetCheckpointDiff, 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),
|
||||||
},
|
},
|
||||||
@@ -102,8 +98,6 @@ export function createWsNativeApi(): NativeApi {
|
|||||||
list: () => transport.request(WS_METHODS.projectsList),
|
list: () => transport.request(WS_METHODS.projectsList),
|
||||||
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
|
||||||
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
|
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
|
||||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
|
||||||
updateScripts: (input) => transport.request(WS_METHODS.projectsUpdateScripts, input),
|
|
||||||
},
|
},
|
||||||
shell: {
|
shell: {
|
||||||
openInEditor: (cwd, editor) =>
|
openInEditor: (cwd, editor) =>
|
||||||
@@ -145,10 +139,6 @@ export function createWsNativeApi(): NativeApi {
|
|||||||
return showContextMenuFallback(items, position);
|
return showContextMenuFallback(items, position);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
server: {
|
|
||||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
|
||||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
instance = { api, transport };
|
instance = { api, transport };
|
||||||
|
|||||||
@@ -37,9 +37,6 @@ export class WsTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
async request<T = unknown>(method: string, params?: unknown): Promise<T> {
|
||||||
if (typeof method !== "string" || method.length === 0) {
|
|
||||||
throw new Error("Request method is required");
|
|
||||||
}
|
|
||||||
const id = String(this.nextId++);
|
const id = String(this.nextId++);
|
||||||
const message: WsRequest = { id, method, ...(params !== undefined ? { params } : {}) };
|
const message: WsRequest = { id, method, ...(params !== undefined ? { params } : {}) };
|
||||||
|
|
||||||
|
|||||||
@@ -52,9 +52,7 @@
|
|||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.2.0",
|
"@base-ui/react": "^1.2.0",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
"@tanstack/react-pacer": "^0.19.4",
|
|
||||||
"@tanstack/react-query": "^5.90.0",
|
"@tanstack/react-query": "^5.90.0",
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
@@ -305,8 +303,6 @@
|
|||||||
|
|
||||||
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DJbQsSJUr4KSi9uU0QqOgI7PX2C+fKGZX+YDprt3vM2sC0dWZsgVTLoN2vtkNyEWJSY2mnvRFUshWXT3bmo0Ug=="],
|
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-DJbQsSJUr4KSi9uU0QqOgI7PX2C+fKGZX+YDprt3vM2sC0dWZsgVTLoN2vtkNyEWJSY2mnvRFUshWXT3bmo0Ug=="],
|
||||||
|
|
||||||
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
|
|
||||||
|
|
||||||
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
|
||||||
|
|
||||||
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
|
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
|
||||||
@@ -387,22 +383,6 @@
|
|||||||
|
|
||||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="],
|
"@rollup/rollup-win32-x64-msvc": ["@rollup/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA=="],
|
||||||
|
|
||||||
"@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4", "hast-util-to-html": "^9.0.5" } }, "sha512-iAlTtSDDbJiRpvgL5ugKEATDtHdUVkqgHDm/gbD2ZS9c88mx7G1zSYjjOxp5Qa0eaW0MAQosFRmJSk354PRoQA=="],
|
|
||||||
|
|
||||||
"@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.4" } }, "sha512-jdKhfgW9CRtj3Tor0L7+yPwdG3CgP7W+ZEqSsojrMzCjD1e0IxIbwUMDDpYlVBlC08TACg4puwFGkZfLS+56Tw=="],
|
|
||||||
|
|
||||||
"@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-DyXsOG0vGtNtl7ygvabHd7Mt5EY8gCNqR9Y7Lpbbd/PbJvgWrqaKzH1JW6H6qFkuUa8aCxoiYVv8/YfFljiQxA=="],
|
|
||||||
|
|
||||||
"@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-x/42TfhWmp6H00T6uwVrdTJGKgNdFbrEdhaDwSR5fd5zhQ1Q46bHq9EO61SCEWJR0HY7z2HNDMaBZp8JRmKiIA=="],
|
|
||||||
|
|
||||||
"@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "3.22.0" } }, "sha512-o+tlOKqsr6FE4+mYJG08tfCFDS+3CG20HbldXeVoyP+cYSUxDhrFf3GPjE60U55iOkkjbpY2uC3It/eeja35/g=="],
|
|
||||||
|
|
||||||
"@shikijs/transformers": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/types": "3.22.0" } }, "sha512-E7eRV7mwDBjueLF6852n2oYeJYxBq3NSsDk+uyruYAXONv4U8holGmIrT+mPRJQ1J1SNOH6L8G19KRzmBawrFw=="],
|
|
||||||
|
|
||||||
"@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-491iAekgKDBFE67z70Ok5a8KBMsQ2IJwOWw3us/7ffQkIBCyOQfm/aNwVMBUriP02QshIfgHCBSIYAl3u2eWjg=="],
|
|
||||||
|
|
||||||
"@shikijs/vscode-textmate": ["@shikijs/[email protected]", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
|
|
||||||
|
|
||||||
"@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
|
"@sindresorhus/is": ["@sindresorhus/[email protected]", "", {}, "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw=="],
|
||||||
|
|
||||||
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
"@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||||
@@ -445,20 +425,10 @@
|
|||||||
|
|
||||||
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.1.18", "@tailwindcss/oxide": "4.1.18", "tailwindcss": "4.1.18" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA=="],
|
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.1.18", "@tailwindcss/oxide": "4.1.18", "tailwindcss": "4.1.18" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7" } }, "sha512-jVA+/UpKL1vRLg6Hkao5jldawNmRo7mQYrZtNHMIVpLfLhDml5nMRUo/8MwoX2vNXvnaXNNMedrMfMugAVX1nA=="],
|
||||||
|
|
||||||
"@tanstack/devtools-event-client": ["@tanstack/[email protected]", "", {}, "sha512-RPfGuk2bDZgcu9bAJodvO2lnZeHuz4/71HjZ0bGb/SPg8+lyTA+RLSKQvo7fSmPSi8/vcH3aKQ8EM9ywf1olaw=="],
|
|
||||||
|
|
||||||
"@tanstack/pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/devtools-event-client": "^0.4.0", "@tanstack/store": "^0.8.0" } }, "sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg=="],
|
|
||||||
|
|
||||||
"@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg=="],
|
"@tanstack/query-core": ["@tanstack/[email protected]", "", {}, "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg=="],
|
||||||
|
|
||||||
"@tanstack/react-pacer": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/pacer": "0.18.0", "@tanstack/react-store": "^0.8.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-coj8ULAuR0qFpjAKD44gTgRuZyjxU6Xu+IX5MwwYvr4e61OtZcJshaExoOBKpCGde0Edb12jDnzzj2Im13Qm9Q=="],
|
|
||||||
|
|
||||||
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
|
"@tanstack/react-query": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/query-core": "5.90.20" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg=="],
|
||||||
|
|
||||||
"@tanstack/react-store": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/store": "0.8.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-XItJt+rG8c5Wn/2L/bnxys85rBpm0BfMbhb4zmPVLXAKY9POrp1xd6IbU4PKoOI+jSEGc3vntPRfLGSgXfE2Ig=="],
|
|
||||||
|
|
||||||
"@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-PtOisLjUZPz5VyPRSCGjNOlwTvabdTBQ2K80DpVL1chGVr35WRxfeavAPdNq6pm/t7F8GhoR2qtmkkqtCEtHYw=="],
|
|
||||||
|
|
||||||
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
|
||||||
|
|
||||||
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
"@types/babel__core": ["@types/[email protected]", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
||||||
@@ -641,8 +611,6 @@
|
|||||||
|
|
||||||
"devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
|
"devlop": ["[email protected]", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
|
||||||
|
|
||||||
"diff": ["[email protected]", "", {}, "sha512-qejHi7bcSD4hQAZE0tNAawRK1ZtafHDmMTMkrrIGgSLl7hTnQHmKCeB45xAcbfTqK2zowkM3j3bHt/4b/ARbYQ=="],
|
|
||||||
|
|
||||||
"dts-resolver": ["[email protected]", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="],
|
"dts-resolver": ["[email protected]", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="],
|
||||||
|
|
||||||
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
|
||||||
@@ -743,8 +711,6 @@
|
|||||||
|
|
||||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||||
|
|
||||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
|
||||||
|
|
||||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||||
|
|
||||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||||
@@ -759,8 +725,6 @@
|
|||||||
|
|
||||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||||
|
|
||||||
"html-void-elements": ["[email protected]", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="],
|
|
||||||
|
|
||||||
"http-cache-semantics": ["[email protected]", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
|
"http-cache-semantics": ["[email protected]", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
|
||||||
|
|
||||||
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
"http2-wrapper": ["[email protected]", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
|
||||||
@@ -847,8 +811,6 @@
|
|||||||
|
|
||||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||||
|
|
||||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
|
||||||
|
|
||||||
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-JJ8GVTQqFwuliifD48U6+h7DXEHdkhJ/E87kksGByII3qHxtPciVb8T8woQONHBQgHVOl7rSMrrip3SeVNy7Fg=="],
|
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-JJ8GVTQqFwuliifD48U6+h7DXEHdkhJ/E87kksGByII3qHxtPciVb8T8woQONHBQgHVOl7rSMrrip3SeVNy7Fg=="],
|
||||||
|
|
||||||
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||||
@@ -979,10 +941,6 @@
|
|||||||
|
|
||||||
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
"once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
|
||||||
|
|
||||||
"oniguruma-parser": ["[email protected]", "", {}, "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w=="],
|
|
||||||
|
|
||||||
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.0.1", "regex-recursion": "^6.0.2" } }, "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA=="],
|
|
||||||
|
|
||||||
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
|
||||||
|
|
||||||
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
|
||||||
@@ -1029,12 +987,6 @@
|
|||||||
|
|
||||||
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
|
||||||
|
|
||||||
"regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
|
|
||||||
|
|
||||||
"regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
|
|
||||||
|
|
||||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
|
||||||
|
|
||||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||||
|
|
||||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||||
@@ -1083,8 +1035,6 @@
|
|||||||
|
|
||||||
"serialize-error": ["[email protected]", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
|
"serialize-error": ["[email protected]", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
|
||||||
|
|
||||||
"shiki": ["[email protected]", "", { "dependencies": { "@shikijs/core": "3.22.0", "@shikijs/engine-javascript": "3.22.0", "@shikijs/engine-oniguruma": "3.22.0", "@shikijs/langs": "3.22.0", "@shikijs/themes": "3.22.0", "@shikijs/types": "3.22.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-LBnhsoYEe0Eou4e1VgJACes+O6S6QC0w71fCSp5Oya79inkwkm15gQ1UF6VtQ8j/taMDh79hAB49WUk8ALQW3g=="],
|
|
||||||
|
|
||||||
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||||
|
|
||||||
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||||
|
|||||||
+1
-3
@@ -19,9 +19,7 @@
|
|||||||
"test": "turbo run test",
|
"test": "turbo run test",
|
||||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||||
"fmt": "oxfmt",
|
"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",
|
|
||||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"oxfmt": "^0.28.0",
|
"oxfmt": "^0.28.0",
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"exports": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"types": "./src/index.ts",
|
"types": "./src/index.ts",
|
||||||
"import": "./src/index.ts",
|
"import": "./dist/index.mjs",
|
||||||
"require": "./dist/index.cjs"
|
"require": "./dist/index.cjs"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -5,7 +5,5 @@ export * from "./terminal";
|
|||||||
export * from "./provider";
|
export * from "./provider";
|
||||||
export * from "./model";
|
export * from "./model";
|
||||||
export * from "./ws";
|
export * from "./ws";
|
||||||
export * from "./keybindings";
|
|
||||||
export * from "./server";
|
|
||||||
export * from "./project";
|
export * from "./project";
|
||||||
export * from "./git";
|
export * from "./git";
|
||||||
@@ -17,13 +17,7 @@ import type {
|
|||||||
} from "./git";
|
} from "./git";
|
||||||
import type {
|
import type {
|
||||||
ProviderEvent,
|
ProviderEvent,
|
||||||
ProviderGetCheckpointDiffInput,
|
|
||||||
ProviderGetCheckpointDiffResult,
|
|
||||||
ProviderInterruptTurnInput,
|
ProviderInterruptTurnInput,
|
||||||
ProviderListCheckpointsInput,
|
|
||||||
ProviderListCheckpointsResult,
|
|
||||||
ProviderRevertToCheckpointInput,
|
|
||||||
ProviderRevertToCheckpointResult,
|
|
||||||
ProviderRespondToRequestInput,
|
ProviderRespondToRequestInput,
|
||||||
ProviderSendTurnInput,
|
ProviderSendTurnInput,
|
||||||
ProviderSession,
|
ProviderSession,
|
||||||
@@ -35,13 +29,8 @@ import type {
|
|||||||
ProjectAddInput,
|
ProjectAddInput,
|
||||||
ProjectAddResult,
|
ProjectAddResult,
|
||||||
ProjectListResult,
|
ProjectListResult,
|
||||||
ProjectSearchEntriesInput,
|
|
||||||
ProjectSearchEntriesResult,
|
|
||||||
ProjectRemoveInput,
|
ProjectRemoveInput,
|
||||||
ProjectUpdateScriptsInput,
|
|
||||||
ProjectUpdateScriptsResult,
|
|
||||||
} from "./project";
|
} from "./project";
|
||||||
import type { ServerConfig } from "./server";
|
|
||||||
import type {
|
import type {
|
||||||
TerminalClearInput,
|
TerminalClearInput,
|
||||||
TerminalCloseInput,
|
TerminalCloseInput,
|
||||||
@@ -52,7 +41,6 @@ import type {
|
|||||||
TerminalWriteInput,
|
TerminalWriteInput,
|
||||||
} from "./terminal";
|
} from "./terminal";
|
||||||
import type { NewTodoInput, Todo } from "./todo";
|
import type { NewTodoInput, Todo } from "./todo";
|
||||||
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
|
|
||||||
|
|
||||||
export const EDITORS = [
|
export const EDITORS = [
|
||||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||||
@@ -95,23 +83,12 @@ 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>;
|
|
||||||
getCheckpointDiff: (
|
|
||||||
input: ProviderGetCheckpointDiffInput,
|
|
||||||
) => Promise<ProviderGetCheckpointDiffResult>;
|
|
||||||
revertToCheckpoint: (
|
|
||||||
input: ProviderRevertToCheckpointInput,
|
|
||||||
) => Promise<ProviderRevertToCheckpointResult>;
|
|
||||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||||
};
|
};
|
||||||
projects: {
|
projects: {
|
||||||
list: () => Promise<ProjectListResult>;
|
list: () => Promise<ProjectListResult>;
|
||||||
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
|
||||||
remove: (input: ProjectRemoveInput) => Promise<void>;
|
remove: (input: ProjectRemoveInput) => Promise<void>;
|
||||||
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
|
|
||||||
updateScripts: (input: ProjectUpdateScriptsInput) => Promise<ProjectUpdateScriptsResult>;
|
|
||||||
};
|
};
|
||||||
shell: {
|
shell: {
|
||||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||||
@@ -136,8 +113,4 @@ export interface NativeApi {
|
|||||||
position?: { x: number; y: number },
|
position?: { x: number; y: number },
|
||||||
) => Promise<T | null>;
|
) => Promise<T | null>;
|
||||||
};
|
};
|
||||||
server: {
|
|
||||||
getConfig: () => Promise<ServerConfig>;
|
|
||||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
import { assert, describe, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
keybindingRuleSchema,
|
|
||||||
keybindingsConfigSchema,
|
|
||||||
resolvedKeybindingRuleSchema,
|
|
||||||
resolvedKeybindingsConfigSchema,
|
|
||||||
} from "./keybindings";
|
|
||||||
|
|
||||||
describe("keybindings contracts", () => {
|
|
||||||
it("parses keybinding rules", () => {
|
|
||||||
const parsed = keybindingRuleSchema.parse({
|
|
||||||
key: "mod+j",
|
|
||||||
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", () => {
|
|
||||||
assert.throws(() =>
|
|
||||||
keybindingRuleSchema.parse({
|
|
||||||
key: "mod+j",
|
|
||||||
command: "script.Test.run",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("accepts dynamic script run commands", () => {
|
|
||||||
const parsed = keybindingRuleSchema.parse({
|
|
||||||
key: "mod+r",
|
|
||||||
command: "script.setup.run",
|
|
||||||
});
|
|
||||||
assert.strictEqual(parsed.command, "script.setup.run");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses keybindings array payload", () => {
|
|
||||||
const parsed = keybindingsConfigSchema.parse([
|
|
||||||
{ key: "mod+j", command: "terminal.toggle" },
|
|
||||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
|
||||||
]);
|
|
||||||
assert.lengthOf(parsed, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses resolved keybinding rules", () => {
|
|
||||||
const parsed = resolvedKeybindingRuleSchema.parse({
|
|
||||||
command: "terminal.split",
|
|
||||||
shortcut: {
|
|
||||||
key: "d",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
},
|
|
||||||
whenAst: {
|
|
||||||
type: "and",
|
|
||||||
left: { type: "identifier", name: "terminalOpen" },
|
|
||||||
right: {
|
|
||||||
type: "not",
|
|
||||||
node: { type: "identifier", name: "terminalFocus" },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
assert.strictEqual(parsed.shortcut.key, "d");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses resolved keybindings arrays", () => {
|
|
||||||
const parsed = resolvedKeybindingsConfigSchema.parse([
|
|
||||||
{
|
|
||||||
command: "terminal.toggle",
|
|
||||||
shortcut: {
|
|
||||||
key: "j",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
assert.lengthOf(parsed, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects unknown fields in resolved keybinding rules", () => {
|
|
||||||
assert.throws(() =>
|
|
||||||
resolvedKeybindingRuleSchema.parse({
|
|
||||||
command: "terminal.toggle",
|
|
||||||
shortcut: {
|
|
||||||
key: "j",
|
|
||||||
metaKey: false,
|
|
||||||
ctrlKey: false,
|
|
||||||
shiftKey: false,
|
|
||||||
altKey: false,
|
|
||||||
modKey: true,
|
|
||||||
},
|
|
||||||
key: "mod+j",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
|
|
||||||
export const STATIC_KEYBINDING_COMMANDS = [
|
|
||||||
"terminal.toggle",
|
|
||||||
"terminal.split",
|
|
||||||
"terminal.new",
|
|
||||||
"terminal.close",
|
|
||||||
"chat.new",
|
|
||||||
"chat.newLocal",
|
|
||||||
"editor.openFavorite",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export const keybindingCommandSchema = z.union([
|
|
||||||
z.enum(STATIC_KEYBINDING_COMMANDS),
|
|
||||||
z
|
|
||||||
.string()
|
|
||||||
.trim()
|
|
||||||
.min(1)
|
|
||||||
.max(96)
|
|
||||||
.regex(/^script\.[a-z0-9][a-z0-9-]*\.run$/),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const keybindingValueSchema = z.string().trim().min(1).max(64);
|
|
||||||
const keybindingWhenSchema = z.string().trim().min(1).max(256);
|
|
||||||
|
|
||||||
export const keybindingRuleSchema = z.object({
|
|
||||||
key: keybindingValueSchema,
|
|
||||||
command: keybindingCommandSchema,
|
|
||||||
when: keybindingWhenSchema.optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const keybindingsConfigSchema = z.array(keybindingRuleSchema).max(256);
|
|
||||||
|
|
||||||
export const keybindingShortcutSchema = z
|
|
||||||
.object({
|
|
||||||
key: z.string().trim().min(1).max(32),
|
|
||||||
metaKey: z.boolean(),
|
|
||||||
ctrlKey: z.boolean(),
|
|
||||||
shiftKey: z.boolean(),
|
|
||||||
altKey: z.boolean(),
|
|
||||||
modKey: z.boolean(),
|
|
||||||
})
|
|
||||||
.strict();
|
|
||||||
|
|
||||||
export type KeybindingWhenNode =
|
|
||||||
| { type: "identifier"; name: string }
|
|
||||||
| { type: "not"; node: KeybindingWhenNode }
|
|
||||||
| { type: "and"; left: KeybindingWhenNode; right: KeybindingWhenNode }
|
|
||||||
| { type: "or"; left: KeybindingWhenNode; right: KeybindingWhenNode };
|
|
||||||
|
|
||||||
export const keybindingWhenNodeSchema: z.ZodType<KeybindingWhenNode> = z.lazy(() =>
|
|
||||||
z.union([
|
|
||||||
z.object({
|
|
||||||
type: z.literal("identifier"),
|
|
||||||
name: z.string().min(1),
|
|
||||||
}),
|
|
||||||
z.object({
|
|
||||||
type: z.literal("not"),
|
|
||||||
node: keybindingWhenNodeSchema,
|
|
||||||
}),
|
|
||||||
z.object({
|
|
||||||
type: z.literal("and"),
|
|
||||||
left: keybindingWhenNodeSchema,
|
|
||||||
right: keybindingWhenNodeSchema,
|
|
||||||
}),
|
|
||||||
z.object({
|
|
||||||
type: z.literal("or"),
|
|
||||||
left: keybindingWhenNodeSchema,
|
|
||||||
right: keybindingWhenNodeSchema,
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
export const resolvedKeybindingRuleSchema = z
|
|
||||||
.object({
|
|
||||||
command: keybindingCommandSchema,
|
|
||||||
shortcut: keybindingShortcutSchema,
|
|
||||||
whenAst: keybindingWhenNodeSchema.optional(),
|
|
||||||
})
|
|
||||||
.strict();
|
|
||||||
|
|
||||||
export const resolvedKeybindingsConfigSchema = z.array(resolvedKeybindingRuleSchema).max(256);
|
|
||||||
|
|
||||||
export type KeybindingCommand = z.infer<typeof keybindingCommandSchema>;
|
|
||||||
export type KeybindingRule = z.infer<typeof keybindingRuleSchema>;
|
|
||||||
export type KeybindingsConfig = z.infer<typeof keybindingsConfigSchema>;
|
|
||||||
export type KeybindingShortcut = z.infer<typeof keybindingShortcutSchema>;
|
|
||||||
export type ResolvedKeybindingRule = z.infer<typeof resolvedKeybindingRuleSchema>;
|
|
||||||
export type ResolvedKeybindingsConfig = z.infer<typeof resolvedKeybindingsConfigSchema>;
|
|
||||||
@@ -3,12 +3,8 @@ import { describe, expect, it } from "vitest";
|
|||||||
import {
|
import {
|
||||||
projectAddInputSchema,
|
projectAddInputSchema,
|
||||||
projectAddResultSchema,
|
projectAddResultSchema,
|
||||||
projectSearchEntriesInputSchema,
|
|
||||||
projectSearchEntriesResultSchema,
|
|
||||||
projectListResultSchema,
|
projectListResultSchema,
|
||||||
projectRemoveInputSchema,
|
projectRemoveInputSchema,
|
||||||
projectUpdateScriptsInputSchema,
|
|
||||||
projectUpdateScriptsResultSchema,
|
|
||||||
} from "./project";
|
} from "./project";
|
||||||
|
|
||||||
describe("project contracts", () => {
|
describe("project contracts", () => {
|
||||||
@@ -18,7 +14,6 @@ describe("project contracts", () => {
|
|||||||
id: "project-1",
|
id: "project-1",
|
||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
name: "project",
|
name: "project",
|
||||||
scripts: [],
|
|
||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
@@ -39,7 +34,6 @@ describe("project contracts", () => {
|
|||||||
id: "project-1",
|
id: "project-1",
|
||||||
cwd: "/tmp/project",
|
cwd: "/tmp/project",
|
||||||
name: "project",
|
name: "project",
|
||||||
scripts: [],
|
|
||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
createdAt: "2026-02-10T00:00:00.000Z",
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||||
},
|
},
|
||||||
@@ -52,96 +46,4 @@ describe("project contracts", () => {
|
|||||||
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
const parsed = projectRemoveInputSchema.parse({ id: "project-1" });
|
||||||
expect(parsed.id).toBe("project-1");
|
expect(parsed.id).toBe("project-1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("parses workspace entry search input with defaults", () => {
|
|
||||||
const parsed = projectSearchEntriesInputSchema.parse({
|
|
||||||
cwd: " /tmp/project ",
|
|
||||||
query: " src ",
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(parsed).toEqual({
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
query: "src",
|
|
||||||
limit: 80,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses workspace entry search result", () => {
|
|
||||||
const parsed = projectSearchEntriesResultSchema.parse({
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
path: "src/components",
|
|
||||||
kind: "directory",
|
|
||||||
parentPath: "src",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: "src/components/Button.tsx",
|
|
||||||
kind: "file",
|
|
||||||
parentPath: "src/components",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
truncated: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(parsed.entries).toHaveLength(2);
|
|
||||||
expect(parsed.entries[0]?.kind).toBe("directory");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses update scripts input", () => {
|
|
||||||
const parsed = projectUpdateScriptsInputSchema.parse({
|
|
||||||
id: "project-1",
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "test",
|
|
||||||
name: "Test",
|
|
||||||
command: "bun test",
|
|
||||||
icon: "test",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(parsed.scripts).toHaveLength(1);
|
|
||||||
expect(parsed.scripts[0]?.id).toBe("test");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses debug icon in scripts", () => {
|
|
||||||
const parsed = projectUpdateScriptsInputSchema.parse({
|
|
||||||
id: "project-1",
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "debug",
|
|
||||||
name: "Debug",
|
|
||||||
command: "bun --inspect test",
|
|
||||||
icon: "debug",
|
|
||||||
runOnWorktreeCreate: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(parsed.scripts[0]?.icon).toBe("debug");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("parses update scripts result", () => {
|
|
||||||
const parsed = projectUpdateScriptsResultSchema.parse({
|
|
||||||
project: {
|
|
||||||
id: "project-1",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
name: "project",
|
|
||||||
scripts: [
|
|
||||||
{
|
|
||||||
id: "setup",
|
|
||||||
name: "Setup",
|
|
||||||
command: "bun install",
|
|
||||||
icon: "configure",
|
|
||||||
runOnWorktreeCreate: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
createdAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(parsed.project.scripts[0]?.id).toBe("setup");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -1,38 +1,9 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
export const PROJECT_SCRIPT_ICON_VALUES = [
|
|
||||||
"play",
|
|
||||||
"test",
|
|
||||||
"lint",
|
|
||||||
"configure",
|
|
||||||
"build",
|
|
||||||
"debug",
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export const projectScriptIconSchema = z.enum(PROJECT_SCRIPT_ICON_VALUES);
|
|
||||||
|
|
||||||
export const projectScriptSchema = z
|
|
||||||
.object({
|
|
||||||
id: z
|
|
||||||
.string()
|
|
||||||
.trim()
|
|
||||||
.min(1)
|
|
||||||
.max(64)
|
|
||||||
.regex(/^[a-z0-9][a-z0-9-]*$/),
|
|
||||||
name: z.string().trim().min(1).max(64),
|
|
||||||
command: z.string().trim().min(1).max(10_000),
|
|
||||||
icon: projectScriptIconSchema,
|
|
||||||
runOnWorktreeCreate: z.boolean().default(false),
|
|
||||||
})
|
|
||||||
.strict();
|
|
||||||
|
|
||||||
export const projectScriptsSchema = z.array(projectScriptSchema).max(64);
|
|
||||||
|
|
||||||
export const projectRecordSchema = z.object({
|
export const projectRecordSchema = z.object({
|
||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
cwd: z.string().min(1),
|
cwd: z.string().min(1),
|
||||||
name: z.string().min(1),
|
name: z.string().min(1),
|
||||||
scripts: projectScriptsSchema.default([]),
|
|
||||||
createdAt: z.string().datetime(),
|
createdAt: z.string().datetime(),
|
||||||
updatedAt: z.string().datetime(),
|
updatedAt: z.string().datetime(),
|
||||||
});
|
});
|
||||||
@@ -52,83 +23,8 @@ export const projectRemoveInputSchema = z.object({
|
|||||||
id: z.string().min(1),
|
id: z.string().min(1),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
|
|
||||||
|
|
||||||
export const projectSearchEntriesInputSchema = z.object({
|
|
||||||
cwd: z.string().trim().min(1),
|
|
||||||
query: z.string().trim().max(256).default(""),
|
|
||||||
limit: z.number().int().min(1).max(PROJECT_SEARCH_ENTRIES_MAX_LIMIT).default(80),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const projectEntryKindSchema = z.enum(["file", "directory"]);
|
|
||||||
|
|
||||||
export const projectEntrySchema = z.object({
|
|
||||||
path: z.string().min(1),
|
|
||||||
kind: projectEntryKindSchema,
|
|
||||||
parentPath: z.string().optional(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const projectSearchEntriesResultSchema = z.object({
|
|
||||||
entries: z.array(projectEntrySchema),
|
|
||||||
truncated: z.boolean(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const projectUpdateScriptsInputSchema = z.object({
|
|
||||||
id: z.string().min(1),
|
|
||||||
scripts: projectScriptsSchema,
|
|
||||||
});
|
|
||||||
|
|
||||||
export const projectUpdateScriptsResultSchema = z.object({
|
|
||||||
project: projectRecordSchema,
|
|
||||||
});
|
|
||||||
|
|
||||||
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
|
|
||||||
export type ProjectScript = z.infer<typeof projectScriptSchema>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Deduplicate scripts by ID and enforce at most one `runOnWorktreeCreate: true`
|
|
||||||
* flag (the first one wins). Fields are trimmed defensively so this is safe to
|
|
||||||
* call on data that hasn't been through Zod parsing.
|
|
||||||
*/
|
|
||||||
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
|
||||||
const seenIds = new Set<string>();
|
|
||||||
const deduped: ProjectScript[] = [];
|
|
||||||
for (const script of scripts) {
|
|
||||||
const id = script.id.trim();
|
|
||||||
if (id.length === 0 || seenIds.has(id)) continue;
|
|
||||||
seenIds.add(id);
|
|
||||||
deduped.push({
|
|
||||||
...script,
|
|
||||||
id,
|
|
||||||
name: script.name.trim(),
|
|
||||||
command: script.command.trim(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let setupAssigned = false;
|
|
||||||
const normalized: ProjectScript[] = [];
|
|
||||||
for (const script of deduped) {
|
|
||||||
if (!script.runOnWorktreeCreate) {
|
|
||||||
normalized.push(script);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!setupAssigned) {
|
|
||||||
setupAssigned = true;
|
|
||||||
normalized.push(script);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
normalized.push({ ...script, runOnWorktreeCreate: false });
|
|
||||||
}
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
|
||||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
|
||||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
|
||||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
|
||||||
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
|
|
||||||
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
|
|
||||||
@@ -2,14 +2,7 @@ import { describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||||
providerCheckpointSchema,
|
|
||||||
providerEventSchema,
|
providerEventSchema,
|
||||||
providerGetCheckpointDiffInputSchema,
|
|
||||||
providerGetCheckpointDiffResultSchema,
|
|
||||||
providerListCheckpointsInputSchema,
|
|
||||||
providerListCheckpointsResultSchema,
|
|
||||||
providerRevertToCheckpointInputSchema,
|
|
||||||
providerRevertToCheckpointResultSchema,
|
|
||||||
providerRespondToRequestInputSchema,
|
providerRespondToRequestInputSchema,
|
||||||
providerSendTurnInputSchema,
|
providerSendTurnInputSchema,
|
||||||
providerSessionStartInputSchema,
|
providerSessionStartInputSchema,
|
||||||
@@ -164,98 +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();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("accepts checkpoint diff input/result", () => {
|
|
||||||
const input = providerGetCheckpointDiffInputSchema.parse({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
});
|
|
||||||
expect(input.fromTurnCount).toBe(1);
|
|
||||||
|
|
||||||
const result = providerGetCheckpointDiffResultSchema.parse({
|
|
||||||
threadId: "thr_1",
|
|
||||||
fromTurnCount: 1,
|
|
||||||
toTurnCount: 2,
|
|
||||||
diff: "diff --git a/src/app.ts b/src/app.ts",
|
|
||||||
});
|
|
||||||
expect(result.toTurnCount).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects checkpoint diff ranges where start is after end", () => {
|
|
||||||
expect(() =>
|
|
||||||
providerGetCheckpointDiffInputSchema.parse({
|
|
||||||
sessionId: "sess_1",
|
|
||||||
fromTurnCount: 3,
|
|
||||||
toTurnCount: 2,
|
|
||||||
}),
|
|
||||||
).toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -111,60 +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 providerGetCheckpointDiffInputSchema = z
|
|
||||||
.object({
|
|
||||||
sessionId: z.string().min(1),
|
|
||||||
fromTurnCount: z.number().int().min(0),
|
|
||||||
toTurnCount: z.number().int().min(0),
|
|
||||||
})
|
|
||||||
.superRefine((value, ctx) => {
|
|
||||||
if (value.fromTurnCount > value.toTurnCount) {
|
|
||||||
ctx.addIssue({
|
|
||||||
code: z.ZodIssueCode.custom,
|
|
||||||
message: "fromTurnCount must be less than or equal to toTurnCount",
|
|
||||||
path: ["fromTurnCount"],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
export const providerGetCheckpointDiffResultSchema = z.object({
|
|
||||||
threadId: z.string().min(1),
|
|
||||||
fromTurnCount: z.number().int().min(0),
|
|
||||||
toTurnCount: z.number().int().min(0),
|
|
||||||
diff: z.string(),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const providerRespondToRequestInputSchema = z.object({
|
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),
|
||||||
@@ -205,15 +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 ProviderGetCheckpointDiffInput = z.input<typeof providerGetCheckpointDiffInputSchema>;
|
|
||||||
export type ProviderGetCheckpointDiffResult = z.infer<typeof providerGetCheckpointDiffResultSchema>;
|
|
||||||
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>;
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { z } from "zod";
|
|
||||||
import { keybindingRuleSchema, resolvedKeybindingsConfigSchema } from "./keybindings";
|
|
||||||
|
|
||||||
export const serverConfigSchema = z.object({
|
|
||||||
cwd: z.string().min(1),
|
|
||||||
keybindings: resolvedKeybindingsConfigSchema.default([]),
|
|
||||||
});
|
|
||||||
|
|
||||||
export const serverUpsertKeybindingInputSchema = keybindingRuleSchema;
|
|
||||||
|
|
||||||
export const serverUpsertKeybindingResultSchema = z.object({
|
|
||||||
keybindings: resolvedKeybindingsConfigSchema.default([]),
|
|
||||||
});
|
|
||||||
|
|
||||||
export type ServerConfig = z.infer<typeof serverConfigSchema>;
|
|
||||||
export type ServerUpsertKeybindingInput = z.infer<typeof serverUpsertKeybindingInputSchema>;
|
|
||||||
export type ServerUpsertKeybindingResult = z.infer<typeof serverUpsertKeybindingResultSchema>;
|
|
||||||
@@ -42,36 +42,6 @@ describe("terminalOpenInputSchema", () => {
|
|||||||
});
|
});
|
||||||
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("accepts optional env overrides", () => {
|
|
||||||
const parsed = terminalOpenInputSchema.parse({
|
|
||||||
threadId: "thread-1",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
cols: 100,
|
|
||||||
rows: 24,
|
|
||||||
env: {
|
|
||||||
T3CODE_PROJECT_ROOT: "/tmp/project",
|
|
||||||
CUSTOM_FLAG: "1",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(parsed.env).toMatchObject({
|
|
||||||
T3CODE_PROJECT_ROOT: "/tmp/project",
|
|
||||||
CUSTOM_FLAG: "1",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects invalid env keys", () => {
|
|
||||||
const result = terminalOpenInputSchema.safeParse({
|
|
||||||
threadId: "thread-1",
|
|
||||||
cwd: "/tmp/project",
|
|
||||||
cols: 100,
|
|
||||||
rows: 24,
|
|
||||||
env: {
|
|
||||||
"bad-key": "1",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("terminalWriteInputSchema", () => {
|
describe("terminalWriteInputSchema", () => {
|
||||||
|
|||||||
@@ -5,11 +5,6 @@ export const DEFAULT_TERMINAL_ID = "default";
|
|||||||
const terminalColsSchema = z.number().int().min(20).max(400);
|
const terminalColsSchema = z.number().int().min(20).max(400);
|
||||||
const terminalRowsSchema = z.number().int().min(5).max(200);
|
const terminalRowsSchema = z.number().int().min(5).max(200);
|
||||||
const terminalIdSchema = z.string().trim().min(1).max(128);
|
const terminalIdSchema = z.string().trim().min(1).max(128);
|
||||||
const terminalEnvKeySchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128);
|
|
||||||
const terminalEnvValueSchema = z.string().max(8_192);
|
|
||||||
const terminalEnvSchema = z
|
|
||||||
.record(terminalEnvKeySchema, terminalEnvValueSchema)
|
|
||||||
.refine((env) => Object.keys(env).length <= 128, "Too many terminal env vars");
|
|
||||||
|
|
||||||
export const terminalThreadInputSchema = z.object({
|
export const terminalThreadInputSchema = z.object({
|
||||||
threadId: z.string().trim().min(1),
|
threadId: z.string().trim().min(1),
|
||||||
@@ -21,9 +16,8 @@ export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
|
|||||||
|
|
||||||
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
|
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
|
||||||
cwd: z.string().trim().min(1),
|
cwd: z.string().trim().min(1),
|
||||||
cols: terminalColsSchema.optional(),
|
cols: terminalColsSchema,
|
||||||
rows: terminalRowsSchema.optional(),
|
rows: terminalRowsSchema,
|
||||||
env: terminalEnvSchema.optional(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
|
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
|
||||||
|
|||||||
@@ -10,16 +10,11 @@ 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",
|
|
||||||
providersGetCheckpointDiff: "providers.getCheckpointDiff",
|
|
||||||
providersRevertToCheckpoint: "providers.revertToCheckpoint",
|
|
||||||
|
|
||||||
// Project registry methods
|
// Project registry methods
|
||||||
projectsList: "projects.list",
|
projectsList: "projects.list",
|
||||||
projectsAdd: "projects.add",
|
projectsAdd: "projects.add",
|
||||||
projectsRemove: "projects.remove",
|
projectsRemove: "projects.remove",
|
||||||
projectsSearchEntries: "projects.searchEntries",
|
|
||||||
projectsUpdateScripts: "projects.updateScripts",
|
|
||||||
|
|
||||||
// Shell methods
|
// Shell methods
|
||||||
shellOpenInEditor: "shell.openInEditor",
|
shellOpenInEditor: "shell.openInEditor",
|
||||||
@@ -45,7 +40,6 @@ export const WS_METHODS = {
|
|||||||
|
|
||||||
// Server meta
|
// Server meta
|
||||||
serverGetConfig: "server.getConfig",
|
serverGetConfig: "server.getConfig",
|
||||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// ── Push Event Channels ──────────────────────────────────────────────
|
// ── Push Event Channels ──────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
|
|
||||||
import fs from "node:fs/promises";
|
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
|
||||||
import vm from "node:vm";
|
|
||||||
import { execFile } from "node:child_process";
|
|
||||||
import { promisify } from "node:util";
|
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
|
||||||
|
|
||||||
const VERSION = process.argv[2] ?? "12.17.0";
|
|
||||||
const VERSION_TAG = `v${VERSION}`;
|
|
||||||
const VSIX_URL = `https://open-vsx.org/api/vscode-icons-team/vscode-icons/${VERSION}/file/vscode-icons-team.vscode-icons-${VERSION}.vsix`;
|
|
||||||
const LANGUAGES_URL = `https://raw.githubusercontent.com/vscode-icons/vscode-icons/${VERSION_TAG}/src/iconsManifest/languages.ts`;
|
|
||||||
|
|
||||||
const REPO_ROOT = process.cwd();
|
|
||||||
const MANIFEST_PATH = path.join(REPO_ROOT, "apps/web/src/vscode-icons-manifest.json");
|
|
||||||
const ASSOCIATIONS_PATH = path.join(
|
|
||||||
REPO_ROOT,
|
|
||||||
"apps/web/src/vscode-icons-language-associations.json",
|
|
||||||
);
|
|
||||||
|
|
||||||
function normalizeExtension(value) {
|
|
||||||
return value.trim().toLowerCase().replace(/^\./, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeFileName(value) {
|
|
||||||
return value.trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
function putIfAbsent(target, key, value) {
|
|
||||||
if (!(key in target)) {
|
|
||||||
target[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function downloadVsix(tmpDir) {
|
|
||||||
const vsixPath = path.join(tmpDir, `vscode-icons-${VERSION}.vsix`);
|
|
||||||
const response = await fetch(VSIX_URL);
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to download VSIX: ${response.status} ${response.statusText}`);
|
|
||||||
}
|
|
||||||
const bytes = Buffer.from(await response.arrayBuffer());
|
|
||||||
await fs.writeFile(vsixPath, bytes);
|
|
||||||
return vsixPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function extractManifestFromVsix(vsixPath) {
|
|
||||||
const { stdout } = await execFileAsync("unzip", [
|
|
||||||
"-p",
|
|
||||||
vsixPath,
|
|
||||||
"extension/dist/src/vsicons-icon-theme.json",
|
|
||||||
]);
|
|
||||||
if (!stdout || stdout.trim().length === 0) {
|
|
||||||
throw new Error("Could not extract vsicons-icon-theme.json from VSIX");
|
|
||||||
}
|
|
||||||
return JSON.parse(stdout);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadLanguagesCollection() {
|
|
||||||
const response = await fetch(LANGUAGES_URL);
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to fetch languages.ts: ${response.status} ${response.statusText}`);
|
|
||||||
}
|
|
||||||
const rawSource = await response.text();
|
|
||||||
const source = rawSource
|
|
||||||
.replace(/^import[^;]+;\s*/gm, "")
|
|
||||||
.replace(/export const languages(?:\s*:\s*[^=]+)?\s*=/, "const languages =")
|
|
||||||
.replace(/\}\s*satisfies\s*Record<[^;]+>;/, "};");
|
|
||||||
|
|
||||||
const context = {};
|
|
||||||
vm.createContext(context);
|
|
||||||
vm.runInContext(`${source}\n;globalThis.__languages = languages;`, context);
|
|
||||||
const languages = context.__languages;
|
|
||||||
if (!languages || typeof languages !== "object") {
|
|
||||||
throw new Error("Failed to parse languages.ts into a collection");
|
|
||||||
}
|
|
||||||
return languages;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildLanguageAssociations(manifest, languages) {
|
|
||||||
const availableLanguageIds = new Set(Object.keys(manifest.languageIds ?? {}));
|
|
||||||
const extensionToLanguageId = {};
|
|
||||||
const fileNameToLanguageId = {};
|
|
||||||
|
|
||||||
for (const entry of Object.values(languages)) {
|
|
||||||
if (!entry || typeof entry !== "object") continue;
|
|
||||||
const idsRaw = entry.ids;
|
|
||||||
const ids = Array.isArray(idsRaw) ? idsRaw : [idsRaw];
|
|
||||||
const knownExtensions = Array.isArray(entry.knownExtensions) ? entry.knownExtensions : [];
|
|
||||||
const knownFilenames = Array.isArray(entry.knownFilenames) ? entry.knownFilenames : [];
|
|
||||||
|
|
||||||
for (const idValue of ids) {
|
|
||||||
if (typeof idValue !== "string") continue;
|
|
||||||
const languageId = idValue.trim();
|
|
||||||
if (languageId.length === 0) continue;
|
|
||||||
if (!availableLanguageIds.has(languageId)) continue;
|
|
||||||
|
|
||||||
for (const extensionValue of knownExtensions) {
|
|
||||||
if (typeof extensionValue !== "string") continue;
|
|
||||||
const extension = normalizeExtension(extensionValue);
|
|
||||||
if (extension.length === 0) continue;
|
|
||||||
putIfAbsent(extensionToLanguageId, extension, languageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const fileNameValue of knownFilenames) {
|
|
||||||
if (typeof fileNameValue !== "string") continue;
|
|
||||||
const fileName = normalizeFileName(fileNameValue);
|
|
||||||
if (fileName.length === 0) continue;
|
|
||||||
putIfAbsent(fileNameToLanguageId, fileName, languageId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
version: VERSION,
|
|
||||||
source: LANGUAGES_URL,
|
|
||||||
generatedAt: new Date().toISOString(),
|
|
||||||
extensionToLanguageId,
|
|
||||||
fileNameToLanguageId,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "t3-vscode-icons-sync-"));
|
|
||||||
try {
|
|
||||||
const vsixPath = await downloadVsix(tmpDir);
|
|
||||||
const manifest = await extractManifestFromVsix(vsixPath);
|
|
||||||
const languages = await loadLanguagesCollection();
|
|
||||||
const associations = buildLanguageAssociations(manifest, languages);
|
|
||||||
|
|
||||||
await fs.writeFile(MANIFEST_PATH, `${JSON.stringify(manifest)}\n`, "utf8");
|
|
||||||
await fs.writeFile(ASSOCIATIONS_PATH, `${JSON.stringify(associations)}\n`, "utf8");
|
|
||||||
|
|
||||||
process.stdout.write(
|
|
||||||
[
|
|
||||||
`Synced vscode-icons ${VERSION}`,
|
|
||||||
`manifest: ${MANIFEST_PATH}`,
|
|
||||||
`language associations: ${ASSOCIATIONS_PATH}`,
|
|
||||||
`extension mappings: ${Object.keys(associations.extensionToLanguageId).length}`,
|
|
||||||
`filename mappings: ${Object.keys(associations.fileNameToLanguageId).length}`,
|
|
||||||
].join("\n") + "\n",
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((error) => {
|
|
||||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
||||||
process.exit(1);
|
|
||||||
});
|
|
||||||
Reference in new issue
Block a user