Compare commits

..
Author SHA1 Message Date
Julius Marminge 42b2a881b0 Fix ChatView height scroll 2026-02-11 18:08:34 -08:00
Julius Marmingeandcodex e4c1729ab3 Address PR review comments for terminal integration
Co-authored-by: codex <[email protected]>
2026-02-11 17:57:47 -08:00
Julius Marminge c561a86997 Improve terminal resizing and perf 2026-02-11 17:35:54 -08:00
105 changed files with 1353 additions and 13268 deletions

No files matched your search

-13
View File
@@ -49,9 +49,6 @@ bun run dev
# Desktop development
bun run dev:desktop
# Desktop development on an isolated port set
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
# Production
bun run build
bun run start
@@ -70,16 +67,6 @@ npx t3
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
### Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
- Default ports: server `3773`, web `5173`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
## Runtime modes
T3 Code has a global runtime mode switch in the chat toolbar:
+3 -12
View File
@@ -1,12 +1,10 @@
# TODO
## Small things
## TODO
- [ ] 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
- [ ] Thread archiving
- [x] Selecting folder should instantly create project
- [ ] Selecting folder should instantly create project
- [ ] New projects should go on top
- [ ] Projects should be sorted by latest thread update
- [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)
- [ ] Insta focus input on new thread creation
- [ ] 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)
+1 -4
View File
@@ -15,13 +15,10 @@ await waitOn({
});
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"], {
stdio: "inherit",
env: {
...childEnv,
...process.env,
VITE_DEV_SERVER_URL: devServerUrl,
},
});
-57
View File
@@ -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?",
}),
);
});
});
-26
View File
@@ -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;
}
+2 -45
View File
@@ -5,17 +5,14 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
@@ -83,12 +80,7 @@ function startBackend(): void {
const child = spawn(process.execPath, [BACKEND_ENTRY], {
cwd: ROOT_DIR,
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
env: backendEnv(),
stdio: "inherit",
});
backendProcess = child;
@@ -149,16 +141,6 @@ function registerIpcHandlers(): void {
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.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -177,31 +159,6 @@ function registerIpcHandlers(): void {
});
});
});
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
return false;
}
let parsedUrl: URL;
try {
parsedUrl = new URL(rawUrl);
} catch {
return false;
}
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
return false;
}
try {
await shell.openExternal(parsedUrl.toString());
return true;
} catch {
return false;
}
});
}
function createWindow(): BrowserWindow {
-4
View File
@@ -1,16 +1,12 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
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 }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
});
+1 -1
View File
@@ -10,7 +10,7 @@
"type": "module",
"main": "./dist/index.mjs",
"scripts": {
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
"dev": "VITE_DEV_SERVER_URL=http://localhost:5173 bun run src/index.ts",
"build": "tsdown && node scripts/bundle-client.mjs",
"start": "node dist/index.mjs",
"typecheck": "tsc --noEmit",
+1 -124
View File
@@ -1,48 +1,11 @@
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import {
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
normalizeCodexModelSlug,
} from "./codexAppServerManager";
function createSendTurnHarness() {
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",
)
.mockResolvedValue({
turn: {
id: "turn_1",
},
});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, requireSession, sendRequest, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -112,89 +75,3 @@ describe("isRecoverableThreadResumeError", () => {
).toBe(false);
});
});
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: "sess_1",
input: "Inspect this image",
attachments: [
{
type: "image",
name: "error.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3",
effort: "high",
});
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
});
expect(requireSession).toHaveBeenCalledWith("sess_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Inspect this image",
text_elements: [],
},
{
type: "image",
url: "data:image/png;base64,AAAA",
},
],
model: "gpt-5.3-codex",
effort: "high",
});
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
});
});
it("supports image-only turns", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 256,
dataUrl: "data:image/png;base64,BBBB",
},
],
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "image",
url: "data:image/png;base64,BBBB",
},
],
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
await expect(
manager.sendTurn({
sessionId: "sess_1",
}),
).rejects.toThrow("Turn input must include text or attachments.");
});
});
+8 -26
View File
@@ -257,38 +257,20 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
throw new Error("Session is missing a thread id.");
}
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
type: "text",
text: input.input,
text_elements: [],
});
}
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
turnInput.push({
type: "image",
url: attachment.dataUrl,
});
}
}
if (turnInput.length === 0) {
throw new Error("Turn input must include text or attachments.");
}
const turnStartParams: {
threadId: string;
input: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
input: Array<{ type: "text"; text: string; text_elements: [] }>;
model?: string;
effort?: string;
} = {
threadId: context.session.threadId,
input: turnInput,
input: [
{
type: "text",
text: input.input,
text_elements: [],
},
],
};
const normalizedModel = normalizeCodexModelSlug(input.model);
if (normalizedModel) {
-252
View File
@@ -1,252 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
CommitMessageGenerationInput,
CommitMessageGenerationResult,
PrContentGenerationInput,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
type ProcessRunner = (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const COMMIT_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
subject: { type: "string" },
body: { type: "string" },
},
required: ["subject", "body"],
additionalProperties: false,
} as const;
const PR_OUTPUT_SCHEMA_JSON = {
type: "object",
properties: {
title: { type: "string" },
body: { type: "string" },
},
required: ["title", "body"],
additionalProperties: false,
} as const;
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object commit message payload.");
}
const record = raw as Record<string, unknown>;
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
const body = typeof record.body === "string" ? record.body : "";
if (subject.length === 0) {
throw new Error("Codex returned an empty commit subject.");
}
return { subject, body };
}
function parsePrOutput(raw: unknown): { title: string; body: string } {
if (!raw || typeof raw !== "object") {
throw new Error("Codex returned a non-object PR payload.");
}
const record = raw as Record<string, unknown>;
const title = typeof record.title === "string" ? record.title.trim() : "";
const body = typeof record.body === "string" ? record.body.trim() : "";
if (title.length === 0 || body.length === 0) {
throw new Error("Codex returned an invalid PR title/body payload.");
}
return { title, body };
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
async function writeTempFile(prefix: string, content: string): Promise<string> {
const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
await fs.writeFile(filePath, content, "utf8");
return filePath;
}
async function safeUnlink(filePath: string): Promise<void> {
try {
await fs.unlink(filePath);
} catch {
// Best-effort cleanup.
}
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
async function runCodexJson<T>({
cwd,
prompt,
outputSchemaJson,
parse,
run,
}: {
cwd: string;
prompt: string;
outputSchemaJson: object;
parse: (raw: unknown) => T;
run: ProcessRunner;
}): Promise<T> {
const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
let outputPath: string | null = null;
try {
outputPath = await writeTempFile("codex-output", "");
await run(
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
CODEX_MODEL,
"--config",
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
"-",
],
{
cwd,
timeoutMs: 180_000,
stdin: prompt,
},
);
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
if (rawOutput.length === 0) {
throw new Error("Codex returned an empty response.");
}
let parsedJson: unknown;
try {
parsedJson = JSON.parse(rawOutput);
} catch {
throw new Error("Codex returned invalid JSON output.");
}
return parse(parsedJson);
} finally {
await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
}
}
interface CodexTextGeneratorDeps {
runProcess?: ProcessRunner;
}
export class CodexTextGenerator implements TextGenerationService {
private readonly run: ProcessRunner;
constructor(deps: CodexTextGeneratorDeps = {}) {
this.run = deps.runProcess ?? runProcess;
}
async generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult> {
const prompt = [
"You write concise git commit messages.",
"Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
parse: (raw) => parseCommitOutput(raw),
run: this.run,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
};
}
async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generated = await runCodexJson({
cwd: input.cwd,
prompt,
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
parse: (raw) => parsePrOutput(raw),
run: this.run,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
}
}
-32
View File
@@ -1,32 +0,0 @@
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
}
export interface PrContentGenerationInput {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface PrContentGenerationResult {
title: string;
body: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}
+5 -424
View File
@@ -2,16 +2,14 @@ import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import {
GitCoreService,
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
runTerminalCommand,
} from "./git";
@@ -52,25 +50,6 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
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 ──
describe("git integration", () => {
@@ -126,82 +105,14 @@ describe("git integration", () => {
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 initRepoWithCommit(tmp.path);
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.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" });
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("older-branch");
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");
expect(result.branches[0]!.current).toBe(true);
});
it("lists multiple branches after creating them", async () => {
@@ -239,207 +150,6 @@ describe("git integration", () => {
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 () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
@@ -725,133 +435,4 @@ describe("git integration", () => {
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
});
});
describe("GitCoreService", () => {
it("supports branch lifecycle operations through the service API", async () => {
await using tmp = await makeTmpDir();
const core = new GitCoreService();
await core.initRepo({ cwd: tmp.path });
await git(tmp.path, "config user.email '[email protected]'");
await git(tmp.path, "config user.name 'Test'");
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
await git(tmp.path, "add .");
await git(tmp.path, "commit -m 'initial commit'");
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
const branches = await core.listBranches({ cwd: tmp.path });
expect(branches.isRepo).toBe(true);
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
});
it("reports status details and dirty state", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const clean = await core.status({ cwd: tmp.path });
expect(clean.hasWorkingTreeChanges).toBe(false);
expect(clean.branch).toBeTruthy();
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
const dirty = await core.statusDetails(tmp.path);
expect(dirty.hasWorkingTreeChanges).toBe(true);
});
it("prepares commit context by auto-staging and creates commit", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
it("pushes with upstream setup and then skips when up to date", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
const core = new GitCoreService();
const context = await core.prepareCommitContext(tmp.path);
expect(context).not.toBeNull();
await core.commit(tmp.path, "Add feature file", "");
const pushed = await core.pushCurrentBranch(tmp.path, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
"origin/feature/core-push",
);
const skipped = await core.pushCurrentBranch(tmp.path, null);
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();
});
});
});
+235 -609
View File
@@ -1,26 +1,18 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
gitPullInputSchema,
gitPullResultSchema,
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
type GitCreateBranchInput,
type GitCreateWorktreeInput,
type GitCreateWorktreeResult,
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitPullInput,
type GitPullResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
import type {
GitCheckoutInput,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitRemoveWorktreeInput,
} from "@t3tools/contracts";
import { type ProcessRunResult, runProcess } from "./processRunner";
export interface TerminalCommandInput {
command: string;
@@ -29,587 +21,95 @@ export interface TerminalCommandInput {
maxOutputBytes?: number;
}
export type TerminalCommandResult = ProcessRunResult;
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
interface RunGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
}
interface ExecuteGitOptions {
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
export interface TerminalCommandResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
}
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
/** Spawn git directly with an argv array — no shell, no quoting needed. */
function runGit(
args: readonly string[],
cwd: string,
timeoutMs = 30_000,
): Promise<ProcessRunResult> {
return runProcess("git", args, {
cwd,
timeoutMs,
allowNonZeroExit: true,
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
outputMode: "truncate",
});
}
function trimStdout(value: string): string {
return value.trim();
}
function parseBranchAb(value: string): { ahead: number; behind: number } {
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
if (!match) return { ahead: 0, behind: 0 };
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
ahead: Number(match[1] ?? "0"),
behind: Number(match[2] ?? "0"),
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
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 {
return `git ${args.join(" ")}`;
}
function normalizeGitSpawnError(cwd: string, error: unknown): Error {
if (!(error instanceof Error)) {
return new Error("Failed to run git command.");
}
if (!fs.existsSync(cwd)) {
return new Error(`Working directory does not exist: ${cwd}`);
}
if (error.message.includes("Command not found: git")) {
return new Error("Git is required but not available on PATH.");
}
return new Error(`Failed to run git command: ${error.message}`);
}
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return new Error("Current folder is not a git repository.");
}
if (result.timedOut) {
return new Error(`${commandLabel(args)} timed out.`);
}
const detail =
stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
return new Error(`${commandLabel(args)} failed: ${detail}`);
}
async function runGitOrThrow(
cwd: string,
args: readonly string[],
options: RunGitOptions = {},
): Promise<TerminalCommandResult> {
let result: TerminalCommandResult;
try {
result = await runGit(args, cwd, options.timeoutMs);
} catch (error) {
throw normalizeGitSpawnError(cwd, error);
}
if (result.timedOut) {
throw normalizeGitExecutionError(args, result);
}
if (!options.allowNonZeroExit && result.code !== 0) {
throw normalizeGitExecutionError(args, result);
}
return result;
}
async function executeGit(
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Promise<TerminalCommandResult> {
const result = await runGitOrThrow(cwd, args, {
timeoutMs: options.timeoutMs,
allowNonZeroExit: true,
});
if (options.allowNonZeroExit || result.code === 0) {
return result;
}
const stderr = result.stderr.trim();
if (stderr.length > 0) {
throw new Error(stderr);
}
if (options.fallbackErrorMessage) {
throw new Error(options.fallbackErrorMessage);
}
throw normalizeGitExecutionError(args, result);
}
export class GitCoreService {
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.statusDetails(input.cwd);
return gitStatusResultSchema.parse({
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
});
}
async statusDetails(cwd: string): Promise<GitStatusDetails> {
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 upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();
for (const line of statusStdout.split(/\r?\n/g)) {
if (line.startsWith("# branch.head ")) {
const value = line.slice("# branch.head ".length).trim();
branch = value.startsWith("(") ? null : value;
continue;
}
if (line.startsWith("# branch.upstream ")) {
const value = line.slice("# branch.upstream ".length).trim();
upstreamRef = value.length > 0 ? value : null;
continue;
}
if (line.startsWith("# branch.ab ")) {
const value = line.slice("# branch.ab ".length).trim();
const parsed = parseBranchAb(value);
aheadCount = parsed.ahead;
behindCount = parsed.behind;
continue;
}
if (line.trim().length > 0 && !line.startsWith("#")) {
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 {
branch,
upstreamRef,
hasWorkingTreeChanges,
workingTree: {
files,
insertions,
deletions,
},
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
};
}
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
return {
stagedSummary,
stagedPatch,
};
}
async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
const args = ["commit", "-m", subject];
const trimmedBody = body.trim();
if (trimmedBody.length > 0) {
args.push("-m", trimmedBody);
}
await this.git(cwd, args);
const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
return { commitSha };
}
async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
const details = await this.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
await this.git(cwd, ["push", "-u", "origin", branch]);
return {
status: "pushed",
branch,
upstreamBranch: `origin/${branch}`,
setUpstream: true,
};
}
await this.git(cwd, ["push"]);
return {
status: "pushed",
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
setUpstream: false,
};
}
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> {
const range = `${baseBranch}..HEAD`;
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
this.gitStdout(cwd, ["log", "--oneline", range]),
this.gitStdout(cwd, ["diff", "--stat", range]),
this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
]);
return {
commitSummary,
diffSummary,
diffPatch,
};
}
async readConfigValue(cwd: string, key: string): Promise<string | null> {
const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
const value = trimStdout(stdout);
return value.length > 0 ? value : null;
}
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
const branchRecency = await executeGit(
/** Spawn git directly with an argv array — no shell, no quoting needed. */
function runGit(args: string[], cwd: string, timeoutMs = 30_000): Promise<TerminalCommandResult> {
return new Promise((resolve, reject) => {
const child = spawn("git", args, {
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
},
);
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
const branchLastCommit = new Map<string, number>();
if (branchRecency.code !== 0) {
return branchLastCommit;
}
const maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES;
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let timedOut = false;
let outputTruncated = false;
for (const line of branchRecency.stdout.split("\n")) {
if (line.length === 0) {
continue;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) child.kill("SIGKILL");
}, 1_000).unref();
}, timeoutMs);
child.stdout?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.stderr?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
if (outputTruncated) {
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
}
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> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
resolve({ stdout, stderr, code: code ?? null, signal: signal ?? null, timedOut });
});
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
throw new Error(stderr || "git branch failed");
}
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
branchRecencyPromise,
]);
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
const worktreeMap = new Map<string, string>();
if (worktreeList.code === 0) {
let currentPath: string | null = null;
for (const line of worktreeList.stdout.split("\n")) {
if (line.startsWith("worktree ")) {
const candidatePath = line.slice("worktree ".length);
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
} else if (line.startsWith("branch refs/heads/") && currentPath) {
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
} else if (line === "") {
currentPath = null;
}
}
}
const branches = result.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
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 { branches, isRepo: true };
}
async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const worktreePath =
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
await executeGit(
input.cwd,
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
{ fallbackErrorMessage: "git worktree add failed" },
);
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
}
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await executeGit(input.cwd, ["worktree", "remove", input.path], {
timeoutMs: 15_000,
fallbackErrorMessage: "git worktree remove failed",
});
}
async createBranch(input: GitCreateBranchInput): Promise<void> {
await executeGit(input.cwd, ["branch", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git branch create failed",
});
}
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
const upstreamRef = trimStdout(
await this.gitStdout(
cwd,
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
true,
),
);
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
return;
}
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0) {
return;
}
if (upstreamBranch.length === 0) {
return;
}
const refspec = `+refs/heads/${upstreamBranch}:refs/remotes/${upstreamRef}`;
await this.git(cwd, ["fetch", "--quiet", "--no-tags", remoteName, refspec], true);
}
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
await executeGit(input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
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> {
await executeGit(input.cwd, ["init"], {
timeoutMs: 10_000,
fallbackErrorMessage: "git init failed",
});
}
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
await executeGit(cwd, args, { allowNonZeroExit });
}
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
const result = await executeGit(cwd, args, { allowNonZeroExit });
return result.stdout;
}
});
}
const defaultGitCoreService = new GitCoreService();
export async function runTerminalCommand(
input: TerminalCommandInput,
): Promise<TerminalCommandResult> {
@@ -622,51 +122,177 @@ export async function runTerminalCommand(
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
const result = await runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: maxOutputBytes,
outputMode: "truncate",
return new Promise((resolve, reject) => {
const child = spawn(shellPath, args, {
cwd: input.cwd,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let timedOut = false;
let outputTruncated = false;
const timeout = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => {
if (!child.killed) {
child.kill("SIGKILL");
}
}, 1_000).unref();
}, input.timeoutMs ?? 30_000);
child.stdout?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.stderr?.on("data", (chunk: Buffer) => {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
outputTruncated = outputTruncated || appended.truncated;
});
child.on("error", (error) => {
clearTimeout(timeout);
reject(error);
});
child.on("close", (code, signal) => {
clearTimeout(timeout);
if (outputTruncated) {
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
}
resolve({
stdout,
stderr,
code: code ?? null,
signal: signal ?? null,
timedOut,
});
});
});
if (!result.stdoutTruncated && !result.stderrTruncated) {
return result;
}
return {
...result,
stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
};
}
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
return defaultGitCoreService.listBranches(input);
}
const result = await runGit(["branch", "--no-color"], input.cwd, 10_000);
export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
const input = gitPullInputSchema.parse(raw);
return defaultGitCoreService.pullCurrentBranch(input.cwd);
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.includes("not a git repository")) {
return { branches: [], isRepo: false };
}
throw new Error(stderr || "git branch failed");
}
// Resolve the real default branch from the remote
const [defaultRef, worktreeList] = await Promise.all([
runGit(["symbolic-ref", "refs/remotes/origin/HEAD"], input.cwd, 5_000),
runGit(["worktree", "list", "--porcelain"], input.cwd, 5_000),
]);
const defaultBranch =
defaultRef.code === 0 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : null;
// Build branch-name → worktree-path map from porcelain output.
// Only include worktrees whose directories still exist on disk (skip prunable/stale ones).
const worktreeMap = new Map<string, string>();
if (worktreeList.code === 0) {
let currentPath: string | null = null;
for (const line of worktreeList.stdout.split("\n")) {
if (line.startsWith("worktree ")) {
const candidatePath = line.slice("worktree ".length);
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
} else if (line.startsWith("branch refs/heads/") && currentPath) {
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
} else if (line === "") {
currentPath = null;
}
}
}
const branches = result.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
if (a.current !== b.current) return a.current ? -1 : 1;
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
return a.name.localeCompare(b.name);
});
return { branches, isRepo: true };
}
export async function createGitWorktree(
input: GitCreateWorktreeInput,
): Promise<GitCreateWorktreeResult> {
return defaultGitCoreService.createWorktree(input);
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
const worktreePath =
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
// Create a new branch from the base branch in a new worktree
const result = await runGit(
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
input.cwd,
);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git worktree add failed");
}
return {
worktree: {
path: worktreePath,
branch: input.newBranch,
},
};
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
await defaultGitCoreService.removeWorktree(input);
const result = await runGit(["worktree", "remove", input.path], input.cwd, 15_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git worktree remove failed");
}
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
await defaultGitCoreService.createBranch(input);
const result = await runGit(["branch", input.branch], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git branch create failed");
}
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
await defaultGitCoreService.checkoutBranch(input);
const result = await runGit(["checkout", input.branch], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git checkout failed");
}
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
await defaultGitCoreService.initRepo(input);
const result = await runGit(["init"], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git init failed");
}
}
-482
View File
@@ -1,482 +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 { GitManager } from "./gitManager";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
interface FakeGhScenario {
prListSequence?: string[];
createdPrUrl?: string;
defaultBranch?: string;
failWith?: Error;
}
interface FakeGitTextGenerator {
generateCommitMessage: (input: {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
}) => Promise<{ subject: string; body: string }>;
generatePrContent: (input: {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}) => Promise<{ title: string; body: string }>;
}
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function runGit(
cwd: string,
args: readonly string[],
allowNonZeroExit = false,
): Promise<ProcessRunResult> {
return runProcess("git", args, { cwd, allowNonZeroExit });
}
async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await runGit(cwd, args);
return result.stdout.trim();
}
async function initRepo(cwd: string): Promise<void> {
await runGit(cwd, ["init", "--initial-branch=main"]);
await runGit(cwd, ["config", "user.email", "[email protected]"]);
await runGit(cwd, ["config", "user.name", "Test User"]);
fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
await runGit(cwd, ["add", "README.md"]);
await runGit(cwd, ["commit", "-m", "Initial commit"]);
}
async function createBareRemote(): Promise<string> {
const remoteDir = makeTempDir("t3code-git-remote-");
await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
return remoteDir;
}
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
body: "",
}),
generatePrContent: async () => ({
title: "Add stacked git actions",
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
}),
...overrides,
};
}
function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
runner: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
ghCalls: string[];
} {
const prListQueue = [...(scenario.prListSequence ?? [])];
const ghCalls: string[] = [];
const runner = async (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
): Promise<ProcessRunResult> => {
if (command !== "gh") {
return runProcess(command, args, options);
}
ghCalls.push(args.join(" "));
if (scenario.failWith) {
throw scenario.failWith;
}
if (args[0] === "pr" && args[1] === "list") {
const stdout = (prListQueue.shift() ?? "[]") + "\n";
return {
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "pr" && args[1] === "view") {
return {
stdout: "",
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
if (args[0] === "repo" && args[1] === "view") {
return {
stdout: `${scenario.defaultBranch ?? "main"}\n`,
stderr: "",
code: 0,
signal: null,
timedOut: false,
};
}
throw new Error(`Unexpected gh command: ${args.join(" ")}`);
};
return { runner, ghCalls };
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("GitManager", () => {
it("status includes open PR metadata when branch already has an open PR", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
const { runner } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseRefName: "main",
headRefName: "feature/status-open-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-pr");
expect(status.openPr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
});
});
it("status is resilient to gh lookup failures and returns openPr null", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const status = await manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.openPr).toBeNull();
});
it("creates a commit when working tree is dirty", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"Implement stacked git actions",
);
});
it("uses custom commit message when provided", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
let generatedCount = 0;
const manager = new GitManager({
textGenerator: createTextGenerator({
generateCommitMessage: async () => {
generatedCount += 1;
return {
subject: "this should not be used",
body: "",
};
},
}),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
commitMessage: "feat: custom summary line\n\n- details from user",
});
expect(result.commit.status).toBe("created");
expect(result.commit.subject).toBe("feat: custom summary line");
expect(generatedCount).toBe(0);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
"feat: custom summary line",
);
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
"- details from user",
);
});
it("skips commit when there are no uncommitted changes", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_not_requested");
expect(result.pr.status).toBe("skipped_not_requested");
});
it("commits and pushes with upstream auto-setup when needed", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/stacked-flow",
);
});
it("skips push when branch is already up to date", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
});
expect(result.commit.status).toBe("skipped_no_changes");
expect(result.push.status).toBe("skipped_up_to_date");
});
it("returns existing PR metadata for commit/push/pr action", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
JSON.stringify([
{
number: 42,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/existing-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
});
it("creates PR when one does not already exist", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
await runGit(repoDir, ["add", "changes.txt"]);
await runGit(repoDir, ["commit", "-m", "Feature commit"]);
await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
const { runner, ghCalls } = createRunnerWithFakeGh({
prListSequence: [
"[]",
JSON.stringify([
{
number: 88,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
baseRefName: "main",
headRefName: "feature-create-pr",
},
]),
],
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
const result = await manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(88);
expect(
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
).toBe(true);
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
});
it("rejects push/pr actions from detached HEAD", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
const manager = new GitManager({
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push",
}),
).rejects.toThrow("detached HEAD");
});
it("surfaces missing gh binary errors", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("Command not found: gh"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("GitHub CLI (`gh`) is required");
});
it("surfaces gh auth errors with guidance", async () => {
const repoDir = makeTempDir("t3code-git-manager-");
await initRepo(repoDir);
await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
const remoteDir = await createBareRemote();
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
const { runner } = createRunnerWithFakeGh({
failWith: new Error("authentication failed"),
});
const manager = new GitManager({
runProcess: runner,
textGenerator: createTextGenerator(),
});
await expect(
manager.runStackedAction({
cwd: repoDir,
action: "commit_push_pr",
}),
).rejects.toThrow("gh auth login");
});
});
-467
View File
@@ -1,467 +0,0 @@
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import {
gitRunStackedActionInputSchema,
gitRunStackedActionResultSchema,
gitStatusInputSchema,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import type {
CommitMessageGenerationResult,
PrContentGenerationResult,
TextGenerationService,
} from "./coreServices";
import { CodexTextGenerator } from "./codexTextGenerator";
import { GitCoreService } from "./git";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
const GH_CLI_TIMEOUT_MS = 30_000;
interface GitManagerDeps {
runProcess?: (
command: string,
args: readonly string[],
options?: ProcessRunOptions,
) => Promise<ProcessRunResult>;
textGenerator?: TextGenerationService;
gitCore?: GitCoreService;
}
interface OpenPrInfo {
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}
function parseOpenPrList(raw: unknown): OpenPrInfo[] {
if (!Array.isArray(raw)) return [];
const parsed: OpenPrInfo[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== "object") continue;
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
continue;
}
if (
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
parsed.push({
number,
title,
url,
baseRefName,
headRefName,
});
}
return parsed;
}
function trimStdout(value: string): string {
return value.trim();
}
function limitContext(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
return `${value.slice(0, maxChars)}\n\n[truncated]`;
}
function sanitizeCommitMessage(
generated: CommitMessageGenerationResult,
): CommitMessageGenerationResult {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
return {
subject: safeSubject,
body: generated.body.trim(),
};
}
function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
const normalized = raw.replace(/\r\n/g, "\n").trim();
if (normalized.length === 0) {
return null;
}
const [firstLine, ...rest] = normalized.split("\n");
const subject = firstLine?.trim() ?? "";
if (subject.length === 0) {
return null;
}
return {
subject,
body: rest.join("\n").trim(),
};
}
function extractBranchFromRef(ref: string): string {
const normalized = ref.trim();
if (normalized.startsWith("refs/remotes/")) {
const withoutPrefix = normalized.slice("refs/remotes/".length);
const firstSlash = withoutPrefix.indexOf("/");
if (firstSlash === -1) {
return withoutPrefix.trim();
}
return withoutPrefix.slice(firstSlash + 1).trim();
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
function asCommandNotFound(command: string, error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
if (command === "gh") {
return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
}
if (command === "codex") {
return new Error("Codex CLI (`codex`) is required but not available on PATH.");
}
return new Error(`${command} is required but not available on PATH.`);
}
function normalizeGitHubAuthError(error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("gh auth login") ||
lower.includes("no oauth token")
) {
return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
}
return undefined;
}
function toStatusOpenPr(pr: OpenPrInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
};
}
export class GitManager {
private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
private readonly textGenerator: TextGenerationService;
private readonly gitCore: GitCoreService;
constructor(deps: GitManagerDeps = {}) {
this.run = deps.runProcess ?? runProcess;
this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
this.gitCore = deps.gitCore ?? new GitCoreService();
}
async status(raw: GitStatusInput): Promise<GitStatusResult> {
const input = gitStatusInputSchema.parse(raw);
const details = await this.gitCore.statusDetails(input.cwd);
let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
if (details.branch && details.hasUpstream) {
try {
const existing = await this.findOpenPr(input.cwd, details.branch);
if (existing) {
openPr = toStatusOpenPr(existing);
}
} catch {
// PR lookup is best-effort for status rendering.
}
}
return {
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr,
};
}
async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
const input = gitRunStackedActionInputSchema.parse(raw);
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = await this.gitCore.statusDetails(input.cwd);
if (wantsPush && !initialStatus.branch) {
throw new Error("Cannot push from detached HEAD.");
}
if (wantsPr && !initialStatus.branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const push = wantsPush
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? await this.runPrStep(input.cwd, initialStatus.branch)
: { status: "skipped_not_requested" as const };
return gitRunStackedActionResultSchema.parse({
action: input.action,
commit,
push,
pr,
});
}
private async runCommitStep(
cwd: string,
branch: string | null,
commitMessage?: string,
): Promise<{
status: "created" | "skipped_no_changes";
commitSha?: string | undefined;
subject?: string | undefined;
}> {
const context = await this.gitCore.prepareCommitContext(cwd);
if (!context) {
return { status: "skipped_no_changes" };
}
let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
commitMessage ?? "",
);
if (!generated) {
try {
generated = sanitizeCommitMessage(
await this.textGenerator.generateCommitMessage({
cwd,
branch,
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
}),
);
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
}
const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
return {
status: "created",
commitSha,
subject: generated.subject,
};
}
private async runPrStep(
cwd: string,
fallbackBranch: string | null,
): Promise<{
status: "created" | "opened_existing" | "skipped_not_requested";
url?: string | undefined;
number?: number | undefined;
baseBranch?: string | undefined;
headBranch?: string | undefined;
title?: string | undefined;
}> {
const details = await this.gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
if (!branch) {
throw new Error("Cannot create a pull request from detached HEAD.");
}
if (!details.hasUpstream) {
throw new Error("Current branch has not been pushed. Push before creating a PR.");
}
const existing = await this.findOpenPr(cwd, branch);
if (existing) {
return {
status: "opened_existing",
url: existing.url,
number: existing.number,
baseBranch: existing.baseRefName,
headBranch: existing.headRefName,
title: existing.title,
};
}
const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
let generated: PrContentGenerationResult;
try {
generated = await this.textGenerator.generatePrContent({
cwd,
baseBranch,
headBranch: branch,
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
});
} catch (error) {
throw asCommandNotFound("codex", error) ?? error;
}
const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
await fs.writeFile(bodyFile, generated.body, "utf8");
try {
await this.runGh(cwd, [
"pr",
"create",
"--base",
baseBranch,
"--head",
branch,
"--title",
generated.title,
"--body-file",
bodyFile,
]);
} finally {
try {
await fs.unlink(bodyFile);
} catch {
// Best-effort cleanup.
}
}
const created = await this.findOpenPr(cwd, branch);
if (!created) {
return {
status: "created",
baseBranch,
headBranch: branch,
title: generated.title,
};
}
return {
status: "created",
url: created.url,
number: created.number,
baseBranch: created.baseRefName,
headBranch: created.headRefName,
title: created.title,
};
}
private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [
"pr",
"list",
"--head",
branch,
"--state",
"open",
"--limit",
"1",
"--json",
"number,title,url,baseRefName,headRefName",
]);
const raw = trimStdout(stdout);
if (raw.length === 0) return null;
let parsedJson: unknown;
try {
parsedJson = JSON.parse(raw);
} catch {
throw new Error("GitHub CLI returned invalid PR list JSON.");
}
const parsed = parseOpenPrList(parsedJson);
return parsed[0] ?? null;
}
private async resolveBaseBranch(
cwd: string,
branch: string,
upstreamRef: string | null,
): Promise<string> {
const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
}
}
try {
const ghDefault = await this.runGhStdout(cwd, [
"repo",
"view",
"--json",
"defaultBranchRef",
"--jq",
".defaultBranchRef.name",
]);
const defaultBranch = trimStdout(ghDefault);
if (defaultBranch.length > 0) return defaultBranch;
} catch {
// Fall through to deterministic fallback.
}
return "main";
}
private async runGh(cwd: string, args: readonly string[]): Promise<void> {
await this.runGhCommand(cwd, args);
}
private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
const result = await this.runGhCommand(cwd, args);
return result.stdout;
}
private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
try {
return await this.run("gh", args, {
cwd,
timeoutMs: GH_CLI_TIMEOUT_MS,
});
} catch (error) {
throw (
asCommandNotFound("gh", error) ??
normalizeGitHubAuthError(error) ??
(error instanceof Error ? error : new Error("GitHub CLI command failed."))
);
}
}
}
-23
View File
@@ -1,23 +0,0 @@
import { describe, expect, it } from "vitest";
import { runProcess } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
).rejects.toThrow("exceeded stdout buffer limit");
});
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
maxBufferBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
});
-242
View File
@@ -1,242 +0,0 @@
import { spawn } from "node:child_process";
export interface ProcessRunOptions {
cwd?: string | undefined;
timeoutMs?: number | undefined;
env?: NodeJS.ProcessEnv | undefined;
stdin?: string | undefined;
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
}
export interface ProcessRunResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
stdoutTruncated?: boolean | undefined;
stderrTruncated?: boolean | undefined;
}
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
const maybeCode = (error as NodeJS.ErrnoException).code;
if (maybeCode === "ENOENT") {
return new Error(`Command not found: ${command}`);
}
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
const stderr = result.stderr.trim();
const detail = stderr.length > 0 ? ` ${stderr}` : "";
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
function normalizeStdinError(command: string, args: readonly string[], error: unknown): 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)}: ${error.message}`);
}
function normalizeBufferError(
command: string,
args: readonly string[],
stream: "stdout" | "stderr",
maxBufferBytes: number,
): Error {
return new Error(
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
);
}
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
export async function runProcess(
command: string,
args: readonly string[],
options: ProcessRunOptions = {},
): Promise<ProcessRunResult> {
const timeoutMs = options.timeoutMs ?? 60_000;
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const outputMode = options.outputMode ?? "error";
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
});
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let stdoutTruncated = false;
let stderrTruncated = false;
let timedOut = false;
let settled = false;
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
const timeoutTimer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
forceKillTimer = setTimeout(() => {
child.kill("SIGKILL");
}, 1_000);
}, timeoutMs);
const finalize = (callback: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timeoutTimer);
if (forceKillTimer) {
clearTimeout(forceKillTimer);
}
callback();
};
const fail = (error: Error): void => {
child.kill("SIGTERM");
finalize(() => {
reject(error);
});
};
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
return null;
}
stdout += text;
stdoutBytes += byteLength;
if (stdoutBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
return null;
}
stderr += text;
stderrBytes += byteLength;
if (stderrBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
}
}
return null;
};
child.stdout.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stdout", chunk);
if (error) {
fail(error);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stderr", chunk);
if (error) {
fail(error);
}
});
child.once("error", (error) => {
finalize(() => {
reject(normalizeSpawnError(command, args, error));
});
});
child.once("close", (code, signal) => {
const result: ProcessRunResult = {
stdout,
stderr,
code,
signal,
timedOut,
stdoutTruncated,
stderrTruncated,
};
finalize(() => {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
return;
}
resolve(result);
});
});
child.stdin.once("error", (error) => {
fail(normalizeStdinError(command, args, error));
});
if (options.stdin !== undefined) {
child.stdin.write(options.stdin, (error) => {
if (error) {
fail(normalizeStdinError(command, args, error));
return;
}
child.stdin.end();
});
return;
}
child.stdin.end();
});
}
-54
View File
@@ -1,54 +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 { ensureNodePtySpawnHelperExecutable } from "./ptyAdapter";
function fileMode(filePath: string): number {
return fs.statSync(filePath).mode & 0o777;
}
describe("ensureNodePtySpawnHelperExecutable", () => {
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("adds executable bits when helper exists but is not executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o644);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("keeps executable helper as executable", () => {
if (process.platform === "win32") return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
tempDirs.push(dir);
const helperPath = path.join(dir, "spawn-helper");
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
fs.chmodSync(helperPath, 0o755);
ensureNodePtySpawnHelperExecutable(helperPath);
expect(fileMode(helperPath) & 0o111).toBe(0o111);
});
it("does not throw when helper path is missing", () => {
const missing = path.join(os.tmpdir(), `does-not-exist-${Date.now()}`);
expect(() => ensureNodePtySpawnHelperExecutable(missing)).not.toThrow();
});
});
-51
View File
@@ -1,7 +1,3 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import * as nodePty from "node-pty";
export interface PtyExitEvent {
@@ -30,52 +26,6 @@ export interface PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess;
}
const requireForNodePty = createRequire(import.meta.url);
let didEnsureSpawnHelperExecutable = false;
function resolveNodePtySpawnHelperPath(): string | null {
try {
const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
const packageDir = path.dirname(packageJsonPath);
const candidates = [
path.join(packageDir, "build", "Release", "spawn-helper"),
path.join(packageDir, "build", "Debug", "spawn-helper"),
path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"),
];
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
} catch {
return null;
}
}
export function ensureNodePtySpawnHelperExecutable(explicitPath?: string): void {
if (process.platform === "win32") return;
if (!explicitPath && didEnsureSpawnHelperExecutable) return;
const helperPath = explicitPath ?? resolveNodePtySpawnHelperPath();
if (!helperPath) return;
if (!explicitPath) {
didEnsureSpawnHelperExecutable = true;
}
try {
const stat = fs.statSync(helperPath);
const mode = stat.mode & 0o777;
if ((mode & 0o111) === 0) {
fs.chmodSync(helperPath, mode | 0o111);
}
} catch {
// Best effort only. If chmod fails, node-pty spawn will surface the real error.
}
}
class NodePtyProcess implements PtyProcess {
constructor(private readonly process: nodePty.IPty) {}
@@ -117,7 +67,6 @@ class NodePtyProcess implements PtyProcess {
export class NodePtyAdapter implements PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess {
ensureNodePtySpawnHelperExecutable();
const ptyProcess = nodePty.spawn(input.shell, [], {
cwd: input.cwd,
cols: input.cols,
+8 -208
View File
@@ -2,10 +2,9 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type TerminalEvent,
type TerminalOpenInput,
import type {
TerminalEvent,
TerminalOpenInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
@@ -63,15 +62,10 @@ class FakePtyProcess implements PtyProcess {
class FakePtyAdapter implements PtyAdapter {
readonly spawnInputs: PtySpawnInput[] = [];
readonly processes: FakePtyProcess[] = [];
readonly spawnFailures: Error[] = [];
private nextPid = 9000;
spawn(input: PtySpawnInput): PtyProcess {
this.spawnInputs.push(input);
const failure = this.spawnFailures.shift();
if (failure) {
throw failure;
}
const process = new FakePtyProcess(this.nextPid++);
this.processes.push(process);
return process;
@@ -110,26 +104,10 @@ function historyLogName(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
}
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return path.join(logsDir, historyLogName(threadId));
}
function multiTerminalHistoryLogPath(
logsDir: string,
threadId = "thread-1",
terminalId = "default",
): string {
return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
describe("TerminalManager", () => {
const tempDirs: string[] = [];
@@ -139,14 +117,7 @@ describe("TerminalManager", () => {
}
});
function makeManager(
historyLineLimit = 5,
options: {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
subprocessPollIntervalMs?: number;
} = {},
) {
function makeManager(historyLineLimit = 5) {
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
tempDirs.push(logsDir);
const ptyAdapter = new FakePtyAdapter();
@@ -154,25 +125,17 @@ describe("TerminalManager", () => {
logsDir,
ptyAdapter,
historyLineLimit,
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
shellResolver: () => "/bin/bash",
});
return { logsDir, ptyAdapter, manager };
}
it("spawns lazily and reuses running terminal per thread", async () => {
const { manager, ptyAdapter } = makeManager();
const [first, second] = await Promise.all([
manager.open(openInput()),
manager.open(openInput()),
]);
const [first, second] = await Promise.all([manager.open(openInput()), manager.open(openInput())]);
const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1");
expect(first.terminalId).toBe("default");
expect(second.threadId).toBe("thread-1");
expect(third.threadId).toBe("thread-1");
expect(ptyAdapter.spawnInputs).toHaveLength(1);
@@ -196,27 +159,6 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("supports multiple terminals per thread with isolated sessions", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "term-2" }));
const first = ptyAdapter.processes[0];
const second = ptyAdapter.processes[1];
expect(first).toBeDefined();
expect(second).toBeDefined();
if (!first || !second) return;
await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
expect(first.writes).toEqual(["pwd\n"]);
expect(second.writes).toEqual(["ls\n"]);
expect(ptyAdapter.spawnInputs).toHaveLength(2);
manager.dispose();
});
it("clears transcript and emits cleared event", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = [];
@@ -234,14 +176,6 @@ describe("TerminalManager", () => {
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
expect(events.some((event) => event.type === "cleared")).toBe(true);
expect(
events.some(
(event) =>
event.type === "cleared" &&
event.threadId === "thread-1" &&
event.terminalId === "default",
),
).toBe(true);
manager.dispose();
});
@@ -288,38 +222,6 @@ describe("TerminalManager", () => {
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 () => {
const { manager, ptyAdapter } = makeManager(3);
await manager.open(openInput());
@@ -352,118 +254,16 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("closes all terminals for a thread when close omits terminalId", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "sidecar" }));
const defaultProcess = ptyAdapter.processes[0];
const sidecarProcess = ptyAdapter.processes[1];
expect(defaultProcess).toBeDefined();
expect(sidecarProcess).toBeDefined();
if (!defaultProcess || !sidecarProcess) return;
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(defaultProcess.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", "sidecar"))).toBe(false);
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 legacyPath = path.join(logsDir, "thread-1.log");
const nextPath = historyLogPath(logsDir);
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
const snapshot = await manager.open(openInput());
expect(snapshot.history).toBe("legacy-line\n");
expect(fs.existsSync(nextPath)).toBe(true);
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
expect(fs.existsSync(legacyPath)).toBe(false);
expect(fs.existsSync(legacyPath)).toBe(true);
manager.dispose();
});
it("retries with fallback shells when preferred shell spawn fails", async () => {
const { manager, ptyAdapter } = makeManager(5, {
shellResolver: () => "/definitely/missing-shell -l",
});
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
const snapshot = await manager.open(openInput());
expect(snapshot.status).toBe("running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
if (process.platform === "win32") {
expect(
ptyAdapter.spawnInputs.some(
(input) => input.shell === "cmd.exe" || input.shell === "powershell.exe",
),
).toBe(true);
} else {
expect(
ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
),
).toBe(true);
}
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();
}
});
});
+87 -493
View File
@@ -3,32 +3,25 @@ import fs from "node:fs";
import path from "node:path";
import {
DEFAULT_TERMINAL_ID,
type TerminalClearInput,
type TerminalCloseInput,
type TerminalEvent,
type TerminalOpenInput,
type TerminalResizeInput,
type TerminalSessionSnapshot,
type TerminalSessionStatus,
type TerminalThreadInput,
type TerminalWriteInput,
terminalClearInputSchema,
terminalCloseInputSchema,
terminalOpenInputSchema,
terminalResizeInputSchema,
terminalThreadInputSchema,
terminalWriteInputSchema,
} from "@t3tools/contracts";
import { createLogger } from "./logger";
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
import { runProcess } from "./processRunner";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
export interface TerminalManagerEvents {
event: [event: TerminalEvent];
@@ -39,13 +32,10 @@ export interface TerminalManagerOptions {
historyLineLimit?: number;
ptyAdapter?: PtyAdapter;
shellResolver?: () => string;
subprocessChecker?: TerminalSubprocessChecker;
subprocessPollIntervalMs?: number;
}
interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
status: TerminalSessionStatus;
pid: number | null;
@@ -58,7 +48,6 @@ interface TerminalSessionState {
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
}
function defaultShellResolver(): string {
@@ -68,140 +57,6 @@ function defaultShellResolver(): string {
return process.env.SHELL ?? "bash";
}
function normalizeShellCommand(value: string | undefined): string | null {
if (!value) return null;
const trimmed = value.trim();
if (trimmed.length === 0) return null;
if (process.platform === "win32") {
return trimmed;
}
const firstToken = trimmed.split(/\s+/g)[0]?.trim();
if (!firstToken) return null;
return firstToken.replace(/^['"]|['"]$/g, "");
}
function uniqueShells(shells: Array<string | null>): string[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const shell of shells) {
if (!shell || shell.length === 0) continue;
if (seen.has(shell)) continue;
seen.add(shell);
ordered.push(shell);
}
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver());
if (process.platform === "win32") {
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
}
return uniqueShells([
requested,
normalizeShellCommand(process.env.SHELL),
"/bin/zsh",
"/bin/bash",
"/bin/sh",
"zsh",
"bash",
"sh",
]);
}
function isRetryableShellSpawnError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const message = error.message.toLowerCase();
return (
message.includes("posix_spawnp failed") ||
message.includes("enoent") ||
message.includes("not found") ||
message.includes("file not found") ||
message.includes("no such file")
);
}
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 {
if (history.length === 0) return history;
const hasTrailingNewline = history.endsWith("\n");
@@ -222,35 +77,6 @@ function toSafeThreadId(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
}
function toSafeTerminalId(terminalId: string): string {
return Buffer.from(terminalId, "utf8").toString("base64url");
}
function toSessionKey(threadId: string, terminalId: string): string {
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): 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;
}
return spawnEnv;
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string;
@@ -262,10 +88,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly pendingPersistHistory = new Map<string, string>();
private readonly threadLocks = new Map<string, Promise<void>>();
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");
constructor(options: TerminalManagerOptions = {}) {
@@ -275,9 +97,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
this.shellResolver = options.shellResolver ?? defaultShellResolver;
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 });
}
@@ -286,14 +105,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
const existing = this.sessions.get(sessionKey);
const existing = this.sessions.get(input.threadId);
if (!existing) {
await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId, input.terminalId);
await this.flushPersistQueue(input.threadId);
const history = await this.readHistory(input.threadId);
const session: TerminalSessionState = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
@@ -306,9 +123,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, session);
this.sessions.set(input.threadId, session);
this.startSession(session, input, "started");
return this.snapshot(session);
}
@@ -317,10 +133,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.stopProcess(existing);
existing.cwd = input.cwd;
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
await this.persistHistory(existing.threadId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
await this.persistHistory(existing.threadId, existing.history);
}
if (!existing.process) {
@@ -341,22 +157,18 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async write(raw: TerminalWriteInput): Promise<void> {
const input = terminalWriteInputSchema.parse(raw);
const session = this.requireSession(input.threadId, input.terminalId);
const session = this.requireSession(input.threadId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
}
session.process.write(input.data);
}
async resize(raw: TerminalResizeInput): Promise<void> {
async resize(raw: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {
const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId, input.terminalId);
const session = this.requireSession(input.threadId);
if (!session.process || session.status !== "running") {
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
}
session.cols = input.cols;
session.rows = input.rows;
@@ -364,17 +176,16 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.process.resize(input.cols, input.rows);
}
async clear(raw: TerminalClearInput): Promise<void> {
const input = terminalClearInputSchema.parse(raw);
async clear(raw: TerminalThreadInput): Promise<void> {
const input = terminalThreadInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
const session = this.requireSession(input.threadId);
session.history = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.persistHistory(input.threadId, session.history);
this.emitEvent({
type: "cleared",
threadId: input.threadId,
terminalId: input.terminalId,
createdAt: new Date().toISOString(),
});
});
@@ -385,12 +196,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
let session = this.sessions.get(input.threadId);
if (!session) {
session = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
@@ -403,16 +212,15 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(sessionKey, session);
this.sessions.set(input.threadId, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
}
session.history = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.persistHistory(input.threadId, session.history);
this.startSession(session, input, "restarted");
return this.snapshot(session);
});
@@ -421,36 +229,23 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async close(raw: TerminalCloseInput): Promise<void> {
const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
if (input.terminalId) {
await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
return;
}
const threadSessions = this.sessionsForThread(input.threadId);
for (const session of threadSessions) {
const session = this.sessions.get(input.threadId);
if (session) {
this.stopProcess(session);
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
this.sessions.delete(input.threadId);
}
await Promise.all(
threadSessions.map((session) =>
this.flushPersistQueue(session.threadId, session.terminalId),
),
);
await this.flushPersistQueue(input.threadId);
if (input.deleteHistory) {
await this.deleteAllHistoryForThread(input.threadId);
await this.deleteHistory(input.threadId);
}
this.updateSubprocessPollingState();
});
}
dispose(): void {
this.stopSubprocessPolling();
const sessions = [...this.sessions.values()];
this.sessions.clear();
for (const session of sessions) {
for (const session of this.sessions.values()) {
this.stopProcess(session);
}
this.sessions.clear();
for (const timer of this.persistTimers.values()) {
clearTimeout(timer);
}
@@ -473,43 +268,18 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.rows = input.rows;
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
session.updatedAt = new Date().toISOString();
const shell = this.shellResolver();
let ptyProcess: PtyProcess | null = null;
let startedShell: string | null = null;
try {
const shellCandidates = resolveShellCandidates(this.shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env);
let lastSpawnError: unknown = null;
for (const shell of shellCandidates) {
try {
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: terminalEnv,
});
startedShell = shell;
break;
} catch (error) {
lastSpawnError = error;
if (!isRetryableShellSpawnError(error)) {
throw error;
}
}
}
if (!ptyProcess) {
const detail =
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
const tried =
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
throw new Error(`${detail}.${tried}`.trim());
}
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: process.env,
});
session.process = ptyProcess;
session.pid = ptyProcess.pid;
session.status = "running";
@@ -520,11 +290,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.unsubscribeExit = ptyProcess.onExit((event) => {
this.onProcessExit(session, event);
});
this.updateSubprocessPollingState();
this.emitEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
snapshot: this.snapshot(session),
});
@@ -539,22 +307,17 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.status = "error";
session.pid = null;
session.process = null;
session.hasRunningSubprocess = false;
session.updatedAt = new Date().toISOString();
this.updateSubprocessPollingState();
const message = error instanceof Error ? error.message : "Terminal start failed";
this.emitEvent({
type: "error",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
message,
});
this.logger.error("failed to start terminal", {
threadId: session.threadId,
terminalId: session.terminalId,
error: message,
...(startedShell ? { shell: startedShell } : {}),
});
}
}
@@ -562,11 +325,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private onProcessData(session: TerminalSessionState, data: string): void {
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.queuePersist(session.threadId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
data,
});
@@ -576,7 +338,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
@@ -584,12 +345,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emitEvent({
type: "exited",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
});
this.updateSubprocessPollingState();
}
private stopProcess(session: TerminalSessionState): void {
@@ -598,7 +357,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.cleanupProcessHandles(session);
session.process = null;
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.updatedAt = new Date().toISOString();
try {
@@ -607,11 +365,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn("failed to kill terminal process", {
threadId: session.threadId,
terminalId: session.terminalId,
error: message,
});
}
this.updateSubprocessPollingState();
}
private cleanupProcessHandles(session: TerminalSessionState): void {
@@ -621,87 +377,69 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.unsubscribeExit = null;
}
private queuePersist(threadId: string, terminalId: string, history: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
this.pendingPersistHistory.set(persistenceKey, history);
this.schedulePersist(threadId, terminalId);
private queuePersist(threadId: string, history: string): void {
this.pendingPersistHistory.set(threadId, history);
this.schedulePersist(threadId);
}
private async persistHistory(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, history);
private async persistHistory(threadId: string, history: string): Promise<void> {
this.clearPersistTimer(threadId);
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, history);
}
private enqueuePersistWrite(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
private enqueuePersistWrite(threadId: string, history: string): Promise<void> {
const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
await fs.promises.writeFile(this.historyPath(threadId), history, "utf8");
};
const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
const previous = this.persistQueues.get(threadId) ?? Promise.resolve();
const next = previous
.catch(() => undefined)
.then(task)
.catch((error) => {
this.logger.warn("failed to persist terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
});
this.persistQueues.set(persistenceKey, next);
this.persistQueues.set(threadId, next);
const finalized = next.finally(() => {
if (this.persistQueues.get(persistenceKey) === next) {
this.persistQueues.delete(persistenceKey);
if (this.persistQueues.get(threadId) === next) {
this.persistQueues.delete(threadId);
}
if (
this.pendingPersistHistory.has(persistenceKey) &&
!this.persistTimers.has(persistenceKey)
) {
this.schedulePersist(threadId, terminalId);
if (this.pendingPersistHistory.has(threadId) && !this.persistTimers.has(threadId)) {
this.schedulePersist(threadId);
}
});
void finalized.catch(() => undefined);
return finalized;
}
private schedulePersist(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
if (this.persistTimers.has(persistenceKey)) return;
private schedulePersist(threadId: string): void {
if (this.persistTimers.has(threadId)) return;
const timer = setTimeout(() => {
this.persistTimers.delete(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
this.persistTimers.delete(threadId);
const pendingHistory = this.pendingPersistHistory.get(threadId);
if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(persistenceKey);
void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
this.pendingPersistHistory.delete(threadId);
void this.enqueuePersistWrite(threadId, pendingHistory);
}, this.persistDebounceMs);
this.persistTimers.set(persistenceKey, timer);
this.persistTimers.set(threadId, timer);
}
private clearPersistTimer(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
const timer = this.persistTimers.get(persistenceKey);
private clearPersistTimer(threadId: string): void {
const timer = this.persistTimers.get(threadId);
if (!timer) return;
clearTimeout(timer);
this.persistTimers.delete(persistenceKey);
this.persistTimers.delete(threadId);
}
private async readHistory(threadId: string, terminalId: string): Promise<string> {
const nextPath = this.historyPath(threadId, terminalId);
private async readHistory(threadId: string): Promise<string> {
try {
const raw = await fs.promises.readFile(nextPath, "utf8");
const raw = await fs.promises.readFile(this.historyPath(threadId), "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(nextPath, capped, "utf8");
await fs.promises.writeFile(this.historyPath(threadId), capped, "utf8");
}
return capped;
} catch (error) {
@@ -710,26 +448,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
if (terminalId !== DEFAULT_TERMINAL_ID) {
return "";
}
const legacyPath = this.legacyHistoryPath(threadId);
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);
// Migrate legacy transcript filename to the terminal-scoped path.
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),
});
if (capped !== raw) {
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -739,34 +463,31 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
if (terminalId === DEFAULT_TERMINAL_ID) {
deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
}
private async deleteHistory(threadId: string): Promise<void> {
try {
await Promise.all(deletions);
await Promise.all([
fs.promises.rm(this.historyPath(threadId), { force: true }),
fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }),
]);
} catch (error) {
this.logger.warn("failed to delete terminal history", {
threadId,
terminalId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
private async flushPersistQueue(threadId: string): Promise<void> {
this.clearPersistTimer(threadId);
while (true) {
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(threadId);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, pendingHistory);
}
const pending = this.persistQueues.get(persistenceKey);
const pending = this.persistQueues.get(threadId);
if (!pending) {
return;
}
@@ -774,86 +495,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> {
let stats: fs.Stats;
try {
@@ -869,55 +510,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
private async closeSession(
threadId: string,
terminalId: string,
deleteHistory: boolean,
): Promise<void> {
const key = toSessionKey(threadId, terminalId);
const session = this.sessions.get(key);
if (session) {
this.stopProcess(session);
this.sessions.delete(key);
}
this.updateSubprocessPollingState();
await this.flushPersistQueue(threadId, terminalId);
if (deleteHistory) {
await this.deleteHistory(threadId, terminalId);
}
}
private sessionsForThread(threadId: string): TerminalSessionState[] {
return [...this.sessions.values()].filter((session) => session.threadId === threadId);
}
private async deleteAllHistoryForThread(threadId: string): Promise<void> {
const threadPrefix = `${toSafeThreadId(threadId)}_`;
try {
const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
const removals = entries
.filter((entry) => entry.isFile())
.map((entry) => entry.name)
.filter(
(name) =>
name === `${toSafeThreadId(threadId)}.log` ||
name === `${legacySafeThreadId(threadId)}.log` ||
name.startsWith(threadPrefix),
)
.map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
await Promise.all(removals);
} catch (error) {
this.logger.warn("failed to delete terminal histories for thread", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private requireSession(threadId: string, terminalId: string): TerminalSessionState {
const session = this.sessions.get(toSessionKey(threadId, terminalId));
private requireSession(threadId: string): TerminalSessionState {
const session = this.sessions.get(threadId);
if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
throw new Error(`Unknown terminal thread: ${threadId}`);
}
return session;
}
@@ -925,7 +521,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return {
threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd,
status: session.status,
pid: session.pid,
@@ -940,19 +535,18 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emit("event", event);
}
private historyPath(threadId: string, terminalId: string): string {
const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
return path.join(this.logsDir, `${threadPart}.log`);
}
return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
private historyPath(threadId: string): string {
return path.join(this.logsDir, `${toSafeThreadId(threadId)}.log`);
}
private legacyHistoryPath(threadId: string): string {
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();
let release: () => void = () => {};
const current = new Promise<void>((resolve) => {
+11 -124
View File
@@ -7,21 +7,14 @@ import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import {
DEFAULT_TERMINAL_ID,
WS_CHANNELS,
WS_METHODS,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry";
import type {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput,
} from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager";
@@ -36,16 +29,10 @@ const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 4242,
@@ -54,12 +41,11 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
this.sessions.set(input.threadId, snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "started",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
@@ -68,8 +54,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
}
async write(input: TerminalWriteInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const existing = this.sessions.get(this.key(input.threadId, terminalId));
const existing = this.sessions.get(input.threadId);
if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`);
}
@@ -77,22 +62,19 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
this.emit("event", {
type: "output",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
data: input.data,
});
});
}
async resize(_input: TerminalResizeInput): Promise<void> {}
async resize(_input: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {}
async clear(input: TerminalClearInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
async clear(input: TerminalThreadInput): Promise<void> {
queueMicrotask(() => {
this.emit("event", {
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
});
});
@@ -100,10 +82,8 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId,
terminalId,
cwd: input.cwd,
status: "running",
pid: 5252,
@@ -112,12 +92,11 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null,
updatedAt: now,
};
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
this.sessions.set(input.threadId, snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "restarted",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
@@ -126,15 +105,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
}
async close(input: TerminalCloseInput): Promise<void> {
if (input.terminalId) {
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
}
this.sessions.delete(input.threadId);
}
dispose(): void {}
@@ -209,10 +180,6 @@ describe("WebSocket Server", () => {
devUrl?: string;
authToken?: string;
stateDir?: string;
gitManager?: {
status: (input: { cwd: string }) => Promise<unknown>;
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
};
terminalManager?: TerminalManager;
} = {},
): ReturnType<typeof createServer> {
@@ -223,8 +190,9 @@ describe("WebSocket Server", () => {
...(options.devUrl ? { devUrl: options.devUrl } : {}),
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
...(options.terminalManager
? { terminalManager: options.terminalManager }
: {}),
});
}
@@ -367,7 +335,6 @@ describe("WebSocket Server", () => {
});
expect(open.error).toBeUndefined();
expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1");
expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID);
const write = await sendRequest(ws, WS_METHODS.terminalWrite, {
threadId: "thread-1",
@@ -404,7 +371,6 @@ describe("WebSocket Server", () => {
const manualEvent: TerminalEvent = {
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "manual test output\n",
};
@@ -543,85 +509,6 @@ describe("WebSocket Server", () => {
});
expect(afterInit.error).toBeUndefined();
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 () => {
const gitManager = {
status: vi.fn().mockResolvedValue({
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: {
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
insertions: 7,
deletions: 2,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
}),
runStackedAction: vi.fn(),
};
server = createTestServer({ cwd: "/test", gitManager });
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.gitStatus, {
cwd: "/test",
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
branch: "feature/test",
hasWorkingTreeChanges: true,
workingTree: {
files: [{ path: "src/index.ts", insertions: 7, deletions: 2 }],
insertions: 7,
deletions: 2,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
});
expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" });
});
it("returns errors from git.runStackedAction", async () => {
const gitManager = {
status: vi.fn(),
runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),
};
server = createTestServer({ cwd: "/test", gitManager });
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.gitRunStackedAction, {
cwd: "/test",
action: "commit_push",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(gitManager.runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit_push",
});
});
it("prunes missing projects on startup", async () => {
+3 -37
View File
@@ -20,14 +20,12 @@ import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { ProjectRegistry } from "./projectRegistry";
import { ProviderManager } from "./providerManager";
import { GitManager } from "./gitManager";
import {
checkoutGitBranch,
createGitBranch,
createGitWorktree,
initGitRepo,
listGitBranches,
pullGitBranch,
removeGitWorktree,
} from "./git";
import { TerminalManager } from "./terminalManager";
@@ -55,7 +53,6 @@ export interface ServerOptions {
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
@@ -77,7 +74,6 @@ export function createServer(options: ServerOptions) {
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
} = options;
@@ -85,7 +81,6 @@ export function createServer(options: ServerOptions) {
const terminalManager = providedTerminalManager ?? new TerminalManager();
const projectRegistry =
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
const gitManager = providedGitManager ?? new GitManager();
const clients = new Set<WebSocket>();
const logger = createLogger("ws");
const logWebSocketEvents =
@@ -325,32 +320,11 @@ export function createServer(options: ServerOptions) {
if (!params?.cwd) throw new Error("cwd is required");
const editorDef = EDITORS.find((e) => e.id === params.editor);
if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`);
let command: string;
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 {
if (!editorDef.command) {
// Can't open file manager programmatically from server, just succeed silently
return undefined;
}
const child = spawn(command, args, {
const child = spawn(editorDef.command, [params.cwd], {
detached: true,
stdio: "ignore",
});
@@ -361,14 +335,6 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.gitStatus:
return gitManager.status(request.params as never);
case WS_METHODS.gitPull:
return pullGitBranch(request.params as never);
case WS_METHODS.gitRunStackedAction:
return gitManager.runStackedAction(request.params as never);
case WS_METHODS.gitListBranches:
return listGitBranches(request.params as never);
-27
View File
@@ -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"
}
}
+3 -6
View File
@@ -11,20 +11,17 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.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",
"lucide-react": "^0.564.0",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"rehype-highlight": "^7.0.2",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zod": "^3.24.1"
},
"devDependencies": {
+14 -32
View File
@@ -1,44 +1,40 @@
import { QueryClient, QueryClientProvider, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useMemo, useRef } from "react";
import ChatView from "./components/ChatView";
import DiffPanel from "./components/DiffPanel";
import Sidebar from "./components/Sidebar";
import { isElectron } from "./env";
import { DEFAULT_MODEL } from "./model-logic";
import { readNativeApi } from "./session-logic";
import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi";
import { AnchoredToastProvider, ToastProvider } from "./components/ui/toast";
import { invalidateGitQueries } from "./lib/gitReactQuery";
function EventRouter() {
const api = useNativeApi();
const api = useMemo(() => readNativeApi(), []);
const { dispatch } = useStore();
const queryClient = useQueryClient();
const activeAssistantItemRef = useRef<string | null>(null);
useEffect(() => {
if (!api) return;
return api.providers.onEvent((event) => {
if (event.method === "turn/completed") {
void invalidateGitQueries(queryClient);
}
dispatch({
type: "APPLY_EVENT",
event,
activeAssistantItemRef,
});
});
}, [api, dispatch, queryClient]);
}, [api, dispatch]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
if (event.type !== "exited") return;
dispatch({
type: "APPLY_TERMINAL_EVENT",
event,
type: "SET_THREAD_TERMINAL_OPEN",
threadId: event.threadId,
open: false,
});
});
}, [api, dispatch]);
@@ -97,16 +93,6 @@ function AutoProjectBootstrap() {
model: DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
@@ -123,7 +109,7 @@ function AutoProjectBootstrap() {
}
function DesktopProjectBootstrap() {
const api = useNativeApi();
const api = useMemo(() => readNativeApi(), []);
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
@@ -173,7 +159,7 @@ function DesktopProjectBootstrap() {
}
function Layout() {
const api = useNativeApi();
const api = useMemo(() => readNativeApi(), []);
const { state } = useStore();
if (!api) {
@@ -187,7 +173,7 @@ function Layout() {
}
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 />
<AutoProjectBootstrap />
<DesktopProjectBootstrap />
@@ -204,11 +190,7 @@ export default function App() {
return (
<QueryClientProvider client={queryClient}>
<StoreProvider>
<ToastProvider>
<AnchoredToastProvider>
<Layout />
</AnchoredToastProvider>
</ToastProvider>
<Layout />
</StoreProvider>
</QueryClientProvider>
);
+180 -141
View File
@@ -1,86 +1,75 @@
import type { GitBranch } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useNativeApi } from "../hooks/useNativeApi";
import {
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import { Button } from "./ui/button";
import {
Combobox,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxPopup,
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
interface BranchToolbarProps {
envMode: "local" | "worktree";
onEnvModeChange: (mode: "local" | "worktree") => void;
envLocked: boolean;
onComposerFocusRequest?: () => void;
}
export default function BranchToolbar({
envMode,
onEnvModeChange,
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useNativeApi();
const api = useMemo(() => readNativeApi(), []);
const queryClient = useQueryClient();
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 activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd;
// ── 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 branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
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;
// Default to true while loading — showing "Initialize git" during a fetch is wrong,
// and worktrees are inherently git repos.
const isRepo = branchesQuery.data?.isRepo ?? !branchesQuery.isLoading;
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation({
...gitCheckoutMutationOptions({ api, cwd: branchCwd, queryClient }),
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
setIsBranchMenuOpen(true);
},
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({
...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 ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
@@ -99,8 +88,17 @@ export default function BranchToolbar({
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
setBranchQuery("");
if (!isBranchMenuOpen) return;
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]);
// ── Helpers ───────────────────────────────────────────────────────────
@@ -129,7 +127,6 @@ export default function BranchToolbar({
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -142,7 +139,6 @@ export default function BranchToolbar({
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
@@ -151,21 +147,20 @@ export default function BranchToolbar({
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
const createBranch = () => {
const name = newBranchName.trim();
if (!api || !activeThreadId || !branchCwd || !name) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setNewBranchName("");
setIsCreatingBranch(false);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
});
};
@@ -176,101 +171,145 @@ 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="flex items-center gap-2">
{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"}
</span>
) : (
<Button
<button
type="button"
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
className={`inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-[12px] transition-colors duration-150 ${
envMode === "worktree"
? "bg-accent text-foreground/80"
: "text-muted-foreground/60 hover:bg-accent/50 hover:text-muted-foreground/80"
}`}
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
>
{envMode === "worktree" ? "New worktree" : "Local"}
</Button>
</button>
)}
</div>
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={activeThread.branch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading}
{!isRepo ? (
<button
type="button"
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"
disabled={!branchCwd || initMutation.isPending}
onClick={() => initMutation.mutate()}
>
<span className="max-w-[240px] truncate">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<ChevronDownIcon />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-64">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxList className="max-h-56">
{(itemValue) => {
if (createBranchItemValue && itemValue === createBranchItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
>
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</div>
</ComboboxItem>
);
}}
</ComboboxList>
</ComboboxPopup>
</Combobox>
{initMutation.isPending ? "Initializing\u2026" : "Initialize git"}
</button>
) : (
<div className="relative" ref={branchMenuRef}>
<button
type="button"
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"
onClick={() => setIsBranchMenuOpen((open) => !open)}
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate font-mono">
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<svg
width="10"
height="10"
viewBox="0 0 10 10"
fill="none"
className="opacity-40"
aria-hidden="true"
>
<path
d="M2.5 4L5 6.5L7.5 4"
stroke="currentColor"
strokeWidth="1.2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</button>
{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
</p>
<div className="max-h-64 overflow-y-auto">
{branches.map((branch) => {
const isSelected = branch.name === activeThread.branch;
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
return (
<button
key={branch.name}
type="button"
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 ${
isSelected
? "bg-accent text-foreground"
: "text-foreground/90 hover:bg-accent/50"
}`}
onClick={() => selectBranch(branch)}
>
<span className="truncate">{branch.name}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</button>
);
})}
</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>
);
}
File diff suppressed because it is too large. Load diff
+5 -8
View File
@@ -1,7 +1,5 @@
import { XIcon } from "lucide-react";
import { isElectron } from "../env";
import { useStore } from "../store";
import { Button } from "./ui/button";
export default function DiffPanel() {
const { dispatch } = useStore();
@@ -10,17 +8,16 @@ export default function DiffPanel() {
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
{/* Header */}
<div
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
className={`flex items-center justify-between border-b border-border px-4 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<Button
<button
type="button"
size="icon-xs"
variant="ghost"
className="text-muted-foreground/60 transition-colors duration-150 hover:text-muted-foreground"
onClick={() => dispatch({ type: "TOGGLE_DIFF" })}
>
<XIcon />
</Button>
<span className="text-sm">&times;</span>
</button>
</div>
{/* Placeholder content */}
@@ -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";
}
@@ -1,734 +0,0 @@
import { type GitStatusResult, type GitStackedAction, type NativeApi } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
import { GitHubIcon } from "./Icons";
import {
buildGitActionProgressStages,
buildMenuItems,
type GitActionIconName,
type GitActionMenuItem,
type GitDialogAction,
type GitQuickAction,
requiresDefaultBranchConfirmation,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
import { Button } from "~/components/ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "~/components/ui/dialog";
import { Group, GroupSeparator } from "~/components/ui/group";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { ScrollArea } from "~/components/ui/scroll-area";
import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitInitMutationOptions,
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { useStore } from "~/store";
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
}
function getMenuActionDisabledReason(
item: GitActionMenuItem,
gitStatus: GitStatusResult | null,
isBusy: boolean,
): string | null {
if (!item.disabled) return null;
if (isBusy) return "Git action in progress.";
if (!gitStatus) return "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;
if (item.id === "commit") {
if (!hasChanges) {
return "Worktree is clean. Make changes before committing.";
}
return "Commit is currently unavailable.";
}
if (item.id === "push") {
if (!hasBranch) {
return "Detached HEAD: checkout a branch before pushing.";
}
if (hasChanges) {
return "Commit or stash local changes before pushing.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before pushing.";
}
if (!isAhead) {
return "No local commits to push.";
}
return "Push is currently unavailable.";
}
if (hasOpenPr) {
return "Open PR is currently unavailable.";
}
if (!hasBranch) {
return "Detached HEAD: checkout a branch before creating a PR.";
}
if (hasChanges) {
return "Commit local changes before creating a PR.";
}
if (!isAhead) {
return "No local commits to include in a PR.";
}
if (!gitStatus.hasUpstream) {
return "Set an upstream branch before creating a PR.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before creating a PR.";
}
return "Create PR is currently unavailable.";
}
const DIALOG_TITLE_BY_ACTION = {
commit: "Commit changes",
push: "Push branch",
create_pr: "Create pull request",
};
const DIALOG_DESCRIPTION_BY_ACTION = {
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
push: "Push this branch now.",
create_pr: "Create a pull request using generated title/body content.",
};
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
if (icon === "commit") return <GitCommitIcon />;
if (icon === "push") return <CloudUploadIcon />;
return <GitHubIcon />;
}
function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
const iconClassName = "size-3.5";
if (quickAction.kind === "open_pr") return <GitHubIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "commit_push") return <CloudUploadIcon className={iconClassName} />;
return <GitHubIcon className={iconClassName} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
return <InfoIcon className={iconClassName} />;
}
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const { state } = useStore();
const activeThreadId = state.activeThreadId;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const queryClient = useQueryClient();
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(api, gitCwd));
// Default to true while loading so we don't flash init controls.
const isRepo = branchList?.isRepo ?? true;
const currentBranch = branchList?.branches.find((branch) => branch.current)?.name ?? null;
const isGitStatusOutOfSync =
!!gitStatus?.branch && !!currentBranch && gitStatus.branch !== currentBranch;
useEffect(() => {
if (!isGitStatusOutOfSync) return;
void invalidateGitQueries(queryClient);
}, [isGitStatusOutOfSync, queryClient]);
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
const initMutation = useMutation(gitInitMutationOptions({ api, cwd: gitCwd, queryClient }));
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ api, cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ api, cwd: gitCwd, queryClient }));
const isGitActionRunning = runImmediateGitActionMutation.isPending || pullMutation.isPending;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
const current = branchList?.branches.find((branch) => branch.name === branchName);
return current?.isDefault ?? (branchName === "main" || branchName === "master");
}, [branchList?.branches, gitStatusForActions?.branch]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning),
[gitStatusForActions, isGitActionRunning],
);
const quickAction = useMemo(
() => resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch),
[gitStatusForActions, isDefaultBranch, isGitActionRunning],
);
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[api, gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
data: threadToastData,
});
return;
}
const prUrl = gitStatusForActions?.openPr?.url ?? null;
if (!prUrl) {
toastManager.add({
type: "error",
title: "No open PR found.",
data: threadToastData,
});
return;
}
const promise = api.shell.openExternal(prUrl);
toastManager.promise(promise, {
loading: { title: "Opening PR...", data: threadToastData },
success: { title: "PR opened", data: threadToastData },
error: (err) => ({
title: "Unable to open PR link",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
}, [api, gitStatusForActions?.openPr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const confirmed = await maybeConfirmPushToDefaultBranch(action);
if (!confirmed) return;
onConfirmed?.();
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
const progressToastId = toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(progressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
data: threadToastData,
});
}, 1100);
const stopProgressUpdates = () => {
clearInterval(stageInterval);
};
const promise = runImmediateGitActionMutation.mutateAsync({
action,
...(commitMessage ? { commitMessage } : {}),
});
try {
const result = await promise;
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
const shouldOfferCreatePrCta =
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
const closeResultToast = () => {
toastManager.close(progressToastId);
};
toastManager.update(progressToastId, {
type: "success",
title: resultToast.title,
description: resultToast.description,
timeout: 0,
data: threadToastData,
...(shouldOfferPushCta
? {
actionProps: {
children: "Push",
onClick: () => {
void runGitActionWithToast({
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
});
},
},
}
: shouldOfferOpenPrCta
? {
actionProps: {
children: "Open PR",
onClick: () => {
closeResultToast();
void api?.shell.openExternal(prUrl);
},
},
}
: shouldOfferCreatePrCta
? {
actionProps: {
children: "Create PR",
onClick: () => {
closeResultToast();
setActiveDialogAction("create_pr");
},
},
}
: {}),
});
} catch (err) {
stopProgressUpdates();
toastManager.update(progressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
});
}
},
[
api,
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.openPr?.url,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setActiveDialogAction,
threadToastData,
],
);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
return;
}
if (quickAction.kind === "run_pull") {
const promise = pullMutation.mutateAsync();
toastManager.promise(promise, {
loading: { title: "Pulling...", data: threadToastData },
success: (result) => ({
title: result.status === "pulled" ? "Pulled" : "Already up to date",
description:
result.status === "pulled"
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
: `${result.branch} is already synchronized.`,
data: threadToastData,
}),
error: (err) => ({
title: "Pull failed",
description: err instanceof Error ? err.message : "An error occurred.",
data: threadToastData,
}),
});
void promise.catch(() => undefined);
return;
}
if (quickAction.kind === "show_hint") {
toastManager.add({
type: "info",
title: quickAction.label,
description: quickAction.hint,
data: threadToastData,
});
return;
}
if (quickAction.action) {
void runGitActionWithToast({ action: quickAction.action });
}
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
const openDialogForMenuItem = useCallback(
(item: GitActionMenuItem) => {
if (item.disabled) return;
if (item.kind === "open_pr") {
void openExistingPr();
return;
}
if (item.dialogAction === "push") {
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction) {
setActiveDialogAction(item.dialogAction);
}
},
[openExistingPr, runGitActionWithToast],
);
const runDialogAction = useCallback(() => {
if (!activeDialogAction) return;
const action: GitStackedAction =
activeDialogAction === "commit"
? "commit"
: activeDialogAction === "push"
? "commit_push"
: "commit_push_pr";
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
const forcePushOnlyProgress = activeDialogAction === "push";
setActiveDialogAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
});
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
const openChangedFileInEditor = useCallback(
(filePath: string) => {
if (!api || !gitCwd) {
toastManager.add({
type: "error",
title: "Editor opening is unavailable.",
data: threadToastData,
});
return;
}
const target = resolvePathLinkTarget(filePath, gitCwd);
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open file",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[api, gitCwd, threadToastData],
);
if (!gitCwd) return null;
return (
<>
{!isRepo ? (
<Button
variant="outline"
size="xs"
disabled={initMutation.isPending}
onClick={() => initMutation.mutate()}
>
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
</Button>
) : (
<Group aria-label="Git actions">
{quickActionDisabledReason ? (
<Popover>
<PopoverTrigger
openOnHover
render={
<Button
aria-disabled="true"
className="cursor-not-allowed rounded-e-none border-e-0 opacity-64 before:rounded-e-none"
size="xs"
variant="outline"
/>
}
>
<GitQuickActionIcon quickAction={quickAction} />
<span className="ml-0.5">{quickAction.label}</span>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="start">
{quickActionDisabledReason}
</PopoverPopup>
</Popover>
) : (
<Button
variant="outline"
size="xs"
disabled={isGitActionRunning || quickAction.disabled}
onClick={runQuickAction}
>
<GitQuickActionIcon quickAction={quickAction} />
<span className="ml-0.5">{quickAction.label}</span>
</Button>
)}
<GroupSeparator />
<Menu
onOpenChange={(open) => {
if (open) void invalidateGitQueries(queryClient);
}}
>
<MenuTrigger
render={<Button aria-label="Git action options" size="icon-xs" variant="outline" />}
disabled={isGitActionRunning}
>
<ChevronDownIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end" className="w-full">
{gitActionMenuItems.map((item) => {
const disabledReason = getMenuActionDisabledReason(
item,
gitStatusForActions,
isGitActionRunning,
);
if (item.disabled && disabledReason) {
return (
<Popover key={`${item.id}-${item.label}`}>
<PopoverTrigger
openOnHover
nativeButton={false}
render={<span className="block w-max cursor-not-allowed" />}
>
<MenuItem className="w-full" disabled>
<GitActionItemIcon icon={item.icon} />
{item.label}
</MenuItem>
</PopoverTrigger>
<PopoverPopup tooltipStyle side="left" align="center">
{disabledReason}
</PopoverPopup>
</Popover>
);
}
return (
<MenuItem
key={`${item.id}-${item.label}`}
disabled={item.disabled}
onClick={() => {
openDialogForMenuItem(item);
}}
>
<GitActionItemIcon icon={item.icon} />
{item.label}
</MenuItem>
);
})}
{gitStatusForActions?.branch === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and checkout a branch to enable push and PR actions.
</p>
)}
{gitStatusForActions &&
gitStatusForActions.branch !== null &&
!gitStatusForActions.hasWorkingTreeChanges &&
gitStatusForActions.behindCount > 0 &&
gitStatusForActions.aheadCount === 0 && (
<p className="px-2 py-1.5 text-xs text-warning">
Behind upstream. Pull/rebase first.
</p>
)}
{isGitStatusOutOfSync && (
<p className="px-2 py-1.5 text-xs text-muted-foreground">
Refreshing git status...
</p>
)}
{gitStatusError && (
<p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError.message}</p>
)}
</MenuPopup>
</Menu>
</Group>
)}
<Dialog
open={activeDialogAction !== null}
onOpenChange={(open) => {
if (!open) {
setActiveDialogAction(null);
setDialogCommitMessage("");
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
<DialogDescription>
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 && gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
</span>
</>
)}
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
{!gitStatusForActions || gitStatusForActions.workingTree.files.length === 0 ? (
<p className="font-medium">none</p>
) : (
<div className="space-y-2">
<ScrollArea className="h-44 rounded-md border border-input bg-background">
<div className="space-y-1 p-1">
{gitStatusForActions.workingTree.files.map((file) => (
<button
type="button"
key={file.path}
className="flex w-full items-center justify-between gap-3 rounded-md px-2 py-1 font-mono text-left transition-colors hover:bg-accent/50"
onClick={() => openChangedFileInEditor(file.path)}
>
<span className="truncate">{file.path}</span>
<span className="shrink-0">
<span className="text-success">+{file.insertions}</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">-{file.deletions}</span>
</span>
</button>
))}
</div>
</ScrollArea>
<div className="flex justify-end font-mono">
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</div>
</div>
)}
</div>
</div>
{activeDialogAction === "commit" && (
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
)}
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
size="sm"
onClick={() => {
setActiveDialogAction(null);
setDialogCommitMessage("");
}}
>
Cancel
</Button>
<Button size="sm" onClick={runDialogAction}>
{activeDialogAction === "commit"
? "Commit"
: activeDialogAction === "push"
? "Push"
: "Create PR"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
</>
);
}
-21
View File
@@ -1,21 +0,0 @@
import type { SVGProps } from "react";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
export const GitHubIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 1024 1024" fill="none">
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
transform="scale(64)"
fill="currentColor"
/>
</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>
);
+33 -168
View File
@@ -1,20 +1,11 @@
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project } from "../types";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -34,98 +25,22 @@ function inferProjectName(cwd: string): string {
return last && last.length > 0 ? last : "project";
}
interface ThreadStatusPill {
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
colorClass: string;
dotClass: string;
pulse: boolean;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
pulse: boolean;
}
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurnCompletedAt) return false;
const completedAt = Date.parse(thread.latestTurnCompletedAt);
if (Number.isNaN(completedAt)) return false;
if (!thread.lastVisitedAt) return true;
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAt)) return true;
return completedAt > lastVisitedAt;
}
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
if (hasPendingApprovals) {
return {
label: "Awaiting response",
colorClass: "text-amber-600 dark:text-amber-300/90",
dotClass: "bg-amber-500 dark:bg-amber-300/90",
pulse: false,
};
}
if (thread.session?.status === "running") {
return {
label: "Working",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (thread.session?.status === "connecting") {
return {
label: "Connecting",
colorClass: "text-sky-600 dark:text-sky-300/80",
dotClass: "bg-sky-500 dark:bg-sky-300/80",
pulse: true,
};
}
if (hasUnseenCompletion(thread)) {
return {
label: "Completed",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
pulse: false,
};
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
if (status === "running") return "Working";
if (status === "connecting") return "Connecting";
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() {
const { state, dispatch } = useStore();
const api = useNativeApi();
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ api, queryClient }));
const api = useMemo(() => readNativeApi(), []);
const { theme, setTheme } = useTheme();
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<string, boolean>();
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
}
return map;
}, [state.threads]);
const handleNewThread = useCallback(
(projectId: string) => {
@@ -139,16 +54,6 @@ export default function Sidebar() {
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
@@ -267,22 +172,6 @@ export default function Sidebar() {
const thread = state.threads.find((t) => t.id === threadId);
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
if (thread.session?.sessionId) {
@@ -305,21 +194,8 @@ export default function Sidebar() {
}
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],
);
useEffect(() => {
@@ -332,6 +208,19 @@ export default function Sidebar() {
event.key.toLowerCase() === "o";
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;
}
}
const activeThread = state.threads.find((t) => t.id === state.activeThreadId);
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
@@ -348,10 +237,10 @@ export default function Sidebar() {
return (
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
{/* Drag region / traffic light space (Electron only) */}
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
{/* Branding */}
<div
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
>
<div className={`flex items-center gap-2.5 px-4 pb-4 ${isElectron ? "" : "pt-4"}`}>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
@@ -423,11 +312,7 @@ export default function Sidebar() {
<div className="ml-2 border-l border-border/80 pl-2">
{threads.map((thread) => {
const isActive = state.activeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const terminalStatus = terminalStatusIndicator(thread);
const threadStatus = threadStatusLabel(thread.session?.status);
return (
<button
key={thread.id}
@@ -453,36 +338,16 @@ export default function Sidebar() {
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
<span className="hidden xl:inline">{threadStatus}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<div className="ml-2 flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<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>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
</button>
);
})}
+176 -601
View File
@@ -1,40 +1,31 @@
import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import {
extractTerminalLinks,
isTerminalLinkActivation,
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../terminal-shortcuts";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type ThreadTerminalGroup,
} from "../types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "../types";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
function maxDrawerHeight(): number {
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 {
const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
const safeHeight = Number.isFinite(height)
? height
: DEFAULT_THREAD_TERMINAL_HEIGHT;
const maxHeight = maxDrawerHeight();
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
}
@@ -48,7 +39,8 @@ function terminalThemeFromApp(): ITheme {
const bodyStyles = getComputedStyle(document.body);
const background =
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) {
return {
@@ -105,30 +97,162 @@ function terminalThemeFromApp(): ITheme {
};
}
interface TerminalViewportProps {
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
terminalId: string;
cwd: string;
height: number;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
drawerHeight: number;
onHeightChange: (height: number) => void;
onThreadExited: () => void;
}
function TerminalViewport({
export default function ThreadTerminalDrawer({
api,
threadId,
terminalId,
cwd,
height,
focusRequestId,
autoFocus,
resizeEpoch,
drawerHeight,
}: TerminalViewportProps) {
onHeightChange,
onThreadExited,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const onThreadExitedRef = useRef(onThreadExited);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
onThreadExitedRef.current = onThreadExited;
}, [onThreadExited]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback(
(nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
},
[],
);
const fitAndResizeTerminal = useCallback((preserveBottom = false) => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
preserveBottom &&
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, [api, threadId]);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
},
[],
);
const handleResizePointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
},
[],
);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
fitAndResizeTerminal(true);
},
[fitAndResizeTerminal, syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
} else {
fitAndResizeTerminal(true);
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [fitAndResizeTerminal, syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
useEffect(() => {
const mount = containerRef.current;
@@ -142,7 +266,8 @@ function TerminalViewport({
lineHeight: 1.2,
fontSize: 12,
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(),
});
terminal.loadAddon(fitAddon);
@@ -156,7 +281,7 @@ function TerminalViewport({
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
await api.terminal.write({ threadId, data: "\u000c" });
} catch (error) {
writeSystemMessage(
activeTerminal,
@@ -173,70 +298,9 @@ function TerminalViewport({
return false;
});
const terminalLinksDisposable = terminal.registerLinkProvider({
provideLinks: (bufferLineNumber, callback) => {
const activeTerminal = terminalRef.current;
if (!activeTerminal) {
callback(undefined);
return;
}
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
if (!line) {
callback(undefined);
return;
}
const lineText = line.translateToString(true);
const matches = extractTerminalLinks(lineText);
if (matches.length === 0) {
callback(undefined);
return;
}
callback(
matches.map((match) => ({
text: match.text,
range: {
start: { x: match.start + 1, y: bufferLineNumber },
end: { x: match.end, y: bufferLineNumber },
},
activate: (event: MouseEvent) => {
if (!isTerminalLinkActivation(event)) {
return;
}
const latestTerminal = terminalRef.current;
if (!latestTerminal) {
return;
}
if (match.kind === "url") {
void api.shell.openExternal(match.text).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open link",
);
});
return;
}
const target = resolvePathLinkTarget(match.text, cwd);
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
writeSystemMessage(
latestTerminal,
error instanceof Error ? error.message : "Unable to open path",
);
});
},
})),
);
},
});
const inputDisposable = terminal.onData((data) => {
void api.terminal
.write({ threadId, terminalId, data })
.write({ threadId, data })
.catch((err) =>
writeSystemMessage(
terminal,
@@ -264,7 +328,6 @@ function TerminalViewport({
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
@@ -274,11 +337,9 @@ function TerminalViewport({
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
} catch (err) {
if (disposed) return;
writeSystemMessage(
@@ -289,7 +350,7 @@ function TerminalViewport({
};
const unsubscribe = api.terminal.onEvent((event) => {
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
if (event.threadId !== threadId) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -318,37 +379,12 @@ function TerminalViewport({
}
if (event.type === "exited") {
const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
onThreadExitedRef.current();
}
});
const fitTimer = window.setTimeout(() => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
fitAndResizeTerminal(true);
}, 30);
void openTerminal();
@@ -357,16 +393,14 @@ function TerminalViewport({
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
terminalLinksDisposable.dispose();
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
}, [api, cwd, fitAndResizeTerminal, threadId]);
useEffect(() => {
if (!autoFocus) return;
const terminal = terminalRef.current;
if (!terminal) return;
const frame = window.requestAnimationFrame(() => {
@@ -375,7 +409,7 @@ function TerminalViewport({
return () => {
window.cancelAnimationFrame(frame);
};
}, [autoFocus, focusRequestId]);
}, [focusRequestId]);
useEffect(() => {
const terminal = terminalRef.current;
@@ -390,7 +424,6 @@ function TerminalViewport({
void api.terminal
.resize({
threadId,
terminalId,
cols: terminal.cols,
rows: terminal.rows,
})
@@ -399,485 +432,27 @@ function TerminalViewport({
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
height: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => 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({
api,
threadId,
cwd,
height,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
focusRequestId,
onSplitTerminal,
onNewTerminal,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
const normalizedTerminalIds = useMemo(() => {
const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
}, [terminalIds]);
const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
? activeTerminalId
: (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const resolvedTerminalGroups = useMemo(() => {
const validTerminalIdSet = new Set(normalizedTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
nextGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
for (const terminalId of normalizedTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
if (nextGroups.length > 0) {
return nextGroups;
}
return [
{
id: `group-${resolvedActiveTerminalId}`,
terminalIds: [resolvedActiveTerminalId],
},
];
}, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
const resolvedActiveGroupIndex = useMemo(() => {
const indexById = resolvedTerminalGroups.findIndex(
(terminalGroup) => terminalGroup.id === activeTerminalGroupId,
);
if (indexById >= 0) return indexById;
const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
);
return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
resolvedActiveTerminalId,
];
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const terminalLabelById = useMemo(
() =>
new Map(
normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
),
[normalizedTerminalIds],
);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback((nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
}, []);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
}, []);
const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
}, []);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
setResizeEpoch((value) => value + 1);
},
[syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
setResizeEpoch((value) => value + 1);
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
}, [api, cwd, drawerHeight, threadId]);
return (
<aside
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
className="thread-terminal-drawer flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
className="flex h-2 cursor-row-resize items-center justify-center"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
/>
{!hasTerminalSidebar && (
<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">
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
label="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
label="New Terminal"
>
<Plus className="size-3.25" />
</TerminalActionButton>
<div className="h-4 w-px bg-border/80" />
<TerminalActionButton
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
</div>
</div>
)}
<div className="min-h-0 w-full flex-1">
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full gap-0 overflow-x-auto"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
}}
>
{visibleTerminalIds.map((terminalId) => (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
api={api}
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
</div>
))}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
api={api}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
)}
</div>
{hasTerminalSidebar && (
<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="inline-flex h-full items-stretch">
<TerminalActionButton
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
label="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
label="New Terminal"
>
<Plus className="size-3.25" />
</TerminalActionButton>
<TerminalActionButton
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
label="Close Terminal"
>
<Trash2 className="size-3.25" />
</TerminalActionButton>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive =
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
return (
<div key={terminalGroup.id} className="pb-0.5">
{showGroupHeaders && (
<button
type="button"
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
isGroupActive
? "bg-accent/70 text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
>
{terminalGroup.terminalIds.length > 1
? `Split ${groupIndex + 1}`
: `Terminal ${groupIndex + 1}`}
</button>
)}
<div
className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
return (
<div
key={terminalId}
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
>
{showGroupHeaders && (
<span className="text-[10px] text-muted-foreground/80">└</span>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1 text-left"
onClick={() => onActiveTerminalChange(terminalId)}
>
<TerminalSquare className="size-3 shrink-0" />
<span className="truncate">
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
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"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
)}
</div>
>
<div className="h-px w-10 rounded-full bg-border/80" />
</div>
<div className="min-h-0 w-full flex-1 px-1.5 pb-1">
<div
ref={containerRef}
className="h-full w-full overflow-hidden rounded-[4px]"
/>
</div>
</aside>
);
-141
View File
@@ -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,
};
-72
View File
@@ -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 };
-271
View File
@@ -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,
};
-56
View File
@@ -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 };
-74
View File
@@ -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 };
-196
View File
@@ -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,
};
-60
View File
@@ -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 };
-380
View File
@@ -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,
};
-221
View File
@@ -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,
};
-181
View File
@@ -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,
};
-114
View File
@@ -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 };
-59
View File
@@ -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 };
-26
View File
@@ -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 };
-17
View File
@@ -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 };
-93
View File
@@ -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 };
-62
View File
@@ -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 };
-28
View File
@@ -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 };
-24
View File
@@ -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 };
-310
View File
@@ -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,
};
-108
View File
@@ -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 };
-234
View File
@@ -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,
};
-19
View File
@@ -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 };
-197
View File
@@ -1,197 +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,
side = "right",
variant = "default",
...props
}: SheetPrimitive.Popup.Props & {
showCloseButton?: boolean;
side?: "right" | "left" | "top" | "bottom";
variant?: "default" | "inset";
}) {
return (
<SheetPortal>
<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,
};
-16
View File
@@ -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 };
-15
View File
@@ -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 };
-27
View File
@@ -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 };
-45
View File
@@ -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 };
-274
View File
@@ -1,274 +0,0 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import {
CircleAlertIcon,
CircleCheckIcon,
InfoIcon,
LoaderCircleIcon,
TriangleAlertIcon,
} from "lucide-react";
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useStore } from "~/store";
type ThreadToastData = {
threadId?: string | null;
tooltipStyle?: boolean;
};
const toastManager = Toast.createToastManager<ThreadToastData>();
const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
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 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");
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"
>
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
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-ending-style:opacity-0",
// Ending animations (direction-aware)
"data-ending-style:not-data-limited:not-data-swipe-direction:transform-[translateY(calc(100%+var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
// Ending animations (expanded)
"data-expanded:data-ending-style:data-[swipe-direction=left]:transform-[translateX(calc(var(--toast-swipe-movement-x)-100%-var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+100%+var(--toast-inset)))_translateY(var(--toast-calc-offset-y))]",
"data-expanded:data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-100%-var(--toast-inset)))]",
"data-expanded:data-ending-style:data-[swipe-direction=down]:transform-[translateY(calc(var(--toast-swipe-movement-y)+100%+var(--toast-inset)))]",
)}
data-position={position}
key={toast.id}
swipeDirection={
position.includes("center")
? [isTop ? "up" : "down"]
: position.includes("left")
? ["left", isTop ? "up" : "down"]
: ["right", isTop ? "up" : "down"]
}
toast={toast}
>
<Toast.Content className="pointer-events-auto flex items-center justify-between gap-1.5 overflow-hidden px-3.5 py-3 text-sm transition-opacity duration-250 data-behind:not-data-expanded:pointer-events-none data-behind:opacity-0 data-expanded:opacity-100">
<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,
};
-28
View File
@@ -91,32 +91,4 @@ describe("buildBootstrapInput", () => {
expect(result.omittedCount).toBe(1);
expect(result.truncated).toBe(true);
});
it("captures user image attachment context in transcript blocks", () => {
const result = buildBootstrapInput(
[
{
id: "u-image",
role: "user",
text: "",
attachments: [
{
type: "image",
id: "img-1",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 2_048,
},
],
createdAt: "2026-02-09T00:00:00.000Z",
streaming: false,
},
],
"What does this error mean?",
1_500,
);
expect(result.text).toContain("Attached image");
expect(result.text).toContain("screenshot.png");
});
});
+3 -29
View File
@@ -18,34 +18,8 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function buildMessageBlock(message: ChatMessage): string {
const text = message.text;
const attachments = attachmentSummary(message);
if (text && attachments) {
return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;
}
if (text) {
return `${messageRoleLabel(message)}:\n${text}`;
}
if (attachments) {
return `${messageRoleLabel(message)}:\n${attachments}`;
}
return `${messageRoleLabel(message)}:\n(empty message)`;
return `${messageRoleLabel(message)}:\n${message.text}`;
}
function finalizeWithPrompt(
@@ -94,7 +68,7 @@ export function buildBootstrapInput(
let includedNewestFirst: string[] = [];
for (const block of newestFirstBlocks) {
const nextNewestFirst = [...includedNewestFirst, block];
const nextChronological = nextNewestFirst.toReversed();
const nextChronological = [...nextNewestFirst].reverse();
const omittedCount = newestFirstBlocks.length - nextChronological.length;
const transcriptBody =
omittedCount > 0
@@ -106,7 +80,7 @@ export function buildBootstrapInput(
includedNewestFirst = nextNewestFirst;
}
let includedChronological = includedNewestFirst.toReversed();
let includedChronological = [...includedNewestFirst].reverse();
while (true) {
const omittedCount = newestFirstBlocks.length - includedChronological.length;
const transcriptBody =
-6
View File
@@ -1,6 +0,0 @@
import { useMemo } from "react";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
}
+41 -2
View File
@@ -11,6 +11,19 @@
--color-info-foreground: var(--info-foreground);
--color-info: var(--info);
--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-input: var(--input);
--color-border: var(--border);
@@ -48,7 +61,7 @@
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground relative;
@apply bg-background text-foreground;
}
}
@@ -76,12 +89,25 @@
--secondary-foreground: var(--color-neutral-800);
--muted: --alpha(var(--color-black) / 4%);
--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);
--destructive: var(--color-red-500);
--border: --alpha(var(--color-black) / 8%);
--input: --alpha(var(--color-black) / 10%);
--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);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
@@ -110,6 +136,19 @@
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--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);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
-173
View File
@@ -1,173 +0,0 @@
import type { GitStackedAction, NativeApi } from "@t3tools/contracts";
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
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,
});
}
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,
});
}
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);
},
});
}
-6
View File
@@ -1,6 +0,0 @@
import { type CxOptions, cx } from "class-variance-authority";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: CxOptions) {
return twMerge(cx(inputs));
}
+1 -2
View File
@@ -6,5 +6,4 @@ export {
} from "@t3tools/contracts";
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
export type ReasoningEffort = (typeof REASONING_OPTIONS)[number];
export const DEFAULT_REASONING: ReasoningEffort = "high";
export const DEFAULT_REASONING = "high";
+5 -124
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
@@ -50,12 +50,6 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -98,12 +92,6 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -129,7 +117,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from legacy v6 payload", () => {
it("hydrates terminal fields from v6 payload", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
@@ -151,13 +139,8 @@ describe("hydratePersistedState", () => {
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalLayout: "tabs",
splitTerminalIds: [],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:01:00.000Z",
},
],
activeThreadId: "t-1",
@@ -166,58 +149,6 @@ describe("hydratePersistedState", () => {
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
});
it("hydrates legacy split layout into a grouped split", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalLayout: "split",
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("defaults terminalHeight when hydrating v5 payloads", () => {
@@ -250,17 +181,11 @@ describe("hydratePersistedState", () => {
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
});
describe("toPersistedState", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
it("writes v6 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
@@ -269,30 +194,12 @@ describe("toPersistedState", () => {
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
session: null,
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
previewUrl: "blob:preview-1",
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
@@ -300,7 +207,6 @@ describe("toPersistedState", () => {
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02:00.000Z",
branch: null,
worktreePath: null,
};
@@ -320,7 +226,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access",
});
expect(persisted.version).toBe(7);
expect(persisted.version).toBe(6);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
@@ -330,33 +236,8 @@ describe("toPersistedState", () => {
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
messages: [
{
id: "m-1",
role: "user",
text: "Hi",
attachments: [
{
type: "image",
id: "img-1",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 4_096,
},
],
createdAt: "2026-02-08T10:00:00.000Z",
streaming: false,
},
],
messages: thread.messages,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: null,
worktreePath: null,
});
+10 -167
View File
@@ -3,12 +3,10 @@ import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
@@ -25,26 +23,10 @@ const persistedMessageSchema = z.object({
id: z.string().min(1),
role: z.enum(["user", "assistant"]),
text: z.string(),
attachments: z
.array(
z.object({
type: z.literal("image"),
id: z.string().min(1),
name: z.string().min(1),
mimeType: z.string().min(1),
sizeBytes: z.number().int().min(1),
}),
)
.optional(),
createdAt: z.string().min(1),
streaming: z.boolean(),
});
const persistedTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)),
});
const persistedThreadSchema = z.object({
id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null),
@@ -52,17 +34,11 @@ const persistedThreadSchema = z.object({
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
// Legacy v6 and older fields retained for migration.
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
terminalHeight: z.number().int().min(120).max(4_096).default(
DEFAULT_THREAD_TERMINAL_HEIGHT,
),
messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1),
lastVisitedAt: z.string().min(1).optional(),
branch: z.string().min(1).nullable().optional(),
worktreePath: z.string().min(1).nullable().optional(),
});
@@ -98,18 +74,12 @@ export const persistedStateV6Schema = persistedStateBodySchema.extend({
version: z.literal(6).optional(),
});
export const persistedStateV7Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(7).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(),
});
const persistedStateSchema = z.union([
persistedStateV7Schema,
persistedStateV6Schema,
persistedStateV5Schema,
persistedStateV4Schema,
@@ -147,96 +117,6 @@ function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
const terminalIds = [
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
];
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const safeTerminalIdSet = new Set(safeTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const normalizedGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of thread.terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!safeTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
normalizedGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set(
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
for (const terminalId of splitGroupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
normalizedGroups.push({
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
terminalIds: splitGroupTerminalIds,
});
}
}
for (const terminalId of safeTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
normalizedGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
const activeGroupIndexFromId = normalizedGroups.findIndex(
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(activeTerminalId),
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
return {
id: thread.id,
codexThreadId: thread.codexThreadId,
@@ -245,29 +125,14 @@ function hydrateThread(
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: safeTerminalIds,
runningTerminalIds: [],
activeTerminalId,
terminalGroups: normalizedGroups,
activeTerminalGroupId,
session: null,
messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
return {
id: message.id,
role: message.role,
text: message.text,
...(hydratedAttachments && hydratedAttachments.length > 0
? { attachments: hydratedAttachments }
: {}),
createdAt: message.createdAt,
streaming: false,
};
}),
messages: thread.messages.map((message) => ({
...message,
streaming: false,
})),
events: [],
error: null,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
};
@@ -312,9 +177,9 @@ export function hydratePersistedState(
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV7Schema> {
): z.infer<typeof persistedStateV6Schema> {
return {
version: 7,
version: 6,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
@@ -324,30 +189,8 @@ export function toPersistedState(
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
messages: thread.messages.map((message) => ({
id: message.id,
role: message.role,
text: message.text,
...(message.attachments && message.attachments.length > 0
? {
attachments: message.attachments.map((attachment) => ({
type: attachment.type,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
})),
}
: {}),
createdAt: message.createdAt,
streaming: message.streaming,
})),
messages: thread.messages,
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
-68
View File
@@ -4,7 +4,6 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -393,73 +392,6 @@ describe("deriveWorkLogEntries", () => {
});
});
describe("derivePendingApprovals", () => {
it("returns pending command/file-change approvals", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
payload: { command: "git commit -m 'msg'" },
}),
]);
expect(approvals).toEqual([
{
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
detail: "git commit -m 'msg'",
},
]);
});
it("removes approvals after a decision event", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-decision",
method: "item/requestApproval/decision",
requestId: "req-1",
createdAt: "2026-02-08T10:00:01.000Z",
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/fileChange/requestApproval",
requestId: "req-1",
requestKind: "file-change",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
it("clears pending approvals after turn completion", () => {
const approvals = derivePendingApprovals([
makeEvent({
id: "evt-turn-complete",
method: "turn/completed",
createdAt: "2026-02-08T10:00:01.000Z",
payload: { turn: { id: "turn-1", status: "completed" } },
}),
makeEvent({
id: "evt-request",
kind: "request",
method: "item/commandExecution/requestApproval",
requestId: "req-1",
requestKind: "command",
createdAt: "2026-02-08T10:00:00.000Z",
}),
]);
expect(approvals).toHaveLength(0);
});
});
describe("evolveSession", () => {
it("updates thread id when thread starts", () => {
const previous = makeSession();
-53
View File
@@ -78,13 +78,6 @@ export interface WorkLogEntry {
tone: "thinking" | "tool" | "info" | "error";
}
export interface PendingApproval {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
export type TimelineEntry =
| {
id: string;
@@ -105,52 +98,6 @@ function normalizeDetail(value: string | undefined): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asObject(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
const pending = new Map<string, PendingApproval>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (
event.method === "session/closed" ||
event.method === "session/exited" ||
event.method === "turn/completed"
) {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
if (!requestId) continue;
if (
event.kind === "request" &&
(event.requestKind === "command" || event.requestKind === "file-change")
) {
const detail = approvalDetail(event);
pending.set(requestId, {
requestId,
requestKind: event.requestKind,
createdAt: event.createdAt,
...(detail ? { detail } : {}),
});
continue;
}
if (event.method === "item/requestApproval/decision") {
pending.delete(requestId);
}
}
return Array.from(pending.values());
}
function normalizeItemType(raw: string | undefined): string {
if (!raw) return "item";
return raw
+2 -312
View File
@@ -1,13 +1,10 @@
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import type { Thread } from "./types";
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
return {
sessionId: "sess-1",
@@ -40,16 +37,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: makeSession(),
messages: [],
events: [],
@@ -79,42 +66,6 @@ function makeState(thread: Thread): AppState {
};
}
function makeTerminalStartedEvent(
overrides: Partial<TerminalStartedEvent> = {},
): TerminalStartedEvent {
return {
type: "started",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:01.000Z",
snapshot: {
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
cwd: "/tmp/project",
status: "running",
pid: 1234,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-02-09T00:00:01.000Z",
},
...overrides,
};
}
function makeTerminalActivityEvent(
overrides: Partial<TerminalActivityEvent> = {},
): TerminalActivityEvent {
return {
type: "activity",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:02.000Z",
hasRunningSubprocess: true,
...overrides,
};
}
describe("store reducer thread continuity", () => {
it("stores codexThreadId from UPDATE_SESSION", () => {
const state = makeState(
@@ -160,223 +111,6 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.terminalHeight).toBe(360);
});
it("splits the active terminal into side-by-side mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("creates a new full-width terminal and switches to tab mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
});
it("switches the active terminal and restores its owning group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: "group-term-3",
}),
);
const next = reducer(state, {
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("supports splitting beyond two terminals in the same group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-3",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
},
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("closes a terminal and keeps grouped layout coherent", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
});
it("closes the final terminal and hides the drawer", () => {
const state = makeState(
makeThread({
terminalOpen: true,
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
]);
});
it("tracks running terminals from subprocess activity events", () => {
const state = makeState(makeThread());
const started = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalStartedEvent(),
});
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
const active = reducer(started, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent(),
});
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
const idle = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
});
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
const exited = reducer(active, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:05.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
});
it("keeps running status when another terminal in the thread is still running", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "APPLY_TERMINAL_EVENT",
event: {
type: "exited",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
createdAt: "2026-02-09T00:00:07.000Z",
exitCode: 0,
exitSignal: null,
},
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
});
it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, {
@@ -485,48 +219,4 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.projectId).toBe("project-new-a");
expect(next.activeThreadId).toBe("thread-a");
});
it("marks the active thread as visited when selected", () => {
const state = makeState(
makeThread({
lastVisitedAt: "2000-01-01T00:00:00.000Z",
}),
);
const next = reducer(state, {
type: "SET_ACTIVE_THREAD",
threadId: "thread-local-1",
});
expect(next.activeThreadId).toBe("thread-local-1");
expect(next.threads[0]?.lastVisitedAt).toBeDefined();
expect(next.threads[0]?.lastVisitedAt).not.toBe("2000-01-01T00:00:00.000Z");
});
it("marks completion as seen immediately for the active thread", () => {
const state = makeState(
makeThread({
session: makeSession({
status: "running",
activeTurnId: "turn-1",
}),
lastVisitedAt: "2026-02-08T10:00:00.000Z",
}),
);
const completedAt = "2026-02-08T10:00:10.000Z";
const next = reducer(state, {
type: "APPLY_EVENT",
event: makeEvent({
method: "turn/completed",
turnId: "turn-1",
createdAt: completedAt,
payload: { turn: { id: "turn-1", status: "completed" } },
}),
activeAssistantItemRef: { current: null },
});
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
});
});
+22 -386
View File
@@ -8,18 +8,15 @@ import {
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
@@ -33,25 +30,14 @@ type Action =
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "TOGGLE_DIFF" }
| {
type: "APPLY_EVENT";
event: ProviderEvent;
activeAssistantItemRef: { current: string | null };
}
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
| {
type: "PUSH_USER_MESSAGE";
threadId: string;
id: string;
text: string;
attachments?: ChatAttachment[];
}
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
@@ -74,9 +60,8 @@ export interface AppState {
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const PERSISTED_STATE_KEY = "t3code:renderer-state:v6";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
@@ -101,12 +86,17 @@ function readPersistedState(): AppState {
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) =>
window.localStorage.getItem(key),
);
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
const hydrated = hydratePersistedState(
raw,
!rawCurrent && raw === rawCodethingV1,
);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
@@ -136,191 +126,6 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)];
if (unique.length > 0) {
return unique;
}
return [DEFAULT_THREAD_TERMINAL_ID];
}
function normalizeRunningTerminalIds(
runningTerminalIds: string[],
terminalIds: string[],
): string[] {
if (runningTerminalIds.length === 0) return [];
const validTerminalIdSet = new Set(terminalIds);
return [...new Set(runningTerminalIds)]
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
}
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const groups: ThreadTerminalGroup[] = [];
for (const group of thread.terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
groups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
groups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (groups.length > 0) {
return groups;
}
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeThreadTerminals(thread: Thread): Thread {
const terminalIds = normalizeTerminalIds(thread.terminalIds);
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
return {
...thread,
terminalIds,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
};
}
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
if (!thread.terminalIds.includes(terminalId)) {
return thread;
}
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: nextTerminalGroupId,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: nextTerminalGroupId,
});
}
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
const closedTerminalGroup = thread.terminalGroups.find((group) =>
group.terminalIds.includes(terminalId),
);
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
(id) => id !== terminalId,
);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
] ??
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: thread.activeTerminalId;
const nextTerminalGroups = thread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
return normalizeThreadTerminals({
...thread,
terminalIds: remainingTerminalIds,
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups: nextTerminalGroups,
});
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId);
}
@@ -447,10 +252,10 @@ export function reducer(state: AppState, action: Action): AppState {
if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null;
return normalizeThreadTerminals({
return {
...thread,
projectId: mappedProjectId,
});
};
})
.filter((thread): thread is Thread => thread !== null);
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
@@ -473,30 +278,21 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
});
case "ADD_THREAD":
return {
...state,
threads: [...state.threads, nextThread],
threads: [
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
},
],
activeThreadId: action.thread.id,
};
}
case "SET_ACTIVE_THREAD": {
const visitedAt = new Date().toISOString();
return {
...state,
activeThreadId: action.threadId,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
lastVisitedAt: visitedAt,
})),
};
}
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
case "TOGGLE_THREAD_TERMINAL":
return {
@@ -525,163 +321,9 @@ export function reducer(state: AppState, action: Action): AppState {
})),
};
case "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
...group,
terminalIds: [...group.terminalIds],
}));
let activeGroupIndex = terminalGroups.findIndex(
(group) => group.id === normalizedThread.activeTerminalGroupId,
);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
normalizedThread.activeTerminalId,
);
}
if (activeGroupIndex < 0) {
terminalGroups.push({
id: fallbackGroupId(normalizedThread.activeTerminalId),
terminalIds: [normalizedThread.activeTerminalId],
});
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
if (existingGroupIndex < activeGroupIndex) {
activeGroupIndex -= 1;
}
}
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalizedThread;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(
normalizedThread.activeTerminalId,
);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: destinationGroup.id,
terminalGroups,
});
}),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextGroupId = fallbackGroupId(action.terminalId);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: nextGroupId,
terminalGroups,
});
}),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
return thread;
}
const nextActiveGroupIndex = findGroupIndexByTerminalId(
normalizedThread.terminalGroups,
action.terminalId,
);
const activeTerminalGroupId =
nextActiveGroupIndex >= 0
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
normalizedThread.activeTerminalGroupId)
: normalizedThread.activeTerminalGroupId;
return normalizeThreadTerminals({
...normalizedThread,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
});
}),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
closeThreadTerminal(thread, action.terminalId),
),
};
case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen };
case "APPLY_TERMINAL_EVENT":
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
return state;
}
return {
...state,
threads: updateThread(state.threads, action.event.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
if (action.event.type === "started" || action.event.type === "restarted") {
runningTerminalIdSet.delete(action.event.terminalId);
} else if (action.event.type === "activity") {
if (action.event.hasRunningSubprocess) {
runningTerminalIdSet.add(action.event.terminalId);
} else {
runningTerminalIdSet.delete(action.event.terminalId);
}
} else if (action.event.type === "exited" || action.event.type === "error") {
runningTerminalIdSet.delete(action.event.terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIdSet],
});
}),
};
case "APPLY_EVENT": {
const { event, activeAssistantItemRef } = action;
const target = findThreadBySessionId(state.threads, event.sessionId);
@@ -707,9 +349,6 @@ export function reducer(state: AppState, action: Action): AppState {
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
events: [event, ...t.events],
...updateTurnFields(t, event),
...(event.method === "turn/completed" && t.id === state.activeThreadId
? { lastVisitedAt: event.createdAt }
: {}),
})),
};
}
@@ -741,9 +380,6 @@ export function reducer(state: AppState, action: Action): AppState {
id: action.id,
role: "user" as const,
text: action.text,
...(action.attachments && action.attachments.length > 0
? { attachments: action.attachments }
: {}),
createdAt: new Date().toISOString(),
streaming: false,
},
-107
View File
@@ -1,107 +0,0 @@
import { describe, expect, it } from "vitest";
import {
extractTerminalLinks,
isTerminalLinkActivation,
resolvePathLinkTarget,
} from "./terminal-links";
describe("extractTerminalLinks", () => {
it("finds http urls and path tokens", () => {
const line =
"failed at https://example.com/docs and src/components/ThreadTerminalDrawer.tsx:42";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "https://example.com/docs",
start: 10,
end: 34,
},
{
kind: "path",
text: "src/components/ThreadTerminalDrawer.tsx:42",
start: 39,
end: 81,
},
]);
});
it("trims trailing punctuation from links", () => {
const line = "(https://example.com/docs), ./src/main.ts:12.";
expect(extractTerminalLinks(line)).toEqual([
{
kind: "url",
text: "https://example.com/docs",
start: 1,
end: 25,
},
{
kind: "path",
text: "./src/main.ts:12",
start: 28,
end: 44,
},
]);
});
});
describe("resolvePathLinkTarget", () => {
it("resolves relative paths against cwd", () => {
expect(
resolvePathLinkTarget(
"src/components/ThreadTerminalDrawer.tsx:42:7",
"/Users/julius/project",
),
).toBe("/Users/julius/project/src/components/ThreadTerminalDrawer.tsx:42:7");
});
it("keeps absolute paths unchanged", () => {
expect(
resolvePathLinkTarget("/Users/julius/project/src/main.ts:12", "/Users/julius/project"),
).toBe("/Users/julius/project/src/main.ts:12");
});
});
describe("isTerminalLinkActivation", () => {
it("requires cmd on macOS", () => {
expect(
isTerminalLinkActivation(
{
metaKey: true,
ctrlKey: false,
},
"MacIntel",
),
).toBe(true);
expect(
isTerminalLinkActivation(
{
metaKey: false,
ctrlKey: true,
},
"MacIntel",
),
).toBe(false);
});
it("requires ctrl on non-macOS", () => {
expect(
isTerminalLinkActivation(
{
metaKey: false,
ctrlKey: true,
},
"Win32",
),
).toBe(true);
expect(
isTerminalLinkActivation(
{
metaKey: true,
ctrlKey: false,
},
"Linux",
),
).toBe(false);
});
});
-200
View File
@@ -1,200 +0,0 @@
import { EDITORS, type EditorId } from "@t3tools/contracts";
export type TerminalLinkKind = "url" | "path";
export interface TerminalLinkMatch {
kind: TerminalLinkKind;
text: string;
start: number;
end: number;
}
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
const FILE_PATH_PATTERN =
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
const LAST_EDITOR_KEY = "t3code:last-editor";
function isMacPlatform(platform: string): boolean {
return /mac|iphone|ipad|ipod/i.test(platform);
}
function trimClosingDelimiters(value: string): string {
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
if (output.length === 0) return output;
const trimUnbalanced = (open: string, close: string) => {
while (output.endsWith(close)) {
const opens = output.split(open).length - 1;
const closes = output.split(close).length - 1;
if (opens >= closes) return;
output = output.slice(0, -1);
}
};
trimUnbalanced("(", ")");
trimUnbalanced("[", "]");
trimUnbalanced("{", "}");
return output;
}
function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
return a.start < b.end && b.start < a.end;
}
function collectMatches(
line: string,
kind: TerminalLinkKind,
pattern: RegExp,
existing: TerminalLinkMatch[],
): TerminalLinkMatch[] {
const matches: TerminalLinkMatch[] = [];
pattern.lastIndex = 0;
for (const rawMatch of line.matchAll(pattern)) {
const raw = rawMatch[0];
const start = rawMatch.index ?? -1;
if (start < 0 || raw.length === 0) continue;
const trimmed = trimClosingDelimiters(raw);
if (trimmed.length === 0) continue;
if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
const candidate: TerminalLinkMatch = {
kind,
text: trimmed,
start,
end: start + trimmed.length,
};
const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
if (collides) continue;
matches.push(candidate);
}
return matches;
}
function isWindowsAbsolutePath(value: string): boolean {
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
}
function isAbsolutePath(value: string): boolean {
return value.startsWith("/") || isWindowsAbsolutePath(value);
}
function isWindowsPathStyle(value: string): boolean {
return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
}
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
const cleanBase = base.replace(/[\\/]+$/, "");
if (separator === "\\") {
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
}
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
}
function inferHomeFromCwd(cwd: string): string | undefined {
const posixUser = cwd.match(/^\/Users\/([^/]+)/);
if (posixUser?.[1]) {
return `/Users/${posixUser[1]}`;
}
const posixHome = cwd.match(/^\/home\/([^/]+)/);
if (posixHome?.[1]) {
return `/home/${posixHome[1]}`;
}
const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
if (windowsUser?.[1]) {
return windowsUser[1];
}
return undefined;
}
function splitPathAndPosition(value: string): {
path: string;
line: string | undefined;
column: string | undefined;
} {
let path = value;
let column: string | undefined;
let line: string | undefined;
const columnMatch = path.match(/:(\d+)$/);
if (!columnMatch?.[1]) {
return { path, line: undefined, column: undefined };
}
column = columnMatch[1];
path = path.slice(0, -columnMatch[0].length);
const lineMatch = path.match(/:(\d+)$/);
if (lineMatch?.[1]) {
line = lineMatch[1];
path = path.slice(0, -lineMatch[0].length);
} else {
line = column;
column = undefined;
}
return { path, line, column };
}
export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
}
export function isTerminalLinkActivation(
event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
platform = typeof navigator === "undefined" ? "" : navigator.platform,
): boolean {
if (platform.length === 0) return false;
return isMacPlatform(platform)
? event.metaKey && !event.ctrlKey
: event.ctrlKey && !event.metaKey;
}
export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
const { path, line, column } = splitPathAndPosition(rawPath);
let resolvedPath = path;
if (path.startsWith("~/")) {
const home = inferHomeFromCwd(cwd);
if (home) {
const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
resolvedPath = joinPath(home, path.slice(2), separator);
}
} else if (!isAbsolutePath(path)) {
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
resolvedPath = joinPath(cwd, path, separator);
}
if (!line) return resolvedPath;
return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
}
export function preferredTerminalEditor(): EditorId {
const fallback = EDITORS.find((editor) => editor.command)?.id ?? EDITORS[0]?.id ?? "cursor";
if (typeof window === "undefined") {
return fallback;
}
const storedEditor = window.localStorage.getItem(LAST_EDITOR_KEY);
if (!storedEditor) {
return fallback;
}
const configured = EDITORS.find((editor) => editor.id === storedEditor);
if (!configured?.command) {
return fallback;
}
return configured.id;
}
+38 -13
View File
@@ -19,45 +19,70 @@ function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
expect(
isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel"),
).toBe(true);
});
it("matches Ctrl+J on non-macOS", () => {
expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
expect(
isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32"),
).toBe(true);
});
it("rejects wrong modifiers", () => {
expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
false,
);
expect(
isTerminalToggleShortcut(
event({ ctrlKey: true, shiftKey: true }),
"Win32",
),
).toBe(false);
expect(
isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
});
it("rejects non-j keys", () => {
expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
expect(
isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux"),
).toBe(false);
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"),
).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"),
).toBe(true);
});
it("matches Cmd+K on macOS", () => {
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"),
).toBe(true);
});
it("rejects Cmd+K on non-macOS", () => {
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32"),
).toBe(false);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
isTerminalClearShortcut(
event({ key: "l", ctrlKey: true, shiftKey: true }),
"Linux",
),
).toBe(false);
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
isTerminalClearShortcut(
event({ key: "k", metaKey: true, altKey: true }),
"MacIntel",
),
).toBe(false);
});
});
+7 -1
View File
@@ -31,7 +31,13 @@ export function isTerminalClearShortcut(
): boolean {
const key = event.key.toLowerCase();
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
if (
key === "l" &&
event.ctrlKey &&
!event.metaKey &&
!event.altKey &&
!event.shiftKey
) {
return true;
}
-24
View File
@@ -4,29 +4,11 @@ export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export interface ThreadTerminalGroup {
id: string;
terminalIds: string[];
}
export interface ChatImageAttachment {
type: "image";
id: string;
name: string;
mimeType: string;
sizeBytes: number;
previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment;
export interface ChatMessage {
id: string;
role: "user" | "assistant";
text: string;
attachments?: ChatAttachment[];
createdAt: string;
streaming: boolean;
}
@@ -47,11 +29,6 @@ export interface Thread {
model: string;
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ProviderSession | null;
messages: ChatMessage[];
events: ProviderEvent[];
@@ -61,7 +38,6 @@ export interface Thread {
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
}
-2
View File
@@ -5,9 +5,7 @@ import type { NativeApi } from "@t3tools/contracts";
interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
}
declare global {
-97
View File
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-1",
codexThreadId: null,
projectId: "project-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
events: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
branch: null,
worktreePath: null,
...overrides,
};
}
describe("getOrphanedWorktreePathForThread", () => {
it("returns null when the target thread does not exist", () => {
const result = getOrphanedWorktreePathForThread([], "missing-thread");
expect(result).toBeNull();
});
it("returns null when the target thread has no worktree", () => {
const threads = [makeThread()];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("returns the path when no other thread links to that worktree", () => {
const threads = [makeThread({ worktreePath: "/tmp/repo/worktrees/feature-a" })];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
it("returns null when another thread links to the same worktree", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-a" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("ignores threads linked to different worktrees", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-b" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
});
describe("formatWorktreePathForDisplay", () => {
it("shows only the last path segment for unix-like paths", () => {
const result = formatWorktreePathForDisplay(
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("normalizes windows separators before selecting the final segment", () => {
const result = formatWorktreePathForDisplay(
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("uses the final segment even when outside ~/.t3/worktrees", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree");
expect(result).toBe("my-worktree");
});
it("ignores trailing slashes", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree/");
expect(result).toBe("my-worktree");
});
});
-45
View File
@@ -1,45 +0,0 @@
import type { Thread } from "./types";
function normalizeWorktreePath(path: string | null): string | null {
const trimmed = path?.trim();
if (!trimmed) {
return null;
}
return trimmed;
}
export function getOrphanedWorktreePathForThread(
threads: readonly Thread[],
threadId: string,
): string | null {
const targetThread = threads.find((thread) => thread.id === threadId);
if (!targetThread) {
return null;
}
const targetWorktreePath = normalizeWorktreePath(targetThread.worktreePath);
if (!targetWorktreePath) {
return null;
}
const isShared = threads.some((thread) => {
if (thread.id === threadId) {
return false;
}
return normalizeWorktreePath(thread.worktreePath) === targetWorktreePath;
});
return isShared ? null : targetWorktreePath;
}
export function formatWorktreePathForDisplay(worktreePath: string): string {
const trimmed = worktreePath.trim();
if (!trimmed) {
return worktreePath;
}
const normalized = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const lastPart = parts[parts.length - 1]?.trim() ?? "";
return lastPart.length > 0 ? lastPart : trimmed;
}
-23
View File
@@ -60,12 +60,6 @@ export function createWsNativeApi(): NativeApi {
if (!window.desktopBridge) return null;
return window.desktopBridge.pickFolder();
},
confirm: async (message) => {
if (window.desktopBridge) {
return window.desktopBridge.confirm(message);
}
return window.confirm(message);
},
},
terminal: {
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
@@ -102,25 +96,8 @@ export function createWsNativeApi(): NativeApi {
shell: {
openInEditor: (cwd, editor) =>
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
openExternal: async (url) => {
if (window.desktopBridge) {
const opened = await window.desktopBridge.openExternal(url);
if (!opened) {
throw new Error("Unable to open link.");
}
return;
}
const popup = window.open(url, "_blank", "noopener,noreferrer");
if (!popup) {
throw new Error("Unable to open link. Allow popups and try again.");
}
},
},
git: {
pull: (input) => transport.request(WS_METHODS.gitPull, input),
status: (input) => transport.request(WS_METHODS.gitStatus, input),
runStackedAction: (input) => transport.request(WS_METHODS.gitRunStackedAction, input),
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
+1 -4
View File
@@ -4,10 +4,7 @@
"composite": true,
"jsx": "react-jsx",
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"types": ["vite/client"],
"paths": {
"~/*": ["./src/*"]
}
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}
-6
View File
@@ -17,12 +17,6 @@ export default defineConfig({
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
},
experimental: {
enableNativePlugin: true,
},
resolve: {
tsconfigPaths: true,
},
server: {
port,
strictPort: true,
+3 -118
View File
@@ -51,20 +51,17 @@
"name": "@t3tools/web",
"version": "0.0.0",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"highlight.js": "^11.11.1",
"lucide-react": "^0.564.0",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"rehype-highlight": "^7.0.2",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zod": "^3.24.1",
},
"devDependencies": {
@@ -123,18 +120,12 @@
"@babel/plugin-transform-react-jsx-source": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw=="],
"@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA=="],
"@babel/template": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.28.6", "@babel/parser": "^7.28.6", "@babel/types": "^7.28.6" } }, "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ=="],
"@babel/traverse": ["@babel/[email protected]", "", { "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", "@babel/parser": "^7.29.0", "@babel/template": "^7.28.6", "@babel/types": "^7.29.0", "debug": "^4.3.1" } }, "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA=="],
"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
"@base-ui/react": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@base-ui/utils": "0.2.5", "@floating-ui/react-dom": "^2.1.6", "@floating-ui/utils": "^0.2.10", "tabbable": "^6.4.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-O6aEQHcm+QyGTFY28xuwRD3SEJGZOBDpyjN2WvpfWYFVhg+3zfXPysAILqtM0C1kWC82MccOE/v1j+GHXE4qIw=="],
"@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.28.6", "@floating-ui/utils": "^0.2.10", "reselect": "^5.1.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-oYC7w0gp76RI5MxprlGLV0wze0SErZaRl3AAkeP3OnNB/UBMb6RqNf6ZSIlxOc9Qp68Ab3C2VOcJQyRs7Xc7Vw=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
"@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.1.0", "tslib": "^2.4.0" } }, "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg=="],
@@ -195,14 +186,6 @@
"@esbuild/win32-x64": ["@esbuild/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="],
"@floating-ui/core": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "sha512-C3HlIdsBxszvm5McXlB8PeOEWfBhcGBTZGkGlWc2U0KFY5IwG5OQEuQ8rq52DZmcHDlPLd+YFBK+cZcytwIFWg=="],
"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.7.4", "@floating-ui/utils": "^0.2.10" } }, "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg=="],
"@floating-ui/react-dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/dom": "^1.7.5" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-0tLRojf/1Go2JgEVm+3Frg9A3IW8bJgKgdO0BN5RkF//ufuz2joZM63Npau2ff3J6lUVYgDSNzNkR+aH3IVfjg=="],
"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="],
"@hapi/address": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="],
"@hapi/formula": ["@hapi/[email protected]", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="],
@@ -215,16 +198,6 @@
"@hapi/topo": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg=="],
"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ=="],
"@inquirer/confirm": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ=="],
"@inquirer/core": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/ansi": "^1.0.2", "@inquirer/figures": "^1.0.15", "@inquirer/type": "^3.0.10", "cli-width": "^4.1.0", "mute-stream": "^2.0.0", "signal-exit": "^4.1.0", "wrap-ansi": "^6.2.0", "yoctocolors-cjs": "^2.1.3" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A=="],
"@inquirer/figures": ["@inquirer/[email protected]", "", {}, "sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g=="],
"@inquirer/type": ["@inquirer/[email protected]", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA=="],
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -235,16 +208,8 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
"@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1", "@tybys/wasm-util": "^0.10.1" } }, "sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A=="],
"@open-draft/deferred-promise": ["@open-draft/[email protected]", "", {}, "sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA=="],
"@open-draft/logger": ["@open-draft/[email protected]", "", { "dependencies": { "is-node-process": "^1.2.0", "outvariant": "^1.4.0" } }, "sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ=="],
"@open-draft/until": ["@open-draft/[email protected]", "", {}, "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg=="],
"@oxc-project/runtime": ["@oxc-project/[email protected]", "", {}, "sha512-4vYtWXMnXM6EaweCxbJ6bISAhkNHeN33SihvuX3wrpqaSJA4ZEoW35i9mSvE74+GDf1yTeVE+aEHA+WBpjDk/g=="],
"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-m6RebKHIRsax2iCwVpYW2ErQwa4ywHJrE4sCK3/8JK8ZZAWOKXaRJFl/uP51gaVyyXlaS4+chU1nSCdzYf6QqQ=="],
@@ -471,8 +436,6 @@
"@types/responselike": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw=="],
"@types/statuses": ["@types/[email protected]", "", {}, "sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA=="],
"@types/unist": ["@types/[email protected]", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
"@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
@@ -501,8 +464,6 @@
"@xterm/xterm": ["@xterm/[email protected]", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
"ansi-regex": ["[email protected]", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"ansis": ["[email protected]", "", {}, "sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig=="],
@@ -557,16 +518,8 @@
"character-reference-invalid": ["[email protected]", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="],
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
"cli-width": ["[email protected]", "", {}, "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ=="],
"cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"clone-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^1.0.0" } }, "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA=="],
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
"color-convert": ["[email protected]", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["[email protected]", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
@@ -577,8 +530,6 @@
"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
@@ -621,8 +572,6 @@
"electronmon": ["[email protected]", "", { "dependencies": { "chalk": "^3.0.0", "import-from": "^3.0.0", "runtime-required": "^1.1.0", "watchboy": "^0.4.3" }, "bin": { "electronmon": "bin/cli.js" } }, "sha512-u6eDrvUbqa+wsnMrhG2vHmo5neL1owLg2e5i1avGWcOb4rHsUf9lSfbs0FvfPsBNpLxxlPO98nrMhAGV+zw/fQ=="],
"emoji-regex": ["[email protected]", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"empathic": ["[email protected]", "", {}, "sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA=="],
"end-of-stream": ["[email protected]", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
@@ -677,8 +626,6 @@
"gensync": ["[email protected]", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-caller-file": ["[email protected]", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
@@ -697,8 +644,6 @@
"graceful-fs": ["[email protected]", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"graphql": ["[email protected]", "", {}, "sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ=="],
"has-flag": ["[email protected]", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
"has-property-descriptors": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
@@ -717,8 +662,6 @@
"hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
"highlight.js": ["[email protected]", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
@@ -743,14 +686,10 @@
"is-docker": ["[email protected]", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="],
"is-fullwidth-code-point": ["[email protected]", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"is-hexadecimal": ["[email protected]", "", {}, "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="],
"is-inside-container": ["[email protected]", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="],
"is-node-process": ["[email protected]", "", {}, "sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw=="],
"is-number": ["[email protected]", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
"is-plain-obj": ["[email protected]", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
@@ -811,7 +750,7 @@
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"lucide-react": ["[email protected]4.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-JJ8GVTQqFwuliifD48U6+h7DXEHdkhJ/E87kksGByII3qHxtPciVb8T8woQONHBQgHVOl7rSMrrip3SeVNy7Fg=="],
"lucide-react": ["[email protected]3.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-8dXPB2GI4dI8jV4MgUDGBeLdGk8ekfqVZ0BdLcrRzocGgG75ltNEmWS+gE7uokKF/0oSUuczNDT+g9hFJ23FkA=="],
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
@@ -919,10 +858,6 @@
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-G3VUymSE0/iegFnuipujpwyTM2GuZAKXNeerUSrG2+Eg391wW63xFs5ixWsK9MWzr1AGoSkYGmyAzNgbR3+urw=="],
"mute-stream": ["[email protected]", "", {}, "sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA=="],
"nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"node-addon-api": ["[email protected]", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
@@ -943,8 +878,6 @@
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/darwin-arm64": "0.28.0", "@oxfmt/darwin-x64": "0.28.0", "@oxfmt/linux-arm64-gnu": "0.28.0", "@oxfmt/linux-arm64-musl": "0.28.0", "@oxfmt/linux-x64-gnu": "0.28.0", "@oxfmt/linux-x64-musl": "0.28.0", "@oxfmt/win32-arm64": "0.28.0", "@oxfmt/win32-x64": "0.28.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-3+hhBqPE6Kp22KfJmnstrZbl+KdOVSEu1V0ABaFIg1rYLtrMgrupx9znnHgHLqKxAVHebjTdiCJDk30CXOt6cw=="],
"oxlint": ["[email protected]", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.46.0", "@oxlint/binding-android-arm64": "1.46.0", "@oxlint/binding-darwin-arm64": "1.46.0", "@oxlint/binding-darwin-x64": "1.46.0", "@oxlint/binding-freebsd-x64": "1.46.0", "@oxlint/binding-linux-arm-gnueabihf": "1.46.0", "@oxlint/binding-linux-arm-musleabihf": "1.46.0", "@oxlint/binding-linux-arm64-gnu": "1.46.0", "@oxlint/binding-linux-arm64-musl": "1.46.0", "@oxlint/binding-linux-ppc64-gnu": "1.46.0", "@oxlint/binding-linux-riscv64-gnu": "1.46.0", "@oxlint/binding-linux-riscv64-musl": "1.46.0", "@oxlint/binding-linux-s390x-gnu": "1.46.0", "@oxlint/binding-linux-x64-gnu": "1.46.0", "@oxlint/binding-linux-x64-musl": "1.46.0", "@oxlint/binding-openharmony-arm64": "1.46.0", "@oxlint/binding-win32-arm64-msvc": "1.46.0", "@oxlint/binding-win32-ia32-msvc": "1.46.0", "@oxlint/binding-win32-x64-msvc": "1.46.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.11.2" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-I9h42QDtAVsRwoueJ4PL/7qN5jFzIUXvbO4Z5ddtII92ZCiD7uiS/JW2V4viBSfGLsbZkQp3YEs6Ls4I8q+8tA=="],
@@ -953,8 +886,6 @@
"parse-entities": ["[email protected]", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"path-to-regexp": ["[email protected]", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="],
"pathe": ["[email protected]", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
"pend": ["[email protected]", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
@@ -999,10 +930,6 @@
"remove-trailing-separator": ["[email protected]", "", {}, "sha512-/hS+Y0u3aOfIETiaiirUFwDBDzmXPvO+jAfKTitUngIPzdKc6Z0LoFjM/CK5PL4C+eKwHohlHAb6H0VFfmmUsw=="],
"require-directory": ["[email protected]", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"reselect": ["[email protected]", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
"resolve-alpn": ["[email protected]", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
"resolve-from": ["[email protected]", "", {}, "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw=="],
@@ -1011,8 +938,6 @@
"responselike": ["[email protected]", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
"rettime": ["[email protected]", "", {}, "sha512-uyDrIlUEH37cinabq0AX4QbgV4HbFZ/gqoiunWQ1UqBtRvTTytwhNYjE++pO/MjPTZL5KQCf2bEoJ/BJNVQ5Kw=="],
"roarr": ["[email protected]", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="],
"rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.112.0", "@rolldown/pluginutils": "1.0.0-rc.3" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.0-rc.3", "@rolldown/binding-darwin-arm64": "1.0.0-rc.3", "@rolldown/binding-darwin-x64": "1.0.0-rc.3", "@rolldown/binding-freebsd-x64": "1.0.0-rc.3", "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.3", "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.3", "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.3", "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.3", "@rolldown/binding-linux-x64-musl": "1.0.0-rc.3", "@rolldown/binding-openharmony-arm64": "1.0.0-rc.3", "@rolldown/binding-wasm32-wasi": "1.0.0-rc.3", "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.3", "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.3" }, "bin": { "rolldown": "bin/cli.mjs" } }, "sha512-Po/YZECDOqVXjIXrtC5h++a5NLvKAQNrd9ggrIG3sbDfGO5BqTUsrI6l8zdniKRp3r5Tp/2JTrXqx4GIguFCMw=="],
@@ -1037,8 +962,6 @@
"siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
"signal-exit": ["[email protected]", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"space-separated-tokens": ["[email protected]", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="],
@@ -1047,18 +970,10 @@
"stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
"statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"std-env": ["[email protected]", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
"strict-event-emitter": ["[email protected]", "", {}, "sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ=="],
"string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"stringify-entities": ["[email protected]", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
"strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"style-to-js": ["[email protected]", "", { "dependencies": { "style-to-object": "1.0.14" } }, "sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ=="],
"style-to-object": ["[email protected]", "", { "dependencies": { "inline-style-parser": "0.2.7" } }, "sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw=="],
@@ -1069,12 +984,6 @@
"t3": ["t3@workspace:apps/server"],
"tabbable": ["[email protected]", "", {}, "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg=="],
"tagged-tag": ["[email protected]", "", {}, "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng=="],
"tailwind-merge": ["[email protected]", "", {}, "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g=="],
"tailwindcss": ["[email protected]", "", {}, "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw=="],
"tapable": ["[email protected]", "", {}, "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg=="],
@@ -1089,14 +998,8 @@
"tinyrainbow": ["[email protected]", "", {}, "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q=="],
"tldts": ["[email protected]", "", { "dependencies": { "tldts-core": "^7.0.23" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-ASdhgQIBSay0R/eXggAkQ53G4nTJqTXqC2kbaBbdDwM7SkjyZyO0OaaN1/FH7U/yCeqOHDwFO5j8+Os/IS1dXw=="],
"tldts-core": ["[email protected]", "", {}, "sha512-0g9vrtDQLrNIiCj22HSe9d4mLVG3g5ph5DZ8zCKBr4OtrspmNB6ss7hVyzArAeE88ceZocIEGkyW1Ime7fxPtQ=="],
"to-regex-range": ["[email protected]", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
"tough-cookie": ["[email protected]", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w=="],
"tree-kill": ["[email protected]", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="],
"trim-lines": ["[email protected]", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
@@ -1121,7 +1024,7 @@
"turbo-windows-arm64": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-WyGiOI2Zp3AhuzVagzQN+T+iq0fWx0oGxDfAWT3ZiLEd4U0cDUkwUZDKVGb3rKqPjDL6lWnuxKKu73ge5xtovQ=="],
"type-fest": ["type-fest@5.4.4", "", { "dependencies": { "tagged-tag": "^1.0.0" } }, "sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw=="],
"type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
@@ -1149,12 +1052,8 @@
"unrun": ["[email protected]", "", { "dependencies": { "rolldown": "1.0.0-rc.3" }, "peerDependencies": { "synckit": "^0.11.11" }, "optionalPeers": ["synckit"], "bin": { "unrun": "dist/cli.mjs" } }, "sha512-Mmur1UJpIbfxasLOhPRvox/QS4xBiDii71hMP7smfRthGcwFL2OAmYRgduLANOAU4LUkvVamuP+02U+c90jlrw=="],
"until-async": ["[email protected]", "", {}, "sha512-IiSk4HlzAMqTUseHHe3VhIGyuFmN90zMTpD3Z3y8jeQbzLIq500MVM7Jq2vUAnTKAFPJrqwkzr6PoTcPhGcOiw=="],
"update-browserslist-db": ["[email protected]", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"vfile": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
@@ -1169,26 +1068,16 @@
"why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
"wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="],
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yargs": ["[email protected]", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="],
"yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
"yauzl": ["[email protected]", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"yoctocolors-cjs": ["[email protected]", "", {}, "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw=="],
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
@@ -1241,8 +1130,6 @@
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw=="],
@@ -1255,8 +1142,6 @@
"rolldown-plugin-dts/@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0-rc.1", "@babel/helper-validator-identifier": "^8.0.0-rc.1" } }, "sha512-ubmJ6TShyaD69VE9DQrlXcdkvJbmwWPB8qYj0H2kaJi29O7vJT9ajSdBd2W8CG34pwL9pYA74fi7RHC1qbLoVQ=="],
"serialize-error/type-fest": ["[email protected]", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"vitest/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"@babel/generator/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
+4 -4
View File
@@ -6,10 +6,10 @@
"packages/*"
],
"scripts": {
"dev": "bun run scripts/dev-runner.mjs dev",
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
"dev:web": "bun run scripts/dev-runner.mjs dev:web",
"dev:desktop": "bun run scripts/dev-runner.mjs dev:desktop",
"dev": "T3CODE_LOG_WS_EVENTS=1 VITE_WS_URL=ws://localhost:3773 turbo run dev --ui=tui --filter=@t3tools/contracts --filter=@t3tools/web --filter=t3 --parallel",
"dev:server": "turbo run dev --filter=t3",
"dev:web": "VITE_WS_URL=ws://localhost:3773 turbo run dev --filter=@t3tools/web",
"dev:desktop": "turbo run dev --filter=@t3tools/desktop --filter=@t3tools/web --parallel",
"start": "turbo run start --filter=t3",
"start:desktop": "turbo run start --filter=@t3tools/desktop",
"build": "turbo run build",
-107
View File
@@ -1,107 +0,0 @@
import { describe, expect, it } from "vitest";
import {
gitPullInputSchema,
gitPullResultSchema,
gitRunStackedActionInputSchema,
gitRunStackedActionResultSchema,
gitStackedActionSchema,
gitStatusInputSchema,
gitStatusResultSchema,
} from "./git";
describe("git contracts", () => {
it("parses git status input and trims cwd", () => {
const parsed = gitStatusInputSchema.parse({ cwd: " /tmp/repo " });
expect(parsed.cwd).toBe("/tmp/repo");
});
it("parses git pull input and trims cwd", () => {
const parsed = gitPullInputSchema.parse({ cwd: " /tmp/repo " });
expect(parsed.cwd).toBe("/tmp/repo");
});
it("parses git status result", () => {
const parsed = gitStatusResultSchema.parse({
branch: "feature/git-actions",
hasWorkingTreeChanges: true,
workingTree: {
files: [
{ path: "src/git.ts", insertions: 8, deletions: 2 },
{ path: "src/git.test.ts", insertions: 4, deletions: 1 },
],
insertions: 12,
deletions: 3,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
});
expect(parsed.branch).toBe("feature/git-actions");
expect(parsed.hasWorkingTreeChanges).toBe(true);
expect(parsed.workingTree.files[0]?.insertions).toBe(8);
expect(parsed.workingTree.files).toHaveLength(2);
});
it("accepts supported stacked actions", () => {
expect(gitStackedActionSchema.parse("commit")).toBe("commit");
expect(gitStackedActionSchema.parse("commit_push")).toBe("commit_push");
expect(gitStackedActionSchema.parse("commit_push_pr")).toBe("commit_push_pr");
});
it("parses stacked action input", () => {
const parsed = gitRunStackedActionInputSchema.parse({
cwd: "/tmp/repo",
action: "commit_push",
});
expect(parsed.action).toBe("commit_push");
});
it("accepts custom commit message input", () => {
const parsed = gitRunStackedActionInputSchema.parse({
cwd: "/tmp/repo",
action: "commit",
commitMessage: " chore: update git action modal ",
});
expect(parsed.commitMessage).toBe("chore: update git action modal");
});
it("parses stacked action result with metadata", () => {
const parsed = gitRunStackedActionResultSchema.parse({
action: "commit_push_pr",
commit: {
status: "created",
commitSha: "abc123",
subject: "Implement stacked git actions",
},
push: {
status: "pushed",
branch: "feature/git-actions",
upstreamBranch: "origin/feature/git-actions",
setUpstream: true,
},
pr: {
status: "created",
url: "https://github.com/pingdotgg/codething-mvp/pull/123",
number: 123,
baseBranch: "main",
headBranch: "feature/git-actions",
title: "Add stacked git actions workflow",
},
});
expect(parsed.commit.status).toBe("created");
expect(parsed.pr.number).toBe(123);
});
it("parses git pull result", () => {
const parsed = gitPullResultSchema.parse({
status: "pulled",
branch: "feature/my-branch",
upstreamBranch: "origin/feature/my-branch",
});
expect(parsed.status).toBe("pulled");
expect(parsed.branch).toBe("feature/my-branch");
});
});
+7 -89
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
// ── Existing branch/worktree Git API ─────────────────────────────────
// ── Input schemas ──
export const gitListBranchesInputSchema = z.object({
cwd: z.string().min(1),
@@ -8,7 +8,9 @@ export const gitListBranchesInputSchema = z.object({
export const gitCreateWorktreeInputSchema = z.object({
cwd: z.string().min(1),
/** Base branch to create the worktree from. */
branch: z.string().min(1),
/** New branch name to create in the worktree. */
newBranch: z.string().min(1),
path: z.string().min(1).optional(),
});
@@ -32,6 +34,8 @@ export const gitInitInputSchema = z.object({
cwd: z.string().min(1),
});
// ── Output schemas ──
export const gitBranchSchema = z.object({
name: z.string().min(1),
current: z.boolean(),
@@ -44,6 +48,8 @@ export const gitWorktreeSchema = z.object({
branch: z.string().min(1),
});
// ── Types ──
export type GitListBranchesInput = z.infer<typeof gitListBranchesInputSchema>;
export type GitBranch = z.infer<typeof gitBranchSchema>;
export type GitCreateWorktreeInput = z.infer<typeof gitCreateWorktreeInputSchema>;
@@ -61,91 +67,3 @@ export interface GitListBranchesResult {
export interface GitCreateWorktreeResult {
worktree: GitWorktree;
}
// ── Stacked action Git API ───────────────────────────────────────────
export const gitStatusInputSchema = z.object({
cwd: z.string().trim().min(1),
});
export const gitPullInputSchema = z.object({
cwd: z.string().trim().min(1),
});
export const gitStatusResultSchema = z.object({
branch: z.string().min(1).nullable(),
hasWorkingTreeChanges: z.boolean(),
workingTree: z.object({
files: z.array(
z.object({
path: z.string().min(1),
insertions: z.number().int().nonnegative(),
deletions: z.number().int().nonnegative(),
}),
),
insertions: z.number().int().nonnegative(),
deletions: z.number().int().nonnegative(),
}),
hasUpstream: z.boolean(),
aheadCount: z.number().int().nonnegative(),
behindCount: z.number().int().nonnegative(),
openPr: z
.object({
number: z.number().int().positive(),
title: z.string().min(1),
url: z.string().url(),
baseBranch: z.string().min(1),
headBranch: z.string().min(1),
})
.nullable(),
});
export const gitStackedActionSchema = z.enum(["commit", "commit_push", "commit_push_pr"]);
const gitCommitStepStatusSchema = z.enum(["created", "skipped_no_changes"]);
const gitPushStepStatusSchema = z.enum(["pushed", "skipped_not_requested", "skipped_up_to_date"]);
const gitPrStepStatusSchema = z.enum(["created", "opened_existing", "skipped_not_requested"]);
export const gitRunStackedActionInputSchema = z.object({
cwd: z.string().trim().min(1),
action: gitStackedActionSchema,
commitMessage: z.string().trim().min(1).max(10_000).optional(),
});
export const gitRunStackedActionResultSchema = z.object({
action: gitStackedActionSchema,
commit: z.object({
status: gitCommitStepStatusSchema,
commitSha: z.string().min(1).optional(),
subject: z.string().min(1).optional(),
}),
push: z.object({
status: gitPushStepStatusSchema,
branch: z.string().min(1).optional(),
upstreamBranch: z.string().min(1).optional(),
setUpstream: z.boolean().optional(),
}),
pr: z.object({
status: gitPrStepStatusSchema,
url: z.string().url().optional(),
number: z.number().int().positive().optional(),
baseBranch: z.string().min(1).optional(),
headBranch: z.string().min(1).optional(),
title: z.string().min(1).optional(),
}),
});
export type GitStatusInput = z.input<typeof gitStatusInputSchema>;
export type GitPullInput = z.input<typeof gitPullInputSchema>;
export type GitStatusResult = z.infer<typeof gitStatusResultSchema>;
export type GitStackedAction = z.infer<typeof gitStackedActionSchema>;
export type GitRunStackedActionInput = z.input<typeof gitRunStackedActionInputSchema>;
export type GitRunStackedActionResult = z.infer<typeof gitRunStackedActionResultSchema>;
export const gitPullResultSchema = z.object({
status: z.enum(["pulled", "skipped_up_to_date"]),
branch: z.string().min(1),
upstreamBranch: z.string().min(1).optional(),
});
export type GitPullResult = z.infer<typeof gitPullResultSchema>;
+2 -15
View File
@@ -7,13 +7,7 @@ import type {
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitPullInput,
GitPullResult,
GitRemoveWorktreeInput,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
GitStatusResult,
} from "./git";
import type {
ProviderEvent,
@@ -32,12 +26,12 @@ import type {
ProjectRemoveInput,
} from "./project";
import type {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput,
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
@@ -58,13 +52,12 @@ export interface NativeApi {
};
dialogs: {
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalClearInput) => Promise<void>;
clear: (input: TerminalThreadInput) => Promise<void>;
restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
@@ -92,20 +85,14 @@ export interface NativeApi {
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
openExternal: (url: string) => Promise<void>;
};
git: {
// Existing branch/worktree API
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
createBranch: (input: GitCreateBranchInput) => Promise<void>;
checkout: (input: GitCheckoutInput) => Promise<void>;
init: (input: GitInitInput) => Promise<void>;
// Stacked action API
pull: (input: GitPullInput) => Promise<GitPullResult>;
status: (input: GitStatusInput) => Promise<GitStatusResult>;
runStackedAction: (input: GitRunStackedActionInput) => Promise<GitRunStackedActionResult>;
};
contextMenu: {
show: <T extends string>(
+1 -1
View File
@@ -29,7 +29,7 @@ describe("resolveModelSlug", () => {
it("resolves only supported model options", () => {
for (const model of MODEL_OPTIONS) {
expect(resolveModelSlug(model.slug)).toBe(model.slug);
expect(resolveModelSlug(model)).toBe(model);
}
});
});
+8 -15
View File
@@ -1,22 +1,13 @@
export const MODEL_OPTIONS = [
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
{ slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark" },
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
{ slug: "gpt-5.2", name: "GPT-5.2" },
] as const;
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
export const MODEL_OPTIONS = ["gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2"] as const;
export const DEFAULT_MODEL = "gpt-5.3-codex";
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
export const MODEL_SLUG_ALIASES: Record<string, string> = {
"5.3": "gpt-5.3-codex",
"gpt-5.3": "gpt-5.3-codex",
"5.3-spark": "gpt-5.3-codex-spark",
"gpt-5.3-spark": "gpt-5.3-codex-spark",
};
export function normalizeModelSlug(model: string | null | undefined): ModelSlug | null {
export function normalizeModelSlug(model: string | null | undefined): string | null {
if (typeof model !== "string") {
return null;
}
@@ -26,14 +17,16 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
return null;
}
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
}
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
export function resolveModelSlug(model: string | null | undefined): string {
const normalized = normalizeModelSlug(model);
if (!normalized) {
return DEFAULT_MODEL;
}
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
return MODEL_OPTIONS.includes(normalized as (typeof MODEL_OPTIONS)[number])
? normalized
: DEFAULT_MODEL;
}
-59
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
providerEventSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
@@ -41,67 +40,9 @@ describe("providerSendTurnInputSchema", () => {
effort: " high ",
});
expect(parsed.input).toBe("summarize this repo");
expect(parsed.attachments).toEqual([]);
expect(parsed.model).toBe("gpt-5.2-codex");
expect(parsed.effort).toBe("high");
});
it("accepts image-only turns", () => {
const parsed = providerSendTurnInputSchema.parse({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "diagram.png",
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
},
],
});
expect(parsed.input).toBeUndefined();
expect(parsed.attachments).toHaveLength(1);
});
it("rejects turns with neither text nor attachments", () => {
expect(() =>
providerSendTurnInputSchema.parse({
sessionId: "sess_1",
}),
).toThrow();
});
it("rejects non-image data urls", () => {
expect(() =>
providerSendTurnInputSchema.parse({
sessionId: "sess_1",
attachments: [
{
type: "image",
name: "not-image.txt",
mimeType: "text/plain",
sizeBytes: 25,
dataUrl: "data:text/plain;base64,QQ==",
},
],
}),
).toThrow();
});
it("rejects more than the max attachment count", () => {
expect(() =>
providerSendTurnInputSchema.parse({
sessionId: "sess_1",
attachments: Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
type: "image" as const,
name: `image-${index}.png`,
mimeType: "image/png",
sizeBytes: 1_024,
dataUrl: "data:image/png;base64,AAAA",
})),
}),
).toThrow();
});
});
describe("providerEventSchema", () => {
+5 -42
View File
@@ -55,48 +55,14 @@ export const providerSessionStartInputSchema = z.object({
});
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
export const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
export const providerSendTurnImageAttachmentSchema = z.object({
type: z.literal("image"),
name: z.string().trim().min(1).max(255),
mimeType: z
.string()
.trim()
.min(1)
.max(100)
.regex(/^image\//i, "mimeType must be an image/* MIME type"),
sizeBytes: z.number().int().min(1).max(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
dataUrl: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
export const providerSendTurnInputSchema = z.object({
sessionId: z.string().min(1),
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),
model: z.string().trim().min(1).optional(),
effort: z.string().trim().min(1).optional(),
});
export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type", [
providerSendTurnImageAttachmentSchema,
]);
export const providerSendTurnInputSchema = z
.object({
sessionId: z.string().min(1),
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
attachments: z
.array(providerSendTurnAttachmentInputSchema)
.max(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)
.default([]),
model: z.string().trim().min(1).optional(),
effort: z.string().trim().min(1).optional(),
})
.superRefine((value, ctx) => {
if (!value.input && value.attachments.length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Either input text or at least one attachment is required",
path: ["input"],
});
}
});
export const providerTurnStartResultSchema = z.object({
threadId: z.string().min(1),
turnId: z.string().min(1),
@@ -144,9 +110,6 @@ export type ProviderApprovalDecision = z.infer<typeof providerApprovalDecisionSc
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
export type ProviderSession = z.infer<typeof providerSessionSchema>;
export type ProviderSessionStartInput = z.input<typeof providerSessionStartInputSchema>;
export type ProviderSendTurnImageAttachment = z.infer<typeof providerSendTurnImageAttachmentSchema>;
export type ProviderSendTurnAttachment = z.infer<typeof providerSendTurnAttachmentInputSchema>;
export type ProviderSendTurnAttachmentInput = z.input<typeof providerSendTurnAttachmentInputSchema>;
export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
export type ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more