From 29480e0d19078cccd5409fa62e048379d29c6373 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 8 Mar 2026 16:23:15 -0700 Subject: [PATCH] fix git links again --- apps/server/src/git/Layers/GitCore.test.ts | 1 + apps/server/src/git/Layers/GitCore.ts | 7 + apps/server/src/git/Layers/GitManager.test.ts | 129 +++++++++--- apps/server/src/git/Layers/GitManager.ts | 192 ++++++++++++++---- apps/server/src/git/Services/GitCore.ts | 8 + .../components/BranchToolbar.logic.test.ts | 67 ++++++ .../web/src/components/BranchToolbar.logic.ts | 27 +++ apps/web/src/components/BranchToolbar.tsx | 29 ++- apps/web/src/components/ChatView.browser.tsx | 55 +++++ packages/shared/src/git.ts | 49 +++++ 10 files changed, 483 insertions(+), 81 deletions(-) diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index d03ad60615..98e68f02c4 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -103,6 +103,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) => pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd), readRangeContext: (cwd, baseBranch) => core.readRangeContext(cwd, baseBranch), readConfigValue: (cwd, key) => core.readConfigValue(cwd, key), + readRemoteUrl: (cwd, remoteName) => core.readRemoteUrl(cwd, remoteName), listBranches: (input) => core.listBranches(input), createWorktree: (input) => core.createWorktree(input), removeWorktree: (input) => core.removeWorktree(input), diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index a288b2f379..7963a75486 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -826,6 +826,12 @@ const makeGitCore = Effect.gen(function* () { Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); + const readRemoteUrl: GitCoreShape["readRemoteUrl"] = (cwd, remoteName) => + runGitStdout("GitCore.readRemoteUrl", cwd, ["remote", "get-url", remoteName], true).pipe( + Effect.map((stdout) => stdout.trim()), + Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + ); + const listBranches: GitCoreShape["listBranches"] = (input) => Effect.gen(function* () { const branchRecencyPromise = readBranchRecency(input.cwd).pipe( @@ -1195,6 +1201,7 @@ const makeGitCore = Effect.gen(function* () { pullCurrentBranch, readRangeContext, readConfigValue, + readRemoteUrl, listBranches, createWorktree, removeWorktree, diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index d8a3753bb0..b2e4016021 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -23,6 +23,7 @@ interface FakeGhScenario { prListSequence?: string[]; createdPrUrl?: string; defaultBranch?: string; + repoNameWithOwner?: string; failWith?: GitHubCliError; } @@ -165,6 +166,35 @@ function createTextGeneration(overrides: Partial = {}): T }; } +function ghPr( + overrides: Partial<{ + number: number; + title: string; + url: string; + baseRefName: string; + headRefName: string; + headRepository: { name: string }; + headRepositoryOwner: { login: string }; + state: "OPEN" | "CLOSED" | "MERGED"; + mergedAt: string | null; + updatedAt: string | null; + }> = {}, +) { + return { + number: 1, + title: "PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/1", + baseRefName: "main", + headRefName: "feature/test", + headRepository: { name: "codething-mvp" }, + headRepositoryOwner: { login: "pingdotgg" }, + state: "OPEN" as const, + updatedAt: "2026-02-01T10:00:00Z", + ...overrides, + ...(overrides.mergedAt !== undefined ? { mergedAt: overrides.mergedAt } : {}), + }; +} + function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { service: GitHubCliShape; ghCalls: string[]; @@ -213,6 +243,17 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): { } if (args[0] === "repo" && args[1] === "view") { + const jqExpression = args[args.indexOf("--jq") + 1]; + if (jqExpression === ".nameWithOwner") { + return Effect.succeed({ + stdout: `${scenario.repoNameWithOwner ?? "pingdotgg/codething-mvp"}\n`, + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + } + return Effect.succeed({ stdout: `${scenario.defaultBranch ?? "main"}\n`, stderr: "", @@ -337,13 +378,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { ghScenario: { prListSequence: [ JSON.stringify([ - { + ghPr({ number: 13, title: "Existing PR", url: "https://github.com/pingdotgg/codething-mvp/pull/13", - baseRefName: "main", headRefName: "feature/status-open-pr", - }, + }), ]), ], }, @@ -362,6 +402,35 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { }), ); + it.effect("status ignores fork PRs that only match by branch name", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + + const { manager } = yield* makeManager({ + ghScenario: { + prListSequence: [ + JSON.stringify([ + ghPr({ + number: 99, + title: "Fork main PR", + url: "https://github.com/pingdotgg/codething-mvp/pull/99", + headRefName: "main", + headRepositoryOwner: { login: "random-user" }, + headRepository: { name: "t3code" }, + }), + ]), + ], + repoNameWithOwner: "pingdotgg/t3code", + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.branch).toBe("main"); + expect(status.pr).toBeNull(); + }), + ); + it.effect("status returns merged PR state when latest PR was merged", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -372,16 +441,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { ghScenario: { prListSequence: [ JSON.stringify([ - { + ghPr({ number: 22, title: "Merged PR", url: "https://github.com/pingdotgg/codething-mvp/pull/22", - baseRefName: "main", headRefName: "feature/status-merged-pr", state: "MERGED", mergedAt: "2026-01-30T10:00:00Z", updatedAt: "2026-01-30T10:00:00Z", - }, + }), ]), ], }, @@ -410,25 +478,23 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { ghScenario: { prListSequence: [ JSON.stringify([ - { + ghPr({ number: 45, title: "Merged PR", url: "https://github.com/pingdotgg/codething-mvp/pull/45", - baseRefName: "main", headRefName: "feature/status-open-over-merged", state: "MERGED", mergedAt: "2026-01-31T10:00:00Z", updatedAt: "2026-02-01T10:00:00Z", - }, - { + }), + ghPr({ number: 46, title: "Open PR", url: "https://github.com/pingdotgg/codething-mvp/pull/46", - baseRefName: "main", headRefName: "feature/status-open-over-merged", state: "OPEN", updatedAt: "2026-01-30T10:00:00Z", - }, + }), ]), ], }, @@ -709,21 +775,20 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n"); const { manager, ghCalls } = yield* makeManager({ - ghScenario: { - prListSequence: [ - "[]", - JSON.stringify([ - { - number: 77, - title: "Add no-upstream PR flow", - url: "https://github.com/pingdotgg/codething-mvp/pull/77", - baseRefName: "main", - headRefName: "feature/no-upstream-pr", - }, - ]), - ], - }, - }); + ghScenario: { + prListSequence: [ + "[]", + JSON.stringify([ + ghPr({ + number: 77, + title: "Add no-upstream PR flow", + url: "https://github.com/pingdotgg/codething-mvp/pull/77", + headRefName: "feature/no-upstream-pr", + }), + ]), + ], + }, + }); const result = yield* runStackedAction(manager, { cwd: repoDir, @@ -782,13 +847,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { ghScenario: { prListSequence: [ JSON.stringify([ - { + ghPr({ number: 42, title: "Existing PR", url: "https://github.com/pingdotgg/codething-mvp/pull/42", - baseRefName: "main", headRefName: "feature/existing-pr", - }, + }), ]), ], }, @@ -823,13 +887,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { prListSequence: [ "[]", JSON.stringify([ - { + ghPr({ number: 88, title: "Add stacked git actions", url: "https://github.com/pingdotgg/codething-mvp/pull/88", - baseRefName: "main", headRefName: "feature-create-pr", - }, + }), ]), ], }, diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index c4a29e15dd..e7f62ba66c 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -1,7 +1,12 @@ import { randomUUID } from "node:crypto"; import { Effect, FileSystem, Layer, Path } from "effect"; -import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git"; +import { + parseGitHubRepositoryFromRemoteUrl, + resolveAutoFeatureBranchName, + sanitizeFeatureBranchName, + type GitHubRepositoryIdentity, +} from "@t3tools/shared/git"; import { GitManagerError } from "../Errors.ts"; import { GitManager, type GitManagerShape } from "../Services/GitManager.ts"; @@ -18,10 +23,34 @@ interface OpenPrInfo { } interface PullRequestInfo extends OpenPrInfo { + headRepositoryOwner: string | null; + headRepositoryName: string | null; state: "open" | "closed" | "merged"; updatedAt: string | null; } +function normalizeOptionalString(value: unknown): string | null { + if (typeof value !== "string") { + return null; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + +function parsePullRequestHeadRepositoryOwner(value: unknown): string | null { + if (!value || typeof value !== "object") { + return normalizeOptionalString(value); + } + return normalizeOptionalString((value as Record).login); +} + +function parsePullRequestHeadRepositoryName(value: unknown): string | null { + if (!value || typeof value !== "object") { + return null; + } + return normalizeOptionalString((value as Record).name); +} + function parsePullRequestList(raw: unknown): PullRequestInfo[] { if (!Array.isArray(raw)) return []; @@ -34,6 +63,8 @@ function parsePullRequestList(raw: unknown): PullRequestInfo[] { const url = record.url; const baseRefName = record.baseRefName; const headRefName = record.headRefName; + const headRepositoryOwner = parsePullRequestHeadRepositoryOwner(record.headRepositoryOwner); + const headRepositoryName = parsePullRequestHeadRepositoryName(record.headRepository); const state = record.state; const mergedAt = record.mergedAt; const updatedAt = record.updatedAt; @@ -66,6 +97,8 @@ function parsePullRequestList(raw: unknown): PullRequestInfo[] { url, baseRefName, headRefName, + headRepositoryOwner, + headRepositoryName, state: normalizedState, updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null, }); @@ -157,6 +190,49 @@ function extractBranchFromRef(ref: string): string { return normalized.slice(firstSlash + 1).trim(); } +function extractRemoteNameFromUpstreamRef(upstreamRef: string): string | null { + const trimmed = upstreamRef.trim(); + const separatorIndex = trimmed.indexOf("/"); + if (separatorIndex <= 0) { + return null; + } + + const remoteName = trimmed.slice(0, separatorIndex).trim(); + return remoteName.length > 0 ? remoteName : null; +} + +function parseGitHubRepositoryIdentity(raw: string): GitHubRepositoryIdentity | null { + const trimmed = raw.trim(); + if (trimmed.length === 0) { + return null; + } + + const [owner, name, ...rest] = trimmed.split("/").map((segment) => segment.trim()); + if (!owner || !name || rest.length > 0) { + return null; + } + + return { owner, name }; +} + +function matchesPullRequestHeadRepository( + pr: PullRequestInfo, + branch: string, + repository: GitHubRepositoryIdentity, +): boolean { + return ( + pr.headRefName === branch && + pr.headRepositoryOwner?.toLowerCase() === repository.owner.toLowerCase() && + pr.headRepositoryName?.toLowerCase() === repository.name.toLowerCase() + ); +} + +function comparePullRequestsByUpdatedAt(a: PullRequestInfo, b: PullRequestInfo): number { + const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; + const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; + return right - left; +} + function toStatusPr(pr: PullRequestInfo): { number: number; title: string; @@ -184,33 +260,48 @@ export const makeGitManager = Effect.gen(function* () { const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp"; - const findOpenPr = (cwd: string, branch: string) => - gitHubCli - .listOpenPullRequests({ - cwd, - headBranch: branch, - limit: 1, - }) - .pipe( - Effect.map((prs) => { - const [first] = prs; - if (!first) { - return null; - } - return { - number: first.number, - title: first.title, - url: first.url, - baseRefName: first.baseRefName, - headRefName: first.headRefName, - state: "open", - updatedAt: null, - } satisfies PullRequestInfo; - }), - ); - - const findLatestPr = (cwd: string, branch: string) => + const resolveCurrentHeadRepository = (cwd: string, upstreamRef: string | null) => Effect.gen(function* () { + if (upstreamRef) { + const remoteName = extractRemoteNameFromUpstreamRef(upstreamRef); + if (remoteName) { + const remoteUrl = yield* gitCore + .readRemoteUrl(cwd, remoteName) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (remoteUrl) { + const parsedRemote = parseGitHubRepositoryFromRemoteUrl(remoteUrl); + if (parsedRemote) { + return parsedRemote; + } + } + } + } + + const repoNameWithOwner = yield* gitHubCli + .execute({ + cwd, + args: ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], + }) + .pipe( + Effect.map((result) => result.stdout.trim()), + Effect.catch(() => Effect.succeed("")), + ); + + return parseGitHubRepositoryIdentity(repoNameWithOwner); + }); + + const findMatchingPrs = ( + cwd: string, + branch: string, + upstreamRef: string | null, + state: "open" | "all", + ) => + Effect.gen(function* () { + const currentHeadRepository = yield* resolveCurrentHeadRepository(cwd, upstreamRef); + if (!currentHeadRepository) { + return [] as PullRequestInfo[]; + } + const stdout = yield* gitHubCli .execute({ cwd, @@ -220,39 +311,50 @@ export const makeGitManager = Effect.gen(function* () { "--head", branch, "--state", - "all", + state, "--limit", "20", "--json", - "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", + "number,title,url,baseRefName,headRefName,headRepository,headRepositoryOwner,state,mergedAt,updatedAt", ], }) .pipe(Effect.map((result) => result.stdout)); const raw = stdout.trim(); if (raw.length === 0) { - return null; + return [] as PullRequestInfo[]; } const parsedJson = yield* Effect.try({ try: () => JSON.parse(raw) as unknown, catch: (cause) => - gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), + gitManagerError("findMatchingPrs", "GitHub CLI returned invalid PR list JSON.", cause), }); - const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => { - const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; - const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; - return right - left; - }); - - const latestOpenPr = parsed.find((pr) => pr.state === "open"); - if (latestOpenPr) { - return latestOpenPr; - } - return parsed[0] ?? null; + return parsePullRequestList(parsedJson) + .filter((pr) => matchesPullRequestHeadRepository(pr, branch, currentHeadRepository)) + .toSorted(comparePullRequestsByUpdatedAt); }); + const findOpenPr = (cwd: string, branch: string, upstreamRef: string | null) => + findMatchingPrs(cwd, branch, upstreamRef, "open").pipe( + Effect.map((prs) => { + const [first] = prs; + return first ?? null; + }), + ); + + const findLatestPr = (cwd: string, branch: string, upstreamRef: string | null) => + findMatchingPrs(cwd, branch, upstreamRef, "all").pipe( + Effect.map((parsed) => { + const latestOpenPr = parsed.find((pr) => pr.state === "open"); + if (latestOpenPr) { + return latestOpenPr; + } + return parsed[0] ?? null; + }), + ); + const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) => Effect.gen(function* () { const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); @@ -361,7 +463,7 @@ export const makeGitManager = Effect.gen(function* () { ); } - const existing = yield* findOpenPr(cwd, branch); + const existing = yield* findOpenPr(cwd, branch, details.upstreamRef); if (existing) { return { status: "opened_existing" as const, @@ -403,7 +505,7 @@ export const makeGitManager = Effect.gen(function* () { }) .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); - const created = yield* findOpenPr(cwd, branch); + const created = yield* findOpenPr(cwd, branch, details.upstreamRef); if (!created) { return { status: "created" as const, @@ -428,7 +530,7 @@ export const makeGitManager = Effect.gen(function* () { const pr = details.branch !== null - ? yield* findLatestPr(input.cwd, details.branch).pipe( + ? yield* findLatestPr(input.cwd, details.branch, details.upstreamRef).pipe( Effect.map((latest) => (latest ? toStatusPr(latest) : null)), Effect.catch(() => Effect.succeed(null)), ) diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index c60b9bd3e9..a802ee08b0 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -110,6 +110,14 @@ export interface GitCoreShape { key: string, ) => Effect.Effect; + /** + * Read a configured remote URL from the local repository. + */ + readonly readRemoteUrl: ( + cwd: string, + remoteName: string, + ) => Effect.Effect; + /** * List local + remote branches and branch metadata. */ diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index ea164b3630..4d328d111e 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -2,9 +2,11 @@ import type { GitBranch } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; import { dedupeRemoteBranchesWithLocalMatches, + getEnvModeButtonLabel, deriveLocalBranchNameFromRemoteRef, resolveDraftEnvModeAfterBranchChange, resolveBranchToolbarValue, + resolveEnvToggleAction, } from "./BranchToolbar.logic"; describe("resolveDraftEnvModeAfterBranchChange", () => { @@ -74,6 +76,71 @@ describe("resolveBranchToolbarValue", () => { }); }); +describe("resolveEnvToggleAction", () => { + it("allows detaching an inherited worktree before the thread is locked", () => { + expect( + resolveEnvToggleAction({ + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + effectiveEnvMode: "worktree", + envLocked: false, + }), + ).toBe("detach-worktree"); + }); + + it("keeps the toggle locked once the thread environment is immutable", () => { + expect( + resolveEnvToggleAction({ + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + effectiveEnvMode: "worktree", + envLocked: true, + }), + ).toBe("locked"); + }); + + it("switches between local and new-worktree modes when no worktree is attached", () => { + expect( + resolveEnvToggleAction({ + activeWorktreePath: null, + effectiveEnvMode: "local", + envLocked: false, + }), + ).toBe("set-worktree"); + expect( + resolveEnvToggleAction({ + activeWorktreePath: null, + effectiveEnvMode: "worktree", + envLocked: false, + }), + ).toBe("set-local"); + }); +}); + +describe("getEnvModeButtonLabel", () => { + it("shows the attached worktree label when a worktree is already bound", () => { + expect( + getEnvModeButtonLabel({ + activeWorktreePath: "/repo/.t3/worktrees/feature-a", + effectiveEnvMode: "worktree", + }), + ).toBe("Worktree"); + }); + + it("distinguishes between local mode and pending new-worktree mode", () => { + expect( + getEnvModeButtonLabel({ + activeWorktreePath: null, + effectiveEnvMode: "local", + }), + ).toBe("Local"); + expect( + getEnvModeButtonLabel({ + activeWorktreePath: null, + effectiveEnvMode: "worktree", + }), + ).toBe("New 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.ts index 1b48970bbf..1d677ec551 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -1,6 +1,7 @@ import type { GitBranch } from "@t3tools/contracts"; export type EnvMode = "local" | "worktree"; +export type EnvToggleAction = "locked" | "set-worktree" | "set-local" | "detach-worktree"; export function resolveEffectiveEnvMode(input: { activeWorktreePath: string | null; @@ -28,6 +29,32 @@ export function resolveDraftEnvModeAfterBranchChange(input: { return "local"; } +export function resolveEnvToggleAction(input: { + activeWorktreePath: string | null; + effectiveEnvMode: EnvMode; + envLocked: boolean; +}): EnvToggleAction { + const { activeWorktreePath, effectiveEnvMode, envLocked } = input; + if (envLocked) { + return "locked"; + } + if (activeWorktreePath) { + return "detach-worktree"; + } + return effectiveEnvMode === "worktree" ? "set-local" : "set-worktree"; +} + +export function getEnvModeButtonLabel(input: { + activeWorktreePath: string | null; + effectiveEnvMode: EnvMode; +}): string { + const { activeWorktreePath, effectiveEnvMode } = input; + if (activeWorktreePath) { + return "Worktree"; + } + return effectiveEnvMode === "worktree" ? "New worktree" : "Local"; +} + export function resolveBranchToolbarValue(input: { envMode: EnvMode; activeWorktreePath: string | null; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index d1c68d321d..352d696935 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -7,8 +7,10 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { useStore } from "../store"; import { EnvMode, + getEnvModeButtonLabel, resolveDraftEnvModeAfterBranchChange, resolveEffectiveEnvMode, + resolveEnvToggleAction, } from "./BranchToolbar.logic"; import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector"; import { Button } from "./ui/button"; @@ -45,6 +47,11 @@ export default function BranchToolbar({ hasServerThread, draftThreadEnvMode: draftThread?.envMode, }); + const envToggleAction = resolveEnvToggleAction({ + activeWorktreePath, + effectiveEnvMode, + envLocked, + }); const setThreadBranch = useCallback( (branch: string | null, worktreePath: string | null) => { @@ -98,12 +105,25 @@ export default function BranchToolbar({ ], ); + const handleEnvToggle = useCallback(() => { + if (envToggleAction === "locked") { + return; + } + if (envToggleAction === "detach-worktree") { + setThreadBranch(null, null); + onComposerFocusRequest?.(); + return; + } + onEnvModeChange(envToggleAction === "set-worktree" ? "worktree" : "local"); + onComposerFocusRequest?.(); + }, [envToggleAction, onComposerFocusRequest, onEnvModeChange, setThreadBranch]); + if (!activeThreadId || !activeProject) return null; return (
- {envLocked || activeWorktreePath ? ( + {envToggleAction === "locked" ? ( {activeWorktreePath ? "Worktree" : "Local"} @@ -113,9 +133,12 @@ export default function BranchToolbar({ variant="ghost" className="text-muted-foreground/70 hover:text-foreground/80" size="xs" - onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")} + onClick={handleEnvToggle} > - {effectiveEnvMode === "worktree" ? "New worktree" : "Local"} + {getEnvModeButtonLabel({ + activeWorktreePath, + effectiveEnvMode, + })} )}
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index e2fd573fe8..b3e7977179 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -409,6 +409,16 @@ async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Pro ); } +async function waitForEnvModeButton(expectedLabel: "Local" | "Worktree" | "New worktree") { + return waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === expectedLabel, + ) as HTMLButtonElement | null, + `Unable to find ${expectedLabel} environment mode button.`, + ); +} + async function waitForImagesToLoad(scope: ParentNode): Promise { const images = Array.from(scope.querySelectorAll("img")); if (images.length === 0) { @@ -803,6 +813,51 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("lets a new draft thread detach an inherited worktree before the first message", async () => { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feature/demo", + worktreePath: "/repo/project/.t3/worktrees/feature-demo", + envMode: "worktree", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + }); + + try { + const worktreeButton = await waitForEnvModeButton("Worktree"); + worktreeButton.click(); + + await vi.waitFor( + () => { + const draftThread = useComposerDraftStore.getState().getDraftThread(THREAD_ID); + expect(draftThread).toMatchObject({ + branch: null, + worktreePath: null, + envMode: "local", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + + await waitForEnvModeButton("Local"); + } finally { + await mounted.cleanup(); + } + }); + it("toggles plan mode with Shift+Tab only while the composer is focused", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index bbd290393f..14bb7b1af0 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -59,3 +59,52 @@ export function resolveAutoFeatureBranchName( return `${resolvedBase}-${suffix}`; } + +export interface GitHubRepositoryIdentity { + owner: string; + name: string; +} + +/** + * Parse a GitHub-style remote URL into `{ owner, name }`. + * Supports SSH scp syntax and URL-based remotes. + */ +export function parseGitHubRepositoryFromRemoteUrl( + remoteUrl: string, +): GitHubRepositoryIdentity | null { + const trimmed = remoteUrl.trim(); + if (trimmed.length === 0) { + return null; + } + + const scpMatch = trimmed.match(/^[^@]+@[^:]+:(.+)$/); + const rawPath = scpMatch?.[1] ?? (() => { + try { + return new URL(trimmed).pathname; + } catch { + return null; + } + })(); + + if (!rawPath) { + return null; + } + + const segments = rawPath + .replace(/^\/+|\/+$/g, "") + .replace(/\.git$/i, "") + .split("/") + .map((segment) => segment.trim()) + .filter((segment) => segment.length > 0); + + if (segments.length !== 2) { + return null; + } + + const owner = segments[0]; + const name = segments[1]; + if (!owner || !name) { + return null; + } + return { owner, name }; +}