Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex e0314cf2b2 Rename branch UI to ref-aware VCS helpers
- Generalize branch toolbar logic and status state around refs
- Add VCS query/status wrappers and keep legacy branch aliases
- Update selector behavior, labels, and tests for remote refs

Co-authored-by: codex <[email protected]>
2026-05-02 23:00:43 -07:00
Julius Marminge 23355c1bdd Merge origin/main into PR branch
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/server/src/git/GitManager.test.ts
#	apps/web/src/components/BranchToolbarBranchSelector.tsx
#	apps/web/src/components/Sidebar.tsx
#	apps/web/src/components/ThreadStatusIndicators.tsx
2026-05-02 20:23:29 -07:00
Julius MarmingeandJulius Marminge 0ce7e56e43 feat(scm): Gitlab (#2462)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 18:59:47 -07:00
Julius MarmingeandJulius Marminge 350d76ee14 [codex] Align GitHub source control adapter errors (#2476)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-02 16:59:03 -07:00
justsomelegs 02bb838ae7 Improve PR status tooltip formatting 2026-05-01 22:30:13 +01:00
justsomelegs 3b0f78dd3e Handle fork-origin PR status matching 2026-05-01 22:30:13 +01:00
justsomelegs 32358fd7e2 Reject same-repo PRs for cross-repo heads 2026-05-01 22:30:13 +01:00
justsomelegs eb9b509af8 Fix cross-repo PR identity matching 2026-05-01 22:30:13 +01:00
justsomelegs d7cc9174ae Improve branch mismatch warnings 2026-05-01 22:30:04 +01:00
39 changed files with 2747 additions and 665 deletions

No files matched your search

+290 -3
View File
@@ -4,7 +4,7 @@ import { spawnSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { Effect, FileSystem, Layer, Option, PlatformError, Scope } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vitest";
import type {
@@ -14,9 +14,10 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "./GitManager.ts";
import {
GitHubCliError,
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
@@ -26,7 +27,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import { makeGitManager } from "./GitManager.ts";
import { makeGitManager, matchesBranchHeadContext } from "./GitManager.ts";
import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
@@ -880,6 +881,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -909,6 +911,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}),
@@ -1671,6 +1674,41 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("pushes existing commits without committing dirty worktree changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/push-dirty"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "push-dirty.txt"), "push dirty\n");
yield* runGit(repoDir, ["add", "push-dirty.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Push dirty branch"]);
fs.mkdirSync(path.join(repoDir, ".vercel"));
fs.writeFileSync(path.join(repoDir, ".vercel", "project.json"), "{}\n");
const { manager } = yield* makeManager();
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "push",
});
expect(result.commit.status).toBe("skipped_not_requested");
expect(result.push.status).toBe("pushed");
expect(result.pr.status).toBe("skipped_not_requested");
expect(
yield* runGit(repoDir, ["status", "--porcelain"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toContain("?? .vercel/");
expect(
yield* runGit(remoteDir, ["log", "-1", "--pretty=%s", "feature/push-dirty"]).pipe(
Effect.map((output) => output.stdout.trim()),
),
).toBe("Push dirty branch");
}),
);
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2087,6 +2125,148 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
12_000,
);
it.effect(
"does not reuse a cross-repo PR when GitHub omits head identity metadata",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "statemachine"]);
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "statemachine"]);
yield* runGit(repoDir, [
"config",
"remote.fork-seed.url",
"[email protected]:octocat/codething-mvp.git",
]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequenceByHeadSelector: {
"octocat:statemachine": [
JSON.stringify([
{
number: 41,
title: "Ambiguous fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
},
]),
JSON.stringify([
{
number: 142,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
},
]),
],
"fork-seed:statemachine": [JSON.stringify([])],
statemachine: [JSON.stringify([])],
},
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(142);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(true);
}),
12_000,
);
it.effect("rejects same-repo PR metadata when matching a cross-repo head context", () =>
Effect.sync(() => {
const headContext = {
headBranch: "statemachine",
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
isCrossRepository: true,
};
expect(
matchesBranchHeadContext(
{
number: 41,
title: "Same-repo PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/41",
baseRefName: "main",
headRefName: "statemachine",
state: "open",
updatedAt: Option.none(),
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
headContext,
),
).toBe(false);
expect(
matchesBranchHeadContext(
{
number: 142,
title: "Fork PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/142",
baseRefName: "main",
headRefName: "statemachine",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
headContext,
),
).toBe(true);
}),
);
it.effect("accepts fork PR metadata when origin is the fork checkout remote", () =>
Effect.sync(() => {
const headContext = {
headBranch: "t3code/git-audit-stability",
headRepositoryNameWithOwner: "justsomelegs/t3code",
headRepositoryOwnerLogin: "justsomelegs",
isCrossRepository: false,
};
expect(
matchesBranchHeadContext(
{
number: 2284,
title: "Improve branch mismatch warnings",
url: "https://github.com/pingdotgg/t3code/pull/2284",
baseRefName: "main",
headRefName: "t3code/git-audit-stability",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "justsomelegs/t3code",
headRepositoryOwnerLogin: "justsomelegs",
},
headContext,
),
).toBe(true);
}),
);
it.effect("creates PR when one does not already exist", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2417,6 +2597,113 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"restores same-repository upstream tracking after local PR checkout without a remote ref",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-upstream"]);
fs.writeFileSync(path.join(repoDir, "upstream.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "upstream.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local upstream PR branch"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-upstream"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-upstream"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-upstream",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 65,
title: "Local upstream PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/65",
baseRefName: "main",
headRefName: "feature/pr-local-upstream",
state: "open",
isCrossRepository: false,
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
headRepositoryOwnerLogin: "pingdotgg",
},
repositoryCloneUrls: {
"pingdotgg/codething-mvp": {
url: remoteDir,
sshUrl: remoteDir,
},
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "65",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-upstream");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-upstream");
}),
);
it.effect(
"restores same-repository upstream tracking when provider omits head repository metadata",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-local-no-head-repo"]);
fs.writeFileSync(path.join(repoDir, "no-head-repo.txt"), "upstream\n");
yield* runGit(repoDir, ["add", "no-head-repo.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Local PR branch without repo metadata"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, ["checkout", "main"]);
yield* runGit(repoDir, ["branch", "-D", "feature/pr-local-no-head-repo"]);
yield* runGit(repoDir, [
"update-ref",
"-d",
"refs/remotes/origin/feature/pr-local-no-head-repo",
]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 66,
title: "Local upstream PR without repo metadata",
url: "https://github.com/pingdotgg/codething-mvp/pull/66",
baseRefName: "main",
headRefName: "feature/pr-local-no-head-repo",
state: "open",
},
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "66",
mode: "local",
});
expect(result.worktreePath).toBeNull();
expect(result.branch).toBe("feature/pr-local-no-head-repo");
expect(
(yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
).toBe("origin/feature/pr-local-no-head-repo");
}),
);
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+83 -33
View File
@@ -250,7 +250,38 @@ function resolvePullRequestHeadRepositoryNameWithOwner(
return `${ownerLogin}/${repositoryName}`;
}
function matchesBranchHeadContext(
interface PullRequestHeadIdentity {
readonly repositoryNameWithOwner: string | null;
readonly ownerLogin: string | null;
}
function resolveExpectedHeadIdentity(
headContext: Pick<BranchHeadContext, "headRepositoryNameWithOwner" | "headRepositoryOwnerLogin">,
): PullRequestHeadIdentity {
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
headContext.headRepositoryNameWithOwner,
);
return {
repositoryNameWithOwner,
ownerLogin:
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
}
function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
resolvePullRequestHeadRepositoryNameWithOwner(pr),
);
return {
repositoryNameWithOwner,
ownerLogin:
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(repositoryNameWithOwner),
};
}
export function matchesBranchHeadContext(
pr: PullRequestInfo,
headContext: Pick<
BranchHeadContext,
@@ -261,44 +292,46 @@ function matchesBranchHeadContext(
return false;
}
const expectedHeadRepository = normalizeOptionalRepositoryNameWithOwner(
headContext.headRepositoryNameWithOwner,
);
const expectedHeadOwner =
normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(expectedHeadRepository);
const prHeadRepository = normalizeOptionalRepositoryNameWithOwner(
resolvePullRequestHeadRepositoryNameWithOwner(pr),
);
const prHeadOwner =
normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??
parseRepositoryOwnerLogin(prHeadRepository);
const expectedHead = resolveExpectedHeadIdentity(headContext);
const pullRequestHead = resolvePullRequestHeadIdentity(pr);
if (expectedHead.repositoryNameWithOwner) {
if (pullRequestHead.repositoryNameWithOwner) {
if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {
return false;
}
}
}
if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {
if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {
return false;
}
}
if (headContext.isCrossRepository) {
if (pr.isCrossRepository === false) {
return false;
}
if ((expectedHeadRepository || expectedHeadOwner) && !prHeadRepository && !prHeadOwner) {
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
if (
(expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&
!pullRequestHead.repositoryNameWithOwner &&
!pullRequestHead.ownerLogin
) {
return false;
}
return true;
}
if (pr.isCrossRepository === true) {
return false;
}
if (expectedHeadRepository && prHeadRepository && expectedHeadRepository !== prHeadRepository) {
return false;
}
if (expectedHeadOwner && prHeadOwner && expectedHeadOwner !== prHeadOwner) {
return false;
if (
(!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||
(!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)
) {
return false;
}
}
return true;
}
@@ -568,6 +601,22 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
localBranch = pullRequest.headBranch,
) {
const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {
const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
remoteName,
remoteBranch: pullRequest.headBranch,
});
return;
}
if (repositoryNameWithOwner.length === 0) {
return;
}
@@ -588,6 +637,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
url: remoteUrl,
});
yield* gitCore.fetchRemoteTrackingBranch({
cwd,
remoteName,
remoteBranch: pullRequest.headBranch,
});
yield* gitCore.setBranchUpstream({
cwd,
branch: localBranch,
@@ -690,6 +744,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
} satisfies GitStatusDetails;
const readLocalStatus = Effect.fn("readLocalStatus")(function* (cwd: string) {
const details = yield* gitCore
@@ -748,6 +803,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
aheadOfDefaultCount: details.aheadOfDefaultCount,
pr,
} satisfies VcsStatusRemoteResult;
});
@@ -1593,12 +1649,6 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
"Feature-branch checkout is only supported for commit actions.",
);
}
if (input.action === "push" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
"Commit or stash local changes before pushing.",
);
}
if (input.action === "create_pr" && initialStatus.hasWorkingTreeChanges) {
return yield* gitManagerError(
"runStackedAction",
@@ -65,6 +65,7 @@ describe("GitWorkflowService", () => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
});
}).pipe(
@@ -112,6 +112,7 @@ function nonRepositoryStatus(): VcsStatusResult {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
};
}
+2 -1
View File
@@ -26,6 +26,7 @@ import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as GitLabCli from "./sourceControl/GitLabCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
@@ -165,7 +166,7 @@ const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
Layer.provideMerge(VcsDriverRegistryLayerLive),
),
),
+12 -2
View File
@@ -1,16 +1,26 @@
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { GitHubCliError, TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
import { TrimmedNonEmptyString, type VcsError } from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../git/githubPullRequests.ts";
} from "./gitHubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
@@ -3,11 +3,10 @@ import {
SourceControlProviderError,
type ChangeRequest,
type ChangeRequestState,
type GitHubCliError,
} from "@t3tools/contracts";
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "../git/githubPullRequests.ts";
import { GitHubCli, type GitHubCliError, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
@@ -0,0 +1,266 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { afterEach, expect, vi } from "vitest";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsProcess, type VcsProcessOutput, type VcsProcessShape } from "../vcs/VcsProcess.ts";
import * as GitLabCli from "./GitLabCli.ts";
const mockedRun = vi.fn<VcsProcessShape["run"]>();
const layer = it.layer(
GitLabCli.layer.pipe(
Layer.provide(
Layer.mock(VcsProcess)({
run: mockedRun,
}),
),
),
);
function processOutput(stdout: string): VcsProcessOutput {
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}
afterEach(() => {
mockedRun.mockReset();
});
layer("GitLabCli.layer", (it) => {
it.effect("parses merge request view output", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
iid: 42,
title: "Add MR thread creation",
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
target_branch: "main",
source_branch: "feature/mr-threads",
state: "opened",
source_project_id: 101,
target_project_id: 100,
source_project: {
path_with_namespace: "octocat/t3code",
},
}),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getMergeRequest({
cwd: "/repo",
reference: "42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add MR thread creation",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/mr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/t3code",
headRepositoryOwnerLogin: "octocat",
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["mr", "view", "42", "--output", "json"],
}),
);
}),
);
it.effect("skips invalid entries when parsing MR lists", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify([
{
iid: 0,
title: "invalid",
web_url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/0",
target_branch: "main",
source_branch: "feature/invalid",
},
{
iid: 43,
title: " Valid MR ",
web_url: " https://gitlab.com/pingdotgg/t3code/-/merge_requests/43 ",
target_branch: " main ",
source_branch: " feature/mr-list ",
state: "merged",
},
]),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.listMergeRequests({
cwd: "/repo",
headSelector: "feature/mr-list",
state: "all",
});
});
assert.deepStrictEqual(result, [
{
number: 43,
title: "Valid MR",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/43",
baseRefName: "main",
headRefName: "feature/mr-list",
state: "merged",
},
]);
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"mr",
"list",
"--source-branch",
"feature/mr-list",
"--all",
"--per-page",
"20",
"--output",
"json",
],
}),
);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.succeed(
processOutput(
JSON.stringify({
path_with_namespace: "octocat/t3code",
web_url: "https://gitlab.com/octocat/t3code",
http_url_to_repo: "https://gitlab.com/octocat/t3code.git",
ssh_url_to_repo: "[email protected]:octocat/t3code.git",
}),
),
),
);
const result = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/t3code",
});
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/t3code",
url: "https://gitlab.com/octocat/t3code.git",
sshUrl: "[email protected]:octocat/t3code.git",
});
}),
);
it.effect("creates merge requests through the GitLab API without placing the body in argv", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("{}")));
const glab = yield* GitLabCli.GitLabCli;
yield* glab.createMergeRequest({
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
title: "Provider MR",
bodyFile: "/tmp/t3-mr-body.md",
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: [
"api",
"--method",
"POST",
"projects/:fullpath/merge_requests",
"--raw-field",
"source_branch=feature/provider",
"--raw-field",
"target_branch=main",
"--raw-field",
"title=Provider MR",
"--field",
"description=@/tmp/t3-mr-body.md",
],
}),
);
}),
);
it.effect("does not pass unsupported force flags when checking out merge requests", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(Effect.succeed(processOutput("")));
const glab = yield* GitLabCli.GitLabCli;
yield* glab.checkoutMergeRequest({
cwd: "/repo",
reference: "42",
force: true,
});
expect(mockedRun).toHaveBeenCalledWith(
expect.objectContaining({
command: "glab",
cwd: "/repo",
args: ["mr", "checkout", "42"],
}),
);
}),
);
it.effect("surfaces a friendly error when the merge request is not found", () =>
Effect.gen(function* () {
mockedRun.mockReturnValueOnce(
Effect.fail(
new VcsProcessExitError({
operation: "GitLabCli.execute",
command: "glab mr view 4888",
cwd: "/repo",
exitCode: 1,
detail: "GET 404 merge request not found",
}),
),
);
const error = yield* Effect.gen(function* () {
const glab = yield* GitLabCli.GitLabCli;
return yield* glab.getMergeRequest({
cwd: "/repo",
reference: "4888",
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Merge request not found"), true);
}),
);
});
+368
View File
@@ -0,0 +1,368 @@
import { Context, Effect, Layer, Option, Result, Schema, SchemaIssue, type DateTime } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import {
decodeGitLabMergeRequestJson,
decodeGitLabMergeRequestListJson,
formatGitLabJsonDecodeError,
} from "./gitLabMergeRequests.ts";
import { VcsProcess, type VcsProcessOutput } from "../vcs/VcsProcess.ts";
import type { SourceControlRefSelector } from "./SourceControlProvider.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
}
}
export interface GitLabMergeRequestSummary {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly updatedAt?: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitLabRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
export interface GitLabCliShape {
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<VcsProcessOutput, GitLabCliError>;
readonly listMergeRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly state: "open" | "closed" | "merged" | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;
readonly getMergeRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;
readonly createMergeRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
readonly target?: SourceControlRefSelector;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitLabCliError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitLabCliError>;
readonly checkoutMergeRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitLabCliError>;
}
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
"t3/source-control/GitLabCli",
) {}
function isVcsProcessSpawnError(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "VcsProcessSpawnError"
);
}
function normalizeGitLabCliError(operation: "execute" | "stdout", error: unknown): GitLabCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: glab") || isVcsProcessSpawnError(error)) {
return new GitLabCliError({
operation,
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
cause: error,
});
}
const lower = error.message.toLowerCase();
if (
lower.includes("authentication failed") ||
lower.includes("not logged in") ||
lower.includes("glab auth login") ||
lower.includes("token")
) {
return new GitLabCliError({
operation,
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
cause: error,
});
}
if (
lower.includes("merge request not found") ||
lower.includes("not found") ||
lower.includes("404")
) {
return new GitLabCliError({
operation,
detail: "Merge request not found. Check the MR number or URL and try again.",
cause: error,
});
}
return new GitLabCliError({
operation,
detail: `GitLab CLI command failed: ${error.message}`,
cause: error,
});
}
return new GitLabCliError({
operation,
detail: "GitLab CLI command failed.",
cause: error,
});
}
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
path_with_namespace: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
http_url_to_repo: TrimmedNonEmptyString,
ssh_url_to_repo: TrimmedNonEmptyString,
});
const RawGitLabDefaultBranchSchema = Schema.Struct({
default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
});
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
): GitLabRepositoryCloneUrls {
return {
nameWithOwner: raw.path_with_namespace,
url: raw.http_url_to_repo || raw.web_url,
sshUrl: raw.ssh_url_to_repo,
};
}
function decodeGitLabJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "getRepositoryCloneUrls" | "getDefaultBranch",
invalidDetail: string,
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitLabCliError({
operation,
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
cause: error,
}),
),
);
}
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
switch (state) {
case "open":
return [];
case "closed":
return ["--closed"];
case "merged":
return ["--merged"];
case "all":
return ["--all"];
}
}
function normalizeHeadSelector(headSelector: string): string {
const trimmed = headSelector.trim();
const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);
return ownerBranch?.[1]?.trim() || trimmed;
}
function sourceRefName(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): string {
return input.source?.refName ?? normalizeHeadSelector(input.headSelector);
}
function sourceProjectIdentifier(source: SourceControlRefSelector | undefined): string | null {
return source?.repository ?? source?.owner ?? null;
}
function toSummaryWithOptionalUpdatedAt(
record: GitLabMergeRequestSummary & {
readonly updatedAt: Option.Option<DateTime.Utc>;
},
): GitLabMergeRequestSummary {
const { updatedAt, ...summary } = record;
return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;
}
export const make = Effect.fn("makeGitLabCli")(function* () {
const process = yield* VcsProcess;
const execute: GitLabCliShape["execute"] = (input) =>
process
.run({
operation: "GitLabCli.execute",
command: "glab",
args: input.args,
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
})
.pipe(Effect.mapError((error) => normalizeGitLabCliError("execute", error)));
return GitLabCli.of({
execute,
listMergeRequests: (input) =>
execute({
cwd: input.cwd,
args: [
"mr",
"list",
"--source-branch",
sourceRefName(input),
...stateArgs(input.state),
"--per-page",
String(input.limit ?? 20),
"--output",
"json",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabCliError({
operation: "listMergeRequests",
detail: `GitLab CLI returned invalid MR list JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));
}),
),
),
),
getMergeRequest: (input) =>
execute({
cwd: input.cwd,
args: ["mr", "view", input.reference, "--output", "json"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
new GitLabCliError({
operation: "getMergeRequest",
detail: `GitLab CLI returned invalid merge request JSON: ${formatGitLabJsonDecodeError(decoded.failure)}`,
cause: decoded.failure,
}),
);
}
return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));
}),
),
),
),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["api", `projects/${encodeURIComponent(input.repository)}`],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createMergeRequest: (input) => {
const sourceProject = sourceProjectIdentifier(input.source);
return execute({
cwd: input.cwd,
args: [
"api",
"--method",
"POST",
"projects/:fullpath/merge_requests",
"--raw-field",
`source_branch=${sourceRefName(input)}`,
"--raw-field",
`target_branch=${input.target?.refName ?? input.baseBranch}`,
...(sourceProject ? ["--raw-field", `source_project_id=${sourceProject}`] : []),
"--raw-field",
`title=${input.title}`,
"--field",
`description=@${input.bodyFile}`,
],
}).pipe(Effect.asVoid);
},
getDefaultBranch: (input) =>
execute({
cwd: input.cwd,
args: ["api", "projects/:fullpath"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitLabJson(
raw,
RawGitLabDefaultBranchSchema,
"getDefaultBranch",
"GitLab CLI returned invalid repository JSON.",
),
),
Effect.map((value) => value.default_branch ?? null),
),
checkoutMergeRequest: (input) =>
execute({
cwd: input.cwd,
args: ["mr", "checkout", input.reference],
}).pipe(Effect.asVoid),
});
});
export const layer = Layer.effect(GitLabCli, make());
@@ -0,0 +1,105 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import { GitLabCli, type GitLabCliShape } from "./GitLabCli.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
function makeProvider(gitlab: Partial<GitLabCliShape>) {
return GitLabSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitLabCli)(gitlab)));
}
it.effect("maps GitLab MR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
getMergeRequest: () =>
Effect.succeed({
number: 42,
title: "Add GitLab provider",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
}),
});
const changeRequest = yield* provider.getChangeRequest({
cwd: "/repo",
reference: "42",
});
assert.deepStrictEqual(changeRequest, {
provider: "gitlab",
number: 42,
title: "Add GitLab provider",
url: "https://gitlab.com/pingdotgg/t3code/-/merge_requests/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
});
}),
);
it.effect("lists GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let listInput: Parameters<GitLabCliShape["listMergeRequests"]>[0] | null = null;
const provider = yield* makeProvider({
listMergeRequests: (input) => {
listInput = input;
return Effect.succeed([]);
},
});
yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/provider",
state: "all",
limit: 10,
});
assert.deepStrictEqual(listInput, {
cwd: "/repo",
headSelector: "feature/provider",
state: "all",
limit: 10,
});
}),
);
it.effect("creates GitLab MRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitLabCliShape["createMergeRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createMergeRequest: (input) => {
createInput = input;
return Effect.void;
},
});
yield* provider.createChangeRequest({
cwd: "/repo",
baseRefName: "main",
headSelector: "owner:feature/provider",
title: "Provider MR",
bodyFile: "/tmp/body.md",
});
assert.deepStrictEqual(createInput, {
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
source: {
owner: "owner",
refName: "feature/provider",
},
title: "Provider MR",
bodyFile: "/tmp/body.md",
});
}),
);
@@ -0,0 +1,106 @@
import { Effect, Layer, Option } from "effect";
import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
import { GitLabCli, type GitLabCliError, type GitLabMergeRequestSummary } from "./GitLabCli.ts";
import { SourceControlProvider, type SourceControlRefSelector } from "./SourceControlProvider.ts";
function providerError(operation: string, cause: GitLabCliError): SourceControlProviderError {
return new SourceControlProviderError({
provider: "gitlab",
operation,
detail: cause.detail,
cause,
});
}
function toChangeRequest(summary: GitLabMergeRequestSummary): ChangeRequest {
return {
provider: "gitlab",
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: summary.updatedAt ?? Option.none(),
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
...(summary.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
: {}),
...(summary.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
: {}),
};
}
function sourceFromInput(input: {
readonly headSelector: string;
readonly source?: SourceControlRefSelector;
}): SourceControlRefSelector | undefined {
if (input.source) {
return input.source;
}
const match = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
const owner = match?.[1]?.trim();
const refName = match?.[2]?.trim();
return owner && refName ? { owner, refName } : undefined;
}
export const make = Effect.fn("makeGitLabSourceControlProvider")(function* () {
const gitlab = yield* GitLabCli;
return SourceControlProvider.of({
kind: "gitlab",
listChangeRequests: (input) => {
const source = sourceFromInput(input);
return gitlab
.listMergeRequests({
cwd: input.cwd,
headSelector: input.headSelector,
...(source ? { source } : {}),
state: input.state,
...(input.limit !== undefined ? { limit: input.limit } : {}),
})
.pipe(
Effect.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
);
},
getChangeRequest: (input) =>
gitlab.getMergeRequest(input).pipe(
Effect.map(toChangeRequest),
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) => {
const source = sourceFromInput(input);
return gitlab
.createMergeRequest({
cwd: input.cwd,
baseBranch: input.baseRefName,
headSelector: input.headSelector,
...(source ? { source } : {}),
...(input.target ? { target: input.target } : {}),
title: input.title,
bodyFile: input.bodyFile,
})
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error)));
},
getRepositoryCloneUrls: (input) =>
gitlab
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
getDefaultBranch: (input) =>
gitlab
.getDefaultBranch(input)
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
checkoutChangeRequest: (input) =>
gitlab
.checkoutMergeRequest(input)
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
});
});
export const layer = Layer.effect(SourceControlProvider, make());
@@ -94,7 +94,7 @@ Logged in to github.com account juliusmarminge (keyring)
},
{
kind: "gitlab",
implemented: false,
implemented: true,
status: "missing",
auth: "unknown",
account: Option.none(),
@@ -83,7 +83,7 @@ const SOURCE_CONTROL_PROVIDER_PROBES: ReadonlyArray<ProviderProbe> = [
versionArgs: ["--version"],
authArgs: ["auth", "status"],
parseAuth: parseGitLabAuth,
implemented: false,
implemented: true,
installHint:
"Install GitLab CLI with `brew install glab` or from https://gitlab.com/gitlab-org/cli.",
},
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli } from "./GitHubCli.ts";
import { GitLabCli } from "./GitLabCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
@@ -50,7 +51,9 @@ function makeRegistry(input: {
});
return SourceControlProviderRegistry.make().pipe(
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
Effect.provide(
Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}), Layer.mock(GitLabCli)({})),
),
);
}
@@ -78,27 +81,16 @@ it.effect("routes directly by provider kind for remote-first workflows", () =>
}),
);
it.effect(
"detects GitLab remotes and returns an unsupported provider until one is registered",
() =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
it.effect("routes GitLab remotes to the GitLab provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "gitlab");
const error = yield* Effect.flip(
provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/source-control",
state: "open",
}),
);
assert.strictEqual(error.provider, "gitlab");
}),
assert.strictEqual(provider.kind, "gitlab");
}),
);
it.effect("falls back to a non-origin remote when origin is not configured", () =>
@@ -9,6 +9,7 @@ import {
type SourceControlProviderShape,
} from "./SourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import * as GitLabSourceControlProvider from "./GitLabSourceControlProvider.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
@@ -151,11 +152,16 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
const github = yield* GitHubSourceControlProvider.make();
const gitlab = yield* GitLabSourceControlProvider.make();
return yield* makeWithProviders([
{
kind: "github",
provider: github,
},
{
kind: "gitlab",
provider: gitlab,
},
]);
});
@@ -0,0 +1,148 @@
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
export interface NormalizedGitLabMergeRequestRecord {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state: "open" | "closed" | "merged";
readonly updatedAt: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
const GitLabProjectReferenceSchema = Schema.Struct({
path_with_namespace: Schema.optional(Schema.String),
pathWithNamespace: Schema.optional(Schema.String),
namespace: Schema.optional(
Schema.NullOr(
Schema.Struct({
path: Schema.optional(Schema.String),
full_path: Schema.optional(Schema.String),
fullPath: Schema.optional(Schema.String),
}),
),
),
});
const GitLabMergeRequestSchema = Schema.Struct({
iid: PositiveInt,
title: TrimmedNonEmptyString,
web_url: TrimmedNonEmptyString,
source_branch: TrimmedNonEmptyString,
target_branch: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
source_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
target_project_id: Schema.optional(Schema.NullOr(Schema.Number)),
source_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
target_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),
});
function trimOptionalString(value: string | null | undefined): string | null {
const trimmed = value?.trim() ?? "";
return trimmed.length > 0 ? trimmed : null;
}
function normalizeGitLabMergeRequestState(
state: string | null | undefined,
): "open" | "closed" | "merged" {
const normalized = state?.trim().toLowerCase();
if (normalized === "merged") {
return "merged";
}
if (normalized === "closed") {
return "closed";
}
return "open";
}
function projectPathWithNamespace(
project: Schema.Schema.Type<typeof GitLabProjectReferenceSchema> | null | undefined,
): string | null {
const explicit =
trimOptionalString(project?.path_with_namespace) ??
trimOptionalString(project?.pathWithNamespace);
if (explicit) {
return explicit;
}
const namespacePath =
trimOptionalString(project?.namespace?.full_path) ??
trimOptionalString(project?.namespace?.fullPath) ??
trimOptionalString(project?.namespace?.path);
return namespacePath;
}
function ownerLoginFromPathWithNamespace(pathWithNamespace: string | null): string | null {
const [owner] = pathWithNamespace?.split("/") ?? [];
return trimOptionalString(owner);
}
function normalizeGitLabMergeRequestRecord(
raw: Schema.Schema.Type<typeof GitLabMergeRequestSchema>,
): NormalizedGitLabMergeRequestRecord {
const sourceProjectPath = projectPathWithNamespace(raw.source_project);
const targetProjectPath = projectPathWithNamespace(raw.target_project);
const isCrossRepository =
typeof raw.source_project_id === "number" && typeof raw.target_project_id === "number"
? raw.source_project_id !== raw.target_project_id
: sourceProjectPath !== null && targetProjectPath !== null
? sourceProjectPath.toLowerCase() !== targetProjectPath.toLowerCase()
: undefined;
const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);
return {
number: raw.iid,
title: raw.title,
url: raw.web_url,
baseRefName: raw.target_branch,
headRefName: raw.source_branch,
state: normalizeGitLabMergeRequestState(raw.state),
updatedAt: raw.updated_at ?? Option.none(),
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
const decodeGitLabMergeRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeGitLabMergeRequest = decodeJsonResult(GitLabMergeRequestSchema);
const decodeGitLabMergeRequestEntry = Schema.decodeUnknownExit(GitLabMergeRequestSchema);
export const formatGitLabJsonDecodeError = formatSchemaError;
export function decodeGitLabMergeRequestListJson(
raw: string,
): Result.Result<
ReadonlyArray<NormalizedGitLabMergeRequestRecord>,
Cause.Cause<Schema.SchemaError>
> {
const result = decodeGitLabMergeRequestList(raw);
if (Result.isSuccess(result)) {
const mergeRequests: NormalizedGitLabMergeRequestRecord[] = [];
for (const entry of result.success) {
const decodedEntry = decodeGitLabMergeRequestEntry(entry);
if (Exit.isFailure(decodedEntry)) {
continue;
}
mergeRequests.push(normalizeGitLabMergeRequestRecord(decodedEntry.value));
}
return Result.succeed(mergeRequests);
}
return Result.fail(result.failure);
}
export function decodeGitLabMergeRequestJson(
raw: string,
): Result.Result<NormalizedGitLabMergeRequestRecord, Cause.Cause<Schema.SchemaError>> {
const result = decodeGitLabMergeRequest(raw);
if (Result.isSuccess(result)) {
return Result.succeed(normalizeGitLabMergeRequestRecord(result.success));
}
return Result.fail(result.failure);
}
+11
View File
@@ -55,6 +55,7 @@ export interface GitStatusDetails {
hasUpstream: boolean;
aheadCount: number;
behindCount: number;
aheadOfDefaultCount: number;
}
export interface GitPreparedCommitContext {
@@ -133,6 +134,12 @@ export interface GitFetchRemoteBranchInput {
localBranch: string;
}
export interface GitFetchRemoteTrackingBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
@@ -176,9 +183,13 @@ export interface GitVcsDriverShape {
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly fetchRemoteTrackingBranch: (
input: GitFetchRemoteTrackingBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
@@ -102,6 +102,51 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
);
}),
);
it.effect("reports default-branch delta separately from upstream delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/synced"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
yield* git(cwd, ["push", "-u", "origin", "feature/synced"]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.hasUpstream, true);
assert.equal(status.aheadCount, 0);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/no-upstream"]);
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* git(cwd, ["add", "feature.txt"]);
yield* git(cwd, ["commit", "-m", "feature commit"]);
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.hasUpstream, false);
assert.equal(status.aheadCount, 1);
assert.equal(status.behindCount, 0);
assert.equal(status.aheadOfDefaultCount, 1);
}),
);
});
describe("refName operations", () => {
@@ -242,5 +287,44 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
}),
);
it.effect(
"pushes upstream branches to the remote branch name, not the upstream shorthand",
() =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-remote-");
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* git(cwd, ["branch", "-M", "main"]);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", "main"]);
yield* writeTextFile(cwd, "upstream.txt", "upstream\n");
yield* driver.prepareCommitContext(cwd);
yield* driver.commit(cwd, "Add upstream update", "");
const pushed = yield* driver.pushCurrentBranch(cwd, null);
assert.deepInclude(pushed, {
status: "pushed",
branch: "main",
upstreamBranch: "origin/main",
setUpstream: false,
});
assert.equal(
yield* git(remote, ["log", "-1", "--pretty=%s", "main"]),
"Add upstream update",
);
const badBranch = yield* driver.execute({
operation: "GitVcsDriver.test.showBadRemoteBranch",
cwd: remote,
args: ["show-ref", "--verify", "--quiet", "refs/heads/origin/main"],
allowNonZeroExit: true,
timeoutMs: 10_000,
});
assert.notEqual(badBranch.exitCode, 0);
}),
);
});
});
+54 -11
View File
@@ -62,6 +62,7 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
});
type TraceTailState = {
@@ -969,6 +970,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
Effect.map(parseRemoteNamesInGitOrder),
);
const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* (
cwd: string,
branchName: string,
) {
const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.catch(() => Effect.succeed([])));
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);
return parsedRemoteRef?.branchName ?? branchName;
});
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
if (yield* originRemoteExists(cwd)) {
return "origin";
@@ -1213,6 +1223,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
let upstreamRef: string | null = null;
let aheadCount = 0;
let behindCount = 0;
let aheadOfDefaultCount = 0;
let hasWorkingTreeChanges = false;
const changedFilesWithoutNumstat = new Set<string>();
@@ -1241,13 +1252,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
}
if (!upstreamRef && refName) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, refName).pipe(
Effect.catch(() => Effect.succeed(0)),
);
const fallbackAheadCount =
!upstreamRef && refName
? yield* computeAheadCountAgainstBase(cwd, refName).pipe(
Effect.catch(() => Effect.succeed(0)),
)
: null;
if (fallbackAheadCount !== null) {
aheadCount = fallbackAheadCount;
behindCount = 0;
}
const isDefaultBranch =
refName !== null &&
(refName === defaultBranch ||
(defaultBranch === null && (refName === "main" || refName === "master")));
if (refName && !isDefaultBranch) {
aheadOfDefaultCount =
fallbackAheadCount !== null
? fallbackAheadCount
: yield* computeAheadCountAgainstBase(cwd, refName).pipe(
Effect.catch(() => Effect.succeed(0)),
);
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
@@ -1277,10 +1306,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return {
isRepo: true,
hasOriginRemote: hasPrimaryRemote,
isDefaultBranch:
refName !== null &&
(refName === defaultBranch ||
(defaultBranch === null && (refName === "main" || refName === "master"))),
isDefaultBranch,
branch: refName,
upstreamRef,
hasWorkingTreeChanges,
@@ -1292,6 +1318,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
hasUpstream: upstreamRef !== null,
aheadCount,
behindCount,
aheadOfDefaultCount,
};
});
@@ -1323,6 +1350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
hasUpstream: details.hasUpstream,
aheadCount: details.aheadCount,
behindCount: details.behindCount,
aheadOfDefaultCount: details.aheadOfDefaultCount,
pr: null,
})),
);
@@ -1461,16 +1489,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
"Cannot push because no git remote is configured for this repository.",
);
}
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
yield* runGit("GitVcsDriver.pushCurrentBranch.pushWithUpstream", cwd, [
"push",
"-u",
publishRemoteName,
`HEAD:refs/heads/${branch}`,
`HEAD:refs/heads/${publishBranch}`,
]);
return {
status: "pushed" as const,
branch,
upstreamBranch: `${publishRemoteName}/${branch}`,
upstreamBranch: `${publishRemoteName}/${publishBranch}`,
setUpstream: true,
};
}
@@ -1482,7 +1511,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
yield* runGit("GitVcsDriver.pushCurrentBranch.pushUpstream", cwd, [
"push",
currentUpstream.remoteName,
`HEAD:${currentUpstream.upstreamRef}`,
`HEAD:refs/heads/${currentUpstream.branchName}`,
]);
return {
status: "pushed" as const,
@@ -1894,6 +1923,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
},
);
const fetchRemoteTrackingBranch: GitVcsDriverShape["fetchRemoteTrackingBranch"] = Effect.fn(
"fetchRemoteTrackingBranch",
)(function* (input) {
yield* runGit("GitVcsDriver.fetchRemoteTrackingBranch", input.cwd, [
"fetch",
"--quiet",
"--no-tags",
input.remoteName,
`+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,
]);
});
const setBranchUpstream: GitVcsDriverShape["setBranchUpstream"] = (input) =>
runGit("GitVcsDriver.setBranchUpstream", input.cwd, [
"branch",
@@ -2075,7 +2116,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
createWorktree,
fetchPullRequestBranch,
ensureRemote,
resolvePrimaryRemoteName,
fetchRemoteBranch,
fetchRemoteTrackingBranch,
setBranchUpstream,
removeWorktree,
renameBranch,
@@ -2,16 +2,17 @@ import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveEnvironmentOptionLabel,
resolveBranchSelectionTarget,
resolveCurrentWorkspaceLabel,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
resolveEnvModeLabel,
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
resolveLocalCheckoutRefMismatch,
resolveLocalRefNameFromRemoteRef,
resolveRefSelectionTarget,
resolveRefToolbarValue,
shouldIncludeRefPickerItem,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -49,41 +50,90 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
});
});
describe("resolveBranchToolbarValue", () => {
it("defaults new-worktree mode to current git ref when no explicit base ref is set", () => {
describe("resolveRefToolbarValue", () => {
it("defaults new-worktree mode to current ref when no explicit base ref is set", () => {
expect(
resolveBranchToolbarValue({
resolveRefToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: null,
currentGitBranch: "main",
activeThreadRefName: null,
currentRefName: "main",
}),
).toBe("main");
});
it("keeps an explicitly selected worktree base ref", () => {
expect(
resolveBranchToolbarValue({
resolveRefToolbarValue({
envMode: "worktree",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
activeThreadRefName: "feature/base",
currentRefName: "main",
}),
).toBe("feature/base");
});
it("shows the actual checked-out ref when not selecting a new worktree base", () => {
expect(
resolveBranchToolbarValue({
resolveRefToolbarValue({
envMode: "local",
activeWorktreePath: null,
activeThreadBranch: "feature/base",
currentGitBranch: "main",
activeThreadRefName: "feature/base",
currentRefName: "main",
}),
).toBe("main");
});
});
describe("resolveLocalCheckoutRefMismatch", () => {
it("detects when a local thread is associated with a different ref than the checkout", () => {
expect(
resolveLocalCheckoutRefMismatch({
effectiveEnvMode: "local",
activeWorktreePath: null,
activeThreadRefName: "feature/thread",
currentRefName: "feature/current",
}),
).toEqual({
threadRefName: "feature/thread",
currentRefName: "feature/current",
});
});
it("ignores matching local checkout state", () => {
expect(
resolveLocalCheckoutRefMismatch({
effectiveEnvMode: "local",
activeWorktreePath: null,
activeThreadRefName: "feature/thread",
currentRefName: "feature/thread",
}),
).toBeNull();
});
it("ignores dedicated worktrees because their checkout is already thread-scoped", () => {
expect(
resolveLocalCheckoutRefMismatch({
effectiveEnvMode: "worktree",
activeWorktreePath: "/repo/.t3/worktrees/feature-thread",
activeThreadRefName: "feature/thread",
currentRefName: "feature/current",
}),
).toBeNull();
});
it("ignores new-worktree base selection before a worktree exists", () => {
expect(
resolveLocalCheckoutRefMismatch({
effectiveEnvMode: "worktree",
activeWorktreePath: null,
activeThreadRefName: "feature/base",
currentRefName: "main",
}),
).toBeNull();
});
});
describe("resolveEnvironmentOptionLabel", () => {
it("prefers the primary environment's machine label", () => {
expect(
@@ -168,20 +218,46 @@ describe("resolveLockedWorkspaceLabel", () => {
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
describe("resolveLocalRefNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref using structured metadata", () => {
expect(
resolveLocalRefNameFromRemoteRef({
name: "origin/feature/demo",
remoteName: "origin",
}),
).toBe("feature/demo");
});
it("supports remote names that contain slashes", () => {
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
"upstream/feature/demo",
);
it("supports remote names that contain slashes through the remoteName field", () => {
expect(
resolveLocalRefNameFromRemoteRef({
name: "my-org/upstream/feature/demo",
remoteName: "my-org/upstream",
}),
).toBe("feature/demo");
});
it("returns the original name when ref is malformed", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
it("returns the original name when remote metadata is unavailable", () => {
expect(
resolveLocalRefNameFromRemoteRef({
name: "origin/feature/demo",
}),
).toBe("origin/feature/demo");
});
it("returns the original name when the remote prefix is malformed", () => {
expect(
resolveLocalRefNameFromRemoteRef({
name: "origin/",
remoteName: "origin",
}),
).toBe("origin/");
expect(
resolveLocalRefNameFromRemoteRef({
name: "/feature/demo",
remoteName: "origin",
}),
).toBe("/feature/demo");
});
});
@@ -291,13 +367,13 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
});
});
describe("resolveBranchSelectionTarget", () => {
describe("resolveRefSelectionTarget", () => {
it("reuses an existing secondary worktree for the selected ref", () => {
expect(
resolveBranchSelectionTarget({
resolveRefSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
refName: {
ref: {
isDefault: false,
worktreePath: "/repo/.t3/worktrees/feature-b",
},
@@ -311,10 +387,10 @@ describe("resolveBranchSelectionTarget", () => {
it("switches back to the main repo when the ref already lives there", () => {
expect(
resolveBranchSelectionTarget({
resolveRefSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
refName: {
ref: {
isDefault: true,
worktreePath: "/repo",
},
@@ -328,10 +404,10 @@ describe("resolveBranchSelectionTarget", () => {
it("checks out the default ref in the main repo when leaving a secondary worktree", () => {
expect(
resolveBranchSelectionTarget({
resolveRefSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
refName: {
ref: {
isDefault: true,
worktreePath: null,
},
@@ -345,10 +421,10 @@ describe("resolveBranchSelectionTarget", () => {
it("keeps checkout in the current worktree for non-default refs", () => {
expect(
resolveBranchSelectionTarget({
resolveRefSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
refName: {
ref: {
isDefault: false,
worktreePath: null,
},
@@ -361,36 +437,36 @@ describe("resolveBranchSelectionTarget", () => {
});
});
describe("shouldIncludeBranchPickerItem", () => {
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
describe("shouldIncludeRefPickerItem", () => {
it("keeps the synthetic checkout change request item visible for change request input", () => {
expect(
shouldIncludeBranchPickerItem({
shouldIncludeRefPickerItem({
itemValue: "__checkout_pull_request__:1359",
normalizedQuery: "gh pr checkout 1359",
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
createRefItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutChangeRequestItemValue: "__checkout_pull_request__:1359",
}),
).toBe(true);
});
it("keeps the synthetic create-ref item visible for arbitrary ref input", () => {
expect(
shouldIncludeBranchPickerItem({
shouldIncludeRefPickerItem({
itemValue: "__create_new_branch__:feature/demo",
normalizedQuery: "feature/demo",
createBranchItemValue: "__create_new_branch__:feature/demo",
checkoutPullRequestItemValue: null,
createRefItemValue: "__create_new_branch__:feature/demo",
checkoutChangeRequestItemValue: null,
}),
).toBe(true);
});
it("still filters ordinary ref items by query text", () => {
expect(
shouldIncludeBranchPickerItem({
shouldIncludeRefPickerItem({
itemValue: "main",
normalizedQuery: "gh pr checkout 1359",
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
createRefItemValue: "__create_new_branch__:gh pr checkout 1359",
checkoutChangeRequestItemValue: "__checkout_pull_request__:1359",
}),
).toBe(false);
});
+102 -24
View File
@@ -1,9 +1,6 @@
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "@t3tools/shared/git";
export { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
export interface EnvironmentOption {
environmentId: EnvironmentId;
@@ -84,40 +81,55 @@ export function resolveDraftEnvModeAfterBranchChange(input: {
return "local";
}
export function resolveBranchToolbarValue(input: {
export function resolveRefToolbarValue(input: {
envMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
activeThreadRefName: string | null;
currentRefName: string | null;
}): string | null {
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
const { envMode, activeWorktreePath, activeThreadRefName, currentRefName } = input;
if (envMode === "worktree" && !activeWorktreePath) {
return activeThreadBranch ?? currentGitBranch;
return activeThreadRefName ?? currentRefName;
}
return currentGitBranch ?? activeThreadBranch;
return currentRefName ?? activeThreadRefName;
}
export function resolveBranchSelectionTarget(input: {
export function resolveLocalCheckoutRefMismatch(input: {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
activeThreadRefName: string | null;
currentRefName: string | null;
}): { threadRefName: string; currentRefName: string } | null {
const { effectiveEnvMode, activeWorktreePath, activeThreadRefName, currentRefName } = input;
if (effectiveEnvMode !== "local" || activeWorktreePath !== null) {
return null;
}
if (!activeThreadRefName || !currentRefName || activeThreadRefName === currentRefName) {
return null;
}
return { threadRefName: activeThreadRefName, currentRefName };
}
export function resolveRefSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
refName: Pick<VcsRef, "isDefault" | "worktreePath">;
ref: Pick<VcsRef, "isDefault" | "worktreePath">;
}): {
checkoutCwd: string;
nextWorktreePath: string | null;
reuseExistingWorktree: boolean;
} {
const { activeProjectCwd, activeWorktreePath, refName } = input;
const { activeProjectCwd, activeWorktreePath, ref } = input;
if (refName.worktreePath) {
if (ref.worktreePath) {
return {
checkoutCwd: refName.worktreePath,
nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
checkoutCwd: ref.worktreePath,
nextWorktreePath: ref.worktreePath === activeProjectCwd ? null : ref.worktreePath,
reuseExistingWorktree: true,
};
}
const nextWorktreePath =
activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
const nextWorktreePath = activeWorktreePath !== null && ref.isDefault ? null : activeWorktreePath;
return {
checkoutCwd: nextWorktreePath ?? activeProjectCwd,
@@ -126,25 +138,91 @@ export function resolveBranchSelectionTarget(input: {
};
}
export function shouldIncludeBranchPickerItem(input: {
export function shouldIncludeRefPickerItem(input: {
itemValue: string;
normalizedQuery: string;
createBranchItemValue: string | null;
checkoutPullRequestItemValue: string | null;
createRefItemValue: string | null;
checkoutChangeRequestItemValue: string | null;
}): boolean {
const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
const { itemValue, normalizedQuery, createRefItemValue, checkoutChangeRequestItemValue } = input;
if (normalizedQuery.length === 0) {
return true;
}
if (createBranchItemValue && itemValue === createBranchItemValue) {
if (createRefItemValue && itemValue === createRefItemValue) {
return true;
}
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
if (checkoutChangeRequestItemValue && itemValue === checkoutChangeRequestItemValue) {
return true;
}
return itemValue.toLowerCase().includes(normalizedQuery);
}
export function resolveLocalRefNameFromRemoteRef(ref: Pick<VcsRef, "name" | "remoteName">): string {
const remotePrefix = ref.remoteName ? `${ref.remoteName}/` : "";
if (remotePrefix.length > 0 && ref.name.startsWith(remotePrefix)) {
const localName = ref.name.slice(remotePrefix.length);
return localName.length > 0 ? localName : ref.name;
}
return ref.name;
}
export const resolveBranchToolbarValue = (input: {
envMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
}) =>
resolveRefToolbarValue({
envMode: input.envMode,
activeWorktreePath: input.activeWorktreePath,
activeThreadRefName: input.activeThreadBranch,
currentRefName: input.currentGitBranch,
});
export const resolveLocalCheckoutBranchMismatch = (input: {
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
activeThreadBranch: string | null;
currentGitBranch: string | null;
}) => {
const mismatch = resolveLocalCheckoutRefMismatch({
effectiveEnvMode: input.effectiveEnvMode,
activeWorktreePath: input.activeWorktreePath,
activeThreadRefName: input.activeThreadBranch,
currentRefName: input.currentGitBranch,
});
return mismatch
? {
threadBranch: mismatch.threadRefName,
currentBranch: mismatch.currentRefName,
}
: null;
};
export const resolveBranchSelectionTarget = (input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
refName: Pick<VcsRef, "isDefault" | "worktreePath">;
}) =>
resolveRefSelectionTarget({
activeProjectCwd: input.activeProjectCwd,
activeWorktreePath: input.activeWorktreePath,
ref: input.refName,
});
export const shouldIncludeBranchPickerItem = (input: {
itemValue: string;
normalizedQuery: string;
createBranchItemValue: string | null;
checkoutPullRequestItemValue: string | null;
}) =>
shouldIncludeRefPickerItem({
itemValue: input.itemValue,
normalizedQuery: input.normalizedQuery,
createRefItemValue: input.createBranchItemValue,
checkoutChangeRequestItemValue: input.checkoutPullRequestItemValue,
});
@@ -2,7 +2,7 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon } from "lucide-react";
import { ChevronDownIcon, TriangleAlertIcon } from "lucide-react";
import {
useCallback,
useDeferredValue,
@@ -16,21 +16,21 @@ import {
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { readEnvironmentApi } from "../environmentApi";
import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
import { useGitStatus } from "../lib/gitStatusState";
import { newCommandId } from "../lib/utils";
import { cn } from "../lib/utils";
import { vcsQueryKeys, vcsRefSearchInfiniteQueryOptions } from "../lib/vcsReactQuery";
import { refreshVcsStatus, useVcsStatus } from "../lib/vcsStatusState";
import { cn, newCommandId } from "../lib/utils";
import { parsePullRequestReference } from "../pullRequestReference";
import { getSourceControlPresentation } from "../sourceControlPresentation";
import { useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import {
deriveLocalBranchNameFromRemoteRef,
resolveBranchSelectionTarget,
resolveBranchToolbarValue,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
shouldIncludeBranchPickerItem,
resolveLocalCheckoutRefMismatch,
resolveLocalRefNameFromRemoteRef,
resolveRefSelectionTarget,
resolveRefToolbarValue,
shouldIncludeRefPickerItem,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
@@ -44,6 +44,7 @@ import {
ComboboxStatus,
ComboboxTrigger,
} from "./ui/combobox";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { stackedThreadToast, toastManager } from "./ui/toast";
interface BranchToolbarBranchSelectorProps {
@@ -59,23 +60,23 @@ interface BranchToolbarBranchSelectorProps {
onComposerFocusRequest?: () => void;
}
function toBranchActionErrorMessage(error: unknown): string {
function toRefActionErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : "An error occurred.";
}
function getBranchTriggerLabel(input: {
function getRefTriggerLabel(input: {
activeWorktreePath: string | null;
effectiveEnvMode: "local" | "worktree";
resolvedActiveBranch: string | null;
resolvedActiveRefName: string | null;
}): string {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
if (!resolvedActiveBranch) {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveRefName } = input;
if (!resolvedActiveRefName) {
return "Select ref";
}
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
return `From ${resolvedActiveBranch}`;
return `From ${resolvedActiveRefName}`;
}
return resolvedActiveBranch;
return resolvedActiveRefName;
}
export function BranchToolbarBranchSelector({
@@ -124,7 +125,7 @@ export function BranchToolbarBranchSelector({
: (serverThread?.branch ?? draftThread?.branch ?? null);
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const activeProjectCwd = activeProject?.cwd ?? null;
const branchCwd = activeWorktreePath ?? activeProjectCwd;
const refCwd = activeWorktreePath ?? activeProjectCwd;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode =
effectiveEnvModeOverride ??
@@ -135,7 +136,7 @@ export function BranchToolbarBranchSelector({
});
// ---------------------------------------------------------------------------
// Thread branch mutation (colocated — only this component calls it)
// Thread ref metadata mutation (colocated — only this component calls it)
// ---------------------------------------------------------------------------
const setThreadBranch = useCallback(
(branch: string | null, worktreePath: string | null) => {
@@ -194,177 +195,184 @@ export function BranchToolbarBranchSelector({
);
// ---------------------------------------------------------------------------
// Git ref queries
// VCS ref queries
// ---------------------------------------------------------------------------
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const deferredBranchQuery = useDeferredValue(branchQuery);
const [isRefMenuOpen, setIsRefMenuOpen] = useState(false);
const [isMismatchPopoverOpen, setIsMismatchPopoverOpen] = useState(false);
const [refQuery, setRefQuery] = useState("");
const refPickerAnchorRef = useRef<HTMLDivElement | null>(null);
const deferredRefQuery = useDeferredValue(refQuery);
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
const vcsStatusQuery = useVcsStatus({ environmentId, cwd: refCwd });
const trimmedRefQuery = refQuery.trim();
const deferredTrimmedRefQuery = deferredRefQuery.trim();
useEffect(() => {
if (!branchCwd) return;
if (!refCwd) return;
void queryClient.prefetchInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({ environmentId, cwd: branchCwd, query: "" }),
vcsRefSearchInfiniteQueryOptions({ environmentId, cwd: refCwd, query: "" }),
);
}, [branchCwd, environmentId, queryClient]);
}, [refCwd, environmentId, queryClient]);
const {
data: branchesSearchData,
data: refsSearchData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isPending: isBranchesSearchPending,
isPending: isRefsSearchPending,
} = useInfiniteQuery(
gitBranchSearchInfiniteQueryOptions({
vcsRefSearchInfiniteQueryOptions({
environmentId,
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
cwd: refCwd,
query: deferredTrimmedRefQuery,
}),
);
const refs = useMemo(
() => branchesSearchData?.pages.flatMap((page) => page.refs) ?? [],
[branchesSearchData?.pages],
() => refsSearchData?.pages.flatMap((page) => page.refs) ?? [],
[refsSearchData?.pages],
);
const currentGitBranch =
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
const currentRefName =
vcsStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
const sourceControlPresentation = useMemo(
() => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
[branchStatusQuery.data?.sourceControlProvider],
() => getSourceControlPresentation(vcsStatusQuery.data?.sourceControlProvider),
[vcsStatusQuery.data?.sourceControlProvider],
);
const SourceControlIcon = sourceControlPresentation.Icon;
const canonicalActiveBranch = resolveBranchToolbarValue({
const canonicalActiveRefName = resolveRefToolbarValue({
envMode: effectiveEnvMode,
activeWorktreePath,
activeThreadBranch,
currentGitBranch,
activeThreadRefName: activeThreadBranch,
currentRefName,
});
const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
const branchByName = useMemo(
const localCheckoutRefMismatch = resolveLocalCheckoutRefMismatch({
effectiveEnvMode,
activeWorktreePath,
activeThreadRefName: activeThreadBranch,
currentRefName,
});
const refNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
const refByName = useMemo(
() => new Map(refs.map((refName) => [refName.name, refName] as const)),
[refs],
);
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
const normalizedDeferredRefQuery = deferredTrimmedRefQuery.toLowerCase();
const changeRequestReference = parsePullRequestReference(trimmedRefQuery);
const isSelectingWorktreeBase =
effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
const checkoutPullRequestItemValue =
prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
: null;
const branchPickerItems = useMemo(() => {
const items = [...branchNames];
if (createBranchItemValue && !hasExactBranchMatch) {
items.push(createBranchItemValue);
const checkoutChangeRequestItemValue =
changeRequestReference && onCheckoutPullRequestRequest
? `__checkout_change_request__:${changeRequestReference}`
: null;
const canCreateRef = !isSelectingWorktreeBase && trimmedRefQuery.length > 0;
const hasExactRefMatch = refByName.has(trimmedRefQuery);
const createRefItemValue = canCreateRef ? `__create_new_ref__:${trimmedRefQuery}` : null;
const refPickerItems = useMemo(() => {
const items = [...refNames];
if (createRefItemValue && !hasExactRefMatch) {
items.push(createRefItemValue);
}
if (checkoutPullRequestItemValue) {
items.unshift(checkoutPullRequestItemValue);
if (checkoutChangeRequestItemValue) {
items.unshift(checkoutChangeRequestItemValue);
}
return items;
}, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
const filteredBranchPickerItems = useMemo(
}, [refNames, checkoutChangeRequestItemValue, createRefItemValue, hasExactRefMatch]);
const filteredRefPickerItems = useMemo(
() =>
normalizedDeferredBranchQuery.length === 0
? branchPickerItems
: branchPickerItems.filter((itemValue) =>
shouldIncludeBranchPickerItem({
normalizedDeferredRefQuery.length === 0
? refPickerItems
: refPickerItems.filter((itemValue) =>
shouldIncludeRefPickerItem({
itemValue,
normalizedQuery: normalizedDeferredBranchQuery,
createBranchItemValue,
checkoutPullRequestItemValue,
normalizedQuery: normalizedDeferredRefQuery,
createRefItemValue,
checkoutChangeRequestItemValue,
}),
),
[
branchPickerItems,
checkoutPullRequestItemValue,
createBranchItemValue,
normalizedDeferredBranchQuery,
refPickerItems,
checkoutChangeRequestItemValue,
createRefItemValue,
normalizedDeferredRefQuery,
],
);
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
const [resolvedActiveRefName, setOptimisticRefName] = useOptimistic(
canonicalActiveRefName,
(_currentRefName: string | null, optimisticRefName: string | null) => optimisticRefName,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
const [isRefActionPending, startRefActionTransition] = useTransition();
const shouldVirtualizeRefList = filteredRefPickerItems.length > 40;
const totalRefCount = refsSearchData?.pages[0]?.totalCount ?? 0;
const refStatusText = isRefsSearchPending
? "Loading refs..."
: isFetchingNextPage
? "Loading more refs..."
: hasNextPage
? `Showing ${refs.length} of ${totalBranchCount} refs`
? `Showing ${refs.length} of ${totalRefCount} refs`
: null;
// ---------------------------------------------------------------------------
// Branch actions
// Ref actions
// ---------------------------------------------------------------------------
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
const runRefAction = (action: () => Promise<void>) => {
startRefActionTransition(async () => {
await action().catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, branchCwd) })
.invalidateQueries({ queryKey: vcsQueryKeys.refs(environmentId, refCwd) })
.catch(() => undefined);
await refreshVcsStatus({ environmentId, cwd: refCwd }).catch(() => undefined);
});
};
const selectBranch = (refName: VcsRef) => {
const selectRef = (ref: VcsRef) => {
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
if (!api || !refCwd || !activeProjectCwd || isRefActionPending) return;
if (isSelectingWorktreeBase) {
setThreadBranch(refName.name, null);
setIsBranchMenuOpen(false);
setThreadBranch(ref.name, null);
setIsRefMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectionTarget = resolveBranchSelectionTarget({
const selectionTarget = resolveRefSelectionTarget({
activeProjectCwd,
activeWorktreePath,
refName,
ref,
});
if (selectionTarget.reuseExistingWorktree) {
setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
setIsBranchMenuOpen(false);
setThreadBranch(ref.name, selectionTarget.nextWorktreePath);
setIsRefMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectedBranchName = refName.isRemote
? deriveLocalBranchNameFromRemoteRef(refName.name)
: refName.name;
const selectedRefName = ref.isRemote ? resolveLocalRefNameFromRemoteRef(ref) : ref.name;
setIsBranchMenuOpen(false);
setIsRefMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
runRefAction(async () => {
const previousRefName = resolvedActiveRefName;
setOptimisticRefName(selectedRefName);
try {
const checkoutResult = await api.vcs.switchRef({
cwd: selectionTarget.checkoutCwd,
refName: refName.name,
refName: ref.name,
});
const nextBranchName = refName.isRemote
? (checkoutResult.refName ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
const nextRefName = ref.isRemote
? (checkoutResult.refName ?? selectedRefName)
: selectedRefName;
setOptimisticRefName(nextRefName);
setThreadBranch(nextRefName, selectionTarget.nextWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
setOptimisticRefName(previousRefName);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to switch ref.",
description: toBranchActionErrorMessage(error),
description: toRefActionErrorMessage(error),
}),
);
}
@@ -374,71 +382,111 @@ export function BranchToolbarBranchSelector({
const createRef = (rawName: string) => {
const name = rawName.trim();
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || !name || isBranchActionPending) return;
if (!api || !refCwd || !name || isRefActionPending) return;
setIsBranchMenuOpen(false);
setIsRefMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
runRefAction(async () => {
const previousRefName = resolvedActiveRefName;
setOptimisticRefName(name);
try {
const createBranchResult = await api.vcs.createRef({
cwd: branchCwd,
const createRefResult = await api.vcs.createRef({
cwd: refCwd,
refName: name,
switchRef: true,
});
setOptimisticBranch(createBranchResult.refName);
setThreadBranch(createBranchResult.refName, activeWorktreePath);
setOptimisticRefName(createRefResult.refName);
setThreadBranch(createRefResult.refName, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
setOptimisticRefName(previousRefName);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to create and switch ref.",
description: toBranchActionErrorMessage(error),
description: toRefActionErrorMessage(error),
}),
);
}
});
};
const switchCheckoutToThreadBranch = () => {
const api = readEnvironmentApi(environmentId);
if (!api || !activeProjectCwd || !localCheckoutRefMismatch || isRefActionPending) {
return;
}
runRefAction(async () => {
const previousRefName = resolvedActiveRefName;
setOptimisticRefName(localCheckoutRefMismatch.threadRefName);
try {
const switchResult = await api.vcs.switchRef({
cwd: activeProjectCwd,
refName: localCheckoutRefMismatch.threadRefName,
});
setOptimisticRefName(switchResult.refName ?? localCheckoutRefMismatch.threadRefName);
setIsMismatchPopoverOpen(false);
onComposerFocusRequest?.();
} catch (error) {
setOptimisticRefName(previousRefName);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to switch checkout.",
description: toRefActionErrorMessage(error),
}),
);
}
});
};
const useCurrentCheckoutForThread = () => {
if (!localCheckoutRefMismatch || isRefActionPending) {
return;
}
setThreadBranch(localCheckoutRefMismatch.currentRefName, null);
setIsMismatchPopoverOpen(false);
onComposerFocusRequest?.();
};
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!currentRefName
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(currentRefName, null);
}, [activeThreadBranch, activeWorktreePath, currentRefName, effectiveEnvMode, setThreadBranch]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
// ---------------------------------------------------------------------------
const handleOpenChange = useCallback(
(open: boolean) => {
setIsBranchMenuOpen(open);
setIsRefMenuOpen(open);
if (!open) {
setBranchQuery("");
setRefQuery("");
return;
}
void queryClient.invalidateQueries({
queryKey: gitQueryKeys.refs(environmentId, branchCwd),
queryKey: vcsQueryKeys.refs(environmentId, refCwd),
});
},
[branchCwd, environmentId, queryClient],
[refCwd, environmentId, queryClient],
);
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
const maybeFetchNextBranchPage = useCallback(() => {
if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
const refListScrollElementRef = useRef<HTMLDivElement | null>(null);
const maybeFetchNextRefPage = useCallback(() => {
if (!isRefMenuOpen || !hasNextPage || isFetchingNextPage) {
return;
}
const scrollElement = branchListScrollElementRef.current;
const scrollElement = refListScrollElementRef.current;
if (!scrollElement) {
return;
}
@@ -450,32 +498,32 @@ export function BranchToolbarBranchSelector({
}
void fetchNextPage().catch(() => undefined);
}, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
const branchListRef = useRef<LegendListRef | null>(null);
const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
}, [fetchNextPage, hasNextPage, isRefMenuOpen, isFetchingNextPage]);
const refListRef = useRef<LegendListRef | null>(null);
const setRefListRef = useCallback((element: HTMLDivElement | null) => {
refListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
}, []);
useEffect(() => {
if (!isBranchMenuOpen) {
if (!isRefMenuOpen) {
return;
}
if (shouldVirtualizeBranchList) {
branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
if (shouldVirtualizeRefList) {
refListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
} else {
branchListScrollElementRef.current?.scrollTo({ top: 0 });
refListScrollElementRef.current?.scrollTo({ top: 0 });
}
}, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
}, [deferredTrimmedRefQuery, isRefMenuOpen, shouldVirtualizeRefList]);
useEffect(() => {
const scrollElement = branchListScrollElementRef.current;
if (!scrollElement || !isBranchMenuOpen) {
const scrollElement = refListScrollElementRef.current;
if (!scrollElement || !isRefMenuOpen) {
return;
}
const handleScroll = () => {
maybeFetchNextBranchPage();
maybeFetchNextRefPage();
};
scrollElement.addEventListener("scroll", handleScroll, { passive: true });
@@ -483,21 +531,21 @@ export function BranchToolbarBranchSelector({
return () => {
scrollElement.removeEventListener("scroll", handleScroll);
};
}, [isBranchMenuOpen, maybeFetchNextBranchPage]);
}, [isRefMenuOpen, maybeFetchNextRefPage]);
useEffect(() => {
if (shouldVirtualizeBranchList) return;
maybeFetchNextBranchPage();
}, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
if (shouldVirtualizeRefList) return;
maybeFetchNextRefPage();
}, [refs.length, maybeFetchNextRefPage, shouldVirtualizeRefList]);
const triggerLabel = getBranchTriggerLabel({
const triggerLabel = getRefTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
resolvedActiveBranch,
resolvedActiveRefName,
});
function renderPickerItem(itemValue: string, index: number) {
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
if (checkoutChangeRequestItemValue && itemValue === checkoutChangeRequestItemValue) {
return (
<ComboboxItem
hideIndicator
@@ -505,13 +553,13 @@ export function BranchToolbarBranchSelector({
index={index}
value={itemValue}
onClick={() => {
if (!prReference || !onCheckoutPullRequestRequest) {
if (!changeRequestReference || !onCheckoutPullRequestRequest) {
return;
}
setIsBranchMenuOpen(false);
setBranchQuery("");
setIsRefMenuOpen(false);
setRefQuery("");
onComposerFocusRequest?.();
onCheckoutPullRequestRequest(prReference);
onCheckoutPullRequestRequest(changeRequestReference);
}}
>
<div className="flex min-w-0 items-center gap-2 py-1">
@@ -520,38 +568,40 @@ export function BranchToolbarBranchSelector({
<span className="truncate font-medium">
Checkout {sourceControlPresentation.terminology.singular}
</span>
<span className="truncate text-muted-foreground text-xs">{prReference}</span>
<span className="truncate text-muted-foreground text-xs">
{changeRequestReference}
</span>
</span>
</div>
</ComboboxItem>
);
}
if (createBranchItemValue && itemValue === createBranchItemValue) {
if (createRefItemValue && itemValue === createRefItemValue) {
return (
<ComboboxItem
hideIndicator
key={itemValue}
index={index}
value={itemValue}
onClick={() => createRef(trimmedBranchQuery)}
onClick={() => createRef(trimmedRefQuery)}
>
<span className="truncate">Create new ref &quot;{trimmedBranchQuery}&quot;</span>
<span className="truncate">Create new ref &quot;{trimmedRefQuery}&quot;</span>
</ComboboxItem>
);
}
const refName = branchByName.get(itemValue);
if (!refName) return null;
const ref = refByName.get(itemValue);
if (!ref) return null;
const hasSecondaryWorktree =
refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
const badge = refName.current
ref.worktreePath && activeProjectCwd && ref.worktreePath !== activeProjectCwd;
const badge = ref.current
? "current"
: hasSecondaryWorktree
? "worktree"
: refName.isRemote
: ref.isRemote
? "remote"
: refName.isDefault
: ref.isDefault
? "default"
: null;
return (
@@ -560,7 +610,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
onClick={() => selectBranch(refName)}
onClick={() => selectRef(ref)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
@@ -571,72 +621,146 @@ export function BranchToolbarBranchSelector({
}
return (
<Combobox
items={branchPickerItems}
filteredItems={filteredBranchPickerItems}
autoHighlight
virtualized={shouldVirtualizeBranchList}
onItemHighlighted={(_value, eventDetails) => {
if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
return;
}
branchListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
}}
onOpenChange={handleOpenChange}
open={isBranchMenuOpen}
value={resolvedActiveBranch}
<div
ref={refPickerAnchorRef}
className={cn("relative flex min-w-0 items-center justify-end", className)}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)}
disabled={(isBranchesSearchPending && refs.length === 0) || isBranchActionPending}
{localCheckoutRefMismatch ? (
<Popover open={isMismatchPopoverOpen} onOpenChange={setIsMismatchPopoverOpen}>
<PopoverTrigger
openOnHover
delay={120}
closeDelay={100}
render={
<button
type="button"
className="absolute left-1.5 top-1/2 z-10 flex size-4.5 -translate-y-1/2 items-center justify-center rounded-sm text-warning outline-none transition-colors hover:bg-warning/10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
aria-label="Thread ref does not match current checkout"
/>
}
>
<TriangleAlertIcon aria-hidden="true" className="size-3.5" />
</PopoverTrigger>
<PopoverPopup
tooltipStyle
side="top"
align="center"
sideOffset={8}
anchor={refPickerAnchorRef}
className="w-[28rem] max-w-[calc(100vw-2rem)] px-2 py-2"
>
<div className="chat-markdown space-y-2.5 text-xs leading-snug">
<div className="grid grid-cols-[5.25rem_minmax(0,1fr)] gap-x-2.5 gap-y-1.5">
<span className="text-muted-foreground">Thread</span>
<code className="max-w-full justify-self-start">
{localCheckoutRefMismatch.threadRefName}
</code>
<span className="text-muted-foreground">Checkout</span>
<code className="max-w-full justify-self-start">
{localCheckoutRefMismatch.currentRefName}
</code>
</div>
<p className="!my-0 border-border/70 border-t pt-2 text-muted-foreground">
This thread was last associated with{" "}
<code>{localCheckoutRefMismatch.threadRefName}</code>, but your checkout is on
another ref. Switch to keep working there, or use current to update the thread to
this checkout.
</p>
<div className="mt-2 flex justify-end gap-1.5">
<Button
variant="ghost"
size="xs"
className="h-6 px-1.5 text-[11px] text-muted-foreground hover:text-foreground"
disabled={isRefActionPending}
title={`Associate this thread with ${localCheckoutRefMismatch.currentRefName}`}
onClick={useCurrentCheckoutForThread}
>
Use current
</Button>
<Button
variant="outline"
size="xs"
className="h-6 px-1.5 text-[11px]"
disabled={isRefActionPending}
title={`Switch to ${localCheckoutRefMismatch.threadRefName}`}
onClick={switchCheckoutToThreadBranch}
>
Switch
</Button>
</div>
</div>
</PopoverPopup>
</Popover>
) : null}
<Combobox
items={refPickerItems}
filteredItems={filteredRefPickerItems}
autoHighlight
virtualized={shouldVirtualizeRefList}
onItemHighlighted={(_value, eventDetails) => {
if (!isRefMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
return;
}
refListRef.current?.scrollIndexIntoView?.({
index: eventDetails.index,
animated: false,
});
}}
onOpenChange={handleOpenChange}
open={isRefMenuOpen}
value={resolvedActiveRefName}
>
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="shrink-0" />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-80">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search refs..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No refs found.</ComboboxEmpty>
{shouldVirtualizeBranchList ? (
<ComboboxListVirtualized>
<LegendList<string>
ref={branchListRef}
data={filteredBranchPickerItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
void fetchNextPage().catch(() => undefined);
}
}}
style={{ maxHeight: "14rem" }}
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className={cn(
"min-w-0 text-muted-foreground/70 hover:text-foreground/80",
localCheckoutRefMismatch &&
"border-warning/35 bg-warning/10 pl-7 text-warning hover:bg-warning/15 hover:text-warning",
)}
disabled={(isRefsSearchPending && refs.length === 0) || isRefActionPending}
>
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="shrink-0" />
</ComboboxTrigger>
<ComboboxPopup align="end" side="top" className="w-80">
<div className="border-b p-1">
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search refs..."
showTrigger={false}
size="sm"
value={refQuery}
onChange={(event) => setRefQuery(event.target.value)}
/>
</ComboboxListVirtualized>
) : (
<ComboboxList ref={setBranchListRef} className="max-h-56">
{filteredBranchPickerItems.map((itemValue, index) =>
renderPickerItem(itemValue, index),
)}
</ComboboxList>
)}
{branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
</div>
<ComboboxEmpty>No refs found.</ComboboxEmpty>
{shouldVirtualizeRefList ? (
<ComboboxListVirtualized>
<LegendList<string>
ref={refListRef}
data={filteredRefPickerItems}
keyExtractor={(item) => item}
renderItem={({ item, index }) => renderPickerItem(item, index)}
estimatedItemSize={28}
drawDistance={336}
onEndReached={() => {
if (hasNextPage && !isFetchingNextPage) {
void fetchNextPage().catch(() => undefined);
}
}}
style={{ maxHeight: "14rem" }}
/>
</ComboboxListVirtualized>
) : (
<ComboboxList ref={setRefListRef} className="max-h-56">
{filteredRefPickerItems.map((itemValue, index) => renderPickerItem(itemValue, index))}
</ComboboxList>
)}
{refStatusText ? <ComboboxStatus>{refStatusText}</ComboboxStatus> : null}
</ComboboxPopup>
</Combobox>
</div>
);
}
@@ -29,6 +29,7 @@ const {
invalidateGitQueriesSpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
serverThreadBranchRef,
setDraftThreadContextSpy,
setThreadBranchSpy,
toastAddSpy,
@@ -42,6 +43,7 @@ const {
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
serverThreadBranchRef: { current: "feature/toast-scope" },
setDraftThreadContextSpy: vi.fn(),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
@@ -134,6 +136,43 @@ vi.mock("~/lib/gitStatusState", () => ({
})),
}));
vi.mock("~/lib/vcsStatusState", () => ({
refreshVcsStatus: refreshGitStatusSpy,
resetVcsStatusStateForTests: () => undefined,
useVcsStatus: vi.fn(() => ({
data: {
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
hasUpstream: true,
aheadCount: 1,
behindCount: 0,
aheadOfDefaultCount: 1,
workingTree: {
files: [
{
path: "src/example.ts",
insertions: 1,
deletions: 0,
},
],
insertions: 1,
deletions: 0,
},
pr: null,
},
error: null,
isPending: false,
})),
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
@@ -207,7 +246,7 @@ vi.mock("~/store", () => ({
? {
[SHARED_THREAD_ID]: {
id: SHARED_THREAD_ID,
branch: BRANCH_NAME,
branch: serverThreadBranchRef.current,
worktreePath: null,
},
}
@@ -228,7 +267,7 @@ vi.mock("~/store", () => ({
? {
[SHARED_THREAD_ID]: {
id: SHARED_THREAD_ID,
branch: BRANCH_NAME,
branch: serverThreadBranchRef.current,
worktreePath: null,
},
}
@@ -285,6 +324,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
activeDraftThreadRef.current = null;
hasServerThreadRef.current = true;
serverThreadBranchRef.current = BRANCH_NAME;
document.body.innerHTML = "";
});
@@ -436,6 +476,32 @@ describe("GitActionsControl thread-scoped progress toast", () => {
}
});
it("does not overwrite an existing server thread branch when the shared checkout differs", async () => {
serverThreadBranchRef.current = "feature/thread-branch";
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
/>,
{
container: host,
},
);
try {
await Promise.resolve();
expect(setThreadBranchSpy).not.toHaveBeenCalled();
expect(setDraftThreadContextSpy).not.toHaveBeenCalled();
} finally {
await screen.unmount();
host.remove();
}
});
it("does not overwrite a selected base branch while a new worktree draft is being configured", async () => {
hasServerThreadRef.current = false;
activeDraftThreadRef.current = {
@@ -280,6 +280,26 @@ describe("when: source control provider uses merge requests", () => {
});
describe("when: ref is clean, up to date, and has no open PR", () => {
it("enables create PR when synced with upstream but ahead of default", () => {
const syncedFeature = status({
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 1,
pr: null,
});
const quick = resolveQuickAction(syncedFeature, false);
assert.deepInclude(quick, {
label: "Create PR",
disabled: false,
kind: "run_action",
action: "create_pr",
});
const items = buildMenuItems(syncedFeature, false);
assert.equal(items.find((item) => item.id === "pr")?.disabled, false);
});
it("resolveQuickAction returns disabled no-action state", () => {
const quick = resolveQuickAction(
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
@@ -444,6 +464,48 @@ describe("when: working tree has local changes", () => {
},
]);
});
it("buildMenuItems enables push for ahead commits while local changes remain uncommitted", () => {
const items = buildMenuItems(
status({
refName: "feature/test",
hasWorkingTreeChanges: true,
aheadCount: 1,
workingTree: {
files: [{ path: ".vercel/project.json", insertions: 1, deletions: 0 }],
insertions: 1,
deletions: 0,
},
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: false,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("when: on default ref without open PR", () => {
@@ -103,12 +103,12 @@ export function buildMenuItems(
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isBehind = gitStatus.behindCount > 0;
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
const canCommit = !isBusy && hasChanges;
const canPush =
!isBusy &&
hasBranch &&
!hasChanges &&
!isBehind &&
gitStatus.aheadCount > 0 &&
(gitStatus.hasUpstream || canPushWithoutUpstream);
@@ -117,7 +117,7 @@ export function buildMenuItems(
hasBranch &&
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
hasDefaultBranchDelta &&
!isBehind &&
(gitStatus.hasUpstream || canPushWithoutUpstream);
const canOpenPr = !isBusy && hasOpenPr;
@@ -181,6 +181,7 @@ export function resolveQuickAction(
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isAhead = gitStatus.aheadCount > 0;
const hasDefaultBranchDelta = (gitStatus.aheadOfDefaultCount ?? gitStatus.aheadCount) > 0;
const isBehind = gitStatus.behindCount > 0;
const isDiverged = isAhead && isBehind;
const terminology = resolveChangeRequestTerminology(gitStatus);
@@ -286,6 +287,15 @@ export function resolveQuickAction(
return { label: `View ${terminology.shortLabel}`, disabled: false, kind: "open_pr" };
}
if (hasDefaultBranchDelta && !isDefaultRef) {
return {
label: `Create ${terminology.shortLabel}`,
disabled: false,
kind: "run_action",
action: "create_pr",
};
}
return {
label: "Commit",
disabled: true,
@@ -45,7 +45,7 @@ import {
gitPullMutationOptions,
gitRunStackedActionMutationOptions,
} from "~/lib/gitReactQuery";
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { refreshVcsStatus, useVcsStatus } from "~/lib/vcsStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
@@ -331,7 +331,7 @@ export default function GitActionsControl({
[persistThreadBranchSync],
);
const { data: gitStatus = null, error: gitStatusError } = useGitStatus({
const { data: gitStatus = null, error: gitStatusError } = useVcsStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
});
@@ -379,12 +379,12 @@ export default function GitActionsControl({
activeDraftThread.worktreePath === null;
useEffect(() => {
if (isGitActionRunning || isSelectingWorktreeBase) {
if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread) {
return;
}
const branchUpdate = resolveLiveThreadBranchUpdate({
threadBranch: activeServerThread?.branch ?? activeDraftThread?.branch ?? null,
threadBranch: activeDraftThread?.branch ?? null,
gitStatus: gitStatusForActions,
});
if (!branchUpdate) {
@@ -393,7 +393,7 @@ export default function GitActionsControl({
persistThreadBranchSync(branchUpdate.branch);
}, [
activeServerThread?.branch,
activeServerThread,
activeDraftThread?.branch,
gitStatusForActions,
isGitActionRunning,
@@ -451,7 +451,7 @@ export default function GitActionsControl({
}
refreshTimeout = window.setTimeout(() => {
refreshTimeout = null;
void refreshGitStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
void refreshVcsStatus({ environmentId: activeEnvironmentId, cwd: gitCwd }).catch(
() => undefined,
);
}, GIT_STATUS_WINDOW_REFRESH_DEBOUNCE_MS);
@@ -939,7 +939,7 @@ export default function GitActionsControl({
<Menu
onOpenChange={(open) => {
if (open) {
void refreshGitStatus({
void refreshVcsStatus({
environmentId: activeEnvironmentId,
cwd: gitCwd,
}).catch(() => undefined);
+169 -20
View File
@@ -15,31 +15,180 @@ export const GitHubIcon: Icon = (props) => (
</svg>
);
export const GitLabIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M22.6 9.3 20.9 4c-.2-.7-1.2-.7-1.5-.1l-2 5.4H6.6l-2-5.4c-.2-.6-1.2-.6-1.5.1L1.4 9.3c-.2.6 0 1.2.5 1.6L12 18.7l10.1-7.8c.5-.4.7-1 .5-1.6Z" />
<path d="m12 18.7 4.1-9.4H7.9L12 18.7Z" opacity=".72" />
<path d="M7.9 9.3H1.5L12 18.7 7.9 9.3ZM16.1 9.3 12 18.7l10.5-9.4h-6.4Z" opacity=".88" />
</svg>
);
export const AzureDevOpsIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M21 5.2v12.7L16 22l-8-2.8V22l-4.9-6.4 4.9.4V4.8L16 2l5 3.2ZM16 6.4l-5 1.4v8.4l5 1.4V6.4Z" />
<path d="m8 8.4-5 .8v5.6l5 .8V8.4Z" opacity=".72" />
</svg>
);
export const BitbucketIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
<path d="M2.4 3.5c-.4 0-.7.3-.6.8L4.3 20c.1.4.4.7.8.7h13.7c.4 0 .7-.3.8-.7l2.6-15.7c.1-.5-.2-.8-.7-.8H2.4Zm12.5 11.1H9.4L8.5 8.7h7.4l-1 5.9Z" />
export const GitIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 256 256">
<path
d="M21 8.7h-5.1l-1 5.9H9.4l-4.2 5c.2.6.5 1.1 1.2 1.1h12.4c.4 0 .7-.3.8-.7L21 8.7Z"
opacity=".72"
d="M251.17 116.6 139.4 4.82a16.49 16.49 0 0 0-23.31 0l-23.21 23.2 29.44 29.45a19.57 19.57 0 0 1 24.8 24.96l28.37 28.38a19.61 19.61 0 1 1-11.75 11.06L137.28 95.4v69.64a19.62 19.62 0 1 1-16.13-.57V94.2a19.61 19.61 0 0 1-10.65-25.73L81.46 39.44 4.83 116.08a16.49 16.49 0 0 0 0 23.32L116.6 251.17a16.49 16.49 0 0 0 23.32 0l111.25-111.25a16.5 16.5 0 0 0 0-23.33"
fill="#DE4C36"
/>
</svg>
);
export const JujutsuIcon: Icon = (props) => {
const groupId = `${useId().replaceAll(":", "")}-jj-a`;
return (
<svg {...props} viewBox="0 0 1024 1024">
<defs>
<g id={groupId}>
<path
d="M380.7 632.3s-14.3 56-50.3 55.5c-12.1-.2-29-10.9-47.1-26.8-34.2 82.7-98.5 239-108.5 268.6-8.9 26.5 13 52 38.2 56 36.4 5.7 49-18.1 49-18.1s13.6 40.7 37.6 39.7c29.9-1.2 34.6-33 34.6-33s11.4 23.8 26.8 23.2c38.4-1.4 41.7-102.9 43.8-135.6 3.8-57.5 6.3-135.4 7.8-190.1-9 6.7-16.5 10.7-21.3 9.9-16.1-2.7-10.6-49.3-10.6-49.3z"
fill="#42acde"
/>
<path
d="M403.7 75.1c-89.7-.3-201.5 32.6-200.6 99.6 1.3 87.4 52.2 62.4 41.2 111.2-4.9 21.6-59.9 49.8-65.5 153.8 2.8.7 5.3 1 7.2 1.2 14.2.7 29.9-26.3 29.9-26.3s9.5 38 35 38 50.7-26.3 50.7-26.3 15 30.3 39.6 32c20 1.6 34-8 34-8s.8 15 14.6 14c13.9-1.2 37.6-27.8 37.6-27.8 16.5 30.3 31.9 21 54.7 5.1 0 0 6.2 26.6 36.8 23.7 6-.6 12.3-1 18.5-1.5l.9-11.6c2-58.8-20.4-129.8-50.4-183-21.7-38.7-52.5-83.4-49.6-107.3 3.5-28.3 46.7-28.4 46.7-28.4l-48.5-16 24-37a279.7 279.7 0 0 0-56.8-5.4Z"
fill="#2f9fdf"
/>
<path
d="M215.9 414.6s-15.7 27-30 26.3c-1.8-.1-4.3-.5-7-1.2l-.3 3c-2.3 52 7.7 100.3 29.7 132 35.1 50.7 92.6 112.6 122 113 36.1.6 50.4-55.4 50.4-55.4s-5.5 46.6 10.6 49.3c16 2.6 62.4-46.7 87.9-79.5 15.8-20.5 52-82.3 58.2-138.3-6.2.4-12.4 1-18.5 1.5-30.6 3-36.8-23.7-36.8-23.7-22.8 16-38.2 25.2-54.7-5 0 0-23.7 26.5-37.6 27.6-13.8 1.1-14.6-13.8-14.6-13.8s-14 9.5-34 8c-24.5-1.8-39.6-32.1-39.6-32.1s-25.2 26.3-50.7 26.3c-25.5 0-35-38-35-38z"
fill="#0e254f"
/>
<path
d="M309.5 418.5a1.5 1.5 0 0 0-.7 0c-.6.2-1.1.8-1.5 1.8a34.7 34.7 0 0 0 4 16.6c5.5 10.6 12.4 22 23.3 27.6 4 2 8.5 3.5 12.5 3.3a36 36 0 0 0 12.5-2.3c4-2 7.6-3.8 10.8-6.2 6-4.4 7.6-6.5 7.6-9.8 0-3.3-2.7-3.5-7.6-.5-5 3-14.6 6.1-18.8 6.1-11.2 0-21.2-8-33.1-26.4-4.3-6.6-7.1-9.9-9-10.2zm174 5c-1.2-.2-2.4.4-3.8 1.7-2.3 2.3-2.7 4-2.6 10.7.5 9 4.8 19.2 11.8 24.6 4.4 3.3 13.2 6 20.4 5.8 6.8-1.1 18.8-6.6 15.3-10.3-2-1.6-5 .7-9.9.7-10.6 0-15.3-3.4-19.6-9-3.8-5-5.4-8.7-7.2-16.8-1.1-4.6-2.6-7.1-4.4-7.4zm-67.5 2.2a1 1 0 0 0-.4 0c-.4.1-.7.4-1.2.9-2.4 2-2.5 5.1-.2 12.6a41.4 41.4 0 0 0 25.3 22c7.6 1.7 14.5.6 20.3-2.7 3.8-2.4 5.3-5 4.4-7.3-4.8-2.9-7.7-1-13.3-1A39.5 39.5 0 0 1 424 435c-4.8-5.9-7-9.3-8-9.4zm-199 .8c-1 .3-1.4 2.7-1 7.2.3 5.3 1.3 8.2 4 12 3 4.5 11.5 11 14.7 11.7 2.5 1 6.9 2.3 10.7 2.3 3.8 0 8-.6 11.2-1.3 3.2-.7 6.8-2 10.3-4l1.3-.7c4-2.1 8-5.1 10.9-7.9l1.4-1.2c6.3-5.4 9.9-10.7 9.9-14.6 0-2.4-5.3-.5-14 5-16 9.8-31.1 13.2-40.9 9l-2.2-1.3-8.8-7.7a32.9 32.9 0 0 1-3.6-4.8c-1.4-2.2-2.5-3.4-3.3-3.7a1 1 0 0 0-.5 0z"
fill="#71beea"
/>
<path
d="M221.6 468.8c-.5 0-.8.1-1.1.4-.3.2-.5.6-.6 1.2a10 10 0 0 0 .6 5.1 55 55 0 0 0 28.3 28.9 42.4 42.4 0 0 0 16.4 2c6.1-.2 12.3-1.4 16.6-3.4a48.3 48.3 0 0 0 13.7-10.6c.9-1 1.3-2 1.3-2.3 0-.6 0-.9-.3-1-.3-.3-.7-.4-1.6-.4-1.8 0-4.9.8-9.7 2.3-6.2 1.9-12.7 3-18.5 3.1-7.8.2-10.2-.4-17-3.7-4.5-2.2-12-7.7-17.7-12.8a232 232 0 0 0-7.2-6.3 63 63 0 0 0-2.4-2 12 12 0 0 0-.7-.4h-.1zm214.8 13.6c-.2 0-.5.7-.7 1.8v4a32 32 0 0 0 2.7 9.9 38.5 38.5 0 0 0 49.1 19.3c5.2-2.3 10-6.4 13-10.5 1.4-2.1 2.5-4.3 3-6.2.5-1.9.4-3.6-.3-4.9-.4-.8-.9-1.4-1.3-1.7-.3-.3-.6-.3-1-.2-.9.2-2.3 1.4-4.3 3.8-5 6.2-12.8 9.5-22.6 9.4-6.2 0-11-1.1-16-4.4-5-3.2-10.4-8.6-18-17.3-.8-1-1.7-2-2.5-2.4l-1-.6c-.1 0-.2 0 0 0zm-33.6 4.2-.6.2-1.4.7a53.5 53.5 0 0 0-4 2.5c-8 5.5-15.6 8.3-23.9 8.4-8.3 0-17.2-2.7-28-8.2a42 42 0 0 0-7.3-3c-2-.5-3.1-.5-3.6-.2-.2.1-.3.3-.4.6 0 .3 0 .8.2 1.5.4 1.3 1.4 3.1 3.1 5.5 4 5.4 10.5 10.1 19.7 14 9.3 3.9 23.8 3.5 32.4-1a42 42 0 0 0 9.1-6.5c2.6-2.6 4.5-6.5 5.3-9.6.5-1.5.6-3 .4-3.8 0-.4-.2-.7-.4-.9-.1-.2-.3-.2-.6-.2zm-132.5 30.8c-.3 0-.4 0-.5.2l-.1.5c0 .5.4 1.7 1.2 3.1a87.3 87.3 0 0 0 13.5 16.2c17 15.6 34.6 20.7 49 14.4a33.3 33.3 0 0 0 19-23c.4-2 .1-3.1-.2-3.5-.2-.2-.5-.3-1-.3l-1.7.5a24 24 0 0 0-5.7 4.6c-7.7 8-14.6 12-23 11.4-8.3-.4-18-5.2-31.7-14.3-5.2-3.4-9.4-6-12.5-7.6a15.5 15.5 0 0 0-6.3-2.2zm109.4 0c-.2 0-.3 0-.5.2-.1 0-.3.3-.4.7a9 9 0 0 0 0 3.3c.4 2.9 1.6 6.7 3.5 10.3 11 20.5 29.4 30.5 46.8 25.7a37.3 37.3 0 0 0 15.6-10c4.4-4.6 7.4-9.9 7.4-13.8 0-1.3-.1-2.3-.4-2.7 0-.3-.2-.4-.3-.4h-.5c-.6 0-1.5.4-2.7 1.2a57 57 0 0 0-4.7 3.7c-9 7.7-16.9 11.2-25.1 10-8.2-1.3-16.7-7.1-27-17.7a159.8 159.8 0 0 0-10.6-9.8 9.8 9.8 0 0 0-.9-.6l-.2-.1zm-140.2 43.5c-1 0-1.6.2-1.8.5-.2.4-.3 1 0 2.1.8 2.2 3.1 5.6 7.1 9.6a78.2 78.2 0 0 0 27.4 17.9c9.7 3.8 16.7 4.1 23.4 1.1 5.5-2.5 8.4-6.1 8.4-10.4a4 4 0 0 0-.4-2c-.3-.4-.6-.6-1-.7-.9-.1-2.5.4-4.6 1.8-2.7 2-6.4 2.3-11.3 1.2-5-1.2-11.3-3.8-19.5-8-8-4-17.5-9-21.3-11-2.9-1.4-5-2-6.4-2.1zm160.1 2.8c-.6-.1-1.7.2-3.1 1-1.4 1-3.2 2.3-5.2 4.1a58 58 0 0 1-12.7 8.7c-5.9 2.7-8.6 3.2-18.3 3.2-12.6 0-17.2-1.6-29.9-11.2a21 21 0 0 0-6.4-3.8c-.5 0-.5 0-.7.2-.2.3-.3 1-.3 2 0 2.2 1.5 5.7 3.8 9.2 2.4 3.4 5.7 7 9.2 9.5 8.1 6 14.3 7.8 26.2 7.4a34 34 0 0 0 18.3-4.1 51 51 0 0 0 13.1-9.8c3.8-3.8 6.5-8 7-10.7.4-2 .4-3.5.2-4.5a2 2 0 0 0-.5-1 1 1 0 0 0-.7-.2zm-2 21.4c-.5 0-.6 0-.8.4-.2.4-.3 1.2-.3 2.4 0 3.2 1.7 7.3 4.4 11 2.7 4 6.3 7.4 10 9.5a35 35 0 0 0 21.3 4.8c11-.9 17.8-3.4 23.8-12.6 1.5-2.5 2-4.8 1.4-6.7-.2-.7-.4-1.1-.8-1.4-.3-.2-.6-.3-1.2-.3-1 0-2.6.7-4.7 2.1-6 4.3-12 6.1-19.9 6.2-8.8 0-16.3-3-26.2-11-3.6-2.8-6-4.3-7-4.4zM290 605.5c-.6.3-.9.5-1 1a9 9 0 0 0 .1 3.3c1.8 11 13 25 24.4 30.2 8.5 4 20 4 28.5 0 7.7-3.5 16-11.1 19-17.3a25 25 0 0 0 2.2-6.3c.1-.7.1-1.3 0-1.6 0-.4-.2-.6-.4-.7-.3-.2-1.3-.2-2.8.5-1.6.7-3.6 2-6 4-10 8.2-18.6 12.1-27 11.4-8.6-.7-16.9-6-26.4-15.9a82.6 82.6 0 0 0-7.6-7.1 10 10 0 0 0-2-1.4c-.5-.2-.8-.2-1-.1z"
fill="#309fdf"
/>
<path
d="M290 125.7a61.4 61.4 0 0 0-19 2.3c-19.9 5.7-33.5 15.8-36.5 52.2-3 36.6-18 45.5-20.3 46.7 14.7 26.7 38 24.5 30.1 59-2.4 11-17.6 23.5-32.8 46.5 34-27 56.4-48 99.6-100.5 0 0 39-47.6 25.1-77a52 52 0 0 0-46.1-29.2z"
fill="#e9f2f1"
/>
<path
d="M288.5 120.8c-8.1 0-16.7 1.4-25.6 5.3-22.5 9.9-25 20.3-29.1 37a96.8 96.8 0 0 0-1.4 24.6 178 178 0 0 0-16.5-31.6s-19 19.8-36.5 18.6c-22.9-1.7-34 2-44.8 9.8-25.4 18.5-21.2 43.8-21.2 43.8s17.6-1.8 40.5 1c20.3 2.7 37.4 4.3 61.3 2.6 8.5-.6 15.8-10 19.3-19 4.5-4 2.9-22 4.8-24.5 3-3.4 8-4.7 10.6-5.2 3.7-.7 4.3 1.5 4.7 2.8a31 31 0 0 0 60.5-3.2c1-4.4 9-5 15.9-4.5 7 0 .9 15.9-1.7 22.3-5.4 13.2-24.9 39-24.9 39l124.3-85s-45.8 22-61.5 20c-19.7-2.3-25.7-34.8-43.2-44-9.9-5.1-22-9.6-35.5-9.8zm1.4 9.4a48.2 48.2 0 0 1 40.6 23.5c3.7 7.1 6.2 17-.3 20.2-7.6 3.7-14.7.7-15.5-2.8a31 31 0 0 0-30.2-24.1 30 30 0 0 0-30.8 27.4c-.4 5.2-9.1 7.7-12.7 3.7-2.7-3 1.7-16.8 3.7-22 6.2-16.2 27.8-25.7 45.2-26zm5.6 27.8a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm-22 29a5.5 5.5 0 1 1 0 11 5.5 5.5 0 0 1 0-11zm40 523.4c-2.6-1.8-15.1 23.5-20 59-6.8 49-8.3 63.2-14.2 96-6 32.7-12.6 66.3-13.4 73.7-.6 4.8-1.7 19-.6 20.1 3.2 3.3 14.7-31.7 16.8-42 2-10.3 7.7-40.7 14.2-86.9 6.4-46.1 8.5-69.6 13.1-91.5 4.7-22 6.7-26.6 4.2-28.4zm66.3-27c-4.1-1.3-10.5 24.6-13.1 37.8-5.6 28.6-6.2 64-8.4 87a1099 1099 0 0 1-12 87.4c-2.7 15-8 29.4-9.8 44.6-1 9-5.2 26-.2 27.3 5.2 1.5 15.4-36.5 20-55.7 8.1-32.9 10.7-65.6 14.2-99.3 3.3-30.7 4.6-62.8 6.5-93.6.7-18.5 5.1-34.5 2.8-35.6z"
fill="#0e254f"
/>
</g>
</defs>
<rect width="1024" height="1024" rx="270" fill="#a7bcd9" />
<use href={`#${groupId}`} transform="matrix(-1 0 0 1 1024 0)" />
<use href={`#${groupId}`} />
</svg>
);
};
export const GitLabIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 32 32" fill="none">
<path
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
fill="#E24329"
/>
<path
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
fill="#FC6D26"
/>
<path
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
fill="#FCA326"
/>
<path
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
fill="#FC6D26"
/>
</svg>
);
export const AzureDevOpsIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientA = `${id}-azure-a`;
const gradientB = `${id}-azure-b`;
const gradientC = `${id}-azure-c`;
return (
<svg {...props} viewBox="0 0 96 96">
<defs>
<linearGradient
id={gradientA}
x1="-1032.17"
x2="-1059.21"
y1="145.31"
y2="65.43"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#114a8b" />
<stop offset="1" stopColor="#0669bc" />
</linearGradient>
<linearGradient
id={gradientB}
x1="-1023.73"
x2="-1029.98"
y1="108.08"
y2="105.97"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopOpacity=".3" />
<stop offset=".07" stopOpacity=".2" />
<stop offset=".32" stopOpacity=".1" />
<stop offset=".62" stopOpacity=".05" />
<stop offset="1" stopOpacity="0" />
</linearGradient>
<linearGradient
id={gradientC}
x1="-1027.16"
x2="-997.48"
y1="147.64"
y2="68.56"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#3ccbf4" />
<stop offset="1" stopColor="#2892df" />
</linearGradient>
</defs>
<path
fill={`url(#${gradientA})`}
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
/>
<path
fill="#0078d4"
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
/>
<path
fill={`url(#${gradientB})`}
d="M33.34 6.54a4.12 4.12 0 0 0-3.95 2.88L4.25 83.92a4.14 4.14 0 0 0 3.91 5.54h20.79a4.44 4.44 0 0 0 3.4-2.9l5.02-14.78 17.91 16.7a4.24 4.24 0 0 0 2.67.97h23.29L71.02 60.26H41.24L59.47 6.55z"
/>
<path
fill={`url(#${gradientC})`}
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
/>
</svg>
);
};
export const BitbucketIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientId = `${id}-bitbucket-a`;
return (
<svg {...props} viewBox="8.4 14.39 2481.29 2231.21">
<path fill="none" d="M989.97,1493.09h518.05l125.04-730.04H852.22L989.97,1493.09z" />
<path
fill="#2684FF"
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
/>
<linearGradient
id={gradientId}
gradientUnits="userSpaceOnUse"
x1="945.1094"
y1="1524.8389"
x2="944.4923"
y2="1524.1893"
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
>
<stop offset="0.18" stopColor="#0052CC" />
<stop offset="1" stopColor="#2684FF" />
</linearGradient>
<path
fill={`url(#${gradientId})`}
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
/>
</svg>
);
};
export const CursorIcon: Icon = ({ className, ...props }) => (
<svg
{...props}
+15 -8
View File
@@ -13,6 +13,7 @@ import {
import {
ChangeRequestStatusIcon,
prStatusIndicator,
PrStatusTooltipContent,
resolveThreadPr,
terminalStatusFromRunningIds,
ThreadStatusLabel,
@@ -82,7 +83,7 @@ import {
} from "../keybindings";
import { useModelPickerOpen } from "../modelPickerOpenState";
import { useShortcutModifierState } from "../shortcutModifierState";
import { useGitStatus } from "../lib/gitStatusState";
import { useVcsStatus } from "../lib/vcsStatusState";
import { readLocalApi } from "../localApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
@@ -342,8 +343,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote")
: null;
// For grouped projects, the thread may belong to a different environment
// than the representative project. Look up the thread's own project cwd
// so git status (and thus PR detection) queries the correct path.
// than the representative project. Look up the thread's own project cwd
// so VCS status (and thus change request detection) queries the correct path.
const threadProjectCwd = useStore(
useMemo(
() => (state: import("../store").AppState) =>
@@ -353,9 +354,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
),
);
const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd;
const gitStatus = useGitStatus({
const vcsStatus = useVcsStatus({
environmentId: thread.environmentId,
cwd: thread.branch != null ? gitCwd : null,
cwd: thread.branch != null || thread.worktreePath !== null ? gitCwd : null,
});
const isHighlighted = isActive || isSelected;
const isThreadRunning =
@@ -366,8 +367,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
lastVisitedAt,
},
});
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const pr = resolveThreadPr({
threadBranch: thread.branch,
vcsStatus: vcsStatus.data,
hasDedicatedWorktree: thread.worktreePath !== null,
});
const prStatus = prStatusIndicator(pr, vcsStatus.data?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
@@ -562,7 +567,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
<TooltipPopup side="top">
<PrStatusTooltipContent status={prStatus} />
</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
@@ -0,0 +1,73 @@
import type { VcsStatusResult } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { prStatusIndicator, resolveThreadPr } from "./ThreadStatusIndicators";
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/current",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: {
number: 42,
title: "PR branch",
url: "https://github.com/pingdotgg/t3code/pull/42",
baseRef: "main",
headRef: "feature/current",
state: "open",
},
...overrides,
};
}
describe("resolveThreadPr", () => {
it("keeps local-checkout PR indicators scoped to the stored thread branch", () => {
expect(
resolveThreadPr({
threadBranch: "feature/other",
vcsStatus: status(),
hasDedicatedWorktree: false,
}),
).toBeNull();
});
it("shows PR indicators for dedicated worktree threads even when branch metadata is stale", () => {
const vcsStatus = status();
expect(
resolveThreadPr({
threadBranch: "feature/old-name",
vcsStatus,
hasDedicatedWorktree: true,
}),
).toBe(vcsStatus.pr);
});
it("shows PR indicators for dedicated worktree threads even when branch metadata is missing", () => {
const vcsStatus = status();
expect(
resolveThreadPr({
threadBranch: null,
vcsStatus,
hasDedicatedWorktree: true,
}),
).toBe(vcsStatus.pr);
});
});
describe("prStatusIndicator", () => {
it("formats PR tooltips with number, uppercase status, and title", () => {
expect(prStatusIndicator(status().pr, undefined)).toMatchObject({
tooltip: "PR #42 - Open: PR branch",
tooltipLead: "PR #42 - Open",
tooltipTitle: "PR branch",
});
});
});
@@ -7,7 +7,7 @@ import {
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
} from "../environments/runtime";
import { useGitStatus } from "../lib/gitStatusState";
import { useVcsStatus } from "../lib/vcsStatusState";
import { type AppState, selectProjectByRef, useStore } from "../store";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { useUiStateStore } from "../uiStateStore";
@@ -20,6 +20,8 @@ export interface PrStatusIndicator {
label: string;
colorClass: string;
tooltip: string;
tooltipLead: string;
tooltipTitle: string;
url: string;
}
@@ -31,6 +33,14 @@ export interface TerminalStatusIndicator {
export type ThreadPr = VcsStatusResult["pr"];
function formatPrState(state: NonNullable<ThreadPr>["state"]): string {
return state.charAt(0).toUpperCase() + state.slice(1);
}
function formatPrStatusTooltip(pr: NonNullable<ThreadPr>, shortName: string): string {
return `${shortName} #${pr.number} - ${formatPrState(pr.state)}: ${pr.title}`;
}
export function prStatusIndicator(
pr: ThreadPr,
provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
@@ -38,11 +48,16 @@ export function prStatusIndicator(
if (!pr) return null;
const presentation = resolveChangeRequestPresentation(provider);
const tooltip = formatPrStatusTooltip(pr, presentation.shortName);
const tooltipLead = `${presentation.shortName} #${pr.number} - ${formatPrState(pr.state)}`;
if (pr.state === "open") {
return {
label: `${presentation.shortName} open`,
colorClass: "text-emerald-600 dark:text-emerald-300/90",
tooltip: `#${pr.number} ${presentation.shortName} open: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
@@ -50,7 +65,9 @@ export function prStatusIndicator(
return {
label: `${presentation.shortName} closed`,
colorClass: "text-zinc-500 dark:text-zinc-400/80",
tooltip: `#${pr.number} ${presentation.shortName} closed: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
@@ -58,26 +75,48 @@ export function prStatusIndicator(
return {
label: `${presentation.shortName} merged`,
colorClass: "text-violet-600 dark:text-violet-300/90",
tooltip: `#${pr.number} ${presentation.shortName} merged: ${pr.title}`,
tooltip,
tooltipLead,
tooltipTitle: pr.title,
url: pr.url,
};
}
return null;
}
export function ChangeRequestStatusIcon({ className }: { className?: string }) {
return <GitPullRequestIcon className={className} />;
export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
return (
<span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
<span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
<span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
<span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
</span>
);
}
export function resolveThreadPr(
threadBranch: string | null,
gitStatus: VcsStatusResult | null,
): ThreadPr | null {
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
export function resolveThreadPr(input: {
threadBranch: string | null;
vcsStatus: VcsStatusResult | null;
hasDedicatedWorktree: boolean;
}): ThreadPr | null {
const { threadBranch, vcsStatus, hasDedicatedWorktree } = input;
if (vcsStatus === null) {
return null;
}
return gitStatus.pr ?? null;
if (hasDedicatedWorktree) {
return vcsStatus.pr ?? null;
}
if (threadBranch === null || vcsStatus.refName !== threadBranch) {
return null;
}
return vcsStatus.pr ?? null;
}
export function ChangeRequestStatusIcon({ className }: { className?: string }) {
return <GitPullRequestIcon className={className} />;
}
export function terminalStatusFromRunningIds(
@@ -150,12 +189,16 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
),
);
const gitCwd = thread.worktreePath ?? threadProjectCwd;
const gitStatus = useGitStatus({
const vcsStatus = useVcsStatus({
environmentId: thread.environmentId,
cwd: thread.branch != null ? gitCwd : null,
cwd: thread.branch != null || thread.worktreePath !== null ? gitCwd : null,
});
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const pr = resolveThreadPr({
threadBranch: thread.branch,
vcsStatus: vcsStatus.data,
hasDedicatedWorktree: thread.worktreePath !== null,
});
const prStatus = prStatusIndicator(pr, vcsStatus.data?.sourceControlProvider);
const threadStatus = resolveThreadStatusPill({
thread: {
...thread,
@@ -181,7 +224,9 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar
>
<ChangeRequestStatusIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
<TooltipPopup side="top">
<PrStatusTooltipContent status={prStatus} />
</TooltipPopup>
</Tooltip>
) : null}
{threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
@@ -1,11 +1,12 @@
import { GitPullRequestIcon, RefreshCwIcon } from "lucide-react";
import { Option } from "effect";
import { type ReactNode, useId } from "react";
import { type ReactNode } from "react";
import type {
SourceControlProviderKind,
SourceControlDiscoveryResult,
SourceControlProviderAuth,
SourceControlProviderDiscoveryItem,
VcsDriverKind,
VcsDiscoveryItem,
} from "@t3tools/contracts";
@@ -27,7 +28,15 @@ import {
import { Skeleton } from "../ui/skeleton";
import { Switch } from "../ui/switch";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { GitHubIcon, type Icon } from "../Icons";
import {
AzureDevOpsIcon,
BitbucketIcon,
GitHubIcon,
GitIcon,
GitLabIcon,
JujutsuIcon,
type Icon,
} from "../Icons";
import { RedactedSensitiveText } from "./RedactedSensitiveText";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
@@ -36,127 +45,6 @@ const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
sourceControlProviders: [],
};
const GitLabIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 32 32" fill="none">
<path
d="m31.46 12.78-.04-.12-4.35-11.35A1.14 1.14 0 0 0 25.94.6c-.24 0-.47.1-.66.24-.19.15-.33.36-.39.6l-2.94 9h-11.9l-2.94-9A1.14 1.14 0 0 0 6.07.58a1.15 1.15 0 0 0-1.14.72L.58 12.68l-.05.11a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48 6.67-5h.02a8.09 8.09 0 0 0 2.7-9.36Z"
fill="#E24329"
/>
<path
d="m31.46 12.78-.04-.12a14.75 14.75 0 0 0-5.86 2.64l-9.55 7.24 6.09 4.6 6.67-5h.02a8.09 8.09 0 0 0 2.67-9.36Z"
fill="#FC6D26"
/>
<path
d="m9.9 27.14 3.28 2.48 2 1.52a1.35 1.35 0 0 0 1.62 0l2-1.52 3.28-2.48-6.1-4.6-6.07 4.6Z"
fill="#FCA326"
/>
<path
d="M6.44 15.3a14.71 14.71 0 0 0-5.86-2.63l-.05.12a8.1 8.1 0 0 0 2.68 9.34l.02.01.04.03 6.63 4.97 6.1-4.6-9.56-7.24Z"
fill="#FC6D26"
/>
</svg>
);
const AzureDevOpsIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientA = `${id}-azure-a`;
const gradientB = `${id}-azure-b`;
const gradientC = `${id}-azure-c`;
return (
<svg {...props} viewBox="0 0 96 96">
<defs>
<linearGradient
id={gradientA}
x1="-1032.17"
x2="-1059.21"
y1="145.31"
y2="65.43"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#114a8b" />
<stop offset="1" stopColor="#0669bc" />
</linearGradient>
<linearGradient
id={gradientB}
x1="-1023.73"
x2="-1029.98"
y1="108.08"
y2="105.97"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopOpacity=".3" />
<stop offset=".07" stopOpacity=".2" />
<stop offset=".32" stopOpacity=".1" />
<stop offset=".62" stopOpacity=".05" />
<stop offset="1" stopOpacity="0" />
</linearGradient>
<linearGradient
id={gradientC}
x1="-1027.16"
x2="-997.48"
y1="147.64"
y2="68.56"
gradientTransform="matrix(1 0 0 -1 1075 158)"
gradientUnits="userSpaceOnUse"
>
<stop offset="0" stopColor="#3ccbf4" />
<stop offset="1" stopColor="#2892df" />
</linearGradient>
</defs>
<path
fill={`url(#${gradientA})`}
d="M33.34 6.54h26.04l-27.03 80.1a4.15 4.15 0 0 1-3.94 2.81H8.15a4.14 4.14 0 0 1-3.93-5.47L29.4 9.38a4.15 4.15 0 0 1 3.94-2.83z"
/>
<path
fill="#0078d4"
d="M71.17 60.26H29.88a1.91 1.91 0 0 0-1.3 3.31l26.53 24.76a4.17 4.17 0 0 0 2.85 1.13h23.38z"
/>
<path
fill={`url(#${gradientB})`}
d="M33.34 6.54a4.12 4.12 0 0 0-3.95 2.88L4.25 83.92a4.14 4.14 0 0 0 3.91 5.54h20.79a4.44 4.44 0 0 0 3.4-2.9l5.02-14.78 17.91 16.7a4.24 4.24 0 0 0 2.67.97h23.29L71.02 60.26H41.24L59.47 6.55z"
/>
<path
fill={`url(#${gradientC})`}
d="M66.6 9.36a4.14 4.14 0 0 0-3.93-2.82H33.65a4.15 4.15 0 0 1 3.93 2.82l25.18 74.62a4.15 4.15 0 0 1-3.93 5.48h29.02a4.15 4.15 0 0 0 3.93-5.48z"
/>
</svg>
);
};
const BitbucketIcon: Icon = (props) => {
const id = useId().replaceAll(":", "");
const gradientId = `${id}-bitbucket-a`;
return (
<svg {...props} viewBox="8.4 14.39 2481.29 2231.21">
<path fill="none" d="M989.97,1493.09h518.05l125.04-730.04H852.22L989.97,1493.09z" />
<path
fill="#2684FF"
d="M88.92,14.4C45.02,13.83,8.97,48.96,8.41,92.86c-0.06,4.61,0.28,9.22,1.02,13.77l337.48,2048.72 c8.68,51.75,53.26,89.8,105.74,90.24h1619.03c39.38,0.5,73.19-27.9,79.49-66.78l337.49-2071.78c7.03-43.34-22.41-84.17-65.75-91.2 c-4.55-0.74-9.15-1.08-13.76-1.02L88.92,14.4z M1509.99,1495.09H993.24l-139.92-731h781.89L1509.99,1495.09z"
/>
<linearGradient
id={gradientId}
gradientUnits="userSpaceOnUse"
x1="945.1094"
y1="1524.8389"
x2="944.4923"
y2="1524.1893"
gradientTransform="matrix(1996.6343 0 0 -1480.3047 -1884485.625 2258195)"
>
<stop offset="0.18" stopColor="#0052CC" />
<stop offset="1" stopColor="#2684FF" />
</linearGradient>
<path
fill={`url(#${gradientId})`}
d="M2379.27,763.06h-745.5l-125.12,730.42H992.31l-609.67,723.67c19.32,16.71,43.96,26,69.5,26.21h1618.13 c39.35,0.51,73.14-27.88,79.44-66.72L2379.27,763.06z"
/>
</svg>
);
};
const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, Icon>> = {
github: GitHubIcon,
gitlab: GitLabIcon,
@@ -164,6 +52,11 @@ const SOURCE_CONTROL_PROVIDER_ICONS: Partial<Record<SourceControlProviderKind, I
bitbucket: BitbucketIcon,
};
const VCS_ICONS: Partial<Record<VcsDriverKind, Icon>> = {
git: GitIcon,
jj: JujutsuIcon,
};
function optionLabel(value: Option.Option<string>): string | null {
return Option.getOrNull(value);
}
@@ -211,7 +104,9 @@ function SourceControlItemMark({
readonly item: VcsDiscoveryItem | SourceControlProviderDiscoveryItem;
}) {
const dotClassName = itemStatusDot(item);
const Icon = isProviderDiscoveryItem(item) ? SOURCE_CONTROL_PROVIDER_ICONS[item.kind] : null;
const Icon = isProviderDiscoveryItem(item)
? SOURCE_CONTROL_PROVIDER_ICONS[item.kind]
: VCS_ICONS[item.kind];
if (!Icon) {
return <span className={cn("size-2 shrink-0 rounded-full", dotClassName)} aria-hidden />;
@@ -342,7 +237,13 @@ function SourceControlSectionSkeleton({
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1 space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="size-2 rounded-full" />
<span className="relative inline-flex size-5 shrink-0 items-center justify-center">
<Skeleton className="size-4.5 rounded-md" />
<Skeleton
className="pointer-events-none absolute -left-0.5 -top-0.5 size-2 rounded-full ring-2 ring-background"
aria-hidden
/>
</span>
<Skeleton className="h-4 w-28 rounded-full" />
<Skeleton className="h-5 w-14 rounded-full" />
</div>
+31 -27
View File
@@ -13,16 +13,21 @@ import {
import { ensureEnvironmentApi } from "../environmentApi";
import { requireEnvironmentConnection } from "../environments/runtime";
const GIT_BRANCHES_STALE_TIME_MS = 15_000;
const GIT_BRANCHES_REFETCH_INTERVAL_MS = 60_000;
const GIT_BRANCHES_PAGE_SIZE = 100;
const VCS_REFS_STALE_TIME_MS = 15_000;
const VCS_REFS_REFETCH_INTERVAL_MS = 60_000;
const VCS_REFS_PAGE_SIZE = 100;
export const vcsQueryKeys = {
all: ["vcs"] as const,
refs: (environmentId: EnvironmentId | null, cwd: string | null) =>
["vcs", "refs", environmentId ?? null, cwd] as const,
refSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) =>
["vcs", "refs", environmentId ?? null, cwd, "search", query] as const,
};
export const gitQueryKeys = {
all: ["git"] as const,
refs: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "refs", environmentId ?? null, cwd] as const,
branchSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) =>
["git", "refs", environmentId ?? null, cwd, "search", query] as const,
...vcsQueryKeys,
branchSearch: vcsQueryKeys.refSearch,
};
export const gitMutationKeys = {
@@ -45,13 +50,13 @@ export function invalidateGitQueries(
const environmentId = input?.environmentId ?? null;
const cwd = input?.cwd ?? null;
if (cwd !== null) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
return queryClient.invalidateQueries({ queryKey: vcsQueryKeys.refs(environmentId, cwd) });
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
return queryClient.invalidateQueries({ queryKey: vcsQueryKeys.all });
}
function invalidateGitBranchQueries(
function invalidateVcsRefQueries(
queryClient: QueryClient,
environmentId: EnvironmentId | null,
cwd: string | null,
@@ -60,13 +65,10 @@ function invalidateGitBranchQueries(
return Promise.resolve();
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
return queryClient.invalidateQueries({ queryKey: vcsQueryKeys.refs(environmentId, cwd) });
}
/**
* @deprecated Use a VCS-named query helper once the UI naming migration lands.
*/
export function gitBranchSearchInfiniteQueryOptions(input: {
export function vcsRefSearchInfiniteQueryOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
query: string;
@@ -75,28 +77,30 @@ export function gitBranchSearchInfiniteQueryOptions(input: {
const normalizedQuery = input.query.trim();
return infiniteQueryOptions({
queryKey: gitQueryKeys.branchSearch(input.environmentId, input.cwd, normalizedQuery),
queryKey: vcsQueryKeys.refSearch(input.environmentId, input.cwd, normalizedQuery),
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
if (!input.cwd) throw new Error("Git refs are unavailable.");
if (!input.environmentId) throw new Error("Git refs are unavailable.");
if (!input.cwd) throw new Error("VCS refs are unavailable.");
if (!input.environmentId) throw new Error("VCS refs are unavailable.");
const api = ensureEnvironmentApi(input.environmentId);
return api.vcs.listRefs({
cwd: input.cwd,
...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}),
cursor: pageParam,
limit: GIT_BRANCHES_PAGE_SIZE,
limit: VCS_REFS_PAGE_SIZE,
});
},
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
enabled: input.cwd !== null && (input.enabled ?? true),
staleTime: GIT_BRANCHES_STALE_TIME_MS,
staleTime: VCS_REFS_STALE_TIME_MS,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchInterval: GIT_BRANCHES_REFETCH_INTERVAL_MS,
refetchInterval: VCS_REFS_REFETCH_INTERVAL_MS,
});
}
export const gitBranchSearchInfiniteQueryOptions = vcsRefSearchInfiniteQueryOptions;
export function gitResolvePullRequestQueryOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
@@ -140,7 +144,7 @@ export function gitInitMutationOptions(input: {
return api.vcs.init({ cwd: input.cwd });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
await invalidateVcsRefQueries(input.queryClient, input.environmentId, input.cwd);
},
});
}
@@ -161,7 +165,7 @@ export function gitCheckoutMutationOptions(input: {
return api.vcs.switchRef({ cwd: input.cwd, refName });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
await invalidateVcsRefQueries(input.queryClient, input.environmentId, input.cwd);
},
});
}
@@ -202,7 +206,7 @@ export function gitRunStackedActionMutationOptions(input: {
);
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
await invalidateVcsRefQueries(input.queryClient, input.environmentId, input.cwd);
},
});
}
@@ -223,7 +227,7 @@ export function gitPullMutationOptions(input: {
return api.vcs.pull({ cwd: input.cwd });
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
await invalidateVcsRefQueries(input.queryClient, input.environmentId, input.cwd);
},
});
}
@@ -298,7 +302,7 @@ export function gitPreparePullRequestThreadMutationOptions(input: {
});
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
await invalidateVcsRefQueries(input.queryClient, input.environmentId, input.cwd);
},
});
}
+81 -75
View File
@@ -15,61 +15,61 @@ import {
} from "../environments/runtime";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
interface GitStatusState {
interface VcsStatusState {
readonly data: VcsStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
type GitStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
interface ResolvedGitStatusClient {
type VcsStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
interface ResolvedVcsStatusClient {
readonly clientIdentity: string;
readonly client: GitStatusClient;
readonly client: VcsStatusClient;
}
interface WatchedGitStatus {
interface WatchedVcsStatus {
refCount: number;
unsubscribe: () => void;
}
interface GitStatusTarget {
interface VcsStatusTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
}
const EMPTY_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
const EMPTY_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
data: null,
error: null,
cause: null,
isPending: false,
});
const INITIAL_GIT_STATUS_STATE = Object.freeze<GitStatusState>({
...EMPTY_GIT_STATUS_STATE,
const INITIAL_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
...EMPTY_VCS_STATUS_STATE,
isPending: true,
});
const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
const EMPTY_VCS_STATUS_ATOM = Atom.make(EMPTY_VCS_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel("git-status:null"),
Atom.withLabel("vcs-status:null"),
);
const NOOP: () => void = () => undefined;
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
const knownGitStatusKeys = new Set<string>();
const gitStatusRefreshInFlight = new Map<string, Promise<VcsStatusResult>>();
const gitStatusLastRefreshAtByKey = new Map<string, number>();
const watchedVcsStatuses = new Map<string, WatchedVcsStatus>();
const knownVcsStatusKeys = new Set<string>();
const vcsStatusRefreshInFlight = new Map<string, Promise<VcsStatusResult>>();
const vcsStatusLastRefreshAtByKey = new Map<string, number>();
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
const VCS_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
const gitStatusStateAtom = Atom.family((key: string) => {
knownGitStatusKeys.add(key);
return Atom.make(INITIAL_GIT_STATUS_STATE).pipe(
const vcsStatusStateAtom = Atom.family((key: string) => {
knownVcsStatusKeys.add(key);
return Atom.make(INITIAL_VCS_STATUS_STATE).pipe(
Atom.keepAlive,
Atom.withLabel(`git-status:${key}`),
Atom.withLabel(`vcs-status:${key}`),
);
});
function getGitStatusTargetKey(target: GitStatusTarget): string | null {
function getVcsStatusTargetKey(target: VcsStatusTarget): string | null {
if (target.environmentId === null || target.cwd === null) {
return null;
}
@@ -77,7 +77,7 @@ function getGitStatusTargetKey(target: GitStatusTarget): string | null {
return `${target.environmentId}:${target.cwd}`;
}
function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatusClient | null {
function readResolvedVcsStatusClient(target: VcsStatusTarget): ResolvedVcsStatusClient | null {
if (target.environmentId === null) {
return null;
}
@@ -87,96 +87,96 @@ function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatus
: null;
}
export function getGitStatusSnapshot(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
export function getVcsStatusSnapshot(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null) {
return EMPTY_GIT_STATUS_STATE;
return EMPTY_VCS_STATUS_STATE;
}
return appAtomRegistry.get(gitStatusStateAtom(targetKey));
return appAtomRegistry.get(vcsStatusStateAtom(targetKey));
}
export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient): () => void {
const targetKey = getGitStatusTargetKey(target);
export function watchVcsStatus(target: VcsStatusTarget, client?: VcsStatusClient): () => void {
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null) {
return NOOP;
}
const watched = watchedGitStatuses.get(targetKey);
const watched = watchedVcsStatuses.get(targetKey);
if (watched) {
watched.refCount += 1;
return () => unwatchGitStatus(targetKey);
return () => unwatchVcsStatus(targetKey);
}
watchedGitStatuses.set(targetKey, {
watchedVcsStatuses.set(targetKey, {
refCount: 1,
unsubscribe: subscribeToGitStatusTarget(targetKey, target, client),
unsubscribe: subscribeToVcsStatusTarget(targetKey, target, client),
});
return () => unwatchGitStatus(targetKey);
return () => unwatchVcsStatus(targetKey);
}
export function refreshGitStatus(
target: GitStatusTarget,
client?: GitStatusClient,
export function refreshVcsStatus(
target: VcsStatusTarget,
client?: VcsStatusClient,
): Promise<VcsStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
const targetKey = getVcsStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
}
const resolvedClient = client ?? readResolvedGitStatusClient(target)?.client;
const resolvedClient = client ?? readResolvedVcsStatusClient(target)?.client;
if (!resolvedClient) {
return Promise.resolve(getGitStatusSnapshot(target).data);
return Promise.resolve(getVcsStatusSnapshot(target).data);
}
const currentInFlight = gitStatusRefreshInFlight.get(targetKey);
const currentInFlight = vcsStatusRefreshInFlight.get(targetKey);
if (currentInFlight) {
return currentInFlight;
}
const lastRequestedAt = gitStatusLastRefreshAtByKey.get(targetKey) ?? 0;
if (Date.now() - lastRequestedAt < GIT_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getGitStatusSnapshot(target).data);
const lastRequestedAt = vcsStatusLastRefreshAtByKey.get(targetKey) ?? 0;
if (Date.now() - lastRequestedAt < VCS_STATUS_REFRESH_DEBOUNCE_MS) {
return Promise.resolve(getVcsStatusSnapshot(target).data);
}
gitStatusLastRefreshAtByKey.set(targetKey, Date.now());
vcsStatusLastRefreshAtByKey.set(targetKey, Date.now());
const refreshPromise = resolvedClient.refreshStatus({ cwd: target.cwd }).finally(() => {
gitStatusRefreshInFlight.delete(targetKey);
vcsStatusRefreshInFlight.delete(targetKey);
});
gitStatusRefreshInFlight.set(targetKey, refreshPromise);
vcsStatusRefreshInFlight.set(targetKey, refreshPromise);
return refreshPromise;
}
export function resetGitStatusStateForTests(): void {
for (const watched of watchedGitStatuses.values()) {
export function resetVcsStatusStateForTests(): void {
for (const watched of watchedVcsStatuses.values()) {
watched.unsubscribe();
}
watchedGitStatuses.clear();
gitStatusRefreshInFlight.clear();
gitStatusLastRefreshAtByKey.clear();
watchedVcsStatuses.clear();
vcsStatusRefreshInFlight.clear();
vcsStatusLastRefreshAtByKey.clear();
for (const key of knownGitStatusKeys) {
appAtomRegistry.set(gitStatusStateAtom(key), INITIAL_GIT_STATUS_STATE);
for (const key of knownVcsStatusKeys) {
appAtomRegistry.set(vcsStatusStateAtom(key), INITIAL_VCS_STATUS_STATE);
}
knownGitStatusKeys.clear();
knownVcsStatusKeys.clear();
}
export function useGitStatus(target: GitStatusTarget): GitStatusState {
const targetKey = getGitStatusTargetKey(target);
export function useVcsStatus(target: VcsStatusTarget): VcsStatusState {
const targetKey = getVcsStatusTargetKey(target);
useEffect(
() => watchGitStatus({ environmentId: target.environmentId, cwd: target.cwd }),
() => watchVcsStatus({ environmentId: target.environmentId, cwd: target.cwd }),
[target.environmentId, target.cwd],
);
const state = useAtomValue(
targetKey !== null ? gitStatusStateAtom(targetKey) : EMPTY_GIT_STATUS_ATOM,
targetKey !== null ? vcsStatusStateAtom(targetKey) : EMPTY_VCS_STATUS_ATOM,
);
return targetKey === null ? EMPTY_GIT_STATUS_STATE : state;
return targetKey === null ? EMPTY_VCS_STATUS_STATE : state;
}
function unwatchGitStatus(targetKey: string): void {
const watched = watchedGitStatuses.get(targetKey);
function unwatchVcsStatus(targetKey: string): void {
const watched = watchedVcsStatuses.get(targetKey);
if (!watched) {
return;
}
@@ -187,13 +187,13 @@ function unwatchGitStatus(targetKey: string): void {
}
watched.unsubscribe();
watchedGitStatuses.delete(targetKey);
watchedVcsStatuses.delete(targetKey);
}
function subscribeToGitStatusTarget(
function subscribeToVcsStatusTarget(
targetKey: string,
target: GitStatusTarget,
providedClient?: GitStatusClient,
target: VcsStatusTarget,
providedClient?: VcsStatusClient,
): () => void {
if (target.cwd === null) {
return NOOP;
@@ -209,7 +209,7 @@ function subscribeToGitStatusTarget(
clientIdentity: `provided:${targetKey}`,
client: providedClient,
}
: readResolvedGitStatusClient(target);
: readResolvedVcsStatusClient(target);
if (!resolved) {
if (currentClientIdentity !== null) {
@@ -217,7 +217,7 @@ function subscribeToGitStatusTarget(
currentUnsubscribe = NOOP;
currentClientIdentity = null;
}
markGitStatusPending(targetKey);
markVcsStatusPending(targetKey);
return;
}
@@ -227,7 +227,7 @@ function subscribeToGitStatusTarget(
currentUnsubscribe();
currentClientIdentity = resolved.clientIdentity;
currentUnsubscribe = subscribeToGitStatus(targetKey, cwd, resolved.client);
currentUnsubscribe = subscribeToVcsStatus(targetKey, cwd, resolved.client);
};
const unsubscribeRegistry = providedClient
@@ -241,12 +241,12 @@ function subscribeToGitStatusTarget(
};
}
function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusClient): () => void {
markGitStatusPending(targetKey);
function subscribeToVcsStatus(targetKey: string, cwd: string, client: VcsStatusClient): () => void {
markVcsStatusPending(targetKey);
return client.onStatus(
{ cwd },
(status: VcsStatusResult) => {
appAtomRegistry.set(gitStatusStateAtom(targetKey), {
appAtomRegistry.set(vcsStatusStateAtom(targetKey), {
data: status,
error: null,
cause: null,
@@ -255,18 +255,18 @@ function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusC
},
{
onResubscribe: () => {
markGitStatusPending(targetKey);
markVcsStatusPending(targetKey);
},
},
);
}
function markGitStatusPending(targetKey: string): void {
const atom = gitStatusStateAtom(targetKey);
function markVcsStatusPending(targetKey: string): void {
const atom = vcsStatusStateAtom(targetKey);
const current = appAtomRegistry.get(atom);
const next =
current.data === null
? INITIAL_GIT_STATUS_STATE
? INITIAL_VCS_STATUS_STATE
: {
...current,
error: null,
@@ -285,3 +285,9 @@ function markGitStatusPending(targetKey: string): void {
appAtomRegistry.set(atom, next);
}
export const getGitStatusSnapshot = getVcsStatusSnapshot;
export const watchGitStatus = watchVcsStatus;
export const refreshGitStatus = refreshVcsStatus;
export const resetGitStatusStateForTests = resetVcsStatusStateForTests;
export const useGitStatus = useVcsStatus;
+1
View File
@@ -0,0 +1 @@
export { vcsQueryKeys, vcsRefSearchInfiniteQueryOptions } from "./gitReactQuery";
+7
View File
@@ -0,0 +1,7 @@
export {
getVcsStatusSnapshot,
refreshVcsStatus,
resetVcsStatusStateForTests,
useVcsStatus,
watchVcsStatus,
} from "./gitStatusState";
+1
View File
@@ -83,6 +83,7 @@ describe("wsRpcClient", () => {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
},
],
+1 -11
View File
@@ -219,6 +219,7 @@ const VcsStatusRemoteShape = {
hasUpstream: Schema.Boolean,
aheadCount: NonNegativeInt,
behindCount: NonNegativeInt,
aheadOfDefaultCount: Schema.optional(NonNegativeInt),
pr: Schema.NullOr(VcsStatusChangeRequest),
};
@@ -328,16 +329,6 @@ export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()(
}
}
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
@@ -364,7 +355,6 @@ export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()(
export const GitManagerServiceError = Schema.Union([
GitManagerError,
GitCommandError,
GitHubCliError,
SourceControlProviderError,
TextGenerationError,
]);
+4
View File
@@ -202,6 +202,7 @@ const EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
pr: null,
};
@@ -220,6 +221,9 @@ function toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {
hasUpstream: status.hasUpstream,
aheadCount: status.aheadCount,
behindCount: status.behindCount,
...(status.aheadOfDefaultCount === undefined
? {}
: { aheadOfDefaultCount: status.aheadOfDefaultCount }),
pr: status.pr,
};
}