Compare commits

..
Author SHA1 Message Date
Julius Marminge fea186cf93 Show pulsing terminal icon for active thread processes
- Replace terminal text badge with a right-aligned `TerminalIcon`
- Add accessible label/title: "Terminal process running"
- Keep pulse animation and terminal-active color styling
2026-02-12 22:22:24 -08:00
Julius Marminge 804572c8ff Tighten test fixtures for terminal options and event typing
- Pass subprocess test options only when defined in `terminalManager` tests
- Narrow web store terminal event fixtures to `started`/`activity` event shapes
2026-02-12 22:20:01 -08:00
Julius Marmingeandcodex ddc4a93c36 Emit terminal activity events from subprocess polling
- Add cross-platform subprocess polling in `TerminalManager` and emit `activity` events when child-process state changes
- Update web store to derive `runningTerminalIds` from `activity.hasRunningSubprocess` instead of start/restart events
- Extend terminal contracts and tests to include the new `activity` event type

Co-authored-by: codex <[email protected]>
2026-02-12 22:20:01 -08:00
Julius Marminge 901579233c Close terminal session when hiding terminal panel
- Attempt `api.terminal.close` when toggling an open terminal off
- Fall back to sending `exit` if close is unavailable or fails
- Include `api` in callback dependencies to keep behavior current
2026-02-12 22:20:01 -08:00
Julius Marminge d27b08bae6 Migrate legacy terminal history to terminal-scoped log path
- On open, read legacy transcript files and write them to the new terminal-scoped history path
- Remove legacy files after migration and warn if cleanup fails
- Update tests to assert migration, content preservation, and legacy file removal
2026-02-12 22:20:01 -08:00
Julius Marminge 485747b892 Track thread terminal running state across UI and store
- add `terminalRunning` to thread state and hydration defaults
- apply terminal events in reducer to sync running/open state (close drawer on exit)
- wire drawer running-state callbacks and show a Terminal status pill in sidebar
- extend store and persistence tests for terminal running/exited behavior
2026-02-12 22:20:01 -08:00
Julius Marminge 15380f2b5f Add dev runner for deterministic multi-instance port offsets
- Route `dev*` scripts through `scripts/dev-runner.mjs` to compute shared server/web port offsets
- Support `T3CODE_DEV_INSTANCE` (hashed or numeric) and explicit `T3CODE_PORT_OFFSET`
- Document multi-instance usage and allow server `VITE_DEV_SERVER_URL` override
2026-02-12 21:41:42 -08:00
Julius Marminge 48b1f7c388 current color github icon 2026-02-12 21:27:50 -08:00
Julius Marminge b26e2d192e Clear terminal history on close and prefer git cwd
- Pass `deleteHistory: true` when closing a terminal
- Fallback path now clears terminal before sending `exit`
- Use `gitCwd` as terminal cwd when available
2026-02-12 21:24:49 -08:00
Julius Marminge e6d6450728 Use terminal close API with exit fallback in ChatView
- Call `api.terminal.close` when available when closing a terminal tab
- Fall back to writing `exit\n` to preserve compatibility with older/uninitialized terminals
2026-02-12 21:24:49 -08:00
Julius Marmingeandmacroscopeapp[bot] 739205872f Update apps/web/src/components/ThreadTerminalDrawer.tsx
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-02-12 21:24:49 -08:00
Julius Marminge 07210d0c91 Migrate thread terminals to grouped layout model
- Replace `terminalLayout`/`splitTerminalIds` with `terminalGroups` and `activeTerminalGroupId`
- Update terminal drawer UI to render grouped splits with a terminal sidebar
- Bump persisted web state to v7 with legacy v6 migration coverage in tests
2026-02-12 21:24:49 -08:00
Julius Marminge ee463f6b76 Add close-terminal actions and state handling in thread drawer
- Add terminal close controls in tab and split terminal views
- Send `exit` before closing and update active terminal/focus in chat state
- Add reducer support and tests for closing tabs, split fallback, and final-terminal drawer hide
2026-02-12 21:24:49 -08:00
Julius Marminge 800eb3b547 Add per-thread multi-terminal sessions and UI state
- Support multiple terminal IDs per thread across contracts, server manager, and WS handling
- Persist terminal history per terminal ID and allow closing all terminals for a thread
- Update web thread state and terminal drawer to create, split, and switch active terminals
- Expand tests for multi-terminal behavior and terminal ID propagation
2026-02-12 21:24:49 -08:00
Julius Marminge 854068dc56 lint 2026-02-12 19:36:40 -08:00
Julius Marminge ccaa58e393 terminal links 2026-02-12 19:36:40 -08:00
Julius Marminge 6d6991bca1 Refine pending approval panel styles
- Constrain pending approval cards to a centered max-width section with updated padding
- Improve light/dark theme contrast for approval detail text and action buttons
- Keep existing approval actions and behavior unchanged while updating visual hierarchy
2026-02-12 18:45:46 -08:00
Julius Marminge 057770ebfc whoop 2026-02-12 18:37:41 -08:00
Julius Marminge 052314b65f Move approval derivation and thread visit tracking into core session log
- Moved pending-approval extraction to `session-logic` and reused it in `Sidebar` status rendering
- Added `lastVisitedAt` threading persistence through schema, types, hydrate/serialize paths, and tests
- Updated sidebar thread pills for completed/approval states and pulsing working status
- Marked active thread visits and completion visibility timestamps on selection and `turn/completed`
- Co-authored-by: codex <[email protected]>
2026-02-12 18:37:41 -08:00
Julius Marminge 1dca7012b5 Merge pull request #15 from pingdotgg/images 2026-02-12 15:52:03 -08:00
Julius Marminge ea16f6fdd7 spark 2026-02-12 15:49:22 -08:00
Julius Marminge 73bc60ef8a simp 2026-02-12 15:46:34 -08:00
Julius Marminge 86e7bd000c Align Electron drag headers and sidebar branding spacing
- Update `ChatView` so Electron uses a fixed 52px drag titlebar, including empty-thread state.
- Make `DiffPanel` header use the same Electron drag-region sizing.
- Consolidate Sidebar drag-region into branding row and remove separate spacer div.
- Co-authored-by: codex <[email protected]>
2026-02-12 15:43:05 -08:00
Julius Marminge 1cad53dae4 Allow attachments field in ChatView 2026-02-12 15:37:30 -08:00
Julius Marminge 760f15f2f9 Expand sendTurn attachment handling 2026-02-12 15:33:33 -08:00
Julius Marminge 3cf58f80d1 Add image paste drag drop dialog 2026-02-12 15:22:03 -08:00
Julius Marminge 44f3b3cb7c Merge pull request #13 from pingdotgg/codex/add-github-commit-push-ui 2026-02-12 14:53:53 -08:00
Julius Marmingeandcodex dd920846b9 Show git step details only on failure
- Render `step.detail` only for failed step states
- Keep failed detail text styled in warning red tone

Co-authored-by: codex <[email protected]>
2026-02-12 14:47:51 -08:00
Julius Marmingeandcodex b7af14ad3f Rework chat header actions and GitActions styling
- Remove branch badge and terminal toggle from ChatView header
- Keep GitActionsControl in the header action area
- Adjust GitActionsControl button styles to emphasize completed action state

Co-authored-by: codex <[email protected]>
2026-02-12 14:44:51 -08:00
Julius Marminge 8f6cd244e7 Use gpt-5.3-codex-spark for git text generation
- Add `gpt-5.3-codex-spark` with medium reasoning effort to commit/PR generation calls
- Inject process runner into `CodexTextGenerator` and add tests for model selection and failure passthrough
- Update PR modal to use status/result PR URLs and keep a single Open PR action path
2026-02-12 14:42:15 -08:00
Julius Marminge 95c8463706 Remove redundant commit message hint from Git actions modal
- Remove the “Leave this empty…” helper text under the commit message field
- Keep AI-generated commit message behavior unchanged
2026-02-12 14:30:43 -08:00
Julius Marminge 5a0f5e9f5e Improve Git action modal state and PR link handling
- Add an `Open PR` button in the result footer and handle link-open errors
- Populate the commit message field with the generated subject when available
- Refine disabled/selected action option styling while git actions are running
2026-02-12 14:28:45 -08:00
Julius Marmingeandcodex c643de8ba7 Enable safe external PR link opening in desktop app
- add desktop IPC handler to validate and open http(s) URLs via Electron shell
- expose `shell.openExternal` in shared NativeApi contracts and web bridge
- route Git PR opening and native API reads through the new `useNativeApi` hook

Co-authored-by: codex <[email protected]>
2026-02-12 14:24:41 -08:00
Julius Marmingeandcodex 9accd1ffb7 Improve git action menu and modal workflow
- Split Git actions into context-aware Commit, Push, and PR menu items
- Add modal action selection with clearer availability and disabled-state guidance
- Migrate git status and immediate actions to React Query and add a custom GitHub icon

Co-authored-by: codex <[email protected]>
2026-02-12 14:12:45 -08:00
Julius Marminge 62cc55ab06 Extract Git actions UI into dedicated GitActionsControl component
- Move git menu, modal, and stacked action logic out of `ChatView`
- Render a new `GitActionsControl` wired with `api` and `gitCwd`
2026-02-12 12:54:36 -08:00
Julius Marmingeandcodex 36bc85f54d Add Git action modal with custom commit message support
- Add a Git action confirmation modal with live commit/push/PR progress states
- Accept optional `commitMessage` input and skip AI message generation when provided
- Expand server and contracts tests for custom commit message handling

Co-authored-by: codex <[email protected]>
2026-02-12 12:22:05 -08:00
Julius Marminge 3c939e8e69 Use Lucide icons for ChatView git action menu
- Replace custom inline SVGs with Lucide commit, push, and GitHub icons
- Keep git action behavior unchanged while applying minor style cleanup
2026-02-12 11:20:38 -08:00
Julius Marminge 6fc632f9a1 Harden git and terminal flows and surface open PR status
- include open PR metadata in git status with graceful `gh` failure handling
- centralize git command execution in `GitCoreService` via `runProcess` with truncation support
- add PTY spawn-helper permission fixes, shell fallback retries, and tests for new behavior
2026-02-12 11:15:11 -08:00
Julius Marmingeandcodex ae296e59a4 Merge origin/main into codex/add-github-commit-push-ui
Co-authored-by: codex <[email protected]>
2026-02-12 02:18:19 -08:00
Julius Marminge 36cdceb4bf Fix ChatView height scroll 2026-02-12 02:12:40 -08:00
Julius Marmingeandcodex 3bfda73dce Address PR review comments for terminal integration
Co-authored-by: codex <[email protected]>
2026-02-12 02:12:40 -08:00
Julius Marminge 0133d9582c Improve terminal resizing and perf 2026-02-12 02:12:40 -08:00
Julius Marminge e0df5d5b58 Update status bar actions state 2026-02-11 18:08:16 -08:00
Julius Marminge 3697765f4d Disable git actions without changes 2026-02-11 18:02:32 -08:00
Julius Marmingeandcodex 533dbdfbda Address PR review feedback for git actions
Co-authored-by: codex <[email protected]>
2026-02-11 17:56:16 -08:00
Julius Marminge 98eb87f5cd Extract git core interfaces 2026-02-11 17:40:23 -08:00
Julius Marmingeandcodex 1768d31669 Merge origin/main into codex/add-github-commit-push-ui
Co-authored-by: codex <[email protected]>
2026-02-11 17:21:25 -08:00
Julius Marminge 39390c0b9a Add stacked git actions flow 2026-02-11 16:34:22 -08:00
54 changed files with 7251 additions and 768 deletions

No files matched your search

+13
View File
@@ -49,6 +49,9 @@ 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
@@ -67,6 +70,16 @@ 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:
+27 -1
View File
@@ -5,7 +5,7 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu } from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { fixPath } from "./fixPath";
@@ -13,6 +13,7 @@ fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
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");
@@ -159,6 +160,31 @@ 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 {
+2
View File
@@ -2,6 +2,7 @@ import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
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", {
@@ -9,4 +10,5 @@ contextBridge.exposeInMainWorld("desktopBridge", {
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
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=http://localhost:5173 bun run src/index.ts",
"dev": "VITE_DEV_SERVER_URL=${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",
+117 -1
View File
@@ -1,11 +1,42 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } 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();
@@ -75,3 +106,88 @@ 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.");
});
});
+28 -8
View File
@@ -257,20 +257,40 @@ 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: [] }>;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
>;
model?: string;
effort?: string;
} = {
threadId: context.session.threadId,
input: [
{
type: "text",
text: input.input,
text_elements: [],
},
],
input: turnInput,
};
const normalizedModel = normalizeCodexModelSlug(input.model);
if (normalizedModel) {
+252
View File
@@ -0,0 +1,252 @@
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(),
};
}
}
+35
View File
@@ -0,0 +1,35 @@
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>;
}
+82
View File
@@ -5,6 +5,7 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import {
GitCoreService,
checkoutGitBranch,
createGitBranch,
createGitWorktree,
@@ -435,4 +436,85 @@ 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");
});
});
});
+438 -241
View File
@@ -1,18 +1,22 @@
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
GitCheckoutInput,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitRemoveWorktreeInput,
import {
gitStatusInputSchema,
gitStatusResultSchema,
type GitCheckoutInput,
type GitCreateBranchInput,
type GitCreateWorktreeInput,
type GitCreateWorktreeResult,
type GitInitInput,
type GitListBranchesInput,
type GitListBranchesResult,
type GitRemoveWorktreeInput,
type GitStatusInput,
type GitStatusResult,
} from "@t3tools/contracts";
import { type ProcessRunResult, runProcess } from "./processRunner";
export interface TerminalCommandInput {
command: string;
@@ -21,95 +25,419 @@ export interface TerminalCommandInput {
maxOutputBytes?: number;
}
export interface TerminalCommandResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
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;
}
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
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,
};
}
/** 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 };
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
ahead: Number(match[1] ?? "0"),
behind: Number(match[2] ?? "0"),
};
}
/** 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,
env: process.env,
stdio: ["ignore", "pipe", "pipe"],
});
const maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES;
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();
}, 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]`;
}
resolve({ stdout, stderr, code: code ?? null, signal: signal ?? null, timedOut });
});
});
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,
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
openPr: null,
});
}
async statusDetails(cwd: string): Promise<GitStatusDetails> {
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let hasWorkingTreeChanges = false;
for (const line of stdout.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;
}
}
return {
branch,
upstreamRef,
hasWorkingTreeChanges,
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 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;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
});
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] = 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,
}),
]);
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) => {
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 };
}
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",
});
}
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
await executeGit(input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
}
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> {
@@ -122,177 +450,46 @@ export async function runTerminalCommand(
const args =
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
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,
});
});
const result = await runProcess(shellPath, args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? 30_000,
allowNonZeroExit: true,
maxBufferBytes: maxOutputBytes,
outputMode: "truncate",
});
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> {
const result = await runGit(["branch", "--no-color"], input.cwd, 10_000);
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 };
return defaultGitCoreService.listBranches(input);
}
export async function createGitWorktree(
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);
// 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,
},
};
return defaultGitCoreService.createWorktree(input);
}
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
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");
}
await defaultGitCoreService.removeWorktree(input);
}
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
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");
}
await defaultGitCoreService.createBranch(input);
}
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
const result = await runGit(["checkout", input.branch], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git checkout failed");
}
await defaultGitCoreService.checkoutBranch(input);
}
export async function initGitRepo(input: GitInitInput): Promise<void> {
const result = await runGit(["init"], input.cwd, 10_000);
if (result.code !== 0) {
throw new Error(result.stderr.trim() || "git init failed");
}
await defaultGitCoreService.initRepo(input);
}
+490
View File
@@ -0,0 +1,490 @@
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("opens existing PR 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 feature/existing-pr --web")),
).toBe(true);
});
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);
});
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");
});
});
+506
View File
@@ -0,0 +1,506 @@
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,
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) {
await this.openPrInBrowser(cwd, branch);
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);
await this.openPrInBrowser(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 openPrInBrowser(cwd: string, branch: string): Promise<void> {
try {
await this.runGh(cwd, ["pr", "view", branch, "--web"]);
} catch {
// Opening the browser is best-effort.
}
}
private async findOpenPr(
cwd: string,
branch: string,
): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [
"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."))
);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
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);
});
});
+271
View File
@@ -0,0 +1,271 @@
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
@@ -0,0 +1,54 @@
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();
});
});
+60 -1
View File
@@ -1,3 +1,7 @@
import fs from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import * as nodePty from "node-pty";
export interface PtyExitEvent {
@@ -26,6 +30,57 @@ 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) {}
@@ -67,12 +122,16 @@ 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,
rows: input.rows,
env: input.env,
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
name:
globalThis.process.platform === "win32"
? "xterm-color"
: "xterm-256color",
});
return new NodePtyProcess(ptyProcess);
}
+166 -8
View File
@@ -2,10 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type {
TerminalEvent,
TerminalOpenInput,
} from "@t3tools/contracts";
import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
@@ -62,10 +59,15 @@ 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;
@@ -104,10 +106,26 @@ 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[] = [];
@@ -117,7 +135,14 @@ describe("TerminalManager", () => {
}
});
function makeManager(historyLineLimit = 5) {
function makeManager(
historyLineLimit = 5,
options: {
shellResolver?: () => string;
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
subprocessPollIntervalMs?: number;
} = {},
) {
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
tempDirs.push(logsDir);
const ptyAdapter = new FakePtyAdapter();
@@ -125,7 +150,11 @@ describe("TerminalManager", () => {
logsDir,
ptyAdapter,
historyLineLimit,
shellResolver: () => "/bin/bash",
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
...(options.subprocessPollIntervalMs
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
: {}),
});
return { logsDir, ptyAdapter, manager };
}
@@ -136,6 +165,7 @@ describe("TerminalManager", () => {
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);
@@ -159,6 +189,27 @@ 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[] = [];
@@ -176,6 +227,14 @@ 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();
});
@@ -222,6 +281,42 @@ 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());
@@ -254,15 +349,78 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
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 () => {
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(legacyPath)).toBe(true);
expect(fs.existsSync(nextPath)).toBe(true);
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
expect(fs.existsSync(legacyPath)).toBe(false);
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();
});
+482 -83
View File
@@ -3,25 +3,31 @@ 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;
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
export interface TerminalManagerEvents {
event: [event: TerminalEvent];
@@ -32,10 +38,13 @@ 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;
@@ -48,6 +57,7 @@ interface TerminalSessionState {
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
}
function defaultShellResolver(): string {
@@ -57,6 +67,145 @@ 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");
@@ -77,6 +226,14 @@ 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}`;
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string;
@@ -88,6 +245,10 @@ 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 = {}) {
@@ -97,6 +258,9 @@ 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 });
}
@@ -105,12 +269,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
const existing = this.sessions.get(input.threadId);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
const existing = this.sessions.get(sessionKey);
if (!existing) {
await this.flushPersistQueue(input.threadId);
const history = await this.readHistory(input.threadId);
await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId, input.terminalId);
const session: TerminalSessionState = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
@@ -123,8 +289,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(input.threadId, session);
this.sessions.set(sessionKey, session);
this.startSession(session, input, "started");
return this.snapshot(session);
}
@@ -133,10 +300,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.stopProcess(existing);
existing.cwd = input.cwd;
existing.history = "";
await this.persistHistory(existing.threadId, existing.history);
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.history = "";
await this.persistHistory(existing.threadId, existing.history);
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
}
if (!existing.process) {
@@ -157,18 +324,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async write(raw: TerminalWriteInput): Promise<void> {
const input = terminalWriteInputSchema.parse(raw);
const session = this.requireSession(input.threadId);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.process.write(input.data);
}
async resize(raw: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {
async resize(raw: TerminalResizeInput): Promise<void> {
const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId);
const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
}
session.cols = input.cols;
session.rows = input.rows;
@@ -176,16 +347,17 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.process.resize(input.cols, input.rows);
}
async clear(raw: TerminalThreadInput): Promise<void> {
const input = terminalThreadInputSchema.parse(raw);
async clear(raw: TerminalClearInput): Promise<void> {
const input = terminalClearInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId);
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, session.history);
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
type: "cleared",
threadId: input.threadId,
terminalId: input.terminalId,
createdAt: new Date().toISOString(),
});
});
@@ -196,10 +368,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd);
let session = this.sessions.get(input.threadId);
const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
if (!session) {
session = {
threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd,
status: "starting",
pid: null,
@@ -212,15 +386,16 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
};
this.sessions.set(input.threadId, session);
this.sessions.set(sessionKey, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
}
session.history = "";
await this.persistHistory(input.threadId, session.history);
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.startSession(session, input, "restarted");
return this.snapshot(session);
});
@@ -229,23 +404,40 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async close(raw: TerminalCloseInput): Promise<void> {
const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
const session = this.sessions.get(input.threadId);
if (session) {
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) {
this.stopProcess(session);
this.sessions.delete(input.threadId);
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
}
await this.flushPersistQueue(input.threadId);
await Promise.all(
threadSessions.map((session) =>
this.flushPersistQueue(session.threadId, session.terminalId),
),
);
if (input.deleteHistory) {
await this.deleteHistory(input.threadId);
await this.deleteAllHistoryForThread(input.threadId);
}
this.updateSubprocessPollingState();
});
}
dispose(): void {
for (const session of this.sessions.values()) {
this.stopSubprocessPolling();
const sessions = [...this.sessions.values()];
this.sessions.clear();
for (const session of sessions) {
this.stopProcess(session);
}
this.sessions.clear();
for (const timer of this.persistTimers.values()) {
clearTimeout(timer);
}
@@ -268,18 +460,46 @@ 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 {
ptyProcess = this.ptyAdapter.spawn({
shell,
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: process.env,
});
const shellCandidates = resolveShellCandidates(this.shellResolver);
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: process.env,
});
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());
}
session.process = ptyProcess;
session.pid = ptyProcess.pid;
session.status = "running";
@@ -290,9 +510,11 @@ 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),
});
@@ -307,17 +529,22 @@ 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 } : {}),
});
}
}
@@ -325,10 +552,11 @@ 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.history);
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(),
data,
});
@@ -338,6 +566,7 @@ 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;
@@ -345,10 +574,12 @@ 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 {
@@ -357,6 +588,7 @@ 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 {
@@ -365,9 +597,11 @@ 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 {
@@ -377,69 +611,87 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.unsubscribeExit = null;
}
private queuePersist(threadId: string, history: string): void {
this.pendingPersistHistory.set(threadId, history);
this.schedulePersist(threadId);
private queuePersist(threadId: string, terminalId: string, history: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
this.pendingPersistHistory.set(persistenceKey, history);
this.schedulePersist(threadId, terminalId);
}
private async persistHistory(threadId: string, history: string): Promise<void> {
this.clearPersistTimer(threadId);
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, history);
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 enqueuePersistWrite(threadId: string, history: string): Promise<void> {
private enqueuePersistWrite(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId), history, "utf8");
await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
};
const previous = this.persistQueues.get(threadId) ?? Promise.resolve();
const previous = this.persistQueues.get(persistenceKey) ?? 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(threadId, next);
this.persistQueues.set(persistenceKey, next);
const finalized = next.finally(() => {
if (this.persistQueues.get(threadId) === next) {
this.persistQueues.delete(threadId);
if (this.persistQueues.get(persistenceKey) === next) {
this.persistQueues.delete(persistenceKey);
}
if (this.pendingPersistHistory.has(threadId) && !this.persistTimers.has(threadId)) {
this.schedulePersist(threadId);
if (
this.pendingPersistHistory.has(persistenceKey) &&
!this.persistTimers.has(persistenceKey)
) {
this.schedulePersist(threadId, terminalId);
}
});
void finalized.catch(() => undefined);
return finalized;
}
private schedulePersist(threadId: string): void {
if (this.persistTimers.has(threadId)) return;
private schedulePersist(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
if (this.persistTimers.has(persistenceKey)) return;
const timer = setTimeout(() => {
this.persistTimers.delete(threadId);
const pendingHistory = this.pendingPersistHistory.get(threadId);
this.persistTimers.delete(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(threadId);
void this.enqueuePersistWrite(threadId, pendingHistory);
this.pendingPersistHistory.delete(persistenceKey);
void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}, this.persistDebounceMs);
this.persistTimers.set(threadId, timer);
this.persistTimers.set(persistenceKey, timer);
}
private clearPersistTimer(threadId: string): void {
const timer = this.persistTimers.get(threadId);
private clearPersistTimer(threadId: string, terminalId: string): void {
const persistenceKey = toSessionKey(threadId, terminalId);
const timer = this.persistTimers.get(persistenceKey);
if (!timer) return;
clearTimeout(timer);
this.persistTimers.delete(threadId);
this.persistTimers.delete(persistenceKey);
}
private async readHistory(threadId: string): Promise<string> {
private async readHistory(threadId: string, terminalId: string): Promise<string> {
const nextPath = this.historyPath(threadId, terminalId);
try {
const raw = await fs.promises.readFile(this.historyPath(threadId), "utf8");
const raw = await fs.promises.readFile(nextPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(this.historyPath(threadId), capped, "utf8");
await fs.promises.writeFile(nextPath, capped, "utf8");
}
return capped;
} catch (error) {
@@ -448,12 +700,26 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
if (terminalId !== DEFAULT_TERMINAL_ID) {
return "";
}
const legacyPath = this.legacyHistoryPath(threadId);
try {
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
const raw = await fs.promises.readFile(legacyPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) {
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
// 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),
});
}
return capped;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -463,31 +729,34 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
private async deleteHistory(threadId: string): Promise<void> {
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 }));
}
try {
await Promise.all([
fs.promises.rm(this.historyPath(threadId), { force: true }),
fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }),
]);
await Promise.all(deletions);
} 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): Promise<void> {
this.clearPersistTimer(threadId);
private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
while (true) {
const pendingHistory = this.pendingPersistHistory.get(threadId);
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(threadId);
await this.enqueuePersistWrite(threadId, pendingHistory);
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}
const pending = this.persistQueues.get(threadId);
const pending = this.persistQueues.get(persistenceKey);
if (!pending) {
return;
}
@@ -495,6 +764,86 @@ 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 {
@@ -510,10 +859,55 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
}
}
private requireSession(threadId: string): TerminalSessionState {
const session = this.sessions.get(threadId);
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));
if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}`);
throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
}
return session;
}
@@ -521,6 +915,7 @@ 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,
@@ -535,8 +930,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emit("event", event);
}
private historyPath(threadId: string): string {
return path.join(this.logsDir, `${toSafeThreadId(threadId)}.log`);
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 legacyHistoryPath(threadId: string): string {
+110 -8
View File
@@ -7,14 +7,21 @@ import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts";
import {
DEFAULT_TERMINAL_ID,
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";
@@ -29,10 +36,16 @@ 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,
@@ -41,11 +54,12 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null,
updatedAt: now,
};
this.sessions.set(input.threadId, snapshot);
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "started",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
@@ -54,7 +68,8 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
}
async write(input: TerminalWriteInput): Promise<void> {
const existing = this.sessions.get(input.threadId);
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const existing = this.sessions.get(this.key(input.threadId, terminalId));
if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`);
}
@@ -62,19 +77,22 @@ 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: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {}
async resize(_input: TerminalResizeInput): Promise<void> {}
async clear(input: TerminalThreadInput): Promise<void> {
async clear(input: TerminalClearInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
queueMicrotask(() => {
this.emit("event", {
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(),
});
});
@@ -82,8 +100,10 @@ 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,
@@ -92,11 +112,12 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null,
updatedAt: now,
};
this.sessions.set(input.threadId, snapshot);
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => {
this.emit("event", {
type: "restarted",
threadId: input.threadId,
terminalId,
createdAt: now,
snapshot,
});
@@ -105,7 +126,15 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
}
async close(input: TerminalCloseInput): Promise<void> {
this.sessions.delete(input.threadId);
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);
}
}
}
dispose(): void {}
@@ -180,6 +209,10 @@ 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> {
@@ -190,6 +223,7 @@ 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 }
: {}),
@@ -335,6 +369,7 @@ 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",
@@ -371,6 +406,7 @@ describe("WebSocket Server", () => {
const manualEvent: TerminalEvent = {
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "manual test output\n",
};
@@ -511,6 +547,72 @@ describe("WebSocket Server", () => {
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
});
it("responds to git.status via the git manager", async () => {
const gitManager = {
status: vi.fn().mockResolvedValue({
branch: "feature/test",
hasWorkingTreeChanges: true,
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,
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 () => {
const stateDir = makeTempDir("t3code-ws-prune-state-");
const existing = makeTempDir("t3code-ws-existing-project-");
+9
View File
@@ -20,6 +20,7 @@ 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,
@@ -53,6 +54,7 @@ export interface ServerOptions {
devUrl?: string | undefined;
logWebSocketEvents?: boolean | undefined;
projectRegistry?: ProjectRegistry | undefined;
gitManager?: GitManager | undefined;
terminalManager?: TerminalManager | undefined;
authToken?: string | undefined;
}
@@ -74,6 +76,7 @@ export function createServer(options: ServerOptions) {
devUrl,
logWebSocketEvents: explicitLogWsEvents,
projectRegistry: providedRegistry,
gitManager: providedGitManager,
terminalManager: providedTerminalManager,
authToken,
} = options;
@@ -81,6 +84,7 @@ 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 =
@@ -335,6 +339,11 @@ export function createServer(options: ServerOptions) {
return undefined;
}
case WS_METHODS.gitStatus:
return gitManager.status(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);
+18 -10
View File
@@ -1,18 +1,18 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useMemo, useRef } from "react";
import { useEffect, 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 } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi";
function EventRouter() {
const api = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
const { dispatch } = useStore();
const activeAssistantItemRef = useRef<string | null>(null);
@@ -30,11 +30,9 @@ function EventRouter() {
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
if (event.type !== "exited") return;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: event.threadId,
open: false,
type: "APPLY_TERMINAL_EVENT",
event,
});
});
}, [api, dispatch]);
@@ -93,6 +91,16 @@ 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: [],
@@ -109,7 +117,7 @@ function AutoProjectBootstrap() {
}
function DesktopProjectBootstrap() {
const api = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
const { dispatch } = useStore();
const bootstrappedRef = useRef(false);
@@ -159,7 +167,7 @@ function DesktopProjectBootstrap() {
}
function Layout() {
const api = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
const { state } = useStore();
if (!api) {
+8 -4
View File
@@ -1,9 +1,9 @@
import type { GitBranch } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { readNativeApi } from "../session-logic";
import { useStore } from "../store";
import { useNativeApi } from "../hooks/useNativeApi";
interface BranchToolbarProps {
envMode: "local" | "worktree";
@@ -13,7 +13,7 @@ interface BranchToolbarProps {
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
const { state, dispatch } = useStore();
const api = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
@@ -254,7 +254,11 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
<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"}
{branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: "default"}
</span>
)}
</button>
+494 -163
View File
@@ -1,9 +1,13 @@
import {
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type ProviderSendTurnAttachmentInput,
type ProviderApprovalDecision,
type ProviderEvent,
} from "@t3tools/contracts";
import {
type ClipboardEvent,
type DragEvent,
type FormEvent,
Fragment,
type KeyboardEvent,
@@ -25,19 +29,22 @@ import {
resolveModelSlug,
} from "../model-logic";
import {
derivePendingApprovals,
derivePhase,
deriveTimelineEntries,
deriveWorkLogEntries,
formatDuration,
formatElapsed,
formatTimestamp,
readNativeApi,
} from "../session-logic";
import { useStore } from "../store";
import type { ChatImageAttachment } from "../types";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import { isTerminalToggleShortcut } from "../terminal-shortcuts";
import ChatMarkdown from "./ChatMarkdown";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { useNativeApi } from "../hooks/useNativeApi";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -56,6 +63,9 @@ function editorLabel(editor: (typeof EDITORS)[number]): string {
const LAST_EDITOR_KEY = "t3code:last-editor";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
@@ -64,13 +74,6 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
return "text-muted-foreground/40";
}
interface PendingApprovalCard {
requestId: string;
requestKind: "command" | "file-change";
createdAt: string;
detail?: string;
}
type SessionContinuityState = "resumed" | "new" | "fallback_new";
interface EnsuredSessionInfo {
@@ -79,61 +82,40 @@ interface EnsuredSessionInfo {
continuityState: SessionContinuityState;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") return undefined;
return value as Record<string, unknown>;
interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
interface ExpandedImagePreview {
src: string;
name: string;
}
function approvalDetail(event: ProviderEvent): string | undefined {
const payload = asRecord(event.payload);
const command = asString(payload?.command);
if (command) return command;
return asString(payload?.reason);
}
function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {
const pending = new Map<string, PendingApprovalCard>();
const ordered = [...events].toReversed();
for (const event of ordered) {
if (event.method === "session/closed" || event.method === "session/exited") {
pending.clear();
continue;
}
const requestId = event.requestId ?? asString(asRecord(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 readFileAsDataUrl(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
if (typeof reader.result === "string") {
resolve(reader.result);
return;
}
reject(new Error("Could not read image data."));
});
reader.addEventListener("error", () => {
reject(reader.error ?? new Error("Failed to read image."));
});
reader.readAsDataURL(file);
});
}
export default function ChatView() {
const { state, dispatch } = useStore();
const api = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
const [prompt, setPrompt] = useState("");
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [isSending, setIsSending] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
@@ -151,6 +133,8 @@ export default function ChatView() {
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const messagesEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const dragDepthRef = useRef(0);
const modelMenuRef = useRef<HTMLDivElement>(null);
const editorMenuRef = useRef<HTMLDivElement>(null);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -256,14 +240,19 @@ export default function ChatView() {
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
} as const);
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const envLocked = Boolean(
activeThread &&
(activeThread.messages.length > 0 ||
(activeThread.session !== null && activeThread.session.status !== "closed")),
);
const terminalShortcutHint = navigator.platform.includes("Mac")
? "\u2318J"
: "Ctrl+J";
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
for (const image of images) {
if (!image.previewUrl) continue;
URL.revokeObjectURL(image.previewUrl);
}
}, []);
const focusComposer = useCallback(() => {
const textarea = textareaRef.current;
if (!textarea) return;
@@ -274,12 +263,74 @@ export default function ChatView() {
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
const isOpen = Boolean(activeThread?.terminalOpen);
if (isOpen && api) {
if (typeof api.terminal.close === "function") {
void api.terminal.close({ threadId: activeThreadId }).catch(() => {
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
});
} else {
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
}
}
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !isOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
}, [activeThread?.terminalOpen, activeThreadId, api, dispatch]);
const splitTerminal = useCallback(() => {
if (!activeThreadId) return;
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId) return;
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, dispatch],
);
const closeTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId || !api) return;
const fallbackExitWrite = () =>
api.terminal.write({ threadId: activeThreadId, terminalId, data: "exit\n" }).catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void api.terminal
.close({ threadId: activeThreadId, terminalId })
.catch(() => fallbackExitWrite());
} else {
void fallbackExitWrite();
}
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, api, dispatch],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
@@ -318,7 +369,46 @@ export default function ChatView() {
setExpandedWorkGroups({});
}, [activeThread?.id]);
useEffect(() => {
composerImagesRef.current = composerImages;
}, [composerImages]);
useEffect(() => {
setComposerImages((existing) => {
revokePreviewUrls(existing);
return [];
});
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [activeThread?.id, revokePreviewUrls]);
useEffect(() => {
return () => {
revokePreviewUrls(composerImagesRef.current);
};
}, [revokePreviewUrls]);
useEffect(() => {
if (!expandedImage) {
return;
}
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key !== "Escape") {
return;
}
setExpandedImage(null);
};
window.addEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
};
}, [expandedImage]);
const activeWorktreePath = activeThread?.worktreePath;
useEffect(() => {
if (!activeThread?.id) return;
setEnvMode(activeWorktreePath ? "worktree" : "local");
@@ -429,6 +519,125 @@ export default function ChatView() {
setIsEditorMenuOpen(false);
};
const setThreadError = (threadId: string | null, error: string | null) => {
if (!threadId) return;
dispatch({
type: "SET_ERROR",
threadId,
error,
});
};
const addComposerImages = (files: File[]) => {
if (!activeThreadId || files.length === 0) return;
const nextImages = [...composerImagesRef.current];
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
continue;
}
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
}
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: "image",
id: crypto.randomUUID(),
name: file.name || "image",
mimeType: file.type,
sizeBytes: file.size,
previewUrl,
file,
});
}
setComposerImages(nextImages);
setThreadError(activeThreadId, error);
};
const removeComposerImage = (imageId: string) => {
setComposerImages((existing) => {
const match = existing.find((image) => image.id === imageId);
if (match?.previewUrl) {
URL.revokeObjectURL(match.previewUrl);
}
return existing.filter((image) => image.id !== imageId);
});
};
const openImageDialog = (src: string | undefined, name: string) => {
if (!src) {
return;
}
setExpandedImage({ src, name });
};
const onComposerPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
const files = Array.from(event.clipboardData.files);
if (files.length === 0) {
return;
}
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
if (imageFiles.length === 0) {
return;
}
event.preventDefault();
addComposerImages(imageFiles);
};
const onComposerDragEnter = (event: DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
event.preventDefault();
dragDepthRef.current += 1;
setIsDragOverComposer(true);
};
const onComposerDragOver = (event: DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setIsDragOverComposer(true);
};
const onComposerDragLeave = (event: DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
event.preventDefault();
const nextTarget = event.relatedTarget;
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) {
return;
}
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) {
setIsDragOverComposer(false);
}
};
const onComposerDrop = (event: DragEvent<HTMLDivElement>) => {
if (!event.dataTransfer.types.includes("Files")) {
return;
}
event.preventDefault();
dragDepthRef.current = 0;
setIsDragOverComposer(false);
const files = Array.from(event.dataTransfer.files);
addComposerImages(files);
focusComposer();
};
const ensureSession = async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
if (!api || !activeThread || !activeProject) return null;
if (activeThread.session && activeThread.session.status !== "closed") {
@@ -490,8 +699,9 @@ export default function ChatView() {
e.preventDefault();
if (!api || !activeThread || isSending || isConnecting) return;
const trimmed = prompt.trim();
if (!trimmed) return;
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
const composerImagesSnapshot = [...composerImages];
// On first message: lock in branch + create worktree if needed.
let sessionCwd: string | undefined;
@@ -527,7 +737,12 @@ export default function ChatView() {
// Auto-title from first message
if (activeThread.messages.length === 0) {
const title = trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = titleSeed.length > 50 ? `${titleSeed.slice(0, 50)}...` : titleSeed;
dispatch({
type: "SET_THREAD_TITLE",
threadId: activeThread.id,
@@ -535,43 +750,63 @@ export default function ChatView() {
});
}
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: null,
});
setThreadError(activeThread.id, null);
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
type: "image",
id: image.id,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
previewUrl: image.previewUrl,
}));
dispatch({
type: "PUSH_USER_MESSAGE",
threadId: activeThread.id,
id: crypto.randomUUID(),
text: trimmed,
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
});
const previousMessages = activeThread.messages;
setPrompt("");
setComposerImages([]);
const sessionInfo = await ensureSession(sessionCwd);
if (!sessionInfo) return;
setIsSending(true);
try {
const turnAttachments = await Promise.all(
composerImagesSnapshot.map(async (image): Promise<ProviderSendTurnAttachmentInput> => ({
type: "image",
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
})),
);
const shouldBootstrap =
previousMessages.length > 0 &&
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
const latestPromptForBootstrap = trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT;
const input = shouldBootstrap
? buildBootstrapInput(previousMessages, trimmed, PROVIDER_SEND_TURN_MAX_INPUT_CHARS).text
: trimmed;
? buildBootstrapInput(
previousMessages,
latestPromptForBootstrap,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
).text
: (trimmed || undefined);
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
input,
...(input ? { input } : {}),
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
model: selectedModel || undefined,
effort: selectedEffort || undefined,
});
} catch (err) {
dispatch({
type: "SET_ERROR",
threadId: activeThread.id,
error: err instanceof Error ? err.message : "Failed to send message.",
});
setThreadError(
activeThread.id,
err instanceof Error ? err.message : "Failed to send message.",
);
} finally {
setIsSending(false);
}
@@ -629,7 +864,11 @@ export default function ChatView() {
if (!activeThread) {
return (
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs text-muted-foreground/50">No active thread</span>
</div>
)}
<div className="flex flex-1 items-center justify-center">
<div className="text-center">
<p className="text-sm">Select a thread or create a new one to get started.</p>
@@ -643,7 +882,7 @@ export default function ChatView() {
<div className="flex min-h-0 flex-1 flex-col bg-background">
{/* Top bar */}
<header
className={`flex items-center justify-between border-b border-border px-5 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<div className="flex items-center gap-3">
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
@@ -652,12 +891,6 @@ export default function ChatView() {
{activeProject.name}
</span>
)}
{activeThread.branch && (
<span className="rounded-full bg-accent px-2 py-0.5 font-mono text-[10px] text-muted-foreground/50">
{activeThread.branch}
{activeThread.worktreePath ? " (worktree)" : ""}
</span>
)}
</div>
<div className="flex items-center gap-3">
{/* Open in editor */}
@@ -691,18 +924,10 @@ export default function ChatView() {
)}
</div>
)}
{/* Git actions */}
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
{/* Diff toggle */}
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
activeThread.terminalOpen
? "bg-accent text-foreground"
: "text-muted-foreground/40 hover:text-muted-foreground/60"
}`}
onClick={toggleTerminalVisibility}
>
Terminal <span className="text-muted-foreground/50">{terminalShortcutHint}</span>
</button>
<button
type="button"
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
@@ -725,64 +950,68 @@ export default function ChatView() {
)}
{pendingApprovals.length > 0 && (
<div className="mx-4 mt-3 space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<div
key={approval.requestId}
className="rounded-lg border border-amber-300/20 bg-amber-500/[0.07] px-3 py-2"
>
<p className="text-xs font-medium text-amber-100">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</p>
{approval.detail && (
<p
className="mt-1 truncate font-mono text-[11px] text-amber-100/75"
title={approval.detail}
>
{approval.detail}
<div className="px-5 pt-3">
<div className="mx-auto max-w-3xl space-y-2">
{pendingApprovals.map((approval) => {
const isResponding = respondingRequestIds.includes(approval.requestId);
return (
<div
key={approval.requestId}
className="rounded-lg border border-amber-300/40 bg-amber-50 px-3 py-2 dark:border-amber-300/20 dark:bg-amber-500/[0.07]"
>
<p className="text-xs font-medium text-amber-900 dark:text-amber-100">
{approval.requestKind === "command"
? "Command approval requested"
: "File-change approval requested"}
</p>
)}
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</button>
<button
type="button"
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
>
Always allow this session
</button>
<button
type="button"
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</button>
<button
type="button"
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</button>
{approval.detail && (
<p
className="mt-1 truncate font-mono text-[11px] text-amber-900/80 dark:text-amber-100/75"
title={approval.detail}
>
{approval.detail}
</p>
)}
<div className="mt-2 flex flex-wrap gap-1.5">
<button
type="button"
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
>
Approve once
</button>
<button
type="button"
className="rounded-md border border-sky-300/70 bg-sky-100 px-2 py-1 text-[11px] text-sky-800 transition-colors duration-150 hover:bg-sky-200 disabled:cursor-not-allowed disabled:opacity-50 dark:border-sky-300/30 dark:bg-sky-500/15 dark:text-sky-100 dark:hover:bg-sky-500/22"
disabled={isResponding}
onClick={() =>
void onRespondToApproval(approval.requestId, "acceptForSession")
}
>
Always allow this session
</button>
<button
type="button"
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
>
Decline
</button>
<button
type="button"
className="rounded-md border border-rose-300/70 bg-rose-100 px-2 py-1 text-[11px] text-rose-800 transition-colors duration-150 hover:bg-rose-200 disabled:cursor-not-allowed disabled:opacity-50 dark:border-rose-300/30 dark:bg-rose-500/12 dark:text-rose-100 dark:hover:bg-rose-500/20"
disabled={isResponding}
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
>
Cancel turn
</button>
</div>
</div>
</div>
);
})}
);
})}
</div>
</div>
)}
@@ -888,13 +1117,39 @@ export default function ChatView() {
}
if (timelineEntry.message.role === "user") {
const userImages = timelineEntry.message.attachments ?? [];
return (
<Fragment key={timelineEntry.id}>
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
{userImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{userImages.map((image) => (
<div
key={image.id}
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
onClick={() => openImageDialog(image.previewUrl, image.name)}
/>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
</div>
))}
</div>
)}
{timelineEntry.message.text && (
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
{timelineEntry.message.text}
</pre>
)}
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
{formatTimestamp(timelineEntry.message.createdAt)}
</p>
@@ -957,9 +1212,48 @@ export default function ChatView() {
{/* Input bar */}
<div className="px-5 pb-1 pt-2">
<form onSubmit={onSend} className="mx-auto max-w-3xl">
<div className="group rounded-[20px] border border-border bg-card transition-colors duration-200 focus-within:border-ring">
<div
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border"
}`}
onDragEnter={onComposerDragEnter}
onDragOver={onComposerDragOver}
onDragLeave={onComposerDragLeave}
onDrop={onComposerDrop}
>
{/* Textarea area */}
<div className="px-4 pt-4 pb-2">
{composerImages.length > 0 && (
<div className="mb-3 flex flex-wrap gap-2">
{composerImages.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
>
{image.previewUrl ? (
<img
src={image.previewUrl}
alt={image.name}
className="h-full w-full cursor-zoom-in object-cover"
onClick={() => openImageDialog(image.previewUrl, image.name)}
/>
) : (
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
{image.name}
</div>
)}
<button
type="button"
className="absolute right-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-background/80 text-[11px] leading-none text-foreground transition-colors duration-150 hover:bg-background"
onClick={() => removeComposerImage(image.id)}
aria-label={`Remove ${image.name}`}
>
×
</button>
</div>
))}
</div>
)}
<textarea
ref={textareaRef}
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
@@ -967,8 +1261,11 @@ export default function ChatView() {
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onKeyDown={onKeyDown}
onPaste={onComposerPaste}
placeholder={
phase === "disconnected" ? "Ask for follow-up changes" : "Ask anything..."
phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, or attach images..."
}
disabled={isSending || isConnecting}
/>
@@ -1158,7 +1455,7 @@ export default function ChatView() {
<button
type="submit"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
disabled={isSending || isConnecting || !prompt.trim()}
disabled={isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)}
aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
}
@@ -1214,9 +1511,17 @@ export default function ChatView() {
key={activeThread.id}
api={api}
threadId={activeThread.id}
cwd={activeProject.cwd}
cwd={gitCwd ?? activeProject.cwd}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) =>
dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT",
@@ -1224,15 +1529,41 @@ export default function ChatView() {
height,
})
}
onThreadExited={() =>
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThread.id,
open: false,
})
}
/>
)}
{expandedImage && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
role="dialog"
aria-modal="true"
aria-label="Expanded image preview"
onClick={() => setExpandedImage(null)}
>
<div
className="relative isolate max-h-[92vh] max-w-[92vw]"
onClick={(event) => event.stopPropagation()}
>
<button
type="button"
className="absolute right-2 top-2 z-30 flex h-8 w-8 cursor-pointer items-center justify-center rounded-full bg-black/60 text-xl leading-none text-white transition-colors duration-150 hover:bg-black/80 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/80 [-webkit-app-region:no-drag]"
onClick={() => setExpandedImage(null)}
aria-label="Close image preview"
>
<span className="pointer-events-none">×</span>
</button>
<img
src={expandedImage.src}
alt={expandedImage.name}
className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
draggable={false}
/>
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
{expandedImage.name}
</p>
</div>
</div>
)}
</div>
);
}
+1 -1
View File
@@ -8,7 +8,7 @@ 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 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
>
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
<button
@@ -0,0 +1,831 @@
import {
type GitRunStackedActionResult,
type GitStackedAction,
type GitStatusResult,
type NativeApi,
} from "@t3tools/contracts";
import { queryOptions, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
CheckIcon,
CircleIcon,
CloudUploadIcon,
GitCommitIcon,
Loader2Icon,
MinusIcon,
XIcon,
} from "lucide-react";
import { GitHubIcon } from "./Icons";
interface GitActionsControlProps {
api: NativeApi | undefined;
gitCwd: string | null;
}
type GitActionIconName = "commit" | "push" | "pr";
interface GitActionMenuItem {
id: "commit" | "push" | "pr";
label: string;
disabled: boolean;
icon: GitActionIconName;
kind: "open_modal" | "run_action" | "open_pr";
action?: GitStackedAction;
}
interface GitModalActionOption {
action: GitStackedAction;
label: string;
disabled: boolean;
icon: GitActionIconName;
detail?: string;
}
type GitProgressStepStatus = "pending" | "running" | "completed" | "skipped" | "failed";
interface GitProgressStep {
id: "generate" | "commit" | "push" | "pr";
label: string;
status: GitProgressStepStatus;
detail?: string;
}
function GitActionIcon(props: { icon: GitActionIconName; disabled: boolean }) {
const toneClass = props.disabled ? "text-muted-foreground/45" : "text-foreground/85";
if (props.icon === "commit") {
return <GitCommitIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
if (props.icon === "push") {
return <CloudUploadIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
return <GitHubIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
}
function gitActionModalTitle(): string {
return "Commit your changes";
}
function initialGitProgressSteps(
action: GitStackedAction,
commitMessage: string,
): GitProgressStep[] {
const hasCustomMessage = commitMessage.trim().length > 0;
const steps: GitProgressStep[] = [];
if (!hasCustomMessage) {
steps.push({
id: "generate",
label: "Generate commit message",
status: "pending",
});
}
steps.push({
id: "commit",
label: "Commit changes",
status: "pending",
});
if (action !== "commit") {
steps.push({
id: "push",
label: "Push branch",
status: "pending",
});
}
if (action === "commit_push_pr") {
steps.push({
id: "pr",
label: "Create or open PR",
status: "pending",
});
}
return steps;
}
function updateProgressStep(
steps: GitProgressStep[],
id: GitProgressStep["id"],
status: GitProgressStepStatus,
detail?: string,
): GitProgressStep[] {
return steps.map((step) => {
if (step.id !== id) return step;
return {
...step,
status,
...(detail ? { detail } : {}),
};
});
}
function runActionLabel(action: GitStackedAction): string {
if (action === "commit") return "Commit changes";
if (action === "commit_push") return "Commit and push";
return "Commit and create PR";
}
function buildGitActionMenuItems(
gitStatus: GitStatusResult | null,
isDisabled: boolean,
): GitActionMenuItem[] {
if (!gitStatus) return [];
const hasBranch = gitStatus.branch !== null;
const hasOpenPr = gitStatus.openPr !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasAhead = gitStatus.aheadCount > 0;
const canCommit = !isDisabled && hasChanges;
const canPush = !isDisabled && hasBranch && !hasChanges && hasAhead;
const canOpenPr = !isDisabled && hasOpenPr;
const canCreatePr =
!isDisabled &&
hasBranch &&
!hasOpenPr &&
!hasChanges &&
gitStatus.hasUpstream &&
gitStatus.behindCount === 0;
return [
{
id: "commit",
label: "Commit",
disabled: !canCommit,
icon: "commit",
kind: "open_modal",
},
{
id: "push",
label: "Push",
disabled: !canPush,
icon: "push",
kind: "run_action",
action: "commit_push",
},
hasOpenPr
? {
id: "pr",
label: "View PR",
disabled: !canOpenPr,
icon: "pr",
kind: "open_pr",
}
: {
id: "pr",
label: "Create PR",
disabled: !canCreatePr,
icon: "pr",
kind: "run_action",
action: "commit_push_pr",
},
];
}
function buildGitModalActionOptions(
gitStatus: GitStatusResult | null,
isDisabled: boolean,
): GitModalActionOption[] {
const hasBranch = gitStatus?.branch !== null;
const hasOpenPr = gitStatus?.openPr !== null;
return [
{
action: "commit",
label: "Commit",
disabled: isDisabled,
icon: "commit",
},
{
action: "commit_push",
label: "Commit and push",
disabled: isDisabled || !hasBranch,
icon: "push",
...(!hasBranch ? { detail: "Requires an attached branch." } : {}),
},
{
action: "commit_push_pr",
label: "Commit and create PR",
disabled: isDisabled || !hasBranch || hasOpenPr,
icon: "pr",
...(!hasBranch
? { detail: "Requires an attached branch." }
: hasOpenPr
? { detail: "A PR is already open for this branch." }
: {}),
},
];
}
function getGitStatusQueryKey(gitCwd: string | null): readonly ["git", "status", string | null] {
return ["git", "status", gitCwd];
}
function gitStatusQueryOptions(api: NativeApi | undefined, gitCwd: string | null) {
return queryOptions({
queryKey: getGitStatusQueryKey(gitCwd),
queryFn: async () => {
if (!api || !gitCwd) {
throw new Error("Git status is unavailable.");
}
return api.git.status({ cwd: gitCwd });
},
enabled: !!api && !!gitCwd,
});
}
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
const queryClient = useQueryClient();
const [isGitMenuOpen, setIsGitMenuOpen] = useState(false);
const [isGitModalActionRunning, setIsGitModalActionRunning] = useState(false);
const [gitActionError, setGitActionError] = useState<string | null>(null);
const [isGitModalOpen, setIsGitModalOpen] = useState(false);
const [gitModalSelectedAction, setGitModalSelectedAction] = useState<GitStackedAction>("commit");
const [gitModalCommitMessage, setGitModalCommitMessage] = useState("");
const [gitModalProgress, setGitModalProgress] = useState<GitProgressStep[]>([]);
const [gitModalError, setGitModalError] = useState<string | null>(null);
const [gitModalResult, setGitModalResult] = useState<GitRunStackedActionResult | null>(null);
const gitMenuRef = useRef<HTMLDivElement>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(
gitStatusQueryOptions(api, gitCwd),
);
const runImmediateGitActionMutation = useMutation({
mutationFn: async (action: GitStackedAction) => {
if (!api || !gitCwd) {
throw new Error("Git action is unavailable.");
}
return api.git.runStackedAction({ cwd: gitCwd, action });
},
onMutate: () => {
setIsGitMenuOpen(false);
setGitActionError(null);
setGitModalError(null);
},
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["git"] });
},
onError: (error) => {
setGitActionError(error instanceof Error ? error.message : "Git action failed.");
},
});
const isGitActionRunning = isGitModalActionRunning || runImmediateGitActionMutation.isPending;
const gitBaseDisabled = !api || !gitCwd || !gitStatus || isGitActionRunning;
const gitActionMenuItems = useMemo(
() => buildGitActionMenuItems(gitStatus, gitBaseDisabled),
[gitBaseDisabled, gitStatus],
);
const gitModalActionOptions = useMemo(
() => buildGitModalActionOptions(gitStatus, !gitStatus || isGitActionRunning),
[gitStatus, isGitActionRunning],
);
const selectedGitModalActionOption = useMemo(
() => gitModalActionOptions.find((option) => option.action === gitModalSelectedAction) ?? null,
[gitModalActionOptions, gitModalSelectedAction],
);
const visibleGitActionError = gitActionError ?? gitStatusError?.message;
const gitModalOpenPrUrl = gitModalResult?.pr.url ?? gitStatus?.openPr?.url ?? null;
const gitModalHasProgress = gitModalProgress.length > 0;
const gitModalSelectionMode = !gitModalHasProgress && gitModalResult === null;
const gitModalSteps = gitModalProgress;
const refreshGitStatus = useCallback(async () => {
if (!api || !gitCwd) return;
await queryClient.invalidateQueries({ queryKey: ["git"] });
setGitActionError(null);
}, [api, gitCwd, queryClient]);
const openGitActionModal = useCallback(() => {
setIsGitMenuOpen(false);
setIsGitModalOpen(true);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
setGitActionError(null);
}, []);
const closeGitActionModal = useCallback(() => {
if (isGitActionRunning) return;
setIsGitModalOpen(false);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalError(null);
setGitModalResult(null);
}, [isGitActionRunning]);
const runGitActionImmediately = useCallback(
(action: GitStackedAction) => {
runImmediateGitActionMutation.mutate(action);
},
[runImmediateGitActionMutation],
);
const openExistingPr = useCallback(() => {
setIsGitMenuOpen(false);
setGitActionError(null);
if (!api) {
setGitActionError("Link opening is unavailable.");
return;
}
const prUrl = gitStatus?.openPr?.url ?? null;
if (!prUrl) {
setGitActionError("No open PR found for the current branch.");
return;
}
void api.shell.openExternal(prUrl).catch((error) => {
setGitActionError(error instanceof Error ? error.message : "Unable to open PR link.");
});
}, [api, gitStatus?.openPr?.url]);
const openPrFromModal = useCallback(() => {
if (!api) {
setGitModalError("Link opening is unavailable.");
return;
}
const prUrl = gitModalOpenPrUrl;
if (!prUrl) return;
void api.shell.openExternal(prUrl).catch((error) => {
setGitModalError(error instanceof Error ? error.message : "Unable to open PR link.");
});
}, [api, gitModalOpenPrUrl]);
const runGitAction = useCallback(async () => {
if (!api || !gitCwd || !isGitModalOpen) return;
if (!selectedGitModalActionOption || selectedGitModalActionOption.disabled) return;
const actionCwd = gitCwd;
const action = selectedGitModalActionOption.action;
const commitMessage = gitModalCommitMessage.trim();
const includeGeneratedCommitMessage = commitMessage.length === 0;
setIsGitModalActionRunning(true);
setGitModalError(null);
setGitActionError(null);
setGitModalResult(null);
setGitModalProgress(initialGitProgressSteps(action, commitMessage));
let commit: GitRunStackedActionResult["commit"] = {
status: "skipped_no_changes",
};
let push: GitRunStackedActionResult["push"] = {
status: "skipped_not_requested",
};
let pr: GitRunStackedActionResult["pr"] = {
status: "skipped_not_requested",
};
const updateStep = (
id: GitProgressStep["id"],
status: GitProgressStepStatus,
detail?: string,
) => {
setGitModalProgress((steps) => updateProgressStep(steps, id, status, detail));
};
try {
if (includeGeneratedCommitMessage) {
updateStep("generate", "running");
} else {
updateStep("commit", "running");
}
const commitRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit",
...(commitMessage.length > 0 ? { commitMessage } : {}),
});
commit = commitRun.commit;
if (includeGeneratedCommitMessage) {
if (commitRun.commit.status === "created") {
if (commitRun.commit.subject) {
setGitModalCommitMessage(commitRun.commit.subject);
}
updateStep("generate", "completed");
} else {
updateStep("generate", "skipped", "No local changes to commit.");
}
}
if (commitRun.commit.status === "created") {
updateStep("commit", "completed", commitRun.commit.subject ?? "Committed local changes.");
} else {
updateStep("commit", "skipped", "No local changes to commit.");
}
if (action !== "commit") {
updateStep("push", "running");
const pushRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit_push",
});
push = pushRun.push;
if (pushRun.push.status === "pushed") {
updateStep(
"push",
"completed",
pushRun.push.upstreamBranch
? `Pushed to ${pushRun.push.upstreamBranch}.`
: "Pushed latest commits.",
);
} else {
updateStep("push", "skipped", "Branch already up to date.");
}
}
if (action === "commit_push_pr") {
updateStep("pr", "running");
const prRun = await api.git.runStackedAction({
cwd: actionCwd,
action: "commit_push_pr",
});
pr = prRun.pr;
if (prRun.pr.status === "opened_existing") {
updateStep(
"pr",
"completed",
prRun.pr.number ? `Opened existing PR #${prRun.pr.number}.` : "Opened existing PR.",
);
} else if (prRun.pr.status === "created") {
updateStep(
"pr",
"completed",
prRun.pr.number ? `Created PR #${prRun.pr.number}.` : "Created PR.",
);
} else {
updateStep("pr", "skipped", "PR step was not requested.");
}
}
setGitModalResult({ action, commit, push, pr });
} catch (error) {
const message = error instanceof Error ? error.message : "Git action failed.";
setGitModalError(message);
setGitActionError(message);
setGitModalProgress((steps) => {
const active = steps.find((step) => step.status === "running");
if (!active) return steps;
return updateProgressStep(steps, active.id, "failed", message);
});
} finally {
setIsGitModalActionRunning(false);
await refreshGitStatus().catch(() => undefined);
}
}, [
api,
gitCwd,
gitModalCommitMessage,
isGitModalOpen,
refreshGitStatus,
selectedGitModalActionOption,
]);
useEffect(() => {
setGitActionError(null);
setGitModalError(null);
setIsGitModalOpen(false);
setGitModalSelectedAction("commit");
setGitModalCommitMessage("");
setGitModalProgress([]);
setGitModalResult(null);
}, [gitCwd]);
useEffect(() => {
if (!isGitModalOpen) return;
if (selectedGitModalActionOption && !selectedGitModalActionOption.disabled) return;
const fallback = gitModalActionOptions.find((option) => !option.disabled);
if (fallback) {
setGitModalSelectedAction(fallback.action);
}
}, [gitModalActionOptions, isGitModalOpen, selectedGitModalActionOption]);
useEffect(() => {
if (!isGitMenuOpen) return;
const handleClickOutside = (event: MouseEvent) => {
if (!gitMenuRef.current) return;
if (event.target instanceof Node && !gitMenuRef.current.contains(event.target)) {
setIsGitMenuOpen(false);
}
};
window.addEventListener("mousedown", handleClickOutside);
return () => {
window.removeEventListener("mousedown", handleClickOutside);
};
}, [isGitMenuOpen]);
useEffect(() => {
if (!isGitModalOpen) return;
const handleEscape = (event: globalThis.KeyboardEvent) => {
if (event.key !== "Escape") return;
if (isGitActionRunning) return;
closeGitActionModal();
};
window.addEventListener("keydown", handleEscape);
return () => {
window.removeEventListener("keydown", handleEscape);
};
}, [closeGitActionModal, isGitActionRunning, isGitModalOpen]);
if (!gitCwd) return null;
return (
<>
<div className="relative" ref={gitMenuRef}>
<button
type="button"
className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80 disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => {
if (!isGitMenuOpen) {
void refreshGitStatus().catch(() => undefined);
}
setIsGitMenuOpen((v) => !v);
}}
disabled={!gitStatus || isGitActionRunning}
>
{isGitActionRunning ? "Running..." : "Git actions"}
<span aria-hidden="true">▾</span>
</button>
{isGitMenuOpen && (
<div className="absolute right-0 top-full z-50 mt-1 w-[280px] rounded-3xl border border-border bg-popover p-3 shadow-xl">
<p className="px-3 pb-2 text-[13px] text-muted-foreground/75">Git actions</p>
{gitActionMenuItems.map((item) => {
return (
<button
key={`${item.id}-${item.label}`}
type="button"
className="mb-1.5 flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left text-[14px] text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:text-muted-foreground/65"
disabled={item.disabled}
onClick={() => {
if (item.kind === "open_modal") {
openGitActionModal();
return;
}
if (item.kind === "open_pr") {
openExistingPr();
return;
}
if (item.action) {
void runGitActionImmediately(item.action);
}
}}
>
<GitActionIcon icon={item.icon} disabled={item.disabled} />
<span>{item.label}</span>
</button>
);
})}
{gitStatus?.branch === null && (
<p className="px-2 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
Detached HEAD: push and PR actions are unavailable.
</p>
)}
{gitStatus &&
gitStatus.branch !== null &&
!gitStatus.hasWorkingTreeChanges &&
gitStatus.aheadCount === 0 &&
gitStatus.behindCount > 0 && (
<p className="px-3 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
Branch is behind upstream. Pull/rebase before opening a PR.
</p>
)}
{visibleGitActionError && (
<p className="px-3 pt-2 text-[11px] text-rose-500 dark:text-rose-300">
{visibleGitActionError}
</p>
)}
</div>
)}
</div>
{isGitModalOpen && (
<div
className="fixed inset-0 z-80 flex items-center justify-center bg-black/35 px-4 py-6"
onMouseDown={() => {
closeGitActionModal();
}}
>
<div
className="w-full max-w-[640px] rounded-3xl border border-border bg-popover p-6 shadow-2xl"
role="dialog"
aria-modal="true"
aria-label="Git action confirmation"
onMouseDown={(event) => {
event.stopPropagation();
}}
>
<div className="flex items-start justify-between gap-4">
<div className="flex items-center gap-3">
<div className="rounded-2xl bg-accent p-3">
<GitActionIcon
icon={selectedGitModalActionOption?.icon ?? "commit"}
disabled={false}
/>
</div>
<div>
<p className="text-xs uppercase tracking-[0.14em] text-muted-foreground/70">
Git actions
</p>
<h3 className="text-3xl font-semibold tracking-tight text-foreground">
{gitActionModalTitle()}
</h3>
</div>
</div>
<button
type="button"
className="rounded-md p-1 text-muted-foreground/60 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
onClick={closeGitActionModal}
disabled={isGitActionRunning}
aria-label="Close git action dialog"
>
<XIcon className="h-5 w-5" />
</button>
</div>
<div className="mt-6 space-y-2 rounded-2xl border border-border/80 bg-card/40 px-4 py-3">
<div className="flex items-center justify-between gap-4 text-sm">
<span className="text-muted-foreground/70">Branch</span>
<span className="font-mono text-foreground">
{gitStatus?.branch ?? "(detached HEAD)"}
</span>
</div>
<div className="flex items-center justify-between gap-4 text-sm">
<span className="text-muted-foreground/70">Changes</span>
<span className="text-foreground">
{gitStatus?.hasWorkingTreeChanges
? "Working tree has changes"
: "No local changes"}
</span>
</div>
</div>
<div className="mt-6">
<label
htmlFor="git-commit-message"
className="mb-2 block text-sm font-medium text-foreground"
>
Commit message
</label>
<textarea
id="git-commit-message"
rows={3}
className="w-full resize-none rounded-2xl border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-70"
placeholder="Leave blank to autogenerate a commit message"
value={gitModalCommitMessage}
onChange={(event) => setGitModalCommitMessage(event.target.value)}
disabled={!gitModalSelectionMode || isGitActionRunning}
/>
</div>
<div className="mt-6">
<p className="text-sm font-medium text-foreground">Next steps</p>
<div className="mt-2 overflow-hidden rounded-2xl border border-border">
{gitModalSelectionMode &&
gitModalActionOptions.map((option, index) => {
const borderClass =
index < gitModalActionOptions.length - 1 ? "border-b border-border/70" : "";
const selected = option.action === gitModalSelectedAction && !option.disabled;
const disabled = option.disabled || isGitActionRunning;
return (
<button
key={option.action}
type="button"
className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors duration-150 ${borderClass} ${
selected
? "bg-accent/55"
: disabled
? "bg-card/25"
: "bg-card/45 hover:bg-accent/35"
} disabled:cursor-not-allowed`}
disabled={disabled}
onClick={() => {
setGitModalSelectedAction(option.action);
}}
>
<span className="mt-0.5">
<GitActionIcon icon={option.icon} disabled={option.disabled} />
</span>
<div className="min-w-0 flex-1">
<p
className={`text-sm ${disabled ? "text-muted-foreground/60" : "text-foreground"}`}
>
{option.label}
</p>
{option.detail && (
<p
className={`mt-0.5 text-xs ${disabled ? "text-muted-foreground/55" : "text-muted-foreground/70"}`}
>
{option.detail}
</p>
)}
</div>
{selected && !disabled ? (
<CheckIcon className="mt-0.5 h-4 w-4 shrink-0 text-foreground" />
) : null}
</button>
);
})}
{!gitModalSelectionMode &&
gitModalSteps.map((step, index) => {
const borderClass =
index < gitModalSteps.length - 1 ? "border-b border-border/70" : "";
return (
<div
key={step.id}
className={`flex items-start gap-3 bg-card/45 px-4 py-3 ${borderClass}`}
>
<span className="mt-0.5">
{step.status === "running" ? (
<Loader2Icon className="h-4 w-4 animate-spin text-foreground" />
) : step.status === "completed" ? (
<CheckIcon className="h-4 w-4 text-emerald-600 dark:text-emerald-300" />
) : step.status === "skipped" ? (
<MinusIcon className="h-4 w-4 text-muted-foreground/70" />
) : step.status === "failed" ? (
<XIcon className="h-4 w-4 text-rose-500 dark:text-rose-300" />
) : (
<CircleIcon className="h-4 w-4 text-muted-foreground/60" />
)}
</span>
<div className="min-w-0">
<p className="text-sm text-foreground">{step.label}</p>
{step.status === "failed" && step.detail && (
<p className="mt-0.5 text-xs text-rose-500 dark:text-rose-300">
{step.detail}
</p>
)}
</div>
</div>
);
})}
</div>
</div>
{(gitModalError ?? visibleGitActionError) && (
<div className="mt-4 rounded-lg border border-rose-300/50 bg-rose-500/10 px-3 py-2 text-xs text-rose-600 dark:text-rose-200">
{gitModalError ?? visibleGitActionError}
</div>
)}
<div className="mt-6 flex justify-end gap-2">
{gitModalResult && gitModalOpenPrUrl && (
<button
type="button"
className="rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
onClick={openPrFromModal}
disabled={isGitActionRunning}
>
Open PR
</button>
)}
<button
type="button"
className={
gitModalResult
? "rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
: "rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
}
onClick={closeGitActionModal}
disabled={isGitActionRunning}
>
{gitModalResult ? "Done" : "Cancel"}
</button>
{!gitModalResult && (
<button
type="button"
className="rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => {
void runGitAction();
}}
disabled={isGitActionRunning || !selectedGitModalActionOption}
>
{isGitActionRunning
? "Running..."
: gitModalSelectionMode
? "Continue"
: runActionLabel(gitModalSelectedAction)}
</button>
)}
</div>
</div>
</div>
)}
</>
);
}
+15
View File
@@ -0,0 +1,15 @@
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>
);
+133 -19
View File
@@ -1,11 +1,17 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic";
import { readNativeApi } from "../session-logic";
import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project } from "../types";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -25,22 +31,96 @@ function inferProjectName(cwd: string): string {
return last && last.length > 0 ? last : "project";
}
function threadStatusLabel(
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
): "Working" | "Connecting" | null {
if (status === "running") return "Working";
if (status === "connecting") return "Connecting";
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,
};
}
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 = useMemo(() => readNativeApi(), []);
const api = useNativeApi();
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) => {
@@ -54,6 +134,16 @@ 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: [],
@@ -237,10 +327,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 pb-4 ${isElectron ? "" : "pt-4"}`}>
<div
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
>
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
T3 <span className="font-normal text-muted-foreground">Code</span>
</span>
@@ -312,7 +402,11 @@ 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 = threadStatusLabel(thread.session?.status);
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const terminalStatus = terminalStatusIndicator(thread);
return (
<button
key={thread.id}
@@ -338,16 +432,36 @@ 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] 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
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>
)}
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
</div>
<span className="shrink-0 text-[10px] text-muted-foreground/40">
{formatRelativeTime(thread.createdAt)}
</span>
<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>
</button>
);
})}
+570 -165
View File
@@ -1,15 +1,27 @@
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,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import {
extractTerminalLinks,
isTerminalLinkActivation,
preferredTerminalEditor,
resolvePathLinkTarget,
} from "../terminal-links";
import { isTerminalClearShortcut } from "../terminal-shortcuts";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "../types";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type ThreadTerminalGroup,
} from "../types";
const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -97,162 +109,30 @@ function terminalThemeFromApp(): ITheme {
};
}
interface ThreadTerminalDrawerProps {
interface TerminalViewportProps {
api: NativeApi;
threadId: string;
terminalId: string;
cwd: string;
height: number;
focusRequestId: number;
onHeightChange: (height: number) => void;
onThreadExited: () => void;
autoFocus: boolean;
resizeEpoch: number;
drawerHeight: number;
}
export default function ThreadTerminalDrawer({
function TerminalViewport({
api,
threadId,
terminalId,
cwd,
height,
focusRequestId,
onHeightChange,
onThreadExited,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
autoFocus,
resizeEpoch,
drawerHeight,
}: TerminalViewportProps) {
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;
@@ -281,7 +161,7 @@ export default function ThreadTerminalDrawer({
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
try {
await api.terminal.write({ threadId, data: "\u000c" });
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
} catch (error) {
writeSystemMessage(
activeTerminal,
@@ -298,9 +178,70 @@ export default function ThreadTerminalDrawer({
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, data })
.write({ threadId, terminalId, data })
.catch((err) =>
writeSystemMessage(
terminal,
@@ -328,6 +269,7 @@ export default function ThreadTerminalDrawer({
activeFitAddon.fit();
const snapshot = await api.terminal.open({
threadId,
terminalId,
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
@@ -337,9 +279,11 @@ export default function ThreadTerminalDrawer({
if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history);
}
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
if (autoFocus) {
window.requestAnimationFrame(() => {
activeTerminal.focus();
});
}
} catch (err) {
if (disposed) return;
writeSystemMessage(
@@ -350,7 +294,7 @@ export default function ThreadTerminalDrawer({
};
const unsubscribe = api.terminal.onEvent((event) => {
if (event.threadId !== threadId) return;
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const activeTerminal = terminalRef.current;
if (!activeTerminal) return;
@@ -379,12 +323,37 @@ export default function ThreadTerminalDrawer({
}
if (event.type === "exited") {
onThreadExitedRef.current();
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",
);
}
});
const fitTimer = window.setTimeout(() => {
fitAndResizeTerminal(true);
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);
}, 30);
void openTerminal();
@@ -393,14 +362,16 @@ export default function ThreadTerminalDrawer({
window.clearTimeout(fitTimer);
unsubscribe();
inputDisposable.dispose();
terminalLinksDisposable.dispose();
themeObserver.disconnect();
terminalRef.current = null;
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, fitAndResizeTerminal, threadId]);
}, [api, cwd, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
const terminal = terminalRef.current;
if (!terminal) return;
const frame = window.requestAnimationFrame(() => {
@@ -409,7 +380,7 @@ export default function ThreadTerminalDrawer({
return () => {
window.cancelAnimationFrame(frame);
};
}, [focusRequestId]);
}, [autoFocus, focusRequestId]);
useEffect(() => {
const terminal = terminalRef.current;
@@ -424,6 +395,7 @@ export default function ThreadTerminalDrawer({
void api.terminal
.resize({
threadId,
terminalId,
cols: terminal.cols,
rows: terminal.rows,
})
@@ -432,27 +404,460 @@ export default function ThreadTerminalDrawer({
return () => {
window.cancelAnimationFrame(frame);
};
}, [api, cwd, drawerHeight, threadId]);
}, [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;
}
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]);
return (
<aside
className="thread-terminal-drawer flex shrink-0 flex-col border-t border-border/80 bg-background"
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }}
>
<div
className="flex h-2 cursor-row-resize items-center justify-center"
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd}
>
<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]"
/>
/>
{!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">
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</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">
<button
type="button"
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</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>
</aside>
);
+28
View File
@@ -91,4 +91,32 @@ 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");
});
});
+29 -3
View File
@@ -18,8 +18,34 @@ 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 {
return `${messageRoleLabel(message)}:\n${message.text}`;
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)`;
}
function finalizeWithPrompt(
@@ -68,7 +94,7 @@ export function buildBootstrapInput(
let includedNewestFirst: string[] = [];
for (const block of newestFirstBlocks) {
const nextNewestFirst = [...includedNewestFirst, block];
const nextChronological = [...nextNewestFirst].reverse();
const nextChronological = nextNewestFirst.toReversed();
const omittedCount = newestFirstBlocks.length - nextChronological.length;
const transcriptBody =
omittedCount > 0
@@ -80,7 +106,7 @@ export function buildBootstrapInput(
includedNewestFirst = nextNewestFirst;
}
let includedChronological = [...includedNewestFirst].reverse();
let includedChronological = includedNewestFirst.toReversed();
while (true) {
const omittedCount = newestFirstBlocks.length - includedChronological.length;
const transcriptBody =
+6
View File
@@ -0,0 +1,6 @@
import { useMemo } from "react";
import { readNativeApi } from "../session-logic";
export function useNativeApi() {
return useMemo(() => readNativeApi(), []);
}
+132 -5
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 } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types";
describe("hydratePersistedState", () => {
@@ -50,6 +50,14 @@ 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");
});
@@ -92,6 +100,14 @@ 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");
});
@@ -117,7 +133,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.runtimeMode).toBe("approval-required");
});
it("hydrates terminal fields from v6 payload", () => {
it("hydrates terminal fields from legacy v6 payload", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
@@ -139,8 +155,13 @@ 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",
@@ -149,6 +170,60 @@ 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", () => {
@@ -181,11 +256,19 @@ 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 v6 payload and strips non-persisted thread fields", () => {
it("writes v7 payload and strips non-persisted thread fields", () => {
const thread: Thread = {
id: "t-1",
codexThreadId: "thr_1",
@@ -194,12 +277,30 @@ 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,
},
@@ -207,6 +308,7 @@ describe("toPersistedState", () => {
events: [],
error: "boom",
createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:02:00.000Z",
branch: null,
worktreePath: null,
};
@@ -226,7 +328,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access",
});
expect(persisted.version).toBe(6);
expect(persisted.version).toBe(7);
expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({
id: "t-1",
@@ -236,8 +338,33 @@ describe("toPersistedState", () => {
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 320,
messages: thread.messages,
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,
},
],
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: null,
worktreePath: null,
});
+161 -7
View File
@@ -3,10 +3,12 @@ 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";
@@ -23,10 +25,26 @@ 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),
@@ -37,8 +55,16 @@ const persistedThreadSchema = z.object({
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(),
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(),
});
@@ -74,12 +100,18 @@ 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,
@@ -117,6 +149,91 @@ 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,
@@ -125,14 +242,29 @@ 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) => ({
...message,
streaming: false,
})),
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,
};
}),
events: [],
error: null,
createdAt: thread.createdAt,
lastVisitedAt: thread.lastVisitedAt,
branch: thread.branch ?? null,
worktreePath: thread.worktreePath ?? null,
};
@@ -177,9 +309,9 @@ export function hydratePersistedState(
export function toPersistedState(
state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV6Schema> {
): z.infer<typeof persistedStateV7Schema> {
return {
version: 6,
version: 7,
projects: state.projects,
threads: state.threads.map((thread) => ({
id: thread.id,
@@ -189,8 +321,30 @@ export function toPersistedState(
model: thread.model,
terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight,
messages: thread.messages,
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,
})),
createdAt: thread.createdAt,
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
branch: thread.branch,
worktreePath: thread.worktreePath,
})),
+68
View File
@@ -4,6 +4,7 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import {
type WorkLogEntry,
applyEventToMessages,
derivePendingApprovals,
deriveTimelineEntries,
deriveWorkLogEntries,
evolveSession,
@@ -392,6 +393,73 @@ 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,6 +78,13 @@ 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;
@@ -98,6 +105,52 @@ 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
+316 -2
View File
@@ -1,10 +1,13 @@
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } 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",
@@ -37,6 +40,16 @@ 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: [],
@@ -66,6 +79,42 @@ 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(
@@ -111,6 +160,227 @@ 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, {
@@ -219,4 +489,48 @@ 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);
});
});
+393 -15
View File
@@ -8,15 +8,18 @@ import {
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import {
type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
@@ -30,14 +33,25 @@ 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 }
| {
type: "PUSH_USER_MESSAGE";
threadId: string;
id: string;
text: string;
attachments?: ChatAttachment[];
}
| { type: "SET_ERROR"; threadId: string; error: string | null }
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
@@ -60,8 +74,9 @@ export interface AppState {
diffOpen: boolean;
}
const PERSISTED_STATE_KEY = "t3code:renderer-state:v6";
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
@@ -126,6 +141,194 @@ 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) {
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
});
}
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);
}
@@ -252,10 +455,10 @@ export function reducer(state: AppState, action: Action): AppState {
if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null;
return {
return normalizeThreadTerminals({
...thread,
projectId: mappedProjectId,
};
});
})
.filter((thread): thread is Thread => thread !== null);
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
@@ -278,21 +481,30 @@ export function reducer(state: AppState, action: Action): AppState {
),
};
case "ADD_THREAD":
case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
});
return {
...state,
threads: [
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
},
],
threads: [...state.threads, nextThread],
activeThreadId: action.thread.id,
};
}
case "SET_ACTIVE_THREAD":
return { ...state, activeThreadId: action.threadId };
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 "TOGGLE_THREAD_TERMINAL":
return {
@@ -321,9 +533,169 @@ 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);
@@ -349,6 +721,9 @@ 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 }
: {}),
})),
};
}
@@ -380,6 +755,9 @@ 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,
},
+110
View File
@@ -0,0 +1,110 @@
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
@@ -0,0 +1,200 @@
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;
}
+24
View File
@@ -4,11 +4,29 @@ 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;
}
@@ -29,6 +47,11 @@ 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[];
@@ -38,6 +61,7 @@ export interface Thread {
latestTurnStartedAt?: string | undefined;
latestTurnCompletedAt?: string | undefined;
latestTurnDurationMs?: number | undefined;
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
}
+1
View File
@@ -6,6 +6,7 @@ interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
}
declare global {
+16
View File
@@ -96,8 +96,24 @@ 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: {
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),
+4 -4
View File
@@ -6,10 +6,10 @@
"packages/*"
],
"scripts": {
"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",
"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",
"start": "turbo run start --filter=t3",
"start:desktop": "turbo run start --filter=@t3tools/desktop",
"build": "turbo run build",
+82
View File
@@ -0,0 +1,82 @@
import { describe, expect, it } from "vitest";
import {
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 status result", () => {
const parsed = gitStatusResultSchema.parse({
branch: "feature/git-actions",
hasWorkingTreeChanges: true,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
openPr: null,
});
expect(parsed.branch).toBe("feature/git-actions");
expect(parsed.hasWorkingTreeChanges).toBe(true);
});
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);
});
});
+77 -7
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
// ── Input schemas ──
// ── Existing branch/worktree Git API ─────────────────────────────────
export const gitListBranchesInputSchema = z.object({
cwd: z.string().min(1),
@@ -8,9 +8,7 @@ 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(),
});
@@ -34,8 +32,6 @@ 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(),
@@ -48,8 +44,6 @@ 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>;
@@ -67,3 +61,79 @@ 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 gitStatusResultSchema = z.object({
branch: z.string().min(1).nullable(),
hasWorkingTreeChanges: z.boolean(),
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 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>;
+13 -2
View File
@@ -8,6 +8,10 @@ import type {
GitListBranchesInput,
GitListBranchesResult,
GitRemoveWorktreeInput,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
GitStatusResult,
} from "./git";
import type {
ProviderEvent,
@@ -26,12 +30,12 @@ import type {
ProjectRemoveInput,
} from "./project";
import type {
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput,
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
@@ -57,7 +61,7 @@ export interface NativeApi {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalThreadInput) => Promise<void>;
clear: (input: TerminalClearInput) => Promise<void>;
restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
@@ -85,14 +89,21 @@ 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
status: (input: GitStatusInput) => Promise<GitStatusResult>;
runStackedAction: (
input: GitRunStackedActionInput,
) => Promise<GitRunStackedActionResult>;
};
contextMenu: {
show: <T extends string>(
+8 -1
View File
@@ -1,10 +1,17 @@
export const MODEL_OPTIONS = ["gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2"] as const;
export const MODEL_OPTIONS = [
"gpt-5.3-codex",
"gpt-5.3-codex-spark",
"gpt-5.2-codex",
"gpt-5.2",
] as const;
export const DEFAULT_MODEL = "gpt-5.3-codex";
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): string | null {
+59
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
providerEventSchema,
providerRespondToRequestInputSchema,
providerSendTurnInputSchema,
@@ -40,9 +41,67 @@ 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", () => {
+42 -5
View File
@@ -55,14 +55,48 @@ 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 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 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 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),
@@ -110,6 +144,9 @@ 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>;
+35
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_TERMINAL_ID,
terminalClearInputSchema,
terminalCloseInputSchema,
terminalEventSchema,
terminalOpenInputSchema,
@@ -30,6 +32,16 @@ describe("terminalOpenInputSchema", () => {
});
expect(result.success).toBe(false);
});
it("defaults terminalId when missing", () => {
const parsed = terminalOpenInputSchema.parse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 100,
rows: 24,
});
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
});
});
describe("terminalWriteInputSchema", () => {
@@ -68,6 +80,15 @@ describe("terminalResizeInputSchema", () => {
});
});
describe("terminalClearInputSchema", () => {
it("defaults terminal id", () => {
const parsed = terminalClearInputSchema.parse({
threadId: "thread-1",
});
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
});
});
describe("terminalCloseInputSchema", () => {
it("accepts optional deleteHistory", () => {
const result = terminalCloseInputSchema.safeParse({
@@ -82,6 +103,7 @@ describe("terminalSessionSnapshotSchema", () => {
it("accepts running snapshots", () => {
const result = terminalSessionSnapshotSchema.safeParse({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
cwd: "/tmp/project",
status: "running",
pid: 1234,
@@ -99,6 +121,7 @@ describe("terminalEventSchema", () => {
const result = terminalEventSchema.safeParse({
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "line\n",
});
@@ -109,10 +132,22 @@ describe("terminalEventSchema", () => {
const result = terminalEventSchema.safeParse({
type: "exited",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
exitCode: 0,
exitSignal: null,
});
expect(result.success).toBe(true);
});
it("accepts activity events", () => {
const result = terminalEventSchema.safeParse({
type: "activity",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
hasRunningSubprocess: true,
});
expect(result.success).toBe(true);
});
});
+23 -3
View File
@@ -1,28 +1,38 @@
import { z } from "zod";
export const DEFAULT_TERMINAL_ID = "default";
const terminalColsSchema = z.number().int().min(20).max(400);
const terminalRowsSchema = z.number().int().min(5).max(200);
const terminalIdSchema = z.string().trim().min(1).max(128);
export const terminalThreadInputSchema = z.object({
threadId: z.string().trim().min(1),
});
export const terminalOpenInputSchema = terminalThreadInputSchema.extend({
export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
terminalId: terminalIdSchema.default(DEFAULT_TERMINAL_ID),
});
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
cwd: z.string().trim().min(1),
cols: terminalColsSchema,
rows: terminalRowsSchema,
});
export const terminalWriteInputSchema = terminalThreadInputSchema.extend({
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
data: z.string().min(1).max(65_536),
});
export const terminalResizeInputSchema = terminalThreadInputSchema.extend({
export const terminalResizeInputSchema = terminalSessionInputSchema.extend({
cols: terminalColsSchema,
rows: terminalRowsSchema,
});
export const terminalClearInputSchema = terminalSessionInputSchema;
export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
terminalId: terminalIdSchema.optional(),
deleteHistory: z.boolean().optional(),
});
@@ -35,6 +45,7 @@ export const terminalSessionStatusSchema = z.enum([
export const terminalSessionSnapshotSchema = z.object({
threadId: z.string().min(1),
terminalId: z.string().min(1),
cwd: z.string().min(1),
status: terminalSessionStatusSchema,
pid: z.number().int().positive().nullable(),
@@ -46,6 +57,7 @@ export const terminalSessionSnapshotSchema = z.object({
const terminalEventBaseSchema = z.object({
threadId: z.string().min(1),
terminalId: z.string().min(1),
createdAt: z.string().datetime(),
});
@@ -79,6 +91,11 @@ export const terminalRestartedEventSchema = terminalEventBaseSchema.extend({
snapshot: terminalSessionSnapshotSchema,
});
export const terminalActivityEventSchema = terminalEventBaseSchema.extend({
type: z.literal("activity"),
hasRunningSubprocess: z.boolean(),
});
export const terminalEventSchema = z.discriminatedUnion("type", [
terminalStartedEventSchema,
terminalOutputEventSchema,
@@ -86,12 +103,15 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
terminalErrorEventSchema,
terminalClearedEventSchema,
terminalRestartedEventSchema,
terminalActivityEventSchema,
]);
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
export type TerminalSessionInput = z.input<typeof terminalSessionInputSchema>;
export type TerminalOpenInput = z.input<typeof terminalOpenInputSchema>;
export type TerminalWriteInput = z.input<typeof terminalWriteInputSchema>;
export type TerminalResizeInput = z.input<typeof terminalResizeInputSchema>;
export type TerminalClearInput = z.input<typeof terminalClearInputSchema>;
export type TerminalCloseInput = z.input<typeof terminalCloseInputSchema>;
export type TerminalSessionStatus = z.infer<typeof terminalSessionStatusSchema>;
export type TerminalSessionSnapshot = z.infer<typeof terminalSessionSnapshotSchema>;
+2
View File
@@ -20,6 +20,8 @@ export const WS_METHODS = {
shellOpenInEditor: "shell.openInEditor",
// Git methods
gitStatus: "git.status",
gitRunStackedAction: "git.runStackedAction",
gitListBranches: "git.listBranches",
gitCreateWorktree: "git.createWorktree",
gitRemoveWorktree: "git.removeWorktree",
+124
View File
@@ -0,0 +1,124 @@
import { spawn } from "node:child_process";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5173;
const MAX_HASH_OFFSET = 3000;
const MODE_ARGS = {
dev: [
"run",
"dev",
"--ui=tui",
"--filter=@t3tools/contracts",
"--filter=@t3tools/web",
"--filter=t3",
"--parallel",
],
"dev:server": ["run", "dev", "--filter=t3"],
"dev:web": ["run", "dev", "--filter=@t3tools/web"],
"dev:desktop": ["run", "dev", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "--parallel"],
};
function parseInteger(value, envName) {
const parsed = Number(value);
if (!Number.isInteger(parsed)) {
throw new Error(`Invalid ${envName}: ${value}`);
}
return parsed;
}
function hashSeed(seed) {
let hash = 0x811c9dc5;
for (let i = 0; i < seed.length; i += 1) {
hash ^= seed.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return hash >>> 0;
}
function resolveOffset() {
const explicitOffset = process.env.T3CODE_PORT_OFFSET?.trim();
if (explicitOffset) {
const parsed = parseInteger(explicitOffset, "T3CODE_PORT_OFFSET");
if (parsed < 0) {
throw new Error(`Invalid T3CODE_PORT_OFFSET: ${explicitOffset}`);
}
return { offset: parsed, source: `T3CODE_PORT_OFFSET=${explicitOffset}` };
}
const seed = process.env.T3CODE_DEV_INSTANCE?.trim();
if (!seed) {
return { offset: 0, source: "default ports" };
}
if (/^\d+$/.test(seed)) {
return { offset: Number(seed), source: `numeric T3CODE_DEV_INSTANCE=${seed}` };
}
const offset = (hashSeed(seed) % MAX_HASH_OFFSET) + 1;
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function main() {
const mode = process.argv[2];
const isDryRun = process.argv.includes("--dry-run");
if (!mode || !(mode in MODE_ARGS)) {
const supportedModes = Object.keys(MODE_ARGS).join(", ");
throw new Error(`Usage: bun scripts/dev-runner.mjs <mode>. Supported modes: ${supportedModes}`);
}
const { offset, source } = resolveOffset();
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
);
}
const env = {
...process.env,
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
};
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
env.T3CODE_LOG_WS_EVENTS = "1";
}
console.info(
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
);
if (isDryRun) {
return;
}
const command = process.platform === "win32" ? "turbo.cmd" : "turbo";
const child = spawn(command, MODE_ARGS[mode], {
stdio: "inherit",
env,
});
child.on("exit", (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
child.on("error", (error) => {
console.error("[dev-runner] failed to start turbo", error);
process.exit(1);
});
}
try {
main();
} catch (error) {
console.error("[dev-runner]", error);
process.exit(1);
}
+1
View File
@@ -4,6 +4,7 @@
"PORT",
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
"ELECTRON_RENDERER_PORT",
"T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE",
"T3CODE_PORT",