Compare commits

..
Author SHA1 Message Date
Julius Marminge fa4f8dd73c Document private Tailscale SSH tunnel setup for remote T3 access
- Add a new Tailscale-based private tunneling workflow using loopback-bound server + SSH local forwarding
- Include usage examples for web and desktop clients over the local forwarded endpoint
- Note fragment-style URL tokens to reduce exposure in request logs/history
2026-02-18 09:30:49 -08:00
Julius Marminge 3421049d5c Add remote backend connection support across server and clients
- document remote architecture and setup in `REMOTE.md` and link from README
- add server host override and WebSocket bearer-token auth support
- enable web runtime/env remote WS config and desktop remote mode without local spawn
- extend WS tests for bearer authorization path
2026-02-18 09:00:49 -08:00
Cursor Agent b236dccca3 refactor: extract shared normalizeProjectScripts into @t3tools/contracts
Move the duplicated script normalization logic (dedup-by-id + single
runOnWorktreeCreate enforcement) from apps/web/src/store.ts and
apps/server/src/projectRegistry.ts into packages/contracts/src/project.ts
so both consumers share one canonical implementation.

Applied via @cursor push command
2026-02-18 00:59:06 -08:00
Cursor Agent ac05ddc0f9 Remove dead code: unused shell env injection functions
Remove injectEnvIntoShellCommand, shellEscapePosix,
shellEscapeWindowsSetValue, ENV_KEY_PATTERN, and the now-unused
isWindowsPlatform import. These were leftover from an earlier approach
where env vars were injected into the shell command string, replaced
by passing env directly to terminal.open.

Applied via @cursor push command
2026-02-18 00:59:06 -08:00
Cursor Agent 0e73dc1527 Fix terminal stability bugs: remove autoFocus from effect deps, stabilize memo, remove dead export
- Remove autoFocus from the main terminal setup effect dependency array to
  prevent full terminal teardown/recreation when switching tabs in split view.
  Focus is already handled by a dedicated effect.
- Change threadTerminalRuntimeEnv memo dependency from activeProject to
  activeProject?.cwd so unrelated project state changes (e.g. saving scripts)
  don't trigger terminal re-initialization.
- Unexport injectEnvIntoShellCommand which is never imported by production
  code (env injection is handled server-side), and remove its tests.

Applied via @cursor push command
2026-02-18 00:59:06 -08:00
Julius Marminge 1a94fcbd29 Handle optional terminal dimensions and preserve active terminal size
- make `cols`/`rows` optional in terminal open contracts
- default new/restarted sessions to 120x30 when size hints are missing
- reuse existing terminal dimensions unless a new size is explicitly requested
- only send script terminal size hints when creating a new terminal
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex ed40fd3364 Reset script dialog state after close animation
- Clear form fields only after the dialog close completes to avoid stale state during transitions
- Keep icon picker closed when the dialog closes

Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marminge 88f31d2f65 Pass runtime env through terminal open and disable zsh prompt spacer
- add optional `env` to terminal open contract and validate env keys/limits
- propagate runtime env from web terminal/script launches to server PTY spawn
- start `zsh` with `-o nopromptsp` to avoid trailing `%` markers and add coverage
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex c8c0dc6c3c Require modifier keys for script keybinding capture
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex e52db0bbc2 Fix keybindings parse error wrapping behavior
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex 71d8f74143 Refactor project script persistence flow in ChatView
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex dfeb673b6d Label setup scripts in project action menu
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex 4d886b99f5 Fix Windows percent escaping in script env injection
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex 4e791759cf Address second-pass PR feedback on parser hardening
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex 9799b42dcd Address PR review feedback for scripts/keybindings handling
Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marmingeandcodex a999933297 Fix web typecheck for optional script env
Only pass extraEnv to projectScriptRuntimeEnv when defined to satisfy exactOptionalPropertyTypes in CI.

Co-authored-by: codex <[email protected]>
2026-02-18 00:59:06 -08:00
Julius Marminge 648a6ac372 Support script editing and persist project keybindings
- add server `upsertKeybinding` flow to write `~/.t3/keybindings.json` and refresh cached config
- wire project script create/edit to save optional keybindings via the WS API
- improve script action UI with edit controls, icon picker, and preferred-script recall
- add coverage for keybinding upsert behavior in server and websocket tests
2026-02-18 00:59:06 -08:00
Julius Marminge 3537d47702 Add project script actions with run shortcuts and persistence
- add project-scoped script actions in the chat toolbar, including setup-on-worktree-create
- support dynamic `script.{id}.run` keybindings and command resolution
- persist and sync project scripts across web state, contracts, WebSocket API, and server registry
- add backend and frontend tests for script helpers, persistence, and registry behavior
2026-02-18 00:59:06 -08:00
24 changed files with 844 additions and 283 deletions

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
# Plan: Remote Execution for T3 Server + Web/Desktop Frontends
## Goal
Enable a remote `t3` backend to run on another machine while both frontend clients (browser web app and Electron desktop app) connect to it reliably.
## Constraints From Current Codebase
- Transport is a single WebSocket RPC channel plus push events.
- Desktop currently assumes local backend process ownership.
- Browser clients cannot set arbitrary WebSocket headers.
- Existing auth support was token-in-query only (`?token=...`).
## Core Design Choices Explored
### 1) Network Topology
Option A: SSH tunnel to remote loopback (`ssh -L`)
- Pros: no public WS exposure, strong default security model.
- Cons: requires SSH session lifecycle and tunnel setup per user/session.
Option B: Direct authenticated WebSocket endpoint (typically behind TLS/reverse proxy)
- Pros: simplest UX for multi-client access, no tunnel required.
- Cons: needs auth hardening and TLS termination in deployment.
Decision: Support both operationally, but implement direct authenticated WS as the primary PoC path, with SSH as a first-class secure deployment mode.
### 2) WS Authentication Mechanism
Option A: Query token (`wss://.../?token=...`)
- Pros: works in browser and Electron renderer immediately.
- Cons: token can leak via logs/history if mishandled.
Option B: `Authorization: Bearer ...` header
- Pros: cleaner for non-browser clients and service integrations.
- Cons: not settable by normal browser WebSocket API.
Option C: mTLS-only
- Pros: strongest transport auth.
- Cons: high setup complexity for a PoC.
Decision: Keep query token as browser-compatible baseline, add bearer-header support on server for non-browser clients.
### 3) Frontend Remote Endpoint Configuration
Option A: Build-time env only (`VITE_WS_URL`)
- Pros: simple in CI/deploy pipelines.
- Cons: rigid for ad-hoc remote switching.
Option B: Runtime URL params (e.g. `?t3WsUrl=...&t3Token=...`)
- Pros: no rebuild needed; easy operator workflow for PoC.
- Cons: requires token hygiene.
Option C: In-app settings UI
- Pros: best UX long-term.
- Cons: more product and persistence work.
Decision: Implement A + B (env + runtime URL params) for web app PoC.
### 4) Desktop Backend Ownership Model
Option A: Always spawn local backend (current)
- Pros: existing stable behavior.
- Cons: cannot target remote backend.
Option B: Configurable remote mode (skip local spawn; renderer connects remote WS)
- Pros: minimal invasive change; preserves existing desktop UX shell.
- Cons: some desktop-only assumptions may need future guardrails.
Decision: Implement B via env (`T3CODE_REMOTE_WS_URL`, optional `T3CODE_REMOTE_WS_TOKEN`).
### 5) Server Bind Strategy
Option A: hardcoded mode-based bind (current desktop loopback / web default)
- Pros: simple.
- Cons: remote deployment lacks explicit operator control.
Option B: explicit `T3CODE_HOST` override
- Pros: supports secure loopback-for-SSH and public bind use cases.
Decision: Implement B.
## Implemented PoC Changes
- `apps/server/src/index.ts`
- Added `T3CODE_HOST` support for explicit bind control.
- `apps/server/src/wsServer.ts`
- WS auth now accepts bearer token from `Authorization` header in addition to `?token=`.
- `apps/server/src/wsServer.test.ts`
- Added test coverage for bearer auth header path.
- `apps/web/src/wsTransport.ts`
- Added runtime remote config via URL params: `t3WsUrl`, `t3Token`.
- Added protocol normalization (`http(s)` -> `ws(s)`) and token attachment logic.
- Default same-origin fallback now respects page protocol (`wss` on https).
- `apps/web/vite.config.ts`
- Added `VITE_WS_TOKEN` injection for build/dev env usage.
- `apps/desktop/src/main.ts`
- Added remote backend mode (`T3CODE_REMOTE_WS_URL`, `T3CODE_REMOTE_WS_TOKEN`) that skips local backend spawn.
## Chosen Architecture (for this PoC)
- Remote `t3` server is the single source of truth and execution node.
- Web and desktop renderers are pure clients over authenticated WebSocket.
- Deployment can be:
- SSH tunnel + loopback bind (`T3CODE_HOST=127.0.0.1`), or
- direct authenticated WS endpoint (prefer TLS/reverse proxy).
## Follow-ups After PoC
- Move token auth from query param to short-lived session token bootstrap for browser UX/security.
- Add explicit origin allowlist + rate limiting for internet-exposed deployments.
- Add in-app connection settings UI for runtime endpoint switching.
- Add reconnect telemetry and health/status endpoint for remote ops.
+2
View File
@@ -27,6 +27,8 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
└─────────────────────────────────┘
```
Remote deployment and frontend-to-remote connection details are documented in `REMOTE.md`.
## Workspace layout
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
+124
View File
@@ -0,0 +1,124 @@
# Remote T3 Architecture (PoC)
## Summary
This PoC supports running `apps/server` on a remote machine and connecting both frontend clients to it:
- Browser web app (via env or runtime URL params)
- Electron desktop app (remote mode; no local backend spawn)
## Final Architecture
```mermaid
flowchart LR
subgraph ClientMachine[Client Machine]
Web[Web App\n(React/Vite)]
Desktop[Desktop App\n(Electron Renderer)]
end
subgraph RemoteMachine[Remote Machine]
Server[T3 Server\n(HTTP + WS RPC)]
Codex[Codex App Server\n(JSON-RPC over stdio)]
end
Web -- "wss/ws + token auth" --> Server
Desktop -- "wss/ws + token auth" --> Server
Server -- "stdio JSON-RPC" --> Codex
```
## Connection Modes
### 1) SSH Tunnel (recommended for operator security)
Run remote server loopback-only:
```bash
T3CODE_HOST=127.0.0.1 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
```
From client machine, forward port:
```bash
ssh -L 3773:127.0.0.1:3773 <user>@<remote-host>
```
Then connect clients to `ws://127.0.0.1:3773` with the same token.
### 1b) Private Tunnel With Tailscale (no public exposure)
This keeps your T3 server private to your tailnet and avoids opening router/firewall ports to the public internet.
1. Install and log in to Tailscale on both machines.
2. Verify the two machines can reach each other over tailnet:
```bash
tailscale status
```
3. On the remote machine, run T3 loopback-only:
```bash
T3CODE_HOST=127.0.0.1 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
```
4. From your client machine, create an SSH local-forward over Tailscale:
```bash
ssh -N -L 3773:127.0.0.1:3773 <user>@<remote-tailnet-name-or-100.x.y.z>
```
Now your local machine has a private tunnel at `127.0.0.1:3773` to the remote T3 server.
Use clients exactly like local:
- Web: `http://localhost:<web-port>/?t3WsUrl=ws://127.0.0.1:3773&t3Token=<token>`
- Desktop:
```bash
T3CODE_REMOTE_WS_URL=ws://127.0.0.1:3773 T3CODE_REMOTE_WS_TOKEN=<token> bun run start:desktop
```
Notes:
- If you use Tailscale SSH, the same `ssh -L` pattern works.
- This model does not expose T3 to the public internet; access is limited by your tailnet + SSH auth + T3 token.
### 2) Direct Authenticated WS
Run remote server network-bound:
```bash
T3CODE_HOST=0.0.0.0 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
```
Use TLS termination/reverse proxy in front for production internet exposure.
## Client Configuration
### Web App
Supported config sources:
- Build/dev env: `VITE_WS_URL`, optional `VITE_WS_TOKEN`
- Runtime URL params: `t3WsUrl`, `t3Token`
Examples:
```text
https://web-host/?t3WsUrl=wss://api.example.com&t3Token=secret
https://api.example.com/?t3Token=secret
```
Notes:
- If `t3WsUrl` is `http://` or `https://`, it is normalized to `ws://` or `wss://`.
- If no URL is provided, web falls back to same-origin WS using page protocol.
- To avoid putting tokens in request logs/history, prefer fragment form (supported): `#t3WsUrl=...&t3Token=...`
### Desktop App
Set remote mode env vars before launch:
- `T3CODE_REMOTE_WS_URL` (required for remote mode)
- `T3CODE_REMOTE_WS_TOKEN` (optional if URL already includes `?token=`)
Example:
```bash
T3CODE_REMOTE_WS_URL=ws://127.0.0.1:3773 T3CODE_REMOTE_WS_TOKEN=secret bun run start:desktop
```
When `T3CODE_REMOTE_WS_URL` is set, desktop skips spawning the local server process.
## Auth Behavior
Server WS auth now accepts either:
- Query token: `?token=...` (browser-compatible)
- `Authorization: Bearer <token>` header (non-browser clients)
## New/Relevant Env Vars
- Server:
- `T3CODE_HOST`
- `T3CODE_PORT`
- `T3CODE_AUTH_TOKEN`
- Web:
- `VITE_WS_URL`
- `VITE_WS_TOKEN`
- Desktop:
- `T3CODE_REMOTE_WS_URL`
- `T3CODE_REMOTE_WS_TOKEN`
+37
View File
@@ -31,6 +31,34 @@ let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
function trimToUndefined(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function resolveRemoteWsUrl(rawUrl: string, rawToken: string | undefined): string {
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
throw new Error(`Invalid T3CODE_REMOTE_WS_URL: ${rawUrl}`);
}
if (parsed.protocol === "http:") parsed.protocol = "ws:";
if (parsed.protocol === "https:") parsed.protocol = "wss:";
if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
throw new Error(`Invalid T3CODE_REMOTE_WS_URL protocol: ${parsed.protocol}`);
}
const token = trimToUndefined(rawToken);
if (token && !parsed.searchParams.get("token")) {
parsed.searchParams.set("token", token);
}
return parsed.toString();
}
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
@@ -247,6 +275,15 @@ function createWindow(): BrowserWindow {
}
async function bootstrap(): Promise<void> {
const remoteWsUrl = trimToUndefined(process.env.T3CODE_REMOTE_WS_URL);
if (remoteWsUrl) {
backendWsUrl = resolveRemoteWsUrl(remoteWsUrl, process.env.T3CODE_REMOTE_WS_TOKEN);
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
registerIpcHandlers();
mainWindow = createWindow();
return;
}
backendPort = await reserveLoopbackPort();
backendAuthToken = randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
+13 -1
View File
@@ -34,6 +34,15 @@ function parsePort(value: string | undefined): number | undefined {
return parsed;
}
function parseHost(value: string | undefined): string | undefined {
if (value === undefined) return undefined;
const trimmed = value.trim();
if (trimmed.length === 0) {
throw new Error("Invalid T3CODE_HOST: cannot be empty");
}
return trimmed;
}
function expandHomePath(input: string): string {
if (input === "~") return os.homedir();
if (input.startsWith("~/")) {
@@ -99,8 +108,10 @@ function resolveStaticDir(): string | undefined {
async function main() {
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
const requestedPort = parsePort(process.env.T3CODE_PORT);
const requestedHost = parseHost(process.env.T3CODE_HOST);
const port =
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
const host = requestedHost ?? (mode === "desktop" ? "127.0.0.1" : undefined);
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
const projectRegistry = new ProjectRegistry(stateDir);
const devUrl = process.env.VITE_DEV_SERVER_URL;
@@ -116,7 +127,7 @@ async function main() {
const server = createServer({
port,
host: mode === "desktop" ? "127.0.0.1" : undefined,
host,
cwd,
staticDir,
devUrl,
@@ -128,6 +139,7 @@ async function main() {
const url = `http://localhost:${port}`;
logger.info("T3 Code running", {
url,
host: host ?? "0.0.0.0",
cwd,
mode,
stateDir,
+33
View File
@@ -91,6 +91,14 @@ describe("server keybindings", () => {
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
});
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
@@ -163,6 +171,31 @@ describe("server keybindings", () => {
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
});
it("reports non-array config parse errors without duplicate prefix", () => {
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).not.toThrow(
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
);
});
it("cleans up temp files when atomic keybinding write fails", () => {
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
const configDir = path.join(fakeHome, ".t3");
+44 -21
View File
@@ -24,6 +24,8 @@ type WhenToken =
| { type: "lparen" }
| { type: "rparen" };
const MAX_WHEN_EXPRESSION_DEPTH = 256;
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
@@ -159,7 +161,10 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (): KeybindingWhenNode | null => {
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
const token = tokens[index];
if (!token) return null;
@@ -170,7 +175,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr();
const expressionNode = parseOr(depth + 1);
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
@@ -182,24 +187,34 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return null;
};
const parseUnary = (): KeybindingWhenNode | null => {
const token = tokens[index];
if (token?.type === "not") {
const parseUnary = (depth: number): KeybindingWhenNode | null => {
let notCount = 0;
while (tokens[index]?.type === "not") {
index += 1;
const node = parseUnary();
if (!node) return null;
return { type: "not", node };
notCount += 1;
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
}
return parsePrimary();
let node = parsePrimary(depth);
if (!node) return null;
while (notCount > 0) {
node = { type: "not", node };
notCount -= 1;
}
return node;
};
const parseAnd = (): KeybindingWhenNode | null => {
let left = parseUnary();
const parseAnd = (depth: number): KeybindingWhenNode | null => {
let left = parseUnary(depth);
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary();
const right = parseUnary(depth);
if (!right) return null;
left = { type: "and", left, right };
}
@@ -207,13 +222,13 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return left;
};
const parseOr = (): KeybindingWhenNode | null => {
let left = parseAnd();
const parseOr = (depth: number): KeybindingWhenNode | null => {
let left = parseAnd(depth);
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd();
const right = parseAnd(depth);
if (!right) return null;
left = { type: "or", left, right };
}
@@ -221,7 +236,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return left;
};
const ast = parseOr();
const ast = parseOr(0);
if (!ast || index !== tokens.length) return null;
return ast;
}
@@ -277,6 +292,12 @@ const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
const MAX_KEYBINDINGS = 256;
class KeybindingsConfigParseError extends Error {
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
}
}
function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
@@ -293,7 +314,7 @@ function loadCustomKeybindingsConfig(
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
if (options?.throwOnUnreadableConfig) {
throw new Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
@@ -328,10 +349,12 @@ function loadCustomKeybindingsConfig(
return [];
}
if (options?.throwOnUnreadableConfig) {
throw new Error(
`Unable to parse keybindings config at ${configPath}: ${
error instanceof Error ? error.message : String(error)
}`,
if (error instanceof KeybindingsConfigParseError) {
throw error;
}
throw new KeybindingsConfigParseError(
configPath,
error instanceof Error ? error.message : String(error),
{ cause: error },
);
}
+1 -1
View File
@@ -11,12 +11,12 @@ import {
type ProjectScript,
type ProjectUpdateScriptsInput,
type ProjectUpdateScriptsResult,
normalizeProjectScripts,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
normalizeProjectScripts,
} from "@t3tools/contracts";
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
+2 -1
View File
@@ -20,6 +20,7 @@ export interface PtyProcess {
export interface PtySpawnInput {
shell: string;
args?: string[];
cwd: string;
cols: number;
rows: number;
@@ -118,7 +119,7 @@ class NodePtyProcess implements PtyProcess {
export class NodePtyAdapter implements PtyAdapter {
spawn(input: PtySpawnInput): PtyProcess {
ensureNodePtySpawnHelperExecutable();
const ptyProcess = nodePty.spawn(input.shell, [], {
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
cwd: input.cwd,
cols: input.cols,
rows: input.rows,
+97
View File
@@ -196,6 +196,65 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("resizes running terminal on open when a different size is requested", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ cols: 100, rows: 24 }));
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
await manager.open(openInput({ cols: 140, rows: 40 }));
expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]);
manager.dispose();
});
it("preserves existing terminal size on open when size is omitted", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ cols: 100, rows: 24 }));
const ptyProcess = ptyAdapter.processes[0];
expect(ptyProcess).toBeDefined();
if (!ptyProcess) return;
await manager.open({
threadId: "thread-1",
cwd: globalThis.process.cwd(),
});
expect(ptyProcess.resizeCalls).toEqual([]);
ptyProcess.emitExit({ exitCode: 0, signal: 0 });
await manager.open({
threadId: "thread-1",
cwd: globalThis.process.cwd(),
});
const resumedSpawn = ptyAdapter.spawnInputs[1];
expect(resumedSpawn).toBeDefined();
if (!resumedSpawn) return;
expect(resumedSpawn.cols).toBe(100);
expect(resumedSpawn.rows).toBe(24);
manager.dispose();
});
it("uses default dimensions when opening a new terminal without size hints", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open({
threadId: "thread-1",
cwd: process.cwd(),
});
const spawned = ptyAdapter.spawnInputs[0];
expect(spawned).toBeDefined();
if (!spawned) return;
expect(spawned.cols).toBe(120);
expect(spawned.rows).toBe(30);
manager.dispose();
});
it("supports multiple terminals per thread with isolated sessions", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
@@ -466,4 +525,42 @@ describe("TerminalManager", () => {
restoreEnv();
}
});
it("injects runtime env overrides into spawned terminals", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(
openInput({
env: {
T3CODE_PROJECT_ROOT: "/repo",
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
CUSTOM_FLAG: "1",
},
}),
);
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo");
expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a");
expect(spawnInput.env.CUSTOM_FLAG).toBe("1");
manager.dispose();
});
it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => {
if (process.platform === "win32") return;
const { manager, ptyAdapter } = makeManager(5, {
shellResolver: () => "/bin/zsh",
});
await manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.shell).toBe("/bin/zsh");
expect(spawnInput.args).toEqual(["-o", "nopromptsp"]);
manager.dispose();
});
});
+108 -37
View File
@@ -26,6 +26,8 @@ import { runProcess } from "./processRunner";
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const DEFAULT_OPEN_COLS = 120;
const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
@@ -59,8 +61,16 @@ interface TerminalSessionState {
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runtimeEnv: Record<string, string> | null;
}
interface ShellCandidate {
shell: string;
args?: string[];
}
type TerminalStartInput = TerminalOpenInput & { cols: number; rows: number };
function defaultShellResolver(): string {
if (process.platform === "win32") {
return process.env.ComSpec ?? "cmd.exe";
@@ -82,34 +92,54 @@ function normalizeShellCommand(value: string | undefined): string | null {
return firstToken.replace(/^['"]|['"]$/g, "");
}
function uniqueShells(shells: Array<string | null>): string[] {
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = path.basename(command).toLowerCase();
if (process.platform !== "win32" && shellName === "zsh") {
return { shell: command, args: ["-o", "nopromptsp"] };
}
return { shell: command };
}
function formatShellCandidate(candidate: ShellCandidate): string {
if (!candidate.args || candidate.args.length === 0) return candidate.shell;
return `${candidate.shell} ${candidate.args.join(" ")}`;
}
function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
const seen = new Set<string>();
const ordered: string[] = [];
for (const shell of shells) {
if (!shell || shell.length === 0) continue;
if (seen.has(shell)) continue;
seen.add(shell);
ordered.push(shell);
const ordered: ShellCandidate[] = [];
for (const candidate of candidates) {
if (!candidate) continue;
const key = formatShellCandidate(candidate);
if (seen.has(key)) continue;
seen.add(key);
ordered.push(candidate);
}
return ordered;
}
function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver());
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
if (process.platform === "win32") {
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
return uniqueShellCandidates([
requested,
shellCandidateFromCommand(process.env.ComSpec ?? null),
shellCandidateFromCommand("powershell.exe"),
shellCandidateFromCommand("cmd.exe"),
]);
}
return uniqueShells([
return uniqueShellCandidates([
requested,
normalizeShellCommand(process.env.SHELL),
"/bin/zsh",
"/bin/bash",
"/bin/sh",
"zsh",
"bash",
"sh",
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
shellCandidateFromCommand("/bin/zsh"),
shellCandidateFromCommand("/bin/bash"),
shellCandidateFromCommand("/bin/sh"),
shellCandidateFromCommand("zsh"),
shellCandidateFromCommand("bash"),
shellCandidateFromCommand("sh"),
]);
}
@@ -241,16 +271,33 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
}
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
function createTerminalSpawnEnv(
baseEnv: NodeJS.ProcessEnv,
runtimeEnv?: Record<string, string> | null,
): NodeJS.ProcessEnv {
const spawnEnv: NodeJS.ProcessEnv = {};
for (const [key, value] of Object.entries(baseEnv)) {
if (value === undefined) continue;
if (shouldExcludeTerminalEnvKey(key)) continue;
spawnEnv[key] = value;
}
if (runtimeEnv) {
for (const [key, value] of Object.entries(runtimeEnv)) {
spawnEnv[key] = value;
}
}
return spawnEnv;
}
function normalizedRuntimeEnv(
env: Record<string, string> | undefined,
): Record<string, string> | null {
if (!env) return null;
const entries = Object.entries(env);
if (entries.length === 0) return null;
return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right)));
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string;
@@ -291,6 +338,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
if (!existing) {
await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId, input.terminalId);
const cols = input.cols ?? DEFAULT_OPEN_COLS;
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
const session: TerminalSessionState = {
threadId: input.threadId,
terminalId: input.terminalId,
@@ -301,37 +350,49 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
cols,
rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runtimeEnv: normalizedRuntimeEnv(input.env),
};
this.sessions.set(sessionKey, session);
this.startSession(session, input, "started");
this.startSession(session, { ...input, cols, rows }, "started");
return this.snapshot(session);
}
if (existing.cwd !== input.cwd) {
const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
const currentRuntimeEnv = existing.runtimeEnv;
const targetCols = input.cols ?? existing.cols;
const targetRows = input.rows ?? existing.rows;
const runtimeEnvChanged =
JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv);
if (existing.cwd !== input.cwd || runtimeEnvChanged) {
this.stopProcess(existing);
existing.cwd = input.cwd;
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
existing.runtimeEnv = nextRuntimeEnv;
}
if (!existing.process) {
this.startSession(existing, input, "started");
this.startSession(existing, { ...input, cols: targetCols, rows: targetRows }, "started");
return this.snapshot(existing);
}
if (existing.cols !== input.cols || existing.rows !== input.rows) {
existing.cols = input.cols;
existing.rows = input.rows;
existing.process.resize(input.cols, input.rows);
if (existing.cols !== targetCols || existing.rows !== targetRows) {
existing.cols = targetCols;
existing.rows = targetRows;
existing.process.resize(targetCols, targetRows);
existing.updatedAt = new Date().toISOString();
}
@@ -388,6 +449,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
if (!session) {
const cols = input.cols ?? DEFAULT_OPEN_COLS;
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
session = {
threadId: input.threadId,
terminalId: input.terminalId,
@@ -398,22 +461,27 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
cols,
rows,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
hasRunningSubprocess: false,
runtimeEnv: normalizedRuntimeEnv(input.env),
};
this.sessions.set(sessionKey, session);
} else {
this.stopProcess(session);
session.cwd = input.cwd;
session.runtimeEnv = normalizedRuntimeEnv(input.env);
}
const cols = input.cols ?? session.cols;
const rows = input.rows ?? session.rows;
session.history = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.startSession(session, input, "restarted");
this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
});
}
@@ -462,7 +530,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private startSession(
session: TerminalSessionState,
input: TerminalOpenInput,
input: TerminalStartInput,
eventType: "started" | "restarted",
): void {
this.stopProcess(session);
@@ -480,19 +548,20 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
let startedShell: string | null = null;
try {
const shellCandidates = resolveShellCandidates(this.shellResolver);
const terminalEnv = createTerminalSpawnEnv(process.env);
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
let lastSpawnError: unknown = null;
for (const shell of shellCandidates) {
for (const candidate of shellCandidates) {
try {
ptyProcess = this.ptyAdapter.spawn({
shell,
shell: candidate.shell,
...(candidate.args ? { args: candidate.args } : {}),
cwd: session.cwd,
cols: session.cols,
rows: session.rows,
env: terminalEnv,
});
startedShell = shell;
startedShell = formatShellCandidate(candidate);
break;
} catch (error) {
lastSpawnError = error;
@@ -506,7 +575,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const detail =
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
const tried =
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
shellCandidates.length > 0
? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
: "";
throw new Error(`${detail}.${tried}`.trim());
}
+24 -2
View File
@@ -143,10 +143,14 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
dispose(): void {}
}
function connectWs(port: number, token?: string): Promise<WebSocket> {
function connectWs(
port: number,
token?: string,
headers?: Record<string, string>,
): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, { headers });
const pending: PendingMessages = { queue: [], waiters: [] };
pendingBySocket.set(ws, pending);
@@ -323,6 +327,8 @@ describe("WebSocket Server", () => {
});
it("responds to server.getConfig", async () => {
const fakeHome = makeTempDir("t3code-home-");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
@@ -1055,4 +1061,20 @@ describe("WebSocket Server", () => {
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
});
it("accepts bearer auth header for websocket authentication", async () => {
server = createTestServer({ cwd: "/test", authToken: "secret-token" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
await expect(
connectWs(port, undefined, { Authorization: "Bearer wrong-token" }),
).rejects.toThrow("WebSocket connection failed");
const ws = await connectWs(port, undefined, { Authorization: "Bearer secret-token" });
connections.push(ws);
const welcome = (await waitForMessage(ws)) as WsPush;
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
});
});
+27 -8
View File
@@ -198,6 +198,28 @@ export function createServer(options: ServerOptions) {
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
function parseBearerToken(authorizationHeader: string | string[] | undefined): string | null {
const raw = Array.isArray(authorizationHeader)
? authorizationHeader[0]
: authorizationHeader;
if (!raw) return null;
const match = raw.match(/^Bearer\s+(.+)$/i);
const token = match?.[1]?.trim();
return token && token.length > 0 ? token : null;
}
function parseTokenFromQuery(requestUrl: string | undefined): string | null {
const url = new URL(requestUrl ?? "/", `http://localhost:${port}`);
const queryToken = url.searchParams.get("token");
return queryToken && queryToken.length > 0 ? queryToken : null;
}
function parseUpgradeToken(request: http.IncomingMessage): string | null {
const bearerToken = parseBearerToken(request.headers.authorization);
if (bearerToken) return bearerToken;
return parseTokenFromQuery(request.url);
}
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.write(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
@@ -212,19 +234,16 @@ export function createServer(options: ServerOptions) {
httpServer.on("upgrade", (request, socket, head) => {
if (authToken) {
let providedToken: string | null = null;
try {
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
providedToken = url.searchParams.get("token");
const providedToken = parseUpgradeToken(request);
if (providedToken !== authToken) {
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
return;
}
} catch {
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
return;
}
if (providedToken !== authToken) {
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
return;
}
}
wss.handleUpgrade(request, socket, head, (ws) => {
+76 -64
View File
@@ -102,7 +102,6 @@ import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
injectEnvIntoShellCommand,
nextProjectScriptId,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
@@ -300,9 +299,7 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
<Command
mode="none"
onItemHighlighted={(highlightedValue) => {
props.onHighlightedItemChange(
typeof highlightedValue === "string" ? highlightedValue : null,
);
props.onHighlightedItemChange(typeof highlightedValue === "string" ? highlightedValue : null);
}}
>
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
@@ -547,6 +544,15 @@ export default function ChatView() {
[composerHighlightedItemId, composerMenuItems],
);
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
const threadTerminalRuntimeEnv = useMemo(() => {
if (!activeProject) return {};
return projectScriptRuntimeEnv({
project: {
cwd: activeProject.cwd,
},
worktreePath: activeThread?.worktreePath ?? null,
});
}, [activeProject?.cwd, activeThread?.worktreePath]);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = branchesQuery.data?.isRepo ?? true;
const splitTerminalShortcutLabel = useMemo(
@@ -663,16 +669,21 @@ export default function ChatView() {
env?: Record<string, string>;
worktreePath?: string | null;
preferNewTerminal?: boolean;
rememberAsLastInvoked?: boolean;
},
) => {
if (!api || !activeThreadId || !activeProject || !activeThread) return;
setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return current;
return { ...current, [activeProject.id]: script.id };
});
if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return current;
return { ...current, [activeProject.id]: script.id };
});
}
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId =
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
activeThread.activeTerminalId ||
activeThread.terminalIds[0] ||
DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal =
@@ -701,33 +712,31 @@ export default function ChatView() {
}
setTerminalFocusRequestId((value) => value + 1);
const resolvedCommand = injectEnvIntoShellCommand(
script.command,
projectScriptRuntimeEnv({
project: {
id: activeProject.id,
name: activeProject.name,
cwd: activeProject.cwd,
},
script,
threadId: activeThreadId,
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
}),
);
const runtimeEnv = projectScriptRuntimeEnv({
project: {
cwd: activeProject.cwd,
},
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
try {
await api.terminal.open({
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
env: runtimeEnv,
...(shouldCreateNewTerminal
? {
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
}
: {}),
});
await api.terminal.write({
threadId: activeThreadId,
terminalId: targetTerminalId,
data: `${resolvedCommand}\n`,
data: `${script.command}\r`,
});
} catch (error) {
dispatch({
@@ -740,25 +749,34 @@ export default function ChatView() {
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
);
const persistProjectScripts = useCallback(
async (
project: { id: string; cwd: string; scripts: ProjectScript[] },
nextScripts: ProjectScript[],
keybinding: string | null,
keybindingCommand: string,
) => {
async (input: {
projectId: string;
projectCwd: string;
previousScripts: ProjectScript[];
nextScripts: ProjectScript[];
keybinding?: string | null;
keybindingCommand: string;
}) => {
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: input.projectId,
scripts: input.nextScripts,
});
if (!isElectron || !api) return;
let scriptsPersisted = false;
try {
const updated = await api.projects.updateScripts({
id: project.id,
scripts: nextScripts,
id: input.projectId,
scripts: input.nextScripts,
});
scriptsPersisted = true;
if (keybinding) {
if (input.keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: keybinding,
command: keybindingCommand,
key: input.keybinding,
command: input.keybindingCommand,
});
queryClient.setQueryData(
serverQueryKeys.config(),
@@ -766,7 +784,7 @@ export default function ChatView() {
current
? { ...current, keybindings: keybindingUpdate.keybindings }
: {
cwd: project.cwd,
cwd: input.projectCwd,
keybindings: keybindingUpdate.keybindings,
},
);
@@ -781,15 +799,15 @@ export default function ChatView() {
if (scriptsPersisted) {
await api.projects
.updateScripts({
id: project.id,
scripts: project.scripts,
id: input.projectId,
scripts: input.previousScripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: project.id,
scripts: project.scripts,
projectId: input.projectId,
scripts: input.previousScripts,
});
throw error;
}
@@ -819,20 +837,16 @@ export default function ChatView() {
]
: [...activeProject.scripts, nextScript];
dispatch({
type: "SET_PROJECT_SCRIPTS",
await persistProjectScripts({
projectId: activeProject.id,
scripts: nextScripts,
});
await persistProjectScripts(
activeProject,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
input.keybinding,
commandForProjectScript(nextId),
);
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(nextId),
});
},
[activeProject, dispatch, persistProjectScripts],
[activeProject, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
@@ -857,20 +871,16 @@ export default function ChatView() {
: script,
);
dispatch({
type: "SET_PROJECT_SCRIPTS",
await persistProjectScripts({
projectId: activeProject.id,
scripts: nextScripts,
});
await persistProjectScripts(
activeProject,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
input.keybinding,
commandForProjectScript(scriptId),
);
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(scriptId),
});
},
[activeProject, dispatch, persistProjectScripts],
[activeProject, persistProjectScripts],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
@@ -1336,6 +1346,7 @@ export default function ChatView() {
void runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
});
}
} catch (err) {
@@ -1888,6 +1899,7 @@ export default function ChatView() {
api={api}
threadId={activeThread.id}
cwd={gitCwd ?? activeProject.cwd}
runtimeEnv={threadTerminalRuntimeEnv}
height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
@@ -6,12 +6,12 @@ import type {
import {
BugIcon,
ChevronDownIcon,
CogIcon,
FlaskConicalIcon,
HammerIcon,
ListChecksIcon,
PlayIcon,
PlusIcon,
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
@@ -122,6 +122,9 @@ function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | n
}
if (event.altKey) parts.push("alt");
if (event.shiftKey) parts.push("shift");
if (parts.length === 0) {
return null;
}
parts.push(keyToken);
return parts.join("+");
}
@@ -222,13 +225,7 @@ export default function ProjectScriptsControl({
await onAddScript(payload);
}
setDialogOpen(false);
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setIconPickerOpen(false);
setRunOnWorktreeCreate(false);
setKeybinding("");
} catch (error) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
@@ -292,7 +289,7 @@ export default function ProjectScriptsControl({
>
<ScriptIcon icon={script.icon} className="size-4" />
<span className="truncate">
{script.runOnWorktreeCreate ? `${script.name}` : script.name}
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
</span>
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
{shortcutLabel && (
@@ -316,7 +313,7 @@ export default function ProjectScriptsControl({
openEditDialog(script);
}}
>
<CogIcon className="size-3.5" />
<SettingsIcon className="size-3.5" />
</Button>
</span>
</MenuItem>
@@ -336,7 +333,25 @@ export default function ProjectScriptsControl({
</Button>
)}
<Dialog onOpenChange={setDialogOpen} open={dialogOpen}>
<Dialog
onOpenChange={(open) => {
setDialogOpen(open);
if (!open) {
setIconPickerOpen(false);
}
}}
onOpenChangeComplete={(open) => {
if (open) return;
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setRunOnWorktreeCreate(false);
setKeybinding("");
setValidationError(null);
}}
open={dialogOpen}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
@@ -434,7 +449,6 @@ export default function ProjectScriptsControl({
variant="outline"
onClick={() => {
setDialogOpen(false);
setEditingScriptId(null);
}}
>
Cancel
@@ -111,6 +111,7 @@ interface TerminalViewportProps {
threadId: string;
terminalId: string;
cwd: string;
runtimeEnv?: Record<string, string>;
focusRequestId: number;
autoFocus: boolean;
resizeEpoch: number;
@@ -122,6 +123,7 @@ function TerminalViewport({
threadId,
terminalId,
cwd,
runtimeEnv,
focusRequestId,
autoFocus,
resizeEpoch,
@@ -274,6 +276,7 @@ function TerminalViewport({
cwd,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
...(runtimeEnv ? { env: runtimeEnv } : {}),
});
if (disposed) return;
activeTerminal.write("\u001bc");
@@ -369,7 +372,7 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
}, [api, cwd, terminalId, threadId]);
}, [api, cwd, runtimeEnv, terminalId, threadId]);
useEffect(() => {
if (!autoFocus) return;
@@ -414,6 +417,7 @@ interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
runtimeEnv?: Record<string, string>;
height: number;
terminalIds: string[];
activeTerminalId: string;
@@ -463,6 +467,7 @@ export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
runtimeEnv,
height,
terminalIds,
activeTerminalId,
@@ -778,6 +783,7 @@ export default function ThreadTerminalDrawer({
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
@@ -795,6 +801,7 @@ export default function ThreadTerminalDrawer({
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
{...(runtimeEnv ? { runtimeEnv } : {})}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
+2 -52
View File
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import {
commandForProjectScript,
injectEnvIntoShellCommand,
nextProjectScriptId,
primaryProjectScript,
projectScriptRuntimeEnv,
@@ -24,33 +23,6 @@ describe("projectScripts helpers", () => {
expect(nextProjectScriptId("!!!", [])).toBe("script");
});
it("injects environment variables for posix shells", () => {
const command = injectEnvIntoShellCommand(
"bun install",
{ T3CODE_PROJECT_ROOT: "/tmp/project" },
"MacIntel",
);
expect(command).toBe("env T3CODE_PROJECT_ROOT='/tmp/project' bun install");
});
it("injects environment variables for windows shells", () => {
const command = injectEnvIntoShellCommand(
"bun install",
{ T3CODE_PROJECT_ROOT: "C:\\\\repo path" },
"Win32",
);
expect(command).toBe('set "T3CODE_PROJECT_ROOT=C:\\\\repo path" && bun install');
});
it("escapes windows env values that trigger interpolation", () => {
const command = injectEnvIntoShellCommand(
"bun install",
{ T3CODE_PROJECT_ROOT: '%USERPROFILE%^"repo"' },
"Win32",
);
expect(command).toBe('set "T3CODE_PROJECT_ROOT=%USERPROFILE%^^""repo""" && bun install');
});
it("resolves primary and setup scripts", () => {
const scripts = [
{
@@ -75,40 +47,19 @@ describe("projectScripts helpers", () => {
it("builds default runtime env for scripts", () => {
const env = projectScriptRuntimeEnv({
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
script: {
id: "test",
name: "Test",
icon: "test",
runOnWorktreeCreate: false,
},
threadId: "thread-1",
project: { cwd: "/repo" },
worktreePath: "/repo/worktree-a",
});
expect(env).toMatchObject({
T3CODE_PROJECT_ROOT: "/repo",
T3CODE_PROJECT_ID: "project-1",
T3CODE_PROJECT_NAME: "acme-web",
T3CODE_THREAD_ID: "thread-1",
T3CODE_SCRIPT_ID: "test",
T3CODE_SCRIPT_NAME: "Test",
T3CODE_SCRIPT_ICON: "test",
T3CODE_SCRIPT_IS_SETUP: "0",
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
});
});
it("allows overriding runtime env values", () => {
const env = projectScriptRuntimeEnv({
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
script: {
id: "setup",
name: "Setup",
icon: "configure",
runOnWorktreeCreate: true,
},
threadId: "thread-1",
project: { cwd: "/repo" },
extraEnv: {
T3CODE_PROJECT_ROOT: "/custom-root",
CUSTOM_FLAG: "1",
@@ -116,7 +67,6 @@ describe("projectScripts helpers", () => {
});
expect(env.T3CODE_PROJECT_ROOT).toBe("/custom-root");
expect(env.T3CODE_SCRIPT_IS_SETUP).toBe("1");
expect(env.CUSTOM_FLAG).toBe("1");
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
});
+2 -52
View File
@@ -1,10 +1,7 @@
import type { ProjectScript } from "@t3tools/contracts";
import { isWindowsPlatform } from "./lib/utils";
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
const MAX_SCRIPT_ID_LENGTH = 64;
const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
function normalizeScriptId(value: string): string {
const cleaned = value
@@ -48,68 +45,21 @@ export function nextProjectScriptId(name: string, existingIds: Iterable<string>)
suffix += 1;
}
// This last-resort fallback only triggers after exhausting thousands of suffixes.
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
}
function shellEscapePosix(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`;
}
function shellEscapeWindowsSetValue(value: string): string {
// Only escape ^ and " for interactive cmd.exe `set "K=V"` commands.
// Do NOT escape % → %% here: that substitution only works in batch files.
// In an interactive cmd.exe session (which is what terminal.write targets),
// %% stays as literal %% and corrupts the value.
return value.replace(/\^/g, "^^").replace(/"/g, '""');
}
export function injectEnvIntoShellCommand(
command: string,
env: Record<string, string>,
platform = typeof navigator === "undefined" ? "" : navigator.platform,
): string {
const entries = Object.entries(env).filter(
([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,
);
if (entries.length === 0) {
return command;
}
if (isWindowsPlatform(platform)) {
const prefixes = entries.map(
([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,
);
return `${prefixes.join(" && ")} && ${command}`;
}
const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");
return `env ${assignments} ${command}`;
}
interface ProjectScriptRuntimeEnvInput {
project: {
id: string;
name: string;
cwd: string;
};
script: Pick<ProjectScript, "id" | "name" | "icon" | "runOnWorktreeCreate">;
threadId: string;
worktreePath?: string | null;
extraEnv?: Record<string, string>;
}
export function projectScriptRuntimeEnv(
input: ProjectScriptRuntimeEnvInput,
): Record<string, string> {
export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
const env: Record<string, string> = {
T3CODE_PROJECT_ROOT: input.project.cwd,
T3CODE_PROJECT_ID: input.project.id,
T3CODE_PROJECT_NAME: input.project.name,
T3CODE_THREAD_ID: input.threadId,
T3CODE_SCRIPT_ID: input.script.id,
T3CODE_SCRIPT_NAME: input.script.name,
T3CODE_SCRIPT_ICON: input.script.icon,
T3CODE_SCRIPT_IS_SETUP: input.script.runOnWorktreeCreate ? "1" : "0",
};
if (input.worktreePath) {
env.T3CODE_WORKTREE_PATH = input.worktreePath;
+10 -8
View File
@@ -8,12 +8,7 @@ import {
useReducer,
} from "react";
import {
type ProviderEvent,
type ProviderSession,
type TerminalEvent,
normalizeProjectScripts,
} from "@t3tools/contracts";
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
import { resolveModelSlug } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
@@ -170,6 +165,7 @@ function normalizeRunningTerminalIds(
.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))];
}
@@ -577,7 +573,10 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
if (
isNewTerminal &&
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
@@ -647,7 +646,10 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
if (
isNewTerminal &&
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
+52 -7
View File
@@ -10,6 +10,49 @@ interface PendingRequest {
const REQUEST_TIMEOUT_MS = 60_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
const RUNTIME_WS_URL_PARAM = "t3WsUrl";
const RUNTIME_WS_TOKEN_PARAM = "t3Token";
function trimToUndefined(value: string | null | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function readRuntimeParam(name: string): string | undefined {
const fromSearch = trimToUndefined(new URLSearchParams(window.location.search).get(name));
if (fromSearch) return fromSearch;
const hash = window.location.hash.startsWith("#")
? window.location.hash.slice(1)
: window.location.hash;
return trimToUndefined(new URLSearchParams(hash).get(name));
}
function normalizeWsUrl(raw: string): string {
try {
const parsed = new URL(raw, window.location.href);
if (parsed.protocol === "http:") parsed.protocol = "ws:";
if (parsed.protocol === "https:") parsed.protocol = "wss:";
return parsed.toString();
} catch {
return raw;
}
}
function withAuthToken(url: string, token: string | undefined): string {
if (!token) return url;
try {
const parsed = new URL(url, window.location.href);
if (!parsed.searchParams.get("token")) {
parsed.searchParams.set("token", token);
}
return parsed.toString();
} catch {
const glue = url.includes("?") ? "&" : "?";
return `${url}${glue}token=${encodeURIComponent(token)}`;
}
}
export class WsTransport {
private ws: WebSocket | null = null;
@@ -23,16 +66,18 @@ export class WsTransport {
constructor(url?: string) {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const runtimeWsUrl = readRuntimeParam(RUNTIME_WS_URL_PARAM);
const runtimeWsToken = readRuntimeParam(RUNTIME_WS_TOKEN_PARAM);
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
// In production, the page is served by the WS server on the same host:port.
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
this.url =
url ??
(bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`);
const envToken = trimToUndefined(import.meta.env.VITE_WS_TOKEN as string | undefined);
const defaultProtocol = window.location.protocol === "https:" ? "wss" : "ws";
const defaultUrl = `${defaultProtocol}://${window.location.host}`;
const selectedUrl = trimToUndefined(
url ?? bridgeUrl ?? runtimeWsUrl ?? trimToUndefined(envUrl) ?? defaultUrl,
);
this.url = withAuthToken(normalizeWsUrl(selectedUrl ?? defaultUrl), runtimeWsToken ?? envToken);
this.connect();
}
+1
View File
@@ -16,6 +16,7 @@ export default defineConfig({
define: {
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
"import.meta.env.VITE_WS_TOKEN": JSON.stringify(process.env.VITE_WS_TOKEN ?? ""),
},
experimental: {
enableNativePlugin: true,
+15 -15
View File
@@ -84,21 +84,11 @@ export const projectUpdateScriptsResultSchema = z.object({
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
export type ProjectScript = z.infer<typeof projectScriptSchema>;
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
/**
* Deduplicate scripts by ID (first occurrence wins), trim string fields,
* and enforce at most one script with `runOnWorktreeCreate: true`.
* Deduplicate scripts by ID and enforce at most one `runOnWorktreeCreate: true`
* flag (the first one wins). Fields are trimmed defensively so this is safe to
* call on data that hasn't been through Zod parsing.
*/
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
const seenIds = new Set<string>();
@@ -108,11 +98,10 @@ export function normalizeProjectScripts(scripts: readonly ProjectScript[]): Proj
if (id.length === 0 || seenIds.has(id)) continue;
seenIds.add(id);
deduped.push({
...script,
id,
name: script.name.trim(),
command: script.command.trim(),
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
});
}
@@ -132,3 +121,14 @@ export function normalizeProjectScripts(scripts: readonly ProjectScript[]): Proj
}
return normalized;
}
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
+30
View File
@@ -42,6 +42,36 @@ describe("terminalOpenInputSchema", () => {
});
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
});
it("accepts optional env overrides", () => {
const parsed = terminalOpenInputSchema.parse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 100,
rows: 24,
env: {
T3CODE_PROJECT_ROOT: "/tmp/project",
CUSTOM_FLAG: "1",
},
});
expect(parsed.env).toMatchObject({
T3CODE_PROJECT_ROOT: "/tmp/project",
CUSTOM_FLAG: "1",
});
});
it("rejects invalid env keys", () => {
const result = terminalOpenInputSchema.safeParse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 100,
rows: 24,
env: {
"bad-key": "1",
},
});
expect(result.success).toBe(false);
});
});
describe("terminalWriteInputSchema", () => {
+8 -2
View File
@@ -5,6 +5,11 @@ 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);
const terminalEnvKeySchema = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(128);
const terminalEnvValueSchema = z.string().max(8_192);
const terminalEnvSchema = z
.record(terminalEnvKeySchema, terminalEnvValueSchema)
.refine((env) => Object.keys(env).length <= 128, "Too many terminal env vars");
export const terminalThreadInputSchema = z.object({
threadId: z.string().trim().min(1),
@@ -16,8 +21,9 @@ export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
cwd: z.string().trim().min(1),
cols: terminalColsSchema,
rows: terminalRowsSchema,
cols: terminalColsSchema.optional(),
rows: terminalRowsSchema.optional(),
env: terminalEnvSchema.optional(),
});
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({