Compare commits

..
Author SHA1 Message Date
Cursor Agent 8e1ca36b46 Fix Windows %% escaping, deduplicate script persistence and normalization logic
- Remove %->%% escaping in shellEscapeWindowsSetValue: the doubling only
  works in batch files, not interactive cmd.exe sessions that terminal.write
  targets. Single % is correct for interactive mode.

- Extract shared persistProjectScripts helper in ChatView.tsx to eliminate
  ~40 lines of duplicated server persistence, keybinding upsert, query cache
  update, and rollback logic between saveProjectScript and updateProjectScript.

- Move normalizeProjectScripts (dedup by ID + enforce single runOnWorktreeCreate)
  into @t3tools/contracts so both store.ts and projectRegistry.ts share a
  single implementation instead of maintaining separate copies.
2026-02-18 05:38:55 +00:00
9 changed files with 110 additions and 139 deletions

No files matched your search

-8
View File
@@ -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", () => {
+16 -31
View File
@@ -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;
}
+3 -34
View File
@@ -16,6 +16,7 @@ import {
projectRemoveInputSchema,
projectScriptsSchema,
projectUpdateScriptsInputSchema,
normalizeProjectScripts,
} from "@t3tools/contracts";
function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
@@ -130,7 +131,7 @@ export class ProjectRegistry {
throw new Error(`Project not found: ${input.id}`);
}
const nextScripts = dedupeScriptsById(projectScriptsSchema.parse(input.scripts));
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
const nextUpdatedAt = new Date().toISOString();
const nextProject: ProjectRecord = {
...this.projects[index]!,
@@ -167,7 +168,7 @@ export class ProjectRegistry {
cwd: normalizedCwd,
name:
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
scripts: dedupeScriptsById(project.scripts),
scripts: normalizeProjectScripts(project.scripts),
};
deduped.set(normalizedCwd, normalizedProject);
normalizedProjects.push(normalizedProject);
@@ -232,35 +233,3 @@ 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;
}
+26 -18
View File
@@ -739,26 +739,26 @@ export default function ChatView() {
},
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
);
const persistScriptsUpdate = useCallback(
const persistProjectScripts = useCallback(
async (
project: NonNullable<typeof activeProject>,
nativeApi: NativeApi,
project: { id: string; cwd: string; scripts: ProjectScript[] },
nextScripts: ProjectScript[],
scriptCommandId: string,
input: NewProjectScriptInput,
keybinding: string | null,
keybindingCommand: string,
) => {
if (!isElectron || !api) return;
let scriptsPersisted = false;
try {
const updated = await nativeApi.projects.updateScripts({
const updated = await api.projects.updateScripts({
id: project.id,
scripts: nextScripts,
});
scriptsPersisted = true;
if (input.keybinding) {
const keybindingUpdate = await nativeApi.server.upsertKeybinding({
key: input.keybinding,
command: commandForProjectScript(scriptCommandId),
if (keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: keybinding,
command: keybindingCommand,
});
queryClient.setQueryData(
serverQueryKeys.config(),
@@ -779,7 +779,7 @@ export default function ChatView() {
});
} catch (error) {
if (scriptsPersisted) {
await nativeApi.projects
await api.projects
.updateScripts({
id: project.id,
scripts: project.scripts,
@@ -794,7 +794,7 @@ export default function ChatView() {
throw error;
}
},
[dispatch, queryClient],
[api, dispatch, queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
@@ -825,10 +825,14 @@ export default function ChatView() {
scripts: nextScripts,
});
if (!isElectron || !api) return;
await persistScriptsUpdate(activeProject, api, nextScripts, nextId, input);
await persistProjectScripts(
activeProject,
nextScripts,
input.keybinding,
commandForProjectScript(nextId),
);
},
[activeProject, api, dispatch, persistScriptsUpdate],
[activeProject, dispatch, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
@@ -859,10 +863,14 @@ export default function ChatView() {
scripts: nextScripts,
});
if (!isElectron || !api) return;
await persistScriptsUpdate(activeProject, api, nextScripts, scriptId, input);
await persistProjectScripts(
activeProject,
nextScripts,
input.keybinding,
commandForProjectScript(scriptId),
);
},
[activeProject, api, dispatch, persistScriptsUpdate],
[activeProject, dispatch, persistProjectScripts],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
@@ -292,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 && (
+11 -3
View File
@@ -25,12 +25,20 @@ describe("projectScripts helpers", () => {
});
it("injects environment variables for posix shells", () => {
const command = injectEnvIntoShellCommand("bun install", { T3CODE_PROJECT_ROOT: "/tmp/project" }, "MacIntel");
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");
const command = injectEnvIntoShellCommand(
"bun install",
{ T3CODE_PROJECT_ROOT: "C:\\\\repo path" },
"Win32",
);
expect(command).toBe('set "T3CODE_PROJECT_ROOT=C:\\\\repo path" && bun install');
});
@@ -40,7 +48,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", () => {
+8 -3
View File
@@ -48,7 +48,6 @@ 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);
}
@@ -57,7 +56,11 @@ function shellEscapePosix(value: string): string {
}
function shellEscapeWindowsSetValue(value: string): string {
return value.replace(/\^/g, "^^").replace(/%/g, "^%").replace(/"/g, '""');
// 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(
@@ -95,7 +98,9 @@ interface ProjectScriptRuntimeEnvInput {
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,
+8 -41
View File
@@ -8,7 +8,12 @@ import {
useReducer,
} from "react";
import type { ProviderEvent, ProviderSession, TerminalEvent } 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,38 +170,6 @@ 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))];
}
@@ -604,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)
@@ -677,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)
+37
View File
@@ -95,3 +95,40 @@ export type ProjectEntry = z.infer<typeof projectEntrySchema>;
export type ProjectSearchEntriesResult = z.infer<typeof projectSearchEntriesResultSchema>;
export type ProjectUpdateScriptsInput = z.input<typeof projectUpdateScriptsInputSchema>;
export type ProjectUpdateScriptsResult = z.infer<typeof projectUpdateScriptsResultSchema>;
/**
* Deduplicate scripts by ID (first occurrence wins), trim string fields,
* and enforce at most one script with `runOnWorktreeCreate: true`.
*/
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
const seenIds = new Set<string>();
const deduped: ProjectScript[] = [];
for (const script of scripts) {
const id = script.id.trim();
if (id.length === 0 || seenIds.has(id)) continue;
seenIds.add(id);
deduped.push({
id,
name: script.name.trim(),
command: script.command.trim(),
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;
}