Add AI-generated worktree branch naming with safe Git branch rename flow #129
Mergedjuliusmarmingemerged 22 commits into
main fromcodething/34345440merged by juliusmarminge View on GitHub- apps/server/src/git/Layers/GitCore.ts line 761OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -711,3 +748,14 @@711748 );712749 });713750751+ const renameBranch: GitCoreShape["renameBranch"] = (input) =>752+ Effect.gen(function* () {753+ if (input.oldBranch === input.newBranch) {754+ return { branch: input.newBranch };755+ }756+ const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);757+758+ yield* executeGit(759+ "GitCore.renameBranch",760+ input.cwd,761+ ["branch", "-m", input.oldBranch, targetBranch],apps/server/src/git/Layers/CodexTextGeneration.ts line 269OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -173,0 +249,21 @@249+ const imagePaths: string[] = [];250+ for (const [index, attachment] of attachments.entries()) {251+ if (attachment.type !== "image") {252+ continue;253+ }254+255+ const parsed = parseBase64DataUrl(attachment.dataUrl);256+ if (!parsed || !parsed.mimeType.startsWith("image/")) {257+ continue;258+ }259+260+ const bytes = Buffer.from(parsed.base64, "base64");261+ if (bytes.byteLength === 0) {262+ continue;263+ }264+265+ const extension = inferImageExtension({266+ mimeType: parsed.mimeType,267+ fileName: attachment.name,268+ });269+ const imagePath = yield* writeTempBinaryFile(
- apps/server/src/wsServer.ts line 162OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -137,0 +142,21 @@142+ const normalized = raw143+ .trim()144+ .toLowerCase()145+ .replace(/^refs\/heads\//, "")146+ .replace(/['"`]/g, "");147+148+ const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)149+ ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)150+ : normalized;151+152+ const branchFragment = withoutPrefix153+ .replace(/[^a-z0-9/_-]+/g, "-")154+ .replace(/\/+/g, "/")155+ .replace(/-+/g, "-")156+ .replace(/^[./_-]+|[./_-]+$/g, "")157+ .slice(0, 64)158+ .replace(/[./_-]+$/g, "");159+160+ const safeFragment = branchFragment.length > 0 ? branchFragment : "update";161+ return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;162+}apps/web/src/components/ChatView.tsx line 1688OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1598,3 +1683,6 @@15981683 sandboxMode,15991684 createdAt: messageCreatedAt,16001685 });1686+ if (pendingWorktreeBranchRename) {1687+ void pendingWorktreeBranchRename;1688+ }apps/web/src/components/ChatView.tsx line 243OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -232,3 +233,11 @@232233 });233234 }234235236+function hashBranchSeed(value: string): string {237+ let hash = 2166136261;238+ for (let index = 0; index < value.length; index++) {239+ hash ^= value.charCodeAt(index);240+ hash = Math.imul(hash, 16777619);241+ }242+ return (hash >>> 0).toString(16).padStart(8, "0");243+}
- @@ -68,0 +75,21 @@75+ return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());76+}77+78+function buildGeneratedWorktreeBranchName(raw: string): string {79+ const normalized = raw80+ .trim()81+ .toLowerCase()82+ .replace(/^refs\/heads\//, "")83+ .replace(/['"`]/g, "");84+85+ const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)86+ ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)87+ : normalized;88+89+ const branchFragment = withoutPrefix90+ .replace(/[^a-z0-9/_-]+/g, "-")91+ .replace(/\/+/g, "/")92+ .replace(/-+/g, "-")93+ .replace(/^[./_-]+|[./_-]+$/g, "")94+ .slice(0, 64)95+ .replace(/[./_-]+$/g, "");@@ -1,3 +1,4 @@11 import fs from "node:fs";22 import http from "node:http";33 import path from "node:path";4+export { IMAGE_EXTENSION_BY_MIME_TYPE, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
- apps/server/src/imageMime.ts lines 35 to 35OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+};16+17+export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([18+ ".avif",19+ ".bmp",20+ ".gif",21+ ".heic",22+ ".heif",23+ ".ico",24+ ".jpeg",25+ ".jpg",26+ ".png",27+ ".svg",28+ ".tiff",29+ ".webp",30+]);31+32+export function parseBase64DataUrl(33+ dataUrl: string,34+): { readonly mimeType: string; readonly base64: string } | null {35+ const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());apps/server/src/git/Layers/CodexTextGeneration.ts line 388OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -254,6 +384,5 @@254384 }255385 });256386257- const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {258- concurrency: "unbounded",259- }).pipe(Effect.asVoid);387+ const cleanup = Effect.all(388+ [schemaPath, outputPath, ...imagePaths].map((filePath) => safeUnlink(filePath)),
- apps/server/src/orchestration/Layers/ProviderCommandReactor.ts line 339OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -249,0 +319,21 @@319+ resolvedRoutePath ??320+ (() => {321+ const parsed = parseBase64DataUrl(attachment.dataUrl);322+ if (!parsed || !parsed.mimeType.startsWith("image/")) {323+ return null;324+ }325+ const extension = inferImageExtension({326+ mimeType: parsed.mimeType,327+ fileName: attachment.name,328+ });329+ return resolveAttachmentRelativePath({330+ stateDir: serverConfig.value.stateDir,331+ relativePath: `${threadSegment}/${messageSegment}-${index}${extension}`,332+ });333+ })();334+335+ if (!resolvedMaterializedPath) {336+ return attachment;337+ }338+339+ const isFile = yield* Effect.sync(() => {
- @@ -254,6 +384,9 @@254384 }255385 });256386257- const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {258- concurrency: "unbounded",259- }).pipe(Effect.asVoid);387+ const cleanup = Effect.all(388+ [schemaPath, outputPath, ...imagePaths].map((filePath) => safeUnlink(filePath)),389+ {390+ concurrency: "unbounded",391+ },392+ ).pipe(Effect.asVoid);
- apps/server/src/git/Layers/CodexTextGeneration.ts line 212OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -174,0 +192,21 @@192+ if (parsed && parsed.mimeType.startsWith("image/")) {193+ const bytes = Buffer.from(parsed.base64, "base64");194+ if (bytes.byteLength === 0) {195+ continue;196+ }197+198+ const extension = inferImageExtension({199+ mimeType: parsed.mimeType,200+ fileName: attachment.name,201+ });202+ const imagePath = yield* writeTempBinaryFile(203+ operation,204+ `codex-image-${index}`,205+ bytes,206+ extension,207+ );208+ imagePaths.push(imagePath);209+ continue;210+ }211+212+ const persistedPath = Option.isSome(serverConfig)
- apps/server/src/imageMime.ts lines 35 to 35OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+};16+17+export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([18+ ".avif",19+ ".bmp",20+ ".gif",21+ ".heic",22+ ".heif",23+ ".ico",24+ ".jpeg",25+ ".jpg",26+ ".png",27+ ".svg",28+ ".tiff",29+ ".webp",30+]);31+32+export function parseBase64DataUrl(33+ dataUrl: string,34+): { readonly mimeType: string; readonly base64: string } | null {35+ const match = /^data:([^,]+),([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());apps/server/src/imageMime.ts lines 58 to 59OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+ .split(";")40+ .map((part) => part.trim())41+ .filter((part) => part.length > 0);42+ if (headerParts.length < 2) {43+ return null;44+ }45+ const trailingToken = headerParts.at(-1)?.toLowerCase();46+ if (trailingToken !== "base64") {47+ return null;48+ }49+50+ const mimeType = headerParts[0]?.toLowerCase();51+ const base64 = match[2]?.replace(/\s+/g, "");52+ if (!mimeType || !base64) return null;53+54+ return { mimeType, base64 };55+}56+57+export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {58+ const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[input.mimeType.toLowerCase()];59+ if (fromMime) {
- @@ -56,3 +56,3 @@5656 }57575858 export function makeServerRuntimeServicesLayer() {
- apps/server/src/git/Layers/CodexTextGeneration.ts line 176Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -174,0 +206,21 @@206+ mimeType: parsed.mimeType,207+ fileName: attachment.name,208+ });209+ const imagePath = yield* writeTempBinaryFile(210+ operation,211+ `codex-image-${index}`,212+ bytes,213+ extension,214+ );215+ imagePaths.push(imagePath);216+ tempImagePaths.push(imagePath);217+ continue;218+ }219+220+ const persistedPath = resolveAttachmentRoutePath({221+ stateDir: serverConfig.stateDir,222+ dataUrl: attachment.dataUrl,223+ });224+ if (!persistedPath || !path.isAbsolute(persistedPath)) {225+ continue;226+ }
- apps/server/src/attachmentStore.ts line 76OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ });57+}58+59+export function attachmentRoutePath(attachment: ChatAttachment): string {60+ return `${ATTACHMENTS_ROUTE_PREFIX}/${encodeURIComponent(attachment.id)}`;61+}62+63+export function resolveAttachmentPathById(input: {64+ readonly stateDir: string;65+ readonly attachmentId: string;66+}): string | null {67+ const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);68+ if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {69+ return null;70+ }71+ for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {72+ const maybePath = resolveAttachmentRelativePath({73+ stateDir: input.stateDir,74+ relativePath: `${normalizedId}${extension}`,75+ });76+ if (maybePath) {apps/server/src/attachmentStore.ts line 84Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+49+export function resolveAttachmentPath(input: {50+ readonly stateDir: string;51+ readonly attachment: ChatAttachment;52+}): string | null {53+ return resolveAttachmentRelativePath({54+ stateDir: input.stateDir,55+ relativePath: attachmentRelativePath(input.attachment),56+ });57+}58+59+export function attachmentRoutePath(attachment: ChatAttachment): string {60+ return `${ATTACHMENTS_ROUTE_PREFIX}/${encodeURIComponent(attachment.id)}`;61+}62+63+export function resolveAttachmentPathById(input: {64+ readonly stateDir: string;65+ readonly attachmentId: string;66+}): string | null {67+ const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);68+ if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {apps/server/src/provider/Layers/CodexAdapter.ts lines 492 to 496OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -475,6 +479,18 @@475479 };476480477481 const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>478- Effect.tryPromise({479- try: () => manager.sendTurn(input),480- catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),482+ Effect.gen(function* () {483+ const codexAttachments = yield* Effect.forEach(484+ input.attachments ?? [],485+ (attachment) =>486+ Effect.gen(function* () {487+ const attachmentPath = resolveAttachmentPath({488+ stateDir: serverConfig.stateDir,489+ attachment,490+ });491+ if (!attachmentPath) {492+ return yield* toRequestError(493+ input.sessionId,494+ "turn/start",495+ new Error(`Invalid attachment id '${attachment.id}'.`),496+ );
- @@ -0,0 +61,21 @@61+}62+63+export function resolveAttachmentPathById(input: {64+ readonly stateDir: string;65+ readonly attachmentId: string;66+}): string | null {67+ const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);68+ if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {69+ return null;70+ }71+ for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {72+ const maybePath = resolveAttachmentRelativePath({73+ stateDir: input.stateDir,74+ relativePath: `${normalizedId}${extension}`,75+ });76+ if (maybePath) {77+ return maybePath;78+ }79+ }80+ return null;81+}@@ -725,8 +782,6 @@725782 });726783727784 // Refresh upstream refs in the background so checkout remains responsive.728- yield* Effect.sync(() => {729- void Effect.runPromise(730- refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),731- );732- });785+ yield* Effect.forkScoped(786+ refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),787+ );
- apps/server/src/orchestration/Layers/ProjectionPipeline.ts line 210Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -308,19 +208,13 @@308208 if (!threadSegment) {309209 return new Set();310210 }311- const threadPrefix = `${threadSegment}/`;312211 const relativePaths = new Set<string>();313212 for (const message of messages) {314213 for (const attachment of message.attachments ?? []) {315214 if (attachment.type !== "image") {316215 continue;317216 }318- const relativePath = toAttachmentRelativePath(attachment.dataUrl);319- if (!relativePath || !relativePath.startsWith(threadPrefix)) {217+ if (!attachment.id.startsWith(`${threadSegment}-`)) {320218 continue;321219 }322- const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");323- if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {324- continue;325- }326- relativePaths.add(threadRelativePath.replace(/\\/g, "/"));220+ relativePaths.add(attachmentRelativePath(attachment));
- @@ -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 {
- apps/server/src/attachmentStore.ts line 62OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +42,21 @@42+ mimeType: attachment.mimeType,43+ fileName: attachment.name,44+ });45+ return `${attachment.id}${extension}`;46+ }47+ }48+}49+50+export function resolveAttachmentPath(input: {51+ readonly stateDir: string;52+ readonly attachment: ChatAttachment;53+}): string | null {54+ return resolveAttachmentRelativePath({55+ stateDir: input.stateDir,56+ relativePath: attachmentRelativePath(input.attachment),57+ });58+}59+60+export function attachmentRoutePath(attachment: ChatAttachment): string {61+ return `${ATTACHMENTS_ROUTE_PREFIX}/${encodeURIComponent(attachment.id)}`;62+}apps/server/src/attachmentPaths.ts line 50OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+ const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));31+ const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));32+ if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {33+ return null;34+ }35+ return filePath;36+}37+38+export function resolveAttachmentRoutePath(input: {39+ readonly stateDir: string;40+ readonly dataUrl: string;41+}): string | null {42+ const relativePath = attachmentRouteToRelativePath(input.dataUrl);43+ if (!relativePath) {44+ return null;45+ }46+ return resolveAttachmentRelativePath({47+ stateDir: input.stateDir,48+ relativePath,49+ });50+}
- apps/server/src/attachmentStore.ts line 35Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";16+const ATTACHMENT_ID_UUID_PATTERN =17+ "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";18+const ATTACHMENT_ID_PATTERN = new RegExp(19+ `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,20+ "i",21+);22+23+export function toSafeThreadAttachmentSegment(threadId: string): string | null {24+ const segment = threadId25+ .trim()26+ .replace(/[^a-z0-9_-]+/gi, "-")27+ .replace(/-+/g, "-")28+ .replace(/^[-_]+|[-_]+$/g, "")29+ .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)30+ .replace(/[-_]+$/g, "");31+ if (segment.length === 0) {32+ return null;33+ }34+ return segment;35+}
- @@ -230,3 +240,12 @@230240 });231241 });232242243+ 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(
- apps/server/src/attachmentPaths.ts line 50OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+ const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));31+ const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));32+ if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {33+ return null;34+ }35+ return filePath;36+}37+38+export function resolveAttachmentRoutePath(input: {39+ readonly stateDir: string;40+ readonly dataUrl: string;41+}): string | null {42+ const relativePath = attachmentRouteToRelativePath(input.dataUrl);43+ if (!relativePath) {44+ return null;45+ }46+ return resolveAttachmentRelativePath({47+ stateDir: input.stateDir,48+ relativePath,49+ });50+}
juliusmarminge merged thisa356cd0
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.