Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4df41a0d7 |
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.
|
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
# TODO
|
## TODO
|
||||||
|
|
||||||
## Small things
|
|
||||||
|
|
||||||
- [ ] 1 click copy in codeblocks
|
- [ ] 1 click copy in codeblocks
|
||||||
- [x] Pasting/adding images to submit with prompts
|
- [ ] Pasting/adding images to submit with prompts
|
||||||
- [ ] Only show last 10 threads for a given project
|
- [ ] Only show last 10 threads for a given project
|
||||||
- [ ] Thread archiving
|
- [ ] Thread archiving
|
||||||
- [x] Selecting folder should instantly create project
|
- [ ] Selecting folder should instantly create project
|
||||||
- [ ] New projects should go on top
|
- [ ] New projects should go on top
|
||||||
- [ ] Projects should be sorted by latest thread update
|
- [ ] Projects should be sorted by latest thread update
|
||||||
- [x] "Response" bar should ONLY appear on work completed
|
- [x] "Response" bar should ONLY appear on work completed
|
||||||
@@ -14,10 +12,3 @@
|
|||||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||||
- [ ] Insta focus input on new thread creation
|
- [ ] Insta focus input on new thread creation
|
||||||
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||||
- [x] Making new thread should auto-focus input box
|
|
||||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
|
||||||
|
|
||||||
## Bigger things
|
|
||||||
|
|
||||||
- [ ] Queueing messages
|
|
||||||
- [ ] External runners (i.e. running the cli on a mac mini)
|
|
||||||
@@ -15,13 +15,10 @@ await waitOn({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||||
const childEnv = { ...process.env };
|
|
||||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
|
||||||
|
|
||||||
const child = spawn(command, ["dist-electron/main.js"], {
|
const child = spawn(command, ["dist-electron/main.js"], {
|
||||||
stdio: "inherit",
|
stdio: "inherit",
|
||||||
env: {
|
env: {
|
||||||
...childEnv,
|
...process.env,
|
||||||
VITE_DEV_SERVER_URL: devServerUrl,
|
VITE_DEV_SERVER_URL: devServerUrl,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,57 +0,0 @@
|
|||||||
import type { BrowserWindow } from "electron";
|
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
||||||
|
|
||||||
const { showMessageBoxMock } = vi.hoisted(() => ({
|
|
||||||
showMessageBoxMock: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock("electron", () => ({
|
|
||||||
dialog: {
|
|
||||||
showMessageBox: showMessageBoxMock,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
|
||||||
|
|
||||||
describe("showDesktopConfirmDialog", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
showMessageBoxMock.mockReset();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns false and does not open a dialog for empty messages", async () => {
|
|
||||||
const result = await showDesktopConfirmDialog(" ", null);
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(showMessageBoxMock).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("opens a dialog for the focused window and returns true on confirm", async () => {
|
|
||||||
const ownerWindow = { id: 1 } as BrowserWindow;
|
|
||||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
|
||||||
|
|
||||||
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
|
|
||||||
|
|
||||||
expect(result).toBe(true);
|
|
||||||
expect(showMessageBoxMock).toHaveBeenCalledWith(
|
|
||||||
ownerWindow,
|
|
||||||
expect.objectContaining({
|
|
||||||
buttons: ["No", "Yes"],
|
|
||||||
message: "Delete worktree?",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("opens an app-level dialog when there is no focused window", async () => {
|
|
||||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
|
||||||
|
|
||||||
const result = await showDesktopConfirmDialog("Delete worktree?", null);
|
|
||||||
|
|
||||||
expect(result).toBe(false);
|
|
||||||
expect(showMessageBoxMock).toHaveBeenCalledWith(
|
|
||||||
expect.objectContaining({
|
|
||||||
buttons: ["No", "Yes"],
|
|
||||||
message: "Delete worktree?",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
import { type BrowserWindow, dialog } from "electron";
|
|
||||||
|
|
||||||
const CONFIRM_BUTTON_INDEX = 1;
|
|
||||||
|
|
||||||
export async function showDesktopConfirmDialog(
|
|
||||||
message: string,
|
|
||||||
ownerWindow: BrowserWindow | null,
|
|
||||||
): Promise<boolean> {
|
|
||||||
const normalizedMessage = message.trim();
|
|
||||||
if (normalizedMessage.length === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const options = {
|
|
||||||
type: "question" as const,
|
|
||||||
buttons: ["No", "Yes"],
|
|
||||||
defaultId: CONFIRM_BUTTON_INDEX,
|
|
||||||
cancelId: 0,
|
|
||||||
noLink: true,
|
|
||||||
message: normalizedMessage,
|
|
||||||
};
|
|
||||||
const result = ownerWindow
|
|
||||||
? await dialog.showMessageBox(ownerWindow, options)
|
|
||||||
: await dialog.showMessageBox(options);
|
|
||||||
return result.response === CONFIRM_BUTTON_INDEX;
|
|
||||||
}
|
|
||||||
@@ -7,13 +7,11 @@ import path from "node:path";
|
|||||||
|
|
||||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||||
|
|
||||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
|
||||||
import { fixPath } from "./fixPath";
|
import { fixPath } from "./fixPath";
|
||||||
|
|
||||||
fixPath();
|
fixPath();
|
||||||
|
|
||||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
|
||||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||||
@@ -83,12 +81,7 @@ function startBackend(): void {
|
|||||||
|
|
||||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||||
cwd: ROOT_DIR,
|
cwd: ROOT_DIR,
|
||||||
// In Electron main, process.execPath points to the Electron binary.
|
env: backendEnv(),
|
||||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
|
||||||
env: {
|
|
||||||
...backendEnv(),
|
|
||||||
ELECTRON_RUN_AS_NODE: "1",
|
|
||||||
},
|
|
||||||
stdio: "inherit",
|
stdio: "inherit",
|
||||||
});
|
});
|
||||||
backendProcess = child;
|
backendProcess = child;
|
||||||
@@ -149,16 +142,6 @@ function registerIpcHandlers(): void {
|
|||||||
return result.filePaths[0] ?? null;
|
return result.filePaths[0] ?? null;
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.removeHandler(CONFIRM_CHANNEL);
|
|
||||||
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
|
|
||||||
if (typeof message !== "string") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
|
||||||
return showDesktopConfirmDialog(message, owner);
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||||
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
|
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
|
||||||
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { contextBridge, ipcRenderer } from "electron";
|
import { contextBridge, ipcRenderer } from "electron";
|
||||||
|
|
||||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
|
||||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||||
@@ -9,7 +8,6 @@ const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
|||||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getWsUrl: () => wsUrl,
|
getWsUrl: () => wsUrl,
|
||||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
||||||
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
|
|
||||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||||
|
|||||||
@@ -21,16 +21,10 @@ function createSendTurnHarness() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const requireSession = vi
|
const requireSession = vi
|
||||||
.spyOn(
|
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
|
||||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
|
||||||
"requireSession",
|
|
||||||
)
|
|
||||||
.mockReturnValue(context);
|
.mockReturnValue(context);
|
||||||
const sendRequest = vi
|
const sendRequest = vi
|
||||||
.spyOn(
|
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
|
||||||
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
|
|
||||||
"sendRequest",
|
|
||||||
)
|
|
||||||
.mockResolvedValue({
|
.mockResolvedValue({
|
||||||
turn: {
|
turn: {
|
||||||
id: "turn_1",
|
id: "turn_1",
|
||||||
@@ -43,36 +37,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,44 +107,9 @@ 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 } = createSendTurnHarness();
|
||||||
createSendTurnHarness();
|
|
||||||
|
|
||||||
const result = await manager.sendTurn({
|
const result = await manager.sendTurn({
|
||||||
sessionId: "sess_1",
|
sessionId: "sess_1",
|
||||||
@@ -262,91 +191,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 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -283,7 +258,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
const turnInput: Array<
|
const turnInput: Array<
|
||||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
| { type: "text"; text: string; text_elements: [] }
|
||||||
|
| { type: "image"; url: string }
|
||||||
> = [];
|
> = [];
|
||||||
if (input.input) {
|
if (input.input) {
|
||||||
turnInput.push({
|
turnInput.push({
|
||||||
@@ -307,7 +283,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
const turnStartParams: {
|
const turnStartParams: {
|
||||||
threadId: string;
|
threadId: string;
|
||||||
input: Array<
|
input: Array<
|
||||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
| { type: "text"; text: string; text_elements: [] }
|
||||||
|
| { type: "image"; url: string }
|
||||||
>;
|
>;
|
||||||
model?: string;
|
model?: string;
|
||||||
effort?: string;
|
effort?: string;
|
||||||
@@ -356,41 +333,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 +744,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 +825,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;
|
||||||
|
|||||||
@@ -28,5 +28,8 @@ export interface TextGenerationService {
|
|||||||
generateCommitMessage(
|
generateCommitMessage(
|
||||||
input: CommitMessageGenerationInput,
|
input: CommitMessageGenerationInput,
|
||||||
): Promise<CommitMessageGenerationResult>;
|
): Promise<CommitMessageGenerationResult>;
|
||||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
generatePrContent(
|
||||||
|
input: PrContentGenerationInput,
|
||||||
|
): Promise<PrContentGenerationResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+10
-376
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
|
|||||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
GitCoreService,
|
GitCoreService,
|
||||||
@@ -11,7 +11,6 @@ import {
|
|||||||
createGitWorktree,
|
createGitWorktree,
|
||||||
initGitRepo,
|
initGitRepo,
|
||||||
listGitBranches,
|
listGitBranches,
|
||||||
pullGitBranch,
|
|
||||||
removeGitWorktree,
|
removeGitWorktree,
|
||||||
runTerminalCommand,
|
runTerminalCommand,
|
||||||
} from "./git";
|
} from "./git";
|
||||||
@@ -52,25 +51,6 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
|
|||||||
await git(cwd, "commit -m 'initial commit'");
|
await git(cwd, "commit -m 'initial commit'");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function commitWithDate(
|
|
||||||
cwd: string,
|
|
||||||
fileName: string,
|
|
||||||
fileContents: string,
|
|
||||||
dateIsoString: string,
|
|
||||||
message: string,
|
|
||||||
): Promise<void> {
|
|
||||||
await writeFile(path.join(cwd, fileName), fileContents);
|
|
||||||
await git(cwd, `add ${fileName}`);
|
|
||||||
const commitResult = await runTerminalCommand({
|
|
||||||
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
|
|
||||||
cwd,
|
|
||||||
timeoutMs: 10_000,
|
|
||||||
});
|
|
||||||
if (commitResult.code !== 0) {
|
|
||||||
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Tests ──
|
// ── Tests ──
|
||||||
|
|
||||||
describe("git integration", () => {
|
describe("git integration", () => {
|
||||||
@@ -126,82 +106,14 @@ describe("git integration", () => {
|
|||||||
expect(current!.current).toBe(true);
|
expect(current!.current).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps current branch first and sorts the remaining branches by recency", async () => {
|
it("sorts current branch first", async () => {
|
||||||
await using tmp = await makeTmpDir();
|
await using tmp = await makeTmpDir();
|
||||||
await initRepoWithCommit(tmp.path);
|
await initRepoWithCommit(tmp.path);
|
||||||
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
|
||||||
(branch) => branch.current,
|
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
|
||||||
)!.name;
|
|
||||||
|
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
|
||||||
await commitWithDate(
|
|
||||||
tmp.path,
|
|
||||||
"older.txt",
|
|
||||||
"older branch change\n",
|
|
||||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
|
||||||
"older branch change",
|
|
||||||
);
|
|
||||||
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
|
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
|
||||||
await commitWithDate(
|
|
||||||
tmp.path,
|
|
||||||
"newer.txt",
|
|
||||||
"newer branch change\n",
|
|
||||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
|
||||||
"newer branch change",
|
|
||||||
);
|
|
||||||
|
|
||||||
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
|
||||||
|
|
||||||
const result = await listGitBranches({ cwd: tmp.path });
|
const result = await listGitBranches({ cwd: tmp.path });
|
||||||
expect(result.branches[0]!.name).toBe("older-branch");
|
expect(result.branches[0]!.current).toBe(true);
|
||||||
expect(result.branches[1]!.name).toBe("newer-branch");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps default branch right after current branch", async () => {
|
|
||||||
await using tmp = await makeTmpDir();
|
|
||||||
await using remote = await makeTmpDir();
|
|
||||||
await initRepoWithCommit(tmp.path);
|
|
||||||
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
|
||||||
(branch) => branch.current,
|
|
||||||
)!.name;
|
|
||||||
|
|
||||||
await git(remote.path, "init --bare");
|
|
||||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
|
||||||
await git(tmp.path, `push -u origin ${defaultBranch}`);
|
|
||||||
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
|
|
||||||
|
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
|
||||||
await commitWithDate(
|
|
||||||
tmp.path,
|
|
||||||
"current.txt",
|
|
||||||
"current change\n",
|
|
||||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
|
||||||
"current change",
|
|
||||||
);
|
|
||||||
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
|
|
||||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
|
||||||
await commitWithDate(
|
|
||||||
tmp.path,
|
|
||||||
"newer.txt",
|
|
||||||
"newer change\n",
|
|
||||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
|
||||||
"newer change",
|
|
||||||
);
|
|
||||||
|
|
||||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
|
||||||
|
|
||||||
const result = await listGitBranches({ cwd: tmp.path });
|
|
||||||
expect(result.branches[0]!.name).toBe("current-branch");
|
|
||||||
expect(result.branches[1]!.name).toBe(defaultBranch);
|
|
||||||
expect(result.branches[2]!.name).toBe("newer-branch");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("lists multiple branches after creating them", async () => {
|
it("lists multiple branches after creating them", async () => {
|
||||||
@@ -239,207 +151,6 @@ describe("git integration", () => {
|
|||||||
expect(current!.name).toBe("feature");
|
expect(current!.name).toBe("feature");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("refreshes upstream behind count after checkout when remote branch advanced", 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 defaultBranch = (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 ${defaultBranch}`);
|
|
||||||
|
|
||||||
const featureBranch = "feature-behind";
|
|
||||||
await createGitBranch({ cwd: source.path, branch: featureBranch });
|
|
||||||
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
|
|
||||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
|
||||||
await git(source.path, "add feature.txt");
|
|
||||||
await git(source.path, "commit -m 'feature base'");
|
|
||||||
await git(source.path, `push -u origin ${featureBranch}`);
|
|
||||||
await checkoutGitBranch({ cwd: source.path, branch: defaultBranch });
|
|
||||||
|
|
||||||
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 ${featureBranch} --track origin/${featureBranch}`);
|
|
||||||
await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n");
|
|
||||||
await git(clone.path, "add feature.txt");
|
|
||||||
await git(clone.path, "commit -m 'remote feature update'");
|
|
||||||
await git(clone.path, `push origin ${featureBranch}`);
|
|
||||||
|
|
||||||
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
|
|
||||||
const core = new GitCoreService();
|
|
||||||
await vi.waitFor(async () => {
|
|
||||||
const details = await core.statusDetails(source.path);
|
|
||||||
expect(details.branch).toBe(featureBranch);
|
|
||||||
expect(details.aheadCount).toBe(0);
|
|
||||||
expect(details.behindCount).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps checkout successful when upstream refresh fails", async () => {
|
|
||||||
await using remote = await makeTmpDir();
|
|
||||||
await using source = await makeTmpDir();
|
|
||||||
await git(remote.path, "init --bare");
|
|
||||||
|
|
||||||
await initRepoWithCommit(source.path);
|
|
||||||
const defaultBranch = (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 ${defaultBranch}`);
|
|
||||||
|
|
||||||
const featureBranch = "feature-refresh-failure";
|
|
||||||
await git(source.path, `branch ${featureBranch}`);
|
|
||||||
await git(source.path, `checkout ${featureBranch}`);
|
|
||||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
|
||||||
await git(source.path, "add feature.txt");
|
|
||||||
await git(source.path, "commit -m 'feature base'");
|
|
||||||
await git(source.path, `push -u origin ${featureBranch}`);
|
|
||||||
await git(source.path, `checkout ${defaultBranch}`);
|
|
||||||
|
|
||||||
class RefreshFailingGitCoreService extends GitCoreService {
|
|
||||||
refreshFetchAttempts = 0;
|
|
||||||
|
|
||||||
override async git(
|
|
||||||
cwd: string,
|
|
||||||
args: readonly string[],
|
|
||||||
allowNonZeroExit = false,
|
|
||||||
): Promise<void> {
|
|
||||||
if (args[0] === "fetch") {
|
|
||||||
this.refreshFetchAttempts += 1;
|
|
||||||
throw new Error("simulated fetch timeout");
|
|
||||||
}
|
|
||||||
await super.git(cwd, args, allowNonZeroExit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const core = new RefreshFailingGitCoreService();
|
|
||||||
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
|
|
||||||
undefined,
|
|
||||||
);
|
|
||||||
await vi.waitFor(() => {
|
|
||||||
expect(core.refreshFetchAttempts).toBe(1);
|
|
||||||
});
|
|
||||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("refresh fetch is scoped to the checked out branch upstream refspec", async () => {
|
|
||||||
await using remote = await makeTmpDir();
|
|
||||||
await using source = await makeTmpDir();
|
|
||||||
await git(remote.path, "init --bare");
|
|
||||||
|
|
||||||
await initRepoWithCommit(source.path);
|
|
||||||
const defaultBranch = (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 ${defaultBranch}`);
|
|
||||||
|
|
||||||
const featureBranch = "feature/scoped-fetch";
|
|
||||||
await git(source.path, `checkout -b ${featureBranch}`);
|
|
||||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
|
||||||
await git(source.path, "add feature.txt");
|
|
||||||
await git(source.path, "commit -m 'feature base'");
|
|
||||||
await git(source.path, `push -u origin ${featureBranch}`);
|
|
||||||
await git(source.path, `checkout ${defaultBranch}`);
|
|
||||||
|
|
||||||
class FetchRecordingGitCoreService extends GitCoreService {
|
|
||||||
fetchArgs: readonly string[] | null = null;
|
|
||||||
|
|
||||||
override async git(
|
|
||||||
cwd: string,
|
|
||||||
args: readonly string[],
|
|
||||||
allowNonZeroExit = false,
|
|
||||||
): Promise<void> {
|
|
||||||
if (args[0] === "fetch") {
|
|
||||||
this.fetchArgs = args;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await super.git(cwd, args, allowNonZeroExit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const core = new FetchRecordingGitCoreService();
|
|
||||||
await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
|
|
||||||
await vi.waitFor(() => {
|
|
||||||
expect(core.fetchArgs).not.toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
|
||||||
expect(core.fetchArgs).toEqual([
|
|
||||||
"fetch",
|
|
||||||
"--quiet",
|
|
||||||
"--no-tags",
|
|
||||||
"origin",
|
|
||||||
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns checkout result before background upstream refresh completes", async () => {
|
|
||||||
await using remote = await makeTmpDir();
|
|
||||||
await using source = await makeTmpDir();
|
|
||||||
await git(remote.path, "init --bare");
|
|
||||||
|
|
||||||
await initRepoWithCommit(source.path);
|
|
||||||
const defaultBranch = (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 ${defaultBranch}`);
|
|
||||||
|
|
||||||
const featureBranch = "feature/background-refresh";
|
|
||||||
await git(source.path, `checkout -b ${featureBranch}`);
|
|
||||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
|
||||||
await git(source.path, "add feature.txt");
|
|
||||||
await git(source.path, "commit -m 'feature base'");
|
|
||||||
await git(source.path, `push -u origin ${featureBranch}`);
|
|
||||||
await git(source.path, `checkout ${defaultBranch}`);
|
|
||||||
|
|
||||||
class SlowRefreshGitCoreService extends GitCoreService {
|
|
||||||
fetchStarted = false;
|
|
||||||
private readonly waitForReleasePromise: Promise<void>;
|
|
||||||
private releaseWait: () => void = () => undefined;
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
super();
|
|
||||||
this.waitForReleasePromise = new Promise<void>((resolve) => {
|
|
||||||
this.releaseWait = resolve;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
releaseFetch(): void {
|
|
||||||
this.releaseWait();
|
|
||||||
}
|
|
||||||
|
|
||||||
override async git(
|
|
||||||
cwd: string,
|
|
||||||
args: readonly string[],
|
|
||||||
allowNonZeroExit = false,
|
|
||||||
): Promise<void> {
|
|
||||||
if (args[0] === "fetch") {
|
|
||||||
this.fetchStarted = true;
|
|
||||||
await this.waitForReleasePromise;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await super.git(cwd, args, allowNonZeroExit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const core = new SlowRefreshGitCoreService();
|
|
||||||
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
|
|
||||||
undefined,
|
|
||||||
);
|
|
||||||
await vi.waitFor(() => {
|
|
||||||
expect(core.fetchStarted).toBe(true);
|
|
||||||
});
|
|
||||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
|
||||||
core.releaseFetch();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("throws when branch does not exist", async () => {
|
it("throws when branch does not exist", async () => {
|
||||||
await using tmp = await makeTmpDir();
|
await using tmp = await makeTmpDir();
|
||||||
await initRepoWithCommit(tmp.path);
|
await initRepoWithCommit(tmp.path);
|
||||||
@@ -760,35 +471,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);
|
||||||
@@ -800,7 +482,11 @@ describe("git integration", () => {
|
|||||||
expect(context!.stagedSummary.length).toBeGreaterThan(0);
|
expect(context!.stagedSummary.length).toBeGreaterThan(0);
|
||||||
expect(context!.stagedPatch.length).toBeGreaterThan(0);
|
expect(context!.stagedPatch.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
|
const created = await core.commit(
|
||||||
|
tmp.path,
|
||||||
|
"Add README update",
|
||||||
|
"- include updated content",
|
||||||
|
);
|
||||||
expect(created.commitSha.length).toBeGreaterThan(0);
|
expect(created.commitSha.length).toBeGreaterThan(0);
|
||||||
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
|
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
|
||||||
});
|
});
|
||||||
@@ -830,57 +516,5 @@ describe("git integration", () => {
|
|||||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||||
expect(skipped.status).toBe("skipped_up_to_date");
|
expect(skipped.status).toBe("skipped_up_to_date");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("pulls behind branch and then reports up-to-date", 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 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 pulled = await core.pullCurrentBranch(source.path);
|
|
||||||
expect(pulled.status).toBe("pulled");
|
|
||||||
expect((await core.statusDetails(source.path)).behindCount).toBe(0);
|
|
||||||
|
|
||||||
const skipped = await core.pullCurrentBranch(source.path);
|
|
||||||
expect(skipped.status).toBe("skipped_up_to_date");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("top-level pullGitBranch rejects when no upstream exists", async () => {
|
|
||||||
await using tmp = await makeTmpDir();
|
|
||||||
await initRepoWithCommit(tmp.path);
|
|
||||||
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("lists branches when recency lookup fails", async () => {
|
|
||||||
await using tmp = await makeTmpDir();
|
|
||||||
await initRepoWithCommit(tmp.path);
|
|
||||||
const core = new GitCoreService();
|
|
||||||
const recencySpy = vi
|
|
||||||
.spyOn(core as any, "readBranchRecency")
|
|
||||||
.mockRejectedValueOnce(new Error("timeout"));
|
|
||||||
|
|
||||||
const result = await core.listBranches({ cwd: tmp.path });
|
|
||||||
|
|
||||||
expect(result.isRepo).toBe(true);
|
|
||||||
expect(result.branches.length).toBeGreaterThan(0);
|
|
||||||
expect(result.branches[0]?.current).toBe(true);
|
|
||||||
recencySpy.mockRestore();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
+16
-249
@@ -3,8 +3,6 @@ import os from "node:os";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
gitPullInputSchema,
|
|
||||||
gitPullResultSchema,
|
|
||||||
gitStatusInputSchema,
|
gitStatusInputSchema,
|
||||||
gitStatusResultSchema,
|
gitStatusResultSchema,
|
||||||
type GitCheckoutInput,
|
type GitCheckoutInput,
|
||||||
@@ -14,8 +12,6 @@ import {
|
|||||||
type GitInitInput,
|
type GitInitInput,
|
||||||
type GitListBranchesInput,
|
type GitListBranchesInput,
|
||||||
type GitListBranchesResult,
|
type GitListBranchesResult,
|
||||||
type GitPullInput,
|
|
||||||
type GitPullResult,
|
|
||||||
type GitRemoveWorktreeInput,
|
type GitRemoveWorktreeInput,
|
||||||
type GitStatusInput,
|
type GitStatusInput,
|
||||||
type GitStatusResult,
|
type GitStatusResult,
|
||||||
@@ -65,8 +61,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(
|
||||||
@@ -96,52 +90,6 @@ function parseBranchAb(value: string): { ahead: number; behind: number } {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseNumstatEntries(
|
|
||||||
stdout: string,
|
|
||||||
): Array<{ path: string; insertions: number; deletions: number }> {
|
|
||||||
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
|
|
||||||
for (const line of stdout.split(/\r?\n/g)) {
|
|
||||||
if (line.trim().length === 0) continue;
|
|
||||||
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
|
|
||||||
const rawPath =
|
|
||||||
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
|
|
||||||
if (rawPath.length === 0) continue;
|
|
||||||
const added = Number.parseInt(addedRaw ?? "0", 10);
|
|
||||||
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
|
|
||||||
const renameArrowIndex = rawPath.indexOf(" => ");
|
|
||||||
const normalizedPath =
|
|
||||||
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
|
|
||||||
entries.push({
|
|
||||||
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
|
|
||||||
insertions: Number.isFinite(added) ? added : 0,
|
|
||||||
deletions: Number.isFinite(deleted) ? deleted : 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return entries;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parsePorcelainPath(line: string): string | null {
|
|
||||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
|
||||||
const simple = line.slice(2).trim();
|
|
||||||
return simple.length > 0 ? simple : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const tabIndex = line.indexOf("\t");
|
|
||||||
if (tabIndex >= 0) {
|
|
||||||
const fromTab = line.slice(tabIndex + 1);
|
|
||||||
const [path] = fromTab.split("\t");
|
|
||||||
return path?.trim().length ? path.trim() : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = line.trim().split(/\s+/g);
|
|
||||||
const path = parts.at(-1) ?? "";
|
|
||||||
return path.length > 0 ? path : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function commandLabel(args: readonly string[]): string {
|
function commandLabel(args: readonly string[]): string {
|
||||||
return `git ${args.join(" ")}`;
|
return `git ${args.join(" ")}`;
|
||||||
}
|
}
|
||||||
@@ -218,15 +166,12 @@ 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);
|
||||||
return gitStatusResultSchema.parse({
|
return gitStatusResultSchema.parse({
|
||||||
branch: details.branch,
|
branch: details.branch,
|
||||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||||
workingTree: details.workingTree,
|
|
||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
@@ -235,22 +180,15 @@ export class GitCoreService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
|
||||||
|
|
||||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
|
||||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
|
||||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
|
||||||
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
let branch: string | null = null;
|
let branch: string | null = null;
|
||||||
let upstreamRef: string | null = null;
|
let upstreamRef: string | null = null;
|
||||||
let aheadCount = 0;
|
let aheadCount = 0;
|
||||||
let behindCount = 0;
|
let behindCount = 0;
|
||||||
let hasWorkingTreeChanges = false;
|
let hasWorkingTreeChanges = false;
|
||||||
const changedFilesWithoutNumstat = new Set<string>();
|
|
||||||
|
|
||||||
for (const line of statusStdout.split(/\r?\n/g)) {
|
for (const line of stdout.split(/\r?\n/g)) {
|
||||||
if (line.startsWith("# branch.head ")) {
|
if (line.startsWith("# branch.head ")) {
|
||||||
const value = line.slice("# branch.head ".length).trim();
|
const value = line.slice("# branch.head ".length).trim();
|
||||||
branch = value.startsWith("(") ? null : value;
|
branch = value.startsWith("(") ? null : value;
|
||||||
@@ -270,45 +208,13 @@ export class GitCoreService {
|
|||||||
}
|
}
|
||||||
if (line.trim().length > 0 && !line.startsWith("#")) {
|
if (line.trim().length > 0 && !line.startsWith("#")) {
|
||||||
hasWorkingTreeChanges = true;
|
hasWorkingTreeChanges = true;
|
||||||
const pathValue = parsePorcelainPath(line);
|
|
||||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
|
||||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
|
||||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
|
||||||
for (const entry of [...stagedEntries, ...unstagedEntries]) {
|
|
||||||
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
|
|
||||||
existing.insertions += entry.insertions;
|
|
||||||
existing.deletions += entry.deletions;
|
|
||||||
fileStatMap.set(entry.path, existing);
|
|
||||||
}
|
|
||||||
|
|
||||||
let insertions = 0;
|
|
||||||
let deletions = 0;
|
|
||||||
const files = Array.from(fileStatMap.entries())
|
|
||||||
.map(([path, stat]) => {
|
|
||||||
insertions += stat.insertions;
|
|
||||||
deletions += stat.deletions;
|
|
||||||
return { path, insertions: stat.insertions, deletions: stat.deletions };
|
|
||||||
})
|
|
||||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
|
||||||
|
|
||||||
for (const filePath of changedFilesWithoutNumstat) {
|
|
||||||
if (fileStatMap.has(filePath)) continue;
|
|
||||||
files.push({ path: filePath, insertions: 0, deletions: 0 });
|
|
||||||
}
|
|
||||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
branch,
|
branch,
|
||||||
upstreamRef,
|
upstreamRef,
|
||||||
hasWorkingTreeChanges,
|
hasWorkingTreeChanges,
|
||||||
workingTree: {
|
|
||||||
files,
|
|
||||||
insertions,
|
|
||||||
deletions,
|
|
||||||
},
|
|
||||||
hasUpstream: upstreamRef !== null,
|
hasUpstream: upstreamRef !== null,
|
||||||
aheadCount,
|
aheadCount,
|
||||||
behindCount,
|
behindCount,
|
||||||
@@ -318,12 +224,21 @@ export class GitCoreService {
|
|||||||
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
|
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
|
||||||
await this.git(cwd, ["add", "-A"]);
|
await this.git(cwd, ["add", "-A"]);
|
||||||
|
|
||||||
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
|
const stagedSummary = await this.gitStdout(cwd, [
|
||||||
|
"diff",
|
||||||
|
"--cached",
|
||||||
|
"--name-status",
|
||||||
|
]);
|
||||||
if (trimStdout(stagedSummary).length === 0) {
|
if (trimStdout(stagedSummary).length === 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
|
const stagedPatch = await this.gitStdout(cwd, [
|
||||||
|
"diff",
|
||||||
|
"--cached",
|
||||||
|
"--patch",
|
||||||
|
"--minimal",
|
||||||
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stagedSummary,
|
stagedSummary,
|
||||||
@@ -376,29 +291,6 @@ export class GitCoreService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
|
|
||||||
const details = await this.statusDetails(cwd);
|
|
||||||
const branch = details.branch;
|
|
||||||
if (!branch) {
|
|
||||||
throw new Error("Cannot pull from detached HEAD.");
|
|
||||||
}
|
|
||||||
if (!details.hasUpstream) {
|
|
||||||
throw new Error("Current branch has no upstream configured. Push with upstream first.");
|
|
||||||
}
|
|
||||||
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
|
|
||||||
await executeGit(cwd, ["pull", "--ff-only"], {
|
|
||||||
timeoutMs: 30_000,
|
|
||||||
fallbackErrorMessage: "git pull failed",
|
|
||||||
});
|
|
||||||
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
|
|
||||||
const refreshed = await this.statusDetails(cwd);
|
|
||||||
return gitPullResultSchema.parse({
|
|
||||||
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
|
|
||||||
branch,
|
|
||||||
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
|
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
|
||||||
const range = `${baseBranch}..HEAD`;
|
const range = `${baseBranch}..HEAD`;
|
||||||
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
|
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
|
||||||
@@ -420,40 +312,7 @@ export class GitCoreService {
|
|||||||
return value.length > 0 ? value : null;
|
return value.length > 0 ? value : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
|
|
||||||
const branchRecency = await executeGit(
|
|
||||||
cwd,
|
|
||||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
|
||||||
{
|
|
||||||
timeoutMs: 15_000,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const branchLastCommit = new Map<string, number>();
|
|
||||||
if (branchRecency.code !== 0) {
|
|
||||||
return branchLastCommit;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const line of branchRecency.stdout.split("\n")) {
|
|
||||||
if (line.length === 0) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const [name, lastCommitRaw] = line.split("\t");
|
|
||||||
if (!name) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
|
||||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
return branchLastCommit;
|
|
||||||
}
|
|
||||||
|
|
||||||
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||||
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
|
|
||||||
() => new Map<string, number>(),
|
|
||||||
);
|
|
||||||
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
@@ -467,7 +326,7 @@ export class GitCoreService {
|
|||||||
throw new Error(stderr || "git branch failed");
|
throw new Error(stderr || "git branch failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
|
const [defaultRef, worktreeList] = await Promise.all([
|
||||||
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
@@ -476,7 +335,6 @@ export class GitCoreService {
|
|||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
}),
|
}),
|
||||||
branchRecencyPromise,
|
|
||||||
]);
|
]);
|
||||||
const defaultBranch =
|
const defaultBranch =
|
||||||
defaultRef.code === 0
|
defaultRef.code === 0
|
||||||
@@ -512,13 +370,8 @@ export class GitCoreService {
|
|||||||
};
|
};
|
||||||
})
|
})
|
||||||
.toSorted((a, b) => {
|
.toSorted((a, b) => {
|
||||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
if (a.current !== b.current) return a.current ? -1 : 1;
|
||||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
|
||||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
|
||||||
|
|
||||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
|
||||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
|
||||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
|
||||||
return a.name.localeCompare(b.name);
|
return a.name.localeCompare(b.name);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -559,92 +412,11 @@ export class GitCoreService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveCurrentUpstream(
|
|
||||||
cwd: string,
|
|
||||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
|
||||||
const upstreamRef = trimStdout(
|
|
||||||
await this.gitStdout(
|
|
||||||
cwd,
|
|
||||||
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
|
|
||||||
true,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const separatorIndex = upstreamRef.indexOf("/");
|
|
||||||
if (separatorIndex <= 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
|
||||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
|
||||||
if (remoteName.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
|
||||||
const now = Date.now();
|
|
||||||
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> {
|
||||||
await executeGit(input.cwd, ["checkout", input.branch], {
|
await executeGit(input.cwd, ["checkout", input.branch], {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
fallbackErrorMessage: "git checkout failed",
|
fallbackErrorMessage: "git checkout failed",
|
||||||
});
|
});
|
||||||
// Refresh upstream refs in the background so checkout remains responsive.
|
|
||||||
void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async initRepo(input: GitInitInput): Promise<void> {
|
async initRepo(input: GitInitInput): Promise<void> {
|
||||||
@@ -700,11 +472,6 @@ export async function listGitBranches(input: GitListBranchesInput): Promise<GitL
|
|||||||
return defaultGitCoreService.listBranches(input);
|
return defaultGitCoreService.listBranches(input);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
|
|
||||||
const input = gitPullInputSchema.parse(raw);
|
|
||||||
return defaultGitCoreService.pullCurrentBranch(input.cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function createGitWorktree(
|
export async function createGitWorktree(
|
||||||
input: GitCreateWorktreeInput,
|
input: GitCreateWorktreeInput,
|
||||||
): Promise<GitCreateWorktreeResult> {
|
): Promise<GitCreateWorktreeResult> {
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ import path from "node:path";
|
|||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { GitManager } from "./gitManager";
|
import { GitManager } from "./gitManager";
|
||||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
import {
|
||||||
|
type ProcessRunOptions,
|
||||||
|
type ProcessRunResult,
|
||||||
|
runProcess,
|
||||||
|
} from "./processRunner";
|
||||||
|
|
||||||
interface FakeGhScenario {
|
interface FakeGhScenario {
|
||||||
prListSequence?: string[];
|
prListSequence?: string[];
|
||||||
@@ -67,7 +71,9 @@ async function createBareRemote(): Promise<string> {
|
|||||||
return remoteDir;
|
return remoteDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
|
function createTextGenerator(
|
||||||
|
overrides: Partial<FakeGitTextGenerator> = {},
|
||||||
|
): FakeGitTextGenerator {
|
||||||
return {
|
return {
|
||||||
generateCommitMessage: async () => ({
|
generateCommitMessage: async () => ({
|
||||||
subject: "Implement stacked git actions",
|
subject: "Implement stacked git actions",
|
||||||
@@ -120,7 +126,8 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
|
|||||||
if (args[0] === "pr" && args[1] === "create") {
|
if (args[0] === "pr" && args[1] === "create") {
|
||||||
return {
|
return {
|
||||||
stdout:
|
stdout:
|
||||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
(scenario.createdPrUrl ??
|
||||||
|
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||||
stderr: "",
|
stderr: "",
|
||||||
code: 0,
|
code: 0,
|
||||||
signal: null,
|
signal: null,
|
||||||
@@ -336,7 +343,7 @@ describe("GitManager", () => {
|
|||||||
expect(result.push.status).toBe("skipped_up_to_date");
|
expect(result.push.status).toBe("skipped_up_to_date");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns existing PR metadata for commit/push/pr action", async () => {
|
it("opens existing PR for commit/push/pr action", async () => {
|
||||||
const repoDir = makeTempDir("t3code-git-manager-");
|
const repoDir = makeTempDir("t3code-git-manager-");
|
||||||
await initRepo(repoDir);
|
await initRepo(repoDir);
|
||||||
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
||||||
@@ -369,7 +376,9 @@ describe("GitManager", () => {
|
|||||||
|
|
||||||
expect(result.pr.status).toBe("opened_existing");
|
expect(result.pr.status).toBe("opened_existing");
|
||||||
expect(result.pr.number).toBe(42);
|
expect(result.pr.number).toBe(42);
|
||||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
expect(
|
||||||
|
ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web")),
|
||||||
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates PR when one does not already exist", async () => {
|
it("creates PR when one does not already exist", async () => {
|
||||||
@@ -413,7 +422,6 @@ describe("GitManager", () => {
|
|||||||
expect(
|
expect(
|
||||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rejects push/pr actions from detached HEAD", async () => {
|
it("rejects push/pr actions from detached HEAD", async () => {
|
||||||
|
|||||||
@@ -20,7 +20,11 @@ import type {
|
|||||||
} from "./coreServices";
|
} from "./coreServices";
|
||||||
import { CodexTextGenerator } from "./codexTextGenerator";
|
import { CodexTextGenerator } from "./codexTextGenerator";
|
||||||
import { GitCoreService } from "./git";
|
import { GitCoreService } from "./git";
|
||||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
import {
|
||||||
|
type ProcessRunOptions,
|
||||||
|
type ProcessRunResult,
|
||||||
|
runProcess,
|
||||||
|
} from "./processRunner";
|
||||||
|
|
||||||
const GH_CLI_TIMEOUT_MS = 30_000;
|
const GH_CLI_TIMEOUT_MS = 30_000;
|
||||||
|
|
||||||
@@ -54,7 +58,11 @@ function parseOpenPrList(raw: unknown): OpenPrInfo[] {
|
|||||||
const url = record.url;
|
const url = record.url;
|
||||||
const baseRefName = record.baseRefName;
|
const baseRefName = record.baseRefName;
|
||||||
const headRefName = record.headRefName;
|
const headRefName = record.headRefName;
|
||||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
if (
|
||||||
|
typeof number !== "number" ||
|
||||||
|
!Number.isInteger(number) ||
|
||||||
|
number <= 0
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -90,7 +98,8 @@ function sanitizeCommitMessage(
|
|||||||
): CommitMessageGenerationResult {
|
): CommitMessageGenerationResult {
|
||||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||||
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
|
const safeSubject =
|
||||||
|
subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
|
||||||
return {
|
return {
|
||||||
subject: safeSubject,
|
subject: safeSubject,
|
||||||
body: generated.body.trim(),
|
body: generated.body.trim(),
|
||||||
@@ -134,7 +143,10 @@ function extractBranchFromRef(ref: string): string {
|
|||||||
return normalized.slice(firstSlash + 1).trim();
|
return normalized.slice(firstSlash + 1).trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
function asCommandNotFound(command: string, error: unknown): Error | undefined {
|
function asCommandNotFound(
|
||||||
|
command: string,
|
||||||
|
error: unknown,
|
||||||
|
): Error | undefined {
|
||||||
if (!(error instanceof Error)) return undefined;
|
if (!(error instanceof Error)) return undefined;
|
||||||
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
|
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
|
||||||
if (command === "gh") {
|
if (command === "gh") {
|
||||||
@@ -206,7 +218,6 @@ export class GitManager {
|
|||||||
return {
|
return {
|
||||||
branch: details.branch,
|
branch: details.branch,
|
||||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||||
workingTree: details.workingTree,
|
|
||||||
hasUpstream: details.hasUpstream,
|
hasUpstream: details.hasUpstream,
|
||||||
aheadCount: details.aheadCount,
|
aheadCount: details.aheadCount,
|
||||||
behindCount: details.behindCount,
|
behindCount: details.behindCount,
|
||||||
@@ -214,7 +225,9 @@ export class GitManager {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
|
async runStackedAction(
|
||||||
|
raw: GitRunStackedActionInput,
|
||||||
|
): Promise<GitRunStackedActionResult> {
|
||||||
const input = gitRunStackedActionInputSchema.parse(raw);
|
const input = gitRunStackedActionInputSchema.parse(raw);
|
||||||
const wantsPush = input.action !== "commit";
|
const wantsPush = input.action !== "commit";
|
||||||
const wantsPr = input.action === "commit_push_pr";
|
const wantsPr = input.action === "commit_push_pr";
|
||||||
@@ -227,7 +240,11 @@ export class GitManager {
|
|||||||
throw new Error("Cannot create a pull request from detached HEAD.");
|
throw new Error("Cannot create a pull request from detached HEAD.");
|
||||||
}
|
}
|
||||||
|
|
||||||
const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
const commit = await this.runCommitStep(
|
||||||
|
input.cwd,
|
||||||
|
initialStatus.branch,
|
||||||
|
input.commitMessage,
|
||||||
|
);
|
||||||
|
|
||||||
const push = wantsPush
|
const push = wantsPush
|
||||||
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||||
@@ -308,6 +325,7 @@ export class GitManager {
|
|||||||
|
|
||||||
const existing = await this.findOpenPr(cwd, branch);
|
const existing = await this.findOpenPr(cwd, branch);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
|
await this.openPrInBrowser(cwd, branch);
|
||||||
return {
|
return {
|
||||||
status: "opened_existing",
|
status: "opened_existing",
|
||||||
url: existing.url,
|
url: existing.url,
|
||||||
@@ -335,7 +353,10 @@ export class GitManager {
|
|||||||
throw asCommandNotFound("codex", error) ?? error;
|
throw asCommandNotFound("codex", error) ?? error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
const bodyFile = path.join(
|
||||||
|
os.tmpdir(),
|
||||||
|
`t3code-pr-body-${process.pid}-${randomUUID()}.md`,
|
||||||
|
);
|
||||||
await fs.writeFile(bodyFile, generated.body, "utf8");
|
await fs.writeFile(bodyFile, generated.body, "utf8");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -360,6 +381,7 @@ export class GitManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const created = await this.findOpenPr(cwd, branch);
|
const created = await this.findOpenPr(cwd, branch);
|
||||||
|
await this.openPrInBrowser(cwd, branch);
|
||||||
|
|
||||||
if (!created) {
|
if (!created) {
|
||||||
return {
|
return {
|
||||||
@@ -380,7 +402,18 @@ export class GitManager {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
|
private async openPrInBrowser(cwd: string, branch: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.runGh(cwd, ["pr", "view", branch, "--web"]);
|
||||||
|
} catch {
|
||||||
|
// Opening the browser is best-effort.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findOpenPr(
|
||||||
|
cwd: string,
|
||||||
|
branch: string,
|
||||||
|
): Promise<OpenPrInfo | null> {
|
||||||
const stdout = await this.runGhStdout(cwd, [
|
const stdout = await this.runGhStdout(cwd, [
|
||||||
"pr",
|
"pr",
|
||||||
"list",
|
"list",
|
||||||
@@ -413,7 +446,10 @@ export class GitManager {
|
|||||||
branch: string,
|
branch: string,
|
||||||
upstreamRef: string | null,
|
upstreamRef: string | null,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
const configured = await this.gitCore.readConfigValue(
|
||||||
|
cwd,
|
||||||
|
`branch.${branch}.gh-merge-base`,
|
||||||
|
);
|
||||||
if (configured) return configured;
|
if (configured) return configured;
|
||||||
|
|
||||||
if (upstreamRef) {
|
if (upstreamRef) {
|
||||||
@@ -450,7 +486,10 @@ export class GitManager {
|
|||||||
return result.stdout;
|
return result.stdout;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
|
private async runGhCommand(
|
||||||
|
cwd: string,
|
||||||
|
args: readonly string[],
|
||||||
|
): Promise<ProcessRunResult> {
|
||||||
try {
|
try {
|
||||||
return await this.run("gh", args, {
|
return await this.run("gh", args, {
|
||||||
cwd,
|
cwd,
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
|
||||||
@@ -5,15 +5,23 @@ import { runProcess } from "./processRunner";
|
|||||||
describe("runProcess", () => {
|
describe("runProcess", () => {
|
||||||
it("fails when output exceeds max buffer in default mode", async () => {
|
it("fails when output exceeds max buffer in default mode", async () => {
|
||||||
await expect(
|
await expect(
|
||||||
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
|
runProcess(
|
||||||
|
"node",
|
||||||
|
["-e", "process.stdout.write('x'.repeat(2048))"],
|
||||||
|
{ maxBufferBytes: 128 },
|
||||||
|
),
|
||||||
).rejects.toThrow("exceeded stdout buffer limit");
|
).rejects.toThrow("exceeded stdout buffer limit");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("truncates output when outputMode is truncate", async () => {
|
it("truncates output when outputMode is truncate", async () => {
|
||||||
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
|
const result = await runProcess(
|
||||||
maxBufferBytes: 128,
|
"node",
|
||||||
outputMode: "truncate",
|
["-e", "process.stdout.write('x'.repeat(2048))"],
|
||||||
});
|
{
|
||||||
|
maxBufferBytes: 128,
|
||||||
|
outputMode: "truncate",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
expect(result.code).toBe(0);
|
expect(result.code).toBe(0);
|
||||||
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ function commandLabel(command: string, args: readonly string[]): string {
|
|||||||
return [command, ...args].join(" ");
|
return [command, ...args].join(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
function normalizeSpawnError(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
error: unknown,
|
||||||
|
): Error {
|
||||||
if (!(error instanceof Error)) {
|
if (!(error instanceof Error)) {
|
||||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||||
}
|
}
|
||||||
@@ -34,7 +38,9 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
|||||||
return new Error(`Command not found: ${command}`);
|
return new Error(`Command not found: ${command}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
return new Error(
|
||||||
|
`Failed to run ${commandLabel(command, args)}: ${error.message}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeExitError(
|
function normalizeExitError(
|
||||||
@@ -50,11 +56,17 @@ function normalizeExitError(
|
|||||||
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
|
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
|
function normalizeStdinError(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
error: unknown,
|
||||||
|
): Error {
|
||||||
if (!(error instanceof Error)) {
|
if (!(error instanceof Error)) {
|
||||||
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
|
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
|
||||||
}
|
}
|
||||||
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
|
return new Error(
|
||||||
|
`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeBufferError(
|
function normalizeBufferError(
|
||||||
@@ -149,13 +161,22 @@ export async function runProcess(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
|
const appendOutput = (
|
||||||
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
stream: "stdout" | "stderr",
|
||||||
|
chunk: Buffer | string,
|
||||||
|
): Error | null => {
|
||||||
|
const chunkBuffer =
|
||||||
|
typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
||||||
const text = chunkBuffer.toString();
|
const text = chunkBuffer.toString();
|
||||||
const byteLength = chunkBuffer.length;
|
const byteLength = chunkBuffer.length;
|
||||||
if (stream === "stdout") {
|
if (stream === "stdout") {
|
||||||
if (outputMode === "truncate") {
|
if (outputMode === "truncate") {
|
||||||
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
|
const appended = appendChunkWithinLimit(
|
||||||
|
stdout,
|
||||||
|
stdoutBytes,
|
||||||
|
chunkBuffer,
|
||||||
|
maxBufferBytes,
|
||||||
|
);
|
||||||
stdout = appended.next;
|
stdout = appended.next;
|
||||||
stdoutBytes = appended.nextBytes;
|
stdoutBytes = appended.nextBytes;
|
||||||
stdoutTruncated = stdoutTruncated || appended.truncated;
|
stdoutTruncated = stdoutTruncated || appended.truncated;
|
||||||
@@ -168,7 +189,12 @@ export async function runProcess(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (outputMode === "truncate") {
|
if (outputMode === "truncate") {
|
||||||
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
|
const appended = appendChunkWithinLimit(
|
||||||
|
stderr,
|
||||||
|
stderrBytes,
|
||||||
|
chunkBuffer,
|
||||||
|
maxBufferBytes,
|
||||||
|
);
|
||||||
stderr = appended.next;
|
stderr = appended.next;
|
||||||
stderrBytes = appended.nextBytes;
|
stderrBytes = appended.nextBytes;
|
||||||
stderrTruncated = stderrTruncated || appended.truncated;
|
stderrTruncated = stderrTruncated || appended.truncated;
|
||||||
@@ -215,7 +241,10 @@ export async function runProcess(
|
|||||||
};
|
};
|
||||||
|
|
||||||
finalize(() => {
|
finalize(() => {
|
||||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
if (
|
||||||
|
!options.allowNonZeroExit &&
|
||||||
|
(timedOut || (code !== null && code !== 0))
|
||||||
|
) {
|
||||||
reject(normalizeExitError(command, args, result));
|
reject(normalizeExitError(command, args, result));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -41,7 +40,12 @@ function resolveNodePtySpawnHelperPath(): string | null {
|
|||||||
const candidates = [
|
const candidates = [
|
||||||
path.join(packageDir, "build", "Release", "spawn-helper"),
|
path.join(packageDir, "build", "Release", "spawn-helper"),
|
||||||
path.join(packageDir, "build", "Debug", "spawn-helper"),
|
path.join(packageDir, "build", "Debug", "spawn-helper"),
|
||||||
path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"),
|
path.join(
|
||||||
|
packageDir,
|
||||||
|
"prebuilds",
|
||||||
|
`${process.platform}-${process.arch}`,
|
||||||
|
"spawn-helper",
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const candidate of candidates) {
|
for (const candidate of candidates) {
|
||||||
@@ -119,12 +123,15 @@ 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,
|
||||||
env: input.env,
|
env: input.env,
|
||||||
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
|
name:
|
||||||
|
globalThis.process.platform === "win32"
|
||||||
|
? "xterm-color"
|
||||||
|
: "xterm-256color",
|
||||||
});
|
});
|
||||||
return new NodePtyProcess(ptyProcess);
|
return new NodePtyProcess(ptyProcess);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,7 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import {
|
import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput } from "@t3tools/contracts";
|
||||||
DEFAULT_TERMINAL_ID,
|
|
||||||
type TerminalEvent,
|
|
||||||
type TerminalOpenInput,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
|
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
|
||||||
@@ -141,11 +137,7 @@ describe("TerminalManager", () => {
|
|||||||
|
|
||||||
function makeManager(
|
function makeManager(
|
||||||
historyLineLimit = 5,
|
historyLineLimit = 5,
|
||||||
options: {
|
options: { shellResolver?: () => string } = {},
|
||||||
shellResolver?: () => string;
|
|
||||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
|
||||||
subprocessPollIntervalMs?: number;
|
|
||||||
} = {},
|
|
||||||
) {
|
) {
|
||||||
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
||||||
tempDirs.push(logsDir);
|
tempDirs.push(logsDir);
|
||||||
@@ -155,20 +147,13 @@ describe("TerminalManager", () => {
|
|||||||
ptyAdapter,
|
ptyAdapter,
|
||||||
historyLineLimit,
|
historyLineLimit,
|
||||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
|
||||||
...(options.subprocessPollIntervalMs
|
|
||||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
|
||||||
: {}),
|
|
||||||
});
|
});
|
||||||
return { logsDir, ptyAdapter, manager };
|
return { logsDir, ptyAdapter, manager };
|
||||||
}
|
}
|
||||||
|
|
||||||
it("spawns lazily and reuses running terminal per thread", async () => {
|
it("spawns lazily and reuses running terminal per thread", async () => {
|
||||||
const { manager, ptyAdapter } = makeManager();
|
const { manager, ptyAdapter } = makeManager();
|
||||||
const [first, second] = await Promise.all([
|
const [first, second] = await Promise.all([manager.open(openInput()), manager.open(openInput())]);
|
||||||
manager.open(openInput()),
|
|
||||||
manager.open(openInput()),
|
|
||||||
]);
|
|
||||||
const third = await manager.open(openInput());
|
const third = await manager.open(openInput());
|
||||||
|
|
||||||
expect(first.threadId).toBe("thread-1");
|
expect(first.threadId).toBe("thread-1");
|
||||||
@@ -196,65 +181,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" }));
|
||||||
@@ -347,38 +273,6 @@ describe("TerminalManager", () => {
|
|||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("emits subprocess activity events when child-process state changes", async () => {
|
|
||||||
let hasRunningSubprocess = false;
|
|
||||||
const { manager } = makeManager(5, {
|
|
||||||
subprocessChecker: async () => hasRunningSubprocess,
|
|
||||||
subprocessPollIntervalMs: 20,
|
|
||||||
});
|
|
||||||
const events: TerminalEvent[] = [];
|
|
||||||
manager.on("event", (event) => {
|
|
||||||
events.push(event);
|
|
||||||
});
|
|
||||||
|
|
||||||
await manager.open(openInput());
|
|
||||||
await waitFor(() => events.some((event) => event.type === "started"));
|
|
||||||
expect(events.some((event) => event.type === "activity")).toBe(false);
|
|
||||||
|
|
||||||
hasRunningSubprocess = true;
|
|
||||||
await waitFor(
|
|
||||||
() =>
|
|
||||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
|
|
||||||
1_200,
|
|
||||||
);
|
|
||||||
|
|
||||||
hasRunningSubprocess = false;
|
|
||||||
await waitFor(
|
|
||||||
() =>
|
|
||||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
|
|
||||||
1_200,
|
|
||||||
);
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("caps persisted history to configured line limit", async () => {
|
it("caps persisted history to configured line limit", async () => {
|
||||||
const { manager, ptyAdapter } = makeManager(3);
|
const { manager, ptyAdapter } = makeManager(3);
|
||||||
await manager.open(openInput());
|
await manager.open(openInput());
|
||||||
@@ -430,24 +324,25 @@ describe("TerminalManager", () => {
|
|||||||
|
|
||||||
expect(defaultProcess.killed).toBe(true);
|
expect(defaultProcess.killed).toBe(true);
|
||||||
expect(sidecarProcess.killed).toBe(true);
|
expect(sidecarProcess.killed).toBe(true);
|
||||||
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false);
|
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
|
||||||
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false);
|
false,
|
||||||
|
);
|
||||||
|
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => {
|
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
|
||||||
const { manager, logsDir } = makeManager();
|
const { manager, logsDir } = makeManager();
|
||||||
const legacyPath = path.join(logsDir, "thread-1.log");
|
const legacyPath = path.join(logsDir, "thread-1.log");
|
||||||
const nextPath = historyLogPath(logsDir);
|
|
||||||
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
||||||
|
|
||||||
const snapshot = await manager.open(openInput());
|
const snapshot = await manager.open(openInput());
|
||||||
|
|
||||||
expect(snapshot.history).toBe("legacy-line\n");
|
expect(snapshot.history).toBe("legacy-line\n");
|
||||||
expect(fs.existsSync(nextPath)).toBe(true);
|
expect(fs.existsSync(legacyPath)).toBe(true);
|
||||||
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
|
|
||||||
expect(fs.existsSync(legacyPath)).toBe(false);
|
|
||||||
|
|
||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
@@ -473,94 +368,13 @@ describe("TerminalManager", () => {
|
|||||||
} else {
|
} else {
|
||||||
expect(
|
expect(
|
||||||
ptyAdapter.spawnInputs.some((input) =>
|
ptyAdapter.spawnInputs.some((input) =>
|
||||||
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
|
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(
|
||||||
|
input.shell,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("filters app runtime env variables from terminal sessions", async () => {
|
|
||||||
const originalValues = new Map<string, string | undefined>();
|
|
||||||
const setEnv = (key: string, value: string | undefined) => {
|
|
||||||
if (!originalValues.has(key)) {
|
|
||||||
originalValues.set(key, process.env[key]);
|
|
||||||
}
|
|
||||||
if (value === undefined) {
|
|
||||||
delete process.env[key];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
process.env[key] = value;
|
|
||||||
};
|
|
||||||
const restoreEnv = () => {
|
|
||||||
for (const [key, value] of originalValues) {
|
|
||||||
if (value === undefined) {
|
|
||||||
delete process.env[key];
|
|
||||||
} else {
|
|
||||||
process.env[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
setEnv("PORT", "5173");
|
|
||||||
setEnv("T3CODE_PORT", "3773");
|
|
||||||
setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173");
|
|
||||||
setEnv("TEST_TERMINAL_KEEP", "keep-me");
|
|
||||||
|
|
||||||
try {
|
|
||||||
const { manager, ptyAdapter } = makeManager();
|
|
||||||
await manager.open(openInput());
|
|
||||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
|
||||||
expect(spawnInput).toBeDefined();
|
|
||||||
if (!spawnInput) return;
|
|
||||||
|
|
||||||
expect(spawnInput.env.PORT).toBeUndefined();
|
|
||||||
expect(spawnInput.env.T3CODE_PORT).toBeUndefined();
|
|
||||||
expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined();
|
|
||||||
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
|
|
||||||
|
|
||||||
manager.dispose();
|
|
||||||
} finally {
|
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -21,16 +21,9 @@ import {
|
|||||||
|
|
||||||
import { createLogger } from "./logger";
|
import { createLogger } from "./logger";
|
||||||
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
||||||
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_OPEN_COLS = 120;
|
|
||||||
const DEFAULT_OPEN_ROWS = 30;
|
|
||||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
|
||||||
|
|
||||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
|
||||||
|
|
||||||
export interface TerminalManagerEvents {
|
export interface TerminalManagerEvents {
|
||||||
event: [event: TerminalEvent];
|
event: [event: TerminalEvent];
|
||||||
@@ -41,8 +34,6 @@ export interface TerminalManagerOptions {
|
|||||||
historyLineLimit?: number;
|
historyLineLimit?: number;
|
||||||
ptyAdapter?: PtyAdapter;
|
ptyAdapter?: PtyAdapter;
|
||||||
shellResolver?: () => string;
|
shellResolver?: () => string;
|
||||||
subprocessChecker?: TerminalSubprocessChecker;
|
|
||||||
subprocessPollIntervalMs?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalSessionState {
|
interface TerminalSessionState {
|
||||||
@@ -60,17 +51,8 @@ interface TerminalSessionState {
|
|||||||
process: PtyProcess | null;
|
process: PtyProcess | null;
|
||||||
unsubscribeData: (() => void) | null;
|
unsubscribeData: (() => void) | null;
|
||||||
unsubscribeExit: (() => void) | null;
|
unsubscribeExit: (() => void) | null;
|
||||||
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 +74,39 @@ 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,
|
requested,
|
||||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
process.env.ComSpec ?? null,
|
||||||
shellCandidateFromCommand("powershell.exe"),
|
"powershell.exe",
|
||||||
shellCandidateFromCommand("cmd.exe"),
|
"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",
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,83 +122,6 @@ function isRetryableShellSpawnError(error: unknown): boolean {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
|
|
||||||
const command = [
|
|
||||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
|
||||||
"if ($children) { exit 0 }",
|
|
||||||
"exit 1",
|
|
||||||
].join("; ");
|
|
||||||
try {
|
|
||||||
const result = await runProcess(
|
|
||||||
"powershell.exe",
|
|
||||||
["-NoProfile", "-NonInteractive", "-Command", command],
|
|
||||||
{
|
|
||||||
timeoutMs: 1_500,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
maxBufferBytes: 32_768,
|
|
||||||
outputMode: "truncate",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return result.code === 0;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
|
|
||||||
timeoutMs: 1_000,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
maxBufferBytes: 32_768,
|
|
||||||
outputMode: "truncate",
|
|
||||||
});
|
|
||||||
if (pgrepResult.code === 0) {
|
|
||||||
return pgrepResult.stdout.trim().length > 0;
|
|
||||||
}
|
|
||||||
if (pgrepResult.code === 1) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Fall back to ps when pgrep is unavailable.
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
|
|
||||||
timeoutMs: 1_000,
|
|
||||||
allowNonZeroExit: true,
|
|
||||||
maxBufferBytes: 262_144,
|
|
||||||
outputMode: "truncate",
|
|
||||||
});
|
|
||||||
if (psResult.code !== 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const line of psResult.stdout.split(/\r?\n/g)) {
|
|
||||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
|
||||||
const pid = Number(pidRaw);
|
|
||||||
const ppid = Number(ppidRaw);
|
|
||||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
|
||||||
if (ppid === terminalPid) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
|
||||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (process.platform === "win32") {
|
|
||||||
return checkWindowsSubprocessActivity(terminalPid);
|
|
||||||
}
|
|
||||||
return checkPosixSubprocessActivity(terminalPid);
|
|
||||||
}
|
|
||||||
|
|
||||||
function capHistory(history: string, maxLines: number): string {
|
function capHistory(history: string, maxLines: number): string {
|
||||||
if (history.length === 0) return history;
|
if (history.length === 0) return history;
|
||||||
const hasTrailingNewline = history.endsWith("\n");
|
const hasTrailingNewline = history.endsWith("\n");
|
||||||
@@ -260,44 +150,6 @@ function toSessionKey(threadId: string, terminalId: string): string {
|
|||||||
return `${threadId}\u0000${terminalId}`;
|
return `${threadId}\u0000${terminalId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldExcludeTerminalEnvKey(key: string): boolean {
|
|
||||||
const normalizedKey = key.toUpperCase();
|
|
||||||
if (normalizedKey.startsWith("T3CODE_")) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (normalizedKey.startsWith("VITE_")) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
function createTerminalSpawnEnv(
|
|
||||||
baseEnv: NodeJS.ProcessEnv,
|
|
||||||
runtimeEnv?: Record<string, string> | null,
|
|
||||||
): NodeJS.ProcessEnv {
|
|
||||||
const spawnEnv: NodeJS.ProcessEnv = {};
|
|
||||||
for (const [key, value] of Object.entries(baseEnv)) {
|
|
||||||
if (value === undefined) continue;
|
|
||||||
if (shouldExcludeTerminalEnvKey(key)) continue;
|
|
||||||
spawnEnv[key] = value;
|
|
||||||
}
|
|
||||||
if (runtimeEnv) {
|
|
||||||
for (const [key, value] of Object.entries(runtimeEnv)) {
|
|
||||||
spawnEnv[key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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;
|
||||||
@@ -309,10 +161,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
private readonly pendingPersistHistory = new Map<string, string>();
|
private readonly pendingPersistHistory = new Map<string, string>();
|
||||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||||
private readonly persistDebounceMs: number;
|
private readonly persistDebounceMs: number;
|
||||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
|
||||||
private readonly subprocessPollIntervalMs: number;
|
|
||||||
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
|
|
||||||
private subprocessPollInFlight = false;
|
|
||||||
private readonly logger = createLogger("terminal");
|
private readonly logger = createLogger("terminal");
|
||||||
|
|
||||||
constructor(options: TerminalManagerOptions = {}) {
|
constructor(options: TerminalManagerOptions = {}) {
|
||||||
@@ -322,9 +170,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
||||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
|
||||||
this.subprocessPollIntervalMs =
|
|
||||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
|
||||||
fs.mkdirSync(this.logsDir, { recursive: true });
|
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -338,8 +183,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 +193,36 @@ 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,
|
|
||||||
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 +279,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 +289,21 @@ 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,
|
|
||||||
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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -490,7 +312,11 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
const input = terminalCloseInputSchema.parse(raw);
|
const input = terminalCloseInputSchema.parse(raw);
|
||||||
await this.runWithThreadLock(input.threadId, async () => {
|
await this.runWithThreadLock(input.threadId, async () => {
|
||||||
if (input.terminalId) {
|
if (input.terminalId) {
|
||||||
await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
|
await this.closeSession(
|
||||||
|
input.threadId,
|
||||||
|
input.terminalId,
|
||||||
|
input.deleteHistory === true,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -508,17 +334,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
if (input.deleteHistory) {
|
if (input.deleteHistory) {
|
||||||
await this.deleteAllHistoryForThread(input.threadId);
|
await this.deleteAllHistoryForThread(input.threadId);
|
||||||
}
|
}
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
dispose(): void {
|
dispose(): void {
|
||||||
this.stopSubprocessPolling();
|
for (const session of this.sessions.values()) {
|
||||||
const sessions = [...this.sessions.values()];
|
|
||||||
this.sessions.clear();
|
|
||||||
for (const session of sessions) {
|
|
||||||
this.stopProcess(session);
|
this.stopProcess(session);
|
||||||
}
|
}
|
||||||
|
this.sessions.clear();
|
||||||
for (const timer of this.persistTimers.values()) {
|
for (const timer of this.persistTimers.values()) {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
}
|
}
|
||||||
@@ -530,7 +353,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);
|
||||||
@@ -541,27 +364,24 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.rows = input.rows;
|
session.rows = input.rows;
|
||||||
session.exitCode = null;
|
session.exitCode = null;
|
||||||
session.exitSignal = null;
|
session.exitSignal = null;
|
||||||
session.hasRunningSubprocess = false;
|
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
|
|
||||||
let ptyProcess: PtyProcess | null = null;
|
let ptyProcess: PtyProcess | null = null;
|
||||||
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);
|
|
||||||
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: process.env,
|
||||||
});
|
});
|
||||||
startedShell = formatShellCandidate(candidate);
|
startedShell = shell;
|
||||||
break;
|
break;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastSpawnError = error;
|
lastSpawnError = error;
|
||||||
@@ -573,10 +393,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
|
|
||||||
if (!ptyProcess) {
|
if (!ptyProcess) {
|
||||||
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.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
|
? ` Tried shells: ${shellCandidates.join(", ")}.`
|
||||||
: "";
|
: "";
|
||||||
throw new Error(`${detail}.${tried}`.trim());
|
throw new Error(`${detail}.${tried}`.trim());
|
||||||
}
|
}
|
||||||
@@ -591,7 +413,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
||||||
this.onProcessExit(session, event);
|
this.onProcessExit(session, event);
|
||||||
});
|
});
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
type: eventType,
|
type: eventType,
|
||||||
threadId: session.threadId,
|
threadId: session.threadId,
|
||||||
@@ -610,9 +431,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
session.status = "error";
|
session.status = "error";
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
session.process = null;
|
session.process = null;
|
||||||
session.hasRunningSubprocess = false;
|
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
const message = error instanceof Error ? error.message : "Terminal start failed";
|
const message = error instanceof Error ? error.message : "Terminal start failed";
|
||||||
this.emitEvent({
|
this.emitEvent({
|
||||||
type: "error",
|
type: "error",
|
||||||
@@ -647,7 +466,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.cleanupProcessHandles(session);
|
this.cleanupProcessHandles(session);
|
||||||
session.process = null;
|
session.process = null;
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
session.hasRunningSubprocess = false;
|
|
||||||
session.status = "exited";
|
session.status = "exited";
|
||||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||||
@@ -660,7 +478,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
exitCode: session.exitCode,
|
exitCode: session.exitCode,
|
||||||
exitSignal: session.exitSignal,
|
exitSignal: session.exitSignal,
|
||||||
});
|
});
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private stopProcess(session: TerminalSessionState): void {
|
private stopProcess(session: TerminalSessionState): void {
|
||||||
@@ -669,7 +486,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.cleanupProcessHandles(session);
|
this.cleanupProcessHandles(session);
|
||||||
session.process = null;
|
session.process = null;
|
||||||
session.pid = null;
|
session.pid = null;
|
||||||
session.hasRunningSubprocess = false;
|
|
||||||
session.status = "exited";
|
session.status = "exited";
|
||||||
session.updatedAt = new Date().toISOString();
|
session.updatedAt = new Date().toISOString();
|
||||||
try {
|
try {
|
||||||
@@ -682,7 +498,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
error: message,
|
error: message,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private cleanupProcessHandles(session: TerminalSessionState): void {
|
private cleanupProcessHandles(session: TerminalSessionState): void {
|
||||||
@@ -767,12 +582,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
||||||
const nextPath = this.historyPath(threadId, terminalId);
|
const historyPath = this.historyPath(threadId, terminalId);
|
||||||
try {
|
try {
|
||||||
const raw = await fs.promises.readFile(nextPath, "utf8");
|
const raw = await fs.promises.readFile(historyPath, "utf8");
|
||||||
const capped = capHistory(raw, this.historyLineLimit);
|
const capped = capHistory(raw, this.historyLineLimit);
|
||||||
if (capped !== raw) {
|
if (capped !== raw) {
|
||||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
await fs.promises.writeFile(historyPath, capped, "utf8");
|
||||||
}
|
}
|
||||||
return capped;
|
return capped;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -785,22 +600,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
const legacyPath = this.legacyHistoryPath(threadId);
|
|
||||||
try {
|
try {
|
||||||
const raw = await fs.promises.readFile(legacyPath, "utf8");
|
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
|
||||||
const capped = capHistory(raw, this.historyLineLimit);
|
const capped = capHistory(raw, this.historyLineLimit);
|
||||||
|
if (capped !== raw) {
|
||||||
// Migrate legacy transcript filename to the terminal-scoped path.
|
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
|
||||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
|
||||||
try {
|
|
||||||
await fs.promises.rm(legacyPath, { force: true });
|
|
||||||
} catch (cleanupError) {
|
|
||||||
this.logger.warn("failed to remove legacy terminal history", {
|
|
||||||
threadId,
|
|
||||||
error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return capped;
|
return capped;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||||
@@ -845,86 +650,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateSubprocessPollingState(): void {
|
|
||||||
const hasRunningSessions = [...this.sessions.values()].some(
|
|
||||||
(session) => session.status === "running" && session.pid !== null,
|
|
||||||
);
|
|
||||||
if (hasRunningSessions) {
|
|
||||||
this.ensureSubprocessPolling();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.stopSubprocessPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
private ensureSubprocessPolling(): void {
|
|
||||||
if (this.subprocessPollTimer) return;
|
|
||||||
this.subprocessPollTimer = setInterval(() => {
|
|
||||||
void this.pollSubprocessActivity();
|
|
||||||
}, this.subprocessPollIntervalMs);
|
|
||||||
this.subprocessPollTimer.unref?.();
|
|
||||||
void this.pollSubprocessActivity();
|
|
||||||
}
|
|
||||||
|
|
||||||
private stopSubprocessPolling(): void {
|
|
||||||
if (!this.subprocessPollTimer) return;
|
|
||||||
clearInterval(this.subprocessPollTimer);
|
|
||||||
this.subprocessPollTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async pollSubprocessActivity(): Promise<void> {
|
|
||||||
if (this.subprocessPollInFlight) return;
|
|
||||||
|
|
||||||
const runningSessions = [...this.sessions.values()].filter(
|
|
||||||
(session): session is TerminalSessionState & { pid: number } =>
|
|
||||||
session.status === "running" && Number.isInteger(session.pid),
|
|
||||||
);
|
|
||||||
if (runningSessions.length === 0) {
|
|
||||||
this.stopSubprocessPolling();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.subprocessPollInFlight = true;
|
|
||||||
try {
|
|
||||||
await Promise.all(
|
|
||||||
runningSessions.map(async (session) => {
|
|
||||||
const terminalPid = session.pid;
|
|
||||||
let hasRunningSubprocess = false;
|
|
||||||
try {
|
|
||||||
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
|
|
||||||
} catch (error) {
|
|
||||||
this.logger.warn("failed to check terminal subprocess activity", {
|
|
||||||
threadId: session.threadId,
|
|
||||||
terminalId: session.terminalId,
|
|
||||||
terminalPid,
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
|
|
||||||
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
liveSession.hasRunningSubprocess = hasRunningSubprocess;
|
|
||||||
liveSession.updatedAt = new Date().toISOString();
|
|
||||||
this.emitEvent({
|
|
||||||
type: "activity",
|
|
||||||
threadId: liveSession.threadId,
|
|
||||||
terminalId: liveSession.terminalId,
|
|
||||||
createdAt: new Date().toISOString(),
|
|
||||||
hasRunningSubprocess,
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
this.subprocessPollInFlight = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async assertValidCwd(cwd: string): Promise<void> {
|
private async assertValidCwd(cwd: string): Promise<void> {
|
||||||
let stats: fs.Stats;
|
let stats: fs.Stats;
|
||||||
try {
|
try {
|
||||||
@@ -951,7 +676,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
this.stopProcess(session);
|
this.stopProcess(session);
|
||||||
this.sessions.delete(key);
|
this.sessions.delete(key);
|
||||||
}
|
}
|
||||||
this.updateSubprocessPollingState();
|
|
||||||
await this.flushPersistQueue(threadId, terminalId);
|
await this.flushPersistQueue(threadId, terminalId);
|
||||||
if (deleteHistory) {
|
if (deleteHistory) {
|
||||||
await this.deleteHistory(threadId, terminalId);
|
await this.deleteHistory(threadId, terminalId);
|
||||||
@@ -1023,7 +747,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
|||||||
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
|
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
|
private async runWithThreadLock<T>(
|
||||||
|
threadId: string,
|
||||||
|
task: () => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
|
||||||
let release: () => void = () => {};
|
let release: () => void = () => {};
|
||||||
const current = new Promise<void>((resolve) => {
|
const current = new Promise<void>((resolve) => {
|
||||||
|
|||||||
@@ -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[] = [];
|
||||||
@@ -253,7 +224,9 @@ describe("WebSocket Server", () => {
|
|||||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||||
projectRegistry: new ProjectRegistry(stateDir),
|
projectRegistry: new ProjectRegistry(stateDir),
|
||||||
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
|
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
|
||||||
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
|
...(options.terminalManager
|
||||||
|
? { terminalManager: options.terminalManager }
|
||||||
|
: {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,8 +296,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 +309,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 +346,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 +511,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 +521,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-");
|
||||||
|
|
||||||
@@ -945,11 +545,6 @@ describe("WebSocket Server", () => {
|
|||||||
});
|
});
|
||||||
expect(afterInit.error).toBeUndefined();
|
expect(afterInit.error).toBeUndefined();
|
||||||
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
|
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
|
||||||
|
|
||||||
const pullResponse = await sendRequest(ws, WS_METHODS.gitPull, { cwd: repoCwd });
|
|
||||||
expect(pullResponse.result).toBeUndefined();
|
|
||||||
expect(pullResponse.error?.message).toBeDefined();
|
|
||||||
expect(pullResponse.error?.message).not.toContain("Unknown method");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("responds to git.status via the git manager", async () => {
|
it("responds to git.status via the git manager", async () => {
|
||||||
@@ -957,11 +552,6 @@ describe("WebSocket Server", () => {
|
|||||||
status: vi.fn().mockResolvedValue({
|
status: vi.fn().mockResolvedValue({
|
||||||
branch: "feature/test",
|
branch: "feature/test",
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
workingTree: {
|
|
||||||
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
|
|
||||||
insertions: 7,
|
|
||||||
deletions: 2,
|
|
||||||
},
|
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
@@ -986,11 +576,6 @@ describe("WebSocket Server", () => {
|
|||||||
expect(response.result).toEqual({
|
expect(response.result).toEqual({
|
||||||
branch: "feature/test",
|
branch: "feature/test",
|
||||||
hasWorkingTreeChanges: true,
|
hasWorkingTreeChanges: true,
|
||||||
workingTree: {
|
|
||||||
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
|
|
||||||
insertions: 7,
|
|
||||||
deletions: 2,
|
|
||||||
},
|
|
||||||
hasUpstream: false,
|
hasUpstream: false,
|
||||||
aheadCount: 0,
|
aheadCount: 0,
|
||||||
behindCount: 0,
|
behindCount: 0,
|
||||||
@@ -1002,7 +587,9 @@ describe("WebSocket Server", () => {
|
|||||||
it("returns errors from git.runStackedAction", async () => {
|
it("returns errors from git.runStackedAction", async () => {
|
||||||
const gitManager = {
|
const gitManager = {
|
||||||
status: vi.fn(),
|
status: vi.fn(),
|
||||||
runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),
|
runStackedAction: vi
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error("Cannot push from detached HEAD.")),
|
||||||
};
|
};
|
||||||
|
|
||||||
server = createTestServer({ cwd: "/test", gitManager });
|
server = createTestServer({ cwd: "/test", gitManager });
|
||||||
|
|||||||
@@ -27,12 +27,9 @@ import {
|
|||||||
createGitWorktree,
|
createGitWorktree,
|
||||||
initGitRepo,
|
initGitRepo,
|
||||||
listGitBranches,
|
listGitBranches,
|
||||||
pullGitBranch,
|
|
||||||
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 +89,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 +306,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 +316,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;
|
||||||
@@ -342,32 +324,11 @@ export function createServer(options: ServerOptions) {
|
|||||||
if (!params?.cwd) throw new Error("cwd is required");
|
if (!params?.cwd) throw new Error("cwd is required");
|
||||||
const editorDef = EDITORS.find((e) => e.id === params.editor);
|
const editorDef = EDITORS.find((e) => e.id === params.editor);
|
||||||
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
|
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
|
||||||
|
if (!editorDef.command) {
|
||||||
let command: string;
|
// Can't open file manager programmatically from server, just succeed silently
|
||||||
let args: string[];
|
|
||||||
|
|
||||||
if (editorDef.command) {
|
|
||||||
command = editorDef.command;
|
|
||||||
args = [params.cwd];
|
|
||||||
} else if (editorDef.id === "file-manager") {
|
|
||||||
// Use platform-specific file manager command
|
|
||||||
switch (process.platform) {
|
|
||||||
case "darwin":
|
|
||||||
command = "open";
|
|
||||||
break;
|
|
||||||
case "win32":
|
|
||||||
command = "explorer";
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
command = "xdg-open";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
args = [params.cwd];
|
|
||||||
} else {
|
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
const child = spawn(editorDef.command, [params.cwd], {
|
||||||
const child = spawn(command, args, {
|
|
||||||
detached: true,
|
detached: true,
|
||||||
stdio: "ignore",
|
stdio: "ignore",
|
||||||
});
|
});
|
||||||
@@ -381,9 +342,6 @@ export function createServer(options: ServerOptions) {
|
|||||||
case WS_METHODS.gitStatus:
|
case WS_METHODS.gitStatus:
|
||||||
return gitManager.status(request.params as never);
|
return gitManager.status(request.params as never);
|
||||||
|
|
||||||
case WS_METHODS.gitPull:
|
|
||||||
return pullGitBranch(request.params as never);
|
|
||||||
|
|
||||||
case WS_METHODS.gitRunStackedAction:
|
case WS_METHODS.gitRunStackedAction:
|
||||||
return gitManager.runStackedAction(request.params as never);
|
return gitManager.runStackedAction(request.params as never);
|
||||||
case WS_METHODS.gitListBranches:
|
case WS_METHODS.gitListBranches:
|
||||||
@@ -427,16 +385,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}`);
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://ui.shadcn.com/schema.json",
|
|
||||||
"style": "base-mira",
|
|
||||||
"rsc": false,
|
|
||||||
"tsx": true,
|
|
||||||
"tailwind": {
|
|
||||||
"config": "",
|
|
||||||
"css": "src/index.css",
|
|
||||||
"baseColor": "zinc",
|
|
||||||
"cssVariables": true,
|
|
||||||
"prefix": ""
|
|
||||||
},
|
|
||||||
"iconLibrary": "lucide",
|
|
||||||
"rtl": false,
|
|
||||||
"menuColor": "default",
|
|
||||||
"menuAccent": "bold",
|
|
||||||
"aliases": {
|
|
||||||
"components": "~/components",
|
|
||||||
"utils": "~/lib/utils",
|
|
||||||
"ui": "~/components/ui",
|
|
||||||
"lib": "~/lib",
|
|
||||||
"hooks": "~/hooks"
|
|
||||||
},
|
|
||||||
"registries": {
|
|
||||||
"@coss": "https://coss.com/ui/r/{name}.json"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -11,22 +11,17 @@
|
|||||||
"test": "vitest run --passWithNoTests"
|
"test": "vitest run --passWithNoTests"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.2.0",
|
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
|
||||||
"@t3tools/contracts": "workspace:*",
|
|
||||||
"@tanstack/react-pacer": "^0.19.4",
|
|
||||||
"@tanstack/react-query": "^5.90.0",
|
|
||||||
"@xterm/addon-fit": "^0.11.0",
|
"@xterm/addon-fit": "^0.11.0",
|
||||||
"@xterm/xterm": "^6.0.0",
|
"@xterm/xterm": "^6.0.0",
|
||||||
"class-variance-authority": "^0.7.1",
|
"@t3tools/contracts": "workspace:*",
|
||||||
|
"@tanstack/react-query": "^5.90.0",
|
||||||
"highlight.js": "^11.11.1",
|
"highlight.js": "^11.11.1",
|
||||||
"lucide-react": "^0.564.0",
|
"lucide-react": "^0.563.0",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"rehype-highlight": "^7.0.2",
|
"rehype-highlight": "^7.0.2",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"tailwind-merge": "^3.4.0",
|
|
||||||
"zod": "^3.24.1"
|
"zod": "^3.24.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
+6
-90
@@ -1,7 +1,8 @@
|
|||||||
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } 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,78 +10,21 @@ 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 { Sheet, SheetPopup } from "./components/ui/sheet";
|
|
||||||
import { invalidateGitQueries } from "./lib/gitReactQuery";
|
|
||||||
|
|
||||||
const DiffPanel = lazy(() => import("./components/DiffPanel"));
|
|
||||||
const DiffWorkerPoolProvider = lazy(() =>
|
|
||||||
import("./components/DiffPanel").then((module) => ({
|
|
||||||
default: module.DiffWorkerPoolProvider,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
const DIFF_INLINE_LAYOUT_MEDIA_QUERY = "(max-width: 1180px)";
|
|
||||||
|
|
||||||
const DiffPanelWrapper = (props: { children: React.ReactNode; sheet: boolean }) => {
|
|
||||||
const { state, dispatch } = useStore();
|
|
||||||
if (props.sheet) {
|
|
||||||
return (
|
|
||||||
<Sheet
|
|
||||||
open={state.diffOpen}
|
|
||||||
onOpenChange={(open) => {
|
|
||||||
if (!open) {
|
|
||||||
dispatch({ type: "CLOSE_DIFF" });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<SheetPopup
|
|
||||||
side="right"
|
|
||||||
showCloseButton={false}
|
|
||||||
keepMounted
|
|
||||||
className="w-[min(88vw,820px)] max-w-[820px] p-0"
|
|
||||||
>
|
|
||||||
{props.children}
|
|
||||||
</SheetPopup>
|
|
||||||
</Sheet>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<aside className={state.diffOpen ? undefined : "hidden"} aria-hidden={!state.diffOpen}>
|
|
||||||
{props.children}
|
|
||||||
</aside>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
function EventRouter() {
|
function EventRouter() {
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
const { dispatch } = useStore();
|
const { dispatch } = useStore();
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const activeAssistantItemRef = useRef<string | null>(null);
|
const activeAssistantItemRef = useRef<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!api) return;
|
if (!api) return;
|
||||||
return api.providers.onEvent((event) => {
|
return api.providers.onEvent((event) => {
|
||||||
if (event.method === "turn/completed") {
|
|
||||||
void invalidateGitQueries(queryClient);
|
|
||||||
}
|
|
||||||
dispatch({
|
dispatch({
|
||||||
type: "APPLY_EVENT",
|
type: "APPLY_EVENT",
|
||||||
event,
|
event,
|
||||||
activeAssistantItemRef,
|
activeAssistantItemRef,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}, [api, dispatch, queryClient]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!api) return;
|
|
||||||
return api.terminal.onEvent((event) => {
|
|
||||||
dispatch({
|
|
||||||
type: "APPLY_TERMINAL_EVENT",
|
|
||||||
event,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}, [api, dispatch]);
|
}, [api, dispatch]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
@@ -125,7 +69,6 @@ function AutoProjectBootstrap() {
|
|||||||
cwd: payload.cwd,
|
cwd: payload.cwd,
|
||||||
model: DEFAULT_MODEL,
|
model: DEFAULT_MODEL,
|
||||||
expanded: true,
|
expanded: true,
|
||||||
scripts: [],
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
dispatch({
|
dispatch({
|
||||||
@@ -139,7 +82,6 @@ function AutoProjectBootstrap() {
|
|||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
runningTerminalIds: [],
|
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{
|
{
|
||||||
@@ -151,7 +93,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 +129,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 +158,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 (
|
||||||
@@ -242,21 +170,13 @@ function Layout() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen overflow-hidden bg-background text-foreground isolate">
|
<div className="flex h-screen overflow-hidden bg-background text-foreground">
|
||||||
<EventRouter />
|
<EventRouter />
|
||||||
<AutoProjectBootstrap />
|
<AutoProjectBootstrap />
|
||||||
<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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -267,11 +187,7 @@ export default function App() {
|
|||||||
return (
|
return (
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<StoreProvider>
|
<StoreProvider>
|
||||||
<ToastProvider>
|
<Layout />
|
||||||
<AnchoredToastProvider>
|
|
||||||
<Layout />
|
|
||||||
</AnchoredToastProvider>
|
|
||||||
</ToastProvider>
|
|
||||||
</StoreProvider>
|
</StoreProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
@@ -1,106 +1,104 @@
|
|||||||
import type { GitBranch } from "@t3tools/contracts";
|
import type { GitBranch } from "@t3tools/contracts";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { useNativeApi } from "../hooks/useNativeApi";
|
|
||||||
import {
|
|
||||||
gitBranchesQueryOptions,
|
|
||||||
gitCheckoutMutationOptions,
|
|
||||||
gitCreateBranchAndCheckoutMutationOptions,
|
|
||||||
} from "../lib/gitReactQuery";
|
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
import { useNativeApi } from "../hooks/useNativeApi";
|
||||||
import { Button } from "./ui/button";
|
|
||||||
import {
|
|
||||||
Combobox,
|
|
||||||
ComboboxEmpty,
|
|
||||||
ComboboxInput,
|
|
||||||
ComboboxItem,
|
|
||||||
ComboboxList,
|
|
||||||
ComboboxPopup,
|
|
||||||
ComboboxTrigger,
|
|
||||||
} from "./ui/combobox";
|
|
||||||
import { ChevronDownIcon } from "lucide-react";
|
|
||||||
|
|
||||||
interface BranchToolbarProps {
|
interface BranchToolbarProps {
|
||||||
envMode: "local" | "worktree";
|
envMode: "local" | "worktree";
|
||||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
onEnvModeChange: (mode: "local" | "worktree") => void;
|
||||||
envLocked: boolean;
|
envLocked: boolean;
|
||||||
onComposerFocusRequest?: () => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function BranchToolbar({
|
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
|
||||||
envMode,
|
|
||||||
onEnvModeChange,
|
|
||||||
envLocked,
|
|
||||||
onComposerFocusRequest,
|
|
||||||
}: BranchToolbarProps) {
|
|
||||||
const { state, dispatch } = useStore();
|
const { state, dispatch } = useStore();
|
||||||
const api = useNativeApi();
|
const api = useNativeApi();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||||
const [branchQuery, setBranchQuery] = useState("");
|
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||||
|
const [newBranchName, setNewBranchName] = useState("");
|
||||||
|
const branchMenuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
const activeThread = state.threads.find((thread) => thread.id === state.activeThreadId);
|
||||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||||
const activeThreadId = activeThread?.id;
|
const activeThreadId = activeThread?.id;
|
||||||
const activeThreadBranch = activeThread?.branch ?? null;
|
const activeThreadBranch = activeThread?.branch ?? null;
|
||||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
||||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
const branchCwd = activeWorktreePath ?? activeProject?.cwd;
|
||||||
|
|
||||||
// ── Queries ───────────────────────────────────────────────────────────
|
// ── Queries ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const branchesQuery = useQuery(gitBranchesQueryOptions(api, branchCwd));
|
const branchesQuery = useQuery({
|
||||||
|
queryKey: ["git", "branches", branchCwd],
|
||||||
|
queryFn: () => api!.git.listBranches({ cwd: branchCwd! }),
|
||||||
|
enabled: !!api && !!branchCwd,
|
||||||
|
});
|
||||||
|
|
||||||
const branches = branchesQuery.data?.branches ?? [];
|
const branches = branchesQuery.data?.branches ?? [];
|
||||||
const branchNames = branches.map((branch) => branch.name);
|
// Default to true while loading — showing "Initialize git" during a fetch is wrong,
|
||||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
// and worktrees are inherently git repos.
|
||||||
const trimmedBranchQuery = branchQuery.trim();
|
const isRepo = branchesQuery.data?.isRepo ?? !branchesQuery.isLoading;
|
||||||
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
|
|
||||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
|
||||||
const createBranchItemValue = canCreateBranch
|
|
||||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
|
||||||
: null;
|
|
||||||
const branchPickerItems =
|
|
||||||
createBranchItemValue && !hasExactBranchMatch
|
|
||||||
? [...branchNames, createBranchItemValue]
|
|
||||||
: branchNames;
|
|
||||||
// ── Mutations ─────────────────────────────────────────────────────────
|
// ── Mutations ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const checkoutMutation = useMutation(
|
const checkoutMutation = useMutation({
|
||||||
gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
mutationFn: (branch: string) => api!.git.checkout({ cwd: branchCwd!, branch }),
|
||||||
);
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] }),
|
||||||
|
onError: (error) =>
|
||||||
|
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch."),
|
||||||
|
});
|
||||||
|
|
||||||
const createBranchMutation = useMutation(
|
const createBranchMutation = useMutation({
|
||||||
gitCreateBranchAndCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
|
mutationFn: (branch: string) =>
|
||||||
);
|
api!.git
|
||||||
|
.createBranch({ cwd: branchCwd!, branch })
|
||||||
|
.then(() => api!.git.checkout({ cwd: branchCwd!, branch })),
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] }),
|
||||||
|
onError: (error) =>
|
||||||
|
setThreadError(error instanceof Error ? error.message : "Failed to create branch."),
|
||||||
|
});
|
||||||
|
|
||||||
|
const initMutation = useMutation({
|
||||||
|
mutationFn: () => api!.git.init({ cwd: branchCwd! }),
|
||||||
|
onSuccess: () => {
|
||||||
|
setThreadError(null);
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["git", "branches", branchCwd] });
|
||||||
|
},
|
||||||
|
onError: (error) =>
|
||||||
|
setThreadError(error instanceof Error ? error.message : "Failed to initialize git repo."),
|
||||||
|
});
|
||||||
|
|
||||||
// ── 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;
|
||||||
setBranchQuery("");
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
if (!branchMenuRef.current) return;
|
||||||
|
if (event.target instanceof Node && !branchMenuRef.current.contains(event.target)) {
|
||||||
|
setIsBranchMenuOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("mousedown", handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("mousedown", handleClickOutside);
|
||||||
|
};
|
||||||
}, [isBranchMenuOpen]);
|
}, [isBranchMenuOpen]);
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────
|
// ── Helpers ───────────────────────────────────────────────────────────
|
||||||
@@ -129,7 +127,6 @@ export default function BranchToolbar({
|
|||||||
setThreadError(null);
|
setThreadError(null);
|
||||||
setThreadBranch(branch.name, null);
|
setThreadBranch(branch.name, null);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +139,6 @@ export default function BranchToolbar({
|
|||||||
// Secondary worktree → point the thread at that worktree path.
|
// Secondary worktree → point the thread at that worktree path.
|
||||||
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,28 +147,20 @@ export default function BranchToolbar({
|
|||||||
setThreadError(null);
|
setThreadError(null);
|
||||||
setThreadBranch(branch.name, activeWorktreePath);
|
setThreadBranch(branch.name, activeWorktreePath);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
|
||||||
setIsBranchMenuOpen(true);
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const createBranch = (rawName: string) => {
|
const createBranch = () => {
|
||||||
const name = rawName.trim();
|
const name = newBranchName.trim();
|
||||||
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
|
if (!api || !activeThreadId || !branchCwd || !name) return;
|
||||||
createBranchMutation.mutate(name, {
|
createBranchMutation.mutate(name, {
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
setThreadError(null);
|
setThreadError(null);
|
||||||
setThreadBranch(name, activeWorktreePath);
|
setThreadBranch(name, activeWorktreePath);
|
||||||
setBranchQuery("");
|
setNewBranchName("");
|
||||||
|
setIsCreatingBranch(false);
|
||||||
setIsBranchMenuOpen(false);
|
setIsBranchMenuOpen(false);
|
||||||
onComposerFocusRequest?.();
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -183,101 +171,149 @@ export default function BranchToolbar({
|
|||||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{envLocked || activeWorktreePath ? (
|
{envLocked || activeWorktreePath ? (
|
||||||
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
<span className="inline-flex items-center gap-1.5 px-1 text-[12px] text-muted-foreground/55">
|
||||||
{activeWorktreePath ? "Worktree" : "Local"}
|
{activeWorktreePath ? "Worktree" : "Local"}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<Button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
className={`inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[12px] transition-colors duration-150 ${
|
||||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
envMode === "worktree"
|
||||||
size="xs"
|
? "bg-accent text-foreground/80"
|
||||||
|
: "text-muted-foreground/60 hover:bg-accent/50 hover:text-muted-foreground/80"
|
||||||
|
}`}
|
||||||
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
|
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
|
||||||
>
|
>
|
||||||
{envMode === "worktree" ? "New worktree" : "Local"}
|
{envMode === "worktree" ? "New worktree" : "Local"}
|
||||||
</Button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Combobox
|
{!isRepo ? (
|
||||||
items={branchPickerItems}
|
<button
|
||||||
autoHighlight
|
type="button"
|
||||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
className="inline-flex items-center gap-1.5 rounded-lg border border-border px-2 py-1 text-[12px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
open={isBranchMenuOpen}
|
disabled={!branchCwd || initMutation.isPending}
|
||||||
value={activeThread.branch}
|
onClick={() => initMutation.mutate()}
|
||||||
>
|
|
||||||
<ComboboxTrigger
|
|
||||||
render={<Button variant="ghost" size="xs" />}
|
|
||||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
|
||||||
disabled={branchesQuery.isLoading}
|
|
||||||
>
|
>
|
||||||
<span className="max-w-[240px] truncate">
|
{initMutation.isPending ? "Initializing\u2026" : "Initialize git"}
|
||||||
{activeThread.branch
|
</button>
|
||||||
? envMode === "worktree" && !activeWorktreePath
|
) : (
|
||||||
? `From ${activeThread.branch}`
|
<div className="relative" ref={branchMenuRef}>
|
||||||
: activeThread.branch
|
<button
|
||||||
: "Select branch"}
|
type="button"
|
||||||
</span>
|
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[12px] text-muted-foreground/60 transition-colors duration-150 hover:bg-accent/50 hover:text-muted-foreground/80"
|
||||||
<ChevronDownIcon />
|
onClick={() => setIsBranchMenuOpen((open) => !open)}
|
||||||
</ComboboxTrigger>
|
disabled={branchesQuery.isLoading}
|
||||||
<ComboboxPopup align="end" side="top" className="w-64">
|
>
|
||||||
<div className="border-b p-1">
|
<span className="max-w-[240px] truncate font-mono">
|
||||||
<ComboboxInput
|
{activeThread.branch
|
||||||
className="[&_input]:font-sans rounded-md"
|
? envMode === "worktree" && !activeWorktreePath
|
||||||
inputClassName="ring-0"
|
? `From ${activeThread.branch}`
|
||||||
placeholder="Search branches..."
|
: activeThread.branch
|
||||||
showTrigger={false}
|
: "Select branch"}
|
||||||
size="sm"
|
</span>
|
||||||
value={branchQuery}
|
<svg
|
||||||
onChange={(event) => setBranchQuery(event.target.value)}
|
width="10"
|
||||||
/>
|
height="10"
|
||||||
</div>
|
viewBox="0 0 10 10"
|
||||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
fill="none"
|
||||||
|
className="opacity-40"
|
||||||
<ComboboxList className="max-h-56">
|
aria-hidden="true"
|
||||||
{(itemValue) => {
|
>
|
||||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
<path
|
||||||
return (
|
d="M2.5 4L5 6.5L7.5 4"
|
||||||
<ComboboxItem
|
stroke="currentColor"
|
||||||
hideIndicator
|
strokeWidth="1.2"
|
||||||
key={itemValue}
|
strokeLinecap="round"
|
||||||
value={itemValue}
|
strokeLinejoin="round"
|
||||||
onClick={() => createBranch(trimmedBranchQuery)}
|
/>
|
||||||
>
|
</svg>
|
||||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
</button>
|
||||||
</ComboboxItem>
|
{isBranchMenuOpen && (
|
||||||
);
|
<div className="absolute bottom-full right-0 z-20 mb-2 w-[320px] rounded-2xl border border-border bg-popover/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
|
||||||
}
|
<p className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/55">
|
||||||
|
Branch
|
||||||
const branch = branchByName.get(itemValue);
|
</p>
|
||||||
if (!branch) return null;
|
<div className="max-h-64 overflow-y-auto">
|
||||||
|
{branches.map((branch) => {
|
||||||
const hasSecondaryWorktree =
|
const isSelected = branch.name === activeThread.branch;
|
||||||
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
const hasSecondaryWorktree =
|
||||||
return (
|
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
||||||
<ComboboxItem
|
return (
|
||||||
hideIndicator
|
<button
|
||||||
key={itemValue}
|
key={branch.name}
|
||||||
value={itemValue}
|
type="button"
|
||||||
className={
|
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-1.5 text-left font-mono text-xs transition-colors duration-150 ${
|
||||||
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
|
isSelected
|
||||||
}
|
? "bg-accent text-foreground"
|
||||||
onClick={() => selectBranch(branch)}
|
: "text-foreground/90 hover:bg-accent/50"
|
||||||
>
|
}`}
|
||||||
<div className="flex w-full items-center justify-between gap-2">
|
onClick={() => selectBranch(branch)}
|
||||||
<span className="truncate">{itemValue}</span>
|
>
|
||||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
<span className="truncate">{branch.name}</span>
|
||||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
||||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
||||||
</span>
|
{branch.current
|
||||||
)}
|
? "current"
|
||||||
</div>
|
: hasSecondaryWorktree
|
||||||
</ComboboxItem>
|
? "worktree"
|
||||||
);
|
: "default"}
|
||||||
}}
|
</span>
|
||||||
</ComboboxList>
|
)}
|
||||||
</ComboboxPopup>
|
</button>
|
||||||
</Combobox>
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{envMode === "local" && (
|
||||||
|
<>
|
||||||
|
<div className="mx-1 my-1 h-px bg-border" />
|
||||||
|
{isCreatingBranch ? (
|
||||||
|
<form
|
||||||
|
className="flex items-center gap-1 px-1"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
createBranch();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="flex-1 rounded-lg border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground placeholder:text-muted-foreground/30 focus:border-ring focus:outline-none"
|
||||||
|
placeholder="branch-name"
|
||||||
|
value={newBranchName}
|
||||||
|
onChange={(event) => setNewBranchName(event.target.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
setIsCreatingBranch(false);
|
||||||
|
setNewBranchName("");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
// biome-ignore lint/a11y/noAutofocus: branch name input should focus when shown
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={!newBranchName.trim() || createBranchMutation.isPending}
|
||||||
|
className="rounded-lg px-2 py-1.5 text-xs text-muted-foreground/70 transition-colors hover:bg-accent hover:text-foreground/80 disabled:opacity-30"
|
||||||
|
>
|
||||||
|
Create
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="w-full rounded-lg px-2 py-1.5 text-left text-xs text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80"
|
||||||
|
onClick={() => setIsCreatingBranch(true)}
|
||||||
|
>
|
||||||
|
+ New branch
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -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);
|
|
||||||
+700
-2046
File diff suppressed because it is too large.
Load diff
@@ -1,470 +1,55 @@
|
|||||||
import { parsePatchFiles } from "@pierre/diffs";
|
|
||||||
import {
|
|
||||||
FileDiff,
|
|
||||||
type FileDiffMetadata,
|
|
||||||
Virtualizer,
|
|
||||||
WorkerPoolContextProvider,
|
|
||||||
} from "@pierre/diffs/react";
|
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { Columns2Icon, Rows3Icon } from "lucide-react";
|
|
||||||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
|
||||||
import { checkpointDiffQueryOptions, providerQueryKeys } from "~/lib/providerReactQuery";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { isElectron } from "../env";
|
import { 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";
|
|
||||||
|
|
||||||
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(
|
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
|
||||||
"rounded-md border px-2 py-1 text-left transition-colors",
|
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
|
||||||
selectedTurnId === null
|
|
||||||
? "border-border bg-accent text-accent-foreground"
|
|
||||||
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="text-[10px] font-medium">All turns</div>
|
|
||||||
<div className="text-[8px] opacity-70">Conversation</div>
|
|
||||||
</div>
|
|
||||||
</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">
|
<span className="text-sm">×</span>
|
||||||
<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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,727 +0,0 @@
|
|||||||
import type { GitStatusResult } from "@t3tools/contracts";
|
|
||||||
import { assert, describe, it } from "vitest";
|
|
||||||
import {
|
|
||||||
buildGitActionProgressStages,
|
|
||||||
buildMenuItems,
|
|
||||||
requiresDefaultBranchConfirmation,
|
|
||||||
resolveQuickAction,
|
|
||||||
summarizeGitResult,
|
|
||||||
} from "./GitActionsControl.logic";
|
|
||||||
|
|
||||||
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
|
||||||
return {
|
|
||||||
branch: "feature/test",
|
|
||||||
hasWorkingTreeChanges: false,
|
|
||||||
workingTree: {
|
|
||||||
files: [],
|
|
||||||
insertions: 0,
|
|
||||||
deletions: 0,
|
|
||||||
},
|
|
||||||
hasUpstream: true,
|
|
||||||
aheadCount: 0,
|
|
||||||
behindCount: 0,
|
|
||||||
openPr: null,
|
|
||||||
...overrides,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("when: branch is clean and has an open PR", () => {
|
|
||||||
it("resolveQuickAction opens the existing PR", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({
|
|
||||||
openPr: {
|
|
||||||
number: 10,
|
|
||||||
title: "Open PR",
|
|
||||||
url: "https://example.com/pr/10",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, { kind: "open_pr", label: "Open PR", disabled: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
|
||||||
const items = buildMenuItems(
|
|
||||||
status({
|
|
||||||
openPr: {
|
|
||||||
number: 11,
|
|
||||||
title: "Existing PR",
|
|
||||||
url: "https://example.com/pr/11",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Open PR",
|
|
||||||
disabled: false,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: actions are busy", () => {
|
|
||||||
it("resolveQuickAction returns running disabled state", () => {
|
|
||||||
const quick = resolveQuickAction(status(), true);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "show_hint",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
hint: "Git action in progress.",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems disables all actions", () => {
|
|
||||||
const items = buildMenuItems(status(), true);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: git status is unavailable", () => {
|
|
||||||
it("resolveQuickAction returns unavailable disabled state", () => {
|
|
||||||
const quick = resolveQuickAction(null, false);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "show_hint",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
hint: "Git status is unavailable.",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems returns no menu items", () => {
|
|
||||||
const items = buildMenuItems(null, false);
|
|
||||||
assert.deepEqual(items, []);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch is clean, ahead, and has an open PR", () => {
|
|
||||||
it("resolveQuickAction prefers push", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({
|
|
||||||
aheadCount: 3,
|
|
||||||
openPr: {
|
|
||||||
number: 13,
|
|
||||||
title: "Open PR",
|
|
||||||
url: "https://example.com/pr/13",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, { kind: "run_action", action: "commit_push", label: "Push" });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems enables push and keeps open PR available", () => {
|
|
||||||
const items = buildMenuItems(
|
|
||||||
status({
|
|
||||||
aheadCount: 2,
|
|
||||||
openPr: {
|
|
||||||
number: 12,
|
|
||||||
title: "Existing PR",
|
|
||||||
url: "https://example.com/pr/12",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: false,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Open PR",
|
|
||||||
disabled: false,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
|
||||||
it("resolveQuickAction pushes and creates a PR", () => {
|
|
||||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push_pr",
|
|
||||||
label: "Push & create PR",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
|
||||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: false,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: false,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
|
||||||
it("resolveQuickAction returns disabled no-action state", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
|
||||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch is behind upstream", () => {
|
|
||||||
it("resolveQuickAction returns pull", () => {
|
|
||||||
const quick = resolveQuickAction(status({ behindCount: 2 }), false);
|
|
||||||
assert.deepInclude(quick, { kind: "run_pull", label: "Pull", disabled: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems disables push and create PR", () => {
|
|
||||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch has diverged from upstream", () => {
|
|
||||||
it("resolveQuickAction returns a disabled sync hint", () => {
|
|
||||||
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
|
|
||||||
assert.deepEqual(quick, {
|
|
||||||
label: "Sync branch",
|
|
||||||
disabled: true,
|
|
||||||
kind: "show_hint",
|
|
||||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: working tree has local changes", () => {
|
|
||||||
it("resolveQuickAction returns commit, push, and create PR", () => {
|
|
||||||
const quick = resolveQuickAction(status({ hasWorkingTreeChanges: true }), false);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push_pr",
|
|
||||||
label: "Commit, push & create PR",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolveQuickAction returns commit and push when open PR exists", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({
|
|
||||||
hasWorkingTreeChanges: true,
|
|
||||||
openPr: {
|
|
||||||
number: 16,
|
|
||||||
title: "Existing PR",
|
|
||||||
url: "https://example.com/pr/16",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push",
|
|
||||||
label: "Commit & push",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems enables commit and disables push and PR", () => {
|
|
||||||
const items = buildMenuItems(status({ hasWorkingTreeChanges: true }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: false,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: on default branch without open PR", () => {
|
|
||||||
it("resolveQuickAction returns commit and push when local changes exist", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ branch: "main", hasWorkingTreeChanges: true }),
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push",
|
|
||||||
label: "Commit & push",
|
|
||||||
disabled: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
|
||||||
false,
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: working tree has local changes and branch is behind upstream", () => {
|
|
||||||
it("resolveQuickAction still prefers commit, push, and create PR", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ hasWorkingTreeChanges: true, behindCount: 1 }),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push_pr",
|
|
||||||
label: "Commit, push & create PR",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems enables commit and keeps push and PR disabled", () => {
|
|
||||||
const items = buildMenuItems(status({ hasWorkingTreeChanges: true, behindCount: 2 }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: false,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: HEAD is detached and there are no local changes", () => {
|
|
||||||
it("resolveQuickAction shows detached head hint", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ branch: null, hasWorkingTreeChanges: false, hasUpstream: false }),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems keeps commit, push, and PR disabled", () => {
|
|
||||||
const items = buildMenuItems(status({ branch: null, hasWorkingTreeChanges: false }), false);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("when: branch has no upstream configured", () => {
|
|
||||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "show_hint",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({
|
|
||||||
hasUpstream: false,
|
|
||||||
aheadCount: 0,
|
|
||||||
openPr: {
|
|
||||||
number: 14,
|
|
||||||
title: "Existing PR",
|
|
||||||
url: "https://example.com/pr/14",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "show_hint",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolveQuickAction runs push when clean, no upstream, and local commits are ahead", () => {
|
|
||||||
const quick = resolveQuickAction(
|
|
||||||
status({
|
|
||||||
hasUpstream: false,
|
|
||||||
aheadCount: 1,
|
|
||||||
openPr: {
|
|
||||||
number: 15,
|
|
||||||
title: "Existing PR",
|
|
||||||
url: "https://example.com/pr/15",
|
|
||||||
baseBranch: "main",
|
|
||||||
headBranch: "feature/test",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepInclude(quick, {
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: false,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
|
||||||
const items = buildMenuItems(
|
|
||||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
assert.deepEqual(items, [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: true,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: true,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("requiresDefaultBranchConfirmation", () => {
|
|
||||||
it("requires confirmation only for push actions on default branch", () => {
|
|
||||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
|
||||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
|
|
||||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
|
|
||||||
assert.isFalse(requiresDefaultBranchConfirmation("commit_push", false));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("buildGitActionProgressStages", () => {
|
|
||||||
it("shows only push progress when push-only is forced", () => {
|
|
||||||
const stages = buildGitActionProgressStages({
|
|
||||||
action: "commit_push",
|
|
||||||
hasCustomCommitMessage: false,
|
|
||||||
hasWorkingTreeChanges: true,
|
|
||||||
forcePushOnly: true,
|
|
||||||
pushTarget: "origin/feature/test",
|
|
||||||
});
|
|
||||||
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("includes commit stages for commit+push when working tree is dirty", () => {
|
|
||||||
const stages = buildGitActionProgressStages({
|
|
||||||
action: "commit_push",
|
|
||||||
hasCustomCommitMessage: false,
|
|
||||||
hasWorkingTreeChanges: true,
|
|
||||||
pushTarget: "origin/feature/test",
|
|
||||||
});
|
|
||||||
assert.deepEqual(stages, [
|
|
||||||
"Generating commit message...",
|
|
||||||
"Committing...",
|
|
||||||
"Pushing to origin/feature/test...",
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("summarizeGitResult", () => {
|
|
||||||
it("returns commit-focused toast for commit action", () => {
|
|
||||||
const result = summarizeGitResult({
|
|
||||||
action: "commit",
|
|
||||||
commit: {
|
|
||||||
status: "created",
|
|
||||||
commitSha: "0123456789abcdef",
|
|
||||||
subject: "feat: add optimistic UI for git action button",
|
|
||||||
},
|
|
||||||
push: { status: "skipped_not_requested" },
|
|
||||||
pr: { status: "skipped_not_requested" },
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result, {
|
|
||||||
title: "Committed 0123456",
|
|
||||||
description: "feat: add optimistic UI for git action button",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns push-focused toast for push action", () => {
|
|
||||||
const result = summarizeGitResult({
|
|
||||||
action: "commit_push",
|
|
||||||
commit: {
|
|
||||||
status: "created",
|
|
||||||
commitSha: "abcdef0123456789",
|
|
||||||
subject: "fix: tighten quick action tooltip hover handling",
|
|
||||||
},
|
|
||||||
push: {
|
|
||||||
status: "pushed",
|
|
||||||
branch: "foo",
|
|
||||||
upstreamBranch: "origin/foo",
|
|
||||||
},
|
|
||||||
pr: { status: "skipped_not_requested" },
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result, {
|
|
||||||
title: "Pushed abcdef0 to origin/foo",
|
|
||||||
description: "fix: tighten quick action tooltip hover handling",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns PR-focused toast for created PR action", () => {
|
|
||||||
const result = summarizeGitResult({
|
|
||||||
action: "commit_push_pr",
|
|
||||||
commit: {
|
|
||||||
status: "created",
|
|
||||||
commitSha: "89abcdef01234567",
|
|
||||||
subject: "feat: ship github shortcuts",
|
|
||||||
},
|
|
||||||
push: {
|
|
||||||
status: "pushed",
|
|
||||||
branch: "foo",
|
|
||||||
},
|
|
||||||
pr: {
|
|
||||||
status: "created",
|
|
||||||
number: 42,
|
|
||||||
title: "feat: ship github shortcuts and improve PR CTA in success toast",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result, {
|
|
||||||
title: "Created PR #42",
|
|
||||||
description: "feat: ship github shortcuts and improve PR CTA in success toast",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("truncates long description text", () => {
|
|
||||||
const result = summarizeGitResult({
|
|
||||||
action: "commit_push_pr",
|
|
||||||
commit: {
|
|
||||||
status: "created",
|
|
||||||
commitSha: "89abcdef01234567",
|
|
||||||
subject: "short subject",
|
|
||||||
},
|
|
||||||
push: { status: "pushed", branch: "foo" },
|
|
||||||
pr: {
|
|
||||||
status: "created",
|
|
||||||
number: 99,
|
|
||||||
title:
|
|
||||||
"feat: this title is intentionally extremely long so we can validate that toast descriptions are truncated with an ellipsis suffix",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.deepEqual(result, {
|
|
||||||
title: "Created PR #99",
|
|
||||||
description: "feat: this title is intentionally extremely long so we can validate t...",
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
import type {
|
|
||||||
GitRunStackedActionResult,
|
|
||||||
GitStackedAction,
|
|
||||||
GitStatusResult,
|
|
||||||
} from "@t3tools/contracts";
|
|
||||||
|
|
||||||
export type GitActionIconName = "commit" | "push" | "pr";
|
|
||||||
|
|
||||||
export type GitDialogAction = "commit" | "push" | "create_pr";
|
|
||||||
|
|
||||||
export interface GitActionMenuItem {
|
|
||||||
id: "commit" | "push" | "pr";
|
|
||||||
label: string;
|
|
||||||
disabled: boolean;
|
|
||||||
icon: GitActionIconName;
|
|
||||||
kind: "open_dialog" | "open_pr";
|
|
||||||
dialogAction?: GitDialogAction;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface GitQuickAction {
|
|
||||||
label: string;
|
|
||||||
disabled: boolean;
|
|
||||||
kind: "run_action" | "run_pull" | "open_pr" | "show_hint";
|
|
||||||
action?: GitStackedAction;
|
|
||||||
hint?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const SHORT_SHA_LENGTH = 7;
|
|
||||||
const TOAST_DESCRIPTION_MAX = 72;
|
|
||||||
|
|
||||||
function shortenSha(sha: string | undefined): string | null {
|
|
||||||
if (!sha) return null;
|
|
||||||
return sha.slice(0, SHORT_SHA_LENGTH);
|
|
||||||
}
|
|
||||||
|
|
||||||
function truncateText(
|
|
||||||
value: string | undefined,
|
|
||||||
maxLength = TOAST_DESCRIPTION_MAX,
|
|
||||||
): string | undefined {
|
|
||||||
if (!value) return undefined;
|
|
||||||
if (value.length <= maxLength) return value;
|
|
||||||
if (maxLength <= 3) return "...".slice(0, maxLength);
|
|
||||||
return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildGitActionProgressStages(input: {
|
|
||||||
action: GitStackedAction;
|
|
||||||
hasCustomCommitMessage: boolean;
|
|
||||||
hasWorkingTreeChanges: boolean;
|
|
||||||
forcePushOnly?: boolean;
|
|
||||||
pushTarget?: string;
|
|
||||||
}): string[] {
|
|
||||||
const shouldIncludeCommitStages =
|
|
||||||
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
|
|
||||||
const commitStages = !shouldIncludeCommitStages
|
|
||||||
? []
|
|
||||||
: input.hasCustomCommitMessage
|
|
||||||
? ["Committing..."]
|
|
||||||
: ["Generating commit message...", "Committing..."];
|
|
||||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
|
||||||
if (input.action === "commit") {
|
|
||||||
return commitStages;
|
|
||||||
}
|
|
||||||
if (input.action === "commit_push") {
|
|
||||||
return [...commitStages, pushStage];
|
|
||||||
}
|
|
||||||
return [...commitStages, pushStage, "Creating PR..."];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function summarizeGitResult(result: GitRunStackedActionResult): {
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
} {
|
|
||||||
const withDescription = (title: string, description: string | undefined) =>
|
|
||||||
description ? { title, description } : { title };
|
|
||||||
|
|
||||||
if (result.pr.status === "created" || result.pr.status === "opened_existing") {
|
|
||||||
const prNumber = result.pr.number ? ` #${result.pr.number}` : "";
|
|
||||||
const title = `${result.pr.status === "created" ? "Created PR" : "Opened PR"}${prNumber}`;
|
|
||||||
return withDescription(title, truncateText(result.pr.title));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.push.status === "pushed") {
|
|
||||||
const shortSha = shortenSha(result.commit.commitSha);
|
|
||||||
const branch = result.push.upstreamBranch ?? result.push.branch;
|
|
||||||
const pushedCommitPart = shortSha ? ` ${shortSha}` : "";
|
|
||||||
const branchPart = branch ? ` to ${branch}` : "";
|
|
||||||
return withDescription(
|
|
||||||
`Pushed${pushedCommitPart}${branchPart}`,
|
|
||||||
truncateText(result.commit.subject),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.commit.status === "created") {
|
|
||||||
const shortSha = shortenSha(result.commit.commitSha);
|
|
||||||
const title = shortSha ? `Committed ${shortSha}` : "Committed changes";
|
|
||||||
return withDescription(title, truncateText(result.commit.subject));
|
|
||||||
}
|
|
||||||
|
|
||||||
return { title: "Done" };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function buildMenuItems(
|
|
||||||
gitStatus: GitStatusResult | null,
|
|
||||||
isBusy: boolean,
|
|
||||||
): GitActionMenuItem[] {
|
|
||||||
if (!gitStatus) return [];
|
|
||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
|
||||||
const canCommit = !isBusy && hasChanges;
|
|
||||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
|
||||||
const canCreatePr =
|
|
||||||
!isBusy &&
|
|
||||||
hasBranch &&
|
|
||||||
!hasChanges &&
|
|
||||||
!hasOpenPr &&
|
|
||||||
gitStatus.aheadCount > 0 &&
|
|
||||||
gitStatus.hasUpstream &&
|
|
||||||
!isBehind;
|
|
||||||
const canOpenPr = !isBusy && hasOpenPr;
|
|
||||||
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
id: "commit",
|
|
||||||
label: "Commit",
|
|
||||||
disabled: !canCommit,
|
|
||||||
icon: "commit",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "commit",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "push",
|
|
||||||
label: "Push",
|
|
||||||
disabled: !canPush,
|
|
||||||
icon: "push",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "push",
|
|
||||||
},
|
|
||||||
hasOpenPr
|
|
||||||
? {
|
|
||||||
id: "pr",
|
|
||||||
label: "Open PR",
|
|
||||||
disabled: !canOpenPr,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_pr",
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
id: "pr",
|
|
||||||
label: "Create PR",
|
|
||||||
disabled: !canCreatePr,
|
|
||||||
icon: "pr",
|
|
||||||
kind: "open_dialog",
|
|
||||||
dialogAction: "create_pr",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function resolveQuickAction(
|
|
||||||
gitStatus: GitStatusResult | null,
|
|
||||||
isBusy: boolean,
|
|
||||||
isDefaultBranch = false,
|
|
||||||
): GitQuickAction {
|
|
||||||
if (isBusy) {
|
|
||||||
return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!gitStatus) {
|
|
||||||
return {
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
kind: "show_hint",
|
|
||||||
hint: "Git status is unavailable.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const hasBranch = gitStatus.branch !== null;
|
|
||||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
|
||||||
const hasOpenPr = gitStatus.openPr !== null;
|
|
||||||
const isAhead = gitStatus.aheadCount > 0;
|
|
||||||
const isBehind = gitStatus.behindCount > 0;
|
|
||||||
const isDiverged = isAhead && isBehind;
|
|
||||||
|
|
||||||
if (!hasBranch) {
|
|
||||||
return {
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
kind: "show_hint",
|
|
||||||
hint: "Create and checkout a branch before pushing or opening a PR.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasChanges) {
|
|
||||||
if (hasOpenPr || isDefaultBranch) {
|
|
||||||
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
label: "Commit, push & create PR",
|
|
||||||
disabled: false,
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push_pr",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isDiverged) {
|
|
||||||
return {
|
|
||||||
label: "Sync branch",
|
|
||||||
disabled: true,
|
|
||||||
kind: "show_hint",
|
|
||||||
hint: "Branch has diverged from upstream. Rebase/merge first.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isBehind) {
|
|
||||||
return {
|
|
||||||
label: "Pull",
|
|
||||||
disabled: false,
|
|
||||||
kind: "run_pull",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isAhead) {
|
|
||||||
if (hasOpenPr || isDefaultBranch) {
|
|
||||||
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
label: "Push & create PR",
|
|
||||||
disabled: false,
|
|
||||||
kind: "run_action",
|
|
||||||
action: "commit_push_pr",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasOpenPr && gitStatus.hasUpstream) {
|
|
||||||
return { label: "Open PR", disabled: false, kind: "open_pr" };
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
label: "Commit",
|
|
||||||
disabled: true,
|
|
||||||
kind: "show_hint",
|
|
||||||
hint: "Branch is up to date. No action needed.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function requiresDefaultBranchConfirmation(
|
|
||||||
action: GitStackedAction,
|
|
||||||
isDefaultBranch: boolean,
|
|
||||||
): boolean {
|
|
||||||
if (!isDefaultBranch) return false;
|
|
||||||
return action === "commit_push" || action === "commit_push_pr";
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -13,9 +13,3 @@ export const GitHubIcon: Icon = (props) => (
|
|||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
export const CursorIcon: Icon = (props) => (
|
|
||||||
<svg {...props} viewBox="0 0 466.73 532.09" fill="currentColor">
|
|
||||||
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
@@ -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,10 @@
|
|||||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
import { MonitorIcon, MoonIcon, SunIcon } 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, 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,
|
||||||
@@ -15,14 +12,8 @@ import {
|
|||||||
type Thread,
|
type Thread,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import { useNativeApi } from "../hooks/useNativeApi";
|
import { useNativeApi } from "../hooks/useNativeApi";
|
||||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
|
||||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
|
||||||
import { toastManager } from "./ui/toast";
|
|
||||||
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);
|
||||||
@@ -47,12 +38,6 @@ interface ThreadStatusPill {
|
|||||||
pulse: boolean;
|
pulse: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalStatusIndicator {
|
|
||||||
label: "Terminal process running";
|
|
||||||
colorClass: string;
|
|
||||||
pulse: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasUnseenCompletion(thread: Thread): boolean {
|
function hasUnseenCompletion(thread: Thread): boolean {
|
||||||
if (!thread.latestTurnCompletedAt) return false;
|
if (!thread.latestTurnCompletedAt) return false;
|
||||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||||
@@ -104,28 +89,9 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
|
||||||
if (thread.runningTerminalIds.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
label: "Terminal process running",
|
|
||||||
colorClass: "text-teal-600 dark:text-teal-300/90",
|
|
||||||
pulse: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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 removeWorktreeMutation = useMutation(
|
|
||||||
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 +106,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: {
|
||||||
@@ -158,7 +118,6 @@ export default function Sidebar() {
|
|||||||
terminalOpen: false,
|
terminalOpen: false,
|
||||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||||
runningTerminalIds: [],
|
|
||||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||||
terminalGroups: [
|
terminalGroups: [
|
||||||
{
|
{
|
||||||
@@ -170,11 +129,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 +173,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 +200,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);
|
||||||
@@ -288,22 +244,6 @@ export default function Sidebar() {
|
|||||||
|
|
||||||
const thread = state.threads.find((t) => t.id === threadId);
|
const thread = state.threads.find((t) => t.id === threadId);
|
||||||
if (!thread) return;
|
if (!thread) return;
|
||||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
|
||||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
|
||||||
const displayWorktreePath = orphanedWorktreePath
|
|
||||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
|
||||||
: null;
|
|
||||||
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
|
|
||||||
const shouldDeleteWorktree =
|
|
||||||
canDeleteWorktree &&
|
|
||||||
(await api.dialogs.confirm(
|
|
||||||
[
|
|
||||||
"This thread is the only one linked to this worktree:",
|
|
||||||
displayWorktreePath ?? orphanedWorktreePath,
|
|
||||||
"",
|
|
||||||
"Delete the worktree too?",
|
|
||||||
].join("\n"),
|
|
||||||
));
|
|
||||||
|
|
||||||
// Stop active session if running
|
// Stop active session if running
|
||||||
if (thread.session?.sessionId) {
|
if (thread.session?.sessionId) {
|
||||||
@@ -326,94 +266,46 @@ export default function Sidebar() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dispatch({ type: "DELETE_THREAD", threadId });
|
dispatch({ type: "DELETE_THREAD", threadId });
|
||||||
|
|
||||||
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await removeWorktreeMutation.mutateAsync({
|
|
||||||
cwd: threadProject.cwd,
|
|
||||||
path: orphanedWorktreePath,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
// Worktree deletion is best-effort and should not block thread deletion.
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
[api, dispatch, removeWorktreeMutation, state.projects, state.threads],
|
[api, dispatch, 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;
|
||||||
|
|
||||||
|
const target = event.target;
|
||||||
|
if (target instanceof HTMLElement) {
|
||||||
|
const tagName = target.tagName;
|
||||||
|
if (
|
||||||
|
target.isContentEditable ||
|
||||||
|
tagName === "INPUT" ||
|
||||||
|
tagName === "TEXTAREA" ||
|
||||||
|
tagName === "SELECT"
|
||||||
|
) {
|
||||||
|
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 +369,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 ? "▼" : "▶"}
|
||||||
@@ -503,7 +388,6 @@ export default function Sidebar() {
|
|||||||
thread,
|
thread,
|
||||||
pendingApprovalByThreadId.get(thread.id) === true,
|
pendingApprovalByThreadId.get(thread.id) === true,
|
||||||
);
|
);
|
||||||
const terminalStatus = terminalStatusIndicator(thread);
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
key={thread.id}
|
key={thread.id}
|
||||||
@@ -542,23 +426,9 @@ export default function Sidebar() {
|
|||||||
)}
|
)}
|
||||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-2 flex shrink-0 items-center gap-1.5">
|
<span className="shrink-0 text-[10px] text-muted-foreground/40">
|
||||||
{terminalStatus && (
|
{formatRelativeTime(thread.createdAt)}
|
||||||
<span
|
</span>
|
||||||
role="img"
|
|
||||||
aria-label={terminalStatus.label}
|
|
||||||
title={terminalStatus.label}
|
|
||||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
|
||||||
>
|
|
||||||
<TerminalIcon
|
|
||||||
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
|
|
||||||
/>
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<span className="text-[10px] text-muted-foreground/40">
|
|
||||||
{formatRelativeTime(thread.createdAt)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -1,28 +1,25 @@
|
|||||||
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 {
|
||||||
type PointerEvent as ReactPointerEvent,
|
type PointerEvent as ReactPointerEvent,
|
||||||
type ReactNode,
|
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
useRef,
|
useRef,
|
||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
|
||||||
import {
|
import {
|
||||||
extractTerminalLinks,
|
extractTerminalLinks,
|
||||||
isTerminalLinkActivation,
|
isTerminalLinkActivation,
|
||||||
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";
|
||||||
|
|
||||||
@@ -31,11 +28,16 @@ const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
|||||||
|
|
||||||
function maxDrawerHeight(): number {
|
function maxDrawerHeight(): number {
|
||||||
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
|
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
|
||||||
return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
|
return Math.max(
|
||||||
|
MIN_DRAWER_HEIGHT,
|
||||||
|
Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function clampDrawerHeight(height: number): number {
|
function clampDrawerHeight(height: number): number {
|
||||||
const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
|
const safeHeight = Number.isFinite(height)
|
||||||
|
? height
|
||||||
|
: DEFAULT_THREAD_TERMINAL_HEIGHT;
|
||||||
const maxHeight = maxDrawerHeight();
|
const maxHeight = maxDrawerHeight();
|
||||||
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
|
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
|
||||||
}
|
}
|
||||||
@@ -49,7 +51,8 @@ function terminalThemeFromApp(): ITheme {
|
|||||||
const bodyStyles = getComputedStyle(document.body);
|
const bodyStyles = getComputedStyle(document.body);
|
||||||
const background =
|
const background =
|
||||||
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
|
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
|
||||||
const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
|
const foreground =
|
||||||
|
bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
|
||||||
|
|
||||||
if (isDark) {
|
if (isDark) {
|
||||||
return {
|
return {
|
||||||
@@ -111,7 +114,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 +125,6 @@ function TerminalViewport({
|
|||||||
threadId,
|
threadId,
|
||||||
terminalId,
|
terminalId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
|
||||||
focusRequestId,
|
focusRequestId,
|
||||||
autoFocus,
|
autoFocus,
|
||||||
resizeEpoch,
|
resizeEpoch,
|
||||||
@@ -145,7 +146,8 @@ function TerminalViewport({
|
|||||||
lineHeight: 1.2,
|
lineHeight: 1.2,
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
scrollback: 5_000,
|
scrollback: 5_000,
|
||||||
fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
|
fontFamily:
|
||||||
|
'"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
|
||||||
theme: terminalThemeFromApp(),
|
theme: terminalThemeFromApp(),
|
||||||
});
|
});
|
||||||
terminal.loadAddon(fitAddon);
|
terminal.loadAddon(fitAddon);
|
||||||
@@ -155,29 +157,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 +273,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 +368,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 +413,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,48 +421,15 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalActionButtonProps {
|
|
||||||
label: string;
|
|
||||||
className: string;
|
|
||||||
onClick: () => void;
|
|
||||||
children: ReactNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
|
|
||||||
return (
|
|
||||||
<Popover>
|
|
||||||
<PopoverTrigger
|
|
||||||
openOnHover
|
|
||||||
render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverPopup
|
|
||||||
tooltipStyle
|
|
||||||
side="bottom"
|
|
||||||
sideOffset={6}
|
|
||||||
align="center"
|
|
||||||
className="pointer-events-none select-none"
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</PopoverPopup>
|
|
||||||
</Popover>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ThreadTerminalDrawer({
|
export default function ThreadTerminalDrawer({
|
||||||
api,
|
api,
|
||||||
threadId,
|
threadId,
|
||||||
cwd,
|
cwd,
|
||||||
runtimeEnv,
|
|
||||||
height,
|
height,
|
||||||
terminalIds,
|
terminalIds,
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
@@ -476,9 +438,6 @@ export default function ThreadTerminalDrawer({
|
|||||||
focusRequestId,
|
focusRequestId,
|
||||||
onSplitTerminal,
|
onSplitTerminal,
|
||||||
onNewTerminal,
|
onNewTerminal,
|
||||||
splitShortcutLabel,
|
|
||||||
newShortcutLabel,
|
|
||||||
closeShortcutLabel,
|
|
||||||
onActiveTerminalChange,
|
onActiveTerminalChange,
|
||||||
onCloseTerminal,
|
onCloseTerminal,
|
||||||
onHeightChange,
|
onHeightChange,
|
||||||
@@ -579,15 +538,13 @@ export default function ThreadTerminalDrawer({
|
|||||||
return indexByTerminal >= 0 ? indexByTerminal : 0;
|
return indexByTerminal >= 0 ? indexByTerminal : 0;
|
||||||
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
|
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
|
||||||
|
|
||||||
const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
|
const visibleTerminalIds =
|
||||||
resolvedActiveTerminalId,
|
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId];
|
||||||
];
|
|
||||||
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
|
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
|
||||||
const isSplitView = visibleTerminalIds.length > 1;
|
const isSplitView = visibleTerminalIds.length > 1;
|
||||||
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 +552,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 +646,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
|
||||||
@@ -720,37 +660,35 @@ export default function ThreadTerminalDrawer({
|
|||||||
{!hasTerminalSidebar && (
|
{!hasTerminalSidebar && (
|
||||||
<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
|
<button
|
||||||
className={`p-1 text-foreground/90 transition-colors ${
|
type="button"
|
||||||
hasReachedTerminalLimit
|
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
onClick={onSplitTerminal}
|
||||||
: "hover:bg-accent"
|
aria-label="Split Terminal"
|
||||||
}`}
|
title="Split Terminal"
|
||||||
onClick={onSplitTerminalAction}
|
|
||||||
label={splitTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<SquareSplitHorizontal className="size-3.25" />
|
<SquareSplitHorizontal className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
<div className="h-4 w-px bg-border/80" />
|
<div className="h-4 w-px bg-border/80" />
|
||||||
<TerminalActionButton
|
<button
|
||||||
className={`p-1 text-foreground/90 transition-colors ${
|
type="button"
|
||||||
hasReachedTerminalLimit
|
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
onClick={onNewTerminal}
|
||||||
: "hover:bg-accent"
|
aria-label="New Terminal"
|
||||||
}`}
|
title="New Terminal"
|
||||||
onClick={onNewTerminalAction}
|
|
||||||
label={newTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<Plus className="size-3.25" />
|
<Plus className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
<div className="h-4 w-px bg-border/80" />
|
<div className="h-4 w-px bg-border/80" />
|
||||||
<TerminalActionButton
|
<button
|
||||||
|
type="button"
|
||||||
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}
|
aria-label="Close Terminal"
|
||||||
|
title="Close Terminal"
|
||||||
>
|
>
|
||||||
<Trash2 className="size-3.25" />
|
<Trash2 className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -760,16 +698,18 @@ 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) => (
|
||||||
<div
|
<div
|
||||||
key={terminalId}
|
key={terminalId}
|
||||||
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
|
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
|
||||||
terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
|
terminalId === resolvedActiveTerminalId
|
||||||
|
? "border-border"
|
||||||
|
: "border-border/70"
|
||||||
}`}
|
}`}
|
||||||
onMouseDown={() => {
|
onMouseDown={() => {
|
||||||
if (terminalId !== resolvedActiveTerminalId) {
|
if (terminalId !== resolvedActiveTerminalId) {
|
||||||
@@ -783,7 +723,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 +740,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}
|
||||||
@@ -815,42 +753,39 @@ export default function ThreadTerminalDrawer({
|
|||||||
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
|
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
|
||||||
<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
|
<button
|
||||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
type="button"
|
||||||
hasReachedTerminalLimit
|
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
onClick={onSplitTerminal}
|
||||||
: "hover:bg-accent/70"
|
aria-label="Split Terminal"
|
||||||
}`}
|
title="Split Terminal"
|
||||||
onClick={onSplitTerminalAction}
|
|
||||||
label={splitTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<SquareSplitHorizontal className="size-3.25" />
|
<SquareSplitHorizontal className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
<TerminalActionButton
|
<button
|
||||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
type="button"
|
||||||
hasReachedTerminalLimit
|
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
onClick={onNewTerminal}
|
||||||
: "hover:bg-accent/70"
|
aria-label="New Terminal"
|
||||||
}`}
|
title="New Terminal"
|
||||||
onClick={onNewTerminalAction}
|
|
||||||
label={newTerminalActionLabel}
|
|
||||||
>
|
>
|
||||||
<Plus className="size-3.25" />
|
<Plus className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
<TerminalActionButton
|
<button
|
||||||
|
type="button"
|
||||||
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}
|
aria-label="Close Terminal"
|
||||||
|
title="Close Terminal"
|
||||||
>
|
>
|
||||||
<Trash2 className="size-3.25" />
|
<Trash2 className="size-3.25" />
|
||||||
</TerminalActionButton>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
|
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
|
||||||
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
|
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
|
||||||
const isGroupActive =
|
const isGroupActive = terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
|
||||||
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
|
|
||||||
const groupActiveTerminalId = isGroupActive
|
const groupActiveTerminalId = isGroupActive
|
||||||
? resolvedActiveTerminalId
|
? resolvedActiveTerminalId
|
||||||
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
|
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
|
||||||
@@ -873,14 +808,9 @@ export default function ThreadTerminalDrawer({
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div
|
<div className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}>
|
||||||
className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
|
|
||||||
>
|
|
||||||
{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 +834,18 @@ export default function ThreadTerminalDrawer({
|
|||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
{normalizedTerminalIds.length > 1 && (
|
{normalizedTerminalIds.length > 1 && (
|
||||||
<Popover>
|
<button
|
||||||
<PopoverTrigger
|
type="button"
|
||||||
openOnHover
|
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||||
render={
|
onClick={(event) => {
|
||||||
<button
|
event.stopPropagation();
|
||||||
type="button"
|
onCloseTerminal(terminalId);
|
||||||
className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
}}
|
||||||
onClick={() => onCloseTerminal(terminalId)}
|
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||||
aria-label={closeTerminalLabel}
|
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||||
/>
|
>
|
||||||
}
|
×
|
||||||
>
|
</button>
|
||||||
<XIcon className="size-2.5" />
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverPopup
|
|
||||||
tooltipStyle
|
|
||||||
side="bottom"
|
|
||||||
sideOffset={6}
|
|
||||||
align="center"
|
|
||||||
className="pointer-events-none select-none"
|
|
||||||
>
|
|
||||||
{closeTerminalLabel}
|
|
||||||
</PopoverPopup>
|
|
||||||
</Popover>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,141 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const AlertDialogCreateHandle = AlertDialogPrimitive.createHandle;
|
|
||||||
|
|
||||||
const AlertDialog = AlertDialogPrimitive.Root;
|
|
||||||
|
|
||||||
const AlertDialogPortal = AlertDialogPrimitive.Portal;
|
|
||||||
|
|
||||||
function AlertDialogTrigger(props: AlertDialogPrimitive.Trigger.Props) {
|
|
||||||
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogBackdrop({ className, ...props }: AlertDialogPrimitive.Backdrop.Props) {
|
|
||||||
return (
|
|
||||||
<AlertDialogPrimitive.Backdrop
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 ease-out data-ending-style:opacity-0 data-starting-style:opacity-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="alert-dialog-backdrop"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogViewport({ className, ...props }: AlertDialogPrimitive.Viewport.Props) {
|
|
||||||
return (
|
|
||||||
<AlertDialogPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="alert-dialog-viewport"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogPopup({
|
|
||||||
className,
|
|
||||||
bottomStickOnMobile = true,
|
|
||||||
...props
|
|
||||||
}: AlertDialogPrimitive.Popup.Props & {
|
|
||||||
bottomStickOnMobile?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<AlertDialogPortal>
|
|
||||||
<AlertDialogBackdrop />
|
|
||||||
<AlertDialogViewport
|
|
||||||
className={cn(bottomStickOnMobile && "max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12")}
|
|
||||||
>
|
|
||||||
<AlertDialogPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-full min-h-0 w-full min-w-0 max-w-lg scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover not-dark:bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg/5 transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
bottomStickOnMobile &&
|
|
||||||
"max-sm:max-w-none max-sm:rounded-none max-sm:border-x-0 max-sm:border-t max-sm:border-b-0 max-sm:opacity-[calc(1-min(var(--nested-dialogs),1))] max-sm:data-ending-style:translate-y-4 max-sm:data-starting-style:translate-y-4 max-sm:before:hidden max-sm:before:rounded-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="alert-dialog-popup"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</AlertDialogViewport>
|
|
||||||
</AlertDialogPortal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("flex flex-col gap-2 p-6 text-center max-sm:pb-4 sm:text-left", className)}
|
|
||||||
data-slot="alert-dialog-header"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogFooter({
|
|
||||||
className,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & {
|
|
||||||
variant?: "default" | "bare";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col-reverse gap-2 px-6 sm:flex-row sm:justify-end sm:rounded-b-[calc(var(--radius-2xl)-1px)]",
|
|
||||||
variant === "default" && "border-t bg-muted/72 py-4",
|
|
||||||
variant === "bare" && "pb-6",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="alert-dialog-footer"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogTitle({ className, ...props }: AlertDialogPrimitive.Title.Props) {
|
|
||||||
return (
|
|
||||||
<AlertDialogPrimitive.Title
|
|
||||||
className={cn("font-heading font-semibold text-xl leading-none", className)}
|
|
||||||
data-slot="alert-dialog-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogDescription({ className, ...props }: AlertDialogPrimitive.Description.Props) {
|
|
||||||
return (
|
|
||||||
<AlertDialogPrimitive.Description
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
data-slot="alert-dialog-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDialogClose(props: AlertDialogPrimitive.Close.Props) {
|
|
||||||
return <AlertDialogPrimitive.Close data-slot="alert-dialog-close" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
AlertDialogCreateHandle,
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogPortal,
|
|
||||||
AlertDialogBackdrop,
|
|
||||||
AlertDialogBackdrop as AlertDialogOverlay,
|
|
||||||
AlertDialogTrigger,
|
|
||||||
AlertDialogPopup,
|
|
||||||
AlertDialogPopup as AlertDialogContent,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogTitle,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogClose,
|
|
||||||
AlertDialogViewport,
|
|
||||||
};
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const alertVariants = cva(
|
|
||||||
"relative grid w-full items-start gap-x-2 gap-y-0.5 rounded-xl border px-3.5 py-3 text-card-foreground text-sm has-[>svg]:has-data-[slot=alert-action]:grid-cols-[calc(var(--spacing)*4)_1fr_auto] has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-data-[slot=alert-action]:grid-cols-[1fr_auto] has-[>svg]:gap-x-2 [&>svg]:h-lh [&>svg]:w-4",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "bg-transparent dark:bg-input/32 [&>svg]:text-muted-foreground",
|
|
||||||
error: "border-destructive/32 bg-destructive/4 [&>svg]:text-destructive",
|
|
||||||
info: "border-info/32 bg-info/4 [&>svg]:text-info",
|
|
||||||
success: "border-success/32 bg-success/4 [&>svg]:text-success",
|
|
||||||
warning: "border-warning/32 bg-warning/4 [&>svg]:text-warning",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function Alert({
|
|
||||||
className,
|
|
||||||
variant,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(alertVariants({ variant }), className)}
|
|
||||||
data-slot="alert"
|
|
||||||
role="alert"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("font-medium [svg~&]:col-start-2", className)}
|
|
||||||
data-slot="alert-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertDescription({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("flex flex-col gap-2.5 text-muted-foreground [svg~&]:col-start-2", className)}
|
|
||||||
data-slot="alert-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex gap-1 max-sm:col-start-2 max-sm:mt-2 sm:row-start-1 sm:row-end-3 sm:self-center sm:[[data-slot=alert-description]~&]:col-start-2 sm:[[data-slot=alert-title]~&]:col-start-2 sm:[svg~&]:col-start-2 sm:[svg~[data-slot=alert-description]~&]:col-start-3 sm:[svg~[data-slot=alert-title]~&]:col-start-3",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="alert-action"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Alert, AlertTitle, AlertDescription, AlertAction };
|
|
||||||
@@ -1,271 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete";
|
|
||||||
import { ChevronsUpDownIcon, XIcon } from "lucide-react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Input } from "~/components/ui/input";
|
|
||||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
||||||
|
|
||||||
const Autocomplete = AutocompletePrimitive.Root;
|
|
||||||
|
|
||||||
function AutocompleteInput({
|
|
||||||
className,
|
|
||||||
showTrigger = false,
|
|
||||||
showClear = false,
|
|
||||||
startAddon,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: Omit<AutocompletePrimitive.Input.Props, "size"> & {
|
|
||||||
showTrigger?: boolean;
|
|
||||||
showClear?: boolean;
|
|
||||||
startAddon?: React.ReactNode;
|
|
||||||
size?: "sm" | "default" | "lg" | number;
|
|
||||||
ref?: React.Ref<HTMLInputElement>;
|
|
||||||
}) {
|
|
||||||
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="relative not-has-[>*.w-full]:w-fit w-full text-foreground has-disabled:opacity-64">
|
|
||||||
{startAddon && (
|
|
||||||
<div
|
|
||||||
aria-hidden="true"
|
|
||||||
className="[&_svg]:-mx-0.5 pointer-events-none absolute inset-y-0 start-px z-10 flex items-center ps-[calc(--spacing(3)-1px)] opacity-80 has-[+[data-size=sm]]:ps-[calc(--spacing(2.5)-1px)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4"
|
|
||||||
data-slot="autocomplete-start-addon"
|
|
||||||
>
|
|
||||||
{startAddon}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<AutocompletePrimitive.Input
|
|
||||||
className={cn(
|
|
||||||
startAddon &&
|
|
||||||
"data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7.5)-1px)] *:data-[slot=autocomplete-input]:ps-[calc(--spacing(8.5)-1px)] sm:data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7)-1px)] sm:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(8)-1px)]",
|
|
||||||
sizeValue === "sm"
|
|
||||||
? "has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-6.5"
|
|
||||||
: "has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-7",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="autocomplete-input"
|
|
||||||
render={<Input nativeInput size={sizeValue} />}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
{showTrigger && (
|
|
||||||
<AutocompleteTrigger
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
sizeValue === "sm" ? "end-0" : "end-0.5",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<AutocompletePrimitive.Icon data-slot="autocomplete-icon">
|
|
||||||
<ChevronsUpDownIcon />
|
|
||||||
</AutocompletePrimitive.Icon>
|
|
||||||
</AutocompleteTrigger>
|
|
||||||
)}
|
|
||||||
{showClear && (
|
|
||||||
<AutocompleteClear
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
sizeValue === "sm" ? "end-0" : "end-0.5",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</AutocompleteClear>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompletePopup({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
side = "bottom",
|
|
||||||
sideOffset = 4,
|
|
||||||
alignOffset,
|
|
||||||
align = "start",
|
|
||||||
anchor,
|
|
||||||
...props
|
|
||||||
}: AutocompletePrimitive.Popup.Props & {
|
|
||||||
align?: AutocompletePrimitive.Positioner.Props["align"];
|
|
||||||
sideOffset?: AutocompletePrimitive.Positioner.Props["sideOffset"];
|
|
||||||
alignOffset?: AutocompletePrimitive.Positioner.Props["alignOffset"];
|
|
||||||
side?: AutocompletePrimitive.Positioner.Props["side"];
|
|
||||||
anchor?: AutocompletePrimitive.Positioner.Props["anchor"];
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Portal>
|
|
||||||
<AutocompletePrimitive.Positioner
|
|
||||||
align={align}
|
|
||||||
alignOffset={alignOffset}
|
|
||||||
anchor={anchor}
|
|
||||||
className="z-50 select-none"
|
|
||||||
data-slot="autocomplete-positioner"
|
|
||||||
side={side}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"relative flex max-h-full min-w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 transition-[scale,opacity] 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%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<AutocompletePrimitive.Popup
|
|
||||||
className="flex max-h-[min(var(--available-height),23rem)] flex-1 flex-col text-foreground"
|
|
||||||
data-slot="autocomplete-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</AutocompletePrimitive.Popup>
|
|
||||||
</span>
|
|
||||||
</AutocompletePrimitive.Positioner>
|
|
||||||
</AutocompletePrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteItem({ className, children, ...props }: AutocompletePrimitive.Item.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Item
|
|
||||||
className={cn(
|
|
||||||
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="autocomplete-item"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</AutocompletePrimitive.Item>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteSeparator({ className, ...props }: AutocompletePrimitive.Separator.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Separator
|
|
||||||
className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}
|
|
||||||
data-slot="autocomplete-separator"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteGroup({ className, ...props }: AutocompletePrimitive.Group.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Group
|
|
||||||
className={cn("[[role=group]+&]:mt-1.5", className)}
|
|
||||||
data-slot="autocomplete-group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteGroupLabel({ className, ...props }: AutocompletePrimitive.GroupLabel.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.GroupLabel
|
|
||||||
className={cn("px-2 py-1.5 font-medium text-muted-foreground text-xs", className)}
|
|
||||||
data-slot="autocomplete-group-label"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteEmpty({ className, ...props }: AutocompletePrimitive.Empty.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Empty
|
|
||||||
className={cn(
|
|
||||||
"not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="autocomplete-empty"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteRow({ className, ...props }: AutocompletePrimitive.Row.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Row className={className} data-slot="autocomplete-row" {...props} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteValue({ ...props }: AutocompletePrimitive.Value.Props) {
|
|
||||||
return <AutocompletePrimitive.Value data-slot="autocomplete-value" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteList({ className, ...props }: AutocompletePrimitive.List.Props) {
|
|
||||||
return (
|
|
||||||
<ScrollArea scrollbarGutter scrollFade>
|
|
||||||
<AutocompletePrimitive.List
|
|
||||||
className={cn("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3", className)}
|
|
||||||
data-slot="autocomplete-list"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ScrollArea>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteClear({ className, ...props }: AutocompletePrimitive.Clear.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Clear
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-1/2 absolute end-0.5 top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="autocomplete-clear"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</AutocompletePrimitive.Clear>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteStatus({ className, ...props }: AutocompletePrimitive.Status.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Status
|
|
||||||
className={cn(
|
|
||||||
"px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="autocomplete-status"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteCollection({ ...props }: AutocompletePrimitive.Collection.Props) {
|
|
||||||
return <AutocompletePrimitive.Collection data-slot="autocomplete-collection" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function AutocompleteTrigger({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: AutocompletePrimitive.Trigger.Props) {
|
|
||||||
return (
|
|
||||||
<AutocompletePrimitive.Trigger
|
|
||||||
className={className}
|
|
||||||
data-slot="autocomplete-trigger"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</AutocompletePrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const useAutocompleteFilter = AutocompletePrimitive.useFilter;
|
|
||||||
|
|
||||||
export {
|
|
||||||
Autocomplete,
|
|
||||||
AutocompleteInput,
|
|
||||||
AutocompleteTrigger,
|
|
||||||
AutocompletePopup,
|
|
||||||
AutocompleteItem,
|
|
||||||
AutocompleteSeparator,
|
|
||||||
AutocompleteGroup,
|
|
||||||
AutocompleteGroupLabel,
|
|
||||||
AutocompleteEmpty,
|
|
||||||
AutocompleteValue,
|
|
||||||
AutocompleteList,
|
|
||||||
AutocompleteClear,
|
|
||||||
AutocompleteStatus,
|
|
||||||
AutocompleteRow,
|
|
||||||
AutocompleteCollection,
|
|
||||||
useAutocompleteFilter,
|
|
||||||
};
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const badgeVariants = cva(
|
|
||||||
"relative inline-flex shrink-0 items-center justify-center gap-1 whitespace-nowrap rounded-sm border border-transparent font-medium outline-none transition-shadow 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 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-3.5 sm:[&_svg:not([class*='size-'])]:size-3 [&_svg]:pointer-events-none [&_svg]:shrink-0 [button&,a&]:cursor-pointer [button&,a&]:pointer-coarse:after:absolute [button&,a&]:pointer-coarse:after:size-full [button&,a&]:pointer-coarse:after:min-h-11 [button&,a&]:pointer-coarse:after:min-w-11",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
size: "default",
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
size: {
|
|
||||||
default:
|
|
||||||
"h-5.5 min-w-5.5 px-[calc(--spacing(1)-1px)] text-sm sm:h-4.5 sm:min-w-4.5 sm:text-xs",
|
|
||||||
lg: "h-6.5 min-w-6.5 px-[calc(--spacing(1.5)-1px)] text-base sm:h-5.5 sm:min-w-5.5 sm:text-sm",
|
|
||||||
sm: "h-5 min-w-5 rounded-[.25rem] px-[calc(--spacing(1)-1px)] text-xs sm:h-4 sm:min-w-4 sm:text-[.625rem]",
|
|
||||||
},
|
|
||||||
variant: {
|
|
||||||
default: "bg-primary text-primary-foreground [button&,a&]:hover:bg-primary/90",
|
|
||||||
destructive: "bg-destructive text-white [button&,a&]:hover:bg-destructive/90",
|
|
||||||
error: "bg-destructive/8 text-destructive-foreground dark:bg-destructive/16",
|
|
||||||
info: "bg-info/8 text-info-foreground dark:bg-info/16",
|
|
||||||
outline:
|
|
||||||
"border-input bg-background text-foreground dark:bg-input/32 [button&,a&]:hover:bg-accent/50 dark:[button&,a&]:hover:bg-input/48",
|
|
||||||
secondary: "bg-secondary text-secondary-foreground [button&,a&]:hover:bg-secondary/90",
|
|
||||||
success: "bg-success/8 text-success-foreground dark:bg-success/16",
|
|
||||||
warning: "bg-warning/8 text-warning-foreground dark:bg-warning/16",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
interface BadgeProps extends useRender.ComponentProps<"span"> {
|
|
||||||
variant?: VariantProps<typeof badgeVariants>["variant"];
|
|
||||||
size?: VariantProps<typeof badgeVariants>["size"];
|
|
||||||
}
|
|
||||||
|
|
||||||
function Badge({ className, variant, size, render, ...props }: BadgeProps) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(badgeVariants({ className, size, variant })),
|
|
||||||
"data-slot": "badge",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "span",
|
|
||||||
props: mergeProps<"span">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Badge, badgeVariants };
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const buttonVariants = cva(
|
|
||||||
"[&_svg]:-mx-0.5 relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-lg border font-medium text-base 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 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 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 px-[calc(--spacing(3)-1px)] sm:h-8",
|
|
||||||
icon: "size-9 sm:size-8",
|
|
||||||
"icon-lg": "size-10 sm:size-9",
|
|
||||||
"icon-sm": "size-8 sm:size-7",
|
|
||||||
"icon-xl":
|
|
||||||
"size-11 sm:size-10 [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
|
|
||||||
"icon-xs":
|
|
||||||
"size-7 rounded-md before:rounded-[calc(var(--radius-md)-1px)] sm:size-6 not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-4 sm:not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-3.5",
|
|
||||||
lg: "h-10 px-[calc(--spacing(3.5)-1px)] sm:h-9",
|
|
||||||
sm: "h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:h-7",
|
|
||||||
xl: "h-11 px-[calc(--spacing(4)-1px)] text-lg sm:h-10 sm:text-base [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
|
|
||||||
xs: "h-7 gap-1 rounded-md px-[calc(--spacing(2)-1px)] text-sm before:rounded-[calc(var(--radius-md)-1px)] sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5",
|
|
||||||
},
|
|
||||||
variant: {
|
|
||||||
default:
|
|
||||||
"not-disabled:inset-shadow-[0_1px_--theme(--color-white/16%)] border-primary bg-primary text-primary-foreground shadow-primary/24 shadow-xs [:active,[data-pressed]]:inset-shadow-[0_1px_--theme(--color-black/8%)] [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:bg-primary/90",
|
|
||||||
destructive:
|
|
||||||
"not-disabled:inset-shadow-[0_1px_--theme(--color-white/16%)] border-destructive bg-destructive text-white shadow-destructive/24 shadow-xs [:active,[data-pressed]]:inset-shadow-[0_1px_--theme(--color-black/8%)] [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:bg-destructive/90",
|
|
||||||
"destructive-outline":
|
|
||||||
"border-input bg-popover not-dark:bg-clip-padding text-destructive-foreground shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:not-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:border-destructive/32 [:hover,[data-pressed]]:bg-destructive/4",
|
|
||||||
ghost:
|
|
||||||
"border-transparent text-foreground data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent",
|
|
||||||
link: "border-transparent underline-offset-4 [:hover,[data-pressed]]:underline",
|
|
||||||
outline:
|
|
||||||
"border-input bg-popover not-dark:bg-clip-padding text-foreground shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:not-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [:disabled,:active,[data-pressed]]:shadow-none [:hover,[data-pressed]]:bg-accent/50 dark:[:hover,[data-pressed]]:bg-input/64",
|
|
||||||
secondary:
|
|
||||||
"border-transparent bg-secondary text-secondary-foreground [:active,[data-pressed]]:bg-secondary/80 [:hover,[data-pressed]]:bg-secondary/90",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
interface ButtonProps extends useRender.ComponentProps<"button"> {
|
|
||||||
variant?: VariantProps<typeof buttonVariants>["variant"];
|
|
||||||
size?: VariantProps<typeof buttonVariants>["size"];
|
|
||||||
}
|
|
||||||
|
|
||||||
function Button({ className, variant, size, render, ...props }: ButtonProps) {
|
|
||||||
const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] = render
|
|
||||||
? undefined
|
|
||||||
: "button";
|
|
||||||
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(buttonVariants({ className, size, variant })),
|
|
||||||
"data-slot": "button",
|
|
||||||
type: typeValue,
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "button",
|
|
||||||
props: mergeProps<"button">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Button, buttonVariants };
|
|
||||||
@@ -1,196 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Card({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"relative flex flex-col rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFrame({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"[--clip-top:-1rem] [--clip-bottom:-1rem] *:data-[slot=card]:first:[--clip-top:1px] *:data-[slot=card]:last:[--clip-bottom:1px] flex flex-col relative rounded-2xl border bg-card before:bg-muted/72 not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] *:data-[slot=card]:-m-px *:not-last:data-[slot=card]:rounded-b-xl *:not-last:data-[slot=card]:before:rounded-b-[calc(var(--radius-xl)-1px)] *:not-first:data-[slot=card]:rounded-t-xl *:not-first:data-[slot=card]:before:rounded-t-[calc(var(--radius-xl)-1px)] *:data-[slot=card]:[clip-path:inset(var(--clip-top)_1px_var(--clip-bottom)_1px_round_calc(var(--radius-2xl)-1px))] *:data-[slot=card]:shadow-none *:data-[slot=card]:before:hidden *:data-[slot=card]:bg-clip-padding",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card-frame",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFrameHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("relative flex flex-col px-6 py-4", className),
|
|
||||||
"data-slot": "card-frame-header",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFrameTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("font-semibold text-sm", className),
|
|
||||||
"data-slot": "card-frame-title",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFrameDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("text-muted-foreground text-sm", className),
|
|
||||||
"data-slot": "card-frame-description",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFrameFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("px-6 py-4", className),
|
|
||||||
"data-slot": "card-frame-footer",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pb-4 has-data-[slot=card-action]:grid-cols-[1fr_auto]",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card-header",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("font-semibold text-lg leading-none", className),
|
|
||||||
"data-slot": "card-title",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn("text-muted-foreground text-sm", className),
|
|
||||||
"data-slot": "card-description",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardAction({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end inline-flex",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card-action",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardPanel({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"flex-1 p-6 in-[[data-slot=card]:has(>[data-slot=card-header]:not(.border-b))]:pt-0 in-[[data-slot=card]:has(>[data-slot=card-footer]:not(.border-t))]:pb-0",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card-panel",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"flex items-center p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pt-4",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "card-footer",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps<"div">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Card,
|
|
||||||
CardFrame,
|
|
||||||
CardFrameHeader,
|
|
||||||
CardFrameTitle,
|
|
||||||
CardFrameDescription,
|
|
||||||
CardFrameFooter,
|
|
||||||
CardAction,
|
|
||||||
CardDescription,
|
|
||||||
CardFooter,
|
|
||||||
CardHeader,
|
|
||||||
CardPanel,
|
|
||||||
CardPanel as CardContent,
|
|
||||||
CardTitle,
|
|
||||||
};
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) {
|
|
||||||
return (
|
|
||||||
<CheckboxPrimitive.Root
|
|
||||||
className={cn(
|
|
||||||
"relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-[.25rem] border border-input bg-background not-dark:bg-clip-padding shadow-xs/5 outline-none ring-ring transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[3px] not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="checkbox"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<CheckboxPrimitive.Indicator
|
|
||||||
className="-inset-px absolute flex items-center justify-center rounded-[.25rem] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground"
|
|
||||||
data-slot="checkbox-indicator"
|
|
||||||
render={(props, state) => (
|
|
||||||
<span {...props}>
|
|
||||||
{state.indeterminate ? (
|
|
||||||
<svg
|
|
||||||
className="size-3.5 sm:size-3"
|
|
||||||
fill="none"
|
|
||||||
height="24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth="3"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
width="24"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<path d="M5.252 12h13.496" />
|
|
||||||
</svg>
|
|
||||||
) : (
|
|
||||||
<svg
|
|
||||||
className="size-3.5 sm:size-3"
|
|
||||||
fill="none"
|
|
||||||
height="24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth="3"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
width="24"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
|
||||||
</svg>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</CheckboxPrimitive.Root>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Checkbox };
|
|
||||||
@@ -1,380 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";
|
|
||||||
import { CheckIcon, ChevronsUpDownIcon, XIcon } from "lucide-react";
|
|
||||||
import * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Input } from "~/components/ui/input";
|
|
||||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
||||||
|
|
||||||
const ComboboxContext = React.createContext<{
|
|
||||||
chipsRef: React.RefObject<Element | null> | null;
|
|
||||||
multiple: boolean;
|
|
||||||
}>({
|
|
||||||
chipsRef: null,
|
|
||||||
multiple: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
function Combobox<Value, Multiple extends boolean | undefined = false>(
|
|
||||||
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
|
||||||
) {
|
|
||||||
const chipsRef = React.useRef<Element | null>(null);
|
|
||||||
return (
|
|
||||||
<ComboboxContext.Provider value={{ chipsRef, multiple: !!props.multiple }}>
|
|
||||||
<ComboboxPrimitive.Root {...props} />
|
|
||||||
</ComboboxContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxChipsInput({
|
|
||||||
className,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: Omit<ComboboxPrimitive.Input.Props, "size"> & {
|
|
||||||
size?: "sm" | "default" | "lg" | number;
|
|
||||||
ref?: React.Ref<HTMLInputElement>;
|
|
||||||
}) {
|
|
||||||
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Input
|
|
||||||
className={cn(
|
|
||||||
"min-w-12 flex-1 text-base outline-none sm:text-sm [[data-slot=combobox-chip]+&]:ps-0.5",
|
|
||||||
sizeValue === "sm" ? "ps-1.5" : "ps-2",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-size={typeof sizeValue === "string" ? sizeValue : undefined}
|
|
||||||
data-slot="combobox-chips-input"
|
|
||||||
size={typeof sizeValue === "number" ? sizeValue : undefined}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxInput({
|
|
||||||
className,
|
|
||||||
inputClassName,
|
|
||||||
showTrigger = true,
|
|
||||||
showClear = false,
|
|
||||||
startAddon,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: Omit<ComboboxPrimitive.Input.Props, "size"> & {
|
|
||||||
inputClassName?: string;
|
|
||||||
showTrigger?: boolean;
|
|
||||||
showClear?: boolean;
|
|
||||||
startAddon?: React.ReactNode;
|
|
||||||
size?: "sm" | "default" | "lg" | number;
|
|
||||||
ref?: React.Ref<HTMLInputElement>;
|
|
||||||
}) {
|
|
||||||
const sizeValue = (size ?? "default") as "sm" | "default" | "lg" | number;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="relative not-has-[>*.w-full]:w-fit w-full text-foreground has-disabled:opacity-64">
|
|
||||||
{startAddon && (
|
|
||||||
<div
|
|
||||||
aria-hidden="true"
|
|
||||||
className="[&_svg]:-mx-0.5 pointer-events-none absolute inset-y-0 start-px z-10 flex items-center ps-[calc(--spacing(3)-1px)] opacity-80 has-[+[data-size=sm]]:ps-[calc(--spacing(2.5)-1px)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4"
|
|
||||||
data-slot="combobox-start-addon"
|
|
||||||
>
|
|
||||||
{startAddon}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<ComboboxPrimitive.Input
|
|
||||||
className={cn(
|
|
||||||
startAddon &&
|
|
||||||
"data-[size=sm]:*:data-[slot=combobox-input]:ps-[calc(--spacing(7.5)-1px)] *:data-[slot=combobox-input]:ps-[calc(--spacing(8.5)-1px)] sm:data-[size=sm]:*:data-[slot=combobox-input]:ps-[calc(--spacing(7)-1px)] sm:*:data-[slot=combobox-input]:ps-[calc(--spacing(8)-1px)]",
|
|
||||||
sizeValue === "sm"
|
|
||||||
? "has-[+[data-slot=combobox-trigger],+[data-slot=combobox-clear]]:*:data-[slot=combobox-input]:pe-6.5"
|
|
||||||
: "has-[+[data-slot=combobox-trigger],+[data-slot=combobox-clear]]:*:data-[slot=combobox-input]:pe-7",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-input"
|
|
||||||
render={
|
|
||||||
<Input
|
|
||||||
className={cn("has-disabled:opacity-100", inputClassName)}
|
|
||||||
nativeInput
|
|
||||||
size={sizeValue}
|
|
||||||
/>
|
|
||||||
}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
{showTrigger && (
|
|
||||||
<ComboboxTrigger
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-opacity pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=combobox-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
sizeValue === "sm" ? "end-0" : "end-0.5",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<ComboboxPrimitive.Icon data-slot="combobox-icon">
|
|
||||||
<ChevronsUpDownIcon />
|
|
||||||
</ComboboxPrimitive.Icon>
|
|
||||||
</ComboboxTrigger>
|
|
||||||
)}
|
|
||||||
{showClear && (
|
|
||||||
<ComboboxClear
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-opacity pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=combobox-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
sizeValue === "sm" ? "end-0" : "end-0.5",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</ComboboxClear>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxTrigger({ className, children, ...props }: ComboboxPrimitive.Trigger.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Trigger className={className} data-slot="combobox-trigger" {...props}>
|
|
||||||
{children}
|
|
||||||
</ComboboxPrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxPopup({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
side = "bottom",
|
|
||||||
sideOffset = 4,
|
|
||||||
alignOffset,
|
|
||||||
align = "start",
|
|
||||||
anchor: anchorProp,
|
|
||||||
...props
|
|
||||||
}: ComboboxPrimitive.Popup.Props & {
|
|
||||||
align?: ComboboxPrimitive.Positioner.Props["align"];
|
|
||||||
sideOffset?: ComboboxPrimitive.Positioner.Props["sideOffset"];
|
|
||||||
alignOffset?: ComboboxPrimitive.Positioner.Props["alignOffset"];
|
|
||||||
side?: ComboboxPrimitive.Positioner.Props["side"];
|
|
||||||
anchor?: ComboboxPrimitive.Positioner.Props["anchor"];
|
|
||||||
}) {
|
|
||||||
const { chipsRef } = React.useContext(ComboboxContext);
|
|
||||||
const anchor = anchorProp ?? chipsRef;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Portal>
|
|
||||||
<ComboboxPrimitive.Positioner
|
|
||||||
align={align}
|
|
||||||
alignOffset={alignOffset}
|
|
||||||
anchor={anchor}
|
|
||||||
className="z-50 select-none"
|
|
||||||
data-slot="combobox-positioner"
|
|
||||||
side={side}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"relative flex max-h-full min-w-(--anchor-width) max-w-(--available-width) origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 transition-[scale,opacity] 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%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<ComboboxPrimitive.Popup
|
|
||||||
className="flex max-h-[min(var(--available-height),23rem)] flex-1 flex-col text-foreground"
|
|
||||||
data-slot="combobox-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</ComboboxPrimitive.Popup>
|
|
||||||
</span>
|
|
||||||
</ComboboxPrimitive.Positioner>
|
|
||||||
</ComboboxPrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxItem({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
hideIndicator = false,
|
|
||||||
...props
|
|
||||||
}: ComboboxPrimitive.Item.Props & {
|
|
||||||
hideIndicator?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Item
|
|
||||||
className={cn(
|
|
||||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-item"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ComboboxPrimitive.ItemIndicator className={cn("col-start-1", hideIndicator && "hidden")}>
|
|
||||||
<CheckIcon />
|
|
||||||
</ComboboxPrimitive.ItemIndicator>
|
|
||||||
<div className={hideIndicator ? "col-start-1 col-span-full" : "col-start-2"}>{children}</div>
|
|
||||||
</ComboboxPrimitive.Item>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxSeparator({ className, ...props }: ComboboxPrimitive.Separator.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Separator
|
|
||||||
className={cn("mx-2 my-1 h-px bg-border last:hidden", className)}
|
|
||||||
data-slot="combobox-separator"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Group
|
|
||||||
className={cn("[[role=group]+&]:mt-1.5", className)}
|
|
||||||
data-slot="combobox-group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxGroupLabel({ className, ...props }: ComboboxPrimitive.GroupLabel.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.GroupLabel
|
|
||||||
className={cn("px-2 py-1.5 font-medium text-muted-foreground text-xs", className)}
|
|
||||||
data-slot="combobox-group-label"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Empty
|
|
||||||
className={cn(
|
|
||||||
"not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-empty"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxRow({ className, ...props }: ComboboxPrimitive.Row.Props) {
|
|
||||||
return <ComboboxPrimitive.Row className={className} data-slot="combobox-row" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
|
|
||||||
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
|
|
||||||
return (
|
|
||||||
<ScrollArea scrollbarGutter scrollFade>
|
|
||||||
<ComboboxPrimitive.List
|
|
||||||
className={cn(
|
|
||||||
"not-empty:scroll-py-1 not-empty:px-1 not-empty:py-1 in-data-has-overflow-y:pe-3",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-list"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ScrollArea>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
|
|
||||||
return <ComboboxPrimitive.Clear className={className} data-slot="combobox-clear" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxStatus({ className, ...props }: ComboboxPrimitive.Status.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Status
|
|
||||||
className={cn(
|
|
||||||
"px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-status"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxCollection(props: ComboboxPrimitive.Collection.Props) {
|
|
||||||
return <ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxChips({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
startAddon,
|
|
||||||
...props
|
|
||||||
}: ComboboxPrimitive.Chips.Props & {
|
|
||||||
startAddon?: React.ReactNode;
|
|
||||||
}) {
|
|
||||||
const { chipsRef } = React.useContext(ComboboxContext);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Chips
|
|
||||||
className={cn(
|
|
||||||
"relative inline-flex min-h-9 w-full flex-wrap gap-1 rounded-lg border border-input bg-background not-dark:bg-clip-padding p-[calc(--spacing(1)-1px)] text-base shadow-xs/5 outline-none ring-ring/24 transition-shadow *:min-h-7 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-focus-within:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-within:border-ring focus-within:ring-[3px] has-disabled:pointer-events-none has-data-[size=lg]:min-h-10 has-data-[size=sm]:min-h-8 has-aria-invalid:border-destructive/36 has-autofill:bg-foreground/4 has-disabled:opacity-64 has-[:disabled,:focus-within,[aria-invalid]]:shadow-none focus-within:has-aria-invalid:border-destructive/64 focus-within:has-aria-invalid:ring-destructive/16 has-data-[size=lg]:*:min-h-8 has-data-[size=sm]:*:min-h-6 sm:min-h-8 sm:text-sm sm:has-data-[size=lg]:min-h-9 sm:has-data-[size=sm]:min-h-7 sm:*:min-h-6 sm:has-data-[size=lg]:*:min-h-7 sm:has-data-[size=sm]:*:min-h-5 dark:not-has-disabled:bg-input/32 dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:not-focus-within:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="combobox-chips"
|
|
||||||
ref={chipsRef as React.Ref<HTMLDivElement> | null}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{startAddon && (
|
|
||||||
<div
|
|
||||||
aria-hidden="true"
|
|
||||||
className="[&_svg]:-ms-0.5 [&_svg]:-me-1.5 flex shrink-0 items-center ps-2 opacity-80 has-[~[data-size=sm]]:has-[+[data-slot=combobox-chip]]:pe-1.5 has-[~[data-size=sm]]:ps-1.5 has-[+[data-slot=combobox-chip]]:pe-2 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none"
|
|
||||||
data-slot="combobox-start-addon"
|
|
||||||
>
|
|
||||||
{startAddon}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{children}
|
|
||||||
</ComboboxPrimitive.Chips>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxChip({ children, ...props }: ComboboxPrimitive.Chip.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.Chip
|
|
||||||
className="flex items-center rounded-[calc(var(--radius-md)-1px)] bg-accent ps-2 font-medium text-accent-foreground text-sm outline-none sm:text-xs/(--text-xs--line-height) [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5"
|
|
||||||
data-slot="combobox-chip"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<ComboboxChipRemove />
|
|
||||||
</ComboboxPrimitive.Chip>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ComboboxChipRemove(props: ComboboxPrimitive.ChipRemove.Props) {
|
|
||||||
return (
|
|
||||||
<ComboboxPrimitive.ChipRemove
|
|
||||||
aria-label="Remove"
|
|
||||||
className="h-full shrink-0 cursor-pointer px-1.5 opacity-80 hover:opacity-100 [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5"
|
|
||||||
data-slot="combobox-chip-remove"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</ComboboxPrimitive.ChipRemove>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const useComboboxFilter = ComboboxPrimitive.useFilter;
|
|
||||||
|
|
||||||
export {
|
|
||||||
Combobox,
|
|
||||||
ComboboxChipsInput,
|
|
||||||
ComboboxInput,
|
|
||||||
ComboboxTrigger,
|
|
||||||
ComboboxPopup,
|
|
||||||
ComboboxItem,
|
|
||||||
ComboboxSeparator,
|
|
||||||
ComboboxGroup,
|
|
||||||
ComboboxGroupLabel,
|
|
||||||
ComboboxEmpty,
|
|
||||||
ComboboxValue,
|
|
||||||
ComboboxList,
|
|
||||||
ComboboxClear,
|
|
||||||
ComboboxStatus,
|
|
||||||
ComboboxRow,
|
|
||||||
ComboboxCollection,
|
|
||||||
ComboboxChips,
|
|
||||||
ComboboxChip,
|
|
||||||
useComboboxFilter,
|
|
||||||
};
|
|
||||||
@@ -1,221 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Dialog as CommandDialogPrimitive } from "@base-ui/react/dialog";
|
|
||||||
import { SearchIcon } from "lucide-react";
|
|
||||||
import type * as React from "react";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import {
|
|
||||||
Autocomplete,
|
|
||||||
AutocompleteCollection,
|
|
||||||
AutocompleteEmpty,
|
|
||||||
AutocompleteGroup,
|
|
||||||
AutocompleteGroupLabel,
|
|
||||||
AutocompleteInput,
|
|
||||||
AutocompleteItem,
|
|
||||||
AutocompleteList,
|
|
||||||
AutocompleteSeparator,
|
|
||||||
} from "~/components/ui/autocomplete";
|
|
||||||
|
|
||||||
const CommandDialog = CommandDialogPrimitive.Root;
|
|
||||||
|
|
||||||
const CommandDialogPortal = CommandDialogPrimitive.Portal;
|
|
||||||
|
|
||||||
const CommandCreateHandle = CommandDialogPrimitive.createHandle;
|
|
||||||
|
|
||||||
function CommandDialogTrigger(props: CommandDialogPrimitive.Trigger.Props) {
|
|
||||||
return <CommandDialogPrimitive.Trigger data-slot="command-dialog-trigger" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandDialogBackdrop({ className, ...props }: CommandDialogPrimitive.Backdrop.Props) {
|
|
||||||
return (
|
|
||||||
<CommandDialogPrimitive.Backdrop
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="command-dialog-backdrop"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandDialogViewport({ className, ...props }: CommandDialogPrimitive.Viewport.Props) {
|
|
||||||
return (
|
|
||||||
<CommandDialogPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 flex flex-col items-center px-4 py-[max(--spacing(4),4vh)] sm:py-[10vh]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="command-dialog-viewport"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandDialogPopup({ className, children, ...props }: CommandDialogPrimitive.Popup.Props) {
|
|
||||||
return (
|
|
||||||
<CommandDialogPortal>
|
|
||||||
<CommandDialogBackdrop />
|
|
||||||
<CommandDialogViewport>
|
|
||||||
<CommandDialogPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-105 min-h-0 w-full min-w-0 max-w-xl scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover not-dark:bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg/5 outline-none transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:bg-muted/72 before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="command-dialog-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</CommandDialogPrimitive.Popup>
|
|
||||||
</CommandDialogViewport>
|
|
||||||
</CommandDialogPortal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Command({
|
|
||||||
autoHighlight = "always",
|
|
||||||
keepHighlight = true,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof Autocomplete>) {
|
|
||||||
return (
|
|
||||||
<Autocomplete
|
|
||||||
autoHighlight={autoHighlight}
|
|
||||||
inline
|
|
||||||
keepHighlight={keepHighlight}
|
|
||||||
open
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandInput({
|
|
||||||
className,
|
|
||||||
placeholder = undefined,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AutocompleteInput>) {
|
|
||||||
return (
|
|
||||||
<div className="px-2.5 py-1.5">
|
|
||||||
<AutocompleteInput
|
|
||||||
autoFocus
|
|
||||||
className={cn(
|
|
||||||
"border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
placeholder={placeholder}
|
|
||||||
size="lg"
|
|
||||||
startAddon={<SearchIcon />}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandList({ className, ...props }: React.ComponentProps<typeof AutocompleteList>) {
|
|
||||||
return (
|
|
||||||
<AutocompleteList
|
|
||||||
className={cn("not-empty:scroll-py-2 not-empty:p-2", className)}
|
|
||||||
data-slot="command-list"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandEmpty({ className, ...props }: React.ComponentProps<typeof AutocompleteEmpty>) {
|
|
||||||
return (
|
|
||||||
<AutocompleteEmpty
|
|
||||||
className={cn("not-empty:py-6", className)}
|
|
||||||
data-slot="command-empty"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandPanel({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="-mx-px not-has-[+[data-slot=command-footer]]:-mb-px relative min-h-0 rounded-t-xl not-has-[+[data-slot=command-footer]]:rounded-b-2xl border border-b-0 bg-popover bg-clip-padding shadow-xs/5 [clip-path:inset(0_1px)] not-has-[+[data-slot=command-footer]]:[clip-path:inset(0_1px_1px_1px_round_0_0_calc(var(--radius-2xl)-1px)_calc(var(--radius-2xl)-1px))] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandGroup({ className, ...props }: React.ComponentProps<typeof AutocompleteGroup>) {
|
|
||||||
return <AutocompleteGroup className={className} data-slot="command-group" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandGroupLabel({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AutocompleteGroupLabel>) {
|
|
||||||
return (
|
|
||||||
<AutocompleteGroupLabel className={className} data-slot="command-group-label" {...props} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandCollection({ ...props }: React.ComponentProps<typeof AutocompleteCollection>) {
|
|
||||||
return <AutocompleteCollection data-slot="command-collection" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandItem({ className, ...props }: React.ComponentProps<typeof AutocompleteItem>) {
|
|
||||||
return (
|
|
||||||
<AutocompleteItem className={cn("py-1.5", className)} data-slot="command-item" {...props} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandSeparator({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof AutocompleteSeparator>) {
|
|
||||||
return (
|
|
||||||
<AutocompleteSeparator
|
|
||||||
className={cn("my-2", className)}
|
|
||||||
data-slot="command-separator"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
|
|
||||||
return (
|
|
||||||
<kbd
|
|
||||||
className={cn(
|
|
||||||
"ms-auto font-medium font-sans text-muted-foreground/72 text-xs tracking-widest",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="command-shortcut"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] border-t px-5 py-3 text-muted-foreground text-xs",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="command-footer"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
CommandCreateHandle,
|
|
||||||
Command,
|
|
||||||
CommandCollection,
|
|
||||||
CommandDialog,
|
|
||||||
CommandDialogPopup,
|
|
||||||
CommandDialogTrigger,
|
|
||||||
CommandEmpty,
|
|
||||||
CommandFooter,
|
|
||||||
CommandGroup,
|
|
||||||
CommandGroupLabel,
|
|
||||||
CommandInput,
|
|
||||||
CommandItem,
|
|
||||||
CommandList,
|
|
||||||
CommandPanel,
|
|
||||||
CommandSeparator,
|
|
||||||
CommandShortcut,
|
|
||||||
};
|
|
||||||
@@ -1,181 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
|
|
||||||
import { XIcon } from "lucide-react";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Button } from "~/components/ui/button";
|
|
||||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
||||||
|
|
||||||
const DialogCreateHandle = DialogPrimitive.createHandle;
|
|
||||||
|
|
||||||
const Dialog = DialogPrimitive.Root;
|
|
||||||
|
|
||||||
const DialogPortal = DialogPrimitive.Portal;
|
|
||||||
|
|
||||||
function DialogTrigger(props: DialogPrimitive.Trigger.Props) {
|
|
||||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogClose(props: DialogPrimitive.Close.Props) {
|
|
||||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogBackdrop({ className, ...props }: DialogPrimitive.Backdrop.Props) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Backdrop
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-backdrop"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogViewport({ className, ...props }: DialogPrimitive.Viewport.Props) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 grid grid-rows-[1fr_auto_3fr] justify-items-center p-4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-viewport"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogPopup({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
showCloseButton = true,
|
|
||||||
bottomStickOnMobile = true,
|
|
||||||
...props
|
|
||||||
}: DialogPrimitive.Popup.Props & {
|
|
||||||
showCloseButton?: boolean;
|
|
||||||
bottomStickOnMobile?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<DialogPortal>
|
|
||||||
<DialogBackdrop />
|
|
||||||
<DialogViewport
|
|
||||||
className={cn(bottomStickOnMobile && "max-sm:grid-rows-[1fr_auto] max-sm:p-0 max-sm:pt-12")}
|
|
||||||
>
|
|
||||||
<DialogPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-full min-h-0 w-full min-w-0 max-w-lg scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover not-dark:bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg/5 transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
bottomStickOnMobile &&
|
|
||||||
"max-sm:max-w-none max-sm:rounded-none max-sm:border-x-0 max-sm:border-t max-sm:border-b-0 max-sm:opacity-[calc(1-min(var(--nested-dialogs),1))] max-sm:data-ending-style:translate-y-4 max-sm:data-starting-style:translate-y-4 max-sm:before:hidden max-sm:before:rounded-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
{showCloseButton && (
|
|
||||||
<DialogPrimitive.Close
|
|
||||||
aria-label="Close"
|
|
||||||
className="absolute end-2 top-2"
|
|
||||||
render={<Button size="icon" variant="ghost" />}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</DialogPrimitive.Close>
|
|
||||||
)}
|
|
||||||
</DialogPrimitive.Popup>
|
|
||||||
</DialogViewport>
|
|
||||||
</DialogPortal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col gap-2 p-6 in-[[data-slot=dialog-popup]:has([data-slot=dialog-panel])]:pb-3 max-sm:pb-4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-header"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogFooter({
|
|
||||||
className,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & {
|
|
||||||
variant?: "default" | "bare";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col-reverse gap-2 px-6 sm:flex-row sm:justify-end sm:rounded-b-[calc(var(--radius-2xl)-1px)]",
|
|
||||||
variant === "default" && "border-t bg-muted/72 py-4",
|
|
||||||
variant === "bare" &&
|
|
||||||
"in-[[data-slot=dialog-popup]:has([data-slot=dialog-panel])]:pt-3 pt-4 pb-6",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-footer"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Title
|
|
||||||
className={cn("font-heading font-semibold text-xl leading-none", className)}
|
|
||||||
data-slot="dialog-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
|
|
||||||
return (
|
|
||||||
<DialogPrimitive.Description
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
data-slot="dialog-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DialogPanel({
|
|
||||||
className,
|
|
||||||
scrollFade = true,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & { scrollFade?: boolean }) {
|
|
||||||
return (
|
|
||||||
<ScrollArea scrollFade={scrollFade}>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"p-6 in-[[data-slot=dialog-popup]:has([data-slot=dialog-header])]:pt-1 in-[[data-slot=dialog-popup]:has([data-slot=dialog-footer]:not(.border-t))]:pb-1",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="dialog-panel"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ScrollArea>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
DialogCreateHandle,
|
|
||||||
Dialog,
|
|
||||||
DialogTrigger,
|
|
||||||
DialogPortal,
|
|
||||||
DialogClose,
|
|
||||||
DialogBackdrop,
|
|
||||||
DialogBackdrop as DialogOverlay,
|
|
||||||
DialogPopup,
|
|
||||||
DialogPopup as DialogContent,
|
|
||||||
DialogHeader,
|
|
||||||
DialogFooter,
|
|
||||||
DialogTitle,
|
|
||||||
DialogDescription,
|
|
||||||
DialogPanel,
|
|
||||||
DialogViewport,
|
|
||||||
};
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance p-6 text-center md:p-12",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="empty"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("flex max-w-sm flex-col items-center text-center", className)}
|
|
||||||
data-slot="empty-header"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const emptyMediaVariants = cva(
|
|
||||||
"flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default: "bg-transparent",
|
|
||||||
icon: "relative flex size-9 shrink-0 items-center justify-center rounded-md border bg-card not-dark:bg-clip-padding text-foreground shadow-sm/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-md)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='size-'])]:size-4.5",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function EmptyMedia({
|
|
||||||
className,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("relative mb-6", className)}
|
|
||||||
data-slot="empty-media"
|
|
||||||
data-variant={variant}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{variant === "icon" && (
|
|
||||||
<>
|
|
||||||
<div
|
|
||||||
aria-hidden="true"
|
|
||||||
className={cn(
|
|
||||||
emptyMediaVariants({ className, variant }),
|
|
||||||
"-translate-x-0.5 -rotate-10 pointer-events-none absolute bottom-px origin-bottom-left scale-84 shadow-none",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div
|
|
||||||
aria-hidden="true"
|
|
||||||
className={cn(
|
|
||||||
emptyMediaVariants({ className, variant }),
|
|
||||||
"pointer-events-none absolute bottom-px origin-bottom-right translate-x-0.5 rotate-10 scale-84 shadow-none",
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div className={cn(emptyMediaVariants({ className, variant }))} {...props} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn("font-heading font-semibold text-xl", className)}
|
|
||||||
data-slot="empty-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"text-muted-foreground text-sm [&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4 [[data-slot=empty-title]+&]:mt-1",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="empty-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="empty-content"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia };
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Field as FieldPrimitive } from "@base-ui/react/field";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Field({ className, ...props }: FieldPrimitive.Root.Props) {
|
|
||||||
return (
|
|
||||||
<FieldPrimitive.Root
|
|
||||||
className={cn("flex flex-col items-start gap-2", className)}
|
|
||||||
data-slot="field"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldLabel({ className, ...props }: FieldPrimitive.Label.Props) {
|
|
||||||
return (
|
|
||||||
<FieldPrimitive.Label
|
|
||||||
className={cn(
|
|
||||||
"inline-flex items-center gap-2 font-medium text-base/4.5 text-foreground sm:text-sm/4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="field-label"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldItem({ className, ...props }: FieldPrimitive.Item.Props) {
|
|
||||||
return (
|
|
||||||
<FieldPrimitive.Item className={cn("flex", className)} data-slot="field-item" {...props} />
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldDescription({ className, ...props }: FieldPrimitive.Description.Props) {
|
|
||||||
return (
|
|
||||||
<FieldPrimitive.Description
|
|
||||||
className={cn("text-muted-foreground text-xs", className)}
|
|
||||||
data-slot="field-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FieldError({ className, ...props }: FieldPrimitive.Error.Props) {
|
|
||||||
return (
|
|
||||||
<FieldPrimitive.Error
|
|
||||||
className={cn("text-destructive-foreground text-xs", className)}
|
|
||||||
data-slot="field-error"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const FieldControl = FieldPrimitive.Control;
|
|
||||||
const FieldValidity = FieldPrimitive.Validity;
|
|
||||||
|
|
||||||
export { Field, FieldLabel, FieldDescription, FieldError, FieldControl, FieldItem, FieldValidity };
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Fieldset as FieldsetPrimitive } from "@base-ui/react/fieldset";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Fieldset({ className, ...props }: FieldsetPrimitive.Root.Props) {
|
|
||||||
return (
|
|
||||||
<FieldsetPrimitive.Root
|
|
||||||
className={cn("flex w-full max-w-64 flex-col gap-6", className)}
|
|
||||||
data-slot="fieldset"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
function FieldsetLegend({ className, ...props }: FieldsetPrimitive.Legend.Props) {
|
|
||||||
return (
|
|
||||||
<FieldsetPrimitive.Legend
|
|
||||||
className={cn("font-semibold text-foreground", className)}
|
|
||||||
data-slot="fieldset-legend"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Fieldset, FieldsetLegend };
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Form as FormPrimitive } from "@base-ui/react/form";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Form({ className, ...props }: FormPrimitive.Props) {
|
|
||||||
return (
|
|
||||||
<FormPrimitive
|
|
||||||
className={cn("flex w-full flex-col gap-4", className)}
|
|
||||||
data-slot="form"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Form };
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Separator } from "./separator";
|
|
||||||
|
|
||||||
const groupVariants = cva(
|
|
||||||
"flex w-fit *:focus-visible:z-1 has-[>[data-slot=group]]:gap-2 *:has-focus-visible:z-1 dark:*:[[data-slot=button]:hover~[data-slot=separator]:not([data-slot]:hover~[data-slot=separator]~[data-slot=separator]),[data-slot][data-pressed]~[data-slot=separator]:not([data-slot][data-pressed]~[data-slot=separator]~[data-slot=separator])]:before:bg-input/64 dark:*:[[data-slot=separator]:has(~[data-slot=button]:hover):not(:has(~[data-slot=separator]~[data-slot]:hover)),[data-slot=separator]:has(~[data-slot][data-pressed]):not(:has(~[data-slot=separator]~[data-slot][data-pressed]))]:before:bg-input/64",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
orientation: "horizontal",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
orientation: {
|
|
||||||
horizontal:
|
|
||||||
"*:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:-start-[0.5px] *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:-end-[0.5px] *:pointer-coarse:after:min-w-auto *:data-slot:has-[~[data-slot]]:rounded-e-none *:data-slot:has-[~[data-slot]]:border-e-0 *:data-slot:has-[~[data-slot]]:before:rounded-e-none *:[[data-slot]~[data-slot]]:rounded-s-none *:[[data-slot]~[data-slot]]:border-s-0 *:[[data-slot]~[data-slot]]:before:rounded-s-none",
|
|
||||||
vertical:
|
|
||||||
"*:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:-top-[0.5px] *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:-bottom-[0.5px] flex-col *:pointer-coarse:after:min-h-auto *:data-slot:has-[~[data-slot]]:rounded-b-none *:data-slot:has-[~[data-slot]]:border-b-0 *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:hidden *:data-slot:has-[~[data-slot]]:before:rounded-b-none dark:*:last:before:hidden dark:*:first:before:block *:[[data-slot]~[data-slot]]:rounded-t-none *:[[data-slot]~[data-slot]]:border-t-0 *:[[data-slot]~[data-slot]]:before:rounded-t-none",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function Group({
|
|
||||||
className,
|
|
||||||
orientation,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: {
|
|
||||||
className?: string;
|
|
||||||
orientation?: VariantProps<typeof groupVariants>["orientation"];
|
|
||||||
children: React.ReactNode;
|
|
||||||
} & React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(groupVariants({ orientation }), className)}
|
|
||||||
data-orientation={orientation}
|
|
||||||
data-slot="group"
|
|
||||||
role="group"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function GroupText({ className, render, ...props }: useRender.ComponentProps<"div">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"relative inline-flex items-center whitespace-nowrap gap-2 rounded-lg border border-input bg-muted not-dark:bg-clip-padding px-[calc(--spacing(3)-1px)] text-muted-foreground text-base sm:text-sm shadow-xs/5 outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/6%)] dark:bg-input/64 dark:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 [&_svg]:-mx-0.5",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "group-text",
|
|
||||||
};
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "div",
|
|
||||||
props: mergeProps(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function GroupSeparator({
|
|
||||||
className,
|
|
||||||
orientation = "vertical",
|
|
||||||
...props
|
|
||||||
}: {
|
|
||||||
className?: string;
|
|
||||||
} & React.ComponentProps<typeof Separator>) {
|
|
||||||
return (
|
|
||||||
<Separator
|
|
||||||
className={cn(
|
|
||||||
"[[data-slot=input-control]:focus-within+&,[data-slot=input-group]:focus-within+&,[data-slot=select-trigger]:focus-visible+*+&,[data-slot=number-field]:focus-within+input+&]:-translate-x-px pointer-events-none relative z-2 bg-input before:absolute before:inset-0 has-[+[data-slot=input-control]:focus-within,+[data-slot=input-group]:focus-within,+[data-slot=select-trigger]:focus-visible+*,+[data-slot=number-field]:focus-within]:translate-x-px has-[+[data-slot=input-control]:focus-within,+[data-slot=input-group]:focus-within,+[data-slot=select-trigger]:focus-visible+*,+[data-slot=number-field]:focus-within]:bg-ring dark:before:bg-input/32 [[data-slot=input-control]:focus-within+&,[data-slot=input-group]:focus-within+&,[data-slot=select-trigger]:focus-visible+*+&,[data-slot=number-field]:focus-within+&,[data-slot=number-field]:focus-within+input+&]:bg-ring",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
orientation={orientation}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Group,
|
|
||||||
Group as ButtonGroup,
|
|
||||||
GroupText,
|
|
||||||
GroupText as ButtonGroupText,
|
|
||||||
GroupSeparator,
|
|
||||||
GroupSeparator as ButtonGroupSeparator,
|
|
||||||
groupVariants,
|
|
||||||
};
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Input, type InputProps } from "~/components/ui/input";
|
|
||||||
import { Textarea, type TextareaProps } from "~/components/ui/textarea";
|
|
||||||
|
|
||||||
function InputGroup({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"relative inline-flex w-full min-w-0 items-center rounded-lg border border-input bg-background not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-[input:disabled,textarea:disabled]:not-has-[input:focus-visible,textarea:focus-visible]:not-has-[input[aria-invalid],textarea[aria-invalid]]:before:shadow-[0_1px_--theme(--color-black/4%)] has-[input:focus-visible,textarea:focus-visible]:has-[input[aria-invalid],textarea[aria-invalid]]:border-destructive/64 has-[input:focus-visible,textarea:focus-visible]:has-[input[aria-invalid],textarea[aria-invalid]]:ring-destructive/16 has-[textarea]:h-auto has-data-[align=block-end]:h-auto has-data-[align=block-start]:h-auto has-data-[align=block-end]:flex-col has-data-[align=block-start]:flex-col has-[input:focus-visible,textarea:focus-visible]:border-ring has-[input[aria-invalid],textarea[aria-invalid]]:border-destructive/36 has-autofill:bg-foreground/4 has-[input:disabled,textarea:disabled]:opacity-64 has-[input:disabled,textarea:disabled,input:focus-visible,textarea:focus-visible,input[aria-invalid],textarea[aria-invalid]]:shadow-none has-[input:focus-visible,textarea:focus-visible]:ring-[3px] sm:text-sm dark:bg-input/32 dark:has-autofill:bg-foreground/8 dark:has-[input[aria-invalid],textarea[aria-invalid]]:ring-destructive/24 dark:not-has-[input:disabled,textarea:disabled]:not-has-[input:focus-visible,textarea:focus-visible]:not-has-[input[aria-invalid],textarea[aria-invalid]]:before:shadow-[0_-1px_--theme(--color-white/6%)] has-data-[align=inline-start]:**:[[data-size=sm]_input]:ps-1.5 has-data-[align=inline-end]:**:[[data-size=sm]_input]:pe-1.5 *:[[data-slot=input-control],[data-slot=textarea-control]]:contents *:[[data-slot=input-control],[data-slot=textarea-control]]:before:hidden has-[[data-align=block-start],[data-align=block-end]]:**:[input]:h-auto has-data-[align=inline-start]:**:[input]:ps-2 has-data-[align=inline-end]:**:[input]:pe-2 has-data-[align=block-end]:**:[input]:pt-1.5 has-data-[align=block-start]:**:[input]:pb-1.5 **:[textarea]:min-h-20.5 **:[textarea]:resize-none **:[textarea]:py-[calc(--spacing(3)-1px)] **:[textarea]:max-sm:min-h-23.5 **:[textarea_button]:rounded-[calc(var(--radius-md)-1px)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="input-group"
|
|
||||||
role="group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const inputGroupAddonVariants = cva(
|
|
||||||
"[&_svg]:-mx-0.5 flex h-auto cursor-text select-none items-center justify-center gap-2 leading-none [&>kbd]:rounded-[calc(var(--radius)-5px)] in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4.5 sm:in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4 not-has-[button]:**:[svg:not([class*='opacity-'])]:opacity-80",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
align: "inline-start",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
align: {
|
|
||||||
"block-end":
|
|
||||||
"order-last w-full justify-start px-[calc(--spacing(3)-1px)] pb-[calc(--spacing(3)-1px)] [.border-t]:pt-[calc(--spacing(3)-1px)] [[data-size=sm]+&]:px-[calc(--spacing(2.5)-1px)]",
|
|
||||||
"block-start":
|
|
||||||
"order-first w-full justify-start px-[calc(--spacing(3)-1px)] pt-[calc(--spacing(3)-1px)] [.border-b]:pb-[calc(--spacing(3)-1px)] [[data-size=sm]+&]:px-[calc(--spacing(2.5)-1px)]",
|
|
||||||
"inline-end":
|
|
||||||
"has-[>:last-child[data-slot=badge]]:-me-1.5 has-[>button]:-me-2 order-last pe-[calc(--spacing(3)-1px)] has-[>kbd:last-child]:me-[-0.35rem] [[data-size=sm]+&]:pe-[calc(--spacing(2.5)-1px)]",
|
|
||||||
"inline-start":
|
|
||||||
"has-[>:last-child[data-slot=badge]]:-ms-1.5 has-[>button]:-ms-2 order-first ps-[calc(--spacing(3)-1px)] has-[>kbd:last-child]:ms-[-0.35rem] [[data-size=sm]+&]:ps-[calc(--spacing(2.5)-1px)]",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
function InputGroupAddon({
|
|
||||||
className,
|
|
||||||
align = "inline-start",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & VariantProps<typeof inputGroupAddonVariants>) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(inputGroupAddonVariants({ align }), className)}
|
|
||||||
data-align={align}
|
|
||||||
data-slot="input-group-addon"
|
|
||||||
onMouseDown={(e) => {
|
|
||||||
const target = e.target as HTMLElement;
|
|
||||||
const isInteractive = target.closest(
|
|
||||||
"button, a, input, select, textarea, [role='button'], [role='combobox'], [role='listbox'], [data-slot='select-trigger']",
|
|
||||||
);
|
|
||||||
if (isInteractive) return;
|
|
||||||
e.preventDefault();
|
|
||||||
const parent = e.currentTarget.parentElement;
|
|
||||||
const input = parent?.querySelector<HTMLInputElement | HTMLTextAreaElement>(
|
|
||||||
"input, textarea",
|
|
||||||
);
|
|
||||||
if (input && !parent?.querySelector("input:focus, textarea:focus")) {
|
|
||||||
input.focus();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function InputGroupText({ className, ...props }: React.ComponentProps<"span">) {
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"[&_svg]:-mx-0.5 line-clamp-1 flex items-center gap-2 text-muted-foreground leading-none in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4.5 sm:in-[[data-slot=input-group]:has([data-slot=input-control],[data-slot=textarea-control])]:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function InputGroupInput({ className, ...props }: InputProps) {
|
|
||||||
return <Input className={className} unstyled {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function InputGroupTextarea({ className, ...props }: TextareaProps) {
|
|
||||||
return <Textarea className={className} unstyled {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
export { InputGroup, InputGroupAddon, InputGroupText, InputGroupInput, InputGroupTextarea };
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Input as InputPrimitive } from "@base-ui/react/input";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
type InputProps = Omit<InputPrimitive.Props & React.RefAttributes<HTMLInputElement>, "size"> & {
|
|
||||||
size?: "sm" | "default" | "lg" | number;
|
|
||||||
unstyled?: boolean;
|
|
||||||
nativeInput?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
function Input({
|
|
||||||
className,
|
|
||||||
size = "default",
|
|
||||||
unstyled = false,
|
|
||||||
nativeInput = false,
|
|
||||||
...props
|
|
||||||
}: InputProps) {
|
|
||||||
const inputClassName = cn(
|
|
||||||
"h-8.5 w-full min-w-0 rounded-[inherit] px-[calc(--spacing(3)-1px)] leading-8.5 outline-none placeholder:text-muted-foreground/72 sm:h-7.5 sm:leading-7.5 [transition:background-color_5000000s_ease-in-out_0s]",
|
|
||||||
size === "sm" && "h-7.5 px-[calc(--spacing(2.5)-1px)] leading-7.5 sm:h-6.5 sm:leading-6.5",
|
|
||||||
size === "lg" && "h-9.5 leading-9.5 sm:h-8.5 sm:leading-8.5",
|
|
||||||
props.type === "search" &&
|
|
||||||
"[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none [&::-webkit-search-results-button]:appearance-none [&::-webkit-search-results-decoration]:appearance-none",
|
|
||||||
props.type === "file" &&
|
|
||||||
"text-muted-foreground file:me-3 file:bg-transparent file:font-medium file:text-foreground file:text-sm",
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={
|
|
||||||
cn(
|
|
||||||
!unstyled &&
|
|
||||||
"relative inline-flex w-full rounded-lg border border-input bg-background not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-aria-invalid:border-destructive/36 has-focus-visible:border-ring has-autofill:bg-foreground/4 has-disabled:opacity-64 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none has-focus-visible:ring-[3px] sm:text-sm dark:bg-input/32 dark:has-autofill:bg-foreground/8 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:not-has-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
) || undefined
|
|
||||||
}
|
|
||||||
data-size={size}
|
|
||||||
data-slot="input-control"
|
|
||||||
>
|
|
||||||
{nativeInput ? (
|
|
||||||
<input
|
|
||||||
className={inputClassName}
|
|
||||||
data-slot="input"
|
|
||||||
size={typeof size === "number" ? size : undefined}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<InputPrimitive
|
|
||||||
className={inputClassName}
|
|
||||||
data-slot="input"
|
|
||||||
size={typeof size === "number" ? size : undefined}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Input, type InputProps };
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
|
||||||
return (
|
|
||||||
<kbd
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none inline-flex h-5 min-w-5 select-none items-center justify-center gap-1 rounded bg-muted px-1 font-medium font-sans text-muted-foreground text-xs [&_svg:not([class*='size-'])]:size-3",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="kbd"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function KbdGroup({ className, ...props }: React.ComponentProps<"kbd">) {
|
|
||||||
return (
|
|
||||||
<kbd
|
|
||||||
className={cn("inline-flex items-center gap-1", className)}
|
|
||||||
data-slot="kbd-group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Kbd, KbdGroup };
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Label({ className, render, ...props }: useRender.ComponentProps<"label">) {
|
|
||||||
const defaultProps = {
|
|
||||||
className: cn(
|
|
||||||
"inline-flex items-center gap-2 text-base/4.5 sm:text-sm/4 font-medium text-foreground",
|
|
||||||
className,
|
|
||||||
),
|
|
||||||
"data-slot": "label",
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "label",
|
|
||||||
props: mergeProps<"label">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Label };
|
|
||||||
@@ -1,310 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
|
|
||||||
import { ChevronRightIcon } from "lucide-react";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const MenuCreateHandle = MenuPrimitive.createHandle;
|
|
||||||
|
|
||||||
const Menu = MenuPrimitive.Root;
|
|
||||||
|
|
||||||
const MenuPortal = MenuPrimitive.Portal;
|
|
||||||
|
|
||||||
function MenuTrigger({ className, children, ...props }: MenuPrimitive.Trigger.Props) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.Trigger className={className} data-slot="menu-trigger" {...props}>
|
|
||||||
{children}
|
|
||||||
</MenuPrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuPopup({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
sideOffset = 4,
|
|
||||||
align = "center",
|
|
||||||
alignOffset,
|
|
||||||
side = "bottom",
|
|
||||||
anchor,
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.Popup.Props & {
|
|
||||||
align?: MenuPrimitive.Positioner.Props["align"];
|
|
||||||
sideOffset?: MenuPrimitive.Positioner.Props["sideOffset"];
|
|
||||||
alignOffset?: MenuPrimitive.Positioner.Props["alignOffset"];
|
|
||||||
side?: MenuPrimitive.Positioner.Props["side"];
|
|
||||||
anchor?: MenuPrimitive.Positioner.Props["anchor"];
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.Portal>
|
|
||||||
<MenuPrimitive.Positioner
|
|
||||||
align={align}
|
|
||||||
alignOffset={alignOffset}
|
|
||||||
anchor={anchor}
|
|
||||||
className="z-50"
|
|
||||||
data-slot="menu-positioner"
|
|
||||||
side={side}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
>
|
|
||||||
<MenuPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"relative flex not-[class*='w-']:min-w-32 origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] focus:outline-none dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="menu-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className="max-h-(--available-height) w-full overflow-y-auto p-1">{children}</div>
|
|
||||||
</MenuPrimitive.Popup>
|
|
||||||
</MenuPrimitive.Positioner>
|
|
||||||
</MenuPrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuGroup(props: MenuPrimitive.Group.Props) {
|
|
||||||
return <MenuPrimitive.Group data-slot="menu-group" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuItem({
|
|
||||||
className,
|
|
||||||
inset,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.Item.Props & {
|
|
||||||
inset?: boolean;
|
|
||||||
variant?: "default" | "destructive";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.Item
|
|
||||||
className={cn(
|
|
||||||
"[&>svg]:-mx-0.5 flex min-h-8 cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-inset:ps-8 data-[variant=destructive]:text-destructive-foreground data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 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",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-inset={inset}
|
|
||||||
data-slot="menu-item"
|
|
||||||
data-variant={variant}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuCheckboxItem({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
checked,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.CheckboxItem.Props & {
|
|
||||||
variant?: "default" | "switch";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.CheckboxItem
|
|
||||||
checked={checked}
|
|
||||||
className={cn(
|
|
||||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 ps-2 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
variant === "switch" ? "grid-cols-[1fr_auto] gap-4 pe-1.5" : "grid-cols-[1rem_1fr] pe-4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="menu-checkbox-item"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{variant === "switch" ? (
|
|
||||||
<>
|
|
||||||
<span className="col-start-1">{children}</span>
|
|
||||||
<MenuPrimitive.CheckboxItemIndicator
|
|
||||||
className="inset-shadow-[0_1px_--theme(--color-black/4%)] inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 items-center rounded-full p-px outline-none transition-[background-color,box-shadow] duration-200 [--thumb-size:--spacing(4)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:opacity-64 sm:[--thumb-size:--spacing(3)]"
|
|
||||||
keepMounted
|
|
||||||
>
|
|
||||||
<span className="pointer-events-none block aspect-square h-full in-[[data-slot=menu-checkbox-item][data-checked]]:origin-[var(--thumb-size)_50%] origin-left in-[[data-slot=menu-checkbox-item][data-checked]]:translate-x-[calc(var(--thumb-size)-4px)] in-[[data-slot=menu-checkbox-item]:active]:not-data-disabled:scale-x-110 in-[[data-slot=menu-checkbox-item]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.10)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s]" />
|
|
||||||
</MenuPrimitive.CheckboxItemIndicator>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<MenuPrimitive.CheckboxItemIndicator className="col-start-1">
|
|
||||||
<svg
|
|
||||||
fill="none"
|
|
||||||
height="24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth="2"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
width="24"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
|
||||||
</svg>
|
|
||||||
</MenuPrimitive.CheckboxItemIndicator>
|
|
||||||
<span className="col-start-2">{children}</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</MenuPrimitive.CheckboxItem>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuRadioGroup(props: MenuPrimitive.RadioGroup.Props) {
|
|
||||||
return <MenuPrimitive.RadioGroup data-slot="menu-radio-group" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuRadioItem({ className, children, ...props }: MenuPrimitive.RadioItem.Props) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.RadioItem
|
|
||||||
className={cn(
|
|
||||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="menu-radio-item"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<MenuPrimitive.RadioItemIndicator className="col-start-1">
|
|
||||||
<svg
|
|
||||||
fill="none"
|
|
||||||
height="24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth="2"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
width="24"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
|
||||||
</svg>
|
|
||||||
</MenuPrimitive.RadioItemIndicator>
|
|
||||||
<span className="col-start-2">{children}</span>
|
|
||||||
</MenuPrimitive.RadioItem>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuGroupLabel({
|
|
||||||
className,
|
|
||||||
inset,
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.GroupLabel.Props & {
|
|
||||||
inset?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.GroupLabel
|
|
||||||
className={cn(
|
|
||||||
"px-2 py-1.5 font-medium text-muted-foreground text-xs data-inset:ps-9 sm:data-inset:ps-8",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-inset={inset}
|
|
||||||
data-slot="menu-label"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuSeparator({ className, ...props }: MenuPrimitive.Separator.Props) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.Separator
|
|
||||||
className={cn("mx-2 my-1 h-px bg-border", className)}
|
|
||||||
data-slot="menu-separator"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
|
|
||||||
return (
|
|
||||||
<kbd
|
|
||||||
className={cn(
|
|
||||||
"ms-auto font-medium font-sans text-muted-foreground/72 text-xs tracking-widest",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="menu-shortcut"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuSub(props: MenuPrimitive.SubmenuRoot.Props) {
|
|
||||||
return <MenuPrimitive.SubmenuRoot data-slot="menu-sub" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuSubTrigger({
|
|
||||||
className,
|
|
||||||
inset,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.SubmenuTrigger.Props & {
|
|
||||||
inset?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<MenuPrimitive.SubmenuTrigger
|
|
||||||
className={cn(
|
|
||||||
"flex min-h-8 items-center gap-2 rounded-sm px-2 py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-popup-open:bg-accent data-inset:ps-8 data-highlighted:text-accent-foreground data-popup-open:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-inset={inset}
|
|
||||||
data-slot="menu-sub-trigger"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<ChevronRightIcon className="-me-0.5 ms-auto opacity-80" />
|
|
||||||
</MenuPrimitive.SubmenuTrigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function MenuSubPopup({
|
|
||||||
className,
|
|
||||||
sideOffset = 0,
|
|
||||||
alignOffset,
|
|
||||||
align = "start",
|
|
||||||
...props
|
|
||||||
}: MenuPrimitive.Popup.Props & {
|
|
||||||
align?: MenuPrimitive.Positioner.Props["align"];
|
|
||||||
sideOffset?: MenuPrimitive.Positioner.Props["sideOffset"];
|
|
||||||
alignOffset?: MenuPrimitive.Positioner.Props["alignOffset"];
|
|
||||||
}) {
|
|
||||||
const defaultAlignOffset = align !== "center" ? -5 : undefined;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<MenuPopup
|
|
||||||
align={align}
|
|
||||||
alignOffset={alignOffset ?? defaultAlignOffset}
|
|
||||||
className={className}
|
|
||||||
data-slot="menu-sub-content"
|
|
||||||
side="inline-end"
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
MenuCreateHandle,
|
|
||||||
MenuCreateHandle as DropdownMenuCreateHandle,
|
|
||||||
Menu,
|
|
||||||
Menu as DropdownMenu,
|
|
||||||
MenuPortal,
|
|
||||||
MenuPortal as DropdownMenuPortal,
|
|
||||||
MenuTrigger,
|
|
||||||
MenuTrigger as DropdownMenuTrigger,
|
|
||||||
MenuPopup,
|
|
||||||
MenuPopup as DropdownMenuContent,
|
|
||||||
MenuGroup,
|
|
||||||
MenuGroup as DropdownMenuGroup,
|
|
||||||
MenuItem,
|
|
||||||
MenuItem as DropdownMenuItem,
|
|
||||||
MenuCheckboxItem,
|
|
||||||
MenuCheckboxItem as DropdownMenuCheckboxItem,
|
|
||||||
MenuRadioGroup,
|
|
||||||
MenuRadioGroup as DropdownMenuRadioGroup,
|
|
||||||
MenuRadioItem,
|
|
||||||
MenuRadioItem as DropdownMenuRadioItem,
|
|
||||||
MenuGroupLabel,
|
|
||||||
MenuGroupLabel as DropdownMenuLabel,
|
|
||||||
MenuSeparator,
|
|
||||||
MenuSeparator as DropdownMenuSeparator,
|
|
||||||
MenuShortcut,
|
|
||||||
MenuShortcut as DropdownMenuShortcut,
|
|
||||||
MenuSub,
|
|
||||||
MenuSub as DropdownMenuSub,
|
|
||||||
MenuSubTrigger,
|
|
||||||
MenuSubTrigger as DropdownMenuSubTrigger,
|
|
||||||
MenuSubPopup,
|
|
||||||
MenuSubPopup as DropdownMenuSubContent,
|
|
||||||
};
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Popover as PopoverPrimitive } from "@base-ui/react/popover";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const PopoverCreateHandle = PopoverPrimitive.createHandle;
|
|
||||||
|
|
||||||
const Popover = PopoverPrimitive.Root;
|
|
||||||
|
|
||||||
function PopoverTrigger({ className, children, ...props }: PopoverPrimitive.Trigger.Props) {
|
|
||||||
return (
|
|
||||||
<PopoverPrimitive.Trigger className={className} data-slot="popover-trigger" {...props}>
|
|
||||||
{children}
|
|
||||||
</PopoverPrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PopoverPopup({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
side = "bottom",
|
|
||||||
align = "center",
|
|
||||||
sideOffset = 4,
|
|
||||||
alignOffset = 0,
|
|
||||||
tooltipStyle = false,
|
|
||||||
anchor,
|
|
||||||
...props
|
|
||||||
}: PopoverPrimitive.Popup.Props & {
|
|
||||||
side?: PopoverPrimitive.Positioner.Props["side"];
|
|
||||||
align?: PopoverPrimitive.Positioner.Props["align"];
|
|
||||||
sideOffset?: PopoverPrimitive.Positioner.Props["sideOffset"];
|
|
||||||
alignOffset?: PopoverPrimitive.Positioner.Props["alignOffset"];
|
|
||||||
tooltipStyle?: boolean;
|
|
||||||
anchor?: PopoverPrimitive.Positioner.Props["anchor"];
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<PopoverPrimitive.Portal>
|
|
||||||
<PopoverPrimitive.Positioner
|
|
||||||
align={align}
|
|
||||||
alignOffset={alignOffset}
|
|
||||||
anchor={anchor}
|
|
||||||
className="z-50 h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-[top,left,right,bottom,transform] data-instant:transition-none"
|
|
||||||
data-slot="popover-positioner"
|
|
||||||
side={side}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
>
|
|
||||||
<PopoverPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"relative flex h-(--popup-height,auto) w-(--popup-width,auto) origin-(--transform-origin) rounded-lg border bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 outline-none transition-[width,height,scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] has-data-[slot=calendar]:rounded-xl has-data-[slot=calendar]:before:rounded-[calc(var(--radius-xl)-1px)] data-starting-style:scale-98 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
tooltipStyle &&
|
|
||||||
"w-fit text-balance rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="popover-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<PopoverPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"relative size-full max-h-(--available-height) overflow-clip px-(--viewport-inline-padding) py-4 [--viewport-inline-padding:--spacing(4)] has-data-[slot=calendar]:p-2 data-instant:transition-none **:data-current:data-ending-style:opacity-0 **:data-current:data-starting-style:opacity-0 **:data-previous:data-ending-style:opacity-0 **:data-previous:data-starting-style:opacity-0 **:data-current:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-previous:w-[calc(var(--popup-width)-2*var(--viewport-inline-padding)-2px)] **:data-current:opacity-100 **:data-previous:opacity-100 **:data-current:transition-opacity **:data-previous:transition-opacity",
|
|
||||||
tooltipStyle
|
|
||||||
? "py-1 [--viewport-inline-padding:--spacing(2)]"
|
|
||||||
: "not-data-transitioning:overflow-y-auto",
|
|
||||||
)}
|
|
||||||
data-slot="popover-viewport"
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</PopoverPrimitive.Viewport>
|
|
||||||
</PopoverPrimitive.Popup>
|
|
||||||
</PopoverPrimitive.Positioner>
|
|
||||||
</PopoverPrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PopoverClose({ ...props }: PopoverPrimitive.Close.Props) {
|
|
||||||
return <PopoverPrimitive.Close data-slot="popover-close" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function PopoverTitle({ className, ...props }: PopoverPrimitive.Title.Props) {
|
|
||||||
return (
|
|
||||||
<PopoverPrimitive.Title
|
|
||||||
className={cn("font-semibold text-lg leading-none", className)}
|
|
||||||
data-slot="popover-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function PopoverDescription({ className, ...props }: PopoverPrimitive.Description.Props) {
|
|
||||||
return (
|
|
||||||
<PopoverPrimitive.Description
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
data-slot="popover-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
PopoverCreateHandle,
|
|
||||||
Popover,
|
|
||||||
PopoverTrigger,
|
|
||||||
PopoverPopup,
|
|
||||||
PopoverPopup as PopoverContent,
|
|
||||||
PopoverTitle,
|
|
||||||
PopoverDescription,
|
|
||||||
PopoverClose,
|
|
||||||
};
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
|
|
||||||
import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {
|
|
||||||
return (
|
|
||||||
<RadioGroupPrimitive
|
|
||||||
className={cn("flex flex-col gap-3", className)}
|
|
||||||
data-slot="radio-group"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Radio({ className, ...props }: RadioPrimitive.Root.Props) {
|
|
||||||
return (
|
|
||||||
<RadioPrimitive.Root
|
|
||||||
className={cn(
|
|
||||||
"relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-full border border-input bg-background not-dark:bg-clip-padding shadow-xs/5 outline-none transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-full not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="radio"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<RadioPrimitive.Indicator
|
|
||||||
className="-inset-px absolute flex size-4.5 items-center justify-center rounded-full before:size-2 before:rounded-full before:bg-primary-foreground data-unchecked:hidden data-checked:bg-primary sm:size-4 sm:before:size-1.5"
|
|
||||||
data-slot="radio-indicator"
|
|
||||||
/>
|
|
||||||
</RadioPrimitive.Root>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { RadioGroup, Radio, Radio as RadioGroupItem };
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function ScrollArea({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
scrollFade = false,
|
|
||||||
scrollbarGutter = false,
|
|
||||||
...props
|
|
||||||
}: ScrollAreaPrimitive.Root.Props & {
|
|
||||||
scrollFade?: boolean;
|
|
||||||
scrollbarGutter?: boolean;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<ScrollAreaPrimitive.Root className={cn("size-full min-h-0", className)} {...props}>
|
|
||||||
<ScrollAreaPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"h-full overscroll-contain rounded-[inherit] outline-none transition-shadows focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-has-overflow-x:overscroll-x-contain",
|
|
||||||
scrollFade &&
|
|
||||||
"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",
|
|
||||||
scrollbarGutter && "data-has-overflow-y:pe-2.5 data-has-overflow-x:pb-2.5",
|
|
||||||
)}
|
|
||||||
data-slot="scroll-area-viewport"
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</ScrollAreaPrimitive.Viewport>
|
|
||||||
<ScrollBar orientation="vertical" />
|
|
||||||
<ScrollBar orientation="horizontal" />
|
|
||||||
<ScrollAreaPrimitive.Corner data-slot="scroll-area-corner" />
|
|
||||||
</ScrollAreaPrimitive.Root>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ScrollBar({
|
|
||||||
className,
|
|
||||||
orientation = "vertical",
|
|
||||||
...props
|
|
||||||
}: ScrollAreaPrimitive.Scrollbar.Props) {
|
|
||||||
return (
|
|
||||||
<ScrollAreaPrimitive.Scrollbar
|
|
||||||
className={cn(
|
|
||||||
"m-1 flex opacity-0 transition-opacity delay-300 data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:w-1.5 data-[orientation=horizontal]:flex-col data-hovering:opacity-100 data-scrolling:opacity-100 data-hovering:delay-0 data-scrolling:delay-0 data-hovering:duration-100 data-scrolling:duration-100",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="scroll-area-scrollbar"
|
|
||||||
orientation={orientation}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ScrollAreaPrimitive.Thumb
|
|
||||||
className="relative flex-1 rounded-full bg-foreground/20"
|
|
||||||
data-slot="scroll-area-thumb"
|
|
||||||
/>
|
|
||||||
</ScrollAreaPrimitive.Scrollbar>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { ScrollArea, ScrollBar };
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import { Select as SelectPrimitive } from "@base-ui/react/select";
|
|
||||||
import { useRender } from "@base-ui/react/use-render";
|
|
||||||
import { cva, type VariantProps } from "class-variance-authority";
|
|
||||||
import { ChevronDownIcon, ChevronsUpDownIcon, ChevronUpIcon } from "lucide-react";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
const Select = SelectPrimitive.Root;
|
|
||||||
|
|
||||||
const selectTriggerVariants = cva(
|
|
||||||
"relative inline-flex select-none items-center justify-between gap-2 border rounded-lg text-left text-base outline-none transition-[color,box-shadow,background-color] data-disabled:pointer-events-none data-disabled:opacity-64 sm:text-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4",
|
|
||||||
{
|
|
||||||
defaultVariants: {
|
|
||||||
size: "default",
|
|
||||||
variant: "default",
|
|
||||||
},
|
|
||||||
variants: {
|
|
||||||
variant: {
|
|
||||||
default:
|
|
||||||
"w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
|
|
||||||
ghost:
|
|
||||||
"border-transparent text-muted-foreground/70 focus-visible:ring-2 focus-visible:ring-ring data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent [:hover,[data-pressed]]:text-foreground/80",
|
|
||||||
},
|
|
||||||
size: {
|
|
||||||
default: "min-h-9 px-[calc(--spacing(3)-1px)] sm:min-h-8",
|
|
||||||
lg: "min-h-10 px-[calc(--spacing(3)-1px)] sm:min-h-9",
|
|
||||||
sm: "min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:min-h-7",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const selectTriggerIconClassName = "-me-1 size-4.5 opacity-80 sm:size-4";
|
|
||||||
|
|
||||||
interface SelectButtonProps extends useRender.ComponentProps<"button"> {
|
|
||||||
size?: VariantProps<typeof selectTriggerVariants>["size"];
|
|
||||||
variant?: VariantProps<typeof selectTriggerVariants>["variant"];
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectButton({ className, size, variant, render, children, ...props }: SelectButtonProps) {
|
|
||||||
const typeValue: React.ButtonHTMLAttributes<HTMLButtonElement>["type"] = render
|
|
||||||
? undefined
|
|
||||||
: "button";
|
|
||||||
|
|
||||||
const defaultProps = {
|
|
||||||
children: (
|
|
||||||
<>
|
|
||||||
<span className="flex-1 truncate in-data-placeholder:text-muted-foreground/72">
|
|
||||||
{children}
|
|
||||||
</span>
|
|
||||||
{variant === "ghost" ? (
|
|
||||||
<ChevronDownIcon className="size-3 opacity-50" />
|
|
||||||
) : (
|
|
||||||
<ChevronsUpDownIcon className={selectTriggerIconClassName} />
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
className: cn(selectTriggerVariants({ size, variant }), "min-w-none", className),
|
|
||||||
"data-slot": "select-button",
|
|
||||||
type: typeValue,
|
|
||||||
};
|
|
||||||
|
|
||||||
return useRender({
|
|
||||||
defaultTagName: "button",
|
|
||||||
props: mergeProps<"button">(defaultProps, props),
|
|
||||||
render,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectTrigger({
|
|
||||||
className,
|
|
||||||
size = "default",
|
|
||||||
variant = "default",
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: SelectPrimitive.Trigger.Props & VariantProps<typeof selectTriggerVariants>) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Trigger
|
|
||||||
className={cn(selectTriggerVariants({ size, variant }), className)}
|
|
||||||
data-slot="select-trigger"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<SelectPrimitive.Icon data-slot="select-icon">
|
|
||||||
<ChevronDownIcon className="size-3 opacity-50" />
|
|
||||||
</SelectPrimitive.Icon>
|
|
||||||
</SelectPrimitive.Trigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Value
|
|
||||||
className={cn("flex-1 truncate data-placeholder:text-muted-foreground", className)}
|
|
||||||
data-slot="select-value"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectPopup({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
side = "bottom",
|
|
||||||
sideOffset = 4,
|
|
||||||
align = "start",
|
|
||||||
alignOffset = 0,
|
|
||||||
alignItemWithTrigger = true,
|
|
||||||
anchor,
|
|
||||||
...props
|
|
||||||
}: SelectPrimitive.Popup.Props & {
|
|
||||||
side?: SelectPrimitive.Positioner.Props["side"];
|
|
||||||
sideOffset?: SelectPrimitive.Positioner.Props["sideOffset"];
|
|
||||||
align?: SelectPrimitive.Positioner.Props["align"];
|
|
||||||
alignOffset?: SelectPrimitive.Positioner.Props["alignOffset"];
|
|
||||||
alignItemWithTrigger?: SelectPrimitive.Positioner.Props["alignItemWithTrigger"];
|
|
||||||
anchor?: SelectPrimitive.Positioner.Props["anchor"];
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Portal>
|
|
||||||
<SelectPrimitive.Positioner
|
|
||||||
align={align}
|
|
||||||
alignItemWithTrigger={alignItemWithTrigger}
|
|
||||||
alignOffset={alignOffset}
|
|
||||||
anchor={anchor}
|
|
||||||
className="z-50 select-none"
|
|
||||||
data-slot="select-positioner"
|
|
||||||
side={side}
|
|
||||||
sideOffset={sideOffset}
|
|
||||||
>
|
|
||||||
<SelectPrimitive.Popup
|
|
||||||
className="origin-(--transform-origin) text-foreground"
|
|
||||||
data-slot="select-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SelectPrimitive.ScrollUpArrow
|
|
||||||
className="top-0 z-50 flex h-6 w-full cursor-default items-center justify-center before:pointer-events-none before:absolute before:inset-x-px before:top-px before:h-[200%] before:rounded-t-[calc(var(--radius-lg)-1px)] before:bg-linear-to-b before:from-50% before:from-popover"
|
|
||||||
data-slot="select-scroll-up-arrow"
|
|
||||||
>
|
|
||||||
<ChevronUpIcon className="relative size-4.5 sm:size-4" />
|
|
||||||
</SelectPrimitive.ScrollUpArrow>
|
|
||||||
<div className="relative h-full min-w-(--anchor-width) rounded-lg border bg-popover not-dark:bg-clip-padding shadow-lg/5 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%)]">
|
|
||||||
<SelectPrimitive.List
|
|
||||||
className={cn("max-h-(--available-height) overflow-y-auto p-1", className)}
|
|
||||||
data-slot="select-list"
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</SelectPrimitive.List>
|
|
||||||
</div>
|
|
||||||
<SelectPrimitive.ScrollDownArrow
|
|
||||||
className="bottom-0 z-50 flex h-6 w-full cursor-default items-center justify-center before:pointer-events-none before:absolute before:inset-x-px before:bottom-px before:h-[200%] before:rounded-b-[calc(var(--radius-lg)-1px)] before:bg-linear-to-t before:from-50% before:from-popover"
|
|
||||||
data-slot="select-scroll-down-arrow"
|
|
||||||
>
|
|
||||||
<ChevronDownIcon className="relative size-4.5 sm:size-4" />
|
|
||||||
</SelectPrimitive.ScrollDownArrow>
|
|
||||||
</SelectPrimitive.Popup>
|
|
||||||
</SelectPrimitive.Positioner>
|
|
||||||
</SelectPrimitive.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Item
|
|
||||||
className={cn(
|
|
||||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="select-item"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SelectPrimitive.ItemIndicator className="col-start-1">
|
|
||||||
<svg
|
|
||||||
fill="none"
|
|
||||||
height="24"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth="2"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
width="24"
|
|
||||||
xmlns="http://www.w3.org/1500/svg"
|
|
||||||
>
|
|
||||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
|
||||||
</svg>
|
|
||||||
</SelectPrimitive.ItemIndicator>
|
|
||||||
<SelectPrimitive.ItemText className="col-start-2 min-w-0">
|
|
||||||
{children}
|
|
||||||
</SelectPrimitive.ItemText>
|
|
||||||
</SelectPrimitive.Item>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectSeparator({ className, ...props }: SelectPrimitive.Separator.Props) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.Separator
|
|
||||||
className={cn("mx-2 my-1 h-px bg-border", className)}
|
|
||||||
data-slot="select-separator"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectGroup(props: SelectPrimitive.Group.Props) {
|
|
||||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SelectGroupLabel(props: SelectPrimitive.GroupLabel.Props) {
|
|
||||||
return (
|
|
||||||
<SelectPrimitive.GroupLabel
|
|
||||||
className="px-2 py-1.5 font-medium text-muted-foreground text-xs"
|
|
||||||
data-slot="select-group-label"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Select,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectButton,
|
|
||||||
selectTriggerVariants,
|
|
||||||
SelectValue,
|
|
||||||
SelectPopup,
|
|
||||||
SelectPopup as SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectSeparator,
|
|
||||||
SelectGroup,
|
|
||||||
SelectGroupLabel,
|
|
||||||
};
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Separator({ className, orientation = "horizontal", ...props }: SeparatorPrimitive.Props) {
|
|
||||||
return (
|
|
||||||
<SeparatorPrimitive
|
|
||||||
className={cn(
|
|
||||||
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:not-[[class^='h-']]:not-[[class*='_h-']]:self-stretch",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="separator"
|
|
||||||
orientation={orientation}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Separator };
|
|
||||||
@@ -1,199 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Dialog as SheetPrimitive } from "@base-ui/react/dialog";
|
|
||||||
import { XIcon } from "lucide-react";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { Button } from "~/components/ui/button";
|
|
||||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
|
||||||
|
|
||||||
const Sheet = SheetPrimitive.Root;
|
|
||||||
|
|
||||||
const SheetPortal = SheetPrimitive.Portal;
|
|
||||||
|
|
||||||
function SheetTrigger(props: SheetPrimitive.Trigger.Props) {
|
|
||||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetClose(props: SheetPrimitive.Close.Props) {
|
|
||||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetBackdrop({ className, ...props }: SheetPrimitive.Backdrop.Props) {
|
|
||||||
return (
|
|
||||||
<SheetPrimitive.Backdrop
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="sheet-backdrop"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetViewport({
|
|
||||||
className,
|
|
||||||
side,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: SheetPrimitive.Viewport.Props & {
|
|
||||||
side?: "right" | "left" | "top" | "bottom";
|
|
||||||
variant?: "default" | "inset";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<SheetPrimitive.Viewport
|
|
||||||
className={cn(
|
|
||||||
"fixed inset-0 z-50 grid",
|
|
||||||
side === "bottom" && "grid grid-rows-[1fr_auto] pt-12",
|
|
||||||
side === "top" && "grid grid-rows-[auto_1fr] pb-12",
|
|
||||||
side === "left" && "flex justify-start",
|
|
||||||
side === "right" && "flex justify-end",
|
|
||||||
variant === "inset" && "sm:p-4",
|
|
||||||
)}
|
|
||||||
data-slot="sheet-viewport"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetPopup({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
showCloseButton = true,
|
|
||||||
keepMounted = false,
|
|
||||||
side = "right",
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: SheetPrimitive.Popup.Props & {
|
|
||||||
showCloseButton?: boolean;
|
|
||||||
keepMounted?: boolean;
|
|
||||||
side?: "right" | "left" | "top" | "bottom";
|
|
||||||
variant?: "default" | "inset";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<SheetPortal keepMounted={keepMounted}>
|
|
||||||
<SheetBackdrop />
|
|
||||||
<SheetViewport side={side} variant={variant}>
|
|
||||||
<SheetPrimitive.Popup
|
|
||||||
className={cn(
|
|
||||||
"relative flex max-h-full min-h-0 w-full min-w-0 flex-col bg-popover not-dark:bg-clip-padding text-popover-foreground shadow-lg/5 transition-[opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:opacity-0 data-starting-style:opacity-0 max-sm:before:hidden dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
side === "bottom" &&
|
|
||||||
"row-start-2 border-t data-ending-style:translate-y-8 data-starting-style:translate-y-8",
|
|
||||||
side === "top" &&
|
|
||||||
"data-ending-style:-translate-y-8 data-starting-style:-translate-y-8 border-b",
|
|
||||||
side === "left" &&
|
|
||||||
"data-ending-style:-translate-x-8 data-starting-style:-translate-x-8 w-[calc(100%-(--spacing(12)))] max-w-md border-e",
|
|
||||||
side === "right" &&
|
|
||||||
"col-start-2 w-[calc(100%-(--spacing(12)))] max-w-md border-s data-ending-style:translate-x-8 data-starting-style:translate-x-8",
|
|
||||||
variant === "inset" &&
|
|
||||||
"before:hidden sm:rounded-2xl sm:border sm:before:rounded-[calc(var(--radius-2xl)-1px)] sm:**:data-[slot=sheet-footer]:rounded-b-[calc(var(--radius-2xl)-1px)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="sheet-popup"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
{showCloseButton && (
|
|
||||||
<SheetPrimitive.Close
|
|
||||||
aria-label="Close"
|
|
||||||
className="absolute end-2 top-2"
|
|
||||||
render={<Button size="icon" variant="ghost" />}
|
|
||||||
>
|
|
||||||
<XIcon />
|
|
||||||
</SheetPrimitive.Close>
|
|
||||||
)}
|
|
||||||
</SheetPrimitive.Popup>
|
|
||||||
</SheetViewport>
|
|
||||||
</SheetPortal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col gap-2 p-6 in-[[data-slot=sheet-popup]:has([data-slot=sheet-panel])]:pb-3 max-sm:pb-4",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="sheet-header"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetFooter({
|
|
||||||
className,
|
|
||||||
variant = "default",
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & {
|
|
||||||
variant?: "default" | "bare";
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"flex flex-col-reverse gap-2 px-6 sm:flex-row sm:justify-end",
|
|
||||||
variant === "default" && "border-t bg-muted/72 py-4",
|
|
||||||
variant === "bare" &&
|
|
||||||
"in-[[data-slot=sheet-popup]:has([data-slot=sheet-panel])]:pt-3 pt-4 pb-6",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="sheet-footer"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
|
|
||||||
return (
|
|
||||||
<SheetPrimitive.Title
|
|
||||||
className={cn("font-heading font-semibold text-xl leading-none", className)}
|
|
||||||
data-slot="sheet-title"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetDescription({ className, ...props }: SheetPrimitive.Description.Props) {
|
|
||||||
return (
|
|
||||||
<SheetPrimitive.Description
|
|
||||||
className={cn("text-muted-foreground text-sm", className)}
|
|
||||||
data-slot="sheet-description"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function SheetPanel({
|
|
||||||
className,
|
|
||||||
scrollFade = true,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<"div"> & { scrollFade?: boolean }) {
|
|
||||||
return (
|
|
||||||
<ScrollArea scrollFade={scrollFade}>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"p-6 in-[[data-slot=sheet-popup]:has([data-slot=sheet-header])]:pt-1 in-[[data-slot=sheet-popup]:has([data-slot=sheet-footer]:not(.border-t))]:pb-1",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="sheet-panel"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</ScrollArea>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
Sheet,
|
|
||||||
SheetTrigger,
|
|
||||||
SheetPortal,
|
|
||||||
SheetClose,
|
|
||||||
SheetBackdrop,
|
|
||||||
SheetBackdrop as SheetOverlay,
|
|
||||||
SheetPopup,
|
|
||||||
SheetPopup as SheetContent,
|
|
||||||
SheetHeader,
|
|
||||||
SheetFooter,
|
|
||||||
SheetTitle,
|
|
||||||
SheetDescription,
|
|
||||||
SheetPanel,
|
|
||||||
};
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"animate-skeleton rounded-sm [--skeleton-highlight:--alpha(var(--color-white)/64%)] [background:linear-gradient(120deg,transparent_40%,var(--skeleton-highlight),transparent_60%)_var(--color-muted)_0_0/200%_100%_fixed] dark:[--skeleton-highlight:--alpha(var(--color-white)/4%)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="skeleton"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Skeleton };
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
import { Loader2Icon } from "lucide-react";
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Spinner({ className, ...props }: React.ComponentProps<typeof Loader2Icon>) {
|
|
||||||
return (
|
|
||||||
<Loader2Icon
|
|
||||||
aria-label="Loading"
|
|
||||||
className={cn("animate-spin", className)}
|
|
||||||
role="status"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Spinner };
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Switch as SwitchPrimitive } from "@base-ui/react/switch";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
function Switch({ className, ...props }: SwitchPrimitive.Root.Props) {
|
|
||||||
return (
|
|
||||||
<SwitchPrimitive.Root
|
|
||||||
className={cn(
|
|
||||||
"inline-flex h-[calc(var(--thumb-size)+2px)] w-[calc(var(--thumb-size)*2-2px)] shrink-0 items-center rounded-full p-px outline-none transition-[background-color,box-shadow] duration-200 [--thumb-size:--spacing(5)] focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background data-checked:bg-primary data-unchecked:bg-input data-disabled:opacity-64 sm:[--thumb-size:--spacing(4)]",
|
|
||||||
className,
|
|
||||||
)}
|
|
||||||
data-slot="switch"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<SwitchPrimitive.Thumb
|
|
||||||
className={cn(
|
|
||||||
"pointer-events-none block aspect-square h-full origin-left in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:not-data-disabled:scale-x-110 in-[[role=switch]:active,[data-slot=label]:active,[data-slot=field-label]:active]:rounded-[var(--thumb-size)/calc(var(--thumb-size)*1.1)] rounded-(--thumb-size) bg-background shadow-sm/5 will-change-transform [transition:translate_.15s,border-radius_.15s,scale_.1s_.1s,transform-origin_.15s] data-checked:origin-[var(--thumb-size)_50%] data-checked:translate-x-[calc(var(--thumb-size)-4px)]",
|
|
||||||
)}
|
|
||||||
data-slot="switch-thumb"
|
|
||||||
/>
|
|
||||||
</SwitchPrimitive.Root>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Switch };
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Field as FieldPrimitive } from "@base-ui/react/field";
|
|
||||||
import { mergeProps } from "@base-ui/react/merge-props";
|
|
||||||
import type * as React from "react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
|
|
||||||
type TextareaProps = React.ComponentProps<"textarea"> & {
|
|
||||||
size?: "sm" | "default" | "lg" | number;
|
|
||||||
unstyled?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
function Textarea({ className, size = "default", unstyled = false, ...props }: TextareaProps) {
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={
|
|
||||||
cn(
|
|
||||||
!unstyled &&
|
|
||||||
"relative inline-flex w-full rounded-lg border border-input bg-background not-dark:bg-clip-padding text-base text-foreground shadow-xs/5 ring-ring/24 transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] has-focus-visible:has-aria-invalid:border-destructive/64 has-focus-visible:has-aria-invalid:ring-destructive/16 has-aria-invalid:border-destructive/36 has-focus-visible:border-ring has-disabled:opacity-64 has-[:disabled,:focus-visible,[aria-invalid]]:shadow-none has-focus-visible:ring-[3px] not-has-disabled:has-not-focus-visible:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] sm:text-sm dark:bg-input/32 dark:has-aria-invalid:ring-destructive/24 dark:not-has-disabled:has-not-focus-visible:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
className,
|
|
||||||
) || undefined
|
|
||||||
}
|
|
||||||
data-size={size}
|
|
||||||
data-slot="textarea-control"
|
|
||||||
>
|
|
||||||
<FieldPrimitive.Control
|
|
||||||
render={(defaultProps) => (
|
|
||||||
<textarea
|
|
||||||
className={cn(
|
|
||||||
"field-sizing-content min-h-17.5 w-full rounded-[inherit] px-[calc(--spacing(3)-1px)] py-[calc(--spacing(1.5)-1px)] outline-none max-sm:min-h-20.5",
|
|
||||||
size === "sm" &&
|
|
||||||
"min-h-16.5 px-[calc(--spacing(2.5)-1px)] py-[calc(--spacing(1)-1px)] max-sm:min-h-19.5",
|
|
||||||
size === "lg" && "min-h-18.5 py-[calc(--spacing(2)-1px)] max-sm:min-h-21.5",
|
|
||||||
)}
|
|
||||||
data-slot="textarea"
|
|
||||||
{...mergeProps(defaultProps, props)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export { Textarea, type TextareaProps };
|
|
||||||
@@ -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,380 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Toast } from "@base-ui/react/toast";
|
|
||||||
import { useEffect } from "react";
|
|
||||||
import {
|
|
||||||
CircleAlertIcon,
|
|
||||||
CircleCheckIcon,
|
|
||||||
InfoIcon,
|
|
||||||
LoaderCircleIcon,
|
|
||||||
TriangleAlertIcon,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
import { cn } from "~/lib/utils";
|
|
||||||
import { buttonVariants } from "~/components/ui/button";
|
|
||||||
import { useStore } from "~/store";
|
|
||||||
import { shouldHideCollapsedToastContent } from "./toast.logic";
|
|
||||||
|
|
||||||
type ThreadToastData = {
|
|
||||||
threadId?: string | null;
|
|
||||||
tooltipStyle?: boolean;
|
|
||||||
dismissAfterVisibleMs?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const toastManager = Toast.createToastManager<ThreadToastData>();
|
|
||||||
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
|
|
||||||
type ToastId = ReturnType<typeof toastManager.add>;
|
|
||||||
const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
|
|
||||||
|
|
||||||
const TOAST_ICONS = {
|
|
||||||
error: CircleAlertIcon,
|
|
||||||
info: InfoIcon,
|
|
||||||
loading: LoaderCircleIcon,
|
|
||||||
success: CircleCheckIcon,
|
|
||||||
warning: TriangleAlertIcon,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
type ToastPosition =
|
|
||||||
| "top-left"
|
|
||||||
| "top-center"
|
|
||||||
| "top-right"
|
|
||||||
| "bottom-left"
|
|
||||||
| "bottom-center"
|
|
||||||
| "bottom-right";
|
|
||||||
|
|
||||||
interface ToastProviderProps extends Toast.Provider.Props {
|
|
||||||
position?: ToastPosition;
|
|
||||||
}
|
|
||||||
|
|
||||||
function shouldRenderForActiveThread(
|
|
||||||
data: ThreadToastData | undefined,
|
|
||||||
activeThreadId: string | null,
|
|
||||||
): boolean {
|
|
||||||
const toastThreadId = data?.threadId;
|
|
||||||
if (!toastThreadId) return true;
|
|
||||||
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) {
|
|
||||||
return (
|
|
||||||
<Toast.Provider toastManager={toastManager} {...props}>
|
|
||||||
{children}
|
|
||||||
<Toasts position={position} />
|
|
||||||
</Toast.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
|
||||||
const { state } = useStore();
|
|
||||||
const { toasts } = Toast.useToastManager<ThreadToastData>();
|
|
||||||
const activeThreadId = state.activeThreadId;
|
|
||||||
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 (
|
|
||||||
<Toast.Portal data-slot="toast-portal">
|
|
||||||
<Toast.Viewport
|
|
||||||
className={cn(
|
|
||||||
"fixed z-50 mx-auto flex w-[calc(100%-var(--toast-inset)*2)] max-w-90 [--toast-header-offset:52px] [--toast-inset:--spacing(4)] sm:[--toast-inset:--spacing(8)]",
|
|
||||||
// Vertical positioning
|
|
||||||
"data-[position*=top]:top-[calc(var(--toast-inset)+var(--toast-header-offset))]",
|
|
||||||
"data-[position*=bottom]:bottom-(--toast-inset)",
|
|
||||||
// Horizontal positioning
|
|
||||||
"data-[position*=left]:left-(--toast-inset)",
|
|
||||||
"data-[position*=right]:right-(--toast-inset)",
|
|
||||||
"data-[position*=center]:-translate-x-1/2 data-[position*=center]:left-1/2",
|
|
||||||
)}
|
|
||||||
data-position={position}
|
|
||||||
data-slot="toast-viewport"
|
|
||||||
>
|
|
||||||
{visibleToasts.map((toast, visibleIndex) => {
|
|
||||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
|
||||||
const hideCollapsedContent = shouldHideCollapsedToastContent(
|
|
||||||
visibleIndex,
|
|
||||||
visibleToasts.length,
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<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(
|
|
||||||
"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",
|
|
||||||
hideCollapsedContent &&
|
|
||||||
"not-data-expanded:pointer-events-none not-data-expanded:opacity-0",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{Icon && (
|
|
||||||
<div
|
|
||||||
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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-0.5">
|
|
||||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
|
||||||
<Toast.Description
|
|
||||||
className="text-muted-foreground"
|
|
||||||
data-slot="toast-description"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{toast.actionProps && (
|
|
||||||
<Toast.Action className={buttonVariants({ size: "xs" })} data-slot="toast-action">
|
|
||||||
{toast.actionProps.children}
|
|
||||||
</Toast.Action>
|
|
||||||
)}
|
|
||||||
</Toast.Content>
|
|
||||||
</Toast.Root>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Toast.Viewport>
|
|
||||||
</Toast.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
|
|
||||||
return (
|
|
||||||
<Toast.Provider toastManager={anchoredToastManager} {...props}>
|
|
||||||
{children}
|
|
||||||
<AnchoredToasts />
|
|
||||||
</Toast.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function AnchoredToasts() {
|
|
||||||
const { state } = useStore();
|
|
||||||
const { toasts } = Toast.useToastManager<ThreadToastData>();
|
|
||||||
const activeThreadId = state.activeThreadId;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Toast.Portal data-slot="toast-portal-anchored">
|
|
||||||
<Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
|
|
||||||
{toasts
|
|
||||||
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
|
|
||||||
.map((toast) => {
|
|
||||||
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
|
|
||||||
const tooltipStyle = toast.data?.tooltipStyle ?? false;
|
|
||||||
const positionerProps = toast.positionerProps;
|
|
||||||
|
|
||||||
if (!positionerProps?.anchor) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Toast.Positioner
|
|
||||||
className="z-50 max-w-[min(--spacing(64),var(--available-width))]"
|
|
||||||
data-slot="toast-positioner"
|
|
||||||
key={toast.id}
|
|
||||||
sideOffset={positionerProps.sideOffset ?? 4}
|
|
||||||
toast={toast}
|
|
||||||
>
|
|
||||||
<Toast.Root
|
|
||||||
className={cn(
|
|
||||||
"relative text-balance border bg-popover not-dark:bg-clip-padding text-popover-foreground text-xs transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
|
||||||
tooltipStyle
|
|
||||||
? "rounded-md shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]"
|
|
||||||
: "rounded-lg shadow-lg/5 before:rounded-[calc(var(--radius-lg)-1px)]",
|
|
||||||
)}
|
|
||||||
data-slot="toast-popup"
|
|
||||||
toast={toast}
|
|
||||||
>
|
|
||||||
{tooltipStyle ? (
|
|
||||||
<Toast.Content className="pointer-events-auto px-2 py-1">
|
|
||||||
<Toast.Title data-slot="toast-title" />
|
|
||||||
</Toast.Content>
|
|
||||||
) : (
|
|
||||||
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm">
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{Icon && (
|
|
||||||
<div
|
|
||||||
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>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-0.5">
|
|
||||||
<Toast.Title className="font-medium" data-slot="toast-title" />
|
|
||||||
<Toast.Description
|
|
||||||
className="text-muted-foreground"
|
|
||||||
data-slot="toast-description"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{toast.actionProps && (
|
|
||||||
<Toast.Action
|
|
||||||
className={buttonVariants({ size: "xs" })}
|
|
||||||
data-slot="toast-action"
|
|
||||||
>
|
|
||||||
{toast.actionProps.children}
|
|
||||||
</Toast.Action>
|
|
||||||
)}
|
|
||||||
</Toast.Content>
|
|
||||||
)}
|
|
||||||
</Toast.Root>
|
|
||||||
</Toast.Positioner>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</Toast.Viewport>
|
|
||||||
</Toast.Portal>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export {
|
|
||||||
ToastProvider,
|
|
||||||
type ToastPosition,
|
|
||||||
toastManager,
|
|
||||||
AnchoredToastProvider,
|
|
||||||
anchoredToastManager,
|
|
||||||
};
|
|
||||||
@@ -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 };
|
|
||||||
}
|
|
||||||
+41
-2
@@ -11,6 +11,19 @@
|
|||||||
--color-info-foreground: var(--info-foreground);
|
--color-info-foreground: var(--info-foreground);
|
||||||
--color-info: var(--info);
|
--color-info: var(--info);
|
||||||
--color-destructive-foreground: var(--destructive-foreground);
|
--color-destructive-foreground: var(--destructive-foreground);
|
||||||
|
--color-sidebar-ring: var(--sidebar-ring);
|
||||||
|
--color-sidebar-border: var(--sidebar-border);
|
||||||
|
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||||
|
--color-sidebar-accent: var(--sidebar-accent);
|
||||||
|
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||||
|
--color-sidebar-primary: var(--sidebar-primary);
|
||||||
|
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||||
|
--color-sidebar: var(--sidebar);
|
||||||
|
--color-chart-5: var(--chart-5);
|
||||||
|
--color-chart-4: var(--chart-4);
|
||||||
|
--color-chart-3: var(--chart-3);
|
||||||
|
--color-chart-2: var(--chart-2);
|
||||||
|
--color-chart-1: var(--chart-1);
|
||||||
--color-ring: var(--ring);
|
--color-ring: var(--ring);
|
||||||
--color-input: var(--input);
|
--color-input: var(--input);
|
||||||
--color-border: var(--border);
|
--color-border: var(--border);
|
||||||
@@ -48,7 +61,7 @@
|
|||||||
@apply border-border outline-ring/50;
|
@apply border-border outline-ring/50;
|
||||||
}
|
}
|
||||||
body {
|
body {
|
||||||
@apply bg-background text-foreground relative;
|
@apply bg-background text-foreground;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,12 +89,25 @@
|
|||||||
--secondary-foreground: var(--color-neutral-800);
|
--secondary-foreground: var(--color-neutral-800);
|
||||||
--muted: --alpha(var(--color-black) / 4%);
|
--muted: --alpha(var(--color-black) / 4%);
|
||||||
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black));
|
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black));
|
||||||
--accent: --alpha(var(--color-black) / 4%);
|
--accent: --alpha(var(--color-black) / 5%);
|
||||||
--accent-foreground: var(--color-neutral-800);
|
--accent-foreground: var(--color-neutral-800);
|
||||||
--destructive: var(--color-red-500);
|
--destructive: var(--color-red-500);
|
||||||
--border: --alpha(var(--color-black) / 8%);
|
--border: --alpha(var(--color-black) / 8%);
|
||||||
--input: --alpha(var(--color-black) / 10%);
|
--input: --alpha(var(--color-black) / 10%);
|
||||||
--ring: oklch(0.488 0.217 264);
|
--ring: oklch(0.488 0.217 264);
|
||||||
|
--chart-1: oklch(0.646 0.222 41.116);
|
||||||
|
--chart-2: oklch(0.6 0.118 184.704);
|
||||||
|
--chart-3: oklch(0.398 0.07 227.392);
|
||||||
|
--chart-4: oklch(0.828 0.189 84.429);
|
||||||
|
--chart-5: oklch(0.769 0.188 70.08);
|
||||||
|
--sidebar: oklch(0.985 0 0);
|
||||||
|
--sidebar-foreground: oklch(0.141 0.005 285.823);
|
||||||
|
--sidebar-primary: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.967 0.001 286.375);
|
||||||
|
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-border: oklch(0.92 0.004 286.32);
|
||||||
|
--sidebar-ring: oklch(0.705 0.015 286.067);
|
||||||
--destructive-foreground: var(--color-red-700);
|
--destructive-foreground: var(--color-red-700);
|
||||||
--info: var(--color-blue-500);
|
--info: var(--color-blue-500);
|
||||||
--info-foreground: var(--color-blue-700);
|
--info-foreground: var(--color-blue-700);
|
||||||
@@ -110,6 +136,19 @@
|
|||||||
--border: --alpha(var(--color-white) / 6%);
|
--border: --alpha(var(--color-white) / 6%);
|
||||||
--input: --alpha(var(--color-white) / 8%);
|
--input: --alpha(var(--color-white) / 8%);
|
||||||
--ring: oklch(0.588 0.217 264);
|
--ring: oklch(0.588 0.217 264);
|
||||||
|
--chart-1: oklch(0.488 0.243 264.376);
|
||||||
|
--chart-2: oklch(0.696 0.17 162.48);
|
||||||
|
--chart-3: oklch(0.769 0.188 70.08);
|
||||||
|
--chart-4: oklch(0.627 0.265 303.9);
|
||||||
|
--chart-5: oklch(0.645 0.246 16.439);
|
||||||
|
--sidebar: oklch(0.21 0.006 285.885);
|
||||||
|
--sidebar-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||||
|
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-accent: oklch(0.274 0.006 286.033);
|
||||||
|
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||||
|
--sidebar-border: oklch(1 0 0 / 10%);
|
||||||
|
--sidebar-ring: oklch(0.552 0.016 285.938);
|
||||||
--destructive-foreground: var(--color-red-400);
|
--destructive-foreground: var(--color-red-400);
|
||||||
--info: var(--color-blue-500);
|
--info: var(--color-blue-500);
|
||||||
--info-foreground: var(--color-blue-400);
|
--info-foreground: var(--color-blue-400);
|
||||||
|
|||||||
@@ -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,186 +0,0 @@
|
|||||||
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
|
|
||||||
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 = {
|
|
||||||
all: ["git"] as const,
|
|
||||||
status: (cwd: string | null) => ["git", "status", cwd] as const,
|
|
||||||
branches: (cwd: string | null) => ["git", "branches", cwd] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function invalidateGitQueries(queryClient: QueryClient) {
|
|
||||||
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitStatusQueryOptions(api: NativeApi | undefined, cwd: string | null) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: gitQueryKeys.status(cwd),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!api || !cwd) {
|
|
||||||
throw new Error("Git status is unavailable.");
|
|
||||||
}
|
|
||||||
return api.git.status({ cwd });
|
|
||||||
},
|
|
||||||
enabled: !!api && !!cwd,
|
|
||||||
staleTime: GIT_STATUS_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: "always",
|
|
||||||
refetchOnReconnect: "always",
|
|
||||||
refetchInterval: GIT_STATUS_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitBranchesQueryOptions(api: NativeApi | undefined, cwd: string | null) {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: gitQueryKeys.branches(cwd),
|
|
||||||
queryFn: async () => {
|
|
||||||
if (!api || !cwd) {
|
|
||||||
throw new Error("Git branches are unavailable.");
|
|
||||||
}
|
|
||||||
return api.git.listBranches({ cwd });
|
|
||||||
},
|
|
||||||
enabled: !!api && !!cwd,
|
|
||||||
staleTime: GIT_BRANCHES_STALE_TIME_MS,
|
|
||||||
refetchOnWindowFocus: true,
|
|
||||||
refetchOnReconnect: true,
|
|
||||||
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitInitMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async () => {
|
|
||||||
if (!input.api || !input.cwd) throw new Error("Git init is unavailable.");
|
|
||||||
return input.api.git.init({ cwd: input.cwd });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitCheckoutMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async (branch: string) => {
|
|
||||||
if (!input.api || !input.cwd) throw new Error("Git checkout is unavailable.");
|
|
||||||
return input.api.git.checkout({ cwd: input.cwd, branch });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async (branch: string) => {
|
|
||||||
if (!input.api || !input.cwd) throw new Error("Git branch creation is unavailable.");
|
|
||||||
await input.api.git.createBranch({ cwd: input.cwd, branch });
|
|
||||||
return input.api.git.checkout({ cwd: input.cwd, branch });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitRunStackedActionMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({
|
|
||||||
action,
|
|
||||||
commitMessage,
|
|
||||||
}: {
|
|
||||||
action: GitStackedAction;
|
|
||||||
commitMessage?: string;
|
|
||||||
}) => {
|
|
||||||
if (!input.api || !input.cwd) {
|
|
||||||
throw new Error("Git action is unavailable.");
|
|
||||||
}
|
|
||||||
return input.api.git.runStackedAction({
|
|
||||||
cwd: input.cwd,
|
|
||||||
action,
|
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitPullMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async () => {
|
|
||||||
if (!input.api || !input.cwd) throw new Error("Git pull is unavailable.");
|
|
||||||
return input.api.git.pull({ cwd: input.cwd });
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitCreateWorktreeMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({
|
|
||||||
cwd,
|
|
||||||
branch,
|
|
||||||
newBranch,
|
|
||||||
}: {
|
|
||||||
cwd: string;
|
|
||||||
branch: string;
|
|
||||||
newBranch: string;
|
|
||||||
}) => {
|
|
||||||
if (!input.api) {
|
|
||||||
throw new Error("Git worktree creation is unavailable.");
|
|
||||||
}
|
|
||||||
return input.api.git.createWorktree({ cwd, branch, newBranch });
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitRemoveWorktreeMutationOptions(input: {
|
|
||||||
api: NativeApi | undefined;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationFn: async ({ cwd, path }: { cwd: string; path: string }) => {
|
|
||||||
if (!input.api) {
|
|
||||||
throw new Error("Git worktree removal is unavailable.");
|
|
||||||
}
|
|
||||||
return input.api.git.removeWorktree({ cwd, path });
|
|
||||||
},
|
|
||||||
onSettled: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -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"));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user