Compare commits

...
Author SHA1 Message Date
Cursor Agent d169cfd54d 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.
2026-02-18 08:34:24 +00:00
Cursor Agent e31fcbdf26 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 08:20:50 +00:00
Julius Marminge b033c60d41 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-17 23:19:28 -08:00
Julius Marmingeandcodex 2a5525a9e5 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-17 23:09:09 -08:00
Julius Marminge 0e500fe025 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-17 23:01:21 -08:00
Julius Marmingeandcodex 442bab63e8 Require modifier keys for script keybinding capture
Co-authored-by: codex <[email protected]>
2026-02-17 22:21:13 -08:00
Julius Marmingeandcodex 191883e599 Fix keybindings parse error wrapping behavior
Co-authored-by: codex <[email protected]>
2026-02-17 22:08:13 -08:00
Julius Marmingeandcodex dca0b9fb33 Refactor project script persistence flow in ChatView
Co-authored-by: codex <[email protected]>
2026-02-17 21:50:40 -08:00
Julius Marmingeandcodex 4437965135 Label setup scripts in project action menu
Co-authored-by: codex <[email protected]>
2026-02-17 21:47:54 -08:00
Julius Marmingeandcodex 5f94bfd5fe Fix Windows percent escaping in script env injection
Co-authored-by: codex <[email protected]>
2026-02-17 21:33:22 -08:00
Julius Marmingeandcodex 718a682782 Address second-pass PR feedback on parser hardening
Co-authored-by: codex <[email protected]>
2026-02-17 21:32:30 -08:00
Julius Marmingeandcodex b7cf04ba93 Address PR review feedback for scripts/keybindings handling
Co-authored-by: codex <[email protected]>
2026-02-17 21:17:57 -08:00
Julius Marmingeandcodex 56bce5617a 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-17 21:07:05 -08:00
Julius Marminge 1327646d42 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-17 19:53:22 -08:00
Julius Marminge 4f36062f9b 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-17 19:52:27 -08:00
34 changed files with 2159 additions and 145 deletions

No files matched your search

+1
View File
@@ -53,6 +53,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
### Key Syntax
+158 -2
View File
@@ -1,8 +1,34 @@
import { assert, describe, it } from "vitest";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, afterEach, describe, expect, it, vi } from "vitest";
import { compileResolvedKeybindingRule, parseKeybindingShortcut } from "./keybindings";
import {
compileResolvedKeybindingRule,
parseKeybindingShortcut,
upsertKeybindingRule,
} from "./keybindings";
describe("server keybindings", () => {
const tempDirs: string[] = [];
const logger = {
warn: vi.fn(),
};
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
vi.restoreAllMocks();
logger.warn.mockReset();
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("parses shortcuts including plus key", () => {
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
key: "j",
@@ -65,5 +91,135 @@ 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", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
const resolved = upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persisted).toEqual([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
});
it("replaces existing custom keybinding for the same command", () => {
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
configPath,
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
});
it("refuses to overwrite malformed keybindings config", () => {
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, "{ not-json", "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/Unable to parse keybindings config/);
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
});
it("reports non-array config parse errors without duplicate prefix", () => {
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).not.toThrow(
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
);
});
it("cleans up temp files when atomic keybinding write fails", () => {
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
vi.spyOn(fs, "renameSync").mockImplementation(() => {
throw new Error("rename failed");
});
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(/rename failed/);
expect(fs.readFileSync(configPath, "utf8")).toBe(
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
);
const tempFiles = fs
.readdirSync(configDir)
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
expect(tempFiles).toEqual([]);
});
});
+163 -71
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;
}
@@ -274,6 +289,93 @@ function compileDefaultKeybindings(): ResolvedKeybindingsConfig {
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
const MAX_KEYBINDINGS = 256;
class KeybindingsConfigParseError extends Error {
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
}
}
function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
function loadCustomKeybindingsConfig(
logger: KeybindingsLogger,
options?: {
throwOnUnreadableConfig?: boolean;
},
): KeybindingsConfig {
const configPath = resolveKeybindingsConfigPath();
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
if (options?.throwOnUnreadableConfig) {
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [];
}
const sanitized: KeybindingsConfig = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = keybindingRuleSchema.safeParse(entry);
if (result.success) {
if (!compileResolvedKeybindingRule(result.data)) {
invalidEntries += 1;
continue;
}
sanitized.push(result.data);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
return sanitized;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
if (options?.throwOnUnreadableConfig) {
if (error instanceof KeybindingsConfigParseError) {
throw error;
}
throw new KeybindingsConfigParseError(
configPath,
error instanceof Error ? error.message : String(error),
{ cause: error },
);
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
});
return [];
}
}
function writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
try {
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
fs.renameSync(tempPath, configPath);
} catch (error) {
fs.rmSync(tempPath, { force: true });
throw error;
}
}
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
if (custom.length === 0) {
@@ -286,70 +388,60 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
);
const merged = [...retainedDefaults, ...custom];
if (merged.length <= 256) {
if (merged.length <= MAX_KEYBINDINGS) {
return merged;
}
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
return merged.slice(-256);
return merged.slice(-MAX_KEYBINDINGS);
}
export function loadResolvedKeybindingsConfig(
logger: KeybindingsLogger,
): ResolvedKeybindingsConfig {
const configPath = path.join(os.homedir(), ".t3", "keybindings.json");
try {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
const sanitized: ResolvedKeybindingsConfig = [];
let invalidEntries = 0;
for (const entry of parsed) {
const result = keybindingRuleSchema.safeParse(entry);
if (result.success) {
const compiled = compileResolvedKeybindingRule(result.data);
if (!compiled) {
invalidEntries += 1;
continue;
}
sanitized.push(compiled);
continue;
}
invalidEntries += 1;
}
if (invalidEntries > 0) {
logger.warn("ignoring invalid keybinding entries", {
path: configPath,
invalidEntries,
totalEntries: parsed.length,
});
}
const overriddenCommands = new Set(sanitized.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + sanitized.length;
const merged = mergeWithDefaultKeybindings(sanitized);
if (mergedBeforeCapLength > 256) {
logger.warn("truncating merged keybindings config to max entries", {
path: configPath,
maxEntries: 256,
});
}
return merged;
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
}
logger.warn("ignoring malformed keybindings config", {
path: configPath,
error: error instanceof Error ? error.message : String(error),
const customConfig = loadCustomKeybindingsConfig(logger);
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
const mergedBeforeCapLength =
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
.length + compiledCustomConfig.length;
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
logger.warn("truncating merged keybindings config to max entries", {
path: resolveKeybindingsConfigPath(),
maxEntries: MAX_KEYBINDINGS,
});
}
return [...DEFAULT_RESOLVED_KEYBINDINGS];
return merged;
}
export function upsertKeybindingRule(
logger: KeybindingsLogger,
rawRule: unknown,
): ResolvedKeybindingsConfig {
const rule = keybindingRuleSchema.parse(rawRule);
if (!compileResolvedKeybindingRule(rule)) {
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
}
const configPath = resolveKeybindingsConfigPath();
const customConfig = loadCustomKeybindingsConfig(logger, {
throwOnUnreadableConfig: true,
});
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
const cappedConfig =
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
if (nextConfig.length > MAX_KEYBINDINGS) {
logger.warn("truncating keybindings config to max entries", {
path: configPath,
maxEntries: MAX_KEYBINDINGS,
});
}
fs.mkdirSync(path.dirname(configPath), { recursive: true });
writeConfigAtomically(configPath, cappedConfig);
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
return mergeWithDefaultKeybindings(compiledCustomConfig);
}
+113
View File
@@ -0,0 +1,113 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ProjectRegistry } from "./projectRegistry";
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
describe("ProjectRegistry scripts", () => {
it("stores and reloads project scripts", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "run",
name: "Run",
command: "bun run dev",
icon: "play",
runOnWorktreeCreate: false,
},
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[1]?.id).toBe("setup");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(true);
const reloaded = new ProjectRegistry(stateDir);
const listed = reloaded.list();
expect(listed).toHaveLength(1);
expect(listed[0]?.scripts).toHaveLength(2);
expect(listed[0]?.scripts[0]?.id).toBe("run");
expect(listed[0]?.scripts[1]?.id).toBe("setup");
});
it("deduplicates script ids and allows only one setup script", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const projectDir = makeTempDir("t3code-project-registry-project-");
const registry = new ProjectRegistry(stateDir);
const created = registry.add({ cwd: projectDir }).project;
const updated = registry.updateScripts({
id: created.id,
scripts: [
{
id: "setup",
name: "Setup",
command: "echo setup",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "setup",
name: "Setup Duplicate",
command: "echo duplicate",
icon: "configure",
runOnWorktreeCreate: true,
},
{
id: "another",
name: "Another Setup",
command: "echo another",
icon: "play",
runOnWorktreeCreate: true,
},
],
});
expect(updated.project.scripts).toHaveLength(2);
expect(updated.project.scripts[0]?.id).toBe("setup");
expect(updated.project.scripts[0]?.runOnWorktreeCreate).toBe(true);
expect(updated.project.scripts[1]?.id).toBe("another");
expect(updated.project.scripts[1]?.runOnWorktreeCreate).toBe(false);
});
it("throws when updating scripts for an unknown project id", () => {
const stateDir = makeTempDir("t3code-project-registry-state-");
const registry = new ProjectRegistry(stateDir);
expect(() =>
registry.updateScripts({
id: "missing-project",
scripts: [],
}),
).toThrowError("Project not found");
});
});
+97 -3
View File
@@ -8,11 +8,30 @@ import {
type ProjectListResult,
type ProjectRecord,
type ProjectRemoveInput,
type ProjectScript,
type ProjectUpdateScriptsInput,
type ProjectUpdateScriptsResult,
projectAddInputSchema,
projectRecordSchema,
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
} from "@t3tools/contracts";
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
const cloned: ProjectScript[] = [];
for (const script of scripts) {
cloned.push({
id: script.id,
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
});
}
return cloned;
}
function normalizeCwd(rawCwd: string): string {
const resolved = path.resolve(rawCwd.trim());
const normalized = path.normalize(resolved);
@@ -48,7 +67,10 @@ export class ProjectRegistry {
}
list(): ProjectListResult {
return this.projects.map((project) => ({ ...project }));
return this.projects.map((project) => ({
...project,
scripts: cloneScripts(project.scripts),
}));
}
add(raw: ProjectAddInput): ProjectAddResult {
@@ -60,7 +82,13 @@ export class ProjectRegistry {
const existing = this.projects.find((project) => normalizeCwd(project.cwd) === normalizedCwd);
if (existing) {
return { project: { ...existing }, created: false };
return {
project: {
...existing,
scripts: cloneScripts(existing.scripts),
},
created: false,
};
}
const now = new Date().toISOString();
@@ -68,13 +96,20 @@ export class ProjectRegistry {
id: randomUUID(),
cwd: normalizedCwd,
name: inferProjectName(normalizedCwd),
scripts: [],
createdAt: now,
updatedAt: now,
};
this.projects = [project, ...this.projects];
this.persist();
return { project: { ...project }, created: true };
return {
project: {
...project,
scripts: cloneScripts(project.scripts),
},
created: true,
};
}
remove(raw: ProjectRemoveInput): void {
@@ -88,6 +123,31 @@ export class ProjectRegistry {
this.persist();
}
updateScripts(raw: ProjectUpdateScriptsInput): ProjectUpdateScriptsResult {
const input = projectUpdateScriptsInputSchema.parse(raw);
const index = this.projects.findIndex((project) => project.id === input.id);
if (index < 0) {
throw new Error(`Project not found: ${input.id}`);
}
const nextScripts = dedupeScriptsById(projectScriptsSchema.parse(input.scripts));
const nextUpdatedAt = new Date().toISOString();
const nextProject: ProjectRecord = {
...this.projects[index]!,
scripts: nextScripts,
updatedAt: nextUpdatedAt,
};
const nextProjects = [...this.projects];
nextProjects[index] = nextProject;
this.projects = nextProjects;
this.persist();
return {
project: { ...nextProject, scripts: cloneScripts(nextProject.scripts) },
};
}
private loadFromDisk(): ProjectRecord[] {
const loaded = this.readPersistedProjects();
const deduped = new Map<string, ProjectRecord>();
@@ -107,6 +167,7 @@ export class ProjectRegistry {
cwd: normalizedCwd,
name:
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
scripts: dedupeScriptsById(project.scripts),
};
deduped.set(normalizedCwd, normalizedProject);
normalizedProjects.push(normalizedProject);
@@ -121,6 +182,7 @@ export class ProjectRegistry {
source.id !== project.id ||
source.cwd !== project.cwd ||
source.name !== project.name ||
JSON.stringify(source.scripts) !== JSON.stringify(project.scripts) ||
source.createdAt !== project.createdAt ||
source.updatedAt !== project.updatedAt
);
@@ -170,3 +232,35 @@ export class ProjectRegistry {
fs.renameSync(tempFile, this.filePath);
}
}
function dedupeScriptsById(scripts: readonly ProjectScript[]): ProjectScript[] {
const seenIds = new Set<string>();
const deduped: ProjectScript[] = [];
for (const script of scripts) {
if (seenIds.has(script.id)) continue;
seenIds.add(script.id);
deduped.push({
id: script.id,
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
});
}
let setupAssigned = false;
const normalized: ProjectScript[] = [];
for (const script of deduped) {
if (!script.runOnWorktreeCreate) {
normalized.push(script);
continue;
}
if (!setupAssigned) {
setupAssigned = true;
normalized.push(script);
continue;
}
normalized.push({ ...script, runOnWorktreeCreate: false });
}
return normalized;
}
+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());
}
+91
View File
@@ -323,6 +323,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();
@@ -491,6 +493,59 @@ describe("WebSocket Server", () => {
expect(secondResponse.result).toEqual(firstResponse.result);
});
it("upserts keybinding rules and updates cached server config", async () => {
const fakeHome = makeTempDir("t3code-home-upsert-keybinding-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const keybindingsPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
server = createTestServer({ cwd: "/my/workspace" });
await server.start();
const addr = server.httpServer.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const upsertResponse = await sendRequest(ws, WS_METHODS.serverUpsertKeybinding, {
key: "mod+shift+r",
command: "script.run-tests.run",
});
expect(upsertResponse.error).toBeUndefined();
expect(upsertResponse.result).toEqual({
keybindings: mergeWithDefaultsForTest([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]),
});
const persistedConfig = JSON.parse(fs.readFileSync(keybindingsPath, "utf8")) as Array<{
key: string;
command: string;
}>;
expect(persistedConfig).toEqual([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]);
const configResponse = await sendRequest(ws, WS_METHODS.serverGetConfig);
expect(configResponse.error).toBeUndefined();
expect(configResponse.result).toEqual({
cwd: "/my/workspace",
keybindings: mergeWithDefaultsForTest([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+r", command: "script.run-tests.run" },
]),
});
});
it("warns and ignores unsupported keybindings config format", async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const fakeHome = makeTempDir("t3code-home-unsupported-format-");
@@ -756,6 +811,42 @@ describe("WebSocket Server", () => {
expect(projectId).toBeTruthy();
if (!projectId) return;
const updatedScripts = await sendRequest(ws, WS_METHODS.projectsUpdateScripts, {
id: projectId,
scripts: [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
],
});
expect(updatedScripts.error).toBeUndefined();
const scriptPayload = (
updatedScripts.result as {
project: {
scripts: Array<{
id: string;
name: string;
command: string;
icon: string;
runOnWorktreeCreate: boolean;
}>;
};
}
).project.scripts;
expect(scriptPayload).toEqual([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]);
const removed = await sendRequest(ws, WS_METHODS.projectsRemove, {
id: projectId,
});
+10 -2
View File
@@ -31,7 +31,7 @@ import {
removeGitWorktree,
} from "./git";
import { TerminalManager } from "./terminalManager";
import { loadResolvedKeybindingsConfig } from "./keybindings";
import { loadResolvedKeybindingsConfig, upsertKeybindingRule } from "./keybindings";
import { searchWorkspaceEntries } from "./workspaceEntries";
const MIME_TYPES: Record<string, string> = {
@@ -92,7 +92,7 @@ export function createServer(options: ServerOptions) {
const logger = createLogger("ws");
const logWebSocketEvents =
explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl);
const keybindingsConfig = loadResolvedKeybindingsConfig(logger);
let keybindingsConfig = loadResolvedKeybindingsConfig(logger);
function logOutgoingPush(push: WsPush, recipients: number) {
if (!logWebSocketEvents) return;
@@ -322,6 +322,8 @@ export function createServer(options: ServerOptions) {
case WS_METHODS.projectsSearchEntries:
return searchWorkspaceEntries(request.params as never);
case WS_METHODS.projectsUpdateScripts:
return projectRegistry.updateScripts(request.params as never);
case WS_METHODS.shellOpenInEditor: {
const params = request.params as {
@@ -421,6 +423,12 @@ export function createServer(options: ServerOptions) {
keybindings: keybindingsConfig,
};
case WS_METHODS.serverUpsertKeybinding:
keybindingsConfig = upsertKeybindingRule(logger, request.params);
return {
keybindings: keybindingsConfig,
};
default:
throw new Error(`Unknown method: ${request.method}`);
}
+2
View File
@@ -85,6 +85,7 @@ function AutoProjectBootstrap() {
cwd: payload.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
},
});
dispatch({
@@ -146,6 +147,7 @@ function DesktopProjectBootstrap() {
cwd: project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: project.scripts,
})),
});
bootstrappedRef.current = true;
+352 -20
View File
@@ -1,9 +1,10 @@
import {
EDITORS,
type EditorId,
type ProjectEntry,
ModelSlug,
type NativeApi,
type ProjectEntry,
type ProjectScript,
ModelSlug,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -30,7 +31,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer/debouncer";
import { gitBranchesQueryOptions, gitCreateWorktreeMutationOptions } from "~/lib/gitReactQuery";
import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery";
import { serverConfigQueryOptions } from "~/lib/serverReactQuery";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
import { isElectron } from "../env";
import { buildBootstrapInput } from "../historyBootstrap";
@@ -59,17 +60,18 @@ import {
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { useStore } from "../store";
import { MAX_THREAD_TERMINAL_COUNT, type ChatImageAttachment } from "../types";
import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ChatImageAttachment,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import BranchToolbar from "./BranchToolbar";
import GitActionsControl from "./GitActionsControl";
import {
isOpenFavoriteEditorShortcut,
isTerminalCloseShortcut,
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
resolveShortcutCommand,
shortcutLabelForCommand,
} from "../keybindings";
import ChatMarkdown from "./ChatMarkdown";
@@ -97,6 +99,14 @@ import { CursorIcon, Icon } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
} from "~/projectScripts";
function formatMessageMeta(createdAt: string, duration: string | null): string {
if (!duration) return formatTimestamp(createdAt);
@@ -104,6 +114,7 @@ function formatMessageMeta(createdAt: string, duration: string | null): string {
}
const LAST_EDITOR_KEY = "t3code:last-editor";
const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
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 =
@@ -117,6 +128,26 @@ const SEARCHABLE_MODEL_OPTIONS = MODEL_OPTIONS.map(({ slug, name }) => ({
searchSlug: slug.toLowerCase(),
searchName: name.toLowerCase(),
}));
const SCRIPT_TERMINAL_COLS = 120;
const SCRIPT_TERMINAL_ROWS = 30;
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
if (!stored) return {};
try {
const parsed: unknown = JSON.parse(stored);
if (!parsed || typeof parsed !== "object") return {};
return Object.fromEntries(
Object.entries(parsed).filter(
(entry): entry is [string, string] =>
typeof entry[0] === "string" && typeof entry[1] === "string",
),
);
} catch {
return {};
}
}
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
@@ -323,6 +354,9 @@ export default function ChatView() {
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
const [composerCursor, setComposerCursor] = useState(0);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
Record<string, string>
>(() => readLastInvokedScriptByProjectFromStorage());
const messagesScrollRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
@@ -510,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(
@@ -618,6 +661,227 @@ export default function ChatView() {
},
[activeThread?.terminalIds.length, activeThreadId, api, dispatch],
);
const runProjectScript = useCallback(
async (
script: ProjectScript,
options?: {
cwd?: string;
env?: Record<string, string>;
worktreePath?: string | null;
preferNewTerminal?: boolean;
rememberAsLastInvoked?: boolean;
},
) => {
if (!api || !activeThreadId || !activeProject || !activeThread) return;
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;
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal =
wantsNewTerminal && activeThread.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}`
: baseTerminalId;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
if (shouldCreateNewTerminal) {
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
} else {
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId: targetTerminalId,
});
}
setTerminalFocusRequestId((value) => value + 1);
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,
env: runtimeEnv,
...(shouldCreateNewTerminal
? {
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
}
: {}),
});
await api.terminal.write({
threadId: activeThreadId,
terminalId: targetTerminalId,
data: `${script.command}\r`,
});
} catch (error) {
dispatch({
type: "SET_ERROR",
threadId: activeThreadId,
error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`,
});
}
},
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
);
const persistProjectScripts = useCallback(
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: input.projectId,
scripts: input.nextScripts,
});
scriptsPersisted = true;
if (input.keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: input.keybinding,
command: input.keybindingCommand,
});
queryClient.setQueryData(
serverQueryKeys.config(),
(current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
current
? { ...current, keybindings: keybindingUpdate.keybindings }
: {
cwd: input.projectCwd,
keybindings: keybindingUpdate.keybindings,
},
);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: updated.project.id,
scripts: updated.project.scripts,
});
} catch (error) {
if (scriptsPersisted) {
await api.projects
.updateScripts({
id: input.projectId,
scripts: input.previousScripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: input.projectId,
scripts: input.previousScripts,
});
throw error;
}
},
[api, dispatch, queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
if (!activeProject) return;
const nextId = nextProjectScriptId(
input.name,
activeProject.scripts.map((script) => script.id),
);
const nextScript: ProjectScript = {
id: nextId,
name: input.name,
command: input.command,
icon: input.icon,
runOnWorktreeCreate: input.runOnWorktreeCreate,
};
const nextScripts = input.runOnWorktreeCreate
? [
...activeProject.scripts.map((script) =>
script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
),
nextScript,
]
: [...activeProject.scripts, nextScript];
await persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(nextId),
});
},
[activeProject, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
if (!activeProject) return;
const existingScript = activeProject.scripts.find((script) => script.id === scriptId);
if (!existingScript) {
throw new Error("Script not found.");
}
const updatedScript: ProjectScript = {
...existingScript,
name: input.name,
command: input.command,
icon: input.icon,
runOnWorktreeCreate: input.runOnWorktreeCreate,
};
const nextScripts = activeProject.scripts.map((script) =>
script.id === scriptId
? updatedScript
: input.runOnWorktreeCreate
? { ...script, runOnWorktreeCreate: false }
: script,
);
await persistProjectScripts({
projectId: activeProject.id,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(scriptId),
});
},
[activeProject, persistProjectScripts],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return;
@@ -642,6 +906,21 @@ export default function ChatView() {
}
};
useEffect(() => {
try {
if (Object.keys(lastInvokedScriptByProjectId).length === 0) {
localStorage.removeItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
return;
}
localStorage.setItem(
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
JSON.stringify(lastInvokedScriptByProjectId),
);
} catch {
// Ignore storage write failures (private mode, quota exceeded, etc.)
}
}, [lastInvokedScriptByProjectId]);
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
const workLogCount = workLogEntries.length;
@@ -793,14 +1072,17 @@ export default function ChatView() {
terminalOpen: Boolean(activeThread?.terminalOpen),
};
if (isTerminalToggleShortcut(event, keybindings, { context: shortcutContext })) {
const command = resolveShortcutCommand(event, keybindings, { context: shortcutContext });
if (!command) return;
if (command === "terminal.toggle") {
event.preventDefault();
event.stopPropagation();
toggleTerminalVisibility();
return;
}
if (isTerminalSplitShortcut(event, keybindings, { context: shortcutContext })) {
if (command === "terminal.split") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
@@ -814,7 +1096,7 @@ export default function ChatView() {
return;
}
if (isTerminalCloseShortcut(event, keybindings, { context: shortcutContext })) {
if (command === "terminal.close") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) return;
@@ -822,27 +1104,39 @@ export default function ChatView() {
return;
}
if (!isTerminalNewShortcut(event, keybindings, { context: shortcutContext })) return;
if (command === "terminal.new") {
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
createNewTerminal();
return;
}
const scriptId = projectScriptIdFromCommand(command);
if (!scriptId || !activeProject) return;
const script = activeProject.scripts.find((entry) => entry.id === scriptId);
if (!script) return;
event.preventDefault();
event.stopPropagation();
if (!activeThread?.terminalOpen) {
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: true,
});
}
createNewTerminal();
void runProjectScript(script);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [
activeProject,
activeThread?.terminalOpen,
activeThread?.activeTerminalId,
activeThreadId,
closeTerminal,
createNewTerminal,
dispatch,
runProjectScript,
splitTerminal,
keybindings,
toggleTerminalVisibility,
@@ -1047,6 +1341,14 @@ export default function ChatView() {
branch: result.worktree.branch,
worktreePath: result.worktree.path,
});
const setupScript = setupProjectScript(activeProject.scripts);
if (setupScript) {
void runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
rememberAsLastInvoked: false,
});
}
} catch (err) {
dispatch({
type: "SET_ERROR",
@@ -1325,10 +1627,19 @@ export default function ChatView() {
<ChatHeader
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
api={api}
gitCwd={gitCwd}
diffOpen={state.diffOpen}
onRunProjectScript={(script) => {
void runProjectScript(script);
}}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onToggleDiff={onToggleDiff}
/>
</header>
@@ -1588,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}
@@ -1652,20 +1964,30 @@ export default function ChatView() {
interface ChatHeaderProps {
activeThreadTitle: string;
activeProjectName: string | undefined;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
api: NativeApi | undefined;
gitCwd: string | null;
diffOpen: boolean;
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
onToggleDiff: () => void;
}
const ChatHeader = memo(function ChatHeader({
activeThreadTitle,
activeProjectName,
activeProjectScripts,
preferredScriptId,
keybindings,
api,
gitCwd,
diffOpen,
onRunProjectScript,
onAddProjectScript,
onUpdateProjectScript,
onToggleDiff,
}: ChatHeaderProps) {
return (
@@ -1677,6 +1999,16 @@ const ChatHeader = memo(function ChatHeader({
{activeProjectName && <Badge variant="outline">{activeProjectName}</Badge>}
</div>
<div className="shrink-0 flex items-center gap-3">
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
keybindings={keybindings}
preferredScriptId={preferredScriptId}
onRunScript={onRunProjectScript}
onAddScript={onAddProjectScript}
onUpdateScript={onUpdateProjectScript}
/>
)}
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
<Button
@@ -0,0 +1,464 @@
import type {
ProjectScript,
ProjectScriptIcon,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import {
BugIcon,
ChevronDownIcon,
FlaskConicalIcon,
HammerIcon,
ListChecksIcon,
PlayIcon,
PlusIcon,
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import { isMacPlatform } from "~/lib/utils";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Group, GroupSeparator } from "./ui/group";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Switch } from "./ui/switch";
import { Textarea } from "./ui/textarea";
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
{ id: "play", label: "Play" },
{ id: "test", label: "Test" },
{ id: "lint", label: "Lint" },
{ id: "configure", label: "Configure" },
{ id: "build", label: "Build" },
{ id: "debug", label: "Debug" },
];
function ScriptIcon({
icon,
className = "size-3.5",
}: {
icon: ProjectScriptIcon;
className?: string;
}) {
if (icon === "test") return <FlaskConicalIcon className={className} />;
if (icon === "lint") return <ListChecksIcon className={className} />;
if (icon === "configure") return <WrenchIcon className={className} />;
if (icon === "build") return <HammerIcon className={className} />;
if (icon === "debug") return <BugIcon className={className} />;
return <PlayIcon className={className} />;
}
export interface NewProjectScriptInput {
name: string;
command: string;
icon: ProjectScriptIcon;
runOnWorktreeCreate: boolean;
keybinding: string | null;
}
interface ProjectScriptsControlProps {
scripts: ProjectScript[];
keybindings: ResolvedKeybindingsConfig;
preferredScriptId?: string | null;
onRunScript: (script: ProjectScript) => void;
onAddScript: (input: NewProjectScriptInput) => Promise<void> | void;
onUpdateScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void> | void;
}
function normalizeShortcutKeyToken(key: string): string | null {
const normalized = key.toLowerCase();
if (
normalized === "meta" ||
normalized === "control" ||
normalized === "ctrl" ||
normalized === "shift" ||
normalized === "alt" ||
normalized === "option"
) {
return null;
}
if (normalized === " ") return "space";
if (normalized === "escape") return "esc";
if (normalized === "arrowup") return "arrowup";
if (normalized === "arrowdown") return "arrowdown";
if (normalized === "arrowleft") return "arrowleft";
if (normalized === "arrowright") return "arrowright";
if (normalized.length === 1) return normalized;
if (normalized.startsWith("f") && normalized.length <= 3) return normalized;
if (normalized === "enter" || normalized === "tab" || normalized === "backspace") {
return normalized;
}
if (normalized === "delete" || normalized === "home" || normalized === "end") {
return normalized;
}
if (normalized === "pageup" || normalized === "pagedown") return normalized;
return null;
}
function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {
const keyToken = normalizeShortcutKeyToken(event.key);
if (!keyToken) return null;
const parts: string[] = [];
if (isMacPlatform(navigator.platform)) {
if (event.metaKey) parts.push("mod");
if (event.ctrlKey) parts.push("ctrl");
} else {
if (event.ctrlKey) parts.push("mod");
if (event.metaKey) parts.push("meta");
}
if (event.altKey) parts.push("alt");
if (event.shiftKey) parts.push("shift");
if (parts.length === 0) {
return null;
}
parts.push(keyToken);
return parts.join("+");
}
function keybindingValueForCommand(
keybindings: ResolvedKeybindingsConfig,
command: string,
): string | null {
for (let index = keybindings.length - 1; index >= 0; index -= 1) {
const binding = keybindings[index];
if (!binding || binding.command !== command) continue;
const parts: string[] = [];
if (binding.shortcut.modKey) parts.push("mod");
if (binding.shortcut.ctrlKey) parts.push("ctrl");
if (binding.shortcut.metaKey) parts.push("meta");
if (binding.shortcut.altKey) parts.push("alt");
if (binding.shortcut.shiftKey) parts.push("shift");
const keyToken =
binding.shortcut.key === " "
? "space"
: binding.shortcut.key === "escape"
? "esc"
: binding.shortcut.key;
parts.push(keyToken);
return parts.join("+");
}
return null;
}
export default function ProjectScriptsControl({
scripts,
keybindings,
preferredScriptId = null,
onRunScript,
onAddScript,
onUpdateScript,
}: ProjectScriptsControlProps) {
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [command, setCommand] = useState("");
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
const [iconPickerOpen, setIconPickerOpen] = useState(false);
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [validationError, setValidationError] = useState<string | null>(null);
const primaryScript = useMemo(() => {
if (preferredScriptId) {
const preferred = scripts.find((script) => script.id === preferredScriptId);
if (preferred) return preferred;
}
return primaryProjectScript(scripts);
}, [preferredScriptId, scripts]);
const isEditing = editingScriptId !== null;
const dropdownItemClassName =
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Tab") return;
event.preventDefault();
if (event.key === "Backspace" || event.key === "Delete") {
setKeybinding("");
return;
}
const next = keybindingFromEvent(event);
if (!next) return;
setKeybinding(next);
};
const submitAddScript = async (event: FormEvent) => {
event.preventDefault();
const trimmedName = name.trim();
const trimmedCommand = command.trim();
if (trimmedName.length === 0) {
setValidationError("Name is required.");
return;
}
if (trimmedCommand.length === 0) {
setValidationError("Command is required.");
return;
}
setValidationError(null);
try {
const payload = {
name: trimmedName,
command: trimmedCommand,
icon,
runOnWorktreeCreate,
keybinding: keybinding.trim() || null,
} satisfies NewProjectScriptInput;
if (editingScriptId) {
await onUpdateScript(editingScriptId, payload);
} else {
await onAddScript(payload);
}
setDialogOpen(false);
setIconPickerOpen(false);
} catch (error) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
};
const openAddDialog = () => {
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setIconPickerOpen(false);
setRunOnWorktreeCreate(false);
setKeybinding("");
setValidationError(null);
setDialogOpen(true);
};
const openEditDialog = (script: ProjectScript) => {
setEditingScriptId(script.id);
setName(script.name);
setCommand(script.command);
setIcon(script.icon);
setIconPickerOpen(false);
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
setValidationError(null);
setDialogOpen(true);
};
return (
<>
{primaryScript ? (
<Group aria-label="Project scripts">
<Button
size="xs"
variant="outline"
onClick={() => onRunScript(primaryScript)}
title={`Run ${primaryScript.name}`}
>
<ScriptIcon icon={primaryScript.icon} />
<span className="ml-0.5">{primaryScript.name}</span>
</Button>
<GroupSeparator />
<Menu highlightItemOnHover={false}>
<MenuTrigger
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
>
<ChevronDownIcon className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
{scripts.map((script) => {
const shortcutLabel = shortcutLabelForCommand(
keybindings,
commandForProjectScript(script.id),
);
return (
<MenuItem
key={script.id}
className={`group ${dropdownItemClassName}`}
onClick={() => onRunScript(script)}
>
<ScriptIcon icon={script.icon} className="size-4" />
<span className="truncate">
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
</span>
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
{shortcutLabel && (
<MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
{shortcutLabel}
</MenuShortcut>
)}
<Button
type="button"
variant="ghost"
size="icon-xs"
className="absolute right-0 top-1/2 size-6 -translate-y-1/2 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"
aria-label={`Edit ${script.name}`}
onPointerDown={(event) => {
event.preventDefault();
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
openEditDialog(script);
}}
>
<SettingsIcon className="size-3.5" />
</Button>
</span>
</MenuItem>
);
})}
<MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
<PlusIcon className="size-4" />
Add action
</MenuItem>
</MenuPopup>
</Menu>
</Group>
) : (
<Button size="xs" variant="outline" onClick={openAddDialog}>
<PlusIcon className="size-3.5" />
Add action
</Button>
)}
<Dialog
onOpenChange={(open) => {
setDialogOpen(open);
if (!open) {
setIconPickerOpen(false);
}
}}
onOpenChangeComplete={(open) => {
if (open) return;
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setRunOnWorktreeCreate(false);
setKeybinding("");
setValidationError(null);
}}
open={dialogOpen}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
<DialogDescription>
Actions are project-scoped commands you can run from the top bar or keybindings.
</DialogDescription>
</DialogHeader>
<DialogPanel>
<form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
<div className="space-y-1.5">
<Label htmlFor="script-name">Name</Label>
<div className="flex items-center gap-2">
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
<PopoverTrigger
render={
<Button
type="button"
variant="outline"
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
aria-label="Choose icon"
/>
}
>
<ScriptIcon icon={icon} className="size-4.5" />
</PopoverTrigger>
<PopoverPopup align="start">
<div className="grid grid-cols-3 gap-2">
{SCRIPT_ICONS.map((entry) => {
const isSelected = entry.id === icon;
return (
<button
key={entry.id}
type="button"
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
isSelected
? "border-primary/70 bg-primary/10"
: "border-border/70 hover:bg-accent/60"
}`}
onClick={() => {
setIcon(entry.id);
setIconPickerOpen(false);
}}
>
<ScriptIcon icon={entry.id} className="size-4" />
<span>{entry.label}</span>
</button>
);
})}
</div>
</PopoverPopup>
</Popover>
<Input
id="script-name"
placeholder="Test"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-keybinding">Keybinding</Label>
<Input
id="script-keybinding"
placeholder="Press shortcut"
value={keybinding}
readOnly
onKeyDown={captureKeybinding}
/>
<p className="text-xs text-muted-foreground">
Press a shortcut. Use <code>Backspace</code> to clear.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-command">Command</Label>
<Textarea
id="script-command"
placeholder="bun test"
value={command}
onChange={(event) => setCommand(event.target.value)}
/>
</div>
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
<span>Run automatically on worktree creation</span>
<Switch
checked={runOnWorktreeCreate}
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
/>
</label>
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
</form>
</DialogPanel>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
setDialogOpen(false);
}}
>
Cancel
</Button>
<Button form={addScriptFormId} type="submit">
{isEditing ? "Save changes" : "Save action"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
</>
);
}
+2
View File
@@ -214,6 +214,7 @@ export default function Sidebar() {
cwd: result.project.cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: result.project.scripts,
};
const existingById = state.projects.find((p) => p.id === project.id);
const existingByCwd = state.projects.find((p) => p.cwd === project.cwd);
@@ -241,6 +242,7 @@ export default function Sidebar() {
cwd,
model: DEFAULT_MODEL,
expanded: true,
scripts: [],
};
dispatch({ type: "ADD_PROJECT", project });
handleNewThread(project.id);
@@ -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}
+16
View File
@@ -16,6 +16,7 @@ import {
isTerminalNewShortcut,
isTerminalSplitShortcut,
isTerminalToggleShortcut,
resolveShortcutCommand,
shortcutLabelForCommand,
terminalNavigationShortcutData,
type ShortcutEventLike,
@@ -339,6 +340,21 @@ describe("cross-command precedence", () => {
});
});
describe("resolveShortcutCommand", () => {
it("returns dynamic script commands", () => {
const keybindings = compile([
{ shortcut: modShortcut("r"), command: "script.setup.run" },
]);
assert.strictEqual(
resolveShortcutCommand(event({ key: "r", ctrlKey: true }), keybindings, {
platform: "Linux",
}),
"script.setup.run",
);
});
});
describe("formatShortcutLabel", () => {
it("formats labels for macOS", () => {
assert.strictEqual(
+2 -2
View File
@@ -100,11 +100,11 @@ function matchesCommandShortcut(
return resolveShortcutCommand(event, keybindings, options) === command;
}
function resolveShortcutCommand(
export function resolveShortcutCommand(
event: ShortcutEventLike,
keybindings: ResolvedKeybindingsConfig,
options?: ShortcutMatchOptions,
): KeybindingCommand | null {
): string | null {
const platform = resolvePlatform(options);
const context = resolveContext(options);
+7
View File
@@ -20,6 +20,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.2-codex",
expanded: true,
scripts: [],
},
],
threads: [
@@ -69,6 +70,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [
@@ -119,6 +121,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
threads: [],
@@ -140,6 +143,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
@@ -187,6 +191,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
@@ -231,6 +236,7 @@ describe("hydratePersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
@@ -313,6 +319,7 @@ describe("toPersistedState", () => {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [thread],
+3
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { projectScriptSchema } from "@t3tools/contracts";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import {
@@ -19,6 +20,7 @@ const persistedProjectSchema = z.object({
cwd: z.string().min(1),
model: z.string().min(1),
expanded: z.boolean(),
scripts: z.array(projectScriptSchema).default([]),
});
const persistedMessageSchema = z.object({
@@ -140,6 +142,7 @@ function hydrateProject(
return {
...project,
model: resolveModelSlug(maybeMigrateLegacyModel(project.model, isLegacyPayload)),
scripts: project.scripts,
};
}
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vitest";
import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
} from "./projectScripts";
describe("projectScripts helpers", () => {
it("builds and parses script run commands", () => {
const command = commandForProjectScript("lint");
expect(command).toBe("script.lint.run");
expect(projectScriptIdFromCommand(command)).toBe("lint");
expect(projectScriptIdFromCommand("terminal.toggle")).toBeNull();
});
it("slugifies and dedupes project script ids", () => {
expect(nextProjectScriptId("Run Tests", [])).toBe("run-tests");
expect(nextProjectScriptId("Run Tests", ["run-tests"])).toBe("run-tests-2");
expect(nextProjectScriptId("!!!", [])).toBe("script");
});
it("resolves primary and setup scripts", () => {
const scripts = [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure" as const,
runOnWorktreeCreate: true,
},
{
id: "test",
name: "Test",
command: "bun test",
icon: "test" as const,
runOnWorktreeCreate: false,
},
];
expect(primaryProjectScript(scripts)?.id).toBe("test");
expect(setupProjectScript(scripts)?.id).toBe("setup");
});
it("builds default runtime env for scripts", () => {
const env = projectScriptRuntimeEnv({
project: { cwd: "/repo" },
worktreePath: "/repo/worktree-a",
});
expect(env).toMatchObject({
T3CODE_PROJECT_ROOT: "/repo",
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
});
});
it("allows overriding runtime env values", () => {
const env = projectScriptRuntimeEnv({
project: { cwd: "/repo" },
extraEnv: {
T3CODE_PROJECT_ROOT: "/custom-root",
CUSTOM_FLAG: "1",
},
});
expect(env.T3CODE_PROJECT_ROOT).toBe("/custom-root");
expect(env.CUSTOM_FLAG).toBe("1");
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
});
});
+80
View File
@@ -0,0 +1,80 @@
import type { ProjectScript } from "@t3tools/contracts";
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
const MAX_SCRIPT_ID_LENGTH = 64;
function normalizeScriptId(value: string): string {
const cleaned = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
if (cleaned.length === 0) {
return "script";
}
if (cleaned.length <= MAX_SCRIPT_ID_LENGTH) {
return cleaned;
}
return cleaned.slice(0, MAX_SCRIPT_ID_LENGTH).replace(/-+$/g, "") || "script";
}
export function commandForProjectScript(scriptId: string): string {
return `script.${scriptId}.run`;
}
export function projectScriptIdFromCommand(command: string): string | null {
const match = SCRIPT_RUN_COMMAND_PATTERN.exec(command.trim());
return match?.[1] ?? null;
}
export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {
const taken = new Set(Array.from(existingIds));
const baseId = normalizeScriptId(name);
if (!taken.has(baseId)) return baseId;
let suffix = 2;
while (suffix < 10_000) {
const candidate = `${baseId}-${suffix}`;
const safeCandidate =
candidate.length <= MAX_SCRIPT_ID_LENGTH
? candidate
: `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;
if (!taken.has(safeCandidate)) {
return safeCandidate;
}
suffix += 1;
}
// This last-resort fallback only triggers after exhausting thousands of suffixes.
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
}
interface ProjectScriptRuntimeEnvInput {
project: {
cwd: string;
};
worktreePath?: string | null;
extraEnv?: Record<string, string>;
}
export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
const env: Record<string, string> = {
T3CODE_PROJECT_ROOT: input.project.cwd,
};
if (input.worktreePath) {
env.T3CODE_WORKTREE_PATH = input.worktreePath;
}
if (input.extraEnv) {
return { ...env, ...input.extraEnv };
}
return env;
}
export function primaryProjectScript(scripts: ProjectScript[]): ProjectScript | null {
const regular = scripts.find((script) => !script.runOnWorktreeCreate);
return regular ?? scripts[0] ?? null;
}
export function setupProjectScript(scripts: ProjectScript[]): ProjectScript | null {
return scripts.find((script) => script.runOnWorktreeCreate) ?? null;
}
+76
View File
@@ -74,6 +74,7 @@ function makeState(thread: Thread): AppState {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [thread],
@@ -507,6 +508,7 @@ describe("store reducer thread continuity", () => {
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
{
id: "project-old-b",
@@ -514,6 +516,7 @@ describe("store reducer thread continuity", () => {
cwd: "/tmp/b",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
@@ -540,6 +543,7 @@ describe("store reducer thread continuity", () => {
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
});
@@ -554,6 +558,76 @@ describe("store reducer thread continuity", () => {
expect(next.activeThreadId).toBe("thread-a");
});
it("treats empty scripts from sync as authoritative", () => {
const state: AppState = {
projects: [
{
id: "project-old-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: true,
scripts: [
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
],
},
],
threads: [makeThread({ id: "thread-a", projectId: "project-old-a" })],
activeThreadId: "thread-a",
runtimeMode: "full-access",
diffOpen: false,
};
const next = reducer(state, {
type: "SYNC_PROJECTS",
projects: [
{
id: "project-new-a",
name: "A",
cwd: "/tmp/a",
model: "gpt-5.3-codex",
expanded: false,
scripts: [],
},
],
});
expect(next.projects[0]?.scripts).toEqual([]);
});
it("updates project scripts", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_PROJECT_SCRIPTS",
projectId: "project-1",
scripts: [
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
],
});
expect(next.projects[0]?.scripts).toEqual([
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
]);
});
it("deletes a project and all of its threads", () => {
const state: AppState = {
projects: [
@@ -563,6 +637,7 @@ describe("store reducer thread continuity", () => {
cwd: "/tmp/one",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
{
id: "project-2",
@@ -570,6 +645,7 @@ describe("store reducer thread continuity", () => {
cwd: "/tmp/two",
model: "gpt-5.3-codex",
expanded: true,
scripts: [],
},
],
threads: [
+47
View File
@@ -17,6 +17,7 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type ProjectScript,
type Project,
type RuntimeMode,
type Thread,
@@ -27,6 +28,7 @@ import {
type Action =
| { type: "ADD_PROJECT"; project: Project }
| { type: "SET_PROJECT_SCRIPTS"; projectId: string; scripts: ProjectScript[] }
| { type: "SYNC_PROJECTS"; projects: Project[] }
| { type: "TOGGLE_PROJECT"; projectId: string }
| { type: "DELETE_PROJECT"; projectId: string }
@@ -163,6 +165,38 @@ function normalizeRunningTerminalIds(
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeProjectScripts(scripts: ProjectScript[]): ProjectScript[] {
const deduped: ProjectScript[] = [];
const seenIds = new Set<string>();
for (const script of scripts) {
const id = script.id.trim();
if (id.length === 0 || seenIds.has(id)) continue;
seenIds.add(id);
deduped.push({
...script,
id,
name: script.name.trim(),
command: script.command.trim(),
});
}
let setupAssigned = false;
const normalized: ProjectScript[] = [];
for (const script of deduped) {
if (!script.runOnWorktreeCreate) {
normalized.push(script);
continue;
}
if (!setupAssigned) {
setupAssigned = true;
normalized.push(script);
continue;
}
normalized.push({ ...script, runOnWorktreeCreate: false });
}
return normalized;
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
@@ -426,20 +460,33 @@ export function reducer(state: AppState, action: Action): AppState {
{
...action.project,
model: resolveModelSlug(action.project.model),
scripts: normalizeProjectScripts(action.project.scripts),
},
],
};
case "SET_PROJECT_SCRIPTS":
return {
...state,
projects: state.projects.map((project) =>
project.id === action.projectId
? { ...project, scripts: normalizeProjectScripts(action.scripts) }
: project,
),
};
case "SYNC_PROJECTS": {
const previousByCwd = new Map(
state.projects.map((project) => [project.cwd, project] as const),
);
const nextProjects = action.projects.map((project) => {
const previous = previousByCwd.get(project.cwd);
const scripts = normalizeProjectScripts(project.scripts);
return {
...project,
model: resolveModelSlug(previous?.model ?? project.model),
expanded: previous?.expanded ?? project.expanded,
scripts,
};
});
const previousProjectById = new Map(
+7 -1
View File
@@ -1,4 +1,8 @@
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import type {
ProjectScript as ContractProjectScript,
ProviderEvent,
ProviderSession,
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
@@ -6,6 +10,7 @@ export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export const MAX_THREAD_TERMINAL_COUNT = 4;
export type ProjectScript = ContractProjectScript;
export interface ThreadTerminalGroup {
id: string;
@@ -38,6 +43,7 @@ export interface Project {
cwd: string;
model: string;
expanded: boolean;
scripts: ProjectScript[];
}
export interface Thread {
+2
View File
@@ -99,6 +99,7 @@ export function createWsNativeApi(): NativeApi {
add: (input) => transport.request(WS_METHODS.projectsAdd, input),
remove: (input) => transport.request(WS_METHODS.projectsRemove, input),
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
updateScripts: (input) => transport.request(WS_METHODS.projectsUpdateScripts, input),
},
shell: {
openInEditor: (cwd, editor) =>
@@ -142,6 +143,7 @@ export function createWsNativeApi(): NativeApi {
},
server: {
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
},
};
+5
View File
@@ -32,6 +32,8 @@ import type {
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
ProjectRemoveInput,
ProjectUpdateScriptsInput,
ProjectUpdateScriptsResult,
} from "./project";
import type { ServerConfig } from "./server";
import type {
@@ -44,6 +46,7 @@ import type {
TerminalWriteInput,
} from "./terminal";
import type { NewTodoInput, Todo } from "./todo";
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor" },
@@ -93,6 +96,7 @@ export interface NativeApi {
add: (input: ProjectAddInput) => Promise<ProjectAddResult>;
remove: (input: ProjectRemoveInput) => Promise<void>;
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
updateScripts: (input: ProjectUpdateScriptsInput) => Promise<ProjectUpdateScriptsResult>;
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
@@ -119,5 +123,6 @@ export interface NativeApi {
};
server: {
getConfig: () => Promise<ServerConfig>;
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
};
}
+9 -1
View File
@@ -32,11 +32,19 @@ describe("keybindings contracts", () => {
assert.throws(() =>
keybindingRuleSchema.parse({
key: "mod+j",
command: "invalid.command",
command: "script.Test.run",
}),
);
});
it("accepts dynamic script run commands", () => {
const parsed = keybindingRuleSchema.parse({
key: "mod+r",
command: "script.setup.run",
});
assert.strictEqual(parsed.command, "script.setup.run");
});
it("parses keybindings array payload", () => {
const parsed = keybindingsConfigSchema.parse([
{ key: "mod+j", command: "terminal.toggle" },
+11 -1
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
export const keybindingCommandSchema = z.enum([
export const STATIC_KEYBINDING_COMMANDS = [
"terminal.toggle",
"terminal.split",
"terminal.new",
@@ -8,6 +8,16 @@ export const keybindingCommandSchema = z.enum([
"chat.new",
"chat.newLocal",
"editor.openFavorite",
] as const;
export const keybindingCommandSchema = z.union([
z.enum(STATIC_KEYBINDING_COMMANDS),
z
.string()
.trim()
.min(1)
.max(96)
.regex(/^script\.[a-z0-9][a-z0-9-]*\.run$/),
]);
const keybindingValueSchema = z.string().trim().min(1).max(64);
+62
View File
@@ -7,6 +7,8 @@ import {
projectSearchEntriesResultSchema,
projectListResultSchema,
projectRemoveInputSchema,
projectUpdateScriptsInputSchema,
projectUpdateScriptsResultSchema,
} from "./project";
describe("project contracts", () => {
@@ -16,6 +18,7 @@ describe("project contracts", () => {
id: "project-1",
cwd: "/tmp/project",
name: "project",
scripts: [],
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
@@ -36,6 +39,7 @@ describe("project contracts", () => {
id: "project-1",
cwd: "/tmp/project",
name: "project",
scripts: [],
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
@@ -82,4 +86,62 @@ describe("project contracts", () => {
expect(parsed.entries).toHaveLength(2);
expect(parsed.entries[0]?.kind).toBe("directory");
});
it("parses update scripts input", () => {
const parsed = projectUpdateScriptsInputSchema.parse({
id: "project-1",
scripts: [
{
id: "test",
name: "Test",
command: "bun test",
icon: "test",
runOnWorktreeCreate: false,
},
],
});
expect(parsed.scripts).toHaveLength(1);
expect(parsed.scripts[0]?.id).toBe("test");
});
it("parses debug icon in scripts", () => {
const parsed = projectUpdateScriptsInputSchema.parse({
id: "project-1",
scripts: [
{
id: "debug",
name: "Debug",
command: "bun --inspect test",
icon: "debug",
runOnWorktreeCreate: false,
},
],
});
expect(parsed.scripts[0]?.icon).toBe("debug");
});
it("parses update scripts result", () => {
const parsed = projectUpdateScriptsResultSchema.parse({
project: {
id: "project-1",
cwd: "/tmp/project",
name: "project",
scripts: [
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
],
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
});
expect(parsed.project.scripts[0]?.id).toBe("setup");
});
});
+42
View File
@@ -1,9 +1,38 @@
import { z } from "zod";
export const PROJECT_SCRIPT_ICON_VALUES = [
"play",
"test",
"lint",
"configure",
"build",
"debug",
] as const;
export const projectScriptIconSchema = z.enum(PROJECT_SCRIPT_ICON_VALUES);
export const projectScriptSchema = z
.object({
id: z
.string()
.trim()
.min(1)
.max(64)
.regex(/^[a-z0-9][a-z0-9-]*$/),
name: z.string().trim().min(1).max(64),
command: z.string().trim().min(1).max(10_000),
icon: projectScriptIconSchema,
runOnWorktreeCreate: z.boolean().default(false),
})
.strict();
export const projectScriptsSchema = z.array(projectScriptSchema).max(64);
export const projectRecordSchema = z.object({
id: z.string().min(1),
cwd: z.string().min(1),
name: z.string().min(1),
scripts: projectScriptsSchema.default([]),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
});
@@ -44,6 +73,17 @@ export const projectSearchEntriesResultSchema = z.object({
truncated: z.boolean(),
});
export const projectUpdateScriptsInputSchema = z.object({
id: z.string().min(1),
scripts: projectScriptsSchema,
});
export const projectUpdateScriptsResultSchema = z.object({
project: projectRecordSchema,
});
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
export type ProjectScript = z.infer<typeof projectScriptSchema>;
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
@@ -53,3 +93,5 @@ export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInput
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>;
+9 -1
View File
@@ -1,9 +1,17 @@
import { z } from "zod";
import { resolvedKeybindingsConfigSchema } from "./keybindings";
import { keybindingRuleSchema, resolvedKeybindingsConfigSchema } from "./keybindings";
export const serverConfigSchema = z.object({
cwd: z.string().min(1),
keybindings: resolvedKeybindingsConfigSchema.default([]),
});
export const serverUpsertKeybindingInputSchema = keybindingRuleSchema;
export const serverUpsertKeybindingResultSchema = z.object({
keybindings: resolvedKeybindingsConfigSchema.default([]),
});
export type ServerConfig = z.infer<typeof serverConfigSchema>;
export type ServerUpsertKeybindingInput = z.infer<typeof serverUpsertKeybindingInputSchema>;
export type ServerUpsertKeybindingResult = z.infer<typeof serverUpsertKeybindingResultSchema>;
+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({
+2
View File
@@ -16,6 +16,7 @@ export const WS_METHODS = {
projectsAdd: "projects.add",
projectsRemove: "projects.remove",
projectsSearchEntries: "projects.searchEntries",
projectsUpdateScripts: "projects.updateScripts",
// Shell methods
shellOpenInEditor: "shell.openInEditor",
@@ -41,6 +42,7 @@ export const WS_METHODS = {
// Server meta
serverGetConfig: "server.getConfig",
serverUpsertKeybinding: "server.upsertKeybinding",
} as const;
// ── Push Event Channels ──────────────────────────────────────────────