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
6 changed files with 142 additions and 180 deletions

No files matched your search

+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;
}
+75 -100
View File
@@ -300,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">
@@ -670,9 +672,7 @@ export default function ChatView() {
});
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 =
@@ -739,6 +739,63 @@ export default function ChatView() {
},
[activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
);
const persistProjectScripts = useCallback(
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: project.id,
scripts: nextScripts,
});
scriptsPersisted = true;
if (keybinding) {
const keybindingUpdate = await api.server.upsertKeybinding({
key: keybinding,
command: keybindingCommand,
});
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 api.projects
.updateScripts({
id: project.id,
scripts: project.scripts,
})
.catch(() => undefined);
}
dispatch({
type: "SET_PROJECT_SCRIPTS",
projectId: project.id,
scripts: project.scripts,
});
throw error;
}
},
[api, dispatch, queryClient],
);
const saveProjectScript = useCallback(
async (input: NewProjectScriptInput) => {
if (!activeProject) return;
@@ -768,55 +825,14 @@ export default function ChatView() {
scripts: nextScripts,
});
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 persistProjectScripts(
activeProject,
nextScripts,
input.keybinding,
commandForProjectScript(nextId),
);
},
[activeProject, api, dispatch, queryClient],
[activeProject, dispatch, persistProjectScripts],
);
const updateProjectScript = useCallback(
async (scriptId: string, input: NewProjectScriptInput) => {
@@ -847,55 +863,14 @@ export default function ChatView() {
scripts: nextScripts,
});
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 persistProjectScripts(
activeProject,
nextScripts,
input.keybinding,
commandForProjectScript(scriptId),
);
},
[activeProject, api, dispatch, queryClient],
[activeProject, dispatch, persistProjectScripts],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
+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 -2
View File
@@ -56,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(
@@ -94,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;
}