Compare commits

...
Author SHA1 Message Date
Cursor Agent c3faa288b8 Fix hardcoded terminal dimensions corrupting reused terminal display
When runProjectScript reuses an existing terminal, it was always passing
hardcoded cols=120/rows=30 to api.terminal.open(), causing the server to
resize the PTY while the client-side xterm.js was never notified (its
resize effect dependencies didn't change). This resulted in a persistent
dimension mismatch and garbled terminal output.

Fix:
- Make cols/rows optional in terminalOpenInputSchema
- In TerminalManager.open()/restart()/startSession(), fall back to the
  session's current dimensions (or 80x24 defaults for new sessions)
  when cols/rows are omitted
- In runProjectScript, only pass hardcoded dimensions when creating a
  new terminal; omit them for reused terminals so the existing
  TerminalViewport-managed dimensions are preserved
2026-02-18 06:41:23 +00: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
8 changed files with 181 additions and 142 deletions

No files matched your search

+33
View File
@@ -91,6 +91,14 @@ describe("server keybindings", () => {
when: "terminalFocus && (",
}),
);
assert.isNull(
compileResolvedKeybindingRule({
key: "mod+d",
command: "terminal.split",
when: `${"!".repeat(300)}terminalFocus`,
}),
);
});
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
@@ -163,6 +171,31 @@ describe("server keybindings", () => {
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
});
it("reports non-array config parse errors without duplicate prefix", () => {
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
const configDir = path.join(fakeHome, ".t3");
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "keybindings.json");
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: expected JSON array`));
expect(() =>
upsertKeybindingRule(logger, {
key: "mod+shift+r",
command: "script.run-tests.run",
}),
).not.toThrow(
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
);
});
it("cleans up temp files when atomic keybinding write fails", () => {
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
const configDir = path.join(fakeHome, ".t3");
+44 -21
View File
@@ -24,6 +24,8 @@ type WhenToken =
| { type: "lparen" }
| { type: "rparen" };
const MAX_WHEN_EXPRESSION_DEPTH = 256;
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
@@ -159,7 +161,10 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
if (!tokens || tokens.length === 0) return null;
let index = 0;
const parsePrimary = (): KeybindingWhenNode | null => {
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
const token = tokens[index];
if (!token) return null;
@@ -170,7 +175,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
if (token.type === "lparen") {
index += 1;
const expressionNode = parseOr();
const expressionNode = parseOr(depth + 1);
const closeToken = tokens[index];
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
return null;
@@ -182,24 +187,34 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return null;
};
const parseUnary = (): KeybindingWhenNode | null => {
const token = tokens[index];
if (token?.type === "not") {
const parseUnary = (depth: number): KeybindingWhenNode | null => {
let notCount = 0;
while (tokens[index]?.type === "not") {
index += 1;
const node = parseUnary();
if (!node) return null;
return { type: "not", node };
notCount += 1;
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
return null;
}
}
return parsePrimary();
let node = parsePrimary(depth);
if (!node) return null;
while (notCount > 0) {
node = { type: "not", node };
notCount -= 1;
}
return node;
};
const parseAnd = (): KeybindingWhenNode | null => {
let left = parseUnary();
const parseAnd = (depth: number): KeybindingWhenNode | null => {
let left = parseUnary(depth);
if (!left) return null;
while (tokens[index]?.type === "and") {
index += 1;
const right = parseUnary();
const right = parseUnary(depth);
if (!right) return null;
left = { type: "and", left, right };
}
@@ -207,13 +222,13 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return left;
};
const parseOr = (): KeybindingWhenNode | null => {
let left = parseAnd();
const parseOr = (depth: number): KeybindingWhenNode | null => {
let left = parseAnd(depth);
if (!left) return null;
while (tokens[index]?.type === "or") {
index += 1;
const right = parseAnd();
const right = parseAnd(depth);
if (!right) return null;
left = { type: "or", left, right };
}
@@ -221,7 +236,7 @@ export function parseKeybindingWhenExpression(expression: string): KeybindingWhe
return left;
};
const ast = parseOr();
const ast = parseOr(0);
if (!ast || index !== tokens.length) return null;
return ast;
}
@@ -277,6 +292,12 @@ const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
const MAX_KEYBINDINGS = 256;
class KeybindingsConfigParseError extends Error {
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
}
}
function resolveKeybindingsConfigPath(): string {
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
}
@@ -293,7 +314,7 @@ function loadCustomKeybindingsConfig(
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) {
if (options?.throwOnUnreadableConfig) {
throw new Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
}
logger.warn("ignoring keybindings config with unsupported format; expected array", {
path: configPath,
@@ -328,10 +349,12 @@ function loadCustomKeybindingsConfig(
return [];
}
if (options?.throwOnUnreadableConfig) {
throw new Error(
`Unable to parse keybindings config at ${configPath}: ${
error instanceof Error ? error.message : String(error)
}`,
if (error instanceof KeybindingsConfigParseError) {
throw error;
}
throw new KeybindingsConfigParseError(
configPath,
error instanceof Error ? error.message : String(error),
{ cause: error },
);
}
+12 -10
View File
@@ -301,8 +301,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
cols: input.cols ?? 80,
rows: input.rows ?? 24,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
@@ -328,10 +328,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
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);
const effectiveCols = input.cols ?? existing.cols;
const effectiveRows = input.rows ?? existing.rows;
if (existing.cols !== effectiveCols || existing.rows !== effectiveRows) {
existing.cols = effectiveCols;
existing.rows = effectiveRows;
existing.process.resize(effectiveCols, effectiveRows);
existing.updatedAt = new Date().toISOString();
}
@@ -398,8 +400,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
cols: input.cols,
rows: input.rows,
cols: input.cols ?? 80,
rows: input.rows ?? 24,
process: null,
unsubscribeData: null,
unsubscribeExit: null,
@@ -469,8 +471,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.status = "starting";
session.cwd = input.cwd;
session.cols = input.cols;
session.rows = input.rows;
session.cols = input.cols ?? session.cols;
session.rows = input.rows ?? session.rows;
session.exitCode = null;
session.exitSignal = null;
session.hasRunningSubprocess = false;
+83 -106
View File
@@ -721,8 +721,9 @@ export default function ChatView() {
threadId: activeThreadId,
terminalId: targetTerminalId,
cwd: targetCwd,
cols: SCRIPT_TERMINAL_COLS,
rows: SCRIPT_TERMINAL_ROWS,
...(shouldCreateNewTerminal
? { cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS }
: {}),
});
await api.terminal.write({
threadId: activeThreadId,
@@ -739,6 +740,72 @@ 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,
});
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;
@@ -762,61 +829,16 @@ export default function ChatView() {
]
: [...activeProject.scripts, nextScript];
dispatch({
type: "SET_PROJECT_SCRIPTS",
await persistProjectScripts({
projectId: activeProject.id,
scripts: nextScripts,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(nextId),
});
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;
}
},
[activeProject, api, dispatch, queryClient],
[activeProject, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
@@ -841,61 +863,16 @@ export default function ChatView() {
: script,
);
dispatch({
type: "SET_PROJECT_SCRIPTS",
await persistProjectScripts({
projectId: activeProject.id,
scripts: nextScripts,
projectCwd: activeProject.cwd,
previousScripts: activeProject.scripts,
nextScripts,
keybinding: input.keybinding,
keybindingCommand: commandForProjectScript(scriptId),
});
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;
}
},
[activeProject, api, dispatch, queryClient],
[activeProject, persistProjectScripts],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
@@ -122,6 +122,9 @@ function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | n
}
if (event.altKey) parts.push("alt");
if (event.shiftKey) parts.push("shift");
if (parts.length === 0) {
return null;
}
parts.push(keyToken);
return parts.join("+");
}
@@ -292,7 +295,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 && (
+1 -1
View File
@@ -40,7 +40,7 @@ describe("projectScripts helpers", () => {
{ T3CODE_PROJECT_ROOT: '%USERPROFILE%^"repo"' },
"Win32",
);
expect(command).toBe('set "T3CODE_PROJECT_ROOT=%%USERPROFILE%%^^""repo""" && bun install');
expect(command).toBe('set "T3CODE_PROJECT_ROOT=^%USERPROFILE^%^^""repo""" && bun install');
});
it("resolves primary and setup 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, "^^").replace(/%/g, "%%").replace(/"/g, '""');
return value.replace(/\^/g, "^^").replace(/%/g, "^%").replace(/"/g, '""');
}
export function injectEnvIntoShellCommand(
+2 -2
View File
@@ -16,8 +16,8 @@ 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(),
});
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({