Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e1ca36b46 |
No files matched your search
@@ -91,14 +91,6 @@ 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", () => {
|
||||
@@ -171,31 +163,6 @@ describe("server keybindings", () => {
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
it("reports non-array config parse errors without duplicate prefix", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
|
||||
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).not.toThrow(
|
||||
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
|
||||
);
|
||||
});
|
||||
|
||||
it("cleans up temp files when atomic keybinding write fails", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
|
||||
@@ -24,8 +24,6 @@ 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" },
|
||||
@@ -161,10 +159,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
|
||||
if (!tokens || tokens.length === 0) return null;
|
||||
let index = 0;
|
||||
|
||||
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
|
||||
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
const parsePrimary = (): KeybindingWhenNode | null => {
|
||||
const token = tokens[index];
|
||||
if (!token) return null;
|
||||
|
||||
@@ -175,7 +170,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
|
||||
|
||||
if (token.type === "lparen") {
|
||||
index += 1;
|
||||
const expressionNode = parseOr(depth + 1);
|
||||
const expressionNode = parseOr();
|
||||
const closeToken = tokens[index];
|
||||
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
||||
return null;
|
||||
@@ -187,34 +182,24 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseUnary = (depth: number): KeybindingWhenNode | null => {
|
||||
let notCount = 0;
|
||||
while (tokens[index]?.type === "not") {
|
||||
const parseUnary = (): KeybindingWhenNode | null => {
|
||||
const token = tokens[index];
|
||||
if (token?.type === "not") {
|
||||
index += 1;
|
||||
notCount += 1;
|
||||
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
const node = parseUnary();
|
||||
if (!node) return null;
|
||||
return { type: "not", node };
|
||||
}
|
||||
|
||||
let node = parsePrimary(depth);
|
||||
if (!node) return null;
|
||||
|
||||
while (notCount > 0) {
|
||||
node = { type: "not", node };
|
||||
notCount -= 1;
|
||||
}
|
||||
|
||||
return node;
|
||||
return parsePrimary();
|
||||
};
|
||||
|
||||
const parseAnd = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseUnary(depth);
|
||||
const parseAnd = (): KeybindingWhenNode | null => {
|
||||
let left = parseUnary();
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "and") {
|
||||
index += 1;
|
||||
const right = parseUnary(depth);
|
||||
const right = parseUnary();
|
||||
if (!right) return null;
|
||||
left = { type: "and", left, right };
|
||||
}
|
||||
@@ -222,13 +207,13 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
|
||||
return left;
|
||||
};
|
||||
|
||||
const parseOr = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseAnd(depth);
|
||||
const parseOr = (): KeybindingWhenNode | null => {
|
||||
let left = parseAnd();
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "or") {
|
||||
index += 1;
|
||||
const right = parseAnd(depth);
|
||||
const right = parseAnd();
|
||||
if (!right) return null;
|
||||
left = { type: "or", left, right };
|
||||
}
|
||||
@@ -236,7 +221,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
|
||||
return left;
|
||||
};
|
||||
|
||||
const ast = parseOr(0);
|
||||
const ast = parseOr();
|
||||
if (!ast || index !== tokens.length) return null;
|
||||
return ast;
|
||||
}
|
||||
@@ -292,12 +277,6 @@ 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);
|
||||
}
|
||||
@@ -314,7 +293,7 @@ function loadCustomKeybindingsConfig(
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
|
||||
throw new Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
|
||||
}
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
@@ -349,12 +328,10 @@ function loadCustomKeybindingsConfig(
|
||||
return [];
|
||||
}
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
if (error instanceof KeybindingsConfigParseError) {
|
||||
throw error;
|
||||
}
|
||||
throw new KeybindingsConfigParseError(
|
||||
configPath,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
throw new Error(
|
||||
`Unable to parse keybindings config at ${configPath}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,12 +11,12 @@ import {
|
||||
type ProjectScript,
|
||||
type ProjectUpdateScriptsInput,
|
||||
type ProjectUpdateScriptsResult,
|
||||
normalizeProjectScripts,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
projectScriptsSchema,
|
||||
projectUpdateScriptsInputSchema,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
|
||||
@@ -20,7 +20,6 @@ export interface PtyProcess {
|
||||
|
||||
export interface PtySpawnInput {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
cwd: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
@@ -119,7 +118,7 @@ class NodePtyProcess implements PtyProcess {
|
||||
export class NodePtyAdapter implements PtyAdapter {
|
||||
spawn(input: PtySpawnInput): PtyProcess {
|
||||
ensureNodePtySpawnHelperExecutable();
|
||||
const ptyProcess = nodePty.spawn(input.shell, input.args ?? [], {
|
||||
const ptyProcess = nodePty.spawn(input.shell, [], {
|
||||
cwd: input.cwd,
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
|
||||
@@ -196,65 +196,6 @@ 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" }));
|
||||
@@ -525,42 +466,4 @@ 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();
|
||||
});
|
||||
});
|
||||
@@ -26,8 +26,6 @@ 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>;
|
||||
@@ -61,16 +59,8 @@ 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";
|
||||
@@ -92,54 +82,34 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
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[] {
|
||||
function uniqueShells(shells: Array<string | null>): string[] {
|
||||
const seen = new Set<string>();
|
||||
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);
|
||||
const ordered: string[] = [];
|
||||
for (const shell of shells) {
|
||||
if (!shell || shell.length === 0) continue;
|
||||
if (seen.has(shell)) continue;
|
||||
seen.add(shell);
|
||||
ordered.push(shell);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
||||
function resolveShellCandidates(shellResolver: () => string): string[] {
|
||||
const requested = normalizeShellCommand(shellResolver());
|
||||
|
||||
if (process.platform === "win32") {
|
||||
return uniqueShellCandidates([
|
||||
requested,
|
||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
||||
shellCandidateFromCommand("powershell.exe"),
|
||||
shellCandidateFromCommand("cmd.exe"),
|
||||
]);
|
||||
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
|
||||
}
|
||||
|
||||
return uniqueShellCandidates([
|
||||
return uniqueShells([
|
||||
requested,
|
||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
||||
shellCandidateFromCommand("/bin/zsh"),
|
||||
shellCandidateFromCommand("/bin/bash"),
|
||||
shellCandidateFromCommand("/bin/sh"),
|
||||
shellCandidateFromCommand("zsh"),
|
||||
shellCandidateFromCommand("bash"),
|
||||
shellCandidateFromCommand("sh"),
|
||||
normalizeShellCommand(process.env.SHELL),
|
||||
"/bin/zsh",
|
||||
"/bin/bash",
|
||||
"/bin/sh",
|
||||
"zsh",
|
||||
"bash",
|
||||
"sh",
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -271,33 +241,16 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
|
||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
||||
}
|
||||
|
||||
function createTerminalSpawnEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
runtimeEnv?: Record<string, string> | null,
|
||||
): NodeJS.ProcessEnv {
|
||||
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const spawnEnv: NodeJS.ProcessEnv = {};
|
||||
for (const [key, value] of Object.entries(baseEnv)) {
|
||||
if (value === undefined) continue;
|
||||
if (shouldExcludeTerminalEnvKey(key)) continue;
|
||||
spawnEnv[key] = value;
|
||||
}
|
||||
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;
|
||||
@@ -338,8 +291,6 @@ 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,
|
||||
@@ -350,49 +301,37 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
cols,
|
||||
rows,
|
||||
cols: input.cols,
|
||||
rows: input.rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.startSession(session, { ...input, cols, rows }, "started");
|
||||
this.startSession(session, input, "started");
|
||||
return this.snapshot(session);
|
||||
}
|
||||
|
||||
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) {
|
||||
if (existing.cwd !== input.cwd) {
|
||||
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, cols: targetCols, rows: targetRows }, "started");
|
||||
this.startSession(existing, input, "started");
|
||||
return this.snapshot(existing);
|
||||
}
|
||||
|
||||
if (existing.cols !== targetCols || existing.rows !== targetRows) {
|
||||
existing.cols = targetCols;
|
||||
existing.rows = targetRows;
|
||||
existing.process.resize(targetCols, targetRows);
|
||||
if (existing.cols !== input.cols || existing.rows !== input.rows) {
|
||||
existing.cols = input.cols;
|
||||
existing.rows = input.rows;
|
||||
existing.process.resize(input.cols, input.rows);
|
||||
existing.updatedAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
@@ -449,8 +388,6 @@ 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,
|
||||
@@ -461,27 +398,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
cols,
|
||||
rows,
|
||||
cols: input.cols,
|
||||
rows: input.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, cols, rows }, "restarted");
|
||||
this.startSession(session, input, "restarted");
|
||||
return this.snapshot(session);
|
||||
});
|
||||
}
|
||||
@@ -530,7 +462,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
|
||||
private startSession(
|
||||
session: TerminalSessionState,
|
||||
input: TerminalStartInput,
|
||||
input: TerminalOpenInput,
|
||||
eventType: "started" | "restarted",
|
||||
): void {
|
||||
this.stopProcess(session);
|
||||
@@ -548,20 +480,19 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
for (const candidate of shellCandidates) {
|
||||
for (const shell of shellCandidates) {
|
||||
try {
|
||||
ptyProcess = this.ptyAdapter.spawn({
|
||||
shell: candidate.shell,
|
||||
...(candidate.args ? { args: candidate.args } : {}),
|
||||
shell,
|
||||
cwd: session.cwd,
|
||||
cols: session.cols,
|
||||
rows: session.rows,
|
||||
env: terminalEnv,
|
||||
});
|
||||
startedShell = formatShellCandidate(candidate);
|
||||
startedShell = shell;
|
||||
break;
|
||||
} catch (error) {
|
||||
lastSpawnError = error;
|
||||
@@ -575,9 +506,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
const detail =
|
||||
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
|
||||
const tried =
|
||||
shellCandidates.length > 0
|
||||
? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
|
||||
: "";
|
||||
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
|
||||
throw new Error(`${detail}.${tried}`.trim());
|
||||
}
|
||||
|
||||
|
||||
@@ -323,8 +323,6 @@ 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();
|
||||
|
||||
@@ -102,6 +102,7 @@ import { Command, CommandInput, CommandItem, CommandList } from "./ui/command";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
injectEnvIntoShellCommand,
|
||||
nextProjectScriptId,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
@@ -299,7 +300,9 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
<Command
|
||||
mode="none"
|
||||
onItemHighlighted={(highlightedValue) => {
|
||||
props.onHighlightedItemChange(typeof highlightedValue === "string" ? highlightedValue : null);
|
||||
props.onHighlightedItemChange(
|
||||
typeof highlightedValue === "string" ? highlightedValue : null,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
|
||||
@@ -544,15 +547,6 @@ 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(
|
||||
@@ -669,21 +663,16 @@ export default function ChatView() {
|
||||
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 };
|
||||
});
|
||||
}
|
||||
setLastInvokedScriptByProjectId((current) => {
|
||||
if (current[activeProject.id] === script.id) return current;
|
||||
return { ...current, [activeProject.id]: script.id };
|
||||
});
|
||||
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
|
||||
const baseTerminalId =
|
||||
activeThread.activeTerminalId ||
|
||||
activeThread.terminalIds[0] ||
|
||||
DEFAULT_THREAD_TERMINAL_ID;
|
||||
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
|
||||
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
|
||||
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
|
||||
const shouldCreateNewTerminal =
|
||||
@@ -712,31 +701,33 @@ export default function ChatView() {
|
||||
}
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
|
||||
const runtimeEnv = projectScriptRuntimeEnv({
|
||||
project: {
|
||||
cwd: activeProject.cwd,
|
||||
},
|
||||
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
|
||||
...(options?.env ? { extraEnv: options.env } : {}),
|
||||
});
|
||||
const resolvedCommand = injectEnvIntoShellCommand(
|
||||
script.command,
|
||||
projectScriptRuntimeEnv({
|
||||
project: {
|
||||
id: activeProject.id,
|
||||
name: activeProject.name,
|
||||
cwd: activeProject.cwd,
|
||||
},
|
||||
script,
|
||||
threadId: activeThreadId,
|
||||
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
|
||||
...(options?.env ? { extraEnv: options.env } : {}),
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
await api.terminal.open({
|
||||
threadId: activeThreadId,
|
||||
terminalId: targetTerminalId,
|
||||
cwd: targetCwd,
|
||||
env: runtimeEnv,
|
||||
...(shouldCreateNewTerminal
|
||||
? {
|
||||
cols: SCRIPT_TERMINAL_COLS,
|
||||
rows: SCRIPT_TERMINAL_ROWS,
|
||||
}
|
||||
: {}),
|
||||
cols: SCRIPT_TERMINAL_COLS,
|
||||
rows: SCRIPT_TERMINAL_ROWS,
|
||||
});
|
||||
await api.terminal.write({
|
||||
threadId: activeThreadId,
|
||||
terminalId: targetTerminalId,
|
||||
data: `${script.command}\r`,
|
||||
data: `${resolvedCommand}\n`,
|
||||
});
|
||||
} catch (error) {
|
||||
dispatch({
|
||||
@@ -749,34 +740,25 @@ export default function ChatView() {
|
||||
[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,
|
||||
});
|
||||
|
||||
async (
|
||||
project: { id: string; cwd: string; scripts: ProjectScript[] },
|
||||
nextScripts: ProjectScript[],
|
||||
keybinding: string | null,
|
||||
keybindingCommand: string,
|
||||
) => {
|
||||
if (!isElectron || !api) return;
|
||||
|
||||
let scriptsPersisted = false;
|
||||
try {
|
||||
const updated = await api.projects.updateScripts({
|
||||
id: input.projectId,
|
||||
scripts: input.nextScripts,
|
||||
id: project.id,
|
||||
scripts: nextScripts,
|
||||
});
|
||||
scriptsPersisted = true;
|
||||
|
||||
if (input.keybinding) {
|
||||
if (keybinding) {
|
||||
const keybindingUpdate = await api.server.upsertKeybinding({
|
||||
key: input.keybinding,
|
||||
command: input.keybindingCommand,
|
||||
key: keybinding,
|
||||
command: keybindingCommand,
|
||||
});
|
||||
queryClient.setQueryData(
|
||||
serverQueryKeys.config(),
|
||||
@@ -784,7 +766,7 @@ export default function ChatView() {
|
||||
current
|
||||
? { ...current, keybindings: keybindingUpdate.keybindings }
|
||||
: {
|
||||
cwd: input.projectCwd,
|
||||
cwd: project.cwd,
|
||||
keybindings: keybindingUpdate.keybindings,
|
||||
},
|
||||
);
|
||||
@@ -799,15 +781,15 @@ export default function ChatView() {
|
||||
if (scriptsPersisted) {
|
||||
await api.projects
|
||||
.updateScripts({
|
||||
id: input.projectId,
|
||||
scripts: input.previousScripts,
|
||||
id: project.id,
|
||||
scripts: project.scripts,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_PROJECT_SCRIPTS",
|
||||
projectId: input.projectId,
|
||||
scripts: input.previousScripts,
|
||||
projectId: project.id,
|
||||
scripts: project.scripts,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
@@ -837,16 +819,20 @@ export default function ChatView() {
|
||||
]
|
||||
: [...activeProject.scripts, nextScript];
|
||||
|
||||
await persistProjectScripts({
|
||||
dispatch({
|
||||
type: "SET_PROJECT_SCRIPTS",
|
||||
projectId: activeProject.id,
|
||||
projectCwd: activeProject.cwd,
|
||||
previousScripts: activeProject.scripts,
|
||||
nextScripts,
|
||||
keybinding: input.keybinding,
|
||||
keybindingCommand: commandForProjectScript(nextId),
|
||||
scripts: nextScripts,
|
||||
});
|
||||
|
||||
await persistProjectScripts(
|
||||
activeProject,
|
||||
nextScripts,
|
||||
input.keybinding,
|
||||
commandForProjectScript(nextId),
|
||||
);
|
||||
},
|
||||
[activeProject, persistProjectScripts],
|
||||
[activeProject, dispatch, persistProjectScripts],
|
||||
);
|
||||
const updateProjectScript = useCallback(
|
||||
async (scriptId: string, input: NewProjectScriptInput) => {
|
||||
@@ -871,16 +857,20 @@ export default function ChatView() {
|
||||
: script,
|
||||
);
|
||||
|
||||
await persistProjectScripts({
|
||||
dispatch({
|
||||
type: "SET_PROJECT_SCRIPTS",
|
||||
projectId: activeProject.id,
|
||||
projectCwd: activeProject.cwd,
|
||||
previousScripts: activeProject.scripts,
|
||||
nextScripts,
|
||||
keybinding: input.keybinding,
|
||||
keybindingCommand: commandForProjectScript(scriptId),
|
||||
scripts: nextScripts,
|
||||
});
|
||||
|
||||
await persistProjectScripts(
|
||||
activeProject,
|
||||
nextScripts,
|
||||
input.keybinding,
|
||||
commandForProjectScript(scriptId),
|
||||
);
|
||||
},
|
||||
[activeProject, persistProjectScripts],
|
||||
[activeProject, dispatch, persistProjectScripts],
|
||||
);
|
||||
|
||||
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
|
||||
@@ -1346,7 +1336,6 @@ export default function ChatView() {
|
||||
void runProjectScript(setupScript, {
|
||||
cwd: result.worktree.path,
|
||||
worktreePath: result.worktree.path,
|
||||
rememberAsLastInvoked: false,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -1899,7 +1888,6 @@ export default function ChatView() {
|
||||
api={api}
|
||||
threadId={activeThread.id}
|
||||
cwd={gitCwd ?? activeProject.cwd}
|
||||
runtimeEnv={threadTerminalRuntimeEnv}
|
||||
height={activeThread.terminalHeight}
|
||||
terminalIds={activeThread.terminalIds}
|
||||
activeTerminalId={activeThread.activeTerminalId}
|
||||
|
||||
@@ -6,12 +6,12 @@ import type {
|
||||
import {
|
||||
BugIcon,
|
||||
ChevronDownIcon,
|
||||
CogIcon,
|
||||
FlaskConicalIcon,
|
||||
HammerIcon,
|
||||
ListChecksIcon,
|
||||
PlayIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
WrenchIcon,
|
||||
} from "lucide-react";
|
||||
import React, { type FormEvent, type KeyboardEvent, useMemo, useState } from "react";
|
||||
@@ -122,9 +122,6 @@ function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | n
|
||||
}
|
||||
if (event.altKey) parts.push("alt");
|
||||
if (event.shiftKey) parts.push("shift");
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
parts.push(keyToken);
|
||||
return parts.join("+");
|
||||
}
|
||||
@@ -225,7 +222,13 @@ export default function ProjectScriptsControl({
|
||||
await onAddScript(payload);
|
||||
}
|
||||
setDialogOpen(false);
|
||||
setEditingScriptId(null);
|
||||
setName("");
|
||||
setCommand("");
|
||||
setIcon("play");
|
||||
setIconPickerOpen(false);
|
||||
setRunOnWorktreeCreate(false);
|
||||
setKeybinding("");
|
||||
} catch (error) {
|
||||
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
|
||||
}
|
||||
@@ -289,7 +292,7 @@ export default function ProjectScriptsControl({
|
||||
>
|
||||
<ScriptIcon icon={script.icon} className="size-4" />
|
||||
<span className="truncate">
|
||||
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
|
||||
{script.runOnWorktreeCreate ? `${script.name}` : script.name}
|
||||
</span>
|
||||
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
|
||||
{shortcutLabel && (
|
||||
@@ -313,7 +316,7 @@ export default function ProjectScriptsControl({
|
||||
openEditDialog(script);
|
||||
}}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
<CogIcon className="size-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
</MenuItem>
|
||||
@@ -333,25 +336,7 @@ export default function ProjectScriptsControl({
|
||||
</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}
|
||||
>
|
||||
<Dialog onOpenChange={setDialogOpen} open={dialogOpen}>
|
||||
<DialogPopup>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
|
||||
@@ -449,6 +434,7 @@ export default function ProjectScriptsControl({
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDialogOpen(false);
|
||||
setEditingScriptId(null);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
|
||||
@@ -111,7 +111,6 @@ interface TerminalViewportProps {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
@@ -123,7 +122,6 @@ function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -276,7 +274,6 @@ function TerminalViewport({
|
||||
cwd,
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
});
|
||||
if (disposed) return;
|
||||
activeTerminal.write("\u001bc");
|
||||
@@ -372,7 +369,7 @@ function TerminalViewport({
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [api, cwd, runtimeEnv, terminalId, threadId]);
|
||||
}, [api, cwd, terminalId, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) return;
|
||||
@@ -417,7 +414,6 @@ interface ThreadTerminalDrawerProps {
|
||||
api: NativeApi;
|
||||
threadId: string;
|
||||
cwd: string;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
height: number;
|
||||
terminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
@@ -467,7 +463,6 @@ export default function ThreadTerminalDrawer({
|
||||
api,
|
||||
threadId,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
height,
|
||||
terminalIds,
|
||||
activeTerminalId,
|
||||
@@ -783,7 +778,6 @@ export default function ThreadTerminalDrawer({
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
@@ -801,7 +795,6 @@ export default function ThreadTerminalDrawer({
|
||||
threadId={threadId}
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
cwd={cwd}
|
||||
{...(runtimeEnv ? { runtimeEnv } : {})}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
commandForProjectScript,
|
||||
injectEnvIntoShellCommand,
|
||||
nextProjectScriptId,
|
||||
primaryProjectScript,
|
||||
projectScriptRuntimeEnv,
|
||||
@@ -23,6 +24,33 @@ describe("projectScripts helpers", () => {
|
||||
expect(nextProjectScriptId("!!!", [])).toBe("script");
|
||||
});
|
||||
|
||||
it("injects environment variables for posix shells", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: "/tmp/project" },
|
||||
"MacIntel",
|
||||
);
|
||||
expect(command).toBe("env T3CODE_PROJECT_ROOT='/tmp/project' bun install");
|
||||
});
|
||||
|
||||
it("injects environment variables for windows shells", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: "C:\\\\repo path" },
|
||||
"Win32",
|
||||
);
|
||||
expect(command).toBe('set "T3CODE_PROJECT_ROOT=C:\\\\repo path" && bun install');
|
||||
});
|
||||
|
||||
it("escapes windows env values that trigger interpolation", () => {
|
||||
const command = injectEnvIntoShellCommand(
|
||||
"bun install",
|
||||
{ T3CODE_PROJECT_ROOT: '%USERPROFILE%^"repo"' },
|
||||
"Win32",
|
||||
);
|
||||
expect(command).toBe('set "T3CODE_PROJECT_ROOT=%USERPROFILE%^^""repo""" && bun install');
|
||||
});
|
||||
|
||||
it("resolves primary and setup scripts", () => {
|
||||
const scripts = [
|
||||
{
|
||||
@@ -47,19 +75,40 @@ describe("projectScripts helpers", () => {
|
||||
|
||||
it("builds default runtime env for scripts", () => {
|
||||
const env = projectScriptRuntimeEnv({
|
||||
project: { cwd: "/repo" },
|
||||
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
|
||||
script: {
|
||||
id: "test",
|
||||
name: "Test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
threadId: "thread-1",
|
||||
worktreePath: "/repo/worktree-a",
|
||||
});
|
||||
|
||||
expect(env).toMatchObject({
|
||||
T3CODE_PROJECT_ROOT: "/repo",
|
||||
T3CODE_PROJECT_ID: "project-1",
|
||||
T3CODE_PROJECT_NAME: "acme-web",
|
||||
T3CODE_THREAD_ID: "thread-1",
|
||||
T3CODE_SCRIPT_ID: "test",
|
||||
T3CODE_SCRIPT_NAME: "Test",
|
||||
T3CODE_SCRIPT_ICON: "test",
|
||||
T3CODE_SCRIPT_IS_SETUP: "0",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktree-a",
|
||||
});
|
||||
});
|
||||
|
||||
it("allows overriding runtime env values", () => {
|
||||
const env = projectScriptRuntimeEnv({
|
||||
project: { cwd: "/repo" },
|
||||
project: { id: "project-1", name: "acme-web", cwd: "/repo" },
|
||||
script: {
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
threadId: "thread-1",
|
||||
extraEnv: {
|
||||
T3CODE_PROJECT_ROOT: "/custom-root",
|
||||
CUSTOM_FLAG: "1",
|
||||
@@ -67,6 +116,7 @@ describe("projectScripts helpers", () => {
|
||||
});
|
||||
|
||||
expect(env.T3CODE_PROJECT_ROOT).toBe("/custom-root");
|
||||
expect(env.T3CODE_SCRIPT_IS_SETUP).toBe("1");
|
||||
expect(env.CUSTOM_FLAG).toBe("1");
|
||||
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
import { isWindowsPlatform } from "./lib/utils";
|
||||
|
||||
const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
|
||||
const MAX_SCRIPT_ID_LENGTH = 64;
|
||||
const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
|
||||
function normalizeScriptId(value: string): string {
|
||||
const cleaned = value
|
||||
@@ -45,21 +48,68 @@ export function nextProjectScriptId(name: string, existingIds: Iterable<string>)
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
// This last-resort fallback only triggers after exhausting thousands of suffixes.
|
||||
return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
|
||||
}
|
||||
|
||||
function shellEscapePosix(value: string): string {
|
||||
return `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
}
|
||||
|
||||
function shellEscapeWindowsSetValue(value: string): string {
|
||||
// Only escape ^ and " for interactive cmd.exe `set "K=V"` commands.
|
||||
// Do NOT escape % → %% here: that substitution only works in batch files.
|
||||
// In an interactive cmd.exe session (which is what terminal.write targets),
|
||||
// %% stays as literal %% and corrupts the value.
|
||||
return value.replace(/\^/g, "^^").replace(/"/g, '""');
|
||||
}
|
||||
|
||||
export function injectEnvIntoShellCommand(
|
||||
command: string,
|
||||
env: Record<string, string>,
|
||||
platform = typeof navigator === "undefined" ? "" : navigator.platform,
|
||||
): string {
|
||||
const entries = Object.entries(env).filter(
|
||||
([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,
|
||||
);
|
||||
if (entries.length === 0) {
|
||||
return command;
|
||||
}
|
||||
|
||||
if (isWindowsPlatform(platform)) {
|
||||
const prefixes = entries.map(
|
||||
([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,
|
||||
);
|
||||
return `${prefixes.join(" && ")} && ${command}`;
|
||||
}
|
||||
|
||||
const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");
|
||||
return `env ${assignments} ${command}`;
|
||||
}
|
||||
|
||||
interface ProjectScriptRuntimeEnvInput {
|
||||
project: {
|
||||
id: string;
|
||||
name: string;
|
||||
cwd: string;
|
||||
};
|
||||
script: Pick<ProjectScript, "id" | "name" | "icon" | "runOnWorktreeCreate">;
|
||||
threadId: string;
|
||||
worktreePath?: string | null;
|
||||
extraEnv?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record<string, string> {
|
||||
export function projectScriptRuntimeEnv(
|
||||
input: ProjectScriptRuntimeEnvInput,
|
||||
): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
T3CODE_PROJECT_ROOT: input.project.cwd,
|
||||
T3CODE_PROJECT_ID: input.project.id,
|
||||
T3CODE_PROJECT_NAME: input.project.name,
|
||||
T3CODE_THREAD_ID: input.threadId,
|
||||
T3CODE_SCRIPT_ID: input.script.id,
|
||||
T3CODE_SCRIPT_NAME: input.script.name,
|
||||
T3CODE_SCRIPT_ICON: input.script.icon,
|
||||
T3CODE_SCRIPT_IS_SETUP: input.script.runOnWorktreeCreate ? "1" : "0",
|
||||
};
|
||||
if (input.worktreePath) {
|
||||
env.T3CODE_WORKTREE_PATH = input.worktreePath;
|
||||
|
||||
+8
-10
@@ -8,7 +8,12 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type TerminalEvent,
|
||||
normalizeProjectScripts,
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
@@ -165,7 +170,6 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -573,10 +577,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
@@ -646,10 +647,7 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
|
||||
if (
|
||||
isNewTerminal &&
|
||||
normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT
|
||||
) {
|
||||
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
|
||||
return normalizedThread;
|
||||
}
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
|
||||
@@ -84,11 +84,21 @@ export const projectUpdateScriptsResultSchema = z.object({
|
||||
|
||||
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
|
||||
export type ProjectScript = z.infer<typeof projectScriptSchema>;
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
||||
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
|
||||
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
|
||||
|
||||
/**
|
||||
* Deduplicate scripts by ID and enforce at most one `runOnWorktreeCreate: true`
|
||||
* flag (the first one wins). Fields are trimmed defensively so this is safe to
|
||||
* call on data that hasn't been through Zod parsing.
|
||||
* Deduplicate scripts by ID (first occurrence wins), trim string fields,
|
||||
* and enforce at most one script with `runOnWorktreeCreate: true`.
|
||||
*/
|
||||
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const seenIds = new Set<string>();
|
||||
@@ -98,10 +108,11 @@ export function normalizeProjectScripts(scripts: readonly ProjectScript[]): Proj
|
||||
if (id.length === 0 || seenIds.has(id)) continue;
|
||||
seenIds.add(id);
|
||||
deduped.push({
|
||||
...script,
|
||||
id,
|
||||
name: script.name.trim(),
|
||||
command: script.command.trim(),
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,14 +132,3 @@ export function normalizeProjectScripts(scripts: readonly ProjectScript[]): Proj
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
export type ProjectAddResult = z.infer<typeof projectAddResultSchema>;
|
||||
export type ProjectRemoveInput = z.input<typeof projectRemoveInputSchema>;
|
||||
export type ProjectSearchEntriesInput = z.input<typeof projectSearchEntriesInputSchema>;
|
||||
export type ProjectEntryKind = z.infer<typeof projectEntryKindSchema>;
|
||||
export type ProjectEntry = z.infer<typeof projectEntrySchema>;
|
||||
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
|
||||
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
|
||||
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
|
||||
@@ -42,36 +42,6 @@ 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", () => {
|
||||
|
||||
@@ -5,11 +5,6 @@ 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),
|
||||
@@ -21,9 +16,8 @@ export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
|
||||
|
||||
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
|
||||
cwd: z.string().trim().min(1),
|
||||
cols: terminalColsSchema.optional(),
|
||||
rows: terminalRowsSchema.optional(),
|
||||
env: terminalEnvSchema.optional(),
|
||||
cols: terminalColsSchema,
|
||||
rows: terminalRowsSchema,
|
||||
});
|
||||
|
||||
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
|
||||
|
||||
Reference in new issue
Block a user