Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Allow empty server threads to bootstrap new worktrees (#1936)
Julius Marminge801b83e9372c
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex a1a69f0ef..a61bd0327 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -11,6 +11,7 @@ import {type RuntimeMode,type TurnId,} from "@t3tools/contracts";+import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";@@ -72,8 +73,6 @@ const serverCommandId = (tag: string): CommandId =>const HANDLED_TURN_START_KEY_MAX = 10_000;const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";-const WORKTREE_BRANCH_PREFIX = "t3code";-const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);const DEFAULT_THREAD_TITLE = "New thread";function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {@@ -119,10 +118,6 @@ function stalePendingRequestDetail(return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;}-function isTemporaryWorktreeBranch(branch: string): boolean {- return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());-}-function buildGeneratedWorktreeBranchName(raw: string): string {const normalized = raw.trim()diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.tsindex faf21d636..7beaec808 100644--- a/apps/web/src/components/BranchToolbar.logic.test.ts+++ b/apps/web/src/components/BranchToolbar.logic.test.ts@@ -10,6 +10,7 @@ import {resolveEffectiveEnvMode,resolveEnvModeLabel,resolveBranchToolbarValue,+ resolveLockedWorkspaceLabel,shouldIncludeBranchPickerItem,} from "./BranchToolbar.logic";@@ -157,6 +158,16 @@ describe("resolveCurrentWorkspaceLabel", () => {});});+describe("resolveLockedWorkspaceLabel", () => {+ it("uses a shorter label for the main repo checkout", () => {+ expect(resolveLockedWorkspaceLabel(null)).toBe("Local checkout");+ });++ it("uses a shorter label for an attached worktree", () => {+ expect(resolveLockedWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Worktree");+ });+});+describe("deriveLocalBranchNameFromRemoteRef", () => {it("strips the remote prefix from a remote ref", () => {expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.tsindex 54ec4370f..7adab1a2e 100644--- a/apps/web/src/components/BranchToolbar.logic.ts+++ b/apps/web/src/components/BranchToolbar.logic.ts@@ -50,6 +50,10 @@ export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null):return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");}+export function resolveLockedWorkspaceLabel(activeWorktreePath: string | null): string {+ return activeWorktreePath ? "Worktree" : "Local checkout";+}+export function resolveEffectiveEnvMode(input: {activeWorktreePath: string | null;hasServerThread: boolean;diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsxindex e91266d65..c6f37c42a 100644--- a/apps/web/src/components/BranchToolbar.tsx+++ b/apps/web/src/components/BranchToolbar.tsx@@ -20,6 +20,9 @@ interface BranchToolbarProps {threadId: ThreadId;draftId?: DraftId;onEnvModeChange: (mode: EnvMode) => void;+ effectiveEnvModeOverride?: EnvMode;+ activeThreadBranchOverride?: string | null;+ onActiveThreadBranchOverrideChange?: (branch: string | null) => void;envLocked: boolean;onCheckoutPullRequestRequest?: (reference: string) => void;onComposerFocusRequest?: () => void;@@ -32,6 +35,9 @@ export const BranchToolbar = memo(function BranchToolbar({threadId,draftId,onEnvModeChange,+ effectiveEnvModeOverride,+ activeThreadBranchOverride,+ onActiveThreadBranchOverrideChange,envLocked,onCheckoutPullRequestRequest,onComposerFocusRequest,@@ -59,11 +65,13 @@ export const BranchToolbar = memo(function BranchToolbar({const activeProject = useStore(activeProjectSelector);const hasActiveThread = serverThread !== undefined || draftThread !== null;const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;- const effectiveEnvMode = resolveEffectiveEnvMode({- activeWorktreePath,- hasServerThread: serverThread !== undefined,- draftThreadEnvMode: draftThread?.envMode,- });+ const effectiveEnvMode =+ effectiveEnvModeOverride ??+ resolveEffectiveEnvMode({+ activeWorktreePath,+ hasServerThread: serverThread !== undefined,+ draftThreadEnvMode: draftThread?.envMode,+ });const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);const showEnvironmentPicker =@@ -98,6 +106,9 @@ export const BranchToolbar = memo(function BranchToolbar({threadId={threadId}{...(draftId ? { draftId } : {})}envLocked={envLocked}+ {...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}+ {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}+ {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}/>diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsxindex 5d5a7b34e..996fca4b3 100644--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx@@ -49,6 +49,9 @@ interface BranchToolbarBranchSelectorProps {threadId: ThreadId;draftId?: DraftId;envLocked: boolean;+ effectiveEnvModeOverride?: "local" | "worktree";+ activeThreadBranchOverride?: string | null;+ onActiveThreadBranchOverrideChange?: (branch: string | null) => void;onCheckoutPullRequestRequest?: (reference: string) => void;onComposerFocusRequest?: () => void;}@@ -77,6 +80,9 @@ export function BranchToolbarBranchSelector({threadId,draftId,envLocked,+ effectiveEnvModeOverride,+ activeThreadBranchOverride,+ onActiveThreadBranchOverrideChange,onCheckoutPullRequestRequest,onComposerFocusRequest,}: BranchToolbarBranchSelectorProps) {@@ -108,16 +114,21 @@ export function BranchToolbarBranchSelector({const activeProject = useStore(activeProjectSelector);const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);- const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;+ const activeThreadBranch =+ activeThreadBranchOverride !== undefined+ ? activeThreadBranchOverride+ : (serverThread?.branch ?? draftThread?.branch ?? null);const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;const activeProjectCwd = activeProject?.cwd ?? null;const branchCwd = activeWorktreePath ?? activeProjectCwd;const hasServerThread = serverThread !== undefined;- const effectiveEnvMode = resolveEffectiveEnvMode({- activeWorktreePath,- hasServerThread,- draftThreadEnvMode: draftThread?.envMode,- });+ const effectiveEnvMode =+ effectiveEnvModeOverride ??+ resolveEffectiveEnvMode({+ activeWorktreePath,+ hasServerThread,+ draftThreadEnvMode: draftThread?.envMode,+ });// ---------------------------------------------------------------------------// Thread branch mutation (colocated — only this component calls it)@@ -146,6 +157,7 @@ export function BranchToolbarBranchSelector({});}if (hasServerThread) {+ onActiveThreadBranchOverrideChange?.(branch);setThreadBranchAction(threadRef, branch, worktreePath);return;}@@ -167,6 +179,7 @@ export function BranchToolbarBranchSelector({serverSession,activeWorktreePath,hasServerThread,+ onActiveThreadBranchOverrideChange,setThreadBranchAction,setDraftThreadContext,draftId,diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsxindex 39bf50359..6e1c80f55 100644--- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx+++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx@@ -4,6 +4,7 @@ import { memo, useMemo } from "react";import {resolveCurrentWorkspaceLabel,resolveEnvModeLabel,+ resolveLockedWorkspaceLabel,type EnvMode,} from "./BranchToolbar.logic";import {@@ -43,12 +44,12 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe{activeWorktreePath ? (<><FolderGitIcon className="size-3" />- {resolveCurrentWorkspaceLabel(activeWorktreePath)}+ {resolveLockedWorkspaceLabel(activeWorktreePath)}</>) : (<><FolderIcon className="size-3" />- {resolveCurrentWorkspaceLabel(activeWorktreePath)}+ {resolveLockedWorkspaceLabel(activeWorktreePath)}</>)}</span>diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsxindex 0b49f1d7d..1a398f12d 100644--- a/apps/web/src/components/ChatView.browser.tsx+++ b/apps/web/src/components/ChatView.browser.tsx@@ -2286,6 +2286,287 @@ describe("ChatView timeline estimator parity (full app)", () => {}});+ it("keeps new-worktree mode on empty server threads and bootstraps the first send", async () => {+ const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);+ const mounted = await mountChatView({+ viewport: DEFAULT_VIEWPORT,+ snapshot: {+ ...snapshot,+ threads: snapshot.threads.map((thread) =>+ thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,+ ),+ },+ resolveRpc: (body) => {+ if (body._tag === WS_METHODS.gitListBranches) {+ return {+ isRepo: true,+ hasOriginRemote: true,+ nextCursor: null,+ totalCount: 1,+ branches: [+ {+ name: "main",+ current: true,+ isDefault: true,+ worktreePath: null,+ },+ ],+ };+ }+ if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {+ return {+ sequence: fixture.snapshot.snapshotSequence + 1,+ };+ }+ return undefined;+ },+ });++ try {+ (await waitForButtonByText("Current checkout")).click();+ await page.getByText("New worktree", { exact: true }).click();++ await vi.waitFor(+ () => {+ expect(findButtonByText("New worktree")).toBeTruthy();+ },+ { timeout: 8_000, interval: 16 },+ );++ useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");+ await waitForLayout();++ const sendButton = await waitForSendButton();+ expect(sendButton.disabled).toBe(false);+ sendButton.click();++ await vi.waitFor(+ () => {+ const turnStartRequest = wsRequests.find(+ (request) =>+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&+ request.type === "thread.turn.start",+ ) as+ | {+ _tag: string;+ type?: string;+ bootstrap?: {+ createThread?: { projectId?: string };+ prepareWorktree?: { projectCwd?: string; baseBranch?: string; branch?: string };+ runSetupScript?: boolean;+ };+ }+ | undefined;++ expect(turnStartRequest).toMatchObject({+ _tag: ORCHESTRATION_WS_METHODS.dispatchCommand,+ type: "thread.turn.start",+ bootstrap: {+ prepareWorktree: {+ projectCwd: "/repo/project",+ baseBranch: "main",+ branch: expect.stringMatching(/^t3code\/[0-9a-f]{8}$/),+ },+ runSetupScript: true,+ },+ });+ expect(turnStartRequest?.bootstrap?.createThread).toBeUndefined();+ },+ { timeout: 8_000, interval: 16 },+ );+ } finally {+ await mounted.cleanup();+ }+ });++ it("updates the selected worktree base branch on empty server threads", async () => {+ const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);+ const mounted = await mountChatView({+ viewport: DEFAULT_VIEWPORT,+ snapshot: {+ ...snapshot,+ threads: snapshot.threads.map((thread) =>+ thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,+ ),+ },+ resolveRpc: (body) => {+ if (body._tag === WS_METHODS.gitListBranches) {+ return {+ isRepo: true,+ hasOriginRemote: true,+ nextCursor: null,+ totalCount: 2,+ branches: [+ {+ name: "main",+ current: true,+ isDefault: true,+ worktreePath: null,+ },+ {+ name: "release/next",+ current: false,+ isDefault: false,+ worktreePath: null,+ },+ ],+ };+ }+ if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {+ return {+ sequence: fixture.snapshot.snapshotSequence + 1,+ };+ }+ return undefined;+ },+ });++ try {+ (await waitForButtonByText("Current checkout")).click();+ await page.getByText("New worktree", { exact: true }).click();+ await page.getByText("From main", { exact: true }).click();+ await page.getByText("release/next", { exact: true }).click();++ await vi.waitFor(+ () => {+ expect(findButtonByText("From release/next")).toBeTruthy();+ },+ { timeout: 8_000, interval: 16 },+ );++ useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");+ await waitForLayout();++ const sendButton = await waitForSendButton();+ expect(sendButton.disabled).toBe(false);+ sendButton.click();++ await vi.waitFor(+ () => {+ const turnStartRequest = wsRequests.find(+ (request) =>+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&+ request.type === "thread.turn.start",+ ) as+ | {+ _tag: string;+ type?: string;+ bootstrap?: {+ prepareWorktree?: { baseBranch?: string };+ };+ }+ | undefined;++ expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("release/next");+ },+ { timeout: 8_000, interval: 16 },+ );+ } finally {+ await mounted.cleanup();+ }+ });++ it("clears pending worktree overrides when switching empty server threads", async () => {+ const secondThreadId = "thread-browser-test-second" as ThreadId;+ const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);+ const snapshotWithSecondThread = addThreadToSnapshot(snapshot, secondThreadId);+ const snapshotWithTwoThreads = {+ ...snapshotWithSecondThread,+ threads: snapshotWithSecondThread.threads.map((thread) => {+ if (thread.id === THREAD_ID) {+ return Object.assign({}, thread, { session: null, title: "Thread alpha" });+ }+ if (thread.id === secondThreadId) {+ return Object.assign({}, thread, { session: null, title: "Thread beta" });+ }+ return thread;+ }),+ };+ const mounted = await mountChatView({+ viewport: DEFAULT_VIEWPORT,+ snapshot: snapshotWithTwoThreads,+ resolveRpc: (body) => {+ if (body._tag === WS_METHODS.gitListBranches) {+ return {+ isRepo: true,+ hasOriginRemote: true,+ nextCursor: null,+ totalCount: 2,+ branches: [+ {+ name: "main",+ current: true,+ isDefault: true,+ worktreePath: null,+ },+ {+ name: "release/next",+ current: false,+ isDefault: false,+ worktreePath: null,+ },+ ],+ };+ }+ if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {+ return {+ sequence: fixture.snapshot.snapshotSequence + 1,+ };+ }+ return undefined;+ },+ });++ try {+ (await waitForButtonByText("Current checkout")).click();+ await page.getByText("New worktree", { exact: true }).click();+ await page.getByText("From main", { exact: true }).click();+ await page.getByText("release/next", { exact: true }).click();++ await vi.waitFor(+ () => {+ expect(findButtonByText("From release/next")).toBeTruthy();+ },+ { timeout: 8_000, interval: 16 },+ );++ await mounted.router.navigate({+ to: "/$environmentId/$threadId",+ params: {+ environmentId: LOCAL_ENVIRONMENT_ID,+ threadId: secondThreadId,+ },+ });++ await waitForURL(+ mounted.router,+ (path) => path === serverThreadPath(secondThreadId),+ "Route should switch to the second empty server thread.",+ );++ await vi.waitFor(+ () => {+ expect(findButtonByText("Current checkout")).toBeTruthy();+ expect(findButtonByText("From release/next")).toBeNull();+ },+ { timeout: 8_000, interval: 16 },+ );++ (await waitForButtonByText("Current checkout")).click();+ await page.getByText("New worktree", { exact: true }).click();++ await vi.waitFor(+ () => {+ expect(findButtonByText("From main")).toBeTruthy();+ expect(findButtonByText("From release/next")).toBeNull();+ },+ { timeout: 8_000, interval: 16 },+ );+ } finally {+ await mounted.cleanup();+ }+ });+it("shows the send state once bootstrap dispatch is in flight", async () => {useTerminalStateStore.setState({terminalStateByThreadKey: {},diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 37bf41b5b..ba0a0eddf 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -11,6 +11,7 @@ import {deriveComposerSendState,hasServerAcknowledgedLocalDispatch,reconcileMountedTerminalThreadIds,+ resolveSendEnvMode,shouldWriteThreadErrorToCurrentServerThread,waitForStartedServerThread,} from "./ChatView.logic";@@ -82,6 +83,17 @@ describe("buildExpiredTerminalContextToastCopy", () => {});});+describe("resolveSendEnvMode", () => {+ it("keeps worktree mode for git repositories", () => {+ expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");+ });++ it("forces local mode for non-git repositories", () => {+ expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: false })).toBe("local");+ expect(resolveSendEnvMode({ requestedEnvMode: "local", isGitRepo: false })).toBe("local");+ });+});+describe("reconcileMountedTerminalThreadIds", () => {it("keeps previously mounted open threads and adds the active open thread", () => {expect(diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 510fef6d3..b77cc7b17 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -8,7 +8,6 @@ import {type TurnId,} from "@t3tools/contracts";import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";-import { randomUUID } from "~/lib/utils";import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";import { Schema } from "effect";import { selectThreadByRef, useStore } from "../store";@@ -17,10 +16,10 @@ import {stripInlineTerminalContextPlaceholders,type TerminalContextDraft,} from "../lib/terminalContext";+import type { DraftThreadEnvMode } from "../composerDraftStore";export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10;-const WORKTREE_BRANCH_PREFIX = "t3code";export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);@@ -157,10 +156,11 @@ export function readFileAsDataUrl(file: File): Promise<string> {});}-export function buildTemporaryWorktreeBranchName(): string {- // Keep the 8-hex suffix shape for backend temporary-branch detection.- const token = randomUUID().slice(0, 8).toLowerCase();- return `${WORKTREE_BRANCH_PREFIX}/${token}`;+export function resolveSendEnvMode(input: {+ requestedEnvMode: DraftThreadEnvMode;+ isGitRepo: boolean;+}): DraftThreadEnvMode {+ return input.isGitRepo ? input.requestedEnvMode : "local";}export function cloneComposerImageForRetry(diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 0bb0e408b..0a87589a1 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -91,6 +91,7 @@ import {import { useTheme } from "../hooks/useTheme";import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";import { useCommandPaletteStore } from "../commandPaletteStore";+import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";import { BranchToolbar } from "./BranchToolbar";import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";import PlanSidebar from "./PlanSidebar";@@ -143,7 +144,6 @@ import {MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,buildExpiredTerminalContextToastCopy,buildLocalDraftThread,- buildTemporaryWorktreeBranchName,collectUserMessageBlobPreviewUrls,createLocalDispatchSnapshot,deriveComposerSendState,@@ -156,6 +156,7 @@ import {deriveLockedProvider,readFileAsDataUrl,reconcileMountedTerminalThreadIds,+ resolveSendEnvMode,revokeBlobPreviewUrl,revokeUserMessagePreviewUrls,shouldWriteThreadErrorToCurrentServerThread,@@ -688,6 +689,9 @@ export default function ChatView(props: ChatViewProps) {const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<Record<string, string[]>>({});+ const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =+ useState<DraftThreadEnvMode | null>(null);+ const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,{},@@ -2043,11 +2047,42 @@ export default function ChatView(props: ChatViewProps) {}, []);const activeWorktreePath = activeThread?.worktreePath ?? null;- const envMode: DraftThreadEnvMode = resolveEffectiveEnvMode({+ const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({activeWorktreePath,hasServerThread: isServerThread,draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined,});+ const canOverrideServerThreadEnvMode = Boolean(+ isServerThread &&+ activeThread &&+ activeThread.messages.length === 0 &&+ activeThread.worktreePath === null &&+ !envLocked,+ );+ const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode+ ? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)+ : derivedEnvMode;+ const activeThreadBranch =+ canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined+ ? pendingServerThreadBranch+ : (activeThread?.branch ?? null);+ const sendEnvMode = resolveSendEnvMode({+ requestedEnvMode: envMode,+ isGitRepo,+ });++ useEffect(() => {+ setPendingServerThreadEnvMode(null);+ setPendingServerThreadBranch(undefined);+ }, [activeThread?.id]);++ useEffect(() => {+ if (canOverrideServerThreadEnvMode) {+ return;+ }+ setPendingServerThreadEnvMode(null);+ setPendingServerThreadBranch(undefined);+ }, [canOverrideServerThreadEnvMode]);useEffect(() => {if (!activeThreadId) {@@ -2360,15 +2395,15 @@ export default function ChatView(props: ChatViewProps) {const threadIdForSend = activeThread.id;const isFirstMessage = !isServerThread || activeThread.messages.length === 0;const baseBranchForWorktree =- isFirstMessage && envMode === "worktree" && !activeThread.worktreePath- ? activeThread.branch+ isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath+ ? activeThreadBranch: null;// In worktree mode, require an explicit base branch so we don't silently// fall back to local execution when branch selection is missing.const shouldCreateWorktree =- isFirstMessage && envMode === "worktree" && !activeThread.worktreePath;- if (shouldCreateWorktree && !activeThread.branch) {+ isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath;+ if (shouldCreateWorktree && !activeThreadBranch) {setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");return;}@@ -2507,7 +2542,7 @@ export default function ChatView(props: ChatViewProps) {modelSelection: threadCreateModelSelection,runtimeMode,interactionMode,- branch: activeThread.branch,+ branch: activeThreadBranch,worktreePath: activeThread.worktreePath,createdAt: activeThread.createdAt,},@@ -2959,7 +2994,7 @@ export default function ChatView(props: ChatViewProps) {modelSelection: nextThreadModelSelection,runtimeMode,interactionMode: "default",- branch: activeThread.branch,+ branch: activeThreadBranch,worktreePath: activeThread.worktreePath,createdAt,})@@ -3018,6 +3053,7 @@ export default function ChatView(props: ChatViewProps) {}, [activeProject,activeProposedPlan,+ activeThreadBranch,activeThread,beginLocalDispatch,isConnecting,@@ -3066,6 +3102,11 @@ export default function ChatView(props: ChatViewProps) {);const onEnvModeChange = useCallback((mode: DraftThreadEnvMode) => {+ if (canOverrideServerThreadEnvMode) {+ setPendingServerThreadEnvMode(mode);+ scheduleComposerFocus();+ return;+ }if (isLocalDraftThread) {setDraftThreadContext(composerDraftTarget, {envMode: mode,@@ -3075,9 +3116,11 @@ export default function ChatView(props: ChatViewProps) {scheduleComposerFocus();},[+ canOverrideServerThreadEnvMode,composerDraftTarget,draftThread?.worktreePath,isLocalDraftThread,+ setPendingServerThreadEnvMode,scheduleComposerFocus,setDraftThreadContext,],@@ -3300,6 +3343,13 @@ export default function ChatView(props: ChatViewProps) {threadId={activeThread.id}{...(routeKind === "draft" && draftId ? { draftId } : {})}onEnvModeChange={onEnvModeChange}+ {...(canOverrideServerThreadEnvMode ? { effectiveEnvModeOverride: envMode } : {})}+ {...(canOverrideServerThreadEnvMode+ ? {+ activeThreadBranchOverride: activeThreadBranch,+ onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,+ }+ : {})}envLocked={envLocked}onComposerFocusRequest={scheduleComposerFocus}{...(canCheckoutPullRequestIntoThreaddiff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.tsindex dac644e83..ba3af6c77 100644--- a/packages/shared/src/git.test.ts+++ b/packages/shared/src/git.test.ts@@ -3,8 +3,11 @@ import { describe, expect, it } from "vitest";import {applyGitStatusStreamEvent,+ buildTemporaryWorktreeBranchName,+ isTemporaryWorktreeBranch,normalizeGitRemoteUrl,parseGitHubRepositoryNameWithOwnerFromRemoteUrl,+ WORKTREE_BRANCH_PREFIX,} from "./git";describe("normalizeGitRemoteUrl", () => {@@ -50,6 +53,24 @@ describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {});});+describe("isTemporaryWorktreeBranch", () => {+ it("matches the generated temporary worktree branch format", () => {+ expect(isTemporaryWorktreeBranch(buildTemporaryWorktreeBranchName())).toBe(true);+ });++ it("matches generated temporary worktree branches", () => {+ expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef`)).toBe(true);+ expect(isTemporaryWorktreeBranch(` ${WORKTREE_BRANCH_PREFIX}/deadbeef `)).toBe(true);+ expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true);+ });++ it("rejects non-temporary branch names", () => {+ expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false);+ expect(isTemporaryWorktreeBranch("main")).toBe(false);+ expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/deadbeef-extra`)).toBe(false);+ });+});+describe("applyGitStatusStreamEvent", () => {it("treats a remote-only update as a repository when local state is missing", () => {const remote: GitStatusRemoteResult = {diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.tsindex a39c92444..4570ba9ec 100644--- a/packages/shared/src/git.ts+++ b/packages/shared/src/git.ts@@ -6,6 +6,11 @@ import type {GitStatusResult,GitStatusStreamEvent,} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Random from "effect/Random";++export const WORKTREE_BRANCH_PREFIX = "t3code";+const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);/*** Sanitize an arbitrary string into a valid, lowercase git branch fragment.@@ -80,6 +85,15 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {return branchName.slice(firstSeparatorIndex + 1);}+export function buildTemporaryWorktreeBranchName(): string {+ const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();+ return `${WORKTREE_BRANCH_PREFIX}/${token}`;+}++export function isTemporaryWorktreeBranch(branch: string): boolean {+ return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());+}+/*** Normalize a git remote URL into a stable comparison key.*/