Skip to content
Source
Sign inSign up
pingdotgg/t3code

Add project script actions with shortcuts, persistence, and setup-run support #57

Mergedjuliusmarmingemerged 16 commits intomain fromcodething/7a5ed533merged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

  • Add project-scoped script actions (name, command, icon, optional setup-on-worktree-create) to shared contracts and server/web state models.
  • Implement server-side script persistence and validation in ProjectRegistry, including script ID deduplication and enforcing a single setup script.
  • Add projects.updateScripts WebSocket handling and coverage in server tests.
  • Introduce ProjectScriptsControl in the chat toolbar to add/run scripts from the UI, including keybinding command previews.
  • Extend keybinding support for dynamic script.{id}.run commands and route resolved shortcuts to script execution.
  • Auto-run the configured setup script after worktree creation with T3CODE_PROJECT_ROOT env injection.
  • Add/expand tests across server, web, and contracts for schema updates, shortcut resolution, script helpers, store/persistence behavior, and WS flows.

Testing

  • Added and updated unit tests for:
  • apps/server/src/projectRegistry.test.ts
  • apps/server/src/wsServer.test.ts
  • apps/web/src/projectScripts.test.ts
  • apps/web/src/keybindings.test.ts
  • apps/web/src/persistenceSchema.test.ts
  • apps/web/src/store.test.ts
  • packages/contracts/src/project.test.ts
  • packages/contracts/src/keybindings.test.ts
  • Lint: Not run (not provided in this prompt context).
  • Full test suite execution: Not run (not provided in this prompt context).

Open with Devin

Summary by CodeRabbit

  • New Features
    • Project scripts: create, edit, run and persist per-project scripts (icons, captured shortcuts, optional auto-run on worktree creation); UI controls and terminal execution integrated.
    • Keybindings: dynamic script commands resolvable via shortcuts; client and server APIs to update scripts and upsert/persist custom keybindings (websocket + native bindings).
  • Tests
    • Extensive coverage for script lifecycle, id deduplication, env injection, keybinding resolution, persistence, and websocket flows.

Note

Medium Risk Touches terminal spawning/session lifecycle and persists user configuration (project scripts + keybindings) on disk, so mistakes could break terminal startup or config handling; scope is moderate but well-covered by new tests.

Overview Adds project script “actions” (name/command/icon + optional setup on worktree create) to the shared contracts and threads/projects state, persists them server-side via a new projects.updateScripts WS method, and exposes them in the web UI via a new ProjectScriptsControl in the chat header.

Extends keybindings and terminal integration: supports dynamic script.{id}.run commands end-to-end (contracts validation, web shortcut resolution, docs), adds a server.upsertKeybinding WS method that atomically updates ~/.t3/keybindings.json, and enhances terminal sessions to accept optional cols/rows defaults plus per-open env overrides (including zsh args tweaks and resize/runtime-env restart behavior).

Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 278066697484657d7075738a365daac0ec80f428. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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_commits setting.

      Use the following commands to manage reviews:

      • @coderabbitai resume to resume automatic reviews.
      • @coderabbitai review to trigger a single review.

      Use the checkboxes below for quick actions:

      • ▶️ Resume reviews
      • 🔍 Trigger review

      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

      Cohort / File(s)Summary
      Server: project scripts & keybindings
      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.ts
      Add project script storage, cloning and deduplication helpers, updateScripts API and tests; implement load/compile/merge and upsertKeybindingRule with on-disk persistence and tests; expose WS handlers projects.updateScripts and server.upsertKeybinding.
      Web: state, persistence & bootstrap
      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.tsx
      Introduce ProjectScript type and add scripts to Project; add SET_PROJECT_SCRIPTS and normalization in reducer; propagate scripts through persistence schema and bootstrap paths; update tests/fixtures.
      Web: UI & execution
      apps/web/src/components/ProjectScriptsControl.tsx, apps/web/src/components/ChatView.tsx
      Add ProjectScriptsControl component and integrate into ChatView/ChatHeader; implement run/add/update flows, terminal execution with injected env, last-invoked tracking, and server persistence calls.
      Web: project script utilities & tests
      apps/web/src/projectScripts.ts, apps/web/src/projectScripts.test.ts
      New utilities for script ID normalization/generation, command encode/decode (script.{id}.run), env injection for POSIX/Windows, selection helpers (primary/setup), and comprehensive unit tests.
      Web: keybindings client
      apps/web/src/keybindings.ts, apps/web/src/keybindings.test.ts
      Export resolveShortcutCommand (now returns `string
      Contracts & IPC/WS
      packages/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.ts
      Add project script schemas/types and updateScripts input/result schemas; extend keybinding command schema to accept script.[id].run dynamic commands; add WS method constants and IPC types for new RPCs.
      Client-native API
      apps/web/src/wsNativeApi.ts, packages/contracts/src/ipc.ts
      Add NativeApi.projects.updateScripts and NativeApi.server.upsertKeybinding methods that proxy to corresponding WS methods.
      Docs & top-level
      KEYBINDINGS.md
      Document dynamic command pattern script.{id}.run in available commands and default keybindings.

      Sequence Diagram(s)

      sequenceDiagram
          participant UI as ProjectScriptsControl
          participant Store as Redux Store
          participant WS as WebSocket API
          participant Server as ProjectRegistry
          participant Disk as Disk State
      
          UI->>Store: dispatch local set/update scripts
          activate Store
          Store->>Store: normalizeProjectScripts()
          Store-->>UI: updated state
          deactivate Store
      
          UI->>WS: api.projects.updateScripts(input)
          activate WS
          WS->>Server: projectsUpdateScripts request
          activate Server
          Server->>Server: dedupeScriptsById()
          Server->>Server: updateScripts + cloneScripts()
          Server->>Disk: persist project state
          Server-->>WS: updated project result
          deactivate Server
          WS-->>Store: response → sync project
          deactivate WS
      sequenceDiagram
          participant User as User
          participant Chat as ChatView
          participant KeyUtil as keybindings.resolveShortcutCommand
          participant ScriptUtils as projectScripts
          participant Terminal as Terminal Manager
          participant Shell as Shell/Process
      
          User->>Chat: press shortcut
          activate Chat
          Chat->>KeyUtil: resolveShortcutCommand(event, keybindings)
          KeyUtil-->>Chat: "script.{id}.run"
          Chat->>ScriptUtils: projectScriptIdFromCommand("script.{id}.run")
          ScriptUtils-->>Chat: scriptId
          Chat->>Chat: lookup script, build runtime env
          Chat->>ScriptUtils: injectEnvIntoShellCommand(command, env, platform)
          ScriptUtils-->>Chat: escaped/prefixed command
          Chat->>Terminal: create/reuse terminal & execute command
          Terminal->>Shell: spawn process
          Shell-->>Terminal: output
          deactivate Chat

      Estimated code review effort

      🎯 4 (Complex) | ⏱️ ~50 minutes

      • pingdotgg/codething-mvp#52 — Modifies keybindings feature and tests; likely closely related to server/client keybinding merging and default keybindings changes.
      🚥 Pre-merge checks | ✅ 2 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 2.22% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely summarizes the main changes: adding project script actions (with shortcuts, persistence, and setup-run support). It accurately reflects the PR's core objective without being vague or misleading.
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing Touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/7a5ed533`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Add project script actions with keyboard shortcuts, persist scripts and keybindings to disk, and pass runtime env to terminals via wsServer.createServer and TerminalManager.open

      Introduce script run commands (script.<id>.run) with validation, upsert keybindings atomically to ~/.t3/keybindings.json, add projects.updateScripts and server.upsertKeybinding WS methods, persist and normalize project scripts, and pass runtime env and shell args to terminals with 120x30 default sizing. Core logic lives in apps/server/src/keybindings.ts, apps/server/src/projectRegistry.ts, apps/server/src/wsServer.ts, apps/server/src/terminalManager.ts, and UI wiring in apps/web/src/components/ChatView.tsx and apps/web/src/components/ProjectScriptsControl.tsx.

      📍Where to Start

      Start with the WS handlers in wsServer.createServer in apps/server/src/wsServer.ts, then follow projectRegistry.updateScripts in apps/server/src/projectRegistry.ts and upsertKeybindingRule in apps/server/src/keybindings.ts; finally review terminal env handling in TerminalManager.open in apps/server/src/terminalManager.ts and the UI entry points in apps/web/src/components/ChatView.tsx.


      Macroscope summarized 2780666.
    3. greptile-apps[bot](GitHub profile, opens in a new tab)commented

      Greptile Summary

      Adds project-scoped script actions across the full stack: shared Zod contracts for script schemas and dynamic script.{id}.run keybinding commands, server-side persistence in ProjectRegistry with ID deduplication and single-setup enforcement, new projects.updateScripts and server.upsertKeybinding WebSocket methods, and a ProjectScriptsControl UI component for adding/editing/running scripts with keybinding capture.

      • Contracts: New projectScriptSchema, projectScriptsSchema, update scripts input/result schemas, and extended keybindingCommandSchema to accept dynamic script commands via regex
      • Server: ProjectRegistry.updateScripts with atomic file writes; upsertKeybindingRule with atomic keybinding config persistence; depth-limited when-expression parser to prevent stack overflow
      • Web: ProjectScriptsControl component with icon picker, keybinding capture, and form validation; refactored shortcut handler in ChatView from individual is*Shortcut checks to resolveShortcutCommand supporting dynamic script commands; setup script auto-runs after worktree creation; persistProjectScripts with optimistic update and rollback on failure
      • Issue found: The keybinding capture UI accepts bare keys without modifiers (e.g., just r), which would intercept normal typing
      • Testing: Extensive unit tests added across all packages covering script lifecycle, deduplication, env injection, keybinding upsert/persistence, and WebSocket flows

      Confidence Score: 4/5

      • This PR is well-structured and thoroughly tested, with one usability bug in keybinding capture that could interfere with normal typing.
      • The PR adds a significant feature across all three packages with consistent patterns, proper validation, atomic file writes, and extensive test coverage. The one issue found (bare key keybinding capture) is a real usability bug but has limited blast radius since users would need to actively bind a bare key. The contracts are well-designed with proper Zod constraints, and the server-side logic includes proper deduplication and safety limits.
      • Pay close attention to apps/web/src/components/ProjectScriptsControl.tsx (bare key keybinding capture issue) and apps/web/src/components/ChatView.tsx (large addition with complex callback chains).

      Important Files Changed

      FilenameOverview
      packages/contracts/src/project.tsAdds well-validated Zod schemas for project scripts (id, name, command, icon, runOnWorktreeCreate) and update scripts input/result types. Clean, well-bounded constraints.
      packages/contracts/src/keybindings.tsExtends keybinding command schema from a static enum to a union supporting dynamic script.{id}.run commands with proper regex validation. Clean change.
      apps/server/src/keybindings.tsMajor refactor: separates custom config loading from default merging, adds atomic file writes, depth-limited when-expression parser, and new upsertKeybindingRule function. Well-structured with proper error handling.
      apps/server/src/projectRegistry.tsAdds script persistence to ProjectRegistry with deduplication, single-setup enforcement, and deep-clone safety. JSON.stringify comparison for change detection is functional but fragile.
      apps/server/src/wsServer.tsAdds two new WS method handlers for script updates and keybinding upsert. The keybindingsConfig variable is changed from const to let to support in-memory mutation on upsert. Clean integration.
      apps/web/src/projectScripts.tsNew module for script helpers: ID generation, env injection (posix/windows), runtime env building, and script resolution. Well-tested, includes proper shell escaping.
      apps/web/src/components/ChatView.tsxLarge addition: script execution, persistence with rollback, keybinding refactor from individual shortcut checks to resolveShortcutCommand, setup script auto-run on worktree creation, and localStorage-based last-invoked tracking. Well-structured callbacks with proper error handling.
      apps/web/src/components/ProjectScriptsControl.tsxNew 450-line component for adding/editing/running scripts with icon picker, keybinding capture, and form validation. Clean component design with proper state management.
      apps/web/src/store.tsAdds SET_PROJECT_SCRIPTS action and normalizeProjectScripts (dedup + single-setup enforcement). SYNC_PROJECTS now treats server scripts as authoritative, fixing the previously reported issue.

      Sequence Diagram

      sequenceDiagram
          participant UI as ProjectScriptsControl
          participant CV as ChatView
          participant WS as WebSocket Transport
          participant SRV as wsServer
          participant PR as ProjectRegistry
          participant KB as keybindings.ts
          participant FS as Filesystem
      
          Note over UI,FS: Add/Update Script Flow
          UI->>CV: onAddScript(input)
          CV->>CV: dispatch(SET_PROJECT_SCRIPTS) [optimistic]
          CV->>WS: projects.updateScripts({id, scripts})
          WS->>SRV: handleRequest
          SRV->>PR: updateScripts(input)
          PR->>PR: dedupeScriptsById + single-setup
          PR->>FS: persist (atomic write)
          PR-->>SRV: {project}
          SRV-->>WS: result
          WS-->>CV: updated project
      
          opt keybinding provided
              CV->>WS: server.upsertKeybinding({key, command})
              WS->>SRV: handleRequest
              SRV->>KB: upsertKeybindingRule(rule)
              KB->>FS: loadCustomConfig + writeConfigAtomically
              KB-->>SRV: mergedKeybindings
              SRV->>SRV: update cached keybindingsConfig
              SRV-->>CV: {keybindings}
              CV->>CV: queryClient.setQueryData(serverConfig)
          end
      
          CV->>CV: dispatch(SET_PROJECT_SCRIPTS) [authoritative]
      
          Note over UI,FS: Run Script Flow
          UI->>CV: onRunScript(script)
          CV->>CV: injectEnvIntoShellCommand
          CV->>WS: terminal.open + terminal.write
          WS->>SRV: open terminal + write command
      Last reviewed commit: 191883e
    4. 25 files reviewed, 2 comments [Edit Code Review Agent Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews)
      apps/web/src/store.ts lines 478 to 481OutdatedResolvedby juliusmarminge
      apps/web/src/projectScripts.ts lines 58 to 59OutdatedResolvedby juliusmarminge
    5. 🧹 Nitpick comments (2)
      apps/web/src/components/ChatView.tsx (1)

      1-86: Prefer @/ alias for the new local imports The new ProjectScriptsControl and projectScripts imports should follow the repo’s alias convention.

      ♻️ Suggested import cleanup
      -import ProjectScriptsControl, { type NewProjectScriptInput } from "./ProjectScriptsControl";
      +import ProjectScriptsControl, { type NewProjectScriptInput } from "@/components/ProjectScriptsControl";
       import {
         injectEnvIntoShellCommand,
         nextProjectScriptId,
         projectScriptIdFromCommand,
         setupProjectScript,
      -} from "~/projectScripts";
      +} from "@/projectScripts";

      Based on learnings: Use @/ import alias to resolve to local src and upstream t3chat/src.

      apps/server/src/projectRegistry.ts (1)

      21-33: Consider a shared script-clone helper to avoid field drift.

      Both cloneScripts and dedupeScriptsById manually copy fields; a shared helper would reduce maintenance risk if ProjectScript evolves.

    6. Actionable comments posted: 3

      🤖 Fix all issues with AI agents
      In `@apps/server/src/keybindings.ts`:
      - Around line 387-389: The current write sequence using fs.mkdirSync(...) and
      fs.writeFileSync(configPath, ...) can produce a partially-written
      keybindings.json on crash; change the write to an atomic replace: serialize
      cappedConfig to a string, write that content to a temporary file in the same
      directory (e.g., `${configPath}.tmp` or use a unique suffix), fsync the temp
      file (or use fs.writeFileSync), then rename the temp file over configPath via
      fs.renameSync to atomically replace the original; update the code around
      configPath and cappedConfig (the block that currently calls fs.writeFileSync) to
      perform write-to-temp + fs.renameSync and ensure the parent directory is created
      first with fs.mkdirSync.
      
      In `@apps/web/src/components/ChatView.tsx`:
      - Around line 96-121: The readLastInvokedScriptByProjectFromStorage function
      calls localStorage.getItem without guarding against Storage access exceptions;
      wrap the localStorage.getItem call in a try/catch and return {} on any error so
      mount-time crashes are avoided, and apply the same defensive pattern to other
      localStorage reads in this file (the other read occurrences around the code that
      read keys for last-invoked scripts and any user prefs / keybinding reads).
      Ensure you still perform the existing JSON.parse/type checks after a successful
      getItem, and keep the function signature and return type (Record<string,string>)
      unchanged.
      - Around line 405-484: The code may reuse an undefined active terminal ID
      (activeThread.activeTerminalId) which can cause dispatches with undefined IDs;
      in runProjectScript, treat a missing base terminal as requiring creation of a
      new terminal by deriving baseTerminalId = activeThread.activeTerminalId ??
      undefined and setting shouldCreateNewTerminal =
      Boolean(options?.preferNewTerminal) || !baseTerminalId ||
      activeThread.runningTerminalIds.includes(baseTerminalId); ensure
      targetTerminalId is only the reused ID when baseTerminalId is truthy, and always
      dispatch NEW_THREAD_TERMINAL when creating a new one (referencing
      runProjectScript, activeThread.activeTerminalId, NEW_THREAD_TERMINAL, and
      SET_THREAD_ACTIVE_TERMINAL).
      🧹 Nitpick comments (1)
      apps/server/src/wsServer.test.ts (1)

      812-846: Consider asserting persisted scripts/config to lock in side effects. Right now this step only checks the response payload; adding a disk or cached-config assertion would make the integration test more resilient to regressions in persistence/caching flows. Based on learnings: “For integration tests: Prefer deterministic inputs and explicit state checks; … Assert on final state and side effects.”

    7. Actionable comments posted: 2

      🧹 Nitpick comments (3)
      apps/server/src/projectRegistry.ts (1)

      176-189: JSON.stringify for deep equality is acceptable here.

      Given the small size of script arrays (max 64 per schema), the performance impact is negligible. Consider adding a comment noting this is intentional for simplicity.

      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/server/src/projectRegistry.ts` around lines 176 - 189, The equality
      check that computes the changed variable uses JSON.stringify to compare
      project.scripts inside the normalizedProjects.some comparator; add a concise
      inline comment above that JSON.stringify comparison (or above the comparator
      block) stating that deep equality via JSON.stringify is intentional and
      acceptable due to the small bounded size of script arrays (max 64) and chosen
      for simplicity and readability, so future readers know this is a deliberate
      decision rather than an oversight.
      packages/contracts/src/ipc.ts (1)

      38-49: Consider consolidating imports from ./server.

      The ServerConfig import on line 38 and the ServerUpsertKeybindingInput, ServerUpsertKeybindingResult imports on line 49 are from the same module. Consolidating them improves readability.

      ♻️ Suggested consolidation
      -import type { ServerConfig } from "./server";
      +import type {
      +  ServerConfig,
      +  ServerUpsertKeybindingInput,
      +  ServerUpsertKeybindingResult,
      +} from "./server";
       import type {
         TerminalClearInput,
         ...
       } from "./terminal";
       import type { NewTodoInput, Todo } from "./todo";
      -import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@packages/contracts/src/ipc.ts` around lines 38 - 49, Consolidate duplicate
      imports from "./server": replace the separate import of ServerConfig and the
      later import of ServerUpsertKeybindingInput and ServerUpsertKeybindingResult by
      combining them into a single import declaration (e.g., import type {
      ServerConfig, ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from
      "./server") so all types from the server module are imported together and
      improve readability; make this change where ServerConfig,
      ServerUpsertKeybindingInput, and ServerUpsertKeybindingResult are currently
      referenced.
      apps/web/src/components/ProjectScriptsControl.tsx (1)

      129-153: Potential modifier duplication in keybinding serialization.

      When binding.shortcut.modKey is true, ctrlKey or metaKey may also be true depending on the platform. This could produce strings like mod+ctrl+k which might not round-trip correctly through the capture logic.

      Consider aligning with how keybindingFromEvent handles modifiers to ensure consistency.

      ♻️ Proposed alignment
       function keybindingValueForCommand(
         keybindings: ResolvedKeybindingsConfig,
         command: string,
       ): string | null {
         for (let index = keybindings.length - 1; index >= 0; index -= 1) {
           const binding = keybindings[index];
           if (!binding || binding.command !== command) continue;
      
           const parts: string[] = [];
           if (binding.shortcut.modKey) parts.push("mod");
      -    if (binding.shortcut.ctrlKey) parts.push("ctrl");
      -    if (binding.shortcut.metaKey) parts.push("meta");
      +    // Only add ctrl/meta if modKey is not set (avoid duplication)
      +    if (!binding.shortcut.modKey) {
      +      if (binding.shortcut.ctrlKey) parts.push("ctrl");
      +      if (binding.shortcut.metaKey) parts.push("meta");
      +    }
           if (binding.shortcut.altKey) parts.push("alt");
           if (binding.shortcut.shiftKey) parts.push("shift");
      🤖 Prompt for AI Agents
      Verify each finding against the current code and only fix it if needed.
      
      In `@apps/web/src/components/ProjectScriptsControl.tsx` around lines 129 - 153,
      The serialization in keybindingValueForCommand can produce duplicate modifiers
      (e.g., "mod+ctrl+K") because it unconditionally appends ctrl/meta even when
      binding.shortcut.modKey is true; update keybindingValueForCommand to align with
      keybindingFromEvent by treating modKey as mutually exclusive with
      ctrlKey/metaKey when serializing: if binding.shortcut.modKey is true, push "mod"
      and do not also push "ctrl" or "meta"; otherwise, push "ctrl" and/or "meta" as
      appropriate, preserving the existing order and then append alt/shift and the key
      token so the serialized string matches the capture logic used by
      keybindingFromEvent.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Inline comments:
      In `@apps/web/src/components/ChatView.tsx`:
      - Around line 694-707: The call to projectScriptRuntimeEnv is passing extraEnv:
      options?.env which can be undefined and violates the required
      Record<string,string> type; update the object passed to projectScriptRuntimeEnv
      (used in injectEnvIntoShellCommand) so that the extraEnv property is only
      included when options?.env is defined (e.g., build the runtime env object
      conditionally or spread extraEnv only when truthy) to ensure extraEnv is always
      a Record<string,string> when present and never undefined.
      
      In `@apps/web/src/projectScripts.ts`:
      - Around line 85-95: The pipeline fails because callers sometimes pass extraEnv:
      undefined while the interface ProjectScriptRuntimeEnvInput declares extraEnv as
      optional but not allowed to be explicitly undefined under
      exactOptionalPropertyTypes; either update the type to allow undefined (change
      the property to extraEnv?: Record<string,string> | undefined or extraEnv:
      Record<string,string> | undefined) in ProjectScriptRuntimeEnvInput, or fix the
      call site (e.g., in ChatView.tsx) to omit extraEnv when there is no value
      (conditionally spread or only include extraEnv when defined).
      
      ---
      
      Duplicate comments:
      In `@apps/server/src/keybindings.ts`:
      - Around line 368-392: The upsertKeybindingRule currently writes directly to
      configPath which can leave keybindings.json truncated on a crash; make the write
      atomic by writing cappedConfig to a temp file in the same directory (e.g.,
      configPath + a unique suffix using process.pid or a random token), fsync/close
      that file to ensure data is flushed, then rename (atomic replace) the temp file
      to configPath; ensure the directory is created beforehand (keep the existing
      fs.mkdirSync(path.dirname(configPath), { recursive: true }) call) and
      handle/propagate any write or rename errors so callers/logging see failures.
      
      In `@apps/web/src/components/ChatView.tsx`:
      - Around line 667-672: activeThread.activeTerminalId may be undefined which
      makes targetTerminalId invalid; update the logic in ChatView to force creation
      of a new terminal when activeThread.activeTerminalId is falsy: change the
      shouldCreateNewTerminal calculation to also check for missing activeTerminalId
      (e.g., shouldCreateNewTerminal = Boolean(options?.preferNewTerminal) ||
      !activeThread.activeTerminalId || isBaseTerminalBusy) and then compute
      targetTerminalId using that flag so targetTerminalId is never undefined when
      reused in subsequent dispatch/API calls.
      - Around line 131-147: The call to localStorage.getItem in
      readLastInvokedScriptByProjectFromStorage can throw in restricted environments;
      move the getItem call inside the try block (or first check for typeof window !==
      "undefined" and 'localStorage' in window) and wrap it in the existing try/catch
      so any DOM/storage exceptions are caught and the function returns {}; update the
      function readLastInvokedScriptByProjectFromStorage to safely obtain stored =
      localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY) inside the try and
      return {} on any thrown error.
      
      ---
      
      Nitpick comments:
      In `@apps/server/src/projectRegistry.ts`:
      - Around line 176-189: The equality check that computes the changed variable
      uses JSON.stringify to compare project.scripts inside the
      normalizedProjects.some comparator; add a concise inline comment above that
      JSON.stringify comparison (or above the comparator block) stating that deep
      equality via JSON.stringify is intentional and acceptable due to the small
      bounded size of script arrays (max 64) and chosen for simplicity and
      readability, so future readers know this is a deliberate decision rather than an
      oversight.
      
      In `@apps/web/src/components/ProjectScriptsControl.tsx`:
      - Around line 129-153: The serialization in keybindingValueForCommand can
      produce duplicate modifiers (e.g., "mod+ctrl+K") because it unconditionally
      appends ctrl/meta even when binding.shortcut.modKey is true; update
      keybindingValueForCommand to align with keybindingFromEvent by treating modKey
      as mutually exclusive with ctrlKey/metaKey when serializing: if
      binding.shortcut.modKey is true, push "mod" and do not also push "ctrl" or
      "meta"; otherwise, push "ctrl" and/or "meta" as appropriate, preserving the
      existing order and then append alt/shift and the key token so the serialized
      string matches the capture logic used by keybindingFromEvent.
      
      In `@packages/contracts/src/ipc.ts`:
      - Around line 38-49: Consolidate duplicate imports from "./server": replace the
      separate import of ServerConfig and the later import of
      ServerUpsertKeybindingInput and ServerUpsertKeybindingResult by combining them
      into a single import declaration (e.g., import type { ServerConfig,
      ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server") so
      all types from the server module are imported together and improve readability;
      make this change where ServerConfig, ServerUpsertKeybindingInput, and
      ServerUpsertKeybindingResult are currently referenced.
      apps/web/src/projectScripts.ts lines 52 to 58Resolvedby juliusmarminge
    8. apps/web/src/store.ts line 487OutdatedResolvedby juliusmarminge
      apps/web/src/components/ChatView.tsx line 1351Resolvedby juliusmarminge
      apps/web/src/components/ChatView.tsx line 705Resolvedby juliusmarminge
    9. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 3 of the 3 bugs found in the latest run.

      • ✅ Fixed: SYNC_PROJECTS preserves stale scripts when server returns empty
        • Changed SYNC_PROJECTS reducer to always use server scripts via normalizeProjectScripts(project.scripts) instead of conditionally falling back to stale local scripts when the server array is empty.
      • ✅ Fixed: Stale closure omits worktree path in setup env
        • Added env: { T3CODE_WORKTREE_PATH: result.worktree.path } to the runProjectScript options at the worktree creation call site, so the env variable is passed directly rather than read from the stale closure.
      • ✅ Fixed: Script execution skips terminal count limit check
        • Added a hasReachedTerminalLimit guard in runProjectScript that returns early when a new terminal is needed but the limit has been reached, preventing orphaned server-side PTY processes.

      Create PR

      Or push these changes by commenting:

      @cursor push 07669d7d1c
      Preview (pingdotgg/codething-mvp@07669d7d1c)
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -667,6 +667,7 @@
             const baseTerminalId = activeThread.activeTerminalId;
             const isBaseTerminalBusy = activeThread.runningTerminalIds.includes(baseTerminalId);
             const shouldCreateNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;
      +      if (shouldCreateNewTerminal && hasReachedTerminalLimit) return;
             const targetTerminalId = shouldCreateNewTerminal
               ? `terminal-${crypto.randomUUID()}`
               : baseTerminalId;
      @@ -727,7 +728,7 @@
               });
             }
           },
      -    [activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
      +    [activeProject, activeThread, activeThreadId, api, dispatch, gitCwd, hasReachedTerminalLimit],
         );
         const saveProjectScript = useCallback(
           async (input: NewProjectScriptInput) => {
      @@ -1350,6 +1351,7 @@
               if (setupScript) {
                 void runProjectScript(setupScript, {
                   cwd: result.worktree.path,
      +            env: { T3CODE_WORKTREE_PATH: result.worktree.path },
                 });
               }
             } catch (err) {
      
      diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
      --- a/apps/web/src/store.ts
      +++ b/apps/web/src/store.ts
      @@ -481,10 +481,7 @@
             );
             const nextProjects = action.projects.map((project) => {
               const previous = previousByCwd.get(project.cwd);
      -        const scripts =
      -          project.scripts.length > 0
      -            ? normalizeProjectScripts(project.scripts)
      -            : normalizeProjectScripts(previous?.scripts ?? []);
      +        const scripts = normalizeProjectScripts(project.scripts);
               return {
                 ...project,
                 model: resolveModelSlug(previous?.model ?? project.model),
    10. 🤖 Prompt for all review comments with AI agents
      Verify each finding against the current code and only fix it if needed.
      
      Duplicate comments:
      In `@apps/web/src/components/ChatView.tsx`:
      - Around line 667-673: activeThread.activeTerminalId can be undefined so
      computing targetTerminalId may yield undefined and later dispatch/open/write
      calls will fail; update the logic in the block that computes
      baseTerminalId/isBaseTerminalBusy/shouldCreateNewTerminal/targetTerminalId to
      guard against undefined by treating a missing activeTerminalId as requiring a
      new terminal (e.g., set shouldCreateNewTerminal =
      Boolean(options?.preferNewTerminal) || !baseTerminalId || isBaseTerminalBusy)
      and ensure targetTerminalId always falls back to generating a new id when
      baseTerminalId is falsy.
      - Around line 131-146: readLastInvokedScriptByProjectFromStorage currently calls
      localStorage.getItem(...) outside the try/catch which can throw in restricted
      contexts; move the getItem call inside the existing try block (covering both
      localStorage.getItem and JSON.parse) so any errors result in returning {}
      instead of crashing, keep the filtering logic unchanged, and avoid adding
      warnings/logging so the function gracefully degrades in environments like
      private/incognito where localStorage is unavailable (refer to
      LAST_INVOKED_SCRIPT_BY_PROJECT_KEY and the
      readLastInvokedScriptByProjectFromStorage function).
    11. apps/web/src/projectScripts.ts line 60OutdatedResolvedby juliusmarminge
      apps/web/src/components/ChatView.tsx line 813Resolvedby juliusmarminge
      apps/web/src/store.ts line 198OutdatedResolvedby juliusmarminge
    12. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 3 of the 3 bugs found in the latest run.

      • ✅ Fixed: Windows %% escaping only works in batch files
        • Removed the % → %% replacement in shellEscapeWindowsSetValue since %% only collapses to % in batch files, not in interactive cmd.exe sessions where terminal.write sends commands.
      • ✅ Fixed: Duplicated save and update script persistence logic
        • Extracted the shared server persistence, keybinding upsert, query cache update, and rollback logic into a persistProjectScripts callback used by both saveProjectScript and updateProjectScript.
      • ✅ Fixed: Duplicated script dedup/normalization across server and client
        • Moved the dedup-by-ID and single-runOnWorktreeCreate normalization algorithm into a shared normalizeProjectScripts function in @t3tools/contracts, replacing the duplicate implementations in store.ts and projectRegistry.ts.

      Create PR

      Or push these changes by commenting:

      @cursor push 8e1ca36b46
      Preview (pingdotgg/codething-mvp@8e1ca36b46)
      diff --git a/apps/server/src/projectRegistry.ts b/apps/server/src/projectRegistry.ts
      --- a/apps/server/src/projectRegistry.ts
      +++ b/apps/server/src/projectRegistry.ts
      @@ -16,6 +16,7 @@
         projectRemoveInputSchema,
         projectScriptsSchema,
         projectUpdateScriptsInputSchema,
      +  normalizeProjectScripts,
       } from "@t3tools/contracts";
       
       function cloneScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
      @@ -130,7 +131,7 @@
             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 @@
               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 @@
           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;
      -}
      
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -300,7 +300,9 @@
           <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 @@
             });
             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,48 +739,26 @@
           },
           [activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
         );
      -  const saveProjectScript = useCallback(
      -    async (input: NewProjectScriptInput) => {
      -      if (!activeProject) return;
      -      const nextId = nextProjectScriptId(
      -        input.name,
      -        activeProject.scripts.map((script) => script.id),
      -      );
      -      const nextScript: ProjectScript = {
      -        id: nextId,
      -        name: input.name,
      -        command: input.command,
      -        icon: input.icon,
      -        runOnWorktreeCreate: input.runOnWorktreeCreate,
      -      };
      -      const nextScripts = input.runOnWorktreeCreate
      -        ? [
      -            ...activeProject.scripts.map((script) =>
      -              script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
      -            ),
      -            nextScript,
      -          ]
      -        : [...activeProject.scripts, nextScript];
      -
      -      dispatch({
      -        type: "SET_PROJECT_SCRIPTS",
      -        projectId: activeProject.id,
      -        scripts: nextScripts,
      -      });
      -
      +  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: activeProject.id,
      +          id: project.id,
                 scripts: nextScripts,
               });
               scriptsPersisted = true;
       
      -        if (input.keybinding) {
      +        if (keybinding) {
                 const keybindingUpdate = await api.server.upsertKeybinding({
      -            key: input.keybinding,
      -            command: commandForProjectScript(nextId),
      +            key: keybinding,
      +            command: keybindingCommand,
                 });
                 queryClient.setQueryData(
                   serverQueryKeys.config(),
      @@ -788,7 +766,7 @@
                     current
                       ? { ...current, keybindings: keybindingUpdate.keybindings }
                       : {
      -                    cwd: activeProject.cwd,
      +                    cwd: project.cwd,
                           keybindings: keybindingUpdate.keybindings,
                         },
                 );
      @@ -803,21 +781,59 @@
               if (scriptsPersisted) {
                 await api.projects
                   .updateScripts({
      -              id: activeProject.id,
      -              scripts: activeProject.scripts,
      +              id: project.id,
      +              scripts: project.scripts,
                   })
                   .catch(() => undefined);
               }
               dispatch({
                 type: "SET_PROJECT_SCRIPTS",
      -          projectId: activeProject.id,
      -          scripts: activeProject.scripts,
      +          projectId: project.id,
      +          scripts: project.scripts,
               });
               throw error;
             }
           },
      -    [activeProject, api, dispatch, queryClient],
      +    [api, dispatch, queryClient],
         );
      +  const saveProjectScript = useCallback(
      +    async (input: NewProjectScriptInput) => {
      +      if (!activeProject) return;
      +      const nextId = nextProjectScriptId(
      +        input.name,
      +        activeProject.scripts.map((script) => script.id),
      +      );
      +      const nextScript: ProjectScript = {
      +        id: nextId,
      +        name: input.name,
      +        command: input.command,
      +        icon: input.icon,
      +        runOnWorktreeCreate: input.runOnWorktreeCreate,
      +      };
      +      const nextScripts = input.runOnWorktreeCreate
      +        ? [
      +            ...activeProject.scripts.map((script) =>
      +              script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
      +            ),
      +            nextScript,
      +          ]
      +        : [...activeProject.scripts, nextScript];
      +
      +      dispatch({
      +        type: "SET_PROJECT_SCRIPTS",
      +        projectId: activeProject.id,
      +        scripts: nextScripts,
      +      });
      +
      +      await persistProjectScripts(
      +        activeProject,
      +        nextScripts,
      +        input.keybinding,
      +        commandForProjectScript(nextId),
      +      );
      +    },
      +    [activeProject, dispatch, persistProjectScripts],
      +  );
         const updateProjectScript = useCallback(
           async (scriptId: string, input: NewProjectScriptInput) => {
             if (!activeProject) return;
      @@ -847,55 +863,14 @@
               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
      --- a/apps/web/src/projectScripts.test.ts
      +++ b/apps/web/src/projectScripts.test.ts
      @@ -25,12 +25,20 @@
         });
       
         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 @@
             { 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
      --- a/apps/web/src/projectScripts.ts
      +++ b/apps/web/src/projectScripts.ts
      @@ -56,7 +56,11 @@
       }
       
       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 @@
         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,
      
      diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
      --- a/apps/web/src/store.ts
      +++ b/apps/web/src/store.ts
      @@ -8,7 +8,12 @@
         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 @@
           .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 @@
               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 @@
               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
      --- a/packages/contracts/src/project.ts
      +++ b/packages/contracts/src/project.ts
      @@ -95,3 +95,40 @@
       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;
      +}
    13. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issues.
      apps/web/src/components/ProjectScriptsControl.tsx line 295OutdatedResolvedby juliusmarminge
      apps/web/src/components/ChatView.tsx line 814Resolvedby juliusmarminge
    14. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 2 of the 2 bugs found in the latest run.

      • ✅ Fixed: No-op ternary renders setup scripts identically to others
        • Added " (setup)" suffix to the template literal so setup scripts are visually distinguished from regular scripts in the dropdown menu.
      • ✅ Fixed: Save and update script callbacks duplicate persistence logic
        • Extracted a shared persistScriptsUpdate callback that encapsulates the server persist, keybinding upsert, cache update, and rollback logic, parameterized by the script command ID.

      Create PR

      Or push these changes by commenting:

      @cursor push a84b28420c
      Preview (pingdotgg/codething-mvp@a84b28420c)
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -300,7 +300,9 @@
           <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 @@
             });
             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,48 +739,26 @@
           },
           [activeProject, activeThread, activeThreadId, api, dispatch, gitCwd],
         );
      -  const saveProjectScript = useCallback(
      -    async (input: NewProjectScriptInput) => {
      -      if (!activeProject) return;
      -      const nextId = nextProjectScriptId(
      -        input.name,
      -        activeProject.scripts.map((script) => script.id),
      -      );
      -      const nextScript: ProjectScript = {
      -        id: nextId,
      -        name: input.name,
      -        command: input.command,
      -        icon: input.icon,
      -        runOnWorktreeCreate: input.runOnWorktreeCreate,
      -      };
      -      const nextScripts = input.runOnWorktreeCreate
      -        ? [
      -            ...activeProject.scripts.map((script) =>
      -              script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
      -            ),
      -            nextScript,
      -          ]
      -        : [...activeProject.scripts, nextScript];
      -
      -      dispatch({
      -        type: "SET_PROJECT_SCRIPTS",
      -        projectId: activeProject.id,
      -        scripts: nextScripts,
      -      });
      -
      -      if (!isElectron || !api) return;
      +  const persistScriptsUpdate = useCallback(
      +    async (
      +      project: NonNullable<typeof activeProject>,
      +      nativeApi: NativeApi,
      +      nextScripts: ProjectScript[],
      +      scriptCommandId: string,
      +      input: NewProjectScriptInput,
      +    ) => {
             let scriptsPersisted = false;
             try {
      -        const updated = await api.projects.updateScripts({
      -          id: activeProject.id,
      +        const updated = await nativeApi.projects.updateScripts({
      +          id: project.id,
                 scripts: nextScripts,
               });
               scriptsPersisted = true;
       
               if (input.keybinding) {
      -          const keybindingUpdate = await api.server.upsertKeybinding({
      +          const keybindingUpdate = await nativeApi.server.upsertKeybinding({
                   key: input.keybinding,
      -            command: commandForProjectScript(nextId),
      +            command: commandForProjectScript(scriptCommandId),
                 });
                 queryClient.setQueryData(
                   serverQueryKeys.config(),
      @@ -788,7 +766,7 @@
                     current
                       ? { ...current, keybindings: keybindingUpdate.keybindings }
                       : {
      -                    cwd: activeProject.cwd,
      +                    cwd: project.cwd,
                           keybindings: keybindingUpdate.keybindings,
                         },
                 );
      @@ -801,23 +779,57 @@
               });
             } catch (error) {
               if (scriptsPersisted) {
      -          await api.projects
      +          await nativeApi.projects
                   .updateScripts({
      -              id: activeProject.id,
      -              scripts: activeProject.scripts,
      +              id: project.id,
      +              scripts: project.scripts,
                   })
                   .catch(() => undefined);
               }
               dispatch({
                 type: "SET_PROJECT_SCRIPTS",
      -          projectId: activeProject.id,
      -          scripts: activeProject.scripts,
      +          projectId: project.id,
      +          scripts: project.scripts,
               });
               throw error;
             }
           },
      -    [activeProject, api, dispatch, queryClient],
      +    [dispatch, queryClient],
         );
      +  const saveProjectScript = useCallback(
      +    async (input: NewProjectScriptInput) => {
      +      if (!activeProject) return;
      +      const nextId = nextProjectScriptId(
      +        input.name,
      +        activeProject.scripts.map((script) => script.id),
      +      );
      +      const nextScript: ProjectScript = {
      +        id: nextId,
      +        name: input.name,
      +        command: input.command,
      +        icon: input.icon,
      +        runOnWorktreeCreate: input.runOnWorktreeCreate,
      +      };
      +      const nextScripts = input.runOnWorktreeCreate
      +        ? [
      +            ...activeProject.scripts.map((script) =>
      +              script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,
      +            ),
      +            nextScript,
      +          ]
      +        : [...activeProject.scripts, nextScript];
      +
      +      dispatch({
      +        type: "SET_PROJECT_SCRIPTS",
      +        projectId: activeProject.id,
      +        scripts: nextScripts,
      +      });
      +
      +      if (!isElectron || !api) return;
      +      await persistScriptsUpdate(activeProject, api, nextScripts, nextId, input);
      +    },
      +    [activeProject, api, dispatch, persistScriptsUpdate],
      +  );
         const updateProjectScript = useCallback(
           async (scriptId: string, input: NewProjectScriptInput) => {
             if (!activeProject) return;
      @@ -848,54 +860,9 @@
             });
       
             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 persistScriptsUpdate(activeProject, api, nextScripts, scriptId, input);
           },
      -    [activeProject, api, dispatch, queryClient],
      +    [activeProject, api, dispatch, persistScriptsUpdate],
         );
       
         const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
      
      diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
      --- a/apps/web/src/components/ProjectScriptsControl.tsx
      +++ b/apps/web/src/components/ProjectScriptsControl.tsx
      @@ -292,7 +292,7 @@
                         >
                           <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 && (
    15. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issue.
      apps/server/src/keybindings.ts line 311OutdatedResolvedby juliusmarminge
    16. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 1 of the 1 bugs found in the latest run.

      • ✅ Fixed: Error message double-wrapped in keybindings config loader
        • Added a check in the catch block to re-throw errors that already carry the 'Unable to parse keybindings config at' prefix directly, preventing the double-wrapping that occurred when the 'not an array' throw inside the try block was caught and re-wrapped with the same prefix.

      Create PR

      Or push these changes by commenting:

      @cursor push b15f55eccd
      Preview (pingdotgg/codething-mvp@b15f55eccd)
      diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts
      --- a/apps/server/src/keybindings.ts
      +++ b/apps/server/src/keybindings.ts
      @@ -343,6 +343,12 @@
             return [];
           }
           if (options?.throwOnUnreadableConfig) {
      +      if (
      +        error instanceof Error &&
      +        error.message.startsWith("Unable to parse keybindings config at ")
      +      ) {
      +        throw error;
      +      }
             throw new Error(
               `Unable to parse keybindings config at ${configPath}: ${
                 error instanceof Error ? error.message : String(error)
    17. @greptileai review

    18. 28 files reviewed, 1 comment [Edit Code Review Agent Settings](https://app.greptile.com/review/github) | [Greptile](https://greptile.com?utm_source=greptile_expert&utm_medium=github&utm_campaign=code_reviews)
    19. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issue.
      @@ -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+ });

      Hardcoded terminal dimensions corrupt reused terminal display

      Medium Severity

      When runProjectScript reuses an existing running terminal (shouldCreateNewTerminal is false), it calls api.terminal.open() with hardcoded SCRIPT_TERMINAL_COLS (120) and SCRIPT_TERMINAL_ROWS (30). The server's TerminalManager.open() forcefully resizes the PTY to these dimensions if they differ from the current size. The client-side xterm.js instance is never notified of this resize because the ThreadTerminalDrawer resize effect's dependencies (drawerHeight, resizeEpoch, terminalId, threadId) don't change. This causes a persistent mismatch between the PTY's assumed dimensions and the UI's actual rendering size, resulting in garbled terminal output until the user manually triggers a resize.

      Additional Locations (1)

      Fix in Cursor Fix in Web

    20. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 1 of the 1 bugs found in the latest run.

      • ✅ Fixed: Hardcoded terminal dimensions corrupt reused terminal display
        • Made cols/rows optional in terminalOpenInputSchema so runProjectScript only passes hardcoded dimensions for new terminals; for reused terminals, the server preserves the existing TerminalViewport-managed dimensions, preventing the PTY/xterm.js size mismatch.

      Create PR

      Or push these changes by commenting:

      @cursor push c3faa288b8
      Preview (pingdotgg/codething-mvp@c3faa288b8)
      diff --git a/apps/server/src/terminalManager.ts b/apps/server/src/terminalManager.ts
      --- a/apps/server/src/terminalManager.ts
      +++ b/apps/server/src/terminalManager.ts
      @@ -301,8 +301,8 @@
                 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 @@
               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 @@
                 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 @@
       
           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;
      
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -721,8 +721,9 @@
                 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,
      
      diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
      --- a/packages/contracts/src/terminal.ts
      +++ b/packages/contracts/src/terminal.ts
      @@ -16,8 +16,8 @@
       
       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({
    21. @@ -241,10 +267,17 @@
      241267 return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
      242268 }
      243269
      244-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+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      src/terminalManager.ts:281 runtimeEnv entries bypass shouldExcludeTerminalEnvKey, allowing callers to inject blocklisted variables like PORT. Consider applying the same filter before assigning runtimeEnv keys to spawnEnv.

      Suggested change
      285+ for (const [key, value] of Object.entries(runtimeEnv)) {
      286+ if (shouldExcludeTerminalEnvKey(key)) continue;
      287+ spawnEnv[key] = value;

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/server/src/terminalManager.ts around lines 281-283:
      
      `runtimeEnv` entries bypass `shouldExcludeTerminalEnvKey`, allowing callers to inject blocklisted variables like `PORT`. Consider applying the same filter before assigning `runtimeEnv` keys to `spawnEnv`.
      
      Evidence trail:
      Viewed `apps/server/src/terminalManager.ts:23-34` at `2a5525a` (TERMINAL_ENV_BLOCKLIST includes PORT). Viewed `apps/server/src/terminalManager.ts:247-277` at `2a5525a` (createTerminalSpawnEnv filters baseEnv with shouldExcludeTerminalEnvKey but assigns runtimeEnv directly).
    22. Cursor Bugbot has reviewed your changes and found 3 potential issues.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issues.
      @@ -369,4 +372,4 @@
      369372 fitAddonRef.current = null;
      370373 terminal.dispose();
      371374 };
      372- }, [api, cwd, terminalId, threadId]);
      375+ }, [api, autoFocus, cwd, runtimeEnv, terminalId, threadId]);
      cursor[bot](GitHub profile, opens in a new tab)commented

      Adding autoFocus to effect deps causes terminal re-initialization

      High Severity

      Adding autoFocus to the main terminal setup effect's dependency array causes the entire xterm Terminal instance to be destroyed and recreated whenever the active terminal tab changes in split view. In group/split mode, each TerminalViewport receives autoFocus={terminalId === resolvedActiveTerminalId}, so switching tabs flips autoFocus for two terminals, triggering a full teardown and reconnect cycle for both. A separate useEffect at line 377 already handles focus changes correctly without re-initialization.

      Fix in Cursor Fix in Web

      @@ -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]);

      Memo depends on whole object causing terminal re-creation

      Medium Severity

      threadTerminalRuntimeEnv depends on the entire activeProject object reference but only reads activeProject.cwd. Any project state change (like saving a script via SET_PROJECT_SCRIPTS) creates a new project object in the reducer, causing the memo to recompute and produce a new object reference. Since runtimeEnv is in the TerminalViewport effect dependency array, this triggers a full terminal teardown and recreation even though cwd hasn't changed. The dependency should be activeProject?.cwd instead of activeProject.

      Additional Locations (1)

      Fix in Cursor Fix in Web

      @@ -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+}

      injectEnvIntoShellCommand is exported but never used

      Low Severity

      injectEnvIntoShellCommand is exported and tested but never imported by any production code. The entire projectScripts.ts file is new in this PR, and neither ChatView.tsx nor ProjectScriptsControl.tsx (the only consumers of this module) imports this function. Env injection is handled server-side via createTerminalSpawnEnv and the env parameter on terminal.open, making this function dead code.

      Fix in Cursor Fix in Web

    23. @@ -0,0 +323,21 @@
      323+ <PlusIcon className="size-4" />
      324+ Add action
      325+ </MenuItem>
      326+ </MenuPopup>
      327+ </Menu>
      328+ </Group>
      329+ ) : (
      330+ <Button size="xs" variant="outline" onClick={openAddDialog}>
      331+ <PlusIcon className="size-3.5" />
      332+ Add action
      333+ </Button>
      334+ )}
      335+
      336+ <Dialog
      337+ onOpenChange={(open) => {
      338+ setDialogOpen(open);
      339+ if (!open) {
      340+ setIconPickerOpen(false);
      341+ }
      342+ }}
      343+ onOpenChangeComplete={(open) => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      components/ProjectScriptsControl.tsx:343 Race condition: if the dialog is reopened before the closing animation completes, onOpenChangeComplete may clear state that was just set for the new dialog. Consider guarding the cleanup with a check like if (editingScriptId === null) or using a ref to track the intended state.

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/web/src/components/ProjectScriptsControl.tsx around line 343:
      
      Race condition: if the dialog is reopened before the closing animation completes, `onOpenChangeComplete` may clear state that was just set for the new dialog. Consider guarding the cleanup with a check like `if (editingScriptId === null)` or using a ref to track the intended state.
      
      Evidence trail:
      Viewed `apps/web/src/components/ProjectScriptsControl.tsx` lines 330-356 at commit `b033c60` (dialog `onOpenChangeComplete` clears state on close). Viewed `apps/web/src/components/ui/dialog.tsx` lines 1-60 at commit `b033c60` (Dialog wraps Base UI). Consulted Base UI docs/source note: `packages/react/src/popover/root/PopoverRoot.tsx` onOpenChangeComplete comment (https://github.com/mui/base-ui/blob/master/packages/react/src/popover/root/PopoverRoot.tsx). Consulted Base UI dialog issue showing onOpenChangeComplete firing despite interrupted transitions: https://github.com/mui/base-ui/issues/3555.
    24. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 3 of the 3 bugs found in the latest run.

      • ✅ Fixed: Adding autoFocus to effect deps causes terminal re-initialization
        • Removed autoFocus from the main terminal setup effect's dependency array since focus toggling is already handled by a dedicated effect at line 377.
      • ✅ Fixed: Memo depends on whole object causing terminal re-creation
        • Changed the threadTerminalRuntimeEnv memo dependency from activeProject to activeProject?.cwd so unrelated project state changes don't produce a new object reference.
      • ✅ Fixed: injectEnvIntoShellCommand is exported but never used
        • Removed the export keyword from injectEnvIntoShellCommand and removed the corresponding test cases since the function is dead code in production.

      Create PR

      Or push these changes by commenting:

      @cursor push 74cb1b6f84
      Preview (pingdotgg/codething-mvp@74cb1b6f84)
      diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
      --- a/apps/web/src/components/ChatView.tsx
      +++ b/apps/web/src/components/ChatView.tsx
      @@ -552,7 +552,7 @@
             },
             worktreePath: activeThread?.worktreePath ?? null,
           });
      -  }, [activeProject, activeThread?.worktreePath]);
      +  }, [activeProject?.cwd, activeThread?.worktreePath]);
         // Default true while loading to avoid toolbar flicker.
         const isGitRepo = branchesQuery.data?.isRepo ?? true;
         const splitTerminalShortcutLabel = useMemo(
      
      diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
      --- a/apps/web/src/components/ThreadTerminalDrawer.tsx
      +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
      @@ -372,7 +372,7 @@
             fitAddonRef.current = null;
             terminal.dispose();
           };
      -  }, [api, autoFocus, cwd, runtimeEnv, terminalId, threadId]);
      +  }, [api, cwd, runtimeEnv, terminalId, threadId]);
       
         useEffect(() => {
           if (!autoFocus) return;
      
      diff --git a/apps/web/src/projectScripts.test.ts b/apps/web/src/projectScripts.test.ts
      --- a/apps/web/src/projectScripts.test.ts
      +++ b/apps/web/src/projectScripts.test.ts
      @@ -2,7 +2,6 @@
       
       import {
         commandForProjectScript,
      -  injectEnvIntoShellCommand,
         nextProjectScriptId,
         primaryProjectScript,
         projectScriptRuntimeEnv,
      @@ -24,25 +23,6 @@
           expect(nextProjectScriptId("!!!", [])).toBe("script");
         });
       
      -  it("injects environment variables for posix shells", () => {
      -    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");
      -    expect(command).toBe('set "T3CODE_PROJECT_ROOT=C:\\\\repo path" && bun install');
      -  });
      -
      -  it("escapes windows env values that trigger interpolation", () => {
      -    const command = injectEnvIntoShellCommand(
      -      "bun install",
      -      { T3CODE_PROJECT_ROOT: '%USERPROFILE%^"repo"' },
      -      "Win32",
      -    );
      -    expect(command).toBe('set "T3CODE_PROJECT_ROOT=^%USERPROFILE^%^^""repo""" && bun install');
      -  });
      -
         it("resolves primary and setup scripts", () => {
           const scripts = [
             {
      
      diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.ts
      --- a/apps/web/src/projectScripts.ts
      +++ b/apps/web/src/projectScripts.ts
      @@ -60,7 +60,7 @@
         return value.replace(/\^/g, "^^").replace(/%/g, "^%").replace(/"/g, '""');
       }
       
      -export function injectEnvIntoShellCommand(
      +function injectEnvIntoShellCommand(
         command: string,
         env: Record<string, string>,
         platform = typeof navigator === "undefined" ? "" : navigator.platform,
    25. @cursor push 74cb1b6f84

    26. @@ -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_LENGTH
      43+ ? candidate
      44+ : `${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);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low

      src/projectScripts.ts:52 The fallback on line 52 can return a duplicate ID: if baseId is 64 chars, slicing removes the timestamp entirely, returning the already-taken baseId. Also, it doesn't check taken, so rapid calls can collide. Consider truncating baseId first to ensure space for the timestamp, then verify against taken.

      Suggested change
      49- }
      49+ const timestamp = String(Date.now());
      50+ const truncatedBase = baseId.slice(0, Math.max(1, MAX_SCRIPT_ID_LENGTH - timestamp.length - 1));
      51+ const fallback = `${truncatedBase}-${timestamp}`;
      52+ return taken.has(fallback) ? `${truncatedBase}-${timestamp}-${Math.random().toString(36).slice(2, 6)}`.slice(0, MAX_SCRIPT_ID_LENGTH) : fallback;

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/web/src/projectScripts.ts around line 52:
      
      The fallback on line 52 can return a duplicate ID: if `baseId` is 64 chars, slicing removes the timestamp entirely, returning the already-taken `baseId`. Also, it doesn't check `taken`, so rapid calls can collide. Consider truncating `baseId` first to ensure space for the timestamp, then verify against `taken`.
      
      Evidence trail:
      Viewed `apps/web/src/projectScripts.ts:1-70` at commit `e31fcbd` (MAX_SCRIPT_ID_LENGTH and fallback return).
    27. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issue.
      @@ -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+}

      Dead code: unused shell env injection functions

      Low Severity

      injectEnvIntoShellCommand, shellEscapePosix, shellEscapeWindowsSetValue, and ENV_KEY_PATTERN are all defined in this brand-new file but never called or exported. The env injection approach was replaced by passing env directly to terminal.open, but these functions were left behind after the refactor. They add ~30 lines of non-trivial shell-escaping logic that may confuse future developers into thinking it's active code.

      Additional Locations (1)

      Fix in Cursor Fix in Web

    28. cursor[bot](GitHub profile, opens in a new tab)commented

      Bugbot Autofix prepared fixes for 1 of the 1 bugs found in the latest run.

      • ✅ Fixed: Dead code: unused shell env injection functions
        • Removed the four unused symbols (injectEnvIntoShellCommand, shellEscapePosix, shellEscapeWindowsSetValue, ENV_KEY_PATTERN) and the now-unused isWindowsPlatform import, eliminating ~30 lines of dead code left over from the earlier env-injection approach.

      Create PR

      Or push these changes by commenting:

      @cursor push d169cfd54d
      Preview (pingdotgg/codething-mvp@d169cfd54d)
      diff --git a/apps/web/src/projectScripts.ts b/apps/web/src/projectScripts.ts
      --- a/apps/web/src/projectScripts.ts
      +++ b/apps/web/src/projectScripts.ts
      @@ -1,10 +1,7 @@
       import type { ProjectScript } from "@t3tools/contracts";
       
      -import { isWindowsPlatform } from "./lib/utils";
      -
       const SCRIPT_RUN_COMMAND_PATTERN = /^script\.([a-z0-9][a-z0-9-]*)\.run$/;
       const MAX_SCRIPT_ID_LENGTH = 64;
      -const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
       
       function normalizeScriptId(value: string): string {
         const cleaned = value
      @@ -52,37 +49,6 @@
         return `${baseId}-${Date.now()}`.slice(0, MAX_SCRIPT_ID_LENGTH);
       }
       
      -function shellEscapePosix(value: string): string {
      -  return `'${value.replace(/'/g, `'\\''`)}'`;
      -}
      -
      -function shellEscapeWindowsSetValue(value: string): string {
      -  return value.replace(/\^/g, "^^").replace(/%/g, "^%").replace(/"/g, '""');
      -}
      -
      -function injectEnvIntoShellCommand(
      -  command: string,
      -  env: Record<string, string>,
      -  platform = typeof navigator === "undefined" ? "" : navigator.platform,
      -): string {
      -  const entries = Object.entries(env).filter(
      -    ([key, value]) => ENV_KEY_PATTERN.test(key) && value.length > 0,
      -  );
      -  if (entries.length === 0) {
      -    return command;
      -  }
      -
      -  if (isWindowsPlatform(platform)) {
      -    const prefixes = entries.map(
      -      ([key, value]) => `set "${key}=${shellEscapeWindowsSetValue(value)}"`,
      -    );
      -    return `${prefixes.join(" && ")} && ${command}`;
      -  }
      -
      -  const assignments = entries.map(([key, value]) => `${key}=${shellEscapePosix(value)}`).join(" ");
      -  return `env ${assignments} ${command}`;
      -}
      -
       interface ProjectScriptRuntimeEnvInput {
         project: {
           cwd: string;
    29. @cursor push d169cfd54d

    30. @@ -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);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      components/ChatView.tsx:134 localStorage.getItem can throw a SecurityError in restricted environments. Consider wrapping the entire function body in a try-catch.

      -function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
      -  const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
      -  if (!stored) return {};
      -
      -  try {
      +function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
      +  try {
      +    const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
      +    if (!stored) return {};

      🚀 Want me to fix this? Reply ex: "fix it for me".

      🤖 Prompt for AI
      In file apps/web/src/components/ChatView.tsx around lines 134-139:
      
      `localStorage.getItem` can throw a `SecurityError` in restricted environments. Consider wrapping the entire function body in a try-catch.
      
      Evidence trail:
      Viewed `apps/web/src/components/ChatView.tsx` lines 120-150 at commit `58a7840` using https://github.com/pingdotgg/codething-mvp/tree/58a784074bff82c360e398b15708a679d32c9ba3 (function `readLastInvokedScriptByProjectFromStorage`, `localStorage.getItem` call before try/catch).
    31. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Bugbot Autofix is [ON](https://www.cursor.com/dashboard?tab=bugbot). A Cloud Agent has been kicked off to fix the reported issue.
      @@ -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+}

      Duplicated script normalization logic across client and server

      Low Severity

      normalizeProjectScripts in store.ts and dedupeScriptsById in projectRegistry.ts implement identical business logic: deduplicate scripts by ID and enforce a single runOnWorktreeCreate flag. If the normalization rules change (e.g., how duplicate IDs or multiple setup scripts are handled), both copies need updating independently, risking inconsistent behavior between client and server. This could be extracted into a shared utility in the contracts package.

      Additional Locations (1)

      Fix in Cursor Fix in Web

Sign in to join this conversation.