Add project script actions with shortcuts, persistence, and setup-run support #57
Mergedjuliusmarmingemerged 16 commits into
main fromcodething/7a5ed533merged by juliusmarminge View on GitHub- @@ -426,7 +461,21 @@426461462+ case "SET_PROJECT_SCRIPTS":463+ return {464+ ...state,465+ projects: state.projects.map((project) =>466+ project.id === action.projectId467+ ? { ...project, scripts: normalizeProjectScripts(action.scripts) }468+ : project,469+ ),470+ };471+427472 case "SYNC_PROJECTS": {428473 const previousByCwd = new Map(429474 state.projects.map((project) => [project.cwd, project] as const),430475 );431476 const nextProjects = action.projects.map((project) => {432477 const previous = previousByCwd.get(project.cwd);478+ const scripts =479+ project.scripts.length > 0480+ ? normalizeProjectScripts(project.scripts)481+ : normalizeProjectScripts(previous?.scripts ?? []);@@ -0,0 +39,21 @@39+ while (suffix < 10_000) {40+ const candidate = `${baseId}-${suffix}`;41+ const safeCandidate =42+ candidate.length <= MAX_SCRIPT_ID_LENGTH43+ ? candidate44+ : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;45+ if (!taken.has(safeCandidate)) {46+ return safeCandidate;47+ }48+ suffix += 1;49+ }50+51+ return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);52+}53+54+function shellEscapePosix(value: string): string {55+ return `'${value.replace(/'/g, `'\\''`)}'`;56+}57+58+function shellEscapeWindowsSetValue(value: string): string {59+ return value.replace(/"/g, '""');
- apps/server/src/keybindings.ts lines 442 to 444Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -350,2 +370,20 @@370+ if (!compileResolvedKeybindingRule(rule)) {371+ throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);372+ }373+374+ const configPath = resolveKeybindingsConfigPath();375+ const customConfig = loadCustomKeybindingsConfig(logger);376+ const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];377+ const cappedConfig =378+ nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;379+380+ if (nextConfig.length > MAX_KEYBINDINGS) {381+ logger.warn("truncating keybindings config to max entries", {382+ path: configPath,383+ maxEntries: MAX_KEYBINDINGS,384+ });350385 }351- return [...DEFAULT_RESOLVED_KEYBINDINGS];386+387+ fs.mkdirSync(path.dirname(configPath), { recursive: true });388+ fs.writeFileSync(configPath, `${JSON.stringify(cappedConfig, null, 2)}\n`, "utf8");389+apps/web/src/components/ChatView.tsx lines 117 to 150Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -92 +101,21 @@92101 const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];102+const SCRIPT_TERMINAL_COLS = 120;103+const SCRIPT_TERMINAL_ROWS = 30;104+105+function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {106+ const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);107+ if (!stored) return {};108+109+ try {110+ const parsed: unknown = JSON.parse(stored);111+ if (!parsed || typeof parsed !== "object") return {};112+ return Object.fromEntries(113+ Object.entries(parsed).filter(114+ (entry): entry is [string, string] =>115+ typeof entry[0] === "string" && typeof entry[1] === "string",116+ ),117+ );118+ } catch {119+ return {};120+ }121+}apps/web/src/components/ChatView.tsx lines 664 to 750Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -372,0 +464,21 @@464+ threadId: activeThreadId,465+ terminalId: targetTerminalId,466+ cwd: targetCwd,467+ cols: SCRIPT_TERMINAL_COLS,468+ rows: SCRIPT_TERMINAL_ROWS,469+ });470+ await api.terminal.write({471+ threadId: activeThreadId,472+ terminalId: targetTerminalId,473+ data: `${resolvedCommand}\n`,474+ });475+ } catch (error) {476+ dispatch({477+ type: "SET_ERROR",478+ threadId: activeThreadId,479+ error: error instanceof Error ? error.message : `Failed to run script "${script.name}".`,480+ });481+ }482+ },483+ [activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],484+ );
- apps/web/src/components/ChatView.tsx line 470OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -382,0 +450,21 @@450+ });451+ } else {452+ dispatch({453+ type: "SET_THREAD_ACTIVE_TERMINAL",454+ threadId: activeThreadId,455+ terminalId: targetTerminalId,456+ });457+ }458+ setTerminalFocusRequestId((value) => value + 1);459+460+ const resolvedCommand = injectEnvIntoShellCommand(461+ script.command,462+ projectScriptRuntimeEnv({463+ project: {464+ id: activeProject.id,465+ name: activeProject.name,466+ cwd: activeProject.cwd,467+ },468+ script,469+ threadId: activeThreadId,470+ worktreePath: activeThread.worktreePath ?? null,apps/web/src/projectScripts.ts line 58OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+ let suffix = 2;39+ while (suffix < 10_000) {40+ const candidate = `${baseId}-${suffix}`;41+ const safeCandidate =42+ candidate.length <= MAX_SCRIPT_ID_LENGTH43+ ? candidate44+ : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;45+ if (!taken.has(safeCandidate)) {46+ return safeCandidate;47+ }48+ suffix += 1;49+ }50+51+ return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);52+}53+54+function shellEscapePosix(value: string): string {55+ return `'${value.replace(/'/g, `'\\''`)}'`;56+}57+58+function shellEscapeWindowsSetValue(value: string): string {apps/web/src/store.ts line 479OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -424,9 +459,21 @@424459 ],425460 };426461462+ case "SET_PROJECT_SCRIPTS":463+ return {464+ ...state,465+ projects: state.projects.map((project) =>466+ project.id === action.projectId467+ ? { ...project, scripts: normalizeProjectScripts(action.scripts) }468+ : project,469+ ),470+ };471+427472 case "SYNC_PROJECTS": {428473 const previousByCwd = new Map(429474 state.projects.map((project) => [project.cwd, project] as const),430475 );431476 const nextProjects = action.projects.map((project) => {432477 const previous = previousByCwd.get(project.cwd);478+ const scripts =479+ project.scripts.length > 0
- apps/server/src/keybindings.ts line 378OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -352,0 +358,21 @@358+ const merged = mergeWithDefaultKeybindings(compiledCustomConfig);359+ if (mergedBeforeCapLength > MAX_KEYBINDINGS) {360+ logger.warn("truncating merged keybindings config to max entries", {361+ path: resolveKeybindingsConfigPath(),362+ maxEntries: MAX_KEYBINDINGS,363+ });364+ }365+ return merged;366+}367+368+export function upsertKeybindingRule(369+ logger: KeybindingsLogger,370+ rawRule: unknown,371+): ResolvedKeybindingsConfig {372+ const rule = keybindingRuleSchema.parse(rawRule);373+ if (!compileResolvedKeybindingRule(rule)) {374+ throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);375+ }376+377+ const configPath = resolveKeybindingsConfigPath();378+ const customConfig = loadCustomKeybindingsConfig(logger);
- apps/web/src/components/ChatView.tsx lines 694 to 707OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -620,0 +687,21 @@687+ type: "SET_THREAD_ACTIVE_TERMINAL",688+ threadId: activeThreadId,689+ terminalId: targetTerminalId,690+ });691+ }692+ setTerminalFocusRequestId((value) => value + 1);693+694+ const resolvedCommand = injectEnvIntoShellCommand(695+ script.command,696+ projectScriptRuntimeEnv({697+ project: {698+ id: activeProject.id,699+ name: activeProject.name,700+ cwd: activeProject.cwd,701+ },702+ script,703+ threadId: activeThreadId,704+ worktreePath: activeThread.worktreePath ?? null,705+ extraEnv: options?.env,706+ }),707+ );@@ -0,0 +75,21 @@75+ const prefixes = entries.map(76+ ([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,77+ );78+ return `${prefixes.join(" && ")} && ${command}`;79+ }80+81+ const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");82+ return `env ${assignments} ${command}`;83+}84+85+interface ProjectScriptRuntimeEnvInput {86+ project: {87+ id: string;88+ name: string;89+ cwd: string;90+ };91+ script: Pick<ProjectScript, "id" | "name" | "icon" | "runOnWorktreeCreate">;92+ threadId: string;93+ worktreePath?: string | null;94+ extraEnv?: Record<string, string>;95+}
- @@ -432,7 +467,21 @@432467468+ case "SET_PROJECT_SCRIPTS":469+ return {470+ ...state,471+ projects: state.projects.map((project) =>472+ project.id === action.projectId473+ ? { ...project, scripts: normalizeProjectScripts(action.scripts) }474+ : project,475+ ),476+ };477+433478 case "SYNC_PROJECTS": {434479 const previousByCwd = new Map(435480 state.projects.map((project) => [project.cwd, project] as const),436481 );437482 const nextProjects = action.projects.map((project) => {438483 const previous = previousByCwd.get(project.cwd);484+ const scripts =485+ project.scripts.length > 0486+ ? normalizeProjectScripts(project.scripts)487+ : normalizeProjectScripts(previous?.scripts ?? []);@@ -1047,3 +1346,9 @@10471346 branch: result.worktree.branch,10481347 worktreePath: result.worktree.path,10491348 });1349+ const setupScript = setupProjectScript(activeProject.scripts);1350+ if (setupScript) {1351+ void runProjectScript(setupScript, {1352+ cwd: result.worktree.path,1353+ });1354+ }@@ -620,0 +664,21 @@664+ return { ...current, [activeProject.id]: script.id };665+ });666+ const targetCwd = options?.cwd ?? gitCwd ?? activeProject.cwd;667+ const baseTerminalId = activeThread.activeTerminalId;668+ const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);669+ const shouldCreateNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;670+ const targetTerminalId = shouldCreateNewTerminal671+ ? `terminal-${crypto.randomUUID()}`672+ : baseTerminalId;673+674+ dispatch({675+ type: "SET_THREAD_TERMINAL_OPEN",676+ threadId: activeThreadId,677+ open: true,678+ });679+ if (shouldCreateNewTerminal) {680+ dispatch({681+ type: "NEW_THREAD_TERMINAL",682+ threadId: activeThreadId,683+ terminalId: targetTerminalId,684+ });
- apps/server/src/keybindings.ts line 423Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -352,0 +380,21 @@380+ const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);381+ const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));382+ const mergedBeforeCapLength =383+ DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))384+ .length + compiledCustomConfig.length;385+ const merged = mergeWithDefaultKeybindings(compiledCustomConfig);386+ if (mergedBeforeCapLength > MAX_KEYBINDINGS) {387+ logger.warn("truncating merged keybindings config to max entries", {388+ path: resolveKeybindingsConfigPath(),389+ maxEntries: MAX_KEYBINDINGS,390+ });391+ }392+ return merged;393+}394+395+export function upsertKeybindingRule(396+ logger: KeybindingsLogger,397+ rawRule: unknown,398+): ResolvedKeybindingsConfig {399+ const rule = keybindingRuleSchema.parse(rawRule);400+ if (!compileResolvedKeybindingRule(rule)) {apps/web/src/projectScripts.ts line 49Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+}32+33+export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {34+ const taken = new Set(Array.from(existingIds));35+ const baseId = normalizeScriptId(name);36+ if (!taken.has(baseId)) return baseId;37+38+ let suffix = 2;39+ while (suffix < 10_000) {40+ const candidate = `${baseId}-${suffix}`;41+ const safeCandidate =42+ candidate.length <= MAX_SCRIPT_ID_LENGTH43+ ? candidate44+ : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;45+ if (!taken.has(safeCandidate)) {46+ return safeCandidate;47+ }48+ suffix += 1;49+ }50+51+ return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
- @@ -0,0 +40,21 @@40+ const candidate = `${baseId}-${suffix}`;41+ const safeCandidate =42+ candidate.length <= MAX_SCRIPT_ID_LENGTH43+ ? candidate44+ : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;45+ if (!taken.has(safeCandidate)) {46+ return safeCandidate;47+ }48+ suffix += 1;49+ }50+51+ return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);52+}53+54+function shellEscapePosix(value: string): string {55+ return `'${value.replace(/'/g, `'\\''`)}'`;56+}57+58+function shellEscapeWindowsSetValue(value: string): string {59+ return value.replace(/\^/g, "^^").replace(/%/g, "%%").replace(/"/g, '""');60+}@@ -620,0 +797,21 @@797+ dispatch({798+ type: "SET_PROJECT_SCRIPTS",799+ projectId: updated.project.id,800+ scripts: updated.project.scripts,801+ });802+ } catch (error) {803+ if (scriptsPersisted) {804+ await api.projects805+ .updateScripts({806+ id: activeProject.id,807+ scripts: activeProject.scripts,808+ })809+ .catch(() => undefined);810+ }811+ dispatch({812+ type: "SET_PROJECT_SCRIPTS",813+ projectId: activeProject.id,814+ scripts: activeProject.scripts,815+ });816+ throw error;817+ }@@ -165,0 +178,21 @@178+ name: script.name.trim(),179+ command: script.command.trim(),180+ });181+ }182+183+ let setupAssigned = false;184+ const normalized: ProjectScript[] = [];185+ for (const script of deduped) {186+ if (!script.runOnWorktreeCreate) {187+ normalized.push(script);188+ continue;189+ }190+ if (!setupAssigned) {191+ setupAssigned = true;192+ normalized.push(script);193+ continue;194+ }195+ normalized.push({ ...script, runOnWorktreeCreate: false });196+ }197+ return normalized;198+}
- @@ -0,0 +275,21 @@275+ <Menu highlightItemOnHover={false}>276+ <MenuTrigger277+ render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}278+ >279+ <ChevronDownIcon className="size-4" />280+ </MenuTrigger>281+ <MenuPopup align="end">282+ {scripts.map((script) => {283+ const shortcutLabel = shortcutLabelForCommand(284+ keybindings,285+ commandForProjectScript(script.id),286+ );287+ return (288+ <MenuItem289+ key={script.id}290+ className={`group ${dropdownItemClassName}`}291+ onClick={() => onRunScript(script)}292+ >293+ <ScriptIcon icon={script.icon} className="size-4" />294+ <span className="truncate">295+ {script.runOnWorktreeCreate ? `${script.name}` : script.name}@@ -620,0 +798,21 @@798+ type: "SET_PROJECT_SCRIPTS",799+ projectId: updated.project.id,800+ scripts: updated.project.scripts,801+ });802+ } catch (error) {803+ if (scriptsPersisted) {804+ await api.projects805+ .updateScripts({806+ id: activeProject.id,807+ scripts: activeProject.scripts,808+ })809+ .catch(() => undefined);810+ }811+ dispatch({812+ type: "SET_PROJECT_SCRIPTS",813+ projectId: activeProject.id,814+ scripts: activeProject.scripts,815+ });816+ throw error;817+ }818+ },
- @@ -294,11 +295,17 @@294- return merged.slice(-256);295+function resolveKeybindingsConfigPath(): string {296+ return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);295297 }296298297-export function loadResolvedKeybindingsConfig(299+function loadCustomKeybindingsConfig(298300 logger: KeybindingsLogger,299-): ResolvedKeybindingsConfig {300- const configPath = path.join(os.homedir(), ".t3", "keybindings.json");301+ options?: {302+ throwOnUnreadableConfig?: boolean;303+ },304+): KeybindingsConfig {305+ const configPath = resolveKeybindingsConfigPath();301306 try {302307 const raw = fs.readFileSync(configPath, "utf8");303308 const parsed = JSON.parse(raw) as unknown;304309 if (!Array.isArray(parsed)) {310+ if (options?.throwOnUnreadableConfig) {311+ throw new Error(`Unable to parse keybindings config at ${configPath}: expected JSON array`);
- apps/server/src/keybindings.ts line 330Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -303,15 +314,17 @@303314 const parsed = JSON.parse(raw) as unknown;304315 if (!Array.isArray(parsed)) {316+ if (options?.throwOnUnreadableConfig) {317+ throw new KeybindingsConfigParseError(configPath, "expected JSON array");318+ }305319 logger.warn("ignoring keybindings config with unsupported format; expected array", {306320 path: configPath,307321 });308- return [...DEFAULT_RESOLVED_KEYBINDINGS];322+ return [];309323 }310324311- const sanitized: ResolvedKeybindingsConfig = [];325+ const sanitized: KeybindingsConfig = [];312326 let invalidEntries = 0;313327 for (const entry of parsed) {314328 const result = keybindingRuleSchema.safeParse(entry);315329 if (result.success) {316- const compiled = compileResolvedKeybindingRule(result.data);317- if (!compiled) {330+ if (!compileResolvedKeybindingRule(result.data)) {
- @@ -0,0 +107,21 @@107+ if (normalized === "pageup" || normalized === "pagedown") return normalized;108+ return null;109+}110+111+function keybindingFromEvent(event: KeyboardEvent<HTMLInputElement>): string | null {112+ const keyToken = normalizeShortcutKeyToken(event.key);113+ if (!keyToken) return null;114+115+ const parts: string[] = [];116+ if (isMacPlatform(navigator.platform)) {117+ if (event.metaKey) parts.push("mod");118+ if (event.ctrlKey) parts.push("ctrl");119+ } else {120+ if (event.ctrlKey) parts.push("mod");121+ if (event.metaKey) parts.push("meta");122+ }123+ if (event.altKey) parts.push("alt");124+ if (event.shiftKey) parts.push("shift");125+ parts.push(keyToken);126+ return parts.join("+");127+}
- @@ -620,0 +706,21 @@706+ projectScriptRuntimeEnv({707+ project: {708+ id: activeProject.id,709+ name: activeProject.name,710+ cwd: activeProject.cwd,711+ },712+ script,713+ threadId: activeThreadId,714+ worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,715+ ...(options?.env ? { extraEnv: options.env } : {}),716+ }),717+ );718+719+ try {720+ await api.terminal.open({721+ threadId: activeThreadId,722+ terminalId: targetTerminalId,723+ cwd: targetCwd,724+ cols: SCRIPT_TERMINAL_COLS,725+ rows: SCRIPT_TERMINAL_ROWS,726+ });
- apps/web/src/components/ThreadTerminalDrawer.tsx lines 375 to 375OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -369,4 +372,4 @@369372 fitAddonRef.current = null;370373 terminal.dispose();371374 };372- }, [api, cwd, terminalId, threadId]);375+ }, [api, autoFocus, cwd, runtimeEnv, terminalId, threadId]);
- @@ -241,10 +267,17 @@241267 return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);242268 }243269244-function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {270+function createTerminalSpawnEnv(271+ baseEnv: NodeJS.ProcessEnv,272+ runtimeEnv?: Record<string, string> | null,273+): NodeJS.ProcessEnv {245274 const spawnEnv: NodeJS.ProcessEnv = {};246275 for (const [key, value] of Object.entries(baseEnv)) {247276 if (value === undefined) continue;248277 if (shouldExcludeTerminalEnvKey(key)) continue;249278 spawnEnv[key] = value;250279 }280+ if (runtimeEnv) {281+ for (const [key, value] of Object.entries(runtimeEnv)) {282+ spawnEnv[key] = value;283+ }
- @@ -369,4 +372,4 @@369372 fitAddonRef.current = null;370373 terminal.dispose();371374 };372- }, [api, cwd, terminalId, threadId]);375+ }, [api, autoFocus, cwd, runtimeEnv, terminalId, threadId]);@@ -510,3 +544,12 @@510544 [composerHighlightedItemId, composerMenuItems],511545 );512546 const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;547+ const threadTerminalRuntimeEnv = useMemo(() => {548+ if (!activeProject) return {};549+ return projectScriptRuntimeEnv({550+ project: {551+ cwd: activeProject.cwd,552+ },553+ worktreePath: activeThread?.worktreePath ?? null,554+ });555+ }, [activeProject, activeThread?.worktreePath]);@@ -0,0 +64,21 @@64+ command: string,65+ env: Record<string, string>,66+ platform = typeof navigator === "undefined" ? "" : navigator.platform,67+): string {68+ const entries = Object.entries(env).filter(69+ ([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,70+ );71+ if (entries.length === 0) {72+ return command;73+ }74+75+ if (isWindowsPlatform(platform)) {76+ const prefixes = entries.map(77+ ([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,78+ );79+ return `${prefixes.join(" && ")} && ${command}`;80+ }81+82+ const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");83+ return `env ${assignments} ${command}`;84+}
- @@ -0,0 +323,21 @@323+ <PlusIcon className="size-4" />324+ Add action325+ </MenuItem>326+ </MenuPopup>327+ </Menu>328+ </Group>329+ ) : (330+ <Button size="xs" variant="outline" onClick={openAddDialog}>331+ <PlusIcon className="size-3.5" />332+ Add action333+ </Button>334+ )}335+336+ <Dialog337+ onOpenChange={(open) => {338+ setDialogOpen(open);339+ if (!open) {340+ setIconPickerOpen(false);341+ }342+ }}343+ onOpenChangeComplete={(open) => {
- @@ -0,0 +32,21 @@32+33+export function nextProjectScriptId(name: string, existingIds: Iterable<string>): string {34+ const taken = new Set(Array.from(existingIds));35+ const baseId = normalizeScriptId(name);36+ if (!taken.has(baseId)) return baseId;37+38+ let suffix = 2;39+ while (suffix < 10_000) {40+ const candidate = `${baseId}-${suffix}`;41+ const safeCandidate =42+ candidate.length <= MAX_SCRIPT_ID_LENGTH43+ ? candidate44+ : `${baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - String(suffix).length - 1))}-${suffix}`;45+ if (!taken.has(safeCandidate)) {46+ return safeCandidate;47+ }48+ suffix += 1;49+ }50+51+ // This last-resort fallback only triggers after exhausting thousands of suffixes.52+ return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
- @@ -0,0 +64,21 @@64+ command: string,65+ env: Record<string, string>,66+ platform = typeof navigator === "undefined" ? "" : navigator.platform,67+): string {68+ const entries = Object.entries(env).filter(69+ ([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,70+ );71+ if (entries.length === 0) {72+ return command;73+ }74+75+ if (isWindowsPlatform(platform)) {76+ const prefixes = entries.map(77+ ([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,78+ );79+ return `${prefixes.join(" && ")} && ${command}`;80+ }81+82+ const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");83+ return `env ${assignments} ${command}`;84+}
- @@ -117,3 +128,12 @@117128 searchSlug: slug.toLowerCase(),118129 searchName: name.toLowerCase(),119130 }));131+const SCRIPT_TERMINAL_COLS = 120;132+const SCRIPT_TERMINAL_ROWS = 30;133+134+function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {135+ const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);136+ if (!stored) return {};137+138+ try {139+ const parsed: unknown = JSON.parse(stored);
- apps/web/src/store.ts line 198Outdated@@ -165,0 +178,21 @@178+ name: script.name.trim(),179+ command: script.command.trim(),180+ });181+ }182+183+ let setupAssigned = false;184+ const normalized: ProjectScript[] = [];185+ for (const script of deduped) {186+ if (!script.runOnWorktreeCreate) {187+ normalized.push(script);188+ continue;189+ }190+ if (!setupAssigned) {191+ setupAssigned = true;192+ normalized.push(script);193+ continue;194+ }195+ normalized.push({ ...script, runOnWorktreeCreate: false });196+ }197+ return normalized;198+}
Sign in to join this conversation.



Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
Walkthrough#
Adds first-class project scripts and dynamic script keybindings across contracts, server, and web: new schemas and WS methods, server-side script storage/deduplication and keybinding upsert persistence, client state/UI and reducers for script CRUD and execution, runtime env injection for cross-platform shells, and shortcut resolution for
script.{id}.run.Changes#
apps/server/src/projectRegistry.ts,apps/server/src/projectRegistry.test.ts,apps/server/src/keybindings.ts,apps/server/src/keybindings.test.ts,apps/server/src/wsServer.ts,apps/server/src/wsServer.test.tsupdateScriptsAPI and tests; implement load/compile/merge andupsertKeybindingRulewith on-disk persistence and tests; expose WS handlersprojects.updateScriptsandserver.upsertKeybinding.apps/web/src/store.ts,apps/web/src/store.test.ts,apps/web/src/types.ts,apps/web/src/persistenceSchema.ts,apps/web/src/persistenceSchema.test.ts,apps/web/src/App.tsx,apps/web/src/Sidebar.tsxProjectScripttype and addscriptstoProject; addSET_PROJECT_SCRIPTSand normalization in reducer; propagate scripts through persistence schema and bootstrap paths; update tests/fixtures.apps/web/src/components/ProjectScriptsControl.tsx,apps/web/src/components/ChatView.tsxapps/web/src/projectScripts.ts,apps/web/src/projectScripts.test.tsscript.{id}.run), env injection for POSIX/Windows, selection helpers (primary/setup), and comprehensive unit tests.apps/web/src/keybindings.ts,apps/web/src/keybindings.test.tsresolveShortcutCommand(now returns `stringpackages/contracts/src/project.ts,packages/contracts/src/project.test.ts,packages/contracts/src/keybindings.ts,packages/contracts/src/keybindings.test.ts,packages/contracts/src/ipc.ts,packages/contracts/src/ws.ts,packages/contracts/src/server.tsscript.[id].rundynamic commands; add WS method constants and IPC types for new RPCs.apps/web/src/wsNativeApi.ts,packages/contracts/src/ipc.tsNativeApi.projects.updateScriptsandNativeApi.server.upsertKeybindingmethods that proxy to corresponding WS methods.KEYBINDINGS.mdscript.{id}.runin available commands and default keybindings.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~50 minutes
Possibly related PRs#
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (2 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.