diff --git a/apps/server/src/projectRegistry.ts b/apps/server/src/projectRegistry.ts index b6b56cbe35..b7b0ac68c0 100644 --- a/apps/server/src/projectRegistry.ts +++ b/apps/server/src/projectRegistry.ts @@ -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(); - 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; -} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b9b06ac1a6..b6b48e3eec 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -300,7 +300,9 @@ const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { { - props.onHighlightedItemChange(typeof highlightedValue === "string" ? highlightedValue : null); + props.onHighlightedItemChange( + typeof highlightedValue === "string" ? highlightedValue : null, + ); }} >
@@ -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") => { diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.ts index 3180e793ef..1ba694b2ec 100644 --- a/apps/web/src/projectScripts.test.ts +++ b/apps/web/src/projectScripts.test.ts @@ -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", () => { diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.ts index a71bd3e3be..0a5d24e9d5 100644 --- a/apps/web/src/projectScripts.ts +++ b/apps/web/src/projectScripts.ts @@ -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; } -export function projectScriptRuntimeEnv(input: ProjectScriptRuntimeEnvInput): Record { +export function projectScriptRuntimeEnv( + input: ProjectScriptRuntimeEnvInput, +): Record { const env: Record = { T3CODE_PROJECT_ROOT: input.project.cwd, T3CODE_PROJECT_ID: input.project.id, diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 1e790fbea8..4331f5c7ae 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -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(); - 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) diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index 0466a6887e..470ae1676f 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -95,3 +95,40 @@ export type ProjectEntry = z.infer; export type ProjectSearchEntriesResult = z.infer; export type ProjectUpdateScriptsInput = z.input; export type ProjectUpdateScriptsResult = z.infer; + +/** + * 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(); + 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; +}