Skip to content
Source
Sign inSign up
pingdotgg/t3code

Add AI-generated worktree branch naming with safe Git branch rename flow #129

Mergedjuliusmarmingemerged 22 commits intomain fromcodething/34345440merged by juliusmarminge View on GitHub

juliusmarmingecommented

Summary

  • Add server-side branch name generation via Codex (generateBranchName) with strict JSON output parsing and branch-fragment sanitization.
  • Add support for image attachments in branch-name generation by materializing data URLs to temp files and passing them to Codex with --image.
  • Add Git core branch rename capability with collision-safe suffixing (-1, -2, etc.) and no-op behavior when old/new names match.
  • Add new WebSocket methods for branch operations: generate name, generate+rename, and direct rename.
  • Prefix generated worktree branches with t3code/ and normalize unsafe input before rename.
  • Extract shared image MIME/extension utilities into imageMime.ts and reuse across projection/attachment handling.
  • Extend contracts and client/server wiring to support the new branch-generation and rename APIs.
  • Add/expand tests across Codex text generation, Git core, Git manager wiring, and WebSocket request handling (including null-generation skip behavior).

Testing

  • apps/server/src/git/Layers/CodexTextGeneration.test.ts: verifies branch generation, normalization, image passthrough to Codex, and invalid payload fallback.
  • apps/server/src/git/Layers/GitCore.test.ts: verifies branch rename success, no-op rename, and collision suffix increment behavior.
  • apps/server/src/wsServer.test.ts: verifies git.generateBranchName, git.generateAndRenameBranch, git.renameBranch, and skip-rename when generation returns null.
  • apps/server/src/git/Layers/GitManager.test.ts: updates fake text generation layer coverage for branch-name generation.
  • Not run: full workspace lint/test execution in this PR description context.

Note

Medium Risk Touches Git operations (new renameBranch with collision handling) and introduces attachment file resolution/cleanup paths used by both Codex and projections, so mistakes could rename the wrong branch or read/delete the wrong files.

Overview AI-generated worktree branch naming: introduces TextGeneration.generateBranchName (Codex CLI-backed) with schema-validated JSON parsing, branch-fragment sanitization, and optional image context passed via --image.

Safe Git branch rename: adds GitCore.renameBranch with -- argument separation, no-op when names match, and automatic -1/-2/... suffixing to avoid collisions; also switches upstream refresh after checkout to Effect.forkDetach.

Attachment storage/usage refactor: adds attachmentStore/attachmentPaths plus imageMime utilities, updates projections to stop materializing data URLs into stateDir and instead persist attachment metadata (id, mimeType, etc.) while pruning/deleting attachment files by attachment-id-derived thread segments; Codex adapter now resolves attachment ids from stateDir and converts them to data: URLs when calling the Codex app server.

Wiring/tests: adds ServerConfig.layerTest and updates integration/unit tests and server layers to provide ServerConfig, NodeServices, and the new GitCore/TextGeneration dependencies; updates Codex manager sendTurn input to use attachments[].url.

Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 150e171a8838b94f518085c8b3b0fffdd876d324. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).

Note

Generate and rename temporary worktree branches to safe t3code/<name> on first user turn using TextGeneration.generateBranchName and GitCore.renameBranch

Add AI-driven branch naming on the first user turn and rename the current temporary branch with collision-safe suffixing; persist image attachments at upload, pass attachment metadata and images to generation, normalize attachment access via id-based routes, and adjust tests and schemas to use id-based attachments without dataUrl. Implement GitCore.renameBranch, branch name sanitization, and id-based attachment resolution across server, adapter, and web layers.

📍Where to Start

Start with the first-turn rename flow in ProviderCommandReactor.maybeGenerateAndRenameWorktreeBranchForFirstTurn in apps/server/src/orchestration/Layers/ProviderCommandReactor.ts.

Macroscope summarized 150e171.
    1. Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `codething/34345440`

      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. apps/server/src/projectFaviconRoute.ts line 4OutdatedResolvedby juliusmarminge
    3. apps/server/src/serverLayers.ts line 58Resolvedby juliusmarminge
    4. apps/server/src/attachmentStore.ts line 97Resolvedby juliusmarminge
      apps/server/src/git/Layers/GitCore.ts line 787Resolvedby juliusmarminge
    5. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Inconsistent thread segment derivation breaks attachment cleanup
        • Removed the duplicate toSafeThreadAttachmentSegment in ProjectionPipeline.ts (which used encodeURIComponent) and replaced it with an import of the canonical version from attachmentStore.ts (which uses regex sanitization), ensuring consistent thread segment derivation for attachment cleanup.

      Create PR

      Or push these changes by commenting:

      @cursor push 462881455e
      Preview (pingdotgg/t3code@462881455e)
      diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts
      --- a/apps/server/src/attachmentStore.ts
      +++ b/apps/server/src/attachmentStore.ts
      @@ -13,7 +13,7 @@
       const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
       const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
       
      -function toSafeThreadAttachmentSegment(threadId: string): string | null {
      +export function toSafeThreadAttachmentSegment(threadId: string): string | null {
         const segment = threadId
           .trim()
           .replace(/[^a-z0-9_-]+/gi, "-")
      
      diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
      @@ -37,7 +37,7 @@
         OrchestrationProjectionPipeline,
         type OrchestrationProjectionPipelineShape,
       } from "../Services/ProjectionPipeline.ts";
      -import { attachmentRelativePath } from "../../attachmentStore.ts";
      +import { attachmentRelativePath, toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
       
       export const ORCHESTRATION_PROJECTOR_NAMES = {
         projects: "projection.projects",
      @@ -66,20 +66,6 @@
         readonly prunedThreadRelativePaths: Map<string, Set<string>>;
       }
       
      -function toSafeThreadAttachmentSegment(threadId: string): string | null {
      -  const segment = encodeURIComponent(threadId);
      -  if (
      -    segment.length === 0 ||
      -    segment === "." ||
      -    segment === ".." ||
      -    segment.includes("/") ||
      -    segment.includes("\\") ||
      -    segment.includes("\0")
      -  ) {
      -    return null;
      -  }
      -  return segment;
      -}
       
       const materializeAttachmentsForProjection = Effect.fn(function* (input: {
         readonly attachments: ReadonlyArray<ChatAttachment>;
    6. @@ -0,0 +1,16 @@
      1+import { randomUUID } from "node:crypto";
      2+import { existsSync } from "node:fs";
      3+
      4+import type { ChatAttachment } from "@t3tools/contracts";
      5+
      6+import {
      7+ ATTACHMENTS_ROUTE_PREFIX,
      8+ normalizeAttachmentRelativePath,
      9+ resolveAttachmentRelativePath,
      10+} from "./attachmentPaths.ts";
      11+import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
      12+
      13+const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
      14+const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
      15+
      16+export function toSafeThreadAttachmentSegment(threadId: string): string | null {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/attachmentStore.ts:16

      Thread segment sanitization allows hyphens, causing prefix collisions during cleanup. Thread foo produces segment foo, so .startsWith('foo-') incorrectly matches files from thread foo-bar (segment foo-bar-uuid). Consider replacing hyphens with a different character or using a hash-based approach to ensure unique, non-colliding prefixes.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/attachmentStore.ts around line 16:
      
      Thread segment sanitization allows hyphens, causing prefix collisions during cleanup. Thread `foo` produces segment `foo`, so `.startsWith('foo-')` incorrectly matches files from thread `foo-bar` (segment `foo-bar-uuid`). Consider replacing hyphens with a different character or using a hash-based approach to ensure unique, non-colliding prefixes.
      
      Evidence trail:
      - apps/server/src/attachmentStore.ts lines 16-26: `toSafeThreadAttachmentSegment` regex `/[^a-z0-9_-]+/gi` preserves hyphens
      - apps/server/src/attachmentStore.ts lines 29-34: `createAttachmentId` creates IDs as `${threadSegment}-${randomUUID()}`
      - apps/server/src/orchestration/Layers/ProjectionPipeline.ts lines 201, 239, 275: cleanup uses `.startsWith(`${threadSegment}-`)` for prefix matching
    7. Cursor Bugbot has reviewed your changes and found 2 potential issues.

      Autofix Details

      Bugbot Autofix prepared fixes for both issues found in the latest run.

      • ✅ Fixed: Unused exported functions in new attachment store module
        • Removed the unused attachmentRoutePath function; parseAttachmentIdFromRelativePath was actually used in ProjectionPipeline.ts so it was correctly kept.
      • ✅ Fixed: Unused exported functions in new attachment paths module
        • Removed both unused resolveAttachmentRoutePath and its only consumer attachmentRouteToRelativePath from attachmentPaths.ts.

      Create PR

      Or push these changes by commenting:

      @cursor push 05bb90eef9
      Preview (pingdotgg/t3code@05bb90eef9)
      diff --git a/apps/server/src/attachmentPaths.ts b/apps/server/src/attachmentPaths.ts
      --- a/apps/server/src/attachmentPaths.ts
      +++ b/apps/server/src/attachmentPaths.ts
      @@ -10,14 +10,6 @@
         return normalized.replace(/\\/g, "/");
       }
       
      -export function attachmentRouteToRelativePath(dataUrl: string): string | null {
      -  const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
      -  if (!dataUrl.startsWith(prefix)) {
      -    return null;
      -  }
      -  return normalizeAttachmentRelativePath(dataUrl.slice(prefix.length));
      -}
      -
       export function resolveAttachmentRelativePath(input: {
         readonly stateDir: string;
         readonly relativePath: string;
      @@ -34,17 +26,3 @@
         }
         return filePath;
       }
      -
      -export function resolveAttachmentRoutePath(input: {
      -  readonly stateDir: string;
      -  readonly dataUrl: string;
      -}): string | null {
      -  const relativePath = attachmentRouteToRelativePath(input.dataUrl);
      -  if (!relativePath) {
      -    return null;
      -  }
      -  return resolveAttachmentRelativePath({
      -    stateDir: input.stateDir,
      -    relativePath,
      -  });
      -}
      
      diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts
      --- a/apps/server/src/attachmentStore.ts
      +++ b/apps/server/src/attachmentStore.ts
      @@ -4,7 +4,6 @@
       import type { ChatAttachment } from "@t3tools/contracts";
       
       import {
      -  ATTACHMENTS_ROUTE_PREFIX,
         normalizeAttachmentRelativePath,
         resolveAttachmentRelativePath,
       } from "./attachmentPaths.ts";
      @@ -76,10 +75,6 @@
         });
       }
       
      -export function attachmentRoutePath(attachment: ChatAttachment): string {
      -  return `${ATTACHMENTS_ROUTE_PREFIX}/${encodeURIComponent(attachment.id)}`;
      -}
      -
       export function resolveAttachmentPathById(input: {
         readonly stateDir: string;
         readonly attachmentId: string;
    8. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Case mismatch causes attachment cleanup to silently fail
        • Added .toLowerCase() early in toSafeThreadAttachmentSegment's pipeline and removed the now-unnecessary i regex flag, ensuring it produces the same lowercase segments as parseThreadSegmentFromAttachmentId.

      Create PR

      Or push these changes by commenting:

      @cursor push b3d2f18faf
      Preview (pingdotgg/t3code@b3d2f18faf)
      diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts
      --- a/apps/server/src/attachmentStore.ts
      +++ b/apps/server/src/attachmentStore.ts
      @@ -23,7 +23,8 @@
       export function toSafeThreadAttachmentSegment(threadId: string): string | null {
         const segment = threadId
           .trim()
      -    .replace(/[^a-z0-9_-]+/gi, "-")
      +    .toLowerCase()
      +    .replace(/[^a-z0-9_-]+/g, "-")
           .replace(/-+/g, "-")
           .replace(/^[-_]+|[-_]+$/g, "")
           .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
    9. @@ -230,3 +240,12 @@
      230240 });
      231241 });
      232242
      243+ const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
      244+ readonly command: ClientOrchestrationCommand;
      245+ }) {
      246+ if (input.command.type !== "thread.turn.start") {
      247+ return input.command as OrchestrationCommand;
      248+ }
      249+ const turnStartCommand = input.command;
      250+
      251+ const normalizedAttachments = yield* Effect.forEach(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/wsServer.ts:251

      When attachment processing fails partway through a batch, already-persisted files become orphaned. Consider adding cleanup logic (e.g., track written paths, delete on failure) or using a two-phase approach (validate all first, then persist).

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/wsServer.ts around line 251:
      
      When attachment processing fails partway through a batch, already-persisted files become orphaned. Consider adding cleanup logic (e.g., track written paths, delete on failure) or using a two-phase approach (validate all first, then persist).
      
      Evidence trail:
      apps/server/src/wsServer.ts lines 251-313 (attachment processing loop using Effect.forEach, writes files individually at lines 302-309), lines 608-610 (caller with no cleanup), git_grep for 'cleanup|rollback|delete|unlink|removeFile' in wsServer.ts shows no attachment cleanup logic, git_grep for 'Effect.acquireRelease|Effect.ensuring' shows these patterns ARE used elsewhere in codebase but NOT in the attachment processing code
    10. Cursor Bugbot has reviewed your changes and found 1 potential issue.

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Newly exported functions are never imported anywhere
        • Removed the three unused exported functions (resolveAttachmentRoutePath, attachmentRouteToRelativePath, attachmentRoutePath) and cleaned up the now-unused ATTACHMENTS_ROUTE_PREFIX import in attachmentStore.ts.

      Create PR

      Or push these changes by commenting:

      @cursor push 68241ecf86
      Preview (pingdotgg/t3code@68241ecf86)
      diff --git a/apps/server/src/attachmentPaths.ts b/apps/server/src/attachmentPaths.ts
      --- a/apps/server/src/attachmentPaths.ts
      +++ b/apps/server/src/attachmentPaths.ts
      @@ -10,14 +10,6 @@
         return normalized.replace(/\\/g, "/");
       }
       
      -export function attachmentRouteToRelativePath(dataUrl: string): string | null {
      -  const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
      -  if (!dataUrl.startsWith(prefix)) {
      -    return null;
      -  }
      -  return normalizeAttachmentRelativePath(dataUrl.slice(prefix.length));
      -}
      -
       export function resolveAttachmentRelativePath(input: {
         readonly stateDir: string;
         readonly relativePath: string;
      @@ -34,17 +26,3 @@
         }
         return filePath;
       }
      -
      -export function resolveAttachmentRoutePath(input: {
      -  readonly stateDir: string;
      -  readonly dataUrl: string;
      -}): string | null {
      -  const relativePath = attachmentRouteToRelativePath(input.dataUrl);
      -  if (!relativePath) {
      -    return null;
      -  }
      -  return resolveAttachmentRelativePath({
      -    stateDir: input.stateDir,
      -    relativePath,
      -  });
      -}
      
      diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts
      --- a/apps/server/src/attachmentStore.ts
      +++ b/apps/server/src/attachmentStore.ts
      @@ -4,7 +4,6 @@
       import type { ChatAttachment } from "@t3tools/contracts";
       
       import {
      -  ATTACHMENTS_ROUTE_PREFIX,
         normalizeAttachmentRelativePath,
         resolveAttachmentRelativePath,
       } from "./attachmentPaths.ts";
      @@ -77,10 +76,6 @@
         });
       }
       
      -export function attachmentRoutePath(attachment: ChatAttachment): string {
      -  return `${ATTACHMENTS_ROUTE_PREFIX}/${encodeURIComponent(attachment.id)}`;
      -}
      -
       export function resolveAttachmentPathById(input: {
         readonly stateDir: string;
         readonly attachmentId: string;
    11. juliusmarminge merged thisa356cd0

    12. juliusmarminge closed this

Sign in to join this conversation.