Compare commits

...
Author SHA1 Message Date
Cursor Agent a84b28420c Fix no-op ternary for setup scripts and deduplicate persistence logic
- Add '(setup)' suffix to script names in dropdown when runOnWorktreeCreate is true
- Extract shared persistScriptsUpdate helper to eliminate ~50 lines of duplicated
  persistence/rollback logic between saveProjectScript and updateProjectScript
2026-02-18 05:48:06 +00: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
8 changed files with 250 additions and 125 deletions

No files matched your search

+53
View File
@@ -91,6 +91,14 @@ describe("server keybindings", () => {
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
});
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
@@ -144,4 +152,49 @@ describe("server keybindings", () => {
}>;
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("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([]);
});
});
+63 -19
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;
}
@@ -281,12 +296,20 @@ function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
function loadCustomKeybindingsConfig(logger: KeybindingsLogger): KeybindingsConfig {
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 Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
});
@@ -319,6 +342,14 @@ function loadCustomKeybindingsConfig(logger: KeybindingsLogger): KeybindingsConf
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
return [];
}
if (options?.throwOnUnreadableConfig) {
throw new Error(
`Unable to parse keybindings config at ${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),
@@ -327,6 +358,17 @@ function loadCustomKeybindingsConfig(logger: KeybindingsLogger): KeybindingsConf
}
}
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) {
return [...DEFAULT_RESOLVED_KEYBINDINGS];
@@ -375,7 +417,9 @@ export function upsertKeybindingRule(
}
const configPath = resolveKeybindingsConfigPath();
const customConfig = loadCustomKeybindingsConfig(logger);
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;
@@ -388,7 +432,7 @@ export function upsertKeybindingRule(
}
fs.mkdirSync(path.dirname(configPath), { recursive: true });
fs.writeFileSync(configPath, `${JSON.stringify(cappedConfig, null, 2)}\n`, "utf8");
writeConfigAtomically(configPath, cappedConfig);
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
return mergeWithDefaultKeybindings(compiledCustomConfig);
+78 -100
View File
@@ -60,7 +60,11 @@ 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";
@@ -296,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">
@@ -655,6 +661,7 @@ export default function ChatView() {
options?: {
cwd?: string;
env?: Record<string, string>;
worktreePath?: string | null;
preferNewTerminal?: boolean;
},
) => {
@@ -664,9 +671,12 @@ export default function ChatView() {
return { ...current, [activeProject.id]: script.id };
});
const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;
const baseTerminalId = activeThread.activeTerminalId;
const baseTerminalId =
activeThread.activeTerminalId || activeThread.terminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;
const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
const shouldCreateNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
const shouldCreateNewTerminal =
wantsNewTerminal && activeThread.terminalIds.length < MAX_THREAD_TERMINAL_COUNT;
const targetTerminalId = shouldCreateNewTerminal
? `terminal-${crypto.randomUUID()}`
: baseTerminalId;
@@ -701,8 +711,8 @@ export default function ChatView() {
},
script,
threadId: activeThreadId,
worktreePath: activeThread.worktreePath ?? null,
extraEnv: options?.env,
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
}),
);
@@ -729,6 +739,63 @@ export default function ChatView() {
},
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
);
const persistScriptsUpdate = useCallback(
async (
project: NonNullable<typeof activeProject>,
nativeApi: NativeApi,
nextScripts: ProjectScript[],
scriptCommandId: string,
input: NewProjectScriptInput,
) => {
let scriptsPersisted = false;
try {
const updated = await nativeApi.projects.updateScripts({
id: project.id,
scripts: nextScripts,
});
scriptsPersisted = true;
if (input.keybinding) {
const keybindingUpdate = await nativeApi.server.upsertKeybinding({
key: input.keybinding,
command: commandForProjectScript(scriptCommandId),
});
queryClient.setQueryData(
serverQueryKeys.config(),
(current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
current
? { ...current, keybindings: keybindingUpdate.keybindings }
: {
cwd: project.cwd,
keybindings: keybindingUpdate.keybindings,
},
);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: updated.project.id,
scripts: updated.project.scripts,
});
} catch (error) {
if (scriptsPersisted) {
await nativeApi.projects
.updateScripts({
id: project.id,
scripts: project.scripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: project.id,
scripts: project.scripts,
});
throw error;
}
},
[dispatch, queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
if (!activeProject) return;
@@ -759,54 +826,9 @@ export default function ChatView() {
});
if (!isElectron || !api) return;
let scriptsPersisted = false;
try {
const updated = await api.projects.updateScripts({
id: activeProject.id,
scripts: nextScripts,
});
scriptsPersisted = true;
if (input.keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: input.keybinding,
command: commandForProjectScript(nextId),
});
queryClient.setQueryData(
serverQueryKeys.config(),
(current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
current
? { ...current, keybindings: keybindingUpdate.keybindings }
: {
cwd: activeProject.cwd,
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: activeProject.id,
scripts: activeProject.scripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: activeProject.id,
scripts: activeProject.scripts,
});
throw error;
}
await persistScriptsUpdate(activeProject, api, nextScripts, nextId, input);
},
[activeProject, api, dispatch, queryClient],
[activeProject, api, dispatch, persistScriptsUpdate],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
@@ -838,54 +860,9 @@ export default function ChatView() {
});
if (!isElectron || !api) return;
let scriptsPersisted = false;
try {
const updated = await api.projects.updateScripts({
id: activeProject.id,
scripts: nextScripts,
});
scriptsPersisted = true;
if (input.keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: input.keybinding,
command: commandForProjectScript(scriptId),
});
queryClient.setQueryData(
serverQueryKeys.config(),
(current: { cwd: string; keybindings: ResolvedKeybindingsConfig } | undefined) =>
current
? { ...current, keybindings: keybindingUpdate.keybindings }
: {
cwd: activeProject.cwd,
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: activeProject.id,
scripts: activeProject.scripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: activeProject.id,
scripts: activeProject.scripts,
});
throw error;
}
await persistScriptsUpdate(activeProject, api, nextScripts, scriptId, input);
},
[activeProject, api, dispatch, queryClient],
[activeProject, api, dispatch, persistScriptsUpdate],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
@@ -1350,6 +1327,7 @@ export default function ChatView() {
if (setupScript) {
void runProjectScript(setupScript, {
cwd: result.worktree.path,
worktreePath: result.worktree.path,
});
}
} catch (err) {
@@ -292,7 +292,7 @@ export default function ProjectScriptsControl({
>
<ScriptIcon icon={script.icon} className="size-4" />
<span className="truncate">
{script.runOnWorktreeCreate ? `${script.name}` : script.name}
{script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
</span>
<span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
{shortcutLabel && (
+9
View File
@@ -34,6 +34,15 @@ describe("projectScripts helpers", () => {
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 = [
{
+2 -1
View File
@@ -48,6 +48,7 @@ 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);
}
@@ -56,7 +57,7 @@ function shellEscapePosix(value: string): string {
}
function shellEscapeWindowsSetValue(value: string): string {
return value.replace(/"/g, '""');
return value.replace(/\^/g, "^^").replace(/%/g, "^%").replace(/"/g, '""');
}
export function injectEnvIntoShellCommand(
+43
View File
@@ -558,6 +558,49 @@ 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, {
+1 -4
View File
@@ -481,10 +481,7 @@ export function reducer(state: AppState, action: Action): AppState {
);
const nextProjects = action.projects.map((project) => {
const previous = previousByCwd.get(project.cwd);
const scripts =
project.scripts.length > 0
? normalizeProjectScripts(project.scripts)
: normalizeProjectScripts(previous?.scripts ?? []);
const scripts = normalizeProjectScripts(project.scripts);
return {
...project,
model: resolveModelSlug(previous?.model ?? project.model),