Fix slash-remote PR resolution

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-04-01 10:55:08 -07:00
1 parent dd46b2b9fc
commit d76318b90a
7 files changed
+395 -60

No files matched your search

+7 -36
View File
@@ -27,6 +27,11 @@ import {
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
import {
parseRemoteNames,
parseRemoteNamesInGitOrder,
parseRemoteRefWithRemoteNames,
} from "../remoteRefs.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
@@ -177,14 +182,6 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function sanitizeRemoteName(value: string): string {
const sanitized = value
.trim()
@@ -217,32 +214,6 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
return remotes;
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseUpstreamRefWithRemoteNames(
upstreamRef: string,
remoteNames: ReadonlyArray<string>,
@@ -255,7 +226,7 @@ function parseUpstreamRefWithRemoteNames(
return {
upstreamRef,
remoteName: parsed.remoteName,
upstreamBranch: parsed.localBranch,
upstreamBranch: parsed.branchName,
};
}
@@ -928,7 +899,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
Effect.map(parseRemoteNamesInGitOrder),
);
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
@@ -159,6 +159,23 @@ function createBareRemote(): Effect.Effect<
});
}
function configureRemote(
cwd: string,
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
"config",
"--replace-all",
`remote.${remoteName}.fetch`,
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
]);
});
}
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
const implementation: FakeGitTextGeneration = {
generateCommitMessage: (input) =>
@@ -633,6 +650,114 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
12_000,
);
it.effect(
"status ignores synthetic local branch aliases when the upstream remote name contains slashes",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const upstreamDir = yield* createBareRemote();
yield* configureRemote(repoDir, "origin", originDir, "origin");
yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream");
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"effect-atom": JSON.stringify([
{
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseRefName: "main",
headRefName: "effect-atom",
state: "OPEN",
updatedAt: "2026-03-01T10:00:00Z",
},
]),
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
"pingdotgg:effect-atom": JSON.stringify([]),
"my-org/upstream:effect-atom": JSON.stringify([]),
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
state: "OPEN",
updatedAt: "2026-04-01T10:00:00Z",
},
]),
},
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseBranch: "main",
headBranch: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
false,
);
expect(
ghCalls.some((call) => call.includes("pr list --head pingdotgg:upstream/effect-atom ")),
).toBe(false);
expect(
ghCalls.some((call) =>
call.includes("pr list --head my-org/upstream:upstream/effect-atom "),
),
).toBe(false);
}),
12_000,
);
it.effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -1149,6 +1274,98 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
12_000,
);
it.effect(
"returns the correct existing PR when a slash remote checks out to a synthetic local alias",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const upstreamDir = yield* createBareRemote();
yield* configureRemote(repoDir, "origin", originDir, "origin");
yield* configureRemote(repoDir, "my-org/upstream", upstreamDir, "my-org/upstream");
yield* runGit(repoDir, ["checkout", "-b", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "origin", "effect-atom"]);
yield* runGit(repoDir, ["push", "-u", "my-org/upstream", "effect-atom"]);
yield* runGit(repoDir, [
"config",
"remote.origin.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.origin.pushurl", originDir]);
yield* runGit(repoDir, [
"config",
"remote.my-org/upstream.url",
"[email protected]:pingdotgg/codething-mvp.git",
]);
yield* runGit(repoDir, ["config", "remote.my-org/upstream.pushurl", upstreamDir]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "effect-atom"]);
yield* runGit(repoDir, ["checkout", "--track", "my-org/upstream/effect-atom"]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
"effect-atom": JSON.stringify([
{
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseRefName: "main",
headRefName: "effect-atom",
},
]),
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
"pingdotgg:effect-atom": JSON.stringify([]),
"my-org/upstream:effect-atom": JSON.stringify([]),
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
title: "Wrong PR",
url: "https://github.com/pingdotgg/t3code/pull/1518",
baseRefName: "main",
headRefName: "upstream/effect-atom",
},
]),
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(1618);
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
false,
);
}),
12_000,
);
it.effect(
"prefers owner-qualified selectors before bare branch names for cross-repo PRs",
() =>
+11 -23
View File
@@ -24,6 +24,7 @@ import {
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
@@ -262,25 +263,6 @@ function parseCustomCommitMessage(raw: string): { subject: string; body: string
};
}
function extractBranchFromRef(ref: string): string {
const normalized = ref.trim();
if (normalized.startsWith("refs/remotes/")) {
const withoutPrefix = normalized.slice("refs/remotes/".length);
const firstSlash = withoutPrefix.indexOf("/");
if (firstSlash === -1) {
return withoutPrefix.trim();
}
return withoutPrefix.slice(firstSlash + 1).trim();
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
function appendUnique(values: string[], next: string | null | undefined): void {
const trimmed = next?.trim() ?? "";
if (trimmed.length === 0 || values.includes(trimmed)) {
@@ -534,9 +516,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
) {
const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);
const headBranchFromUpstream = details.upstreamRef
? extractBranchFromRef(details.upstreamRef)
? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName })
: "";
const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;
const shouldProbeLocalBranchSelector =
headBranchFromUpstream.length === 0 || headBranch === details.branch;
const [remoteRepository, originRepository] = yield* Effect.all(
[
@@ -572,7 +556,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,
);
}
appendUnique(headSelectors, details.branch);
if (shouldProbeLocalBranchSelector) {
appendUnique(headSelectors, details.branch);
}
appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);
if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {
appendUnique(headSelectors, ownerHeadSelector);
@@ -682,13 +668,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
cwd: string,
branch: string,
upstreamRef: string | null,
headContext: Pick<BranchHeadContext, "isCrossRepository">,
headContext: Pick<BranchHeadContext, "isCrossRepository" | "remoteName">,
) {
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef && !headContext.isCrossRepository) {
const upstreamBranch = extractBranchFromRef(upstreamRef);
const upstreamBranch = extractBranchNameFromRemoteRef(upstreamRef, {
remoteName: headContext.remoteName,
});
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
return upstreamBranch;
}
+67
View File
@@ -0,0 +1,67 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
}
export function parseRemoteRefWithRemoteNames(
ref: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; branchName: string } | null {
const trimmedRef = ref.trim();
if (trimmedRef.length === 0) {
return null;
}
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedRef.startsWith(remotePrefix)) {
continue;
}
const branchName = trimmedRef.slice(remotePrefix.length).trim();
if (branchName.length === 0) {
return null;
}
return {
remoteRef: trimmedRef,
remoteName,
branchName,
};
}
return null;
}
export function extractBranchNameFromRemoteRef(
ref: string,
options?: {
remoteName?: string | null;
remoteNames?: ReadonlyArray<string>;
},
): string {
const normalized = ref.trim();
if (normalized.length === 0) {
return "";
}
if (normalized.startsWith("refs/remotes/")) {
return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options);
}
const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);
const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);
if (parsedRemoteRef) {
return parsedRemoteRef.branchName;
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
@@ -7,6 +7,7 @@ import {
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
resolveThreadBranchUpdate,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -986,6 +987,47 @@ describe("summarizeGitResult", () => {
});
});
describe("resolveThreadBranchUpdate", () => {
it("returns a branch update when the action created a new branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push_pr",
branch: {
status: "created",
name: "feature/fix-toast-copy",
},
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
});
assert.deepEqual(update, {
branch: "feature/fix-toast-copy",
});
});
it("returns null when the action stayed on the existing branch", () => {
const update = resolveThreadBranchUpdate({
action: "commit_push",
branch: {
status: "skipped_not_requested",
},
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
});
assert.equal(update, null);
});
});
describe("resolveAutoFeatureBranchName", () => {
it("uses semantic preferred branch names when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
@@ -346,5 +346,17 @@ export function resolveDefaultBranchActionDialogCopy(input: {
};
}
export function resolveThreadBranchUpdate(
result: GitRunStackedActionResult,
): { branch: string } | null {
if (result.branch.status !== "created" || !result.branch.name) {
return null;
}
return {
branch: result.branch.name,
};
}
// Re-export from shared for backwards compatibility in this module's exports
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
+39 -1
View File
@@ -1,5 +1,6 @@
import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
ThreadId,
@@ -18,6 +19,7 @@ import {
requiresDefaultBranchConfirmation,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
resolveThreadBranchUpdate,
summarizeGitResult,
} from "./GitActionsControl.logic";
import { Button } from "~/components/ui/button";
@@ -47,9 +49,10 @@ import {
gitStatusQueryOptions,
invalidateGitQueries,
} from "~/lib/gitReactQuery";
import { randomUUID } from "~/lib/utils";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { readNativeApi } from "~/nativeApi";
import { useStore } from "~/store";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -208,6 +211,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
);
const activeServerThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
@@ -231,6 +238,36 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
}, [threadToastData]);
const syncThreadBranchAfterGitAction = useCallback(
(result: GitRunStackedActionResult) => {
const branchUpdate = resolveThreadBranchUpdate(result);
if (!branchUpdate || !activeThreadId || !activeServerThread) {
return;
}
const worktreePath = activeServerThread.worktreePath;
if (activeServerThread.branch === branchUpdate.branch) {
return;
}
const api = readNativeApi();
if (api) {
void api.orchestration
.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch: branchUpdate.branch,
worktreePath,
})
.catch(() => undefined);
}
setThreadBranch(activeThreadId, branchUpdate.branch, worktreePath);
},
[activeServerThread, activeThreadId, setThreadBranch],
);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
const { data: branchList = null } = useQuery(gitBranchesQueryOptions(gitCwd));
@@ -483,6 +520,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
try {
const result = await promise;
activeGitActionProgressRef.current = null;
syncThreadBranchAfterGitAction(result);
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =